@rulecad/cad 0.8.0 → 0.9.0
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 +24 -10
- package/CHANGELOG.md +404 -0
- package/EXAMPLES.md +40 -38
- package/README.md +193 -67
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2250 -512
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1847 -434
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/design.mjs +649 -121
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +899 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2702 -507
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +100 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +81 -17
- package/lib/framesize.mjs +792 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +123 -21
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +438 -68
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +326 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +579 -130
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +417 -94
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1021 -213
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +3 -1
- package/lib/optimise.mjs +978 -283
- package/lib/order.mjs +519 -112
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +78 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +15 -5
- package/lib/sandbox-hooks.mjs +77 -19
- package/lib/sandbox-run.mjs +117 -18
- package/lib/sandbox.mjs +509 -60
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +851 -178
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +111 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +197 -12
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
package/lib/optimise.mjs
CHANGED
|
@@ -8,20 +8,40 @@ import fs from 'node:fs';
|
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import crypto from 'node:crypto';
|
|
10
10
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
11
|
-
import { host, readJson } from './host.mjs';
|
|
12
|
-
import { paths, printerOf } from './workspace.mjs';
|
|
11
|
+
import { host, readJson, cached } from './host.mjs';
|
|
12
|
+
import { paths, printerOf, noLinksOut } from './workspace.mjs';
|
|
13
13
|
import { plainName } from './names.mjs';
|
|
14
|
-
import { resolve, evaluate } from './rules.mjs';
|
|
14
|
+
import { resolve, evaluate, fmt } from './rules.mjs';
|
|
15
15
|
import { located } from './errors.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
discretise,
|
|
18
|
+
optimise,
|
|
19
|
+
outlines,
|
|
20
|
+
surface,
|
|
21
|
+
area,
|
|
22
|
+
bounds,
|
|
23
|
+
resultant,
|
|
24
|
+
printable,
|
|
25
|
+
refine,
|
|
26
|
+
despike,
|
|
27
|
+
reduce,
|
|
28
|
+
undercuts,
|
|
29
|
+
voids,
|
|
30
|
+
grey,
|
|
31
|
+
featureCells,
|
|
32
|
+
thin,
|
|
33
|
+
inside,
|
|
34
|
+
} from '@rulecad/topopt';
|
|
17
35
|
import { islands } from '@rulecad/printcheck';
|
|
18
36
|
import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
|
|
19
37
|
import { section, loops, slabLevels } from './mesh.mjs';
|
|
20
38
|
import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
|
|
21
39
|
import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
|
|
22
40
|
|
|
23
|
-
const VERSION = 2,
|
|
24
|
-
|
|
41
|
+
const VERSION = 2,
|
|
42
|
+
source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
|
|
43
|
+
export const problemFile = (project, name) =>
|
|
44
|
+
path.join(paths.project(project), 'problems', `${plainName(name, 'problem name')}.json`); // (a name from a design's file: never ../)
|
|
25
45
|
export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
|
|
26
46
|
|
|
27
47
|
/**
|
|
@@ -31,10 +51,15 @@ export const hasProblem = (project, ref) => host.exists(problemFile(project, Str
|
|
|
31
51
|
export async function readProblem(project, ref) {
|
|
32
52
|
// The problems being read above this one, each with the design it reads that is built from the next: a problem met
|
|
33
53
|
// again on that chain is refused by name, since each would need the other's result before its own could be made
|
|
34
|
-
const name = String(ref).split(':')[0],
|
|
54
|
+
const name = String(ref).split(':')[0],
|
|
55
|
+
chain = reading.getStore() || [],
|
|
56
|
+
key = `${project}/${name}`;
|
|
35
57
|
if (chain.some((c) => c.key === key)) {
|
|
36
|
-
const from = chain.slice(chain.findIndex((c) => c.key === key)),
|
|
37
|
-
|
|
58
|
+
const from = chain.slice(chain.findIndex((c) => c.key === key)),
|
|
59
|
+
steps = from.map((c, i) => `${c.name} reads ${c.object}, built from ${(from[i + 1] || { name })?.name}`);
|
|
60
|
+
throw new Error(
|
|
61
|
+
`${name}.json: problems read each other through designs built from them: ${steps.join(', then ')}. Fix one of them to a part or anchor of a design that is not made from the others`,
|
|
62
|
+
);
|
|
38
63
|
}
|
|
39
64
|
const link = { key, name, object: null };
|
|
40
65
|
return reading.run([...chain, link], () => readOne(project, ref, link));
|
|
@@ -47,39 +72,67 @@ export async function readProblem(project, ref) {
|
|
|
47
72
|
const REDUCE = 0.1;
|
|
48
73
|
const reading = new AsyncLocalStorage();
|
|
49
74
|
async function readOne(project, ref, link) {
|
|
50
|
-
const [name, variant] = String(ref).split(':'),
|
|
75
|
+
const [name, variant] = String(ref).split(':'),
|
|
76
|
+
file = problemFile(project, name);
|
|
51
77
|
if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
|
|
52
78
|
const p = readJson(file);
|
|
53
|
-
if (variant && !p.variants?.[variant])
|
|
79
|
+
if (variant && !p.variants?.[variant])
|
|
80
|
+
throw new Error(
|
|
81
|
+
`problem ${name} has no variant "${variant}" (variants: ${Object.keys(p.variants || {}).join(', ') || 'none'})`,
|
|
82
|
+
);
|
|
54
83
|
const uses = [...new Set([...(p.uses || []), p.material])];
|
|
55
84
|
let values;
|
|
56
|
-
try {
|
|
85
|
+
try {
|
|
86
|
+
({ values } = resolve({ uses, variables: p.variables || {} }, { set: variant ? p.variants[variant] : {} }));
|
|
87
|
+
} catch (e) {
|
|
88
|
+
throw located(e, file, 'var');
|
|
89
|
+
}
|
|
57
90
|
const lookup = (n) => {
|
|
58
91
|
const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), values);
|
|
59
|
-
if (typeof v !== 'number')
|
|
92
|
+
if (typeof v !== 'number')
|
|
93
|
+
throw new Error(
|
|
94
|
+
`${path.basename(file)}: "${n}" isn't a number here (variables: ${Object.keys(p.variables || {}).join(', ')})`,
|
|
95
|
+
);
|
|
60
96
|
return v;
|
|
61
97
|
};
|
|
62
|
-
const ev = (x) => evaluate(x, lookup),
|
|
98
|
+
const ev = (x) => evaluate(x, lookup),
|
|
99
|
+
pt = (a) => a.map(ev),
|
|
100
|
+
flat = p.thickness != null;
|
|
63
101
|
// Another design in the project, built once with its defaults, for its parts and anchors. One whose default is built
|
|
64
102
|
// from this very problem is refused: it would need the result before the result could be made.
|
|
65
103
|
const designs = new Map();
|
|
66
|
-
const design = (object, what) => {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
104
|
+
const design = (object, what) => {
|
|
105
|
+
// (the build kept as it starts: regions are read side by side)
|
|
106
|
+
if (!designs.has(object))
|
|
107
|
+
designs.set(
|
|
108
|
+
object,
|
|
109
|
+
(async () => {
|
|
110
|
+
const { build, locateIn, readObject } = await import('./design.mjs'),
|
|
111
|
+
d = locateIn(project, object, `${path.basename(file)}: ${what}`);
|
|
112
|
+
const own = Object.entries(readObject(d).variables || {}).find(
|
|
113
|
+
([, v]) => v.type === 'problem' && String(v.value).split(':')[0] === name,
|
|
114
|
+
);
|
|
115
|
+
if (own)
|
|
116
|
+
throw new Error(
|
|
117
|
+
`${path.basename(file)}: ${what} is on ${object}, which is built from this problem (its variable ${own[0]}): name a part or anchor of what it is fixed to instead`,
|
|
118
|
+
);
|
|
119
|
+
const chain = reading.getStore(); // this problem's place on the chain names the design it reads
|
|
120
|
+
return reading.run([...chain.slice(0, -1), { ...link, object }], () => build(d));
|
|
121
|
+
})(),
|
|
122
|
+
);
|
|
74
123
|
return designs.get(object);
|
|
75
124
|
};
|
|
76
125
|
// A named part of another design in the project, as triangles (built with its defaults)
|
|
77
126
|
const parts = new Map();
|
|
78
127
|
const part = async (ref) => {
|
|
79
128
|
if (!parts.has(ref)) {
|
|
80
|
-
const [object, partName] = ref.split('.'),
|
|
129
|
+
const [object, partName] = ref.split('.'),
|
|
130
|
+
b = await design(object, `the part "${ref}"`);
|
|
81
131
|
const found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
|
|
82
|
-
if (!found)
|
|
132
|
+
if (!found)
|
|
133
|
+
throw new Error(
|
|
134
|
+
`${path.basename(file)}: ${object} has no part "${partName}" (parts: ${b.parts.map((q) => q.name).join(', ')})`,
|
|
135
|
+
);
|
|
83
136
|
parts.set(ref, found.triangles);
|
|
84
137
|
}
|
|
85
138
|
return parts.get(ref);
|
|
@@ -90,16 +143,26 @@ async function readOne(project, ref, link) {
|
|
|
90
143
|
const anchor = async (ref) => {
|
|
91
144
|
if (!anchors.has(ref)) {
|
|
92
145
|
const [object, a, ...more] = String(ref).split('.');
|
|
93
|
-
if (!object || !a || more.length)
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
146
|
+
if (!object || !a || more.length)
|
|
147
|
+
throw new Error(`${path.basename(file)}: name an anchor as <object>.<anchor> (got "${ref}")`);
|
|
148
|
+
const b = await design(object, `the anchor "${ref}"`),
|
|
149
|
+
spec = b.object.anchors?.[a];
|
|
150
|
+
if (!spec)
|
|
151
|
+
throw new Error(
|
|
152
|
+
`${path.basename(file)}: ${object} has no anchor "${a}" (anchors: ${Object.keys(b.object.anchors || {}).join(', ') || 'none'})`,
|
|
153
|
+
);
|
|
154
|
+
const num = (x) =>
|
|
155
|
+
evaluate(x, (n) => {
|
|
156
|
+
const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values);
|
|
157
|
+
if (typeof v !== 'number')
|
|
158
|
+
throw new Error(
|
|
159
|
+
`${path.basename(file)}: the anchor "${ref}" reads "${n}", which isn't one of ${object}'s numbers`,
|
|
160
|
+
);
|
|
161
|
+
return v;
|
|
162
|
+
});
|
|
101
163
|
// Its axis is its z, as an assembly reads it: turned by its rotate (degrees about x, then y, then z) where it has one
|
|
102
|
-
const m = spec.rotate && turn(spec.rotate.map(num)),
|
|
164
|
+
const m = spec.rotate && turn(spec.rotate.map(num)),
|
|
165
|
+
axis = m ? [m[2], m[6], m[10]].map((c) => (Math.abs(c) < 1e-12 ? 0 : c)) : (spec.axis || [0, 0, 1]).map(num);
|
|
103
166
|
anchors.set(ref, { anchor: ref, at: (spec.at || [0, 0, 0]).map(num), axis });
|
|
104
167
|
}
|
|
105
168
|
return anchors.get(ref);
|
|
@@ -111,31 +174,57 @@ async function readOne(project, ref, link) {
|
|
|
111
174
|
const fileName = path.basename(file);
|
|
112
175
|
let placing = null;
|
|
113
176
|
const inAssembly = (what) => {
|
|
114
|
-
if (!p.in)
|
|
177
|
+
if (!p.in)
|
|
178
|
+
throw new Error(
|
|
179
|
+
`${fileName}: ${what} needs the problem placed in an assembly: "in": { "assembly": "<name>", "item": "<the item it is drawn in>" }`,
|
|
180
|
+
);
|
|
115
181
|
return (placing ||= (async () => {
|
|
116
|
-
const { buildAssembly, assemblyPath } = await import('./assembly.mjs'),
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
182
|
+
const { buildAssembly, assemblyPath } = await import('./assembly.mjs'),
|
|
183
|
+
{ locateIn, readObject } = await import('./design.mjs');
|
|
184
|
+
const ref = `${project}/${p.in.assembly}`,
|
|
185
|
+
overrides = {};
|
|
186
|
+
if (!host.exists(assemblyPath(ref)))
|
|
187
|
+
throw new Error(
|
|
188
|
+
`${fileName}: no assembly "${p.in.assembly}" to place the problem in (projects/${project}/assemblies/${p.in.assembly}.json)`,
|
|
189
|
+
);
|
|
190
|
+
for (const it of readJson(assemblyPath(ref)).items || [])
|
|
191
|
+
if (typeof it.object === 'string') {
|
|
192
|
+
let vars = {};
|
|
193
|
+
try {
|
|
194
|
+
vars = readObject(locateIn(project, it.object.split(/[:@]/)[0])).variables || {};
|
|
195
|
+
} catch {
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
for (const [k, v] of Object.entries(vars))
|
|
199
|
+
if (v.type === 'problem' && (it.id === p.in.item || String(it.set?.[k] ?? v.value).split(':')[0] === name))
|
|
200
|
+
(overrides[it.id] ||= {})[k] = 'none';
|
|
201
|
+
}
|
|
124
202
|
const chain = reading.getStore();
|
|
125
|
-
const s = await reading.run([...chain.slice(0, -1), { ...link, object: `the assembly ${p.in.assembly}` }], () =>
|
|
203
|
+
const s = await reading.run([...chain.slice(0, -1), { ...link, object: `the assembly ${p.in.assembly}` }], () =>
|
|
204
|
+
buildAssembly(ref, [], overrides, { pose: p.in.pose, onePose: true }),
|
|
205
|
+
);
|
|
126
206
|
const k = s.motion.items.findIndex((x) => x[0] === p.in.item);
|
|
127
|
-
if (k < 0)
|
|
207
|
+
if (k < 0)
|
|
208
|
+
throw new Error(
|
|
209
|
+
`${fileName}: ${p.in.assembly} has no item "${p.in.item}" (items: ${s.motion.items.map((x) => x[0]).join(', ')})`,
|
|
210
|
+
);
|
|
128
211
|
return { s, k, W0: placeItems(s.motion, s.jointValues) };
|
|
129
212
|
})());
|
|
130
213
|
};
|
|
131
214
|
// A joint of that assembly, where it is in the item's frame: the joint's anchor on the item when the item is one of
|
|
132
215
|
// its ends (the same in every pose), else the parent's anchor as the pose places it. Its axis is the anchor's z.
|
|
133
|
-
const joints = new Map(),
|
|
216
|
+
const joints = new Map(),
|
|
217
|
+
clean = (c) => (Math.abs(c) < 1e-9 ? 0 : round(c, 9));
|
|
134
218
|
const jointAt = async (id) => {
|
|
135
219
|
if (!joints.has(id)) {
|
|
136
|
-
const { s, k, W0 } = await inAssembly(`the joint "${id}"`),
|
|
137
|
-
|
|
138
|
-
|
|
220
|
+
const { s, k, W0 } = await inAssembly(`the joint "${id}"`),
|
|
221
|
+
j = s.motion.joints.find((x) => x.id === id);
|
|
222
|
+
if (!j)
|
|
223
|
+
throw new Error(
|
|
224
|
+
`${fileName}: ${p.in.assembly} has no joint "${id}" (joints: ${s.motion.joints.map((x) => x.id).join(', ') || 'none'})`,
|
|
225
|
+
);
|
|
226
|
+
const F =
|
|
227
|
+
j.child === k ? j.b : j.parent === k ? j.a : mul(inv(W0[k]), j.parent < 0 ? j.a : mul(W0[j.parent], j.a));
|
|
139
228
|
joints.set(id, { joint: id, at: [F[3], F[7], F[11]].map(clean), axis: [F[2], F[6], F[10]].map(clean) });
|
|
140
229
|
}
|
|
141
230
|
return joints.get(id);
|
|
@@ -148,67 +237,156 @@ async function readOne(project, ref, link) {
|
|
|
148
237
|
// into the plate's top or bottom is kept clear; one only passing over or under it, or touching a face, is not.
|
|
149
238
|
const sweeps = [];
|
|
150
239
|
const swept = async (r) => {
|
|
151
|
-
const { s, k, W0 } = await inAssembly(`the sweep of "${r.sweep}"`),
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
if (!
|
|
157
|
-
|
|
240
|
+
const { s, k, W0 } = await inAssembly(`the sweep of "${r.sweep}"`),
|
|
241
|
+
item = p.in.item,
|
|
242
|
+
cell = ev(p.cell);
|
|
243
|
+
const isNamed = (q, n) => q.name === n || q.leaf === n || q.item === n || q.name.startsWith(`${n}.`),
|
|
244
|
+
moving = s.parts.filter((q) => isNamed(q, r.sweep));
|
|
245
|
+
if (!moving.length)
|
|
246
|
+
throw new Error(
|
|
247
|
+
`${fileName}: ${p.in.assembly} has no item or part "${r.sweep}" to sweep (items: ${s.motion.items.map((x) => x[0]).join(', ')})`,
|
|
248
|
+
);
|
|
249
|
+
if (moving.some((q) => (q.moves ?? q.item) === item))
|
|
250
|
+
throw new Error(
|
|
251
|
+
`${fileName}: "${r.sweep}" is ${item} itself, the item this problem is in: sweep a part that moves against it`,
|
|
252
|
+
);
|
|
253
|
+
const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length),
|
|
254
|
+
through = [r.through ?? []].flat();
|
|
255
|
+
if (!through.length)
|
|
256
|
+
throw new Error(
|
|
257
|
+
`${fileName}: the sweep of "${r.sweep}" needs the joint it moves through: "through": "<joint>" (joints: ${free.map((j) => j.id).join(', ') || 'none'})`,
|
|
258
|
+
);
|
|
259
|
+
const apply = (M, [x, y, z]) => [
|
|
260
|
+
M[0] * x + M[1] * y + M[2] * z + M[3],
|
|
261
|
+
M[4] * x + M[5] * y + M[6] * z + M[7],
|
|
262
|
+
M[8] * x + M[9] * y + M[10] * z + M[11],
|
|
263
|
+
];
|
|
158
264
|
const idx = moving.map((q) => s.motion.items.findIndex((x) => x[0] === (q.moves ?? q.item)));
|
|
159
|
-
const local = moving.map((q, i) => {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
265
|
+
const local = moving.map((q, i) => {
|
|
266
|
+
const L = inv(W0[idx[i]]);
|
|
267
|
+
return q.triangles.map((t) => t.map((v) => apply(L, v)));
|
|
268
|
+
}); // each in its own item's frame
|
|
269
|
+
const sample = local.map((tris) => {
|
|
270
|
+
const v = tris.flat(),
|
|
271
|
+
n = Math.ceil(v.length / 400);
|
|
272
|
+
return v.filter((_, i) => i % n === 0);
|
|
273
|
+
}); // (no more than about 400 points a part)
|
|
274
|
+
const held = Object.fromEntries(
|
|
275
|
+
Object.entries(s.jointValues).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow),
|
|
276
|
+
);
|
|
277
|
+
const z = flat ? (p.in.z != null ? ev(p.in.z) : ev(p.thickness) / 2) : null,
|
|
278
|
+
zlo = flat ? z - ev(p.thickness) / 2 : null,
|
|
279
|
+
zhi = flat ? z + ev(p.thickness) / 2 : null,
|
|
280
|
+
out = [];
|
|
163
281
|
for (const id of through) {
|
|
164
282
|
const j = free.find((x) => x.id === id);
|
|
165
|
-
if (!j)
|
|
283
|
+
if (!j)
|
|
284
|
+
throw new Error(
|
|
285
|
+
`${fileName}: ${p.in.assembly} has no joint "${id}" that moves on its own to sweep "${r.sweep}" through (joints: ${free.map((x) => x.id).join(', ') || 'none'})`,
|
|
286
|
+
);
|
|
166
287
|
j.dofs.forEach(([lo, hi], d) => {
|
|
167
|
-
const at = (v) => {
|
|
168
|
-
|
|
288
|
+
const at = (v) => {
|
|
289
|
+
const W = placeItems(
|
|
290
|
+
s.motion,
|
|
291
|
+
jointValues(s.motion, { ...held, [id]: held[id].map((x, i) => (i === d ? v : x)) }),
|
|
292
|
+
),
|
|
293
|
+
T = inv(W[k]);
|
|
294
|
+
return idx.map((m) => mul(T, W[m]));
|
|
295
|
+
};
|
|
296
|
+
let travel = 0,
|
|
297
|
+
before = at(lo).map((M, m) => sample[m].map((v) => apply(M, v)));
|
|
169
298
|
for (let i = 1; i <= 32; i++) {
|
|
170
299
|
const now = at(lo + ((hi - lo) * i) / 32).map((M, m) => sample[m].map((v) => apply(M, v)));
|
|
171
|
-
travel += Math.max(
|
|
300
|
+
travel += Math.max(
|
|
301
|
+
0,
|
|
302
|
+
...now.flatMap((pts, m) => pts.map((q, n) => Math.hypot(...q.map((c, a) => c - before[m][n][a])))),
|
|
303
|
+
);
|
|
172
304
|
before = now;
|
|
173
305
|
}
|
|
174
306
|
const what = `${id}${j.dofs.length > 1 ? ` (its value ${d + 1})` : ''}`;
|
|
175
|
-
if (!(travel > 1e-6))
|
|
307
|
+
if (!(travel > 1e-6))
|
|
308
|
+
throw new Error(
|
|
309
|
+
`${fileName}: ${what} doesn't move "${r.sweep}" against ${item} (from ${round(lo)} to ${round(hi)}): sweep it through a joint between them`,
|
|
310
|
+
);
|
|
176
311
|
const steps = r.steps ?? Math.max(1, Math.ceil((2 * travel) / cell));
|
|
177
|
-
if (r.steps == null && steps > 360)
|
|
312
|
+
if (r.steps == null && steps > 360)
|
|
313
|
+
throw new Error(
|
|
314
|
+
`${fileName}: sweeping "${r.sweep}" through ${what} would take ${steps} steps on ${cell} mm cells (its farthest point travels ${round(travel, 1)} mm): give the sweep its steps, or larger cells`,
|
|
315
|
+
);
|
|
178
316
|
let made = 0;
|
|
179
317
|
for (let i = 0; i <= steps; i++) {
|
|
180
|
-
const v = lo + ((hi - lo) * i) / steps,
|
|
318
|
+
const v = lo + ((hi - lo) * i) / steps,
|
|
319
|
+
Ms = at(v);
|
|
181
320
|
for (const [m, tris] of local.entries()) {
|
|
182
321
|
const moved = tris.map((t) => t.map((q) => apply(Ms[m], q).map(clean)));
|
|
183
|
-
if (!flat) {
|
|
322
|
+
if (!flat) {
|
|
323
|
+
out.push({ triangles: moved, sweep: r.sweep, joint: id, value: round(v, 6) });
|
|
324
|
+
made++;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
184
327
|
// Each section's outlines, each a ring turned solid on its left (an outline counter-clockwise, a hole in it
|
|
185
328
|
// clockwise), for the design to cut exactly (rings); and for the solver one polygon of them all, each closed and
|
|
186
329
|
// back to the first one's start, so a point is inside where it is inside an odd number of them (a hole in the
|
|
187
330
|
// part stays open) and the joins cancel out. A point within 0.001 mm of the line through its neighbours (where a face's diagonal is
|
|
188
331
|
// cut, or a boolean left a sliver) is dropped, and a section whose corners all lie within 0.01 mm of one already taken at this step is left out.
|
|
189
|
-
const same = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9,
|
|
190
|
-
|
|
191
|
-
const
|
|
332
|
+
const same = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9,
|
|
333
|
+
kept = [];
|
|
334
|
+
const off = (q, a, b) => {
|
|
335
|
+
const d = [b[0] - a[0], b[1] - a[1]],
|
|
336
|
+
L = Math.hypot(...d);
|
|
337
|
+
return L < 1e-12
|
|
338
|
+
? Math.hypot(q[0] - a[0], q[1] - a[1])
|
|
339
|
+
: Math.abs(d[0] * (q[1] - a[1]) - d[1] * (q[0] - a[0])) / L;
|
|
340
|
+
};
|
|
341
|
+
const straight = (ring) => {
|
|
342
|
+
const l = [...ring];
|
|
343
|
+
for (let n = 0; n < l.length && l.length > 3;)
|
|
344
|
+
if (off(l[n], l[(n + l.length - 1) % l.length], l[(n + 1) % l.length]) < 1e-3) {
|
|
345
|
+
l.splice(n, 1);
|
|
346
|
+
n = Math.max(0, n - 1);
|
|
347
|
+
} else n++;
|
|
348
|
+
return l;
|
|
349
|
+
};
|
|
192
350
|
for (const h of slabLevels(moved, zlo, zhi, cell)) {
|
|
193
|
-
const rings = loops(section(moved, 2, h))
|
|
351
|
+
const rings = loops(section(moved, 2, h))
|
|
352
|
+
.map((l) => straight((same(l[0], l.at(-1)) ? l.slice(0, -1) : l).map((q) => q.map(clean))))
|
|
353
|
+
.filter((l) => l.length >= 3);
|
|
194
354
|
if (!rings.length) continue;
|
|
195
|
-
const within = (q, P) => {
|
|
355
|
+
const within = (q, P) => {
|
|
356
|
+
let c = false;
|
|
357
|
+
for (let a = 0, b = P.length - 1; a < P.length; b = a++)
|
|
358
|
+
if (
|
|
359
|
+
P[a][1] > q[1] !== P[b][1] > q[1] &&
|
|
360
|
+
q[0] < ((P[b][0] - P[a][0]) * (q[1] - P[a][1])) / (P[b][1] - P[a][1]) + P[a][0]
|
|
361
|
+
)
|
|
362
|
+
c = !c;
|
|
363
|
+
return c;
|
|
364
|
+
};
|
|
196
365
|
const turned = rings.map((l, n) => {
|
|
197
|
-
const depth = rings.filter((o, m) => m !== n && within(l[0], o)).length,
|
|
366
|
+
const depth = rings.filter((o, m) => m !== n && within(l[0], o)).length,
|
|
367
|
+
ccw =
|
|
368
|
+
l.reduce((t, q, a) => t + q[0] * l[(a + 1) % l.length][1] - l[(a + 1) % l.length][0] * q[1], 0) > 0;
|
|
198
369
|
return ccw === (depth % 2 === 0) ? l : [...l].reverse();
|
|
199
370
|
});
|
|
200
|
-
const near = (l, o) =>
|
|
201
|
-
|
|
371
|
+
const near = (l, o) =>
|
|
372
|
+
l.length === o.length && l.every((q) => o.some((w) => Math.hypot(q[0] - w[0], q[1] - w[1]) < 0.01));
|
|
373
|
+
if (kept.some((k) => k.length === turned.length && turned.every((l) => k.some((o) => near(l, o)))))
|
|
374
|
+
continue;
|
|
202
375
|
kept.push(turned);
|
|
203
|
-
const start = turned[0][0],
|
|
204
|
-
|
|
376
|
+
const start = turned[0][0],
|
|
377
|
+
points = turned.flatMap((l, n) => [...l, l[0], ...(n ? [start] : [])]);
|
|
378
|
+
out.push({ points, rings: turned, sweep: r.sweep, joint: id, value: round(v, 6) });
|
|
379
|
+
made++;
|
|
205
380
|
}
|
|
206
381
|
}
|
|
207
382
|
}
|
|
208
383
|
sweeps.push({ sweep: r.sweep, through: what, from: round(lo, 6), to: round(hi, 6), steps, regions: made });
|
|
209
384
|
});
|
|
210
385
|
}
|
|
211
|
-
if (!out.length)
|
|
386
|
+
if (!out.length)
|
|
387
|
+
throw new Error(
|
|
388
|
+
`${fileName}: "${r.sweep}" never reaches into the plate (z ${round(zlo)} to ${round(zhi)} mm in ${item}) through ${through.join(', ')}: nothing to keep clear there (set in.z, the plate's middle, if it lies elsewhere)`,
|
|
389
|
+
);
|
|
212
390
|
return out;
|
|
213
391
|
};
|
|
214
392
|
// The build direction: a direction ('+z'), or a variable holding one
|
|
@@ -216,70 +394,218 @@ async function readOne(project, ref, link) {
|
|
|
216
394
|
// The sides it is milled from, and a one-way mould's draw, likewise: or a variable holding them ('+z', '+z +x', or
|
|
217
395
|
// 'none': not milled, not cast), so a variant can switch the process
|
|
218
396
|
const named = (v) => (typeof v === 'string' && typeof values[v] === 'string' ? values[v] : v);
|
|
219
|
-
const millSides = (() => {
|
|
220
|
-
|
|
397
|
+
const millSides = (() => {
|
|
398
|
+
const v = named(p.mill);
|
|
399
|
+
if (typeof v !== 'string') return v;
|
|
400
|
+
const list = v
|
|
401
|
+
.trim()
|
|
402
|
+
.split(/[\s,]+/)
|
|
403
|
+
.filter(Boolean);
|
|
404
|
+
return v === 'none' ? null : list.length > 1 ? list : v;
|
|
405
|
+
})();
|
|
406
|
+
const castWay = (() => {
|
|
407
|
+
const v = named(p.cast);
|
|
408
|
+
return v === 'none' ? null : v;
|
|
409
|
+
})();
|
|
221
410
|
// A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
|
|
222
|
-
const point = (t) => {
|
|
411
|
+
const point = (t) => {
|
|
412
|
+
const up = overhang && overhang !== 'none' ? overhang : '+z';
|
|
413
|
+
return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t;
|
|
414
|
+
};
|
|
223
415
|
const region = async (r) => {
|
|
224
|
-
if (r.sweep != null)
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
416
|
+
if (r.sweep != null)
|
|
417
|
+
throw new Error(
|
|
418
|
+
`${path.basename(file)}: a swept part ("${r.sweep}") is a region to keep clear: put it under avoid`,
|
|
419
|
+
);
|
|
420
|
+
if (r.anchor || r.joint) {
|
|
421
|
+
// at an anchor, or an assembly's joint: its place (x and y in a flat problem), and a cylinder along its axis unless it names one
|
|
422
|
+
const kind = r.anchor ? 'anchor' : 'joint',
|
|
423
|
+
named = `the ${kind} "${r.anchor || r.joint}"`;
|
|
424
|
+
if (r.anchor && r.joint)
|
|
425
|
+
throw new Error(
|
|
426
|
+
`${path.basename(file)}: a region is at an anchor or at a joint, not both ("${r.anchor}", "${r.joint}")`,
|
|
427
|
+
);
|
|
428
|
+
if (r.at)
|
|
429
|
+
throw new Error(
|
|
430
|
+
`${path.basename(file)}: a region at an ${kind} ("${r.anchor || r.joint}") takes no at: the ${kind} places it`,
|
|
431
|
+
);
|
|
432
|
+
const a = r.anchor ? await anchor(r.anchor) : await jointAt(r.joint),
|
|
433
|
+
along = a.axis.map((c) => Math.abs(c) > 1e-9);
|
|
434
|
+
if (r.length != null && !r.axis && along.filter(Boolean).length !== 1)
|
|
435
|
+
throw new Error(
|
|
436
|
+
`${path.basename(file)}: ${named} points along [${a.axis.map((c) => round(c, 3)).join(', ')}], not along x, y or z: give the cylinder an axis`,
|
|
437
|
+
);
|
|
438
|
+
return region({
|
|
439
|
+
...r,
|
|
440
|
+
anchor: undefined,
|
|
441
|
+
joint: undefined,
|
|
442
|
+
at: flat ? a.at.slice(0, 2) : a.at,
|
|
443
|
+
...(r.length != null && !r.axis ? { axis: 'xyz'[along.indexOf(true)] } : {}),
|
|
444
|
+
});
|
|
232
445
|
}
|
|
233
|
-
if (r.part) {
|
|
234
|
-
|
|
235
|
-
|
|
446
|
+
if (r.part) {
|
|
447
|
+
// with where it is (its box's centre), for a load's or support's resultant
|
|
448
|
+
const triangles = await part(r.part),
|
|
449
|
+
lo = [Infinity, Infinity, Infinity],
|
|
450
|
+
hi = [-Infinity, -Infinity, -Infinity];
|
|
451
|
+
for (const t of triangles)
|
|
452
|
+
for (const q of t)
|
|
453
|
+
for (let a = 0; a < 3; a++) {
|
|
454
|
+
lo[a] = Math.min(lo[a], q[a]);
|
|
455
|
+
hi[a] = Math.max(hi[a], q[a]);
|
|
456
|
+
}
|
|
236
457
|
const at = lo.map((x, a) => (x + hi[a]) / 2);
|
|
237
458
|
return flat ? { triangles, part: r.part, at: at.slice(0, 2), flat: true } : { triangles, part: r.part, at }; // flat: its section halfway up
|
|
238
459
|
}
|
|
239
460
|
if (r.points) return { points: r.points.map(pt) };
|
|
240
461
|
if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
|
|
241
|
-
if (r.length != null) {
|
|
462
|
+
if (r.length != null) {
|
|
463
|
+
const axis = r.axis || 'z',
|
|
464
|
+
t = r.teardrop && point(r.teardrop);
|
|
465
|
+
return { at: pt(r.at), r: ev(r.r), length: ev(r.length), axis, ...(t && t[1] !== axis ? { teardrop: t } : {}) };
|
|
466
|
+
} // along its axis, a teardrop has no point
|
|
242
467
|
return { at: pt(r.at), ...(r.r != null ? { r: ev(r.r) } : {}) };
|
|
243
468
|
};
|
|
244
469
|
const regions = (list) => Promise.all([list || []].flat().map(region));
|
|
245
470
|
const m = values[p.material];
|
|
246
|
-
if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number')
|
|
471
|
+
if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number')
|
|
472
|
+
throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
|
|
247
473
|
// The filter's radius is about the thinnest member: a cell and a half unless the problem gives one, and never under two
|
|
248
474
|
// of the printer's lines, the thinnest wall it lays solid (so it only binds on cells under 0.56 mm on a 0.42 mm line)
|
|
249
|
-
const printer = printerOf(project),
|
|
250
|
-
|
|
475
|
+
const printer = printerOf(project),
|
|
476
|
+
line = printer ? resolve({ uses: [printer] }).values[printer]?.line : null,
|
|
477
|
+
lines = typeof line === 'number' ? 2 * line : 0;
|
|
478
|
+
const space = await regions(p.space),
|
|
479
|
+
dim = flat
|
|
480
|
+
? 2
|
|
481
|
+
: space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3
|
|
482
|
+
? 3
|
|
483
|
+
: 2;
|
|
251
484
|
const problem = {
|
|
252
|
-
space,
|
|
253
|
-
|
|
254
|
-
|
|
485
|
+
space,
|
|
486
|
+
keep: await regions(p.keep),
|
|
487
|
+
avoid: (
|
|
488
|
+
await Promise.all([p.avoid || []].flat().map(async (r) => (r.sweep != null ? swept(r) : [await region(r)])))
|
|
489
|
+
).flat(),
|
|
490
|
+
supports: await Promise.all(
|
|
491
|
+
p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) })),
|
|
492
|
+
),
|
|
493
|
+
loads: await Promise.all(
|
|
494
|
+
p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' })),
|
|
495
|
+
),
|
|
255
496
|
cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
|
|
256
|
-
material: { E: m.modulus, nu: m.poisson },
|
|
257
|
-
...(
|
|
258
|
-
|
|
497
|
+
material: { E: m.modulus, nu: m.poisson },
|
|
498
|
+
...(dim === 2 ? { thickness: ev(p.thickness) } : {}),
|
|
499
|
+
cell: ev(p.cell),
|
|
500
|
+
...(p.volume != null ? { volume: ev(p.volume) } : {}),
|
|
501
|
+
...(p.stress != null ? { stress: ev(p.stress) } : {}),
|
|
502
|
+
...(p.strain != null ? { strain: ev(p.strain) } : {}),
|
|
503
|
+
...(p.robust ? { robust: true } : {}),
|
|
504
|
+
...(p.filter != null ? { filter: ev(p.filter) } : lines > ev(p.cell) * 1.5 ? { filter: lines } : {}),
|
|
505
|
+
...(p.penal != null ? { penal: ev(p.penal) } : {}),
|
|
506
|
+
...(p.projection != null ? { projection: p.projection } : {}),
|
|
507
|
+
...(p.steps != null ? { steps: p.steps } : {}),
|
|
259
508
|
...(overhang && overhang !== 'none' ? { overhang } : {}),
|
|
260
509
|
// How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
|
|
261
|
-
...(millSides ? { mill: millSides } : {}),
|
|
510
|
+
...(millSides ? { mill: millSides } : {}),
|
|
511
|
+
...(castWay
|
|
512
|
+
? {
|
|
513
|
+
cast:
|
|
514
|
+
typeof castWay === 'string'
|
|
515
|
+
? castWay
|
|
516
|
+
: { draw: castWay.draw, ...(castWay.parting != null ? { parting: ev(castWay.parting) } : {}) },
|
|
517
|
+
}
|
|
518
|
+
: {}),
|
|
262
519
|
// (a tool or draft with the process switched off by its variable is left out with it; one with no such process
|
|
263
520
|
// at all goes on, for topopt to refuse by name)
|
|
264
|
-
...(p.tool != null && (millSides || !p.mill) ? { tool: ev(p.tool) } : {}),
|
|
521
|
+
...(p.tool != null && (millSides || !p.mill) ? { tool: ev(p.tool) } : {}),
|
|
522
|
+
...(p.draft != null && (castWay || !p.cast) ? { draft: ev(p.draft) } : {}),
|
|
523
|
+
...(p.voids === 'prevented' ? { voids: 'prevented' } : {}),
|
|
265
524
|
...(p.feature != null ? { feature: ev(p.feature) } : {}),
|
|
266
|
-
...(p.symmetry ? { symmetry: p.symmetry } : {}),
|
|
525
|
+
...(p.symmetry ? { symmetry: p.symmetry } : {}),
|
|
526
|
+
...(p.extrude ? { extrude: p.extrude } : {}),
|
|
267
527
|
// A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
|
|
268
|
-
...(p.output
|
|
528
|
+
...(p.output
|
|
529
|
+
? {
|
|
530
|
+
output: {
|
|
531
|
+
...(await region(p.output)),
|
|
532
|
+
direction: pt(p.output.direction),
|
|
533
|
+
...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}),
|
|
534
|
+
},
|
|
535
|
+
}
|
|
536
|
+
: {}),
|
|
269
537
|
...(p.input_spring != null ? { input_spring: ev(p.input_spring) } : {}),
|
|
270
538
|
};
|
|
271
|
-
if (dim === 2 && !(problem.thickness > 0))
|
|
272
|
-
|
|
539
|
+
if (dim === 2 && !(problem.thickness > 0))
|
|
540
|
+
throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
|
|
541
|
+
const outline = {
|
|
542
|
+
smooth: p.outline?.smooth ?? 4,
|
|
543
|
+
minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2,
|
|
544
|
+
fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25,
|
|
545
|
+
...(dim === 3 && p.outline?.reduce !== false
|
|
546
|
+
? { reduce: p.outline?.reduce != null ? ev(p.outline.reduce) : REDUCE }
|
|
547
|
+
: {}),
|
|
548
|
+
}; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
|
|
273
549
|
// A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
|
|
274
550
|
// (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
|
|
275
551
|
// tipped corners leave dips that slice as islands, and the layers step out no further for it)
|
|
276
|
-
if (dim === 3 && problem.overhang) {
|
|
552
|
+
if (dim === 3 && problem.overhang) {
|
|
553
|
+
const n = printerOf(project),
|
|
554
|
+
pr = resolve({ uses: [n] }).values[n];
|
|
555
|
+
outline.overhang = {
|
|
556
|
+
up: problem.overhang,
|
|
557
|
+
angle: pr?.overhang ?? 45,
|
|
558
|
+
bridge: pr?.bridge ?? 5,
|
|
559
|
+
layer: pr?.layer ?? 0.2,
|
|
560
|
+
line: pr?.line ?? 0.42,
|
|
561
|
+
...(p.outline?.tip ? { tip: true } : {}),
|
|
562
|
+
};
|
|
563
|
+
problem.bridge = outline.overhang.bridge;
|
|
564
|
+
} // (the optimiser bridges half that)
|
|
277
565
|
// What the result is made from, for cad why: the rule sets, the problem's own values, the parts and anchors of other
|
|
278
566
|
// designs it reads, and where its filter came from
|
|
279
|
-
const inputs = {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
567
|
+
const inputs = {
|
|
568
|
+
uses,
|
|
569
|
+
variables: Object.fromEntries(Object.keys(p.variables || {}).map((k) => [k, values[k]])),
|
|
570
|
+
...(variant ? { set: p.variants[variant] } : {}),
|
|
571
|
+
parts: [...parts.keys()].sort(),
|
|
572
|
+
...(p.in
|
|
573
|
+
? {
|
|
574
|
+
assembly: {
|
|
575
|
+
name: p.in.assembly,
|
|
576
|
+
item: p.in.item,
|
|
577
|
+
pose: placing ? (await placing).s.pose : (p.in.pose ?? null),
|
|
578
|
+
joints: [...joints.values()]
|
|
579
|
+
.sort((a, b) => (a.joint < b.joint ? -1 : 1))
|
|
580
|
+
.map(({ joint: j, at }) => ({ joint: j, at: at.map((c) => round(c, 4)) })),
|
|
581
|
+
sweeps,
|
|
582
|
+
},
|
|
583
|
+
}
|
|
584
|
+
: {}),
|
|
585
|
+
anchors: [...anchors.values()]
|
|
586
|
+
.sort((a, b) => (a.anchor < b.anchor ? -1 : 1))
|
|
587
|
+
.map(({ anchor: a, at }) => ({ anchor: a, at: at.map((c) => round(c, 4)) })),
|
|
588
|
+
filter:
|
|
589
|
+
p.filter != null
|
|
590
|
+
? { value: problem.filter, from: `the problem: ${p.filter}` }
|
|
591
|
+
: problem.filter
|
|
592
|
+
? { value: problem.filter, from: `two of ${printer}'s lines (2 × ${line} mm), more than a cell and a half` }
|
|
593
|
+
: { value: round(problem.cell * 1.5), from: 'a cell and a half' },
|
|
594
|
+
};
|
|
595
|
+
return {
|
|
596
|
+
ref,
|
|
597
|
+
name,
|
|
598
|
+
variant,
|
|
599
|
+
file,
|
|
600
|
+
dim,
|
|
601
|
+
title: p.title || name,
|
|
602
|
+
material: { name: p.material, ...m },
|
|
603
|
+
problem,
|
|
604
|
+
outline,
|
|
605
|
+
critical: !!p.critical,
|
|
606
|
+
inputs,
|
|
607
|
+
voids: p.voids || 'allowed',
|
|
608
|
+
};
|
|
283
609
|
}
|
|
284
610
|
|
|
285
611
|
/**
|
|
@@ -292,8 +618,12 @@ async function readOne(project, ref, link) {
|
|
|
292
618
|
// Nodes no cell that may be solid touches (the grid's corners outside a shaped space, the inside of avoided pockets)
|
|
293
619
|
// are held: at the void's near-nothing stiffness they are what the solver crawls through, and they carry no material
|
|
294
620
|
function holdEmpty(spec) {
|
|
295
|
-
const g = makeGrid(spec.grid),
|
|
296
|
-
|
|
621
|
+
const g = makeGrid(spec.grid),
|
|
622
|
+
dim = spec.grid.nz ? 3 : 2,
|
|
623
|
+
corners = 1 << dim,
|
|
624
|
+
on = new Uint8Array(g.nodes);
|
|
625
|
+
for (let e = 0; e < g.cells; e++)
|
|
626
|
+
if (spec.passive[e] >= 0) for (let k = 0; k < corners; k++) on[g.edof[e * g.cellDofs + dim * k] / dim] = 1;
|
|
297
627
|
for (let m = 0; m < g.nodes; m++) if (!on[m]) for (let a = 0; a < dim; a++) spec.fixed[dim * m + a] = 1;
|
|
298
628
|
return spec;
|
|
299
629
|
}
|
|
@@ -302,32 +632,58 @@ function holdEmpty(spec) {
|
|
|
302
632
|
// refused or prevented (a powder bed print, a trapped core), each void left with its volume (mm³, or mm² in 2D) and
|
|
303
633
|
// where it is, and with prevented that they were
|
|
304
634
|
function made(r, spec, density) {
|
|
305
|
-
const p = r.problem,
|
|
635
|
+
const p = r.problem,
|
|
636
|
+
out = {};
|
|
306
637
|
if (p.mill || p.cast) {
|
|
307
|
-
const c = spec.cast,
|
|
308
|
-
|
|
638
|
+
const c = spec.cast,
|
|
639
|
+
from = p.mill || (typeof c === 'string' ? c : c.draw),
|
|
640
|
+
tool = p.tool ? p.tool / spec.grid.h : undefined;
|
|
641
|
+
const u = undercuts(spec.grid, density, {
|
|
642
|
+
from,
|
|
643
|
+
...(c && typeof c === 'object' ? { parting: c.parting } : {}),
|
|
644
|
+
...(p.draft ? { draft: p.draft } : {}),
|
|
645
|
+
});
|
|
309
646
|
// With a tool's size: the cells it can't get its end into besides, in the design (none, by construction) and in
|
|
310
647
|
// avoid regions (a hole narrower than the tool: drilled, or a smaller tool)
|
|
311
648
|
if (tool) {
|
|
312
|
-
const hidden = new Set(u.cells),
|
|
313
|
-
|
|
649
|
+
const hidden = new Set(u.cells),
|
|
650
|
+
narrow = undercuts(spec.grid, density, { from, tool }).cells.filter((e) => !hidden.has(e));
|
|
651
|
+
out.narrow = {
|
|
652
|
+
design: narrow.filter((e) => spec.passive[e] === 0).length,
|
|
653
|
+
avoided: narrow.filter((e) => spec.passive[e] === -1).length,
|
|
654
|
+
};
|
|
314
655
|
}
|
|
315
656
|
// (a draft at the grid: a step out every whole number of layers in 1 / tan, so the angle made is atan of one over it)
|
|
316
657
|
const every = p.draft ? Math.max(1, Math.floor(1 / Math.tan((p.draft * Math.PI) / 180) + 1e-9)) : 0;
|
|
317
|
-
out.process = p.mill
|
|
658
|
+
out.process = p.mill
|
|
659
|
+
? { mill: p.mill, ...(p.tool ? { tool: p.tool } : {}) }
|
|
660
|
+
: {
|
|
661
|
+
cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) },
|
|
662
|
+
...(every ? { draft: p.draft, every, made: round((Math.atan(1 / every) * 180) / Math.PI, 2) } : {}),
|
|
663
|
+
};
|
|
318
664
|
out.undercuts = u.count;
|
|
319
665
|
}
|
|
320
666
|
if (p.symmetry) out.symmetry = p.symmetry;
|
|
321
667
|
if (p.extrude) out.extrude = p.extrude;
|
|
322
668
|
// How grey it came out: a process or a tie can leave no clear part (a 2D section milled from its side)
|
|
323
669
|
if (p.mill || p.cast || p.symmetry || p.extrude) out.grey = round(grey(density, spec.passive), 3);
|
|
324
|
-
if (r.voids === 'refused' || r.voids === 'prevented')
|
|
670
|
+
if (r.voids === 'refused' || r.voids === 'prevented')
|
|
671
|
+
out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({
|
|
672
|
+
volume: round(v.volume, 3),
|
|
673
|
+
at: v.at.map((x) => round(x, 3)),
|
|
674
|
+
}));
|
|
325
675
|
if (r.voids === 'prevented') out.vented = true;
|
|
326
676
|
// The thinnest member asked: the ball's radius on the grid, the width it holds members to (a cell, where the grid
|
|
327
677
|
// already does), and the solid cells left in members narrower (or on a square outside corner)
|
|
328
678
|
if (p.feature != null) {
|
|
329
|
-
const h = spec.grid.h,
|
|
330
|
-
|
|
679
|
+
const h = spec.grid.h,
|
|
680
|
+
cells = featureCells(p.feature, h);
|
|
681
|
+
out.feature = {
|
|
682
|
+
asked: p.feature,
|
|
683
|
+
cells,
|
|
684
|
+
holds: round((2 * cells + 1) * h, 3),
|
|
685
|
+
thin: cells ? thin(spec.grid, density, { radius: cells }).count : 0,
|
|
686
|
+
};
|
|
331
687
|
}
|
|
332
688
|
return out;
|
|
333
689
|
}
|
|
@@ -338,7 +694,19 @@ const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).dige
|
|
|
338
694
|
* that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
|
|
339
695
|
* @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
|
|
340
696
|
*/
|
|
341
|
-
|
|
697
|
+
/**
|
|
698
|
+
* Throws (code workspace.outside, naming the link) where the kept results optimised() reads (.cache/optimise,
|
|
699
|
+
* .cache/densities) hold a link out of the workspace: a cloned workspace may carry a .cache/ of its own. Called before
|
|
700
|
+
* optimised(), as its own text is part of the densities key (densityCode).
|
|
701
|
+
*/
|
|
702
|
+
export const ownResults = () => noLinksOut([paths.cache('optimise'), paths.cache('densities')]);
|
|
703
|
+
export const densityCode = () => ({
|
|
704
|
+
version: VERSION,
|
|
705
|
+
solver: source('@rulecad/topopt').split('// ---------- shapes from results ----------')[0],
|
|
706
|
+
fea: source('@rulecad/fea'),
|
|
707
|
+
threads: source('@rulecad/fea/threads'),
|
|
708
|
+
cad: `${holdEmpty.toString()}\n${optimised.toString()}`,
|
|
709
|
+
});
|
|
342
710
|
/**
|
|
343
711
|
* The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
|
|
344
712
|
* densityCode (cad's own share is holdEmpty and optimised, which readies the problem and calls the solver with its
|
|
@@ -346,102 +714,211 @@ export const densityCode = () => ({ version: VERSION, solver: source('@rulecad/t
|
|
|
346
714
|
* the folder (scripts/dimension-diff.mjs).
|
|
347
715
|
* @param {object} problem readProblem's problem @param {ReturnType<typeof densityCode>} [code] @returns {string}
|
|
348
716
|
*/
|
|
349
|
-
export const densitiesKey = (problem, code = densityCode()) =>
|
|
717
|
+
export const densitiesKey = (problem, code = densityCode()) =>
|
|
718
|
+
digest([code.version, problem, code.solver, code.fea, code.threads, code.cad]);
|
|
350
719
|
export async function optimised(project, ref, { onStep, onRun, fresh = false } = {}) {
|
|
351
|
-
const r = await readProblem(project, ref),
|
|
720
|
+
const r = await readProblem(project, ref),
|
|
721
|
+
topopt = source('@rulecad/topopt');
|
|
352
722
|
// Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
|
|
353
723
|
// them, by everything: a change to how shapes are drawn redraws them without optimising again
|
|
354
724
|
// The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
|
|
355
|
-
const hash = digest([
|
|
356
|
-
|
|
357
|
-
|
|
725
|
+
const hash = digest([
|
|
726
|
+
VERSION,
|
|
727
|
+
r.problem,
|
|
728
|
+
r.outline,
|
|
729
|
+
r.voids,
|
|
730
|
+
topopt,
|
|
731
|
+
source('@rulecad/fea'),
|
|
732
|
+
fs.readFileSync(new URL(import.meta.url), 'utf8'),
|
|
733
|
+
]),
|
|
734
|
+
file = paths.cache('optimise', `${hash}.json`);
|
|
735
|
+
if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file))
|
|
736
|
+
return { ...JSON.parse(host.readText(file)), cached: true };
|
|
737
|
+
const spec = holdEmpty(discretise(r.problem)),
|
|
738
|
+
densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
|
|
358
739
|
// A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
|
|
359
740
|
const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
|
|
360
|
-
if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities))
|
|
741
|
+
if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities))
|
|
742
|
+
onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
|
|
361
743
|
else if (fresh) onRun?.('asked to run afresh');
|
|
362
|
-
const o =
|
|
744
|
+
const o =
|
|
745
|
+
!fresh && !process.env.CAD_NO_CACHE && host.exists(densities)
|
|
746
|
+
? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(JSON.parse(host.readText(densities)))
|
|
747
|
+
: optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
|
|
363
748
|
if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
|
|
364
749
|
if (!host.exists(seen)) host.writeText(seen, '');
|
|
365
750
|
// Regions as data: a part's triangles are named, not copied
|
|
366
751
|
const named = (list) => list.map(({ triangles, ...x }) => x);
|
|
367
|
-
const shape =
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
752
|
+
const shape =
|
|
753
|
+
r.dim === 2
|
|
754
|
+
? (() => {
|
|
755
|
+
const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
|
|
756
|
+
return {
|
|
757
|
+
outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])),
|
|
758
|
+
area: loops.reduce((s, l) => s + area(l), 0),
|
|
759
|
+
};
|
|
760
|
+
})()
|
|
761
|
+
: (() => {
|
|
762
|
+
// The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
|
|
763
|
+
// thin members come out thinner than they are)
|
|
764
|
+
// Printed without supports: before it's drawn at a level, whatever wouldn't print at that level (hanging with nothing
|
|
765
|
+
// under it) is emptied (printable, in topopt); kept regions stay. A bridge may run out half the printer's span.
|
|
766
|
+
const ov = r.outline.overhang,
|
|
767
|
+
coarseKeep = Uint8Array.from(spec.passive, (p) => (p === 1 ? 1 : 0)),
|
|
768
|
+
emptied = new Map();
|
|
769
|
+
const cleaned = (grid, density, keep, iso) => {
|
|
770
|
+
if (!ov) return density;
|
|
771
|
+
const reach = Math.floor(ov.bridge / 2 / grid.h);
|
|
772
|
+
// Spikes off the underside first (a hanging cell with few neighbours), then whatever is left hanging, in turn until neither finds any
|
|
773
|
+
let d = density,
|
|
774
|
+
gone = 0;
|
|
775
|
+
for (let round = 0; round < 10; round++) {
|
|
776
|
+
const sp = despike(grid, d, { up: ov.up, iso, keep }),
|
|
777
|
+
c = printable(grid, sp.density, { up: ov.up, iso, keep, reach });
|
|
778
|
+
d = c.density;
|
|
779
|
+
gone += sp.emptied + c.emptied;
|
|
780
|
+
if (!sp.emptied && !c.emptied) break;
|
|
781
|
+
}
|
|
782
|
+
emptied.set(iso, gone);
|
|
783
|
+
return d;
|
|
784
|
+
};
|
|
785
|
+
// The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
|
|
786
|
+
// thin members come out thinner than they are): found on the grid it was optimised on, which is quick
|
|
787
|
+
const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3,
|
|
788
|
+
draw = (grid, density, keep, iso) =>
|
|
789
|
+
surface(grid, cleaned(grid, density, keep, iso), spec.origin, {
|
|
790
|
+
smooth: r.outline.smooth,
|
|
791
|
+
iso,
|
|
792
|
+
overhang: ov,
|
|
793
|
+
});
|
|
794
|
+
let lo = 0.2,
|
|
795
|
+
hi = 0.8,
|
|
796
|
+
best = draw(spec.grid, o.density, coarseKeep, 0.5),
|
|
797
|
+
iso = 0.5;
|
|
798
|
+
for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
|
|
799
|
+
if (meshVolume(best.vertices, best.faces) < want) hi = iso;
|
|
800
|
+
else lo = iso; // a lower level encloses more
|
|
801
|
+
iso = (lo + hi) / 2;
|
|
802
|
+
best = draw(spec.grid, o.density, coarseKeep, iso);
|
|
803
|
+
}
|
|
804
|
+
// Then drawn on a finer grid (cells no bigger than the outline's fine size, 1 mm), so the cleaning works at nearer
|
|
805
|
+
// the printer's resolution: between two coarse cells the surface can dip under the overhang line, which sliced is an
|
|
806
|
+
// island; on the fine grid those dips are cells of their own, and go. One correction of the level for the volume.
|
|
807
|
+
const cells = spec.grid.nx * spec.grid.ny * spec.grid.nz,
|
|
808
|
+
factor = ov
|
|
809
|
+
? Math.max(
|
|
810
|
+
1,
|
|
811
|
+
Math.min(Math.ceil(spec.grid.h / (r.outline.fine ?? 1) - 1e-9), Math.floor(Math.cbrt(2e6 / cells))),
|
|
812
|
+
)
|
|
813
|
+
: 1; // and no more than about two million fine cells
|
|
814
|
+
const fine = factor > 1 ? refine(spec.grid, o.density, factor, { keep: coarseKeep, smooth: 1 }) : null;
|
|
815
|
+
let cleared = 0;
|
|
816
|
+
if (fine) {
|
|
817
|
+
best = draw(fine.grid, fine.density, fine.keep, iso);
|
|
818
|
+
const ratio = meshVolume(best.vertices, best.faces) / want;
|
|
819
|
+
if (Math.abs(ratio - 1) > 0.01) {
|
|
820
|
+
iso = Math.min(0.8, Math.max(0.2, iso + (ratio - 1) * 0.3));
|
|
821
|
+
best = draw(fine.grid, fine.density, fine.keep, iso);
|
|
822
|
+
} // a touch up or down the level
|
|
823
|
+
// Then as the printer will see it: sliced into layers, each against the one below. Wherever a layer's region has
|
|
824
|
+
// nothing under it (an island, which the printer lays on air), the fine cells it starts from are emptied, the
|
|
825
|
+
// cleaning takes whatever hung on them, and it's drawn again, until a slice finds none (each round a redraw)
|
|
826
|
+
const { nx, ny, nz, h } = fine.grid,
|
|
827
|
+
[ox, oy, oz] = spec.origin;
|
|
828
|
+
if ('xyz'.indexOf(ov.up[1]) === 2)
|
|
829
|
+
for (let round = 0; round < 4; round++) {
|
|
830
|
+
// (the slicer's layers are along z: a part is drawn in its print orientation); a safety net: the drawing leaves none as a rule
|
|
831
|
+
const found = islands(
|
|
832
|
+
best.faces.map((f) => f.map((n) => best.vertices[n])),
|
|
833
|
+
{ layer: ov.layer, overhang: ov.angle, line: ov.line },
|
|
834
|
+
).islands;
|
|
835
|
+
if (!found.length) break;
|
|
836
|
+
let hit = 0;
|
|
837
|
+
const clear = (i, j, k) => {
|
|
838
|
+
if (i < 0 || i >= nx || j < 0 || j >= ny || k < 0 || k >= nz) return 0;
|
|
839
|
+
const e = (k * ny + j) * nx + i;
|
|
840
|
+
if (fine.density[e] > 0 && !fine.keep[e]) {
|
|
841
|
+
fine.density[e] = 0;
|
|
842
|
+
return 1;
|
|
843
|
+
}
|
|
844
|
+
return 0;
|
|
845
|
+
};
|
|
846
|
+
for (const isl of found) {
|
|
847
|
+
let own = 0;
|
|
848
|
+
for (const [x, y] of isl.cells) {
|
|
849
|
+
const i = Math.floor((x - ox) / h),
|
|
850
|
+
j = Math.floor((y - oy) / h),
|
|
851
|
+
k0 = Math.floor((isl.z - oz) / h);
|
|
852
|
+
own += clear(i, j, k0) + clear(i, j, k0 + 1);
|
|
853
|
+
} // the cell the island starts in and the one above it
|
|
854
|
+
// Its own cells already empty: the island is drawn from the cells round them, so those go too
|
|
855
|
+
if (!own)
|
|
856
|
+
for (const [x, y] of isl.cells) {
|
|
857
|
+
const i0 = Math.floor((x - ox) / h),
|
|
858
|
+
j0 = Math.floor((y - oy) / h),
|
|
859
|
+
k0 = Math.floor((isl.z - oz) / h);
|
|
860
|
+
for (let k = k0; k <= k0 + 1; k++)
|
|
861
|
+
for (let j = j0 - 1; j <= j0 + 1; j++)
|
|
862
|
+
for (let i = i0 - 1; i <= i0 + 1; i++) own += clear(i, j, k);
|
|
863
|
+
}
|
|
864
|
+
hit += own;
|
|
865
|
+
}
|
|
866
|
+
cleared += hit;
|
|
867
|
+
if (!hit) break;
|
|
868
|
+
best = draw(fine.grid, fine.density, fine.keep, iso);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
|
|
872
|
+
let { vertices, faces, dropped } = anchored(best, anchors, (fine ?? { grid: spec.grid }).grid.h),
|
|
873
|
+
reduced = null;
|
|
874
|
+
// Fewer triangles, if asked: within outline.reduce mm of the surface as drawn, closed, and no more overhang or tips
|
|
875
|
+
if (r.outline.reduce != null) {
|
|
876
|
+
const { nx, ny, nz, h } = spec.grid,
|
|
877
|
+
lo = spec.origin,
|
|
878
|
+
hi = [lo[0] + nx * h, lo[1] + ny * h, lo[2] + nz * h],
|
|
879
|
+
before = faces.length;
|
|
880
|
+
({ vertices, faces } = reduce(
|
|
881
|
+
{ vertices, faces },
|
|
882
|
+
{ tolerance: r.outline.reduce, lo, hi, ...(ov ? { overhang: { up: ov.up, angle: ov.angle } } : {}) },
|
|
883
|
+
));
|
|
884
|
+
reduced = { before, after: faces.length, tolerance: r.outline.reduce };
|
|
885
|
+
}
|
|
886
|
+
return {
|
|
887
|
+
mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces },
|
|
888
|
+
solid: meshVolume(vertices, faces),
|
|
889
|
+
iso,
|
|
890
|
+
...(reduced ? { reduced } : {}),
|
|
891
|
+
...(dropped.length ? { dropped } : {}),
|
|
892
|
+
...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}),
|
|
893
|
+
...(cleared ? { cleared } : {}),
|
|
894
|
+
};
|
|
895
|
+
})();
|
|
438
896
|
const result = {
|
|
439
|
-
problem: ref,
|
|
440
|
-
|
|
897
|
+
problem: ref,
|
|
898
|
+
title: r.title,
|
|
899
|
+
hash,
|
|
900
|
+
dim: r.dim,
|
|
901
|
+
material: r.material.name,
|
|
902
|
+
...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
|
|
903
|
+
grid: spec.grid,
|
|
904
|
+
origin: spec.origin,
|
|
905
|
+
regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) },
|
|
906
|
+
...shape,
|
|
441
907
|
...made(r, spec, o.density),
|
|
442
|
-
volume: o.volume,
|
|
443
|
-
|
|
444
|
-
|
|
908
|
+
volume: o.volume,
|
|
909
|
+
compliance: o.compliance,
|
|
910
|
+
cases: o.cases,
|
|
911
|
+
...(o.unsupported ? { unsupported: o.unsupported } : {}),
|
|
912
|
+
...(o.mechanism ? { mechanism: o.mechanism } : {}),
|
|
913
|
+
...(o.stress ? { stress: o.stress } : {}),
|
|
914
|
+
overhang: r.problem.overhang || null,
|
|
915
|
+
steps: o.steps,
|
|
916
|
+
converged: o.converged,
|
|
917
|
+
seconds: o.seconds,
|
|
918
|
+
history: o.history,
|
|
919
|
+
density: Array.from(o.density, (d) => round(d, 3)),
|
|
920
|
+
supports: named(r.problem.supports),
|
|
921
|
+
loads: named(r.problem.loads),
|
|
445
922
|
};
|
|
446
923
|
host.writeText(file, JSON.stringify(result));
|
|
447
924
|
return result;
|
|
@@ -450,10 +927,25 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
|
|
|
450
927
|
// A closed mesh's volume (mm³), by the divergence theorem
|
|
451
928
|
function meshVolume(vertices, faces) {
|
|
452
929
|
let v = 0;
|
|
453
|
-
for (const [i, j, k] of faces) {
|
|
930
|
+
for (const [i, j, k] of faces) {
|
|
931
|
+
const a = vertices[i],
|
|
932
|
+
b = vertices[j],
|
|
933
|
+
c = vertices[k];
|
|
934
|
+
v +=
|
|
935
|
+
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) /
|
|
936
|
+
6;
|
|
937
|
+
}
|
|
454
938
|
return v;
|
|
455
939
|
}
|
|
456
940
|
|
|
941
|
+
// Where a flat problem's region is, to draw its mark and to sum a case's loads about: its place, or a polygon's (which
|
|
942
|
+
// has none) the middle of its box
|
|
943
|
+
const placeOf = (r) => {
|
|
944
|
+
if (r.at) return r.at;
|
|
945
|
+
const b = bounds(r);
|
|
946
|
+
return [(b[0] + b[2]) / 2, (b[1] + b[3]) / 2];
|
|
947
|
+
};
|
|
948
|
+
|
|
457
949
|
// What a design gets as v.problems[name]: the outlines and regions to build from, and the numbers to report
|
|
458
950
|
export const forDesign = ({ density, history, ...r }) => r;
|
|
459
951
|
|
|
@@ -466,68 +958,202 @@ export const forDesign = ({ density, history, ...r }) => r;
|
|
|
466
958
|
* @param {{ cell?: number }} [options] cell: a finer cell size than the problem's, to check a final shape
|
|
467
959
|
*/
|
|
468
960
|
export async function analysePart(triangles, project, ref, { cell } = {}) {
|
|
469
|
-
const r = await readProblem(project, ref),
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
961
|
+
const r = await readProblem(project, ref),
|
|
962
|
+
{ problem } = r,
|
|
963
|
+
h = cell || problem.cell;
|
|
964
|
+
if (r.dim === 3) {
|
|
965
|
+
// kept: a fine analysis of a solid takes minutes
|
|
966
|
+
const file = paths.cache(
|
|
967
|
+
'analysis',
|
|
968
|
+
`${crypto
|
|
969
|
+
.createHash('sha256')
|
|
970
|
+
.update(
|
|
971
|
+
JSON.stringify([
|
|
972
|
+
VERSION,
|
|
973
|
+
triangles,
|
|
974
|
+
problem,
|
|
975
|
+
h,
|
|
976
|
+
source('@rulecad/topopt'),
|
|
977
|
+
source('@rulecad/fea'),
|
|
978
|
+
fs.readFileSync(new URL(import.meta.url), 'utf8'),
|
|
979
|
+
]),
|
|
980
|
+
)
|
|
981
|
+
.digest('hex')}.json`,
|
|
982
|
+
);
|
|
983
|
+
if (!process.env.CAD_NO_CACHE && cached(file)) {
|
|
984
|
+
const { density, ...x } = JSON.parse(host.readText(file));
|
|
985
|
+
return { ...x, density: Float64Array.from(density) };
|
|
986
|
+
}
|
|
473
987
|
const out = analyseSolid(triangles, r, h);
|
|
474
988
|
host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
|
|
475
989
|
return out;
|
|
476
990
|
}
|
|
477
991
|
// The grid covers the part and the problem's space
|
|
478
|
-
let x0 = Infinity,
|
|
479
|
-
|
|
480
|
-
|
|
992
|
+
let x0 = Infinity,
|
|
993
|
+
y0 = Infinity,
|
|
994
|
+
x1 = -Infinity,
|
|
995
|
+
y1 = -Infinity;
|
|
996
|
+
for (const t of triangles)
|
|
997
|
+
for (const [x, y] of t) {
|
|
998
|
+
x0 = Math.min(x0, x);
|
|
999
|
+
y0 = Math.min(y0, y);
|
|
1000
|
+
x1 = Math.max(x1, x);
|
|
1001
|
+
y1 = Math.max(y1, y);
|
|
1002
|
+
}
|
|
1003
|
+
const nx = Math.max(1, Math.ceil((x1 - x0) / h)),
|
|
1004
|
+
ny = Math.max(1, Math.ceil((y1 - y0) / h));
|
|
481
1005
|
const density = fill(triangles, { nx, ny, h, origin: [x0, y0] }, problem.thickness);
|
|
482
|
-
const g = makeGrid({ nx, ny, h }),
|
|
483
|
-
|
|
1006
|
+
const g = makeGrid({ nx, ny, h }),
|
|
1007
|
+
at = positions(g).map(([x, y]) => [x + x0, y + y0]);
|
|
1008
|
+
// Supports and loads on the nodes of the part inside their regions, read as topopt's discretise reads them for cad
|
|
1009
|
+
// optimise: a box (size) or a point and radius grown by three quarters of a cell, a polygon (points) or another
|
|
1010
|
+
// design's part (its section halfway up) as drawn. (Once a point and a radius only: a box clamping an edge became
|
|
1011
|
+
// one point there and the plate came out nine times too soft, and a polygon crashed the check.)
|
|
484
1012
|
const onPart = new Uint8Array(g.nodes);
|
|
485
|
-
for (let e = 0; e < density.length; e++)
|
|
486
|
-
|
|
1013
|
+
for (let e = 0; e < density.length; e++)
|
|
1014
|
+
if (density[e] >= 0.5) for (let k = 0; k < 4; k++) onPart[g.edof[e * 8 + 2 * k] / 2] = 1;
|
|
1015
|
+
const near = (zone, what) => {
|
|
1016
|
+
const d = h * 0.75,
|
|
1017
|
+
grown =
|
|
1018
|
+
zone.points || zone.triangles
|
|
1019
|
+
? zone
|
|
1020
|
+
: zone.size
|
|
1021
|
+
? { ...zone, size: zone.size.map((s) => s + 2 * d) }
|
|
1022
|
+
: { ...zone, r: (zone.r || 0) + d };
|
|
487
1023
|
const found = [];
|
|
488
|
-
for (let n = 0; n < g.nodes; n++) if (onPart[n] &&
|
|
489
|
-
if (!found.length)
|
|
1024
|
+
for (let n = 0; n < g.nodes; n++) if (onPart[n] && inside(grown, at[n])) found.push(n);
|
|
1025
|
+
if (!found.length)
|
|
1026
|
+
throw new Error(
|
|
1027
|
+
`${what}${zone.at ? ` at ${zone.at.join(', ')}` : ''} isn't on the part: is it placed as the problem expects?`,
|
|
1028
|
+
);
|
|
490
1029
|
return found;
|
|
491
1030
|
};
|
|
492
1031
|
const fixed = new Uint8Array(g.dofs);
|
|
493
|
-
for (const s of problem.supports)
|
|
1032
|
+
for (const s of problem.supports)
|
|
1033
|
+
for (const n of near(s, 'a support')) {
|
|
1034
|
+
if (s.fix.includes('x')) fixed[2 * n] = 1;
|
|
1035
|
+
if (s.fix.includes('y')) fixed[2 * n + 1] = 1;
|
|
1036
|
+
}
|
|
494
1037
|
const names = [...new Set(problem.loads.map((l) => l.case))];
|
|
495
1038
|
const loads = names.map((name) => {
|
|
496
1039
|
const f = new Float64Array(g.dofs);
|
|
497
|
-
for (const l of problem.loads.filter((x) => x.case === name)) {
|
|
1040
|
+
for (const l of problem.loads.filter((x) => x.case === name)) {
|
|
1041
|
+
const ns = near(l, `the load "${name}"`);
|
|
1042
|
+
for (const n of ns) {
|
|
1043
|
+
f[2 * n] += l.force[0] / ns.length;
|
|
1044
|
+
f[2 * n + 1] += l.force[1] / ns.length;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
498
1047
|
return f;
|
|
499
1048
|
});
|
|
500
1049
|
const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
|
|
501
1050
|
const cases = names.map((name, c) => {
|
|
502
|
-
const { size, moment } = resultant(
|
|
1051
|
+
const { size, moment } = resultant(
|
|
1052
|
+
problem.loads.filter((l) => l.case === name).map((l) => ({ ...l, at: placeOf(l) })),
|
|
1053
|
+
);
|
|
503
1054
|
return measures(name, size, moment, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
|
|
504
1055
|
});
|
|
505
|
-
return {
|
|
1056
|
+
return {
|
|
1057
|
+
problem: ref,
|
|
1058
|
+
dim: 2,
|
|
1059
|
+
material: r.material,
|
|
1060
|
+
critical: r.critical,
|
|
1061
|
+
cases,
|
|
1062
|
+
thin: a.thin,
|
|
1063
|
+
volume: volume(triangles),
|
|
1064
|
+
grid: { nx, ny, h },
|
|
1065
|
+
origin: [x0, y0],
|
|
1066
|
+
density,
|
|
1067
|
+
};
|
|
506
1068
|
}
|
|
507
1069
|
|
|
508
1070
|
// A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
|
|
509
1071
|
// supports and loads land on it as they would on an optimised layout
|
|
510
1072
|
function analyseSolid(triangles, r, cell) {
|
|
511
|
-
const { problem } = r,
|
|
512
|
-
|
|
1073
|
+
const { problem } = r,
|
|
1074
|
+
spec = discretise({ ...problem, cell, space: { triangles }, keep: [], avoid: [], volume: 1 });
|
|
1075
|
+
const g = makeGrid(spec.grid),
|
|
1076
|
+
density = solidFill(triangles, spec.grid, spec.origin);
|
|
513
1077
|
if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
|
|
514
|
-
const a = analyse({
|
|
1078
|
+
const a = analyse({
|
|
1079
|
+
grid: g,
|
|
1080
|
+
density,
|
|
1081
|
+
material: problem.material,
|
|
1082
|
+
fixed: spec.fixed,
|
|
1083
|
+
loads: spec.loads.map((l) => l.force),
|
|
1084
|
+
backend: threadsBackend,
|
|
1085
|
+
});
|
|
515
1086
|
const cases = spec.loads.map((l, c) => measures(l.name, l.size, l.moment, a, c, density, spec.grid, spec.origin));
|
|
516
|
-
return {
|
|
1087
|
+
return {
|
|
1088
|
+
problem: r.ref,
|
|
1089
|
+
dim: 3,
|
|
1090
|
+
material: r.material,
|
|
1091
|
+
critical: r.critical,
|
|
1092
|
+
cases,
|
|
1093
|
+
thin: a.thin,
|
|
1094
|
+
volume: volume(triangles),
|
|
1095
|
+
grid: spec.grid,
|
|
1096
|
+
origin: spec.origin,
|
|
1097
|
+
density,
|
|
1098
|
+
};
|
|
517
1099
|
}
|
|
518
1100
|
|
|
519
1101
|
// A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness (a twist: the
|
|
520
1102
|
// angle it turns, compliance over its moment, and the torsion, N·mm a radian), the largest
|
|
521
|
-
// stress in the part and the centre of the cell it's in, and the largest movement of any point of the part and where
|
|
1103
|
+
// stress in the part and the centre of the cell it's in, and the largest movement of any point of the part and where.
|
|
1104
|
+
// The stress is fea's surface stress (analyse().surface): read at the cells' centres, half a cell inside the part, a
|
|
1105
|
+
// bending part's peak reads 10 to 30% low on the cells a part is usually analysed on, and min_safety passed parts
|
|
1106
|
+
// that beam theory fails
|
|
522
1107
|
function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
|
|
523
|
-
const deflection = force ? a.compliance[c] / force : 0,
|
|
524
|
-
|
|
525
|
-
|
|
1108
|
+
const deflection = force ? a.compliance[c] / force : 0,
|
|
1109
|
+
angle = moment ? a.compliance[c] / moment : 0;
|
|
1110
|
+
let most = 0,
|
|
1111
|
+
cellAt = 0;
|
|
1112
|
+
for (let e = 0; e < density.length; e++)
|
|
1113
|
+
if (density[e] >= 0.5 && a.surface[c][e] > most) {
|
|
1114
|
+
most = a.surface[c][e];
|
|
1115
|
+
cellAt = e;
|
|
1116
|
+
}
|
|
526
1117
|
const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
|
|
527
|
-
const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)),
|
|
1118
|
+
const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)),
|
|
1119
|
+
d = a.deflection[c];
|
|
528
1120
|
return {
|
|
529
|
-
name,
|
|
530
|
-
|
|
1121
|
+
name,
|
|
1122
|
+
...(moment
|
|
1123
|
+
? { moment, angle, torsion: moment / angle }
|
|
1124
|
+
: { force, deflection, stiffness: deflection ? force / deflection : Infinity }),
|
|
1125
|
+
stress: most,
|
|
1126
|
+
stressAt,
|
|
1127
|
+
movement: d.most,
|
|
1128
|
+
movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/**
|
|
1133
|
+
* The check of an analysis's check (fea.settled): how much a load case's stiffness and peak stress moved on cells a
|
|
1134
|
+
* quarter bigger. It settles when the stiffness moves 5% or less; when the part is held to a safety factor
|
|
1135
|
+
* (min_safety), the peak stress must too, as the cells can be fine enough for the stiffness while the stress still reads
|
|
1136
|
+
* low. A peak stress at a sharp inside corner, or beside a support or load held at a few points, keeps rising as the
|
|
1137
|
+
* cells shrink (there it has no limit in theory): a fillet, or the hold spread over the face it acts on, is the answer.
|
|
1138
|
+
* @param {string} problem the problem's name @param {string} name the load case's
|
|
1139
|
+
* @param {{ stiffness: number, stress: number, cell: number }} change each as a fraction (0.05 is 5%), cell the coarser cells' size
|
|
1140
|
+
* @param {boolean} strength whether the peak stress is judged too (min_safety was given)
|
|
1141
|
+
* @returns {{ level: 'pass' | 'warn', code: 'fea.settled', values: { stiffness: number, stress: number, cell: number }, text: string }}
|
|
1142
|
+
*/
|
|
1143
|
+
export function settledFinding(problem, name, change, strength) {
|
|
1144
|
+
const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`,
|
|
1145
|
+
stiff = Math.abs(change.stiffness) <= 0.05,
|
|
1146
|
+
strong = !strength || Math.abs(change.stress) <= 0.05,
|
|
1147
|
+
ok = stiff && strong;
|
|
1148
|
+
return {
|
|
1149
|
+
level: ok ? 'pass' : 'warn',
|
|
1150
|
+
code: 'fea.settled',
|
|
1151
|
+
values: { stiffness: change.stiffness, stress: change.stress, cell: change.cell },
|
|
1152
|
+
text: `${problem} ${name}: stiffness ${pct(change.stiffness)} from ${fmt(change.cell)} mm cells, peak stress ${pct(change.stress)}${
|
|
1153
|
+
ok
|
|
1154
|
+
? `, settled (${strength ? 'both' : 'the stiffness'} within 5%)`
|
|
1155
|
+
: `: not settled, use a smaller cell${strong ? '' : ' (a peak stress that keeps rising as the cells shrink is where stress concentrates: at a sharp inside corner, round it; at a support or load on a few points, spread it over the face it acts on)'}`
|
|
1156
|
+
}`,
|
|
531
1157
|
};
|
|
532
1158
|
}
|
|
533
1159
|
|
|
@@ -536,32 +1162,47 @@ function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
|
|
|
536
1162
|
// through each column of cubes, n × n of them (exact up the column, to within half their spacing across it); each enters the part through a face facing down and leaves through
|
|
537
1163
|
// one facing up, and the lengths inside each cube are averaged.
|
|
538
1164
|
export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
|
|
539
|
-
const R = nx * n,
|
|
1165
|
+
const R = nx * n,
|
|
1166
|
+
hits = Array.from({ length: R * ny * n }, () => []),
|
|
1167
|
+
jx = h * 1e-4 * Math.SQRT2,
|
|
1168
|
+
jy = h * 1e-4 * Math.PI;
|
|
540
1169
|
for (const [a, b, c] of triangles) {
|
|
541
1170
|
const d = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
542
1171
|
if (Math.abs(d) < 1e-12) continue; // a wall: the ray runs alongside it
|
|
543
|
-
const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)),
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
1172
|
+
const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)),
|
|
1173
|
+
i1 = Math.min(R - 1, Math.ceil(((Math.max(a[0], b[0], c[0]) - origin[0]) / h) * n));
|
|
1174
|
+
const j0 = Math.max(0, Math.floor(((Math.min(a[1], b[1], c[1]) - origin[1]) / h) * n - 1)),
|
|
1175
|
+
j1 = Math.min(ny * n - 1, Math.ceil(((Math.max(a[1], b[1], c[1]) - origin[1]) / h) * n));
|
|
1176
|
+
for (let j = j0; j <= j1; j++)
|
|
1177
|
+
for (let i = i0; i <= i1; i++) {
|
|
1178
|
+
const x = origin[0] + ((i + 0.5) / n) * h + jx,
|
|
1179
|
+
y = origin[1] + ((j + 0.5) / n) * h + jy;
|
|
1180
|
+
const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / d,
|
|
1181
|
+
w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / d,
|
|
1182
|
+
w2 = 1 - w0 - w1;
|
|
1183
|
+
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
|
|
1184
|
+
hits[j * R + i].push([w0 * a[2] + w1 * b[2] + w2 * c[2], Math.sign(d)]);
|
|
1185
|
+
}
|
|
551
1186
|
}
|
|
552
|
-
const density = new Float64Array(nx * ny * nz),
|
|
1187
|
+
const density = new Float64Array(nx * ny * nz),
|
|
1188
|
+
share = 1 / (n * n * h);
|
|
553
1189
|
hits.forEach((list, ray) => {
|
|
554
1190
|
if (!list.length) return;
|
|
555
1191
|
list.sort((p, q) => p[0] - q[0]);
|
|
556
|
-
const ci = Math.floor((ray % R) / n),
|
|
557
|
-
|
|
1192
|
+
const ci = Math.floor((ray % R) / n),
|
|
1193
|
+
cj = Math.floor(Math.floor(ray / R) / n);
|
|
1194
|
+
let depth = 0,
|
|
1195
|
+
from = 0;
|
|
558
1196
|
for (const [z, sign] of list) {
|
|
559
|
-
const was = depth;
|
|
1197
|
+
const was = depth;
|
|
1198
|
+
depth -= sign; // a face facing down (its normal's z below 0, counter-clockwise from above: sign -1) is the way in
|
|
560
1199
|
if (was <= 0 && depth > 0) from = z;
|
|
561
|
-
else if (was > 0 && depth <= 0)
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
1200
|
+
else if (was > 0 && depth <= 0)
|
|
1201
|
+
for (let k = Math.max(0, Math.floor((from - origin[2]) / h)); k < nz && origin[2] + k * h < z; k++) {
|
|
1202
|
+
const lo = Math.max(from, origin[2] + k * h),
|
|
1203
|
+
hi = Math.min(z, origin[2] + (k + 1) * h);
|
|
1204
|
+
if (hi > lo) density[(k * ny + cj) * nx + ci] += (hi - lo) * share;
|
|
1205
|
+
}
|
|
565
1206
|
}
|
|
566
1207
|
});
|
|
567
1208
|
return density.map((x) => Math.min(1, x));
|
|
@@ -571,19 +1212,28 @@ export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
|
|
|
571
1212
|
// through faces that face down and leaves through faces that face up, so the filled length is the sum of the up
|
|
572
1213
|
// faces' heights there less the down faces'
|
|
573
1214
|
function fill(triangles, { nx, ny, h, origin }, thickness) {
|
|
574
|
-
const length = new Float64Array(nx * ny),
|
|
1215
|
+
const length = new Float64Array(nx * ny),
|
|
1216
|
+
jx = h * 1e-4 * Math.SQRT2,
|
|
1217
|
+
jy = h * 1e-4 * Math.PI; // off-centre, so no ray meets an edge exactly
|
|
575
1218
|
for (const [a, b, c] of triangles) {
|
|
576
1219
|
const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
577
1220
|
if (Math.abs(nz) < 1e-12) continue; // a wall: the ray runs alongside it
|
|
578
|
-
const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])],
|
|
579
|
-
|
|
580
|
-
const
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
1221
|
+
const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])],
|
|
1222
|
+
hi = [Math.max(a[0], b[0], c[0]), Math.max(a[1], b[1], c[1])];
|
|
1223
|
+
const i0 = Math.max(0, Math.floor((lo[0] - origin[0]) / h)),
|
|
1224
|
+
i1 = Math.min(nx - 1, Math.ceil((hi[0] - origin[0]) / h));
|
|
1225
|
+
const j0 = Math.max(0, Math.floor((lo[1] - origin[1]) / h)),
|
|
1226
|
+
j1 = Math.min(ny - 1, Math.ceil((hi[1] - origin[1]) / h));
|
|
1227
|
+
for (let j = j0; j <= j1; j++)
|
|
1228
|
+
for (let i = i0; i <= i1; i++) {
|
|
1229
|
+
const x = origin[0] + (i + 0.5) * h + jx,
|
|
1230
|
+
y = origin[1] + (j + 0.5) * h + jy;
|
|
1231
|
+
const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / nz,
|
|
1232
|
+
w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / nz,
|
|
1233
|
+
w2 = 1 - w0 - w1;
|
|
1234
|
+
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
|
|
1235
|
+
length[j * nx + i] += Math.sign(nz) * (w0 * a[2] + w1 * b[2] + w2 * c[2]);
|
|
1236
|
+
}
|
|
587
1237
|
}
|
|
588
1238
|
return length.map((l) => Math.min(1, Math.max(0, l / thickness)));
|
|
589
1239
|
}
|
|
@@ -591,7 +1241,10 @@ function fill(triangles, { nx, ny, h, origin }, thickness) {
|
|
|
591
1241
|
// A closed mesh's volume (mm³), by the divergence theorem
|
|
592
1242
|
function volume(triangles) {
|
|
593
1243
|
let v = 0;
|
|
594
|
-
for (const [a, b, c] of triangles)
|
|
1244
|
+
for (const [a, b, c] of triangles)
|
|
1245
|
+
v +=
|
|
1246
|
+
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) /
|
|
1247
|
+
6;
|
|
595
1248
|
return Math.abs(v);
|
|
596
1249
|
}
|
|
597
1250
|
|
|
@@ -604,21 +1257,39 @@ const round = (n, d = 4) => Number(n.toFixed(d));
|
|
|
604
1257
|
* @param {{ title?: string, lines?: string[] }} [label]
|
|
605
1258
|
*/
|
|
606
1259
|
export function picture(r, { title = '', lines = [] } = {}) {
|
|
607
|
-
const { nx, ny, h } = r.grid,
|
|
608
|
-
|
|
609
|
-
|
|
1260
|
+
const { nx, ny, h } = r.grid,
|
|
1261
|
+
s = Math.max(2, Math.min(8, Math.floor(1100 / (nx * h)))),
|
|
1262
|
+
pad = 24,
|
|
1263
|
+
top = 30 + lines.length * 16;
|
|
1264
|
+
const W = nx * h * s + 2 * pad,
|
|
1265
|
+
H = ny * h * s + pad + top + 12;
|
|
1266
|
+
const X = (x) => pad + (x - r.origin[0]) * s,
|
|
1267
|
+
Y = (y) => top + (ny * h - (y - r.origin[1])) * s;
|
|
610
1268
|
const cells = [];
|
|
611
|
-
for (let j = 0; j < ny; j++)
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1269
|
+
for (let j = 0; j < ny; j++)
|
|
1270
|
+
for (let i = 0; i < nx; i++) {
|
|
1271
|
+
const d = r.density[j * nx + i];
|
|
1272
|
+
if (d > 0.02)
|
|
1273
|
+
cells.push(
|
|
1274
|
+
`<rect x="${X(r.origin[0] + i * h).toFixed(1)}" y="${Y(r.origin[1] + (j + 1) * h).toFixed(1)}" width="${(h * s + 0.3).toFixed(1)}" height="${(h * s + 0.3).toFixed(1)}" fill-opacity="${d.toFixed(2)}"/>`,
|
|
1275
|
+
);
|
|
1276
|
+
}
|
|
1277
|
+
const loops = (r.outlines || []).map(
|
|
1278
|
+
(l) => `<path d="M${l.map(([x, y]) => `${X(x).toFixed(1)},${Y(y).toFixed(1)}`).join('L')}Z"/>`,
|
|
1279
|
+
);
|
|
1280
|
+
const supports = (r.supports || []).map((p) => `<path d="M${X(placeOf(p)[0])},${Y(placeOf(p)[1])}l-6,10h12z"/>`);
|
|
617
1281
|
const loads = (r.loads || []).map((l) => {
|
|
618
|
-
const len = Math.hypot(...l.force) || 1,
|
|
1282
|
+
const len = Math.hypot(...l.force) || 1,
|
|
1283
|
+
dx = (l.force[0] / len) * 30,
|
|
1284
|
+
dy = (-l.force[1] / len) * 30,
|
|
1285
|
+
x = X(placeOf(l)[0]),
|
|
1286
|
+
y = Y(placeOf(l)[1]);
|
|
619
1287
|
return `<path d="M${x - dx},${y - dy}L${x},${y}"/><circle cx="${x}" cy="${y}" r="3"/>`;
|
|
620
1288
|
});
|
|
621
|
-
const text = [title, ...lines].map(
|
|
1289
|
+
const text = [title, ...lines].map(
|
|
1290
|
+
(t, i) =>
|
|
1291
|
+
`<text x="${pad}" y="${20 + i * 16}" font-size="${i ? 12 : 14}"${i ? '' : ' font-weight="600"'}>${t.replace(/&/g, '&').replace(/</g, '<')}</text>`,
|
|
1292
|
+
);
|
|
622
1293
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="system-ui, sans-serif">
|
|
623
1294
|
<rect width="100%" height="100%" fill="#fff"/>${text.join('')}
|
|
624
1295
|
<g fill="#2b4c7e">${cells.join('')}</g>
|
|
@@ -633,21 +1304,45 @@ export function picture(r, { title = '', lines = [] } = {}) {
|
|
|
633
1304
|
// print as a stray bit. Only pieces touching a support, a load or a kept region (within a cell) stay; the volumes of
|
|
634
1305
|
// the rest, mm³, come back as dropped.
|
|
635
1306
|
export function anchored({ vertices, faces }, anchors, h) {
|
|
636
|
-
const up = vertices.map((_, i) => i),
|
|
637
|
-
|
|
1307
|
+
const up = vertices.map((_, i) => i),
|
|
1308
|
+
find = (i) => {
|
|
1309
|
+
while (up[i] !== i) i = up[i] = up[up[i]];
|
|
1310
|
+
return i;
|
|
1311
|
+
};
|
|
1312
|
+
for (const [a, b, c] of faces) {
|
|
1313
|
+
up[find(a)] = find(b);
|
|
1314
|
+
up[find(b)] = find(c);
|
|
1315
|
+
}
|
|
638
1316
|
const pieces = new Map();
|
|
639
1317
|
for (const f of faces) {
|
|
640
|
-
const r = find(f[0]),
|
|
1318
|
+
const r = find(f[0]),
|
|
1319
|
+
p = pieces.get(r) ?? { faces: [], lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] };
|
|
641
1320
|
p.faces.push(f);
|
|
642
|
-
for (const v of f)
|
|
1321
|
+
for (const v of f)
|
|
1322
|
+
for (let k = 0; k < 3; k++) {
|
|
1323
|
+
p.lo[k] = Math.min(p.lo[k], vertices[v][k]);
|
|
1324
|
+
p.hi[k] = Math.max(p.hi[k], vertices[v][k]);
|
|
1325
|
+
}
|
|
643
1326
|
pieces.set(r, p);
|
|
644
1327
|
}
|
|
645
1328
|
if (pieces.size < 2) return { vertices, faces, dropped: [] };
|
|
646
1329
|
const touches = (p) => anchors.some((b) => [0, 1, 2].every((k) => p.lo[k] <= b[3 + k] + h && p.hi[k] >= b[k] - h));
|
|
647
|
-
const kept = [],
|
|
1330
|
+
const kept = [],
|
|
1331
|
+
dropped = [];
|
|
648
1332
|
for (const p of pieces.values()) (touches(p) ? kept : dropped).push(p);
|
|
649
1333
|
if (!kept.length) return { vertices, faces, dropped: [] }; // nothing anchored: keep it all rather than nothing
|
|
650
|
-
const index = new Map(),
|
|
651
|
-
|
|
1334
|
+
const index = new Map(),
|
|
1335
|
+
out = [];
|
|
1336
|
+
const keptFaces = kept
|
|
1337
|
+
.flatMap((p) => p.faces)
|
|
1338
|
+
.map((f) =>
|
|
1339
|
+
f.map((v) => {
|
|
1340
|
+
if (!index.has(v)) {
|
|
1341
|
+
index.set(v, out.length);
|
|
1342
|
+
out.push(vertices[v]);
|
|
1343
|
+
}
|
|
1344
|
+
return index.get(v);
|
|
1345
|
+
}),
|
|
1346
|
+
);
|
|
652
1347
|
return { vertices: out, faces: keptFaces, dropped: dropped.map((p) => round(meshVolume(vertices, p.faces), 3)) };
|
|
653
1348
|
}
|