@rulecad/cad 0.7.97 → 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 +26 -10
- package/CHANGELOG.md +442 -2
- package/EXAMPLES.md +48 -42
- package/README.md +226 -73
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2253 -514
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1854 -437
- 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 +734 -113
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +900 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2710 -502
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +792 -176
- 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 +149 -18
- 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 +3 -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 +1022 -212
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +41 -0
- package/lib/optimise.mjs +979 -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 +224 -36
- 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 +38 -4
- package/lib/sandbox-hooks.mjs +154 -12
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +127 -12
- package/lib/sandbox.mjs +632 -35
- package/lib/schema.mjs +43 -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 +42 -6
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +113 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +216 -17
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
- package/schemas/object.schema.json +1 -1
- package/schemas/project.schema.json +1 -1
package/lib/optimise.mjs
CHANGED
|
@@ -8,19 +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';
|
|
13
|
-
import {
|
|
11
|
+
import { host, readJson, cached } from './host.mjs';
|
|
12
|
+
import { paths, printerOf, noLinksOut } from './workspace.mjs';
|
|
13
|
+
import { plainName } from './names.mjs';
|
|
14
|
+
import { resolve, evaluate, fmt } from './rules.mjs';
|
|
14
15
|
import { located } from './errors.mjs';
|
|
15
|
-
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';
|
|
16
35
|
import { islands } from '@rulecad/printcheck';
|
|
17
36
|
import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
|
|
18
37
|
import { section, loops, slabLevels } from './mesh.mjs';
|
|
19
38
|
import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
|
|
20
39
|
import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
|
|
21
40
|
|
|
22
|
-
const VERSION = 2,
|
|
23
|
-
|
|
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 ../)
|
|
24
45
|
export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
|
|
25
46
|
|
|
26
47
|
/**
|
|
@@ -30,10 +51,15 @@ export const hasProblem = (project, ref) => host.exists(problemFile(project, Str
|
|
|
30
51
|
export async function readProblem(project, ref) {
|
|
31
52
|
// The problems being read above this one, each with the design it reads that is built from the next: a problem met
|
|
32
53
|
// again on that chain is refused by name, since each would need the other's result before its own could be made
|
|
33
|
-
const name = String(ref).split(':')[0],
|
|
54
|
+
const name = String(ref).split(':')[0],
|
|
55
|
+
chain = reading.getStore() || [],
|
|
56
|
+
key = `${project}/${name}`;
|
|
34
57
|
if (chain.some((c) => c.key === key)) {
|
|
35
|
-
const from = chain.slice(chain.findIndex((c) => c.key === key)),
|
|
36
|
-
|
|
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
|
+
);
|
|
37
63
|
}
|
|
38
64
|
const link = { key, name, object: null };
|
|
39
65
|
return reading.run([...chain, link], () => readOne(project, ref, link));
|
|
@@ -46,39 +72,67 @@ export async function readProblem(project, ref) {
|
|
|
46
72
|
const REDUCE = 0.1;
|
|
47
73
|
const reading = new AsyncLocalStorage();
|
|
48
74
|
async function readOne(project, ref, link) {
|
|
49
|
-
const [name, variant] = String(ref).split(':'),
|
|
75
|
+
const [name, variant] = String(ref).split(':'),
|
|
76
|
+
file = problemFile(project, name);
|
|
50
77
|
if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
|
|
51
78
|
const p = readJson(file);
|
|
52
|
-
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
|
+
);
|
|
53
83
|
const uses = [...new Set([...(p.uses || []), p.material])];
|
|
54
84
|
let values;
|
|
55
|
-
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
|
+
}
|
|
56
90
|
const lookup = (n) => {
|
|
57
91
|
const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), values);
|
|
58
|
-
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
|
+
);
|
|
59
96
|
return v;
|
|
60
97
|
};
|
|
61
|
-
const ev = (x) => evaluate(x, lookup),
|
|
98
|
+
const ev = (x) => evaluate(x, lookup),
|
|
99
|
+
pt = (a) => a.map(ev),
|
|
100
|
+
flat = p.thickness != null;
|
|
62
101
|
// Another design in the project, built once with its defaults, for its parts and anchors. One whose default is built
|
|
63
102
|
// from this very problem is refused: it would need the result before the result could be made.
|
|
64
103
|
const designs = new Map();
|
|
65
|
-
const design = (object, what) => {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
+
);
|
|
73
123
|
return designs.get(object);
|
|
74
124
|
};
|
|
75
125
|
// A named part of another design in the project, as triangles (built with its defaults)
|
|
76
126
|
const parts = new Map();
|
|
77
127
|
const part = async (ref) => {
|
|
78
128
|
if (!parts.has(ref)) {
|
|
79
|
-
const [object, partName] = ref.split('.'),
|
|
129
|
+
const [object, partName] = ref.split('.'),
|
|
130
|
+
b = await design(object, `the part "${ref}"`);
|
|
80
131
|
const found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
|
|
81
|
-
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
|
+
);
|
|
82
136
|
parts.set(ref, found.triangles);
|
|
83
137
|
}
|
|
84
138
|
return parts.get(ref);
|
|
@@ -89,16 +143,26 @@ async function readOne(project, ref, link) {
|
|
|
89
143
|
const anchor = async (ref) => {
|
|
90
144
|
if (!anchors.has(ref)) {
|
|
91
145
|
const [object, a, ...more] = String(ref).split('.');
|
|
92
|
-
if (!object || !a || more.length)
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
+
});
|
|
100
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
|
|
101
|
-
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);
|
|
102
166
|
anchors.set(ref, { anchor: ref, at: (spec.at || [0, 0, 0]).map(num), axis });
|
|
103
167
|
}
|
|
104
168
|
return anchors.get(ref);
|
|
@@ -110,31 +174,57 @@ async function readOne(project, ref, link) {
|
|
|
110
174
|
const fileName = path.basename(file);
|
|
111
175
|
let placing = null;
|
|
112
176
|
const inAssembly = (what) => {
|
|
113
|
-
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
|
+
);
|
|
114
181
|
return (placing ||= (async () => {
|
|
115
|
-
const { buildAssembly, assemblyPath } = await import('./assembly.mjs'),
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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
|
+
}
|
|
123
202
|
const chain = reading.getStore();
|
|
124
|
-
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
|
+
);
|
|
125
206
|
const k = s.motion.items.findIndex((x) => x[0] === p.in.item);
|
|
126
|
-
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
|
+
);
|
|
127
211
|
return { s, k, W0: placeItems(s.motion, s.jointValues) };
|
|
128
212
|
})());
|
|
129
213
|
};
|
|
130
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
|
|
131
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.
|
|
132
|
-
const joints = new Map(),
|
|
216
|
+
const joints = new Map(),
|
|
217
|
+
clean = (c) => (Math.abs(c) < 1e-9 ? 0 : round(c, 9));
|
|
133
218
|
const jointAt = async (id) => {
|
|
134
219
|
if (!joints.has(id)) {
|
|
135
|
-
const { s, k, W0 } = await inAssembly(`the joint "${id}"`),
|
|
136
|
-
|
|
137
|
-
|
|
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));
|
|
138
228
|
joints.set(id, { joint: id, at: [F[3], F[7], F[11]].map(clean), axis: [F[2], F[6], F[10]].map(clean) });
|
|
139
229
|
}
|
|
140
230
|
return joints.get(id);
|
|
@@ -147,67 +237,156 @@ async function readOne(project, ref, link) {
|
|
|
147
237
|
// into the plate's top or bottom is kept clear; one only passing over or under it, or touching a face, is not.
|
|
148
238
|
const sweeps = [];
|
|
149
239
|
const swept = async (r) => {
|
|
150
|
-
const { s, k, W0 } = await inAssembly(`the sweep of "${r.sweep}"`),
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if (!
|
|
156
|
-
|
|
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
|
+
];
|
|
157
264
|
const idx = moving.map((q) => s.motion.items.findIndex((x) => x[0] === (q.moves ?? q.item)));
|
|
158
|
-
const local = moving.map((q, i) => {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
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 = [];
|
|
162
281
|
for (const id of through) {
|
|
163
282
|
const j = free.find((x) => x.id === id);
|
|
164
|
-
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
|
+
);
|
|
165
287
|
j.dofs.forEach(([lo, hi], d) => {
|
|
166
|
-
const at = (v) => {
|
|
167
|
-
|
|
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)));
|
|
168
298
|
for (let i = 1; i <= 32; i++) {
|
|
169
299
|
const now = at(lo + ((hi - lo) * i) / 32).map((M, m) => sample[m].map((v) => apply(M, v)));
|
|
170
|
-
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
|
+
);
|
|
171
304
|
before = now;
|
|
172
305
|
}
|
|
173
306
|
const what = `${id}${j.dofs.length > 1 ? ` (its value ${d + 1})` : ''}`;
|
|
174
|
-
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
|
+
);
|
|
175
311
|
const steps = r.steps ?? Math.max(1, Math.ceil((2 * travel) / cell));
|
|
176
|
-
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
|
+
);
|
|
177
316
|
let made = 0;
|
|
178
317
|
for (let i = 0; i <= steps; i++) {
|
|
179
|
-
const v = lo + ((hi - lo) * i) / steps,
|
|
318
|
+
const v = lo + ((hi - lo) * i) / steps,
|
|
319
|
+
Ms = at(v);
|
|
180
320
|
for (const [m, tris] of local.entries()) {
|
|
181
321
|
const moved = tris.map((t) => t.map((q) => apply(Ms[m], q).map(clean)));
|
|
182
|
-
if (!flat) {
|
|
322
|
+
if (!flat) {
|
|
323
|
+
out.push({ triangles: moved, sweep: r.sweep, joint: id, value: round(v, 6) });
|
|
324
|
+
made++;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
183
327
|
// Each section's outlines, each a ring turned solid on its left (an outline counter-clockwise, a hole in it
|
|
184
328
|
// clockwise), for the design to cut exactly (rings); and for the solver one polygon of them all, each closed and
|
|
185
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
|
|
186
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
|
|
187
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.
|
|
188
|
-
const same = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9,
|
|
189
|
-
|
|
190
|
-
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
|
+
};
|
|
191
350
|
for (const h of slabLevels(moved, zlo, zhi, cell)) {
|
|
192
|
-
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);
|
|
193
354
|
if (!rings.length) continue;
|
|
194
|
-
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
|
+
};
|
|
195
365
|
const turned = rings.map((l, n) => {
|
|
196
|
-
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;
|
|
197
369
|
return ccw === (depth % 2 === 0) ? l : [...l].reverse();
|
|
198
370
|
});
|
|
199
|
-
const near = (l, o) =>
|
|
200
|
-
|
|
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;
|
|
201
375
|
kept.push(turned);
|
|
202
|
-
const start = turned[0][0],
|
|
203
|
-
|
|
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++;
|
|
204
380
|
}
|
|
205
381
|
}
|
|
206
382
|
}
|
|
207
383
|
sweeps.push({ sweep: r.sweep, through: what, from: round(lo, 6), to: round(hi, 6), steps, regions: made });
|
|
208
384
|
});
|
|
209
385
|
}
|
|
210
|
-
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
|
+
);
|
|
211
390
|
return out;
|
|
212
391
|
};
|
|
213
392
|
// The build direction: a direction ('+z'), or a variable holding one
|
|
@@ -215,70 +394,218 @@ async function readOne(project, ref, link) {
|
|
|
215
394
|
// The sides it is milled from, and a one-way mould's draw, likewise: or a variable holding them ('+z', '+z +x', or
|
|
216
395
|
// 'none': not milled, not cast), so a variant can switch the process
|
|
217
396
|
const named = (v) => (typeof v === 'string' && typeof values[v] === 'string' ? values[v] : v);
|
|
218
|
-
const millSides = (() => {
|
|
219
|
-
|
|
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
|
+
})();
|
|
220
410
|
// A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
|
|
221
|
-
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
|
+
};
|
|
222
415
|
const region = async (r) => {
|
|
223
|
-
if (r.sweep != null)
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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
|
+
});
|
|
231
445
|
}
|
|
232
|
-
if (r.part) {
|
|
233
|
-
|
|
234
|
-
|
|
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
|
+
}
|
|
235
457
|
const at = lo.map((x, a) => (x + hi[a]) / 2);
|
|
236
458
|
return flat ? { triangles, part: r.part, at: at.slice(0, 2), flat: true } : { triangles, part: r.part, at }; // flat: its section halfway up
|
|
237
459
|
}
|
|
238
460
|
if (r.points) return { points: r.points.map(pt) };
|
|
239
461
|
if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
|
|
240
|
-
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
|
|
241
467
|
return { at: pt(r.at), ...(r.r != null ? { r: ev(r.r) } : {}) };
|
|
242
468
|
};
|
|
243
469
|
const regions = (list) => Promise.all([list || []].flat().map(region));
|
|
244
470
|
const m = values[p.material];
|
|
245
|
-
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`);
|
|
246
473
|
// The filter's radius is about the thinnest member: a cell and a half unless the problem gives one, and never under two
|
|
247
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)
|
|
248
|
-
const printer = printerOf(project),
|
|
249
|
-
|
|
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;
|
|
250
484
|
const problem = {
|
|
251
|
-
space,
|
|
252
|
-
|
|
253
|
-
|
|
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
|
+
),
|
|
254
496
|
cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
|
|
255
|
-
material: { E: m.modulus, nu: m.poisson },
|
|
256
|
-
...(
|
|
257
|
-
|
|
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 } : {}),
|
|
258
508
|
...(overhang && overhang !== 'none' ? { overhang } : {}),
|
|
259
509
|
// How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
|
|
260
|
-
...(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
|
+
: {}),
|
|
261
519
|
// (a tool or draft with the process switched off by its variable is left out with it; one with no such process
|
|
262
520
|
// at all goes on, for topopt to refuse by name)
|
|
263
|
-
...(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' } : {}),
|
|
264
524
|
...(p.feature != null ? { feature: ev(p.feature) } : {}),
|
|
265
|
-
...(p.symmetry ? { symmetry: p.symmetry } : {}),
|
|
525
|
+
...(p.symmetry ? { symmetry: p.symmetry } : {}),
|
|
526
|
+
...(p.extrude ? { extrude: p.extrude } : {}),
|
|
266
527
|
// A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
|
|
267
|
-
...(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
|
+
: {}),
|
|
268
537
|
...(p.input_spring != null ? { input_spring: ev(p.input_spring) } : {}),
|
|
269
538
|
};
|
|
270
|
-
if (dim === 2 && !(problem.thickness > 0))
|
|
271
|
-
|
|
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)
|
|
272
549
|
// A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
|
|
273
550
|
// (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
|
|
274
551
|
// tipped corners leave dips that slice as islands, and the layers step out no further for it)
|
|
275
|
-
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)
|
|
276
565
|
// What the result is made from, for cad why: the rule sets, the problem's own values, the parts and anchors of other
|
|
277
566
|
// designs it reads, and where its filter came from
|
|
278
|
-
const inputs = {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
+
};
|
|
282
609
|
}
|
|
283
610
|
|
|
284
611
|
/**
|
|
@@ -291,8 +618,12 @@ async function readOne(project, ref, link) {
|
|
|
291
618
|
// Nodes no cell that may be solid touches (the grid's corners outside a shaped space, the inside of avoided pockets)
|
|
292
619
|
// are held: at the void's near-nothing stiffness they are what the solver crawls through, and they carry no material
|
|
293
620
|
function holdEmpty(spec) {
|
|
294
|
-
const g = makeGrid(spec.grid),
|
|
295
|
-
|
|
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;
|
|
296
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;
|
|
297
628
|
return spec;
|
|
298
629
|
}
|
|
@@ -301,32 +632,58 @@ function holdEmpty(spec) {
|
|
|
301
632
|
// refused or prevented (a powder bed print, a trapped core), each void left with its volume (mm³, or mm² in 2D) and
|
|
302
633
|
// where it is, and with prevented that they were
|
|
303
634
|
function made(r, spec, density) {
|
|
304
|
-
const p = r.problem,
|
|
635
|
+
const p = r.problem,
|
|
636
|
+
out = {};
|
|
305
637
|
if (p.mill || p.cast) {
|
|
306
|
-
const c = spec.cast,
|
|
307
|
-
|
|
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
|
+
});
|
|
308
646
|
// With a tool's size: the cells it can't get its end into besides, in the design (none, by construction) and in
|
|
309
647
|
// avoid regions (a hole narrower than the tool: drilled, or a smaller tool)
|
|
310
648
|
if (tool) {
|
|
311
|
-
const hidden = new Set(u.cells),
|
|
312
|
-
|
|
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
|
+
};
|
|
313
655
|
}
|
|
314
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)
|
|
315
657
|
const every = p.draft ? Math.max(1, Math.floor(1 / Math.tan((p.draft * Math.PI) / 180) + 1e-9)) : 0;
|
|
316
|
-
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
|
+
};
|
|
317
664
|
out.undercuts = u.count;
|
|
318
665
|
}
|
|
319
666
|
if (p.symmetry) out.symmetry = p.symmetry;
|
|
320
667
|
if (p.extrude) out.extrude = p.extrude;
|
|
321
668
|
// How grey it came out: a process or a tie can leave no clear part (a 2D section milled from its side)
|
|
322
669
|
if (p.mill || p.cast || p.symmetry || p.extrude) out.grey = round(grey(density, spec.passive), 3);
|
|
323
|
-
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
|
+
}));
|
|
324
675
|
if (r.voids === 'prevented') out.vented = true;
|
|
325
676
|
// The thinnest member asked: the ball's radius on the grid, the width it holds members to (a cell, where the grid
|
|
326
677
|
// already does), and the solid cells left in members narrower (or on a square outside corner)
|
|
327
678
|
if (p.feature != null) {
|
|
328
|
-
const h = spec.grid.h,
|
|
329
|
-
|
|
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
|
+
};
|
|
330
687
|
}
|
|
331
688
|
return out;
|
|
332
689
|
}
|
|
@@ -337,7 +694,19 @@ const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).dige
|
|
|
337
694
|
* that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
|
|
338
695
|
* @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
|
|
339
696
|
*/
|
|
340
|
-
|
|
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
|
+
});
|
|
341
710
|
/**
|
|
342
711
|
* The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
|
|
343
712
|
* densityCode (cad's own share is holdEmpty and optimised, which readies the problem and calls the solver with its
|
|
@@ -345,102 +714,211 @@ export const densityCode = () => ({ version: VERSION, solver: source('@rulecad/t
|
|
|
345
714
|
* the folder (scripts/dimension-diff.mjs).
|
|
346
715
|
* @param {object} problem readProblem's problem @param {ReturnType<typeof densityCode>} [code] @returns {string}
|
|
347
716
|
*/
|
|
348
|
-
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]);
|
|
349
719
|
export async function optimised(project, ref, { onStep, onRun, fresh = false } = {}) {
|
|
350
|
-
const r = await readProblem(project, ref),
|
|
720
|
+
const r = await readProblem(project, ref),
|
|
721
|
+
topopt = source('@rulecad/topopt');
|
|
351
722
|
// Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
|
|
352
723
|
// them, by everything: a change to how shapes are drawn redraws them without optimising again
|
|
353
724
|
// The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
|
|
354
|
-
const hash = digest([
|
|
355
|
-
|
|
356
|
-
|
|
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`);
|
|
357
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
|
|
358
740
|
const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
|
|
359
|
-
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');
|
|
360
743
|
else if (fresh) onRun?.('asked to run afresh');
|
|
361
|
-
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 })) });
|
|
362
748
|
if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
|
|
363
749
|
if (!host.exists(seen)) host.writeText(seen, '');
|
|
364
750
|
// Regions as data: a part's triangles are named, not copied
|
|
365
751
|
const named = (list) => list.map(({ triangles, ...x }) => x);
|
|
366
|
-
const shape =
|
|
367
|
-
|
|
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
|
-
|
|
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
|
+
})();
|
|
437
896
|
const result = {
|
|
438
|
-
problem: ref,
|
|
439
|
-
|
|
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,
|
|
440
907
|
...made(r, spec, o.density),
|
|
441
|
-
volume: o.volume,
|
|
442
|
-
|
|
443
|
-
|
|
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),
|
|
444
922
|
};
|
|
445
923
|
host.writeText(file, JSON.stringify(result));
|
|
446
924
|
return result;
|
|
@@ -449,10 +927,25 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
|
|
|
449
927
|
// A closed mesh's volume (mm³), by the divergence theorem
|
|
450
928
|
function meshVolume(vertices, faces) {
|
|
451
929
|
let v = 0;
|
|
452
|
-
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
|
+
}
|
|
453
938
|
return v;
|
|
454
939
|
}
|
|
455
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
|
+
|
|
456
949
|
// What a design gets as v.problems[name]: the outlines and regions to build from, and the numbers to report
|
|
457
950
|
export const forDesign = ({ density, history, ...r }) => r;
|
|
458
951
|
|
|
@@ -465,68 +958,202 @@ export const forDesign = ({ density, history, ...r }) => r;
|
|
|
465
958
|
* @param {{ cell?: number }} [options] cell: a finer cell size than the problem's, to check a final shape
|
|
466
959
|
*/
|
|
467
960
|
export async function analysePart(triangles, project, ref, { cell } = {}) {
|
|
468
|
-
const r = await readProblem(project, ref),
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
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
|
+
}
|
|
472
987
|
const out = analyseSolid(triangles, r, h);
|
|
473
988
|
host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
|
|
474
989
|
return out;
|
|
475
990
|
}
|
|
476
991
|
// The grid covers the part and the problem's space
|
|
477
|
-
let x0 = Infinity,
|
|
478
|
-
|
|
479
|
-
|
|
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));
|
|
480
1005
|
const density = fill(triangles, { nx, ny, h, origin: [x0, y0] }, problem.thickness);
|
|
481
|
-
const g = makeGrid({ nx, ny, h }),
|
|
482
|
-
|
|
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.)
|
|
483
1012
|
const onPart = new Uint8Array(g.nodes);
|
|
484
|
-
for (let e = 0; e < density.length; e++)
|
|
485
|
-
|
|
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 };
|
|
486
1023
|
const found = [];
|
|
487
|
-
for (let n = 0; n < g.nodes; n++) if (onPart[n] &&
|
|
488
|
-
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
|
+
);
|
|
489
1029
|
return found;
|
|
490
1030
|
};
|
|
491
1031
|
const fixed = new Uint8Array(g.dofs);
|
|
492
|
-
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
|
+
}
|
|
493
1037
|
const names = [...new Set(problem.loads.map((l) => l.case))];
|
|
494
1038
|
const loads = names.map((name) => {
|
|
495
1039
|
const f = new Float64Array(g.dofs);
|
|
496
|
-
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
|
+
}
|
|
497
1047
|
return f;
|
|
498
1048
|
});
|
|
499
1049
|
const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
|
|
500
1050
|
const cases = names.map((name, c) => {
|
|
501
|
-
const { size, moment } = resultant(
|
|
1051
|
+
const { size, moment } = resultant(
|
|
1052
|
+
problem.loads.filter((l) => l.case === name).map((l) => ({ ...l, at: placeOf(l) })),
|
|
1053
|
+
);
|
|
502
1054
|
return measures(name, size, moment, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
|
|
503
1055
|
});
|
|
504
|
-
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
|
+
};
|
|
505
1068
|
}
|
|
506
1069
|
|
|
507
1070
|
// A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
|
|
508
1071
|
// supports and loads land on it as they would on an optimised layout
|
|
509
1072
|
function analyseSolid(triangles, r, cell) {
|
|
510
|
-
const { problem } = r,
|
|
511
|
-
|
|
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);
|
|
512
1077
|
if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
|
|
513
|
-
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
|
+
});
|
|
514
1086
|
const cases = spec.loads.map((l, c) => measures(l.name, l.size, l.moment, a, c, density, spec.grid, spec.origin));
|
|
515
|
-
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
|
+
};
|
|
516
1099
|
}
|
|
517
1100
|
|
|
518
1101
|
// A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness (a twist: the
|
|
519
1102
|
// angle it turns, compliance over its moment, and the torsion, N·mm a radian), the largest
|
|
520
|
-
// 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
|
|
521
1107
|
function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
|
|
522
|
-
const deflection = force ? a.compliance[c] / force : 0,
|
|
523
|
-
|
|
524
|
-
|
|
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
|
+
}
|
|
525
1117
|
const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
|
|
526
|
-
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];
|
|
527
1120
|
return {
|
|
528
|
-
name,
|
|
529
|
-
|
|
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
|
+
}`,
|
|
530
1157
|
};
|
|
531
1158
|
}
|
|
532
1159
|
|
|
@@ -535,32 +1162,47 @@ function measures(name, force, moment, a, c, density, { nx, ny, h }, origin) {
|
|
|
535
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
|
|
536
1163
|
// one facing up, and the lengths inside each cube are averaged.
|
|
537
1164
|
export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
|
|
538
|
-
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;
|
|
539
1169
|
for (const [a, b, c] of triangles) {
|
|
540
1170
|
const d = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
541
1171
|
if (Math.abs(d) < 1e-12) continue; // a wall: the ray runs alongside it
|
|
542
|
-
const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)),
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
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
|
+
}
|
|
550
1186
|
}
|
|
551
|
-
const density = new Float64Array(nx * ny * nz),
|
|
1187
|
+
const density = new Float64Array(nx * ny * nz),
|
|
1188
|
+
share = 1 / (n * n * h);
|
|
552
1189
|
hits.forEach((list, ray) => {
|
|
553
1190
|
if (!list.length) return;
|
|
554
1191
|
list.sort((p, q) => p[0] - q[0]);
|
|
555
|
-
const ci = Math.floor((ray % R) / n),
|
|
556
|
-
|
|
1192
|
+
const ci = Math.floor((ray % R) / n),
|
|
1193
|
+
cj = Math.floor(Math.floor(ray / R) / n);
|
|
1194
|
+
let depth = 0,
|
|
1195
|
+
from = 0;
|
|
557
1196
|
for (const [z, sign] of list) {
|
|
558
|
-
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
|
|
559
1199
|
if (was <= 0 && depth > 0) from = z;
|
|
560
|
-
else if (was > 0 && depth <= 0)
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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
|
+
}
|
|
564
1206
|
}
|
|
565
1207
|
});
|
|
566
1208
|
return density.map((x) => Math.min(1, x));
|
|
@@ -570,19 +1212,28 @@ export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
|
|
|
570
1212
|
// through faces that face down and leaves through faces that face up, so the filled length is the sum of the up
|
|
571
1213
|
// faces' heights there less the down faces'
|
|
572
1214
|
function fill(triangles, { nx, ny, h, origin }, thickness) {
|
|
573
|
-
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
|
|
574
1218
|
for (const [a, b, c] of triangles) {
|
|
575
1219
|
const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
|
576
1220
|
if (Math.abs(nz) < 1e-12) continue; // a wall: the ray runs alongside it
|
|
577
|
-
const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])],
|
|
578
|
-
|
|
579
|
-
const
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
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
|
+
}
|
|
586
1237
|
}
|
|
587
1238
|
return length.map((l) => Math.min(1, Math.max(0, l / thickness)));
|
|
588
1239
|
}
|
|
@@ -590,7 +1241,10 @@ function fill(triangles, { nx, ny, h, origin }, thickness) {
|
|
|
590
1241
|
// A closed mesh's volume (mm³), by the divergence theorem
|
|
591
1242
|
function volume(triangles) {
|
|
592
1243
|
let v = 0;
|
|
593
|
-
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;
|
|
594
1248
|
return Math.abs(v);
|
|
595
1249
|
}
|
|
596
1250
|
|
|
@@ -603,21 +1257,39 @@ const round = (n, d = 4) => Number(n.toFixed(d));
|
|
|
603
1257
|
* @param {{ title?: string, lines?: string[] }} [label]
|
|
604
1258
|
*/
|
|
605
1259
|
export function picture(r, { title = '', lines = [] } = {}) {
|
|
606
|
-
const { nx, ny, h } = r.grid,
|
|
607
|
-
|
|
608
|
-
|
|
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;
|
|
609
1268
|
const cells = [];
|
|
610
|
-
for (let j = 0; j < ny; j++)
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
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"/>`);
|
|
616
1281
|
const loads = (r.loads || []).map((l) => {
|
|
617
|
-
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]);
|
|
618
1287
|
return `<path d="M${x - dx},${y - dy}L${x},${y}"/><circle cx="${x}" cy="${y}" r="3"/>`;
|
|
619
1288
|
});
|
|
620
|
-
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
|
+
);
|
|
621
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">
|
|
622
1294
|
<rect width="100%" height="100%" fill="#fff"/>${text.join('')}
|
|
623
1295
|
<g fill="#2b4c7e">${cells.join('')}</g>
|
|
@@ -632,21 +1304,45 @@ export function picture(r, { title = '', lines = [] } = {}) {
|
|
|
632
1304
|
// print as a stray bit. Only pieces touching a support, a load or a kept region (within a cell) stay; the volumes of
|
|
633
1305
|
// the rest, mm³, come back as dropped.
|
|
634
1306
|
export function anchored({ vertices, faces }, anchors, h) {
|
|
635
|
-
const up = vertices.map((_, i) => i),
|
|
636
|
-
|
|
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
|
+
}
|
|
637
1316
|
const pieces = new Map();
|
|
638
1317
|
for (const f of faces) {
|
|
639
|
-
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] };
|
|
640
1320
|
p.faces.push(f);
|
|
641
|
-
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
|
+
}
|
|
642
1326
|
pieces.set(r, p);
|
|
643
1327
|
}
|
|
644
1328
|
if (pieces.size < 2) return { vertices, faces, dropped: [] };
|
|
645
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));
|
|
646
|
-
const kept = [],
|
|
1330
|
+
const kept = [],
|
|
1331
|
+
dropped = [];
|
|
647
1332
|
for (const p of pieces.values()) (touches(p) ? kept : dropped).push(p);
|
|
648
1333
|
if (!kept.length) return { vertices, faces, dropped: [] }; // nothing anchored: keep it all rather than nothing
|
|
649
|
-
const index = new Map(),
|
|
650
|
-
|
|
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
|
+
);
|
|
651
1347
|
return { vertices: out, faces: keptFaces, dropped: dropped.map((p) => round(meshVolume(vertices, p.faces), 3)) };
|
|
652
1348
|
}
|