@rulecad/cad 0.7.78 → 0.7.81

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/CHANGELOG.md CHANGED
@@ -5,6 +5,71 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
5
5
  its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the screw by thread
6
6
  and head, the parts it passes through and the part it ends in.
7
7
 
8
+ ## 0.7.81: a folding sheet checked in an assembly's poses (#78)
9
+ ### Tests
10
+
11
+ - A test that an assembly's pose can fold a sheet from `@rulecad/flexures` (the workspace example `flexures/tray-fit`
12
+ sets `tray.fold`): the fit is checked flat and folded, and a block that clears the flat sheet is caught once the
13
+ walls stand. No code in cad changed: a design whose `main` returns a fold check's findings with its parts has them
14
+ reported by `cad check`, as a lamina mechanism's are.
15
+
16
+ ### Printed sizes that moved
17
+
18
+ - None.
19
+
20
+ ## 0.7.80: problems tied to designs, and optimisation you can watch again
21
+ ### Added
22
+
23
+ - A problem's regions, supports and loads can sit at another design's anchor: `"anchor": "plate.pivot"` in place of
24
+ `at`, where that anchor is as the design is built (x and y of it in a flat problem; a cylinder along the anchor's
25
+ axis unless it names one; an anchor with a `rotate` points along its z turned by it, as an assembly reads it).
26
+ Moving the anchor moves the problem and optimises it again; a value of that design the anchors do not read leaves
27
+ the result as it is. A design built from the problem itself is refused by name, as is an anchor that is not there
28
+ (with the anchors there are). So are problems that reach each other through designs built from them, however long
29
+ the loop (problem a held at a design built from b, and b at one built from a): refused with the chain, where before
30
+ they were read until memory ran out. Schema first: `anchor` on regions, supports, loads and the output.
31
+ - `cad preview <project>/problems/<problem>` (or the problem file's path) shows the run: the result is drawn as by
32
+ `cad optimise`, and `.preview/<project>/<problem>-run.html` replays the run step by step with no server (the live
33
+ view's page, its densities, compliance and change for every step read from the file). Every `cad optimise` run is
34
+ recorded and kept by its densities' key, so a cached result still shows the run that made it; one made without
35
+ recording (by a design's build) shows its end and each step's compliance, and says to run it with `--fresh`.
36
+ `--watch` on the preview shows the run live, as on `cad optimise`.
37
+ - A flat (2D) problem's regions can be another design's part (`{ "part": "blank.body" }`), as solid problems' could:
38
+ its section halfway up, holes open, so an arm is optimised within the blank it is cut from. A problem with a
39
+ `thickness` is flat whatever its regions are.
40
+ - `cad why <project>/<object>.<problem variable>` says what the optimised result is made from: the problem file, its
41
+ title and material, its rule sets and values, the parts and anchors of other designs it reads, where its filter
42
+ came from, and the file its densities are kept in (made, or not yet).
43
+
44
+ - `"outline": { "reduce": 0.1 }` on a solid problem draws its surface with fewer triangles: within that many mm of
45
+ the surface as drawn, closed, with no more area past the printer's overhang limit and no new tips (topopt's
46
+ `reduce`). `cad optimise` says how many triangles it had and has. Off unless given: no existing result changes.
47
+ On the bracket bench's printable result, 0.1 mm took 75,592 triangles to 21,124 (27.808 to 27.806 cm³).
48
+
49
+ ### Changed
50
+
51
+ - A problem with no `filter` is never filtered under two of the printer's lines (the thinnest wall it lays solid).
52
+ It was a cell and a half always, and still is wherever that is more: on an X1C's 0.42 mm lines, every cell of
53
+ 0.56 mm or more. No existing problem's result moves: the kit's problems all give their filter or use cells of 1 mm
54
+ or more.
55
+
56
+ ## 0.7.79: strength in optimisation
57
+ ### Added
58
+
59
+ - A problem takes `strain`, a strain limit (a share: `"pla.strength / pla.modulus / 2"`), in place of `stress`: the
60
+ stress limit is it times the material's modulus. A mechanism given either is optimised as before and then checked:
61
+ `cad optimise` gives its peak stress at its push and the push and output travel that take it to the limit.
62
+ - The rule set schema takes `low` and `high` on a rule: the range it is found in.
63
+
64
+ ### Changed
65
+
66
+ - A project whose material has no rule set is refused with every plastic the workspace and the kit have a set for
67
+ (abs, asa, pa_cf, petg and pla in the kit), where it named only pla and petg. A plastic is a set that gives
68
+ strength, modulus, density and modulus_z. `plastics()` in `lib/fittings.mjs` lists them. A project of ABS, ASA or
69
+ PA-CF has its printed fittings sized from the kit's set.
70
+
71
+ No printed size moved.
72
+
8
73
  ## 0.7.78: frames solved under their joints' loads, sized with joins that fit (#302, #303, #304)
9
74
 
10
75
  ### Added
package/README.md CHANGED
@@ -1484,14 +1484,23 @@ with numbers as expressions like an object's (schema: `schemas/problem.schema.js
1484
1484
  }
1485
1485
  ```
1486
1486
 
1487
- - **The space** is where material may go (a circle `r`, a rectangle `size`, or a polygon `points`, in mm). **Keep**
1487
+ - **The space** is where material may go (a circle `r`, a rectangle `size`, a polygon `points`, in mm, or another
1488
+ design's part, `{ "part": "blank.body" }`, taken as its section halfway up, holes open). **Keep**
1488
1489
  regions stay solid (bosses round bolts), **avoid** regions stay empty (the holes, clearances).
1489
1490
  - **Supports** hold the material within `r` of a point (a bolt's hole); **loads** push on it, in newtons, each in a load
1490
1491
  case. Cases are optimised together, each by its weight in `cases` (0: analysed, not optimised for).
1491
1492
  - **The material** is a rule set with `modulus` (MPa) and `poisson`: `pla`, `petg`, `al6061`, `al7075`, `s275`,
1492
1493
  `ss304`, `ti64` come with rulecad. Printed values vary: measure yours.
1493
1494
  - **Settings:** `volume`, the share of the space to fill; `cell`, the grid (smaller is finer and slower: a 140 × 40
1494
- grid takes about half a minute); `filter`, about the thinnest member, in mm.
1495
+ grid takes about half a minute); `filter`, about the thinnest member, in mm. Left out, the filter is a cell and a
1496
+ half, and never under two of the project's printer's lines (the thinnest wall it lays solid): on an X1C's 0.42 mm
1497
+ lines that is 0.84 mm, which only takes over on cells under 0.56 mm.
1498
+ - **At a design's anchors:** any region, support or load can take `"anchor": "plate.pivot"` in place of `at`: the
1499
+ anchor of another design in the project, where it is as that design is built (x and y of it in a flat problem; a
1500
+ cylinder lies along the anchor's axis unless it names one, and an anchor with a `rotate` points along its z turned by
1501
+ it, as an assembly reads it). The problem then follows the design: move the plate's
1502
+ pivot and the support, the boss round it and the result move with it. A design built from this problem can't be
1503
+ named (it would need the result to be built): name the part it is fixed to.
1495
1504
  - **Or a stress limit instead of a volume:** `"stress": "pla.strength / 3"` (MPa) finds the lightest layout that keeps
1496
1505
  every cell's von Mises stress under it, which rounds off the sharp inside corners where cracks start. It takes about
1497
1506
  a thousand steps, each with two solves, so it's slower: give it a coarse cell first. Give supports and loads some
@@ -1502,7 +1511,9 @@ with numbers as expressions like an object's (schema: `schemas/problem.schema.js
1502
1511
 
1503
1512
  `cad optimise <project>/<problem>` runs it, reports how far each load case moves its load and the stiffness that
1504
1513
  gives, and draws the layout in `.preview/`. The result is kept, keyed by everything it's made from, so it's only
1505
- worked out again when something it depends on changes.
1514
+ worked out again when something it depends on changes. `cad why <project>/<object>.<problem variable>` names what
1515
+ that is: the problem file, its rule sets and values, the parts and anchors it reads, where its filter came from, and
1516
+ the file the result is kept in.
1506
1517
 
1507
1518
  A 3D result with a build direction is made printable before it's drawn: built up layer by layer from the bed, every
1508
1519
  cell that nothing holds up (an icicle, a loose bit, a sheet hanging under an edge: whatever the optimiser's smooth
@@ -1519,6 +1530,13 @@ dropped, and `cad check` tests the part for one piece and nothing starting in mi
1519
1530
  the densities as they change (a 3D part as a surface you can turn, and from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
1520
1531
  It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
1521
1532
 
1533
+ Every run is kept to watch again. `cad optimise` writes `.preview/<project>/<problem>-run.html`: the same page,
1534
+ reading its steps from the file, so it opens with no server and can be sent to someone. Drag the slider or the chart
1535
+ to any step. `cad preview <project>/problems/<problem>` (or the file's path) draws the result and writes that page.
1536
+ A result made without its steps recorded (by building a design that reads it) shows its end and each step's
1537
+ compliance; `cad preview <project>/problems/<problem> --fresh` runs it again to record the steps, and `--watch`
1538
+ shows the run live. A 3D run shows its three views; the turning surface needs the live view.
1539
+
1522
1540
  A design uses it through a variable of type `problem`, which picks a problem by name:
1523
1541
 
1524
1542
  ```json
@@ -1575,6 +1593,11 @@ regions exactly. The surface is a big mesh, so set the object's `"engine": "mani
1575
1593
  surface is also kept within the printer's overhang limit: faces smoothing tipped past it are tipped back. An
1576
1594
  `analysis` of a solid part voxelises it on the problem's grid.
1577
1595
 
1596
+ The surface comes out with many small triangles. `"outline": { "reduce": 0.1 }` thins them: the surface stays within
1597
+ 0.1 mm of where it was drawn (a quarter of an X1C's print line), closed, with no more overhang and no new tips, and
1598
+ `cad optimise` says how many triangles it had and has. On the bracket bench's printable result that took 75,592
1599
+ triangles to 21,124 and 27.808 cm³ to 27.806 cm³, a quarter of the size in a file or a link. It is off unless given.
1600
+
1578
1601
  A part prints in one orientation and is loaded in another. Draw it as it prints, and turn it back for its analysis:
1579
1602
  `"rotate"` (degrees about x, then y, then z, as JSCAD's `rotate`) then `"move"` (mm) put it in the problem's frame.
1580
1603
  Both take expressions, so a variant can lie the part down:
package/bin/cad.mjs CHANGED
@@ -18,12 +18,12 @@ import { valuesOf, why } from '../lib/explain.mjs';
18
18
  import { errorData, near } from '../lib/errors.mjs';
19
19
  import { schemaFindings } from '../lib/schema.mjs';
20
20
  import { readJson } from '../lib/host.mjs';
21
- import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
21
+ import { optimised, readProblem, analysePart, picture, problemFile, densitiesKey } from '../lib/optimise.mjs';
22
22
  import { evaluate } from '../lib/rules.mjs';
23
23
  import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue, parseSetting, newProject, setProject, newAssembly, newObject, setInAssembly, removeFromAssembly, moveInAssembly } from '../lib/edit.mjs';
24
24
  import { setAt } from '../lib/jsonedit.mjs';
25
25
  import { threemf, slotOf } from '../lib/threemf.mjs';
26
- import { liveView } from '../lib/live.mjs';
26
+ import { liveView, recorder, endOnly } from '../lib/live.mjs';
27
27
  import { checkSets, drawSet, draftSet, draftPart, draftParts } from '../lib/sheet.mjs';
28
28
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
29
29
 
@@ -87,7 +87,10 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
87
87
  assembly with a motor or gears: the drive turning them, cut across the shafts [--turns n]
88
88
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
89
89
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
90
- [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
90
+ [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button];
91
+ each run is kept to watch again: <problem>-run.html in .preview/
92
+ cad preview <project>/problems/<problem> a problem's result and its run, step by step, as a page that needs no
93
+ server (or the run live, with --watch [port])
91
94
  cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
92
95
  cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
93
96
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
@@ -231,7 +234,7 @@ const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
231
234
  const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
232
235
  // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
233
236
  // densities, a 3D one as the preview's views of its surface
234
- async function optimiseProblem(ref) {
237
+ async function optimiseProblem(ref, { preview: previewing = false } = {}) {
235
238
  const [project, name] = String(ref).split('/');
236
239
  if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
237
240
  const file = problemFile(project, name.split(':')[0]);
@@ -246,8 +249,10 @@ async function optimiseProblem(ref) {
246
249
  const view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
247
250
  if (view) say(`watching at ${view.url}`);
248
251
  let r;
252
+ const rec = recorder(); // each step kept, so the run can be watched again (cad preview <project>/problems/<name>)
249
253
  try {
250
254
  r = await optimised(project, name, { fresh: !!opt('fresh') || !!view, onStep: (s) => {
255
+ rec.step(s);
251
256
  if (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}`);
252
257
  if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
253
258
  } });
@@ -269,19 +274,28 @@ async function optimiseProblem(ref) {
269
274
  fs.mkdirSync(path.dirname(out), { recursive: true });
270
275
  fs.writeFileSync(out, picture(r, { title: r.title, lines }));
271
276
  }
277
+ // The run, to watch again: kept by the densities' key when it was recorded here, else its end alone
278
+ const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, kept = paths.cache('runs', `${densitiesKey(p.problem)}.html`);
279
+ if (rec.steps()) { fs.mkdirSync(path.dirname(kept), { recursive: true }); fs.writeFileSync(kept, rec.page(`cad optimise ${ref}`, done)); }
280
+ const run = paths.preview(project, `${name.replace(':', '-')}-run.html`), recorded = fs.existsSync(kept);
281
+ fs.mkdirSync(path.dirname(run), { recursive: true });
282
+ fs.writeFileSync(run, recorded ? fs.readFileSync(kept, 'utf8') : endOnly(`cad optimise ${ref}`, r, `${done} (its steps weren't recorded: run it again with --fresh to watch them)`));
272
283
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
273
284
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
274
285
  for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
275
286
  if (r.mechanism) console.log(` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`);
276
- if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
287
+ if (r.stress && r.mechanism) console.log(` peak stress ${sig(r.stress.peak)} MPa at its input force${r.stress.strain != null ? ` (strain ${sig(r.stress.strain * 100)}%)` : ''}, the limit ${sig(r.stress.limit)} MPa${r.stress.strainLimit != null ? ` (${sig(r.stress.strainLimit * 100)}%)` : ''}: it reaches the limit at ${sig(r.stress.force)} N of push, its output then ${sig(r.stress.travel)} mm along`);
288
+ else if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
277
289
  if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
278
290
  else 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)`);
291
+ if (r.reduced) console.log(` ${r.reduced.before} triangles reduced to ${r.reduced.after} (${fmt(r.reduced.after / r.reduced.before * 100)}%), the surface kept within ${fmt(r.reduced.tolerance)} mm`);
279
292
  console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
280
293
  if (r.process) console.log(` ${processLine(r)}`);
281
294
  if (r.symmetry || r.extrude) console.log(` ${[r.symmetry?.mirror ? `mirrored across ${[...r.symmetry.mirror].join(' and ')}` : '', r.symmetry?.turns ? `the same each ${r.symmetry.turns === 4 ? 'quarter' : 'half'} turn about ${r.symmetry.axis || 'z'}` : '', r.extrude ? `one section along ${r.extrude}` : ''].filter(Boolean).join(', ')}`);
282
295
  if (r.grey > 0.1) console.log(` warning: ${greyLine(r)}`);
283
296
  if (r.voids?.length) { console.log(` error: ${voidsLine(r)}`); process.exitCode = 1; }
284
297
  console.log(out);
298
+ if (previewing) console.log(`${run}\n ${recorded ? `the run, step by step: open it to watch it again (${r.steps} steps)` : 'the run\'s end only: its steps weren\'t recorded (cad preview --fresh runs it again and records them)'}`);
285
299
  }
286
300
  // How a milled or cast result is made, and its undercuts (none, unless an avoid region or the space's own shape sits
287
301
  // behind material: the optimiser keeps every cell as solid as those on its way out, but can't fill a cell it mustn't)
@@ -527,6 +541,9 @@ async function main() {
527
541
  if (cmd === 'add') return editAssembly(pos[1], pos[2]);
528
542
  if (cmd === 'remove' || cmd === 'move') return removeOrMove(cmd, ref, pos[2]);
529
543
  if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
544
+ // A problem file's preview: its result drawn, and its run to watch again (or live, with --watch)
545
+ const problemRef = /^(?:projects[\\/])?([^\\/]+)[\\/]problems[\\/]([^\\/:]+?)(?:\.json)?(:[^\\/]+)?$/.exec(ref || '');
546
+ if (cmd === 'preview' && problemRef) return await optimiseProblem(`${problemRef[1]}/${problemRef[2]}${problemRef[3] || ''}`, { preview: true });
530
547
  if (isAssembly(ref)) return assembly(cmd, ref);
531
548
  const [base, at] = ref.split('@');
532
549
  const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
@@ -763,6 +780,16 @@ async function explainValue(ref) {
763
780
  const where = n.via ? ` (${n.object})` : '';
764
781
  console.log(`${pad}${n.name} = ${fmt(n.value)}${n.unit ? ` ${n.unit}` : ''}${n.expr ? ` = ${n.expr}` : ''}${where}${n.seen ? ' (above)' : ''}${about}`);
765
782
  if (!n.seen && n.rule && !pad) console.log(` ${n.rule}`);
783
+ if (n.problem) { // the result a problem variable picks, and what it is made from
784
+ const q = n.problem, vals = Object.entries(q.variables);
785
+ console.log(`${pad} optimised from ${q.file}: ${q.title}, ${q.material}${q.set ? `, with ${Object.entries(q.set).map(([k, v]) => `${k} = ${v}`).join(', ')}` : ''}`);
786
+ console.log(`${pad} rule sets: ${q.uses.join(', ')}`);
787
+ if (vals.length) console.log(`${pad} its values: ${vals.map(([k, v]) => `${k} = ${typeof v === 'number' ? fmt(v) : v}`).join(', ')}`);
788
+ if (q.parts.length) console.log(`${pad} parts read: ${q.parts.join(', ')}`);
789
+ if (q.anchors.length) console.log(`${pad} anchors read: ${q.anchors.map((a) => `${a.anchor} at (${a.at.map(fmt).join(', ')})`).join(', ')}`);
790
+ console.log(`${pad} filter ${fmt(q.filter.value)} mm: ${q.filter.from}`);
791
+ console.log(`${pad} ${q.made ? `kept in ${q.densities}` : `not made yet (cad optimise ${n.object.split('/')[0]}/${q.problem}); it will be kept in ${q.densities}`}: made again only when one of these, or the solver, changes`);
792
+ }
766
793
  for (const c of n.reads || []) line(c, `${pad} `);
767
794
  };
768
795
  line(tree, '');
package/lib/explain.mjs CHANGED
@@ -1,7 +1,23 @@
1
1
  // What an object's numbers are, and why: `cad values` and `cad why`. A value's explanation is the tree of names its
2
2
  // expression reads, down to the rules (each with its kind and source), following other objects' values into their own
3
3
  // designs (link.l = keyboard.link_l, explained in the keyboard).
4
+ import path from 'node:path';
4
5
  import { locate, build, isObjectRef } from './design.mjs';
6
+ import { WS, paths } from './workspace.mjs';
7
+ import { host } from './host.mjs';
8
+
9
+ /**
10
+ * What an optimised result is made from, for a problem variable: the problem file, its title and material, the rule
11
+ * sets it uses, its own values, the parts and anchors of other designs it reads, where its filter came from, and the
12
+ * file its densities are kept in (made, or not yet). Change any of these and the result is made again; nothing else.
13
+ * @param {string} project @param {string} ref the problem, name or name:variant
14
+ */
15
+ export async function problemInputs(project, ref) {
16
+ const { readProblem, densitiesKey } = await import('./optimise.mjs'), r = await readProblem(project, ref);
17
+ const kept = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
18
+ return { problem: ref, file: path.relative(WS, r.file).split(path.sep).join('/'), title: r.title, material: r.material.name, ...r.inputs,
19
+ densities: path.relative(WS, kept).split(path.sep).join('/'), made: host.exists(kept) };
20
+ }
5
21
 
6
22
  /**
7
23
  * An object's own variables, resolved: name, value, unit, expression and rule (all of them, or the names given).
@@ -34,6 +50,8 @@ export async function why(ref, name, { depth = 12 } = {}) {
34
50
  const from = set && (b.object.uses || []).find((u) => isObjectRef(u) && u.split('/').pop().split(/[:@]/)[0] === set);
35
51
  if (from && d > 0) return { ...(await node(from.split(/[:@]/)[0], rest, d - 1)), via: `${r}:${n}` };
36
52
  out.reads = d > 0 ? await Promise.all((b.deps?.[n] || []).map((m) => node(r, m, d - 1))) : [];
53
+ // A problem variable: the optimised result it picks, and what that is made from
54
+ if (b.object.variables?.[n]?.type === 'problem' && e.value && e.value !== 'none') out.problem = await problemInputs(r.split('/')[0], e.value);
37
55
  return out;
38
56
  };
39
57
  return node(ref, name, depth);
package/lib/fittings.mjs CHANGED
@@ -9,7 +9,7 @@ import crypto from 'node:crypto';
9
9
  import * as frames from '@rulecad/frames';
10
10
  const { bracketModel, bracket, plateModel, plate } = frames;
11
11
  import { host } from './host.mjs';
12
- import { paths } from './workspace.mjs';
12
+ import { paths, RULE_DIRS } from './workspace.mjs';
13
13
  import { named } from './parts.mjs';
14
14
  import { givenFor } from './frames.mjs';
15
15
  import { peekRuleSet } from './rules.mjs';
@@ -77,7 +77,25 @@ export function plasticNamed(raw, where = 'the project') {
77
77
  let set = null; try { set = peekRuleSet(m); } catch {}
78
78
  const lacks = ['strength', 'modulus', 'density'].filter((k) => !(typeof set?.rules?.[k]?.value === 'number'));
79
79
  if (set && !lacks.length) return set;
80
- throw new Error(`${where}: its material is ${JSON.stringify(raw)}, and printed fittings are sized from their plastic's strength, modulus and density: ${set ? `rules/${m}.json gives no ${lacks.join(', ')}` : `the kit has pla and petg, and there is no rules/${m}.json`}. Give rules/${m}.json with all three, or set the material to pla or petg`);
80
+ const have = plastics().join(', ');
81
+ throw new Error(`${where}: its material is ${JSON.stringify(raw)}, and printed fittings are sized from their plastic's strength, modulus and density: ${set ? `rules/${m}.json gives no ${lacks.join(', ')}` : `the kit and this workspace have rule sets for ${have}, and there is no rules/${m}.json`}. Give rules/${m}.json with all three, or set the material to one of ${have}`);
82
+ }
83
+
84
+ /**
85
+ * The plastics a project can name: the rule sets (the workspace's rules/, then the kit's) that give strength, modulus,
86
+ * density and modulus_z, the modulus across a print's layers, which only a printed plastic's set gives.
87
+ * @returns {string[]} their names, sorted
88
+ */
89
+ export function plastics() {
90
+ const out = new Set();
91
+ for (const d of RULE_DIRS) {
92
+ let files = []; try { files = fs.readdirSync(d).filter((f) => f.endsWith('.json')); } catch { continue; }
93
+ for (const f of files) {
94
+ let r; try { r = JSON.parse(fs.readFileSync(path.join(d, f), 'utf8')).rules; } catch { continue; }
95
+ if (['strength', 'modulus', 'density', 'modulus_z'].every((k) => typeof r?.[k]?.value === 'number')) out.add(f.slice(0, -5));
96
+ }
97
+ }
98
+ return [...out].sort();
81
99
  }
82
100
 
83
101
  /**
package/lib/live.mjs CHANGED
@@ -103,10 +103,10 @@ function plot() {
103
103
  ys.forEach((v, k) => { const x = k / (n - 1) * w, y = h - 8 - (v - lo) / (hi - lo || 1) * (h - 28); k ? c.lineTo(x, y) : c.moveTo(x, y); });
104
104
  c.stroke();
105
105
  };
106
- line(history.compliance, false, '#6cf'); line(history.change, true, '#fc6');
106
+ line(history.compliance, false, '#6cf'); if (history.change.length) line(history.change, true, '#fc6');
107
107
  const x = shown / (n - 1) * w; c.strokeStyle = '#fff8'; c.lineWidth = 1; c.beginPath(); c.moveTo(x, 0); c.lineTo(x, h); c.stroke();
108
108
  c.font = '12px system-ui'; c.fillStyle = '#6cf'; c.fillText('compliance, N·mm: ' + fig(history.compliance[0]) + ' to ' + fig(history.compliance.at(-1)), 8, 14);
109
- c.fillStyle = '#fc6'; c.textAlign = 'right'; c.fillText('change (log scale): ' + fig(history.change[0]) + ' to ' + fig(history.change.at(-1)), w - 8, 14); c.textAlign = 'left';
109
+ if (history.change.length) { c.fillStyle = '#fc6'; c.textAlign = 'right'; c.fillText('change (log scale): ' + fig(history.change[0]) + ' to ' + fig(history.change.at(-1)), w - 8, 14); c.textAlign = 'left'; }
110
110
  }
111
111
  // The 3D view's step: remembered, so the 3D script picks it up when it loads (it loads after the first steps arrive)
112
112
  const want3d = (n, grid) => { window.wanted3d = [n, grid]; window.model3d?.(n, grid); };
@@ -189,6 +189,56 @@ window.model3d = (n, grid) => { if (!box.hidden && grid) load(n, grid); };
189
189
  if (window.wanted3d) window.model3d(...window.wanted3d);
190
190
  </script>`;
191
191
 
192
+ /**
193
+ * A run kept to watch again: each step's densities (as the live view draws them) and its numbers, recorded as the
194
+ * optimiser goes, then written as one page that needs no server: the live view's own page, its steps read from the
195
+ * file. A 3D run shows its three views (the turning surface needs the live view's server).
196
+ * @returns {{ step: (s: object) => void, steps: () => number, page: (title: string, done: string) => string }}
197
+ */
198
+ export function recorder() {
199
+ const frames = [], history = { compliance: [], change: [] }, t0 = Date.now(), times = [];
200
+ return {
201
+ step(s) {
202
+ const now = Date.now(); times.push(now);
203
+ const last = times.slice(-11), perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null, { nx, ny, nz, h } = s.grid;
204
+ frames.push({ index: frames.length, grid: { nx, ny, nz, h }, step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, travel: s.travel,
205
+ elapsed: (now - t0) / 1000, perStep, views: views(s.density, s.grid).map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })) });
206
+ history.compliance.push(s.compliance); history.change.push(s.change);
207
+ },
208
+ steps: () => frames.length,
209
+ page: (title, done) => replay(title, { history, frames, done }),
210
+ };
211
+ }
212
+
213
+ /**
214
+ * The page of a run that wasn't recorded step by step (made by a design's build, or before runs were kept): its end
215
+ * alone, with the compliance of each step where the result has it.
216
+ * @param {string} title @param {{ grid: object, density: ArrayLike<number>, history?: number[], steps: number, compliance: number }} r @param {string} done
217
+ */
218
+ export function endOnly(title, r, done) {
219
+ const { nx, ny, nz, h } = r.grid;
220
+ const frame = { index: Math.max(0, (r.history?.length || 1) - 1), grid: { nx, ny, nz, h }, step: r.steps, steps: r.steps, compliance: r.compliance, change: 0, beta: '', elapsed: r.seconds ?? null, perStep: null,
221
+ views: views(r.density, r.grid).map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })) };
222
+ return replay(title, { history: { compliance: r.history?.length ? r.history : [r.compliance], change: [] }, frames: [frame], done });
223
+ }
224
+
225
+ // The live view's page with its server's two answers read from the run instead: the stream of steps (one message: the
226
+ // whole history, the last step and how it ended) and any step asked for (the nearest one kept at or before it). Long
227
+ // runs keep every few steps, so the page stays under about 8 MB.
228
+ function replay(title, { history, frames, done }) {
229
+ const size = frames.reduce((t, f) => t + f.views.reduce((u, v) => u + v.image.length, 0), 0), every = Math.max(1, Math.ceil(size / 8e6));
230
+ const kept = frames.filter((f, k) => k % every === 0 || k === frames.length - 1);
231
+ const run = JSON.stringify({ history, frames: kept, done }).replace(/</g, '\\u003c');
232
+ const shim = `<script>
233
+ const RUN = ${run};
234
+ window.EventSource = class { constructor() { setTimeout(() => this.onmessage?.({ data: JSON.stringify({ about: [['Recorded', 'a run kept to watch again: drag the slider or the chart to any step']], history: RUN.history, frame: RUN.frames.at(-1), done: RUN.done }) }), 0); } close() {} };
235
+ window.fetch = async (u) => { const k = Number(String(u).replace('frame/', '')); let f = RUN.frames[0]; for (const x of RUN.frames) if (x.index <= k) f = x; return { ok: false, json: async () => f }; };
236
+ </script>
237
+ <style>#model,#hint{display:none!important}#stop{display:none}</style>
238
+ `;
239
+ return page(title).split('<script type="importmap">')[0].replace('<script>', `${shim}<script>`);
240
+ }
241
+
192
242
  const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // three's build files, for the 3D view
193
243
 
194
244
  if (!isMainThread && workerData?.flag) {
package/lib/optimise.mjs CHANGED
@@ -7,12 +7,14 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
+ import { AsyncLocalStorage } from 'node:async_hooks';
10
11
  import { host, readJson } from './host.mjs';
11
12
  import { paths, printerOf } from './workspace.mjs';
12
13
  import { resolve, evaluate } from './rules.mjs';
13
14
  import { located } from './errors.mjs';
14
- import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, undercuts, voids, grey } from '@rulecad/topopt';
15
+ import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey } from '@rulecad/topopt';
15
16
  import { islands } from '@rulecad/printcheck';
17
+ import { turn } from '@rulecad/model-link';
16
18
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
17
19
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
18
20
 
@@ -25,6 +27,18 @@ export const hasProblem = (project, ref) => host.exists(problemFile(project, Str
25
27
  * @param {string} project @param {string} ref name, or name:variant
26
28
  */
27
29
  export async function readProblem(project, ref) {
30
+ // The problems being read above this one, each with the design it reads that is built from the next: a problem met
31
+ // again on that chain is refused by name, since each would need the other's result before its own could be made
32
+ const name = String(ref).split(':')[0], chain = reading.getStore() || [], key = `${project}/${name}`;
33
+ if (chain.some((c) => c.key === key)) {
34
+ const from = chain.slice(chain.findIndex((c) => c.key === key)), steps = from.map((c, i) => `${c.name} reads ${c.object}, built from ${(from[i + 1] || { name })?.name}`);
35
+ throw new Error(`${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`);
36
+ }
37
+ const link = { key, name, object: null };
38
+ return reading.run([...chain, link], () => readOne(project, ref, link));
39
+ }
40
+ const reading = new AsyncLocalStorage();
41
+ async function readOne(project, ref, link) {
28
42
  const [name, variant] = String(ref).split(':'), file = problemFile(project, name);
29
43
  if (!host.exists(file)) throw new Error(`no problem "${name}" (projects/${project}/problems/${name}.json)`);
30
44
  const p = readJson(file);
@@ -37,27 +51,67 @@ export async function readProblem(project, ref) {
37
51
  if (typeof v !== 'number') throw new Error(`${path.basename(file)}: "${n}" isn't a number here (variables: ${Object.keys(p.variables || {}).join(', ')})`);
38
52
  return v;
39
53
  };
40
- const ev = (x) => evaluate(x, lookup), pt = (a) => a.map(ev);
54
+ const ev = (x) => evaluate(x, lookup), pt = (a) => a.map(ev), flat = p.thickness != null;
55
+ // Another design in the project, built once with its defaults, for its parts and anchors. One whose default is built
56
+ // from this very problem is refused: it would need the result before the result could be made.
57
+ const designs = new Map();
58
+ const design = (object, what) => { // (the build kept as it starts: regions are read side by side)
59
+ if (!designs.has(object)) designs.set(object, (async () => {
60
+ const { build, locate, readObject } = await import('./design.mjs'), d = locate(`${project}/${object}`);
61
+ const own = Object.entries(readObject(d).variables || {}).find(([, v]) => v.type === 'problem' && String(v.value).split(':')[0] === name);
62
+ if (own) throw new Error(`${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`);
63
+ const chain = reading.getStore(); // this problem's place on the chain names the design it reads
64
+ return reading.run([...chain.slice(0, -1), { ...link, object }], () => build(d));
65
+ })());
66
+ return designs.get(object);
67
+ };
41
68
  // A named part of another design in the project, as triangles (built with its defaults)
42
69
  const parts = new Map();
43
70
  const part = async (ref) => {
44
71
  if (!parts.has(ref)) {
45
- const [object, partName] = ref.split('.'), { build, locate } = await import('./design.mjs');
46
- const b = await build(locate(`${project}/${object}`)), found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
72
+ const [object, partName] = ref.split('.'), b = await design(object, `the part "${ref}"`);
73
+ const found = partName ? b.parts.find((q) => q.name === partName) : b.parts.find((q) => q.role !== 'support');
47
74
  if (!found) throw new Error(`${path.basename(file)}: ${object} has no part "${partName}" (parts: ${b.parts.map((q) => q.name).join(', ')})`);
48
75
  parts.set(ref, found.triangles);
49
76
  }
50
77
  return parts.get(ref);
51
78
  };
79
+ // An anchor of another design (object.anchor): where it is and its axis, in that design's frame, worked out from its
80
+ // values as built. A region at an anchor follows the design: move the anchor, and the problem (and its result) moves.
81
+ const anchors = new Map();
82
+ const anchor = async (ref) => {
83
+ if (!anchors.has(ref)) {
84
+ const [object, a, ...more] = String(ref).split('.');
85
+ if (!object || !a || more.length) throw new Error(`${path.basename(file)}: name an anchor as <object>.<anchor> (got "${ref}")`);
86
+ const b = await design(object, `the anchor "${ref}"`), spec = b.object.anchors?.[a];
87
+ if (!spec) throw new Error(`${path.basename(file)}: ${object} has no anchor "${a}" (anchors: ${Object.keys(b.object.anchors || {}).join(', ') || 'none'})`);
88
+ const num = (x) => evaluate(x, (n) => {
89
+ const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values);
90
+ if (typeof v !== 'number') throw new Error(`${path.basename(file)}: the anchor "${ref}" reads "${n}", which isn't one of ${object}'s numbers`);
91
+ return v;
92
+ });
93
+ // 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
94
+ const m = spec.rotate && turn(spec.rotate.map(num)), axis = m ? [m[2], m[6], m[10]].map((c) => (Math.abs(c) < 1e-12 ? 0 : c)) : (spec.axis || [0, 0, 1]).map(num);
95
+ anchors.set(ref, { anchor: ref, at: (spec.at || [0, 0, 0]).map(num), axis });
96
+ }
97
+ return anchors.get(ref);
98
+ };
52
99
  // The build direction: a direction ('+z'), or a variable holding one
53
100
  const overhang = p.overhang ? (typeof values[p.overhang] === 'string' ? values[p.overhang] : p.overhang) : null;
54
101
  // A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
55
102
  const point = (t) => { const up = overhang && overhang !== 'none' ? overhang : '+z'; return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t; };
56
103
  const region = async (r) => {
104
+ if (r.anchor) { // at an anchor: its place (x and y in a flat problem), and a cylinder along the anchor's axis unless it names one
105
+ if (r.at) throw new Error(`${path.basename(file)}: a region at an anchor ("${r.anchor}") takes no at: the anchor places it`);
106
+ const a = await anchor(r.anchor), along = a.axis.map((c) => Math.abs(c) > 1e-9);
107
+ if (r.length != null && !r.axis && along.filter(Boolean).length !== 1) throw new Error(`${path.basename(file)}: the anchor "${r.anchor}" points along [${a.axis.map((c) => round(c, 3)).join(', ')}], not along x, y or z: give the cylinder an axis`);
108
+ return region({ ...r, anchor: undefined, at: flat ? a.at.slice(0, 2) : a.at, ...(r.length != null && !r.axis ? { axis: 'xyz'[along.indexOf(true)] } : {}) });
109
+ }
57
110
  if (r.part) { // with where it is (its box's centre), for a load's or support's resultant
58
111
  const triangles = await part(r.part), lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
59
112
  for (const t of triangles) for (const q of t) for (let a = 0; a < 3; a++) { lo[a] = Math.min(lo[a], q[a]); hi[a] = Math.max(hi[a], q[a]); }
60
- return { triangles, part: r.part, at: lo.map((x, a) => (x + hi[a]) / 2) };
113
+ const at = lo.map((x, a) => (x + hi[a]) / 2);
114
+ return flat ? { triangles, part: r.part, at: at.slice(0, 2), flat: true } : { triangles, part: r.part, at }; // flat: its section halfway up
61
115
  }
62
116
  if (r.points) return { points: r.points.map(pt) };
63
117
  if (r.size) return { at: pt(r.at), size: r.size.map(ev) };
@@ -67,14 +121,17 @@ export async function readProblem(project, ref) {
67
121
  const regions = (list) => Promise.all([list || []].flat().map(region));
68
122
  const m = values[p.material];
69
123
  if (typeof m?.modulus !== 'number' || typeof m?.poisson !== 'number') throw new Error(`material ${p.material}: its rule set needs modulus (MPa) and poisson`);
70
- const space = await regions(p.space), dim = space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3 ? 3 : 2;
124
+ // The filter's radius is about the thinnest member: a cell and a half unless the problem gives one, and never under two
125
+ // 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)
126
+ const printer = printerOf(project), line = printer ? resolve({ uses: [printer] }).values[printer]?.line : null, lines = typeof line === 'number' ? 2 * line : 0;
127
+ const space = await regions(p.space), dim = flat ? 2 : space[0].triangles || space[0].length != null || (space[0].size || space[0].at)?.length === 3 ? 3 : 2;
71
128
  const problem = {
72
129
  space, keep: await regions(p.keep), avoid: await regions(p.avoid),
73
130
  supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
74
131
  loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
75
132
  cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
76
- material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}),
77
- ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
133
+ material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}), ...(p.strain != null ? { strain: ev(p.strain) } : {}),
134
+ ...(p.filter != null ? { filter: ev(p.filter) } : lines > ev(p.cell) * 1.5 ? { filter: lines } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
78
135
  ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
79
136
  ...(overhang && overhang !== 'none' ? { overhang } : {}),
80
137
  // How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
@@ -85,12 +142,17 @@ export async function readProblem(project, ref) {
85
142
  ...(p.input_spring != null ? { input_spring: ev(p.input_spring) } : {}),
86
143
  };
87
144
  if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
88
- const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2, fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25 }; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
145
+ const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2, fine: p.outline?.fine != null ? ev(p.outline.fine) : 1.25, ...(p.outline?.reduce != null ? { reduce: ev(p.outline.reduce) } : {}) }; // fine: the cells a printable solid is cleaned and drawn on, mm (its own cells if smaller)
89
146
  // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
90
147
  // (outline.tip: faces the smoothing left steeper than the limit are tipped back to it too; off unless asked, since
91
148
  // tipped corners leave dips that slice as islands, and the layers step out no further for it)
92
149
  if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5, layer: pr?.layer ?? 0.2, line: pr?.line ?? 0.42, ...(p.outline?.tip ? { tip: true } : {}) }; problem.bridge = outline.overhang.bridge; } // (the optimiser bridges half that)
93
- return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical, voids: p.voids || 'allowed' };
150
+ // What the result is made from, for cad why: the rule sets, the problem's own values, the parts and anchors of other
151
+ // designs it reads, and where its filter came from
152
+ const inputs = { uses, variables: Object.fromEntries(Object.keys(p.variables || {}).map((k) => [k, values[k]])), ...(variant ? { set: p.variants[variant] } : {}),
153
+ parts: [...parts.keys()].sort(), anchors: [...anchors.values()].sort((a, b) => (a.anchor < b.anchor ? -1 : 1)).map(({ anchor: a, at }) => ({ anchor: a, at: at.map((c) => round(c, 4)) })),
154
+ filter: p.filter != null ? { value: problem.filter, from: `the problem: ${p.filter}` } : problem.filter ? { value: problem.filter, from: `two of ${printer}'s lines (2 × ${line} mm), more than a cell and a half` } : { value: round(problem.cell * 1.5), from: 'a cell and a half' } };
155
+ return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical, inputs, voids: p.voids || 'allowed' };
94
156
  }
95
157
 
96
158
  /**
@@ -220,8 +282,14 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
220
282
  }
221
283
  }
222
284
  const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
223
- const { vertices, faces, dropped } = anchored(best, anchors, (fine ?? { grid: spec.grid }).grid.h);
224
- return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(dropped.length ? { dropped } : {}), ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}), ...(cleared ? { cleared } : {}) };
285
+ let { vertices, faces, dropped } = anchored(best, anchors, (fine ?? { grid: spec.grid }).grid.h), reduced = null;
286
+ // Fewer triangles, if asked: within outline.reduce mm of the surface as drawn, closed, and no more overhang or tips
287
+ if (r.outline.reduce != null) {
288
+ const { nx, ny, nz, h } = spec.grid, lo = spec.origin, hi = [lo[0] + nx * h, lo[1] + ny * h, lo[2] + nz * h], before = faces.length;
289
+ ({ vertices, faces } = reduce({ vertices, faces }, { tolerance: r.outline.reduce, lo, hi, ...(ov ? { overhang: { up: ov.up, angle: ov.angle } } : {}) }));
290
+ reduced = { before, after: faces.length, tolerance: r.outline.reduce };
291
+ }
292
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(reduced ? { reduced } : {}), ...(dropped.length ? { dropped } : {}), ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}), ...(cleared ? { cleared } : {}) };
225
293
  })();
226
294
  const result = {
227
295
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.78",
3
+ "version": "0.7.81",
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": {
@@ -58,19 +58,19 @@
58
58
  "url": "https://github.com/JoniBach/rulecad/issues"
59
59
  },
60
60
  "dependencies": {
61
- "@rulecad/variables": "^0.3.5",
61
+ "@rulecad/variables": "^0.3.6",
62
62
  "@rulecad/keyboard-layout": "^0.1.2",
63
63
  "@rulecad/printcheck": "^0.3.3",
64
64
  "@rulecad/fit": "^0.4.0",
65
65
  "@rulecad/model-link": "^0.3.2",
66
66
  "@rulecad/versions": "^0.1.6",
67
- "@rulecad/shapes": "^0.4.6",
68
- "@rulecad/rules": "^0.3.22",
67
+ "@rulecad/shapes": "^0.4.8",
68
+ "@rulecad/rules": "^0.3.23",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
71
  "@rulecad/fea": "^0.2.14",
72
- "@rulecad/topopt": "^0.3.4",
73
- "@rulecad/flexures": "^0.5.4",
72
+ "@rulecad/topopt": "^0.3.6",
73
+ "@rulecad/flexures": "^0.5.12",
74
74
  "@rulecad/gears": "^0.3.4",
75
75
  "@rulecad/motors": "^0.1.6",
76
76
  "@rulecad/fixings": "^0.1.7",
@@ -58,11 +58,15 @@
58
58
  },
59
59
  "stress": {
60
60
  "$ref": "#/$defs/expr",
61
- "description": "A limit on von Mises stress (MPa), such as \"pla.strength / 3\": the lightest layout that keeps every cell under it (Senhora et al. 2020). Give this or a volume"
61
+ "description": "A limit on von Mises stress (MPa), such as \"pla.strength / 3\": the lightest layout that keeps every cell under it (Senhora et al. 2020). Give this or a volume. A mechanism (with output) fills its volume as before and is checked against the limit at its input force: its peak, and the input force and output travel that reach the limit"
62
+ },
63
+ "strain": {
64
+ "$ref": "#/$defs/expr",
65
+ "description": "A strain limit in place of stress, a share of the length (0.02 is 2%), such as \"pla.strength / pla.modulus / 2\": the stress limit is it times the material's modulus. Most use for a mechanism, whose hinges bend"
62
66
  },
63
67
  "filter": {
64
68
  "$ref": "#/$defs/expr",
65
- "description": "Filter radius, mm: about the thinnest member (default 1.5 cells)"
69
+ "description": "Filter radius, mm: about the thinnest member (default a cell and a half, and never under two of the printer's lines)"
66
70
  },
67
71
  "penal": {
68
72
  "$ref": "#/$defs/expr",
@@ -144,6 +148,10 @@
144
148
  "tip": {
145
149
  "type": "boolean",
146
150
  "description": "3D with an overhang direction: faces the smoothing left steeper than the printer's limit are tipped back to it as well (off by default: tipped corners can leave dips that slice as islands, and the sliced overhang is no smaller for it; the bracket example's 160 mm² of lean is the same either way)"
151
+ },
152
+ "reduce": {
153
+ "$ref": "#/$defs/expr",
154
+ "description": "3D: fewer triangles, the surface kept within this many mm of where it was drawn (0.1 is a quarter of a print line), closed, and no more overhang or tips than it had. Off unless given"
147
155
  }
148
156
  }
149
157
  },
@@ -197,7 +205,6 @@
197
205
  "type": "object",
198
206
  "additionalProperties": false,
199
207
  "required": [
200
- "at",
201
208
  "direction"
202
209
  ],
203
210
  "description": "A mechanism's output: where it should move, along one axis, against a spring. The first load is then the input.",
@@ -206,6 +213,11 @@
206
213
  "$ref": "#/$defs/point",
207
214
  "description": "The centre, mm"
208
215
  },
216
+ "anchor": {
217
+ "type": "string",
218
+ "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$",
219
+ "description": "In place of at: another design's anchor, object.anchor, where it is as that design is built (x and y of it in a flat problem). A cylinder lies along the anchor's axis unless it names one. Move the anchor and the problem moves with it. A design built from this problem can't be named: name what it's fixed to"
220
+ },
209
221
  "r": {
210
222
  "$ref": "#/$defs/expr"
211
223
  },
@@ -243,7 +255,19 @@
243
255
  "label": {
244
256
  "type": "string"
245
257
  }
246
- }
258
+ },
259
+ "anyOf": [
260
+ {
261
+ "required": [
262
+ "at"
263
+ ]
264
+ },
265
+ {
266
+ "required": [
267
+ "anchor"
268
+ ]
269
+ }
270
+ ]
247
271
  },
248
272
  "input_spring": {
249
273
  "$ref": "#/$defs/expr",
@@ -273,6 +297,11 @@
273
297
  "$ref": "#/$defs/point",
274
298
  "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
275
299
  },
300
+ "anchor": {
301
+ "type": "string",
302
+ "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$",
303
+ "description": "In place of at: another design's anchor, object.anchor, where it is as that design is built (x and y of it in a flat problem). A cylinder lies along the anchor's axis unless it names one. Move the anchor and the problem moves with it. A design built from this problem can't be named: name what it's fixed to"
304
+ },
276
305
  "r": {
277
306
  "$ref": "#/$defs/expr",
278
307
  "description": "A circle's or ball's radius, or a cylinder's"
@@ -308,7 +337,7 @@
308
337
  },
309
338
  "part": {
310
339
  "type": "string",
311
- "description": "3D: a named part of another design in the project, as it's built: object.part"
340
+ "description": "A named part of another design in the project, as it's built: object.part. In a flat (2D) problem, its section halfway up (a plate's outline, its holes open)"
312
341
  },
313
342
  "label": {
314
343
  "type": "string"
@@ -337,6 +366,11 @@
337
366
  "$ref": "#/$defs/point",
338
367
  "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
339
368
  },
369
+ "anchor": {
370
+ "type": "string",
371
+ "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$",
372
+ "description": "In place of at: another design's anchor, object.anchor, where it is as that design is built (x and y of it in a flat problem). A cylinder lies along the anchor's axis unless it names one. Move the anchor and the problem moves with it. A design built from this problem can't be named: name what it's fixed to"
373
+ },
340
374
  "r": {
341
375
  "$ref": "#/$defs/expr",
342
376
  "description": "A circle's or ball's radius, or a cylinder's"
@@ -372,7 +406,7 @@
372
406
  },
373
407
  "part": {
374
408
  "type": "string",
375
- "description": "3D: a named part of another design in the project, as it's built: object.part"
409
+ "description": "A named part of another design in the project, as it's built: object.part. In a flat (2D) problem, its section halfway up (a plate's outline, its holes open)"
376
410
  },
377
411
  "label": {
378
412
  "type": "string"
@@ -408,6 +442,11 @@
408
442
  "$ref": "#/$defs/point",
409
443
  "description": "The centre, mm: [x, y] in 2D, [x, y, z] in 3D"
410
444
  },
445
+ "anchor": {
446
+ "type": "string",
447
+ "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$",
448
+ "description": "In place of at: another design's anchor, object.anchor, where it is as that design is built (x and y of it in a flat problem). A cylinder lies along the anchor's axis unless it names one. Move the anchor and the problem moves with it. A design built from this problem can't be named: name what it's fixed to"
449
+ },
411
450
  "r": {
412
451
  "$ref": "#/$defs/expr",
413
452
  "description": "A circle's or ball's radius, or a cylinder's"
@@ -443,7 +482,7 @@
443
482
  },
444
483
  "part": {
445
484
  "type": "string",
446
- "description": "3D: a named part of another design in the project, as it's built: object.part"
485
+ "description": "A named part of another design in the project, as it's built: object.part. In a flat (2D) problem, its section halfway up (a plate's outline, its holes open)"
447
486
  },
448
487
  "label": {
449
488
  "type": "string"
@@ -482,6 +521,11 @@
482
521
  "required": [
483
522
  "stress"
484
523
  ]
524
+ },
525
+ {
526
+ "required": [
527
+ "strain"
528
+ ]
485
529
  }
486
530
  ]
487
531
  }
@@ -27,6 +27,8 @@
27
27
  "properties": {
28
28
  "value": { "type": ["number", "string", "array"], "minItems": 1, "items": { "type": ["number", "string"] }, "description": "A number, an expression, text, or a list of numbers or expressions in the rule's one unit (the lengths a screw is sold in)" },
29
29
  "unit": { "type": "string" },
30
+ "low": { "type": "number", "description": "The lowest it is found at, in the rule's unit (a printed plastic's, which varies with the printer and the spool): at most the value" },
31
+ "high": { "type": "number", "description": "The highest it is found at, in the rule's unit: at least the value" },
30
32
  "rule": { "type": "string" },
31
33
  "kind": { "type": "string", "description": "How far to trust it, most to least: measured, spec, community, default, derived, estimate" },
32
34
  "source": { "type": "string" },