@rulecad/cad 0.5.1 → 0.6.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 CHANGED
@@ -80,6 +80,15 @@ variable says which rule it comes from. Follow these steps; they're what makes a
80
80
  - Join pins with `nets` (`GND: ['U1.GND', 'J1.GND']`) and let the autorouter draw them; `cad check` runs the fab's
81
81
  design rules. Look at the copper preview: connectors should face the edge their plug comes from.
82
82
 
83
+ ## Optimised parts
84
+ - For a flat part that carries load (a lever, a bracket, a pedal arm), describe it as a problem in `problems/`: the
85
+ space it may fill, the bosses to keep, the holes to avoid, the supports and loads (in newtons, each in a case), the
86
+ material's rule set. `npx cad optimise <project>/<problem>` and **look at the picture** in `.preview/`.
87
+ - A design reads the result through a `problem` variable and builds it with `v.shapes.optimisedOutline(...)`. Add an
88
+ `analysis` to the object so `cad check` reports its stiffness; report those numbers with their load and material.
89
+ - Say plainly that the analysis is coarse and the material values are data-sheet figures: anything that could hurt
90
+ someone if it broke needs testing, not just a check.
91
+
83
92
  ## Talking to the person
84
93
  - Give links as one labelled line (`npx cad link <project>/<object> --md`), never a raw URL. If it says
85
94
  "(not a release)", say so. If it says the link is too long for chat, don't paste it: tell the person, and offer
package/README.md CHANGED
@@ -329,6 +329,70 @@ then y, then z, as `rotate` does.
329
329
  and a quick look for parts pushed into each other when you let a slider go. The quick look can miss parts that cross
330
330
  without a corner going in, so `--sweep` is the real check.
331
331
 
332
+ ## Optimised parts
333
+
334
+ `cad optimise` finds the stiffest layout of a flat part: where to put a fixed amount of material so the part bends
335
+ least under its loads (topology optimisation, by @rulecad/topopt). A problem is a file in the project's `problems/`,
336
+ with numbers as expressions like an object's (schema: `schemas/problem.schema.json`):
337
+
338
+ ```json
339
+ {
340
+ "title": "A lever",
341
+ "uses": ["m5", "x1c"],
342
+ "material": "pla",
343
+ "thickness": 6, "cell": 1, "volume": 0.5, "filter": 2.5,
344
+ "space": { "at": [60, 0], "size": [140, 40] },
345
+ "keep": [{ "at": [0, 0], "r": 6 }, { "at": [120, 0], "r": 5 }],
346
+ "avoid": [{ "at": [0, 0], "r": "m5.clearance / 2" }, { "at": [120, 0], "r": 2.3 }],
347
+ "supports": [{ "at": [0, 0], "r": "m5.clearance / 2" }],
348
+ "loads": [{ "at": [120, 0], "r": 2.3, "force": [0, -20], "case": "down" }]
349
+ }
350
+ ```
351
+
352
+ - **The space** is where material may go (a circle `r`, a rectangle `size`, or a polygon `points`, in mm). **Keep**
353
+ regions stay solid (bosses round bolts), **avoid** regions stay empty (the holes, clearances).
354
+ - **Supports** hold the material within `r` of a point (a bolt's hole); **loads** push on it, in newtons, each in a load
355
+ case. Cases are optimised together, each by its weight in `cases` (0: analysed, not optimised for).
356
+ - **The material** is a rule set with `modulus` (MPa) and `poisson`: `pla`, `petg`, `al6061`, `al7075`, `s275`,
357
+ `ss304`, `ti64` come with rulecad. Printed values vary: measure yours.
358
+ - **Settings:** `volume`, the share of the space to fill; `cell`, the grid (smaller is finer and slower: a 140 × 40
359
+ grid takes about half a minute); `filter`, about the thinnest member, in mm.
360
+ - **Variants**, picked as `name:variant`, set variables that have a tweak range, as an object's do.
361
+
362
+ `cad optimise <project>/<problem>` runs it, reports how far each load case moves its load and the stiffness that
363
+ gives, and draws the layout in `.preview/`. The result is kept, keyed by everything it's made from, so it's only
364
+ worked out again when something it depends on changes.
365
+
366
+ A design uses it through a variable of type `problem`, which picks a problem by name:
367
+
368
+ ```json
369
+ "problem": { "type": "problem", "value": "lever", "choice": ["lever", "lever:both"] }
370
+ ```
371
+
372
+ ```js
373
+ export function main (v) {
374
+ return extrudeLinear({ height: v.thickness }, v.shapes.optimisedOutline(v.problems[v.problem]))
375
+ }
376
+ ```
377
+
378
+ `optimisedOutline` gives the outline as a 2D shape, its keep regions added and avoid regions cut exactly, so bolt
379
+ holes come out true.
380
+
381
+ ### Analysis
382
+
383
+ Any flat part, optimised or not, can be checked under a problem's supports and loads. An object's `analysis` names
384
+ the problem, and optionally a limit:
385
+
386
+ ```json
387
+ "analysis": [{ "problem": "lever", "max_deflection": 0.5, "volume": "target", "tolerance": 0.01 }]
388
+ ```
389
+
390
+ `cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
391
+ stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
392
+ further fails; with `volume` a part whose volume is further than `tolerance` (a share) from it fails. A picture goes in
393
+ `.preview/`. The analysis is coarse: it's a design aid, not engineering sign-off. A part that could hurt someone if
394
+ it failed needs testing.
395
+
332
396
  ## Boards
333
397
 
334
398
  A circuit board is an object whose .json says `"engine": "pcb"`. Its `main(v)` returns a
package/bin/cad.mjs CHANGED
@@ -16,6 +16,8 @@ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } f
16
16
  import { valuesOf, why } from '../lib/explain.mjs';
17
17
  import { errorData } from '../lib/errors.mjs';
18
18
  import { schemaFindings } from '../lib/schema.mjs';
19
+ import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
20
+ import { evaluate } from '../lib/rules.mjs';
19
21
  import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
20
22
  import { threemf, slotOf } from '../lib/threemf.mjs';
21
23
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
@@ -44,6 +46,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
44
46
  cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
45
47
  cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
46
48
  cad preview <project>/<object> four views as a PNG in .preview/ (prints the path)
49
+ cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
50
+ variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
47
51
  cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
48
52
  cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
49
53
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
@@ -105,6 +109,57 @@ function report(findings, about = {}) {
105
109
  }
106
110
  const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
107
111
 
112
+ const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
113
+ // cad optimise: run a problem (with a progress line), then report it and draw it
114
+ function optimiseProblem(ref) {
115
+ const [project, name] = String(ref).split('/');
116
+ if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
117
+ const file = problemFile(project, name.split(':')[0]);
118
+ if (fs.existsSync(file)) {
119
+ const bad = schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'problem', path.relative(WS, file));
120
+ if (bad.length) { report(bad); process.exitCode = 1; return; }
121
+ }
122
+ const live = !opt('json') && process.stderr.isTTY;
123
+ const r = optimised(project, name, { fresh: !!opt('fresh'), onStep: (s) => live && process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`) });
124
+ if (live) process.stderr.write('\r\x1b[K');
125
+ const out = paths.preview(project, `${name.replace(':', '-')}-optimised.svg`), p = readProblem(project, name);
126
+ const lines = [`${p.material.name}, ${fmt(r.thickness)} mm thick: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
127
+ `${fmt(r.volume * 100)}% of the space, ${r.grid.nx} × ${r.grid.ny} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}`];
128
+ fs.mkdirSync(path.dirname(out), { recursive: true });
129
+ fs.writeFileSync(out, picture(r, { title: r.title, lines }));
130
+ if (opt('json')) return console.log(JSON.stringify((({ density, history, ...x }) => x)(r), null, 2));
131
+ console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
132
+ for (const c of r.cases) console.log(` ${c.name}: moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
133
+ console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
134
+ console.log(` ${r.grid.nx} × ${r.grid.ny} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
135
+ console.log(out);
136
+ }
137
+
138
+ // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
139
+ function analyses(b, d, tag) {
140
+ const lookup = (n) => { const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values); if (typeof v !== 'number') throw new Error(`analysis: "${n}" isn't a number`); return v; };
141
+ return (b.object.analysis || []).flatMap((a) => {
142
+ const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
143
+ if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
144
+ const r = analysePart(part.triangles, d.project, a.problem), m = r.material, limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
145
+ const out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
146
+ fs.mkdirSync(path.dirname(out), { recursive: true });
147
+ fs.writeFileSync(out, picture({ ...r, ...readProblem(d.project, a.problem).problem }, { title: `${b.object.title || d.name}: ${a.problem}`, lines: r.cases.map((c) => `${c.name}: ${sig(c.deflection)} mm, ${sig(c.stiffness)} N/mm, peak stress ${sig(c.stress)} MPa`) }));
148
+ const found = r.cases.map((c) => {
149
+ const safety = m.strength ? `, peak stress ${sig(c.stress)} MPa (${sig(m.strength / c.stress)}× under ${m.name}'s strength; coarse)` : '';
150
+ const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm${safety}`;
151
+ const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
152
+ return { level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs: { problem: a.problem, part: part.name, picture: path.relative(WS, out) } };
153
+ });
154
+ const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
155
+ if (a.volume != null) {
156
+ const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
157
+ found.push({ level: Math.abs(off) <= tol ? 'pass' : 'fail', text: `volume ${fmt(r.volume)} mm³${grams}: ${off >= 0 ? '+' : ''}${fmt(off * 100)}% from ${fmt(want)} (within ${fmt(tol * 100)}%)`, code: 'fea.volume', values: { volume: r.volume, target: want, off } });
158
+ } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
159
+ return found;
160
+ });
161
+ }
162
+
108
163
  async function main() {
109
164
  const [cmd, ref] = args;
110
165
  if (!cmd || cmd === 'help') return console.log(HELP);
@@ -162,6 +217,7 @@ async function main() {
162
217
  if (cmd === 'why') return explainValue(ref);
163
218
  if (cmd === 'set') return editVariables(ref);
164
219
  if (cmd === 'add') return editAssembly(args[1], args[2]);
220
+ if (cmd === 'optimise' || cmd === 'optimize') return optimiseProblem(ref);
165
221
  if (isAssembly(ref)) return assembly(cmd, ref);
166
222
  const [base, at] = ref.split('@');
167
223
  const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
@@ -197,7 +253,9 @@ async function main() {
197
253
  const raw = lint(fs.readFileSync(d.js, 'utf8')), file = path.relative(WS, d.js);
198
254
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
199
255
  const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
200
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f)))];
256
+ const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
257
+ const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
258
+ ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
201
259
  const failed = report([
202
260
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
203
261
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
@@ -206,6 +264,7 @@ async function main() {
206
264
  ...(b.object.role === 'reference'
207
265
  ? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
208
266
  : check(b.triangles, printer(b, d), { parts: b.parts })),
267
+ ...analyses(b, d, tag),
209
268
  ], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
210
269
  if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
211
270
  if (b.parts.length > 1) say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
@@ -305,7 +364,9 @@ async function board(cmd, d, b, { title, version, tag }) {
305
364
  const raw = lint(fs.readFileSync(d.js, 'utf8'));
306
365
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
307
366
  const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
308
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f)))];
367
+ const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
368
+ const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
369
+ ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
309
370
  const failed = report([
310
371
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
311
372
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
package/lib/design.mjs CHANGED
@@ -27,6 +27,7 @@ import crypto from 'node:crypto';
27
27
  import { resolve, loadRuleSet } from './rules.mjs';
28
28
  import { WS, paths, printerOf } from './workspace.mjs';
29
29
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
30
+ import { optimised, forDesign } from './optimise.mjs';
30
31
  import * as shapes from '@rulecad/shapes';
31
32
  import { engineId, packageVersion, materialise } from './versions.mjs';
32
33
  import { satisfies } from '@rulecad/versions';
@@ -89,6 +90,19 @@ export function layoutsOf(d, object) {
89
90
  return out;
90
91
  }
91
92
 
93
+ // The optimised layouts an object's problem variables pick, by name, for v.problems
94
+ export function problemsOf(d, object, values) {
95
+ const out = {};
96
+ for (const [name, v] of Object.entries(object.variables || {})) if (v.type === 'problem') {
97
+ const ref = values[name];
98
+ if (!out[ref]) {
99
+ const r = optimised(d.project, ref, { onStep: (s) => s.step === 1 && console.error(`optimising ${ref} (once: the result is cached until the problem changes)…`) });
100
+ out[ref] = forDesign(r);
101
+ }
102
+ }
103
+ return out;
104
+ }
105
+
92
106
  // A variant's inputs, under what's set explicitly
93
107
  export function variantSet(d, object, set = {}) {
94
108
  if (!d.variant) return set;
@@ -134,10 +148,14 @@ export async function build(d, set = {}, { mirror = false } = {}) {
134
148
  const files = layoutsOf(d, object);
135
149
  if (object.layouts) values.layouts = object.layouts; // older designs kept layouts in their .json
136
150
  if (Object.keys(files).length) values.layouts = Object.fromEntries(Object.entries(files).map(([n, l]) => [n, { ...l, keys: keys(l), width: width(l), depth: depth(l) }]));
151
+ // Optimised layouts: a "type": "problem" variable picks a problem in the project's problems/; the design gets the
152
+ // one it picked as v.problems[name] (lib/optimise.mjs), optimised the first time and cached after
153
+ const problems = problemsOf(d, object, values);
154
+ if (Object.keys(problems).length) values.problems = problems;
137
155
 
138
156
  // The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether
139
157
  const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
140
- const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), JSON.stringify(object), ruleText, files, set, display])).digest('hex');
158
+ const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), JSON.stringify(object), ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
141
159
  const hit = path.join(CACHE, `${key}.json`);
142
160
  if (!process.env.CAD_NO_CACHE && host.exists(hit)) {
143
161
  const c = JSON.parse(host.readText(hit));
@@ -0,0 +1,182 @@
1
+ // Optimisation problems and analysis: problems/<name>.json in a project describes a flat part to optimise (where
2
+ // material may go, what stays solid or empty, supports, loads, material); @rulecad/topopt finds the stiffest layout,
3
+ // and @rulecad/fea analyses any flat part under the same problem's loads (an object's "analysis", run by cad check).
4
+ // The problem file is the source: a result is derived from it, cached by everything it's made from, and remade only
5
+ // when one of those changes. A name may pick a variant: lever:both.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import crypto from 'node:crypto';
9
+ import { host } from './host.mjs';
10
+ import { paths } from './workspace.mjs';
11
+ import { resolve, loadRuleSet, evaluate } from './rules.mjs';
12
+ import { located } from './errors.mjs';
13
+ import { discretise, optimise, outlines, area } from '@rulecad/topopt';
14
+ import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
15
+
16
+ const VERSION = 1, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
17
+ export const problemFile = (project, name) => path.join(paths.project(project), 'problems', `${name}.json`);
18
+ export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
19
+
20
+ /**
21
+ * A problem with every expression worked out: what @rulecad/topopt takes, with its material and settings.
22
+ * @param {string} project @param {string} ref name, or name:variant
23
+ */
24
+ export function readProblem(project, ref) {
25
+ const [name, variant] = String(ref).split(':'), file = problemFile(project, name);
26
+ if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
27
+ const p = JSON.parse(host.readText(file));
28
+ if (variant && !p.variants?.[variant]) throw new Error(`problem ${name} has no variant "${variant}" (variants: ${Object.keys(p.variants || {}).join(', ') || 'none'})`);
29
+ const uses = [...new Set([...(p.uses || []), p.material])];
30
+ let values;
31
+ try { ({ values } = resolve({ uses, variables: p.variables || {} }, { set: variant ? p.variants[variant] : {} })); } catch (e) { throw located(e, file, 'var'); }
32
+ const lookup = (n) => {
33
+ const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), values);
34
+ if (typeof v !== 'number') throw new Error(`${path.basename(file)}: "${n}" isn't a number here (variables: ${Object.keys(p.variables || {}).join(', ')})`);
35
+ return v;
36
+ };
37
+ const ev = (x) => evaluate(x, lookup), pt = (a) => a.map(ev);
38
+ const region = (r) => (r.points ? { points: r.points.map(pt) } : r.size ? { at: pt(r.at), size: r.size.map(ev) } : { at: pt(r.at), r: ev(r.r) });
39
+ const m = values[p.material];
40
+ if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number') throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
41
+ const problem = {
42
+ space: [p.space].flat().map(region), keep: (p.keep || []).map(region), avoid: (p.avoid || []).map(region),
43
+ supports: p.supports.map((s) => ({ at: pt(s.at), ...(s.r != null ? { r: ev(s.r) } : {}), fix: s.fix || 'xy' })),
44
+ loads: p.loads.map((l) => ({ at: pt(l.at), ...(l.r != null ? { r: ev(l.r) } : {}), force: pt(l.force), case: l.case || 'load' })),
45
+ cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
46
+ material: { E: m.modulus, nu: m.poisson }, thickness: ev(p.thickness), cell: ev(p.cell), volume: ev(p.volume),
47
+ ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
48
+ ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
49
+ };
50
+ const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
51
+ return { ref, name, variant, file, title: p.title || name, material: { name: p.material, ...m }, problem, outline };
52
+ }
53
+
54
+ /**
55
+ * The optimised layout for a problem, from the cache when nothing it depends on has changed.
56
+ * @param {string} project @param {string} ref
57
+ * @param {{ onStep?: Function, fresh?: boolean }} [options] fresh: run it even if it's cached
58
+ */
59
+ export function optimised(project, ref, { onStep, fresh = false } = {}) {
60
+ const r = readProblem(project, ref);
61
+ const hash = crypto.createHash('sha256').update(JSON.stringify([VERSION, r.problem, r.outline, source('@rulecad/topopt'), source('@rulecad/fea')])).digest('hex');
62
+ const file = paths.cache('optimise', `${hash}.json`);
63
+ if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
64
+ const spec = discretise(r.problem);
65
+ const o = optimise(spec, { onStep });
66
+ const loops = outlines(spec.grid, o.density, spec.origin, r.outline);
67
+ const result = {
68
+ problem: ref, title: r.title, hash, material: r.material.name, thickness: r.problem.thickness,
69
+ grid: spec.grid, origin: spec.origin, regions: spec.regions, outlines: loops.map((l) => l.map(([x, y]) => [round(x), round(y)])),
70
+ area: loops.reduce((s, l) => s + area(l), 0), volume: o.volume, compliance: o.compliance, cases: o.cases,
71
+ steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
72
+ supports: r.problem.supports, loads: r.problem.loads,
73
+ };
74
+ host.writeText(file, JSON.stringify(result));
75
+ return result;
76
+ }
77
+
78
+ // What a design gets as v.problems[name]: the outlines and regions to build from, and the numbers to report
79
+ export const forDesign = ({ density, history, ...r }) => r;
80
+
81
+ /**
82
+ * Analyse a flat part (triangles, z up, the plate lying on the bed) under a problem's supports and loads, on its grid:
83
+ * each cell is as solid as the share of the problem's thickness the part fills above it.
84
+ * @param {number[][][]} triangles @param {string} project @param {string} ref
85
+ */
86
+ export function analysePart(triangles, project, ref) {
87
+ const r = readProblem(project, ref), { problem } = r, h = problem.cell;
88
+ // The grid covers the part and the problem's space
89
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
90
+ for (const t of triangles) for (const [x, y] of t) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }
91
+ const nx = Math.max(1, Math.ceil((x1 - x0) / h)), ny = Math.max(1, Math.ceil((y1 - y0) / h));
92
+ const density = fill(triangles, { nx, ny, h, origin: [x0, y0] }, problem.thickness);
93
+ const g = makeGrid({ nx, ny, h }), at = positions(g).map(([x, y]) => [x + x0, y + y0]);
94
+ // Supports and loads on the nodes near them that touch the part
95
+ const onPart = new Uint8Array(g.nodes);
96
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 4; k++) onPart[g.edof[e * 8 + 2 * k] / 2] = 1;
97
+ const near = (p, rr = 0, what) => {
98
+ const found = [];
99
+ for (let n = 0; n < g.nodes; n++) if (onPart[n] && Math.hypot(at[n][0] - p[0], at[n][1] - p[1]) <= rr + h * 0.75) found.push(n);
100
+ if (!found.length) throw new Error(`${what} at ${p.join(', ')} isn't on the part: is it placed as the problem expects?`);
101
+ return found;
102
+ };
103
+ const fixed = new Uint8Array(g.dofs);
104
+ for (const s of problem.supports) for (const n of near(s.at, s.r, 'a support')) { if (s.fix.includes('x')) fixed[2 * n] = 1; if (s.fix.includes('y')) fixed[2 * n + 1] = 1; }
105
+ const names = [...new Set(problem.loads.map((l) => l.case))];
106
+ const loads = names.map((name) => {
107
+ const f = new Float64Array(g.dofs);
108
+ for (const l of problem.loads.filter((x) => x.case === name)) { const ns = near(l.at, l.r, `the load "${name}"`); for (const n of ns) { f[2 * n] += l.force[0] / ns.length; f[2 * n + 1] += l.force[1] / ns.length; } }
109
+ return f;
110
+ });
111
+ const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
112
+ const cases = names.map((name, c) => {
113
+ const size = Math.hypot(...problem.loads.filter((l) => l.case === name).reduce((s, l) => [s[0] + l.force[0], s[1] + l.force[1]], [0, 0]));
114
+ const deflection = size ? a.compliance[c] / size : 0;
115
+ let most = 0;
116
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) most = Math.max(most, a.stress[c][e]);
117
+ return { name, force: size, deflection, stiffness: deflection ? size / deflection : Infinity, stress: most };
118
+ });
119
+ return { problem: ref, material: r.material, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
120
+ }
121
+
122
+ // How much of the thickness the part fills over each cell's centre: a ray straight up through the part enters it
123
+ // through faces that face down and leaves through faces that face up, so the filled length is the sum of the up
124
+ // faces' heights there less the down faces'
125
+ function fill(triangles, { nx, ny, h, origin }, thickness) {
126
+ const length = new Float64Array(nx * ny), jx = h * 1e-4 * Math.SQRT2, jy = h * 1e-4 * Math.PI; // off-centre, so no ray meets an edge exactly
127
+ for (const [a, b, c] of triangles) {
128
+ const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
129
+ if (Math.abs(nz) < 1e-12) continue; // a wall: the ray runs alongside it
130
+ const lo = [Math.min(a[0], b[0], c[0]), Math.min(a[1], b[1], c[1])], hi = [Math.max(a[0], b[0], c[0]), Math.max(a[1], b[1], c[1])];
131
+ const i0 = Math.max(0, Math.floor((lo[0] - origin[0]) / h)), i1 = Math.min(nx - 1, Math.ceil((hi[0] - origin[0]) / h));
132
+ const j0 = Math.max(0, Math.floor((lo[1] - origin[1]) / h)), j1 = Math.min(ny - 1, Math.ceil((hi[1] - origin[1]) / h));
133
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
134
+ const x = origin[0] + (i + 0.5) * h + jx, y = origin[1] + (j + 0.5) * h + jy;
135
+ const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / nz, w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / nz, w2 = 1 - w0 - w1;
136
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
137
+ length[j * nx + i] += Math.sign(nz) * (w0 * a[2] + w1 * b[2] + w2 * c[2]);
138
+ }
139
+ }
140
+ return length.map((l) => Math.min(1, Math.max(0, l / thickness)));
141
+ }
142
+
143
+ // A closed mesh's volume (mm³), by the divergence theorem
144
+ function volume(triangles) {
145
+ let v = 0;
146
+ for (const [a, b, c] of triangles) v += (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])) / 6;
147
+ return Math.abs(v);
148
+ }
149
+
150
+ const round = (n, d = 4) => Number(n.toFixed(d));
151
+
152
+ /**
153
+ * A picture of a density field (an optimised result, or an analysed part) as SVG: cells shaded by density, outlines,
154
+ * supports (triangles) and loads (arrows).
155
+ * @param {{ grid: { nx: number, ny: number, h: number }, origin: number[], density: ArrayLike<number>, outlines?: number[][][], supports?: any[], loads?: any[] }} r
156
+ * @param {{ title?: string, lines?: string[] }} [label]
157
+ */
158
+ export function picture(r, { title = '', lines = [] } = {}) {
159
+ const { nx, ny, h } = r.grid, s = Math.max(2, Math.min(8, Math.floor(1100 / (nx * h)))) , pad = 24, top = 30 + lines.length * 16;
160
+ const W = nx * h * s + 2 * pad, H = ny * h * s + pad + top + 12;
161
+ const X = (x) => pad + (x - r.origin[0]) * s, Y = (y) => top + (ny * h - (y - r.origin[1])) * s;
162
+ const cells = [];
163
+ for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
164
+ const d = r.density[j * nx + i];
165
+ if (d > 0.02) cells.push(`<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)}"/>`);
166
+ }
167
+ const loops = (r.outlines || []).map((l) => `<path d="M${l.map(([x, y]) => `${X(x).toFixed(1)},${Y(y).toFixed(1)}`).join('L')}Z"/>`);
168
+ const supports = (r.supports || []).map((p) => `<path d="M${X(p.at[0])},${Y(p.at[1])}l-6,10h12z"/>`);
169
+ const loads = (r.loads || []).map((l) => {
170
+ const len = Math.hypot(...l.force) || 1, dx = (l.force[0] / len) * 30, dy = (-l.force[1] / len) * 30, x = X(l.at[0]), y = Y(l.at[1]);
171
+ return `<path d="M${x - dx},${y - dy}L${x},${y}"/><circle cx="${x}" cy="${y}" r="3"/>`;
172
+ });
173
+ const text = [title, ...lines].map((t, i) => `<text x="${pad}" y="${20 + i * 16}" font-size="${i ? 12 : 14}"${i ? '' : ' font-weight="600"'}>${t.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</text>`);
174
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="system-ui, sans-serif">
175
+ <rect width="100%" height="100%" fill="#fff"/>${text.join('')}
176
+ <g fill="#2b4c7e">${cells.join('')}</g>
177
+ <g fill="none" stroke="#e8a33d" stroke-width="1.5">${loops.join('')}</g>
178
+ <g fill="#3a9d5d">${supports.join('')}</g>
179
+ <g stroke="#c0392b" fill="#c0392b" stroke-width="2.5">${loads.join('')}</g>
180
+ </svg>
181
+ `;
182
+ }
package/lib/schema.mjs CHANGED
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
 
8
8
  const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schemas');
9
9
  const cache = new Map();
10
- /** A schema by name: object, assembly, rules or layout. @param {'object' | 'assembly' | 'rules' | 'layout'} name */
10
+ /** A schema by name: object, assembly, rules, layout or problem. @param {'object' | 'assembly' | 'rules' | 'layout' | 'problem'} name */
11
11
  export function schema(name) {
12
12
  if (!cache.has(name)) cache.set(name, JSON.parse(fs.readFileSync(path.join(DIR, `${name}.schema.json`), 'utf8')));
13
13
  return cache.get(name);
@@ -63,7 +63,7 @@ export function validate(value, s, root = s, at = '') {
63
63
  return out;
64
64
  }
65
65
 
66
- /** Problems with a file's JSON as findings (code schema), for cad check. @param {any} json @param {'object' | 'assembly' | 'rules' | 'layout'} kind @param {string} file */
66
+ /** Problems with a file's JSON as findings (code schema), for cad check. @param {any} json @param {'object' | 'assembly' | 'rules' | 'layout' | 'problem'} kind @param {string} file */
67
67
  export function schemaFindings(json, kind, file) {
68
68
  return validate(json, schema(kind)).map((x) => ({ level: 'fail', text: `${file}: ${x.path}: ${x.message}`, code: 'schema', refs: { file, path: x.path } }));
69
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -44,16 +44,18 @@
44
44
  "directory": "packages/cad"
45
45
  },
46
46
  "dependencies": {
47
- "@rulecad/variables": "^0.1.7",
47
+ "@rulecad/variables": "^0.2.0",
48
48
  "@rulecad/keyboard-layout": "^0.1.2",
49
49
  "@rulecad/printcheck": "^0.1.3",
50
50
  "@rulecad/fit": "^0.2.1",
51
51
  "@rulecad/model-link": "^0.2.0",
52
52
  "@rulecad/versions": "^0.1.0",
53
- "@rulecad/shapes": "^0.2.1",
54
- "@rulecad/rules": "^0.2.0",
53
+ "@rulecad/shapes": "^0.3.0",
54
+ "@rulecad/rules": "^0.3.0",
55
55
  "@jscad/modeling": "^2.12.0",
56
- "three": "^0.186.1"
56
+ "three": "^0.186.1",
57
+ "@rulecad/fea": "^0.1.0",
58
+ "@rulecad/topopt": "^0.1.0"
57
59
  },
58
60
  "peerDependencies": {
59
61
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0"
@@ -24,7 +24,8 @@
24
24
  "parts": { "type": "object", "additionalProperties": { "$ref": "#/$defs/part" } },
25
25
  "variants": { "type": "object", "additionalProperties": { "type": "object" } },
26
26
  "anchors": { "type": "object", "additionalProperties": { "$ref": "#/$defs/anchor" } },
27
- "layouts": { "type": "object", "description": "Older designs kept layouts here; now in the project's layouts/" }
27
+ "layouts": { "type": "object", "description": "Older designs kept layouts here; now in the project's layouts/" },
28
+ "analysis": { "type": "array", "items": { "$ref": "#/$defs/analysis" }, "description": "Checks of how the part bends under a problem's loads (cad check)" }
28
29
  },
29
30
  "$defs": {
30
31
  "expr": { "type": ["number", "string"] },
@@ -40,7 +41,7 @@
40
41
  "show": { "type": "boolean" },
41
42
  "interface": { "type": "boolean", "description": "Other objects depend on it: a change bumps the version accordingly" },
42
43
  "tweak": { "type": "object", "required": ["min", "max"], "additionalProperties": false, "properties": { "min": { "$ref": "#/$defs/expr" }, "max": { "$ref": "#/$defs/expr" }, "step": { "type": "number" } } },
43
- "type": { "enum": ["text", "anchor", "choice", "layout"] },
44
+ "type": { "enum": ["text", "anchor", "choice", "layout", "problem"] },
44
45
  "choice": { "type": "array" },
45
46
  "max": { "type": "number" },
46
47
  "fields": { "type": "array", "items": { "type": "string" } },
@@ -49,6 +50,18 @@
49
50
  "checked": { "type": "string" }
50
51
  }
51
52
  },
53
+ "analysis": {
54
+ "type": "object",
55
+ "required": ["problem"],
56
+ "additionalProperties": false,
57
+ "properties": {
58
+ "problem": { "type": "string", "description": "A problem in the project's problems/ (name, or name:variant): its supports, loads, material and thickness" },
59
+ "part": { "type": "string", "description": "The part analysed (default: the first that isn't a support)" },
60
+ "max_deflection": { "$ref": "#/$defs/expr", "description": "Fail if any load case moves its load further than this, in mm" },
61
+ "volume": { "$ref": "#/$defs/expr", "description": "Fail if the part's volume differs from this (mm³) by more than tolerance" },
62
+ "tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" }
63
+ }
64
+ },
52
65
  "part": {
53
66
  "type": "object",
54
67
  "additionalProperties": false,
@@ -0,0 +1,77 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://jonibach.github.io/rulecad/schemas/problem.schema.json",
4
+ "title": "rulecad optimisation problem",
5
+ "description": "A flat part to optimise (projects/<project>/problems/<name>.json): where material may go, what must stay solid or empty, where it's held and loaded, and what it's made of. Numbers are expressions, as in objects: of its variables and the rule sets it uses. cad optimise runs it; a design reads the result through a variable of type problem.",
6
+ "type": "object",
7
+ "required": ["material", "thickness", "cell", "volume", "space", "supports", "loads"],
8
+ "additionalProperties": false,
9
+ "properties": {
10
+ "$schema": { "type": "string" },
11
+ "title": { "type": "string" },
12
+ "description": { "type": "string" },
13
+ "uses": { "type": "array", "items": { "type": "string" }, "description": "Rule sets: the material's, the printer's, the part's own" },
14
+ "variables": { "type": "object", "description": "As in objects" },
15
+ "variants": { "type": "object", "additionalProperties": { "type": "object" }, "description": "Named settings of variables with tweak ranges, picked as name:variant" },
16
+ "material": { "type": "string", "description": "A rule set with modulus (MPa), poisson and, for safety factors, strength (MPa)" },
17
+ "thickness": { "$ref": "#/$defs/expr", "description": "The plate's thickness, mm" },
18
+ "cell": { "$ref": "#/$defs/expr", "description": "The grid's cell size, mm: smaller is finer and slower" },
19
+ "volume": { "$ref": "#/$defs/expr", "description": "The share of the space to fill, 0 to 1 (keep regions count towards it)" },
20
+ "filter": { "$ref": "#/$defs/expr", "description": "Filter radius, mm: about the thinnest member (default 1.5 cells)" },
21
+ "penal": { "$ref": "#/$defs/expr", "description": "The penalty on part-solid cells (default 3)" },
22
+ "projection": { "type": "boolean", "description": "Sharpen the result to solid and empty (default true)" },
23
+ "steps": { "type": "integer", "description": "At most this many steps (default 300)" },
24
+ "space": { "oneOf": [{ "$ref": "#/$defs/region" }, { "type": "array", "items": { "$ref": "#/$defs/region" } }], "description": "Where material may go" },
25
+ "keep": { "type": "array", "items": { "$ref": "#/$defs/region" }, "description": "Must stay solid: bosses round bolt holes" },
26
+ "avoid": { "type": "array", "items": { "$ref": "#/$defs/region" }, "description": "Must stay empty: holes, clearances (avoid wins over keep)" },
27
+ "supports": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/support" } },
28
+ "loads": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/load" } },
29
+ "cases": { "type": "object", "additionalProperties": { "$ref": "#/$defs/expr" }, "description": "Each load case's weight in the optimisation (default 1); 0 analyses it without optimising for it" },
30
+ "outline": {
31
+ "type": "object",
32
+ "additionalProperties": false,
33
+ "properties": {
34
+ "smooth": { "type": "integer", "description": "Smoothing passes (default 4)" },
35
+ "min_area": { "$ref": "#/$defs/expr", "description": "Holes and islands smaller than this (mm²) are dropped" }
36
+ }
37
+ }
38
+ },
39
+ "$defs": {
40
+ "expr": { "type": ["number", "string"] },
41
+ "point": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 2 },
42
+ "region": {
43
+ "type": "object",
44
+ "additionalProperties": false,
45
+ "properties": {
46
+ "at": { "$ref": "#/$defs/point", "description": "The centre, mm" },
47
+ "r": { "$ref": "#/$defs/expr", "description": "A circle's radius" },
48
+ "size": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 2, "description": "A rectangle's width and depth" },
49
+ "points": { "type": "array", "items": { "$ref": "#/$defs/point" }, "minItems": 3, "description": "A polygon's corners" },
50
+ "label": { "type": "string" }
51
+ }
52
+ },
53
+ "support": {
54
+ "type": "object",
55
+ "required": ["at"],
56
+ "additionalProperties": false,
57
+ "properties": {
58
+ "at": { "$ref": "#/$defs/point" },
59
+ "r": { "$ref": "#/$defs/expr", "description": "Holds the material within this radius (a bolt hole's)" },
60
+ "fix": { "enum": ["xy", "x", "y"], "description": "Which ways it's held (default both)" },
61
+ "label": { "type": "string" }
62
+ }
63
+ },
64
+ "load": {
65
+ "type": "object",
66
+ "required": ["at", "force"],
67
+ "additionalProperties": false,
68
+ "properties": {
69
+ "at": { "$ref": "#/$defs/point" },
70
+ "r": { "$ref": "#/$defs/expr", "description": "Spread over the material within this radius" },
71
+ "force": { "$ref": "#/$defs/point", "description": "x and y, in N" },
72
+ "case": { "type": "string", "description": "Its load case (default load)" },
73
+ "label": { "type": "string" }
74
+ }
75
+ }
76
+ }
77
+ }