@rulecad/topopt 0.2.3 → 0.2.5
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 +16 -3
- package/package.json +1 -1
- package/topopt.d.mts +89 -14
- package/topopt.mjs +135 -8
package/README.md
CHANGED
|
@@ -18,7 +18,9 @@ const spec = discretise({
|
|
|
18
18
|
material: { E: 2680, nu: 0.36 }, thickness: 6, cell: 1, volume: 0.5, filter: 2.5,
|
|
19
19
|
});
|
|
20
20
|
const result = optimise(spec, { onStep: (s) => console.log(s.step, s.compliance) });
|
|
21
|
-
result.
|
|
21
|
+
result.unsupported; // with overhang: the share of the kept regions' material nothing holds up (0: all held up)
|
|
22
|
+
result.cases; // [{ name: 'down', deflection (mm along the load), stiffness (N/mm) }]; a twist (forces adding
|
|
23
|
+
// to nothing): { name, moment (N·mm), angle (radians), torsion (N·mm a radian) }
|
|
22
24
|
const loops = outlines(spec.grid, result.density, spec.origin); // closed loops, solid on the left
|
|
23
25
|
```
|
|
24
26
|
|
|
@@ -60,7 +62,10 @@ Two more steps shape the result:
|
|
|
60
62
|
- **Heaviside projection** sharpens the result, more on each pass, until cells are solid or empty.
|
|
61
63
|
- **The overhang filter** (optional, after Langelaar 2017) applies the printer's limit. Layer by layer from the bed, a
|
|
62
64
|
cell can only be as solid as the material under it: the cell below and its neighbours, so nothing overhangs more
|
|
63
|
-
than 45°. The result prints without supports in that direction.
|
|
65
|
+
than 45°. The result prints without supports in that direction. Kept regions must print too: a kept cell that
|
|
66
|
+
nothing holds up costs the optimiser as much as the whole part's compliance (shared over the kept cells), so it grows
|
|
67
|
+
what holds it up; `result.unsupported` says how much of the kept material is still left hanging, which means there
|
|
68
|
+
wasn't material enough to stand it on.
|
|
64
69
|
|
|
65
70
|
Several load cases are optimised together by weight. A case weighted 0 is solved only at the end, for its figures.
|
|
66
71
|
`model(spec)` exposes the analysis and its gradient, for other update methods.
|
|
@@ -70,7 +75,15 @@ and drops holes and islands smaller than `minArea`.
|
|
|
70
75
|
|
|
71
76
|
`surface` does the same for a 3D result: a closed triangle mesh at density 0.5, by marching tetrahedra. Every cube
|
|
72
77
|
is split along the same diagonal, so neighbouring cubes cut their shared faces the same way and the surface has no
|
|
73
|
-
gaps. Then it's smoothed.
|
|
78
|
+
gaps. Then it's smoothed. With `overhang`, the smoothed surface is made printable: faces left steeper than the limit
|
|
79
|
+
are tipped back to it, and tips left hanging in mid-air (the lowest point of a dip under an edge, which a printer has
|
|
80
|
+
nothing to lay down on) are lifted level with their neighbours, in turn until neither finds any.
|
|
81
|
+
|
|
82
|
+
`printable` makes a result printable before it's drawn, the hard way: built up layer by layer from the bed, a cell
|
|
83
|
+
stays only if something holds it up (a cell in the layer below, straight under it or diagonally next to that; or,
|
|
84
|
+
within `reach` cells along its own layer, one that is: a short bridge); kept regions always stay. Whatever's left
|
|
85
|
+
hanging is emptied, and with it, layer by layer, whatever rested on it. It's what `cad optimise` does to every 3D
|
|
86
|
+
result with a build direction.
|
|
74
87
|
|
|
75
88
|
## Stress limits
|
|
76
89
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/topopt",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Topology optimisation for flat and solid parts: the stiffest layout of a fixed amount of material, printable without supports if asked, as outlines or a surface ready to print.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
package/topopt.d.mts
CHANGED
|
@@ -31,7 +31,55 @@
|
|
|
31
31
|
* @param {Problem} p
|
|
32
32
|
* @returns {object} a spec for optimise(), with origin (the grid's lowest corner, mm) and regions
|
|
33
33
|
*/
|
|
34
|
-
|
|
34
|
+
/**
|
|
35
|
+
* What a case's forces add up to: their total's size (N), and if that's nothing, the moment they turn the part with
|
|
36
|
+
* (N·mm, about where they act, weighted by size): a twist.
|
|
37
|
+
* @param {{ at: number[], force: number[] }[]} loads
|
|
38
|
+
* @returns {{ size: number, moment: number }}
|
|
39
|
+
*/
|
|
40
|
+
export function resultant(loads: {
|
|
41
|
+
at: number[];
|
|
42
|
+
force: number[];
|
|
43
|
+
}[]): {
|
|
44
|
+
size: number;
|
|
45
|
+
moment: number;
|
|
46
|
+
};
|
|
47
|
+
export function discretise(p: any): {
|
|
48
|
+
regions: {
|
|
49
|
+
keep: any;
|
|
50
|
+
avoid: any;
|
|
51
|
+
};
|
|
52
|
+
stress?: any;
|
|
53
|
+
overhang?: any;
|
|
54
|
+
grid: {
|
|
55
|
+
nx: number;
|
|
56
|
+
ny: number;
|
|
57
|
+
nz: number;
|
|
58
|
+
h: any;
|
|
59
|
+
} | {
|
|
60
|
+
nx: number;
|
|
61
|
+
ny: number;
|
|
62
|
+
h: any;
|
|
63
|
+
nz?: undefined;
|
|
64
|
+
};
|
|
65
|
+
origin: number[];
|
|
66
|
+
passive: Int8Array<ArrayBuffer>;
|
|
67
|
+
fixed: Uint8Array<ArrayBuffer>;
|
|
68
|
+
loads: {
|
|
69
|
+
moment?: number;
|
|
70
|
+
name: any;
|
|
71
|
+
force: Float64Array<ArrayBuffer>;
|
|
72
|
+
weight: any;
|
|
73
|
+
size: number;
|
|
74
|
+
}[];
|
|
75
|
+
material: any;
|
|
76
|
+
thickness: any;
|
|
77
|
+
volume: any;
|
|
78
|
+
filter: any;
|
|
79
|
+
penal: any;
|
|
80
|
+
projection: any;
|
|
81
|
+
steps: any;
|
|
82
|
+
};
|
|
35
83
|
/**
|
|
36
84
|
* The density filter: each cell's filtered density is the weighted average of the cells within radius (weights
|
|
37
85
|
* falling linearly to 0 at the radius). apply filters densities; adjoint carries sensitivities back through it.
|
|
@@ -60,18 +108,17 @@ export function overhangFilter({ nx, ny, nz }: {
|
|
|
60
108
|
apply(x: any, out: any): any;
|
|
61
109
|
adjoint(g: any, out: any): any;
|
|
62
110
|
};
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
backend?: typeof jsBackend;
|
|
111
|
+
export function model(spec: any, { method, backend }?: {
|
|
112
|
+
backend?: {
|
|
113
|
+
name: string;
|
|
114
|
+
precision: number;
|
|
115
|
+
operator: (g: import("@rulecad/fea").Grid, ke: Float64Array | null, cellMatrices?: Float64Array) => {
|
|
116
|
+
multiply: (scale: Float64Array | null, x: Float64Array, y: Float64Array) => void;
|
|
117
|
+
diagonal: (scale: Float64Array | null, d: Float64Array) => void;
|
|
118
|
+
};
|
|
119
|
+
dot: (a: Float64Array, b: Float64Array) => number;
|
|
120
|
+
axpy: (a: number, x: Float64Array, y: Float64Array) => void;
|
|
121
|
+
};
|
|
75
122
|
}): {
|
|
76
123
|
physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
|
|
77
124
|
evaluate: (x: any, beta: any, { all, multipliers }?: {
|
|
@@ -88,6 +135,7 @@ export function model(spec: ReturnType<typeof discretise>, { method, backend }?:
|
|
|
88
135
|
dv: Float64Array<ArrayBuffer>;
|
|
89
136
|
u: any;
|
|
90
137
|
cases: any;
|
|
138
|
+
unsupported: number;
|
|
91
139
|
};
|
|
92
140
|
cells: number;
|
|
93
141
|
passive: any;
|
|
@@ -112,7 +160,9 @@ export function mma({ n, m, xmin, xmax, move }: {
|
|
|
112
160
|
* @param {ReturnType<typeof discretise>} spec
|
|
113
161
|
* @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
|
|
114
162
|
* @returns {{ density: Float64Array, compliance: number, cases: { name: string, compliance: number, deflection: number, stiffness: number }[], volume: number, steps: number, converged: boolean, history: number[], seconds: number }}
|
|
115
|
-
*
|
|
163
|
+
* unsupported: with a build direction, the share of the kept regions' material nothing holds up (0: all held up);
|
|
164
|
+
* each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm);
|
|
165
|
+
* a twist (forces adding to nothing) has instead its moment (N·mm), the angle it turns (radians) and torsion (N·mm a radian)
|
|
116
166
|
*/
|
|
117
167
|
export function optimise(spec: ReturnType<typeof discretise>, { onStep, method, backend, tol, move }?: {
|
|
118
168
|
onStep?: (s: {
|
|
@@ -206,6 +256,31 @@ export function surface({ nx, ny, nz, h }: {
|
|
|
206
256
|
vertices: number[][];
|
|
207
257
|
faces: number[][];
|
|
208
258
|
};
|
|
259
|
+
/**
|
|
260
|
+
* A result made printable before it's drawn. Built up layer by layer from the bed, a cell denser than iso stays only if
|
|
261
|
+
* something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing
|
|
262
|
+
* overhangs by more than 45°), or, within reach cells along its own layer, one that is (a short bridge). Kept regions
|
|
263
|
+
* always stay, and hold up what's above them. Whatever's left hanging (an icicle, a loose bit, a sheet hanging under an
|
|
264
|
+
* edge) is emptied, and with it, layer by layer, whatever rested on it. The optimiser's overhang filter does the same
|
|
265
|
+
* smoothly, on the densities as they're optimised; this is the hard version, on the result as it'll be drawn.
|
|
266
|
+
* @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
|
|
267
|
+
* @param {{ up: string, iso?: number, keep?: ArrayLike<number>, reach?: number }} options up: the build direction ('+z',
|
|
268
|
+
* '-y', …); keep: cells that always stay (non-zero); reach: how many cells a bridge may run out from what holds it
|
|
269
|
+
* @returns {{ density: Float64Array, emptied: number }} the densities, and how many cells were emptied
|
|
270
|
+
*/
|
|
271
|
+
export function printable({ nx, ny, nz }: {
|
|
272
|
+
nx: number;
|
|
273
|
+
ny: number;
|
|
274
|
+
nz?: number;
|
|
275
|
+
}, density: ArrayLike<number>, { up, iso, keep, reach }: {
|
|
276
|
+
up: string;
|
|
277
|
+
iso?: number;
|
|
278
|
+
keep?: ArrayLike<number>;
|
|
279
|
+
reach?: number;
|
|
280
|
+
}): {
|
|
281
|
+
density: Float64Array;
|
|
282
|
+
emptied: number;
|
|
283
|
+
};
|
|
209
284
|
export { jsBackend };
|
|
210
285
|
export function inside(r: Region, pt: number[]): boolean;
|
|
211
286
|
/**
|
package/topopt.mjs
CHANGED
|
@@ -54,6 +54,25 @@ export { jsBackend };
|
|
|
54
54
|
* @param {Problem} p
|
|
55
55
|
* @returns {object} a spec for optimise(), with origin (the grid's lowest corner, mm) and regions
|
|
56
56
|
*/
|
|
57
|
+
/**
|
|
58
|
+
* What a case's forces add up to: their total's size (N), and if that's nothing, the moment they turn the part with
|
|
59
|
+
* (N·mm, about where they act, weighted by size): a twist.
|
|
60
|
+
* @param {{ at: number[], force: number[] }[]} loads
|
|
61
|
+
* @returns {{ size: number, moment: number }}
|
|
62
|
+
*/
|
|
63
|
+
export function resultant(loads) {
|
|
64
|
+
const w = loads.map((l) => Math.hypot(...l.force)), all = w.reduce((t, x) => t + x, 0) || 1, dim = loads[0]?.force.length ?? 3;
|
|
65
|
+
const p3 = (v) => [v[0], v[1], dim === 3 ? v[2] : 0], c = [0, 1, 2].map((a) => loads.reduce((t, l, i) => t + (p3(l.at)[a]) * w[i], 0) / all);
|
|
66
|
+
const total = [0, 0, 0], turn = [0, 0, 0];
|
|
67
|
+
for (const l of loads) {
|
|
68
|
+
const F = p3(l.force), at = p3(l.at), r = [at[0] - c[0], at[1] - c[1], at[2] - c[2]];
|
|
69
|
+
for (let a = 0; a < 3; a++) total[a] += F[a];
|
|
70
|
+
turn[0] += r[1] * F[2] - r[2] * F[1]; turn[1] += r[2] * F[0] - r[0] * F[2]; turn[2] += r[0] * F[1] - r[1] * F[0];
|
|
71
|
+
}
|
|
72
|
+
const size = Math.hypot(...total);
|
|
73
|
+
return { size, moment: size < 1e-9 * all ? Math.hypot(...turn) : 0 };
|
|
74
|
+
}
|
|
75
|
+
|
|
57
76
|
export function discretise(p) {
|
|
58
77
|
const space = [p.space].flat(), keep = p.keep || [], avoid = p.avoid || [], dim = dimension(space[0]);
|
|
59
78
|
if (!(p.cell > 0)) throw new Error('the cell size must be more than 0 mm');
|
|
@@ -109,7 +128,8 @@ export function discretise(p) {
|
|
|
109
128
|
for (const m of ns) for (let a = 0; a < dim; a++) f[dim * m + a] += l.force[a] / ns.length;
|
|
110
129
|
for (let a = 0; a < dim; a++) total[a] += l.force[a];
|
|
111
130
|
}
|
|
112
|
-
|
|
131
|
+
const { size, moment } = resultant(mine);
|
|
132
|
+
return { name, force: f, weight: p.cases?.[name] ?? 1, size, ...(moment ? { moment } : {}) };
|
|
113
133
|
});
|
|
114
134
|
return {
|
|
115
135
|
grid: size, origin, passive, fixed, loads,
|
|
@@ -219,6 +239,8 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
|
|
|
219
239
|
* @param {ReturnType<typeof discretise>} spec
|
|
220
240
|
* @param {{ method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} [options]
|
|
221
241
|
*/
|
|
242
|
+
const SUPPORT = 10; // what a kept cell nothing holds up costs, in the part's compliances, over the kept cells
|
|
243
|
+
|
|
222
244
|
export function model(spec, { method, backend = jsBackend } = {}) {
|
|
223
245
|
const g = makeGrid(spec.grid), dim = g.dim, cells = g.cells, m = g.cellDofs, ke = cellStiffness(spec.material.nu, dim);
|
|
224
246
|
const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5, size = dim === 3 ? g.h : spec.thickness;
|
|
@@ -230,12 +252,22 @@ export function model(spec, { method, backend = jsBackend } = {}) {
|
|
|
230
252
|
const denominator = (beta) => Math.tanh(beta * eta) + Math.tanh(beta * (1 - eta));
|
|
231
253
|
const project = (t, beta) => (spec.projection ? (Math.tanh(beta * eta) + Math.tanh(beta * (t - eta))) / denominator(beta) : t);
|
|
232
254
|
const slope = (t, beta) => (spec.projection ? (beta * (1 - Math.tanh(beta * (t - eta)) ** 2)) / denominator(beta) : 1);
|
|
255
|
+
// Kept and avoided cells are set before the overhang filter as well as after it: a kept cell holds up what's above
|
|
256
|
+
// it, an avoided cell holds up nothing, and a kept cell is printed (made) only as far as what's below holds it up,
|
|
257
|
+
// which is what the kept regions' support cost (below) is measured on. The part is analysed with every kept cell solid.
|
|
233
258
|
const physical = (x, beta) => {
|
|
234
259
|
filter.apply(x, tilde);
|
|
260
|
+
for (let e = 0; e < cells; e++) if (passive[e]) tilde[e] = fixedValue(passive[e]);
|
|
235
261
|
if (print) print.apply(tilde, made); else made.set(tilde);
|
|
236
262
|
for (let e = 0; e < cells; e++) phys[e] = passive[e] ? fixedValue(passive[e]) : project(made[e], beta);
|
|
237
263
|
return phys;
|
|
238
264
|
};
|
|
265
|
+
// Kept regions must print. With a build direction, how much of the kept material nothing holds up (0 to 1), and its
|
|
266
|
+
// cost: a kept cell nothing holds up costs SUPPORT times the part's compliance, shared over the kept cells, so the
|
|
267
|
+
// optimiser puts material in under it. The cost's gradient goes back through the overhang filter to the cells that
|
|
268
|
+
// would hold it up.
|
|
269
|
+
const keptCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p === 1 ? [e] : [])));
|
|
270
|
+
const unsupported = (beta) => (print && keptCells.length ? keptCells.reduce((t, e) => t + 1 - project(made[e], beta), 0) / keptCells.length : 0);
|
|
239
271
|
let last = null;
|
|
240
272
|
// Each step solves only the load cases it optimises for (weight above 0); every case is solved when all is set
|
|
241
273
|
const evaluate = (x, beta, { all = false, multipliers } = {}) => {
|
|
@@ -262,17 +294,26 @@ export function model(spec, { method, backend = jsBackend } = {}) {
|
|
|
262
294
|
});
|
|
263
295
|
// Back through the projection, the overhang filter and the density filter to the design densities; kept and
|
|
264
296
|
// avoided cells don't change
|
|
297
|
+
const lack = unsupported(beta);
|
|
265
298
|
for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta); dc[e] *= s; dv[e] = s; }
|
|
266
|
-
|
|
299
|
+
if (print && keptCells.length) { const w = (SUPPORT * Math.max(compliance, 1e-12)) / keptCells.length; for (const e of keptCells) dc[e] = -w * slope(made[e], beta); }
|
|
300
|
+
const toDesign = (d) => {
|
|
301
|
+
if (print) { print.adjoint(d, back); d.set(back); }
|
|
302
|
+
for (let e = 0; e < cells; e++) if (passive[e]) d[e] = 0;
|
|
303
|
+
filter.adjoint(d, back); d.set(back);
|
|
304
|
+
};
|
|
267
305
|
toDesign(dc); toDesign(dv);
|
|
268
306
|
const stress = Ss ? stressLimits(u, active, run.again, multipliers || { lam: active.map(() => new Float64Array(cells * Ss.length)), mu: 1 }) : null;
|
|
269
307
|
const cases = spec.loads.map((l, c) => {
|
|
270
308
|
if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
|
|
271
|
-
const ci = jsBackend.dot(l.force, u[c])
|
|
309
|
+
const ci = jsBackend.dot(l.force, u[c]);
|
|
310
|
+
// A twist turns rather than moves: the work it does is its moment times the angle it turns through
|
|
311
|
+
if (l.moment) { const angle = ci / l.moment; return { name: l.name, compliance: ci, moment: l.moment, angle, torsion: l.moment / angle }; }
|
|
312
|
+
const deflection = l.size ? ci / l.size : 0;
|
|
272
313
|
return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
|
|
273
314
|
});
|
|
274
315
|
if (stress) { for (let e = 0; e < cells; e++) stress.d[e] *= passive[e] ? 0 : slope(made[e], beta); toDesign(stress.d); }
|
|
275
|
-
return { compliance, dc, dv, u, cases, ...(stress ? { stress } : {}) };
|
|
316
|
+
return { compliance, dc, dv, u, cases, unsupported: lack, ...(stress ? { stress } : {}) };
|
|
276
317
|
};
|
|
277
318
|
// Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
|
|
278
319
|
// centre, as if solid, over the limit, less 1, times the cell's density, so an empty cell's limit vanishes. They're
|
|
@@ -474,7 +515,9 @@ function gauss(A) {
|
|
|
474
515
|
* @param {ReturnType<typeof discretise>} spec
|
|
475
516
|
* @param {{ onStep?: (s: { step: number, steps: number, compliance: number, change: number, beta: number, density: Float64Array }) => void, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, move?: number }} [options]
|
|
476
517
|
* @returns {{ density: Float64Array, compliance: number, cases: { name: string, compliance: number, deflection: number, stiffness: number }[], volume: number, steps: number, converged: boolean, history: number[], seconds: number }}
|
|
477
|
-
*
|
|
518
|
+
* unsupported: with a build direction, the share of the kept regions' material nothing holds up (0: all held up);
|
|
519
|
+
* each case's deflection is along its load (mm, compliance over the load's size), stiffness the load over that (N/mm);
|
|
520
|
+
* a twist (forces adding to nothing) has instead its moment (N·mm), the angle it turns (radians) and torsion (N·mm a radian)
|
|
478
521
|
*/
|
|
479
522
|
export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
|
|
480
523
|
const started = Date.now(), m = model(spec, { method, backend }), { cells, passive } = m;
|
|
@@ -551,8 +594,9 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
|
|
|
551
594
|
}
|
|
552
595
|
// The final design, analysed as it is
|
|
553
596
|
const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
|
|
597
|
+
// (the final physical call is after evaluate's, so unsupported comes from the evaluation of this design)
|
|
554
598
|
return {
|
|
555
|
-
density: phys, compliance: final.compliance, cases: final.cases, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
|
|
599
|
+
density: phys, compliance: final.compliance, cases: final.cases, unsupported: final.unsupported, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
|
|
556
600
|
volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
|
|
557
601
|
};
|
|
558
602
|
}
|
|
@@ -830,7 +874,9 @@ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth
|
|
|
830
874
|
return held[n] ? p : p.map((x, q) => Math.min(hi[q], Math.max(lo[q], x + f * (avg[q] - x))));
|
|
831
875
|
});
|
|
832
876
|
}
|
|
833
|
-
|
|
877
|
+
// Printable: faces past the limit tipped back, and tips lifted, in turn until neither finds any (each can make work for
|
|
878
|
+
// the other: a lifted tip leaves a face sloping more, a tipped face can leave a corner lowest)
|
|
879
|
+
if (overhang) for (let round = 0; round < 20; round++) { const tipped = steepen(pts, faces, held, overhang, lo, hi), lifted = lift(pts, faces, held, overhang, lo); if (!tipped && !lifted) break; }
|
|
834
880
|
return { vertices: pts, faces };
|
|
835
881
|
}
|
|
836
882
|
|
|
@@ -860,9 +906,90 @@ function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
|
|
|
860
906
|
move[m] += c[q] + k * (ga * (v[a] - c[a]) + gb * (v[b] - c[b])) - v[q]; count[m]++;
|
|
861
907
|
}
|
|
862
908
|
}
|
|
863
|
-
if (!left)
|
|
909
|
+
if (!left) return pass > 0;
|
|
864
910
|
for (let m = 0; m < pts.length; m++) if (count[m] && !held[m]) pts[m][q] = Math.min(hi[q], Math.max(lo[q], pts[m][q] + move[m] / count[m]));
|
|
865
911
|
}
|
|
912
|
+
return true;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// Tips lifted: a corner lower than every corner round it (along the build direction), on faces facing down, starts in
|
|
916
|
+
// mid-air, where a printer has nothing to lay it on. Smoothing leaves these under edges and bridges. Each is raised level
|
|
917
|
+
// with its lowest neighbour, which leaves a small flat underside (bridged), until none are left. The bed's corners and
|
|
918
|
+
// those held on the grid's sides stay.
|
|
919
|
+
function lift(pts, faces, held, { up }, lo, passes = 50) {
|
|
920
|
+
const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, near = pts.map(() => new Set()), facing = new Float64Array(pts.length);
|
|
921
|
+
for (const f of faces) {
|
|
922
|
+
for (let i = 0; i < 3; i++) { near[f[i]].add(f[(i + 1) % 3]); near[f[i]].add(f[(i + 2) % 3]); }
|
|
923
|
+
const [p, r, t] = f.map((n) => pts[n]), u = [0, 1, 2].map((x) => r[x] - p[x]), w = [0, 1, 2].map((x) => t[x] - p[x]);
|
|
924
|
+
const nq = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]][q];
|
|
925
|
+
for (const m of f) facing[m] += s * nq;
|
|
926
|
+
}
|
|
927
|
+
const bed = s > 0 ? lo[q] : null, height = (v) => s * v[q];
|
|
928
|
+
for (let pass = 0; pass < passes; pass++) {
|
|
929
|
+
let moved = 0;
|
|
930
|
+
for (let m = 0; m < pts.length; m++) {
|
|
931
|
+
if (held[m] || !near[m].size || facing[m] >= 0 || (bed !== null && Math.abs(pts[m][q] - bed) < 1e-9)) continue;
|
|
932
|
+
let lowest = Infinity;
|
|
933
|
+
for (const n of near[m]) lowest = Math.min(lowest, height(pts[n]));
|
|
934
|
+
if (height(pts[m]) < lowest - 1e-6) { pts[m][q] = s * lowest; moved++; }
|
|
935
|
+
}
|
|
936
|
+
if (!moved) return pass > 0;
|
|
937
|
+
}
|
|
938
|
+
return true;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* A result made printable before it's drawn. Built up layer by layer from the bed, a cell denser than iso stays only if
|
|
943
|
+
* something holds it up: a cell kept in the layer below, straight under it or diagonally next to that (so nothing
|
|
944
|
+
* overhangs by more than 45°), or, within reach cells along its own layer, one that is (a short bridge). Kept regions
|
|
945
|
+
* always stay, and hold up what's above them. Whatever's left hanging (an icicle, a loose bit, a sheet hanging under an
|
|
946
|
+
* edge) is emptied, and with it, layer by layer, whatever rested on it. The optimiser's overhang filter does the same
|
|
947
|
+
* smoothly, on the densities as they're optimised; this is the hard version, on the result as it'll be drawn.
|
|
948
|
+
* @param {{ nx: number, ny: number, nz?: number }} size @param {ArrayLike<number>} density
|
|
949
|
+
* @param {{ up: string, iso?: number, keep?: ArrayLike<number>, reach?: number }} options up: the build direction ('+z',
|
|
950
|
+
* '-y', …); keep: cells that always stay (non-zero); reach: how many cells a bridge may run out from what holds it
|
|
951
|
+
* @returns {{ density: Float64Array, emptied: number }} the densities, and how many cells were emptied
|
|
952
|
+
*/
|
|
953
|
+
export function printable({ nx, ny, nz = 1 }, density, { up, iso = 0.5, keep, reach = 0 }) {
|
|
954
|
+
const n = nz > 1 ? [nx, ny, nz] : [nx, ny], dim = n.length, ax = 'xyz'.indexOf(up.at(-1)), sign = up[0] === '-' ? -1 : 1;
|
|
955
|
+
if (ax < 0 || ax >= dim) throw new Error(`printable: the build direction is ${dim === 3 ? '+x, -x, +y, -y, +z or -z' : '+x, -x, +y or -y'} (got ${up})`);
|
|
956
|
+
const stride = [1, nx, nx * ny], other = [0, 1, 2].slice(0, dim).filter((a) => a !== ax), cells = n.reduce((p, c) => p * c, 1);
|
|
957
|
+
const ok = new Uint8Array(cells), out = Float64Array.from(density);
|
|
958
|
+
const solid = (e) => density[e] >= iso || (keep && keep[e]);
|
|
959
|
+
const coord = (e, a) => Math.floor(e / stride[a]) % n[a];
|
|
960
|
+
// The cells of each layer, in build order
|
|
961
|
+
const layers = Array.from({ length: n[ax] }, () => []);
|
|
962
|
+
for (let e = 0; e < cells; e++) { const c = coord(e, ax); layers[sign > 0 ? c : n[ax] - 1 - c].push(e); }
|
|
963
|
+
const near = (e) => { // a cell's neighbours in its own layer, along each other axis
|
|
964
|
+
const list = [];
|
|
965
|
+
for (const a of other) { const c = coord(e, a); if (c > 0) list.push(e - stride[a]); if (c < n[a] - 1) list.push(e + stride[a]); }
|
|
966
|
+
return list;
|
|
967
|
+
};
|
|
968
|
+
layers.forEach((layer, L) => {
|
|
969
|
+
const queue = [], dist = new Map();
|
|
970
|
+
for (const e of layer) {
|
|
971
|
+
if (!solid(e)) continue;
|
|
972
|
+
let held = L === 0 || (keep && keep[e]);
|
|
973
|
+
if (!held) {
|
|
974
|
+
const below = e - sign * stride[ax], under = [below];
|
|
975
|
+
// and its neighbours along each other axis, and diagonally (in 3D)
|
|
976
|
+
const offs = other.map((a) => [-stride[a], 0, stride[a]].filter((d, i) => { const c = coord(below, a); return (i === 0 && c > 0) || i === 1 || (i === 2 && c < n[a] - 1); }));
|
|
977
|
+
if (offs.length === 1) for (const d of offs[0]) under.push(below + d);
|
|
978
|
+
else for (const d0 of offs[0]) for (const d1 of offs[1]) under.push(below + d0 + d1);
|
|
979
|
+
held = under.some((q) => ok[q]);
|
|
980
|
+
}
|
|
981
|
+
if (held) { ok[e] = 1; dist.set(e, 0); queue.push(e); }
|
|
982
|
+
}
|
|
983
|
+
// Short bridges: solid cells within reach of a held one, along the layer
|
|
984
|
+
for (let i = 0; i < queue.length; i++) {
|
|
985
|
+
const e = queue[i], d = dist.get(e);
|
|
986
|
+
if (d >= reach) continue;
|
|
987
|
+
for (const f of near(e)) if (!ok[f] && solid(f)) { ok[f] = 1; dist.set(f, d + 1); queue.push(f); }
|
|
988
|
+
}
|
|
989
|
+
});
|
|
990
|
+
let emptied = 0;
|
|
991
|
+
for (let e = 0; e < cells; e++) if (!ok[e] && density[e] >= iso) { out[e] = 0; emptied++; }
|
|
992
|
+
return { density: out, emptied };
|
|
866
993
|
}
|
|
867
994
|
|
|
868
995
|
const fmt = (n) => String(Number(n.toFixed(2)));
|