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