@rulecad/cad 0.7.1 → 0.7.2

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
@@ -90,8 +90,12 @@ variable says which rule it comes from. Follow these steps; they're what makes a
90
90
  `"overhang"` to the way up it will print, so the result needs no supports, and give horizontal bosses and holes a
91
91
  `teardrop` (`"down"`, `"up"`). Draw the part as it prints; if that isn't the problem's frame, give its `analysis` a
92
92
  `rotate` and `move` back. Build with `v.shapes.optimisedSolid(...)` and `"engine": "manifold"`; look at the four views.
93
- - Say plainly that the analysis is coarse and the material values are data-sheet figures: anything that could hurt
94
- someone if it broke needs testing, not just a check.
93
+ - Before reporting numbers for a final shape, verify them: give the `analysis` a smaller `cell` (solids: about a
94
+ third of the problem's) and check the stiffness has settled (`fea.settled`). Report the verified numbers, the safety
95
+ factor, and where the peak stress is.
96
+ - Mark a problem `"critical": true` if the part could hurt someone if it broke. Say plainly that the analysis is a
97
+ design aid and the material values are data-sheet figures: such a part needs testing, recorded under
98
+ `"verification"`, not just a check.
95
99
 
96
100
  ## Talking to the person
97
101
  - Give links as one labelled line (`npx cad link <project>/<object> --md`), never a raw URL. If it says
package/README.md CHANGED
@@ -420,8 +420,36 @@ the problem, and optionally a limit:
420
420
  `cad check` then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak
421
421
  stress against the material's strength, and the part's volume and weight. With `max_deflection` a case that moves
422
422
  further fails; with `volume` a part whose volume is further than `tolerance` (a share) from it fails. A picture goes in
423
- `.preview/`. The analysis is coarse: it's a design aid, not engineering sign-off. A part that could hurt someone if
424
- it failed needs testing.
423
+ `.preview/`.
424
+
425
+ On the problem's own cells the analysis is quick and coarse. A solid part's cubes are filled by the share of each the
426
+ part takes up, so a wall between cell centres still counts, but thin walls on big cubes still come out too stiff when
427
+ they bend. To check a final shape, give the analysis a smaller `cell`:
428
+
429
+ ```json
430
+ "analysis": [{ "problem": "bracket", "cell": 0.8, "min_safety": 3 }]
431
+ ```
432
+
433
+ The part is then analysed on those cells and again on cells a quarter bigger. For each load case, `cad check`
434
+ reports:
435
+ - **Stiffness and its change:** under 5% from the bigger cells and it has settled; more, and the cells are too big.
436
+ - **Peak stress, where it is, and the safety factor:** against the material's strength (its weaker one across a
437
+ print's layers, where the rule set has `strength_z`), and its fatigue strength where it has one. With
438
+ `min_safety`, a case below it fails. Peak stress at a sharp inside corner keeps rising as cells shrink, so read it
439
+ with its change.
440
+ - **The largest movement anywhere, and where.**
441
+
442
+ A report goes in `.preview/` (`<object>-report-<problem>.md`, and `.json`), with what the analysis doesn't cover. A
443
+ solid's analysis is kept in `.cache/analysis/`, so it runs once.
444
+
445
+ **Safety-critical parts.** A problem with `"critical": true` (a pedal, a lever, a bracket that holds people) marks
446
+ every part analysed under it as unverified, until a test or an independent analysis is recorded in the object:
447
+
448
+ ```json
449
+ "verification": [{ "kind": "test", "date": "2026-11-02", "by": "J. Smith", "summary": "20 N straight down, three prints: 0.21 mm, 95 N/mm", "source": "results.json" }]
450
+ ```
451
+
452
+ The analysis is a design aid, not engineering sign-off: anything that could hurt someone if it failed needs testing.
425
453
 
426
454
  ## Boards
427
455
 
package/bin/cad.mjs CHANGED
@@ -157,6 +157,28 @@ function place(triangles, [rx, ry, rz], move) {
157
157
  }));
158
158
  }
159
159
 
160
+ // A part's analysis report, in Markdown: what was analysed, how, each load case's numbers and where, and what it
161
+ // doesn't cover
162
+ function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
163
+ const at = (p) => `(${p.map(fmt).join(', ')})`;
164
+ const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
165
+ const rows = r.cases.map((c) => `| ${c.name} | ${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`);
166
+ return [
167
+ `# ${title}: analysed under ${a.problem}`, '',
168
+ `${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled; peak stress at a sharp inside corner keeps rising as cells shrink, so read it with its change.` : ' On the problem\'s own cells: a quick check. Give the analysis a smaller cell to verify it.'}`, '',
169
+ '| Load case | Force (N) | Moves its load (mm) | Stiffness (N/mm) | Peak stress (MPa) | Safety factor | Largest movement (mm) |',
170
+ '|---|---|---|---|---|---|---|', ...rows, '',
171
+ `Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`, '',
172
+ '## Findings', '', ...found.map((f) => `- ${f.level}: ${f.text}`), '',
173
+ '## Verification', '',
174
+ ...(records.length ? records.map((v) => `- ${v.kind}, ${v.date}${v.by ? `, by ${v.by}` : ''}: ${v.summary}${v.source ? ` (${v.source})` : ''}`) : [r.critical ? '**Unverified.** This part is safety-critical: do not rely on it until a test or an independent analysis is recorded.' : 'None recorded.']), '',
175
+ '## What this doesn\'t cover', '',
176
+ '- The analysis is linear and static, on cubes: a design aid, not engineering sign-off. Stress at sharp inside corners, and where supports and loads are applied, depends on the cell size; compare a finer cell before trusting a peak.',
177
+ '- Material values are data-sheet figures. Printed parts vary with the printer, settings and spool, and are weaker across their layers; measure your own.',
178
+ '- Buckling, impact, creep, heat and wear are not checked.', '',
179
+ ].join('\n');
180
+ }
181
+
160
182
  async function analyses(b, d, tag) {
161
183
  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; };
162
184
  const all = [];
@@ -165,25 +187,61 @@ async function analyses(b, d, tag) {
165
187
  if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
166
188
  // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
167
189
  // then z, as JSCAD's rotate), then moved
168
- const turned = a.rotate || a.move ? place(part.triangles, (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)), (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup))) : part.triangles;
169
- const r = await analysePart(turned, d.project, a.problem), m = r.material, limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
190
+ const turn = (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) || (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
191
+ const turned = turn ? place(part.triangles, (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)), (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup))) : part.triangles;
192
+ const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
193
+ const r = await analysePart(turned, d.project, a.problem, { cell }), m = r.material;
194
+ // A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
195
+ // number changes says whether the cells are small enough. Peak stress at a sharp inside corner never settles (in
196
+ // theory it's endless there), so it's reported, not judged.
197
+ if (cell) {
198
+ const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
199
+ r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: c.stiffness / o.stiffness - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
200
+ }
201
+ const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
202
+ const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
170
203
  let out = null;
171
204
  if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
172
205
  out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
173
206
  fs.mkdirSync(path.dirname(out), { recursive: true });
174
207
  fs.writeFileSync(out, picture({ ...r, ...(await 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`) }));
175
208
  }
176
- const found = r.cases.map((c) => {
177
- const safety = m.strength ? `, peak stress ${sig(c.stress)} MPa (${sig(m.strength / c.stress)}× under ${m.name}'s strength; coarse)` : '';
178
- const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm${safety}`;
209
+ // Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
210
+ // its fatigue strength where it has one
211
+ const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null, weaker = m.strength_z != null && m.strength_z < m.strength;
212
+ const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
213
+ const at = (p) => `(${p.map(fmt).join(', ')})`;
214
+ const found = r.cases.flatMap((c) => {
215
+ const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
216
+ const text = `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
179
217
  const values = { deflection: c.deflection, force: c.force, stiffness: c.stiffness, stress: c.stress, ...(limit != null ? { limit } : {}) };
180
- 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, ...(out ? { picture: path.relative(WS, out) } : {}) } };
218
+ const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
219
+ const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
220
+ const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
221
+ const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
222
+ text: `${a.problem} ${c.name}: stiffness ${c.change.stiffness >= 0 ? '+' : ''}${fmt(c.change.stiffness * 100)}% from ${fmt(c.change.cell)} mm cells${Math.abs(c.change.stiffness) <= 0.05 ? ', settled (within 5%)' : ': not settled, use a smaller cell'}` }] : [];
223
+ return [
224
+ { level: limit == null ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
225
+ { level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
226
+ values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
227
+ ];
181
228
  });
182
229
  const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
183
230
  if (a.volume != null) {
184
231
  const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
185
232
  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 } });
186
233
  } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
234
+ // A safety-critical part stays unverified until a test or an independent analysis is recorded against it
235
+ const records = b.object.verification || [];
236
+ if (r.critical) found.push(records.length
237
+ ? { level: 'pass', text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`, code: 'fea.verified', values: { records } }
238
+ : { level: 'warn', text: `${a.problem} is safety-critical and unverified: rulecad's analysis is a design aid. Test it, or have it analysed independently, and record that under "verification"`, code: 'fea.unverified' });
239
+ // The report: everything above, with where, written next to the previews
240
+ const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
241
+ fs.mkdirSync(path.dirname(report), { recursive: true });
242
+ fs.writeFileSync(report, reportText({ turn, object: `${d.project}/${d.name}${tag}`, title: b.object.title || d.name, version: b.object.version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }));
243
+ fs.writeFileSync(report.replace(/\.md$/, '.json'), JSON.stringify({ object: `${d.project}/${d.name}${tag}`, version: b.object.version, problem: a.problem, critical: r.critical, verification: records, material: { name: m.name, modulus: m.modulus, strength: m.strength, ...(m.strength_z != null ? { strength_z: m.strength_z } : {}), ...(m.fatigue != null ? { fatigue: m.fatigue } : {}) }, grid: r.grid, volume: r.volume, cases: r.cases, findings: found.map(({ level, code, text }) => ({ level, code, text })) }, null, 2) + '\n');
244
+ found.push({ level: 'info', text: `report (${grid}): ${path.relative(WS, report)}`, code: 'fea.report', refs: { report: path.relative(WS, report) } });
187
245
  return found;
188
246
  })());
189
247
  return all;
package/lib/optimise.mjs CHANGED
@@ -76,7 +76,7 @@ export async function readProblem(project, ref) {
76
76
  const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
77
77
  // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
78
78
  if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45 }; }
79
- return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline };
79
+ return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical };
80
80
  }
81
81
 
82
82
  /**
@@ -136,12 +136,20 @@ export const forDesign = ({ density, history, ...r }) => r;
136
136
  /**
137
137
  * Analyse a part under a problem's supports and loads, on its grid. A flat part (2D problem: triangles, z up, the
138
138
  * plate lying on the bed): each cell is as solid as the share of the problem's thickness the part fills above it. A
139
- * solid part (3D): each cube is solid if its centre is inside the part.
139
+ * solid part (3D): each cube is solid if its centre is inside the part. Each load case reports how far it moves its load
140
+ * (and the stiffness), the largest stress and where, and the largest movement anywhere and where.
140
141
  * @param {number[][][]} triangles @param {string} project @param {string} ref
142
+ * @param {{ cell?: number }} [options] cell: a finer cell size than the problem's, to check a final shape
141
143
  */
142
- export async function analysePart(triangles, project, ref) {
143
- const r = await readProblem(project, ref), { problem } = r, h = problem.cell;
144
- if (r.dim === 3) return analyseSolid(triangles, r);
144
+ export async function analysePart(triangles, project, ref, { cell } = {}) {
145
+ const r = await readProblem(project, ref), { problem } = r, h = cell || problem.cell;
146
+ if (r.dim === 3) { // kept: a fine analysis of a solid takes minutes
147
+ const file = paths.cache('analysis', `${crypto.createHash('sha256').update(JSON.stringify([VERSION, triangles, problem, h, source('@rulecad/topopt'), source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')])).digest('hex')}.json`);
148
+ if (!process.env.CAD_NO_CACHE && host.exists(file)) { const { density, ...x } = JSON.parse(host.readText(file)); return { ...x, density: Float64Array.from(density) }; }
149
+ const out = analyseSolid(triangles, r, h);
150
+ host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
151
+ return out;
152
+ }
145
153
  // The grid covers the part and the problem's space
146
154
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
147
155
  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); }
@@ -168,28 +176,70 @@ export async function analysePart(triangles, project, ref) {
168
176
  const a = analyse({ grid: g, density, material: problem.material, thickness: problem.thickness, fixed, loads });
169
177
  const cases = names.map((name, c) => {
170
178
  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]));
171
- const deflection = size ? a.compliance[c] / size : 0;
172
- let most = 0;
173
- for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) most = Math.max(most, a.stress[c][e]);
174
- return { name, force: size, deflection, stiffness: deflection ? size / deflection : Infinity, stress: most };
179
+ return measures(name, size, a, c, density, { nx, ny, nz: 1, h }, [x0, y0]);
175
180
  });
176
- return { problem: ref, material: r.material, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
181
+ return { problem: ref, dim: 2, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: { nx, ny, h }, origin: [x0, y0], density };
177
182
  }
178
183
 
179
184
  // A solid part on the problem's grid: the part itself is the space (keep and avoid regions don't apply), so the
180
185
  // supports and loads land on it as they would on an optimised layout
181
- function analyseSolid(triangles, r) {
182
- const { problem } = r, spec = discretise({ ...problem, space: { triangles }, keep: [], avoid: [], volume: 1 });
183
- const g = makeGrid(spec.grid), density = Float64Array.from(spec.passive, (p) => (p === 0 ? 1 : 0));
186
+ function analyseSolid(triangles, r, cell) {
187
+ const { problem } = r, spec = discretise({ ...problem, cell, space: { triangles }, keep: [], avoid: [], volume: 1 });
188
+ const g = makeGrid(spec.grid), density = solidFill(triangles, spec.grid, spec.origin);
184
189
  if (!density.some((d) => d)) throw new Error('the part is smaller than one cell of the problem: use a smaller cell');
185
190
  const a = analyse({ grid: g, density, material: problem.material, fixed: spec.fixed, loads: spec.loads.map((l) => l.force) });
186
- const cases = spec.loads.map((l, c) => {
187
- const deflection = l.size ? a.compliance[c] / l.size : 0;
188
- let most = 0;
189
- for (let e = 0; e < density.length; e++) if (density[e]) most = Math.max(most, a.stress[c][e]);
190
- return { name: l.name, force: l.size, deflection, stiffness: deflection ? l.size / deflection : Infinity, stress: most };
191
+ const cases = spec.loads.map((l, c) => measures(l.name, l.size, a, c, density, spec.grid, spec.origin));
192
+ return { problem: r.ref, dim: 3, material: r.material, critical: r.critical, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
193
+ }
194
+
195
+ // A load case's numbers: how far the load moves along itself (compliance over force) and the stiffness, the largest
196
+ // stress in the part and the centre of the cell it's in, and the largest movement of any point of the part and where
197
+ function measures(name, force, a, c, density, { nx, ny, h }, origin) {
198
+ const deflection = force ? a.compliance[c] / force : 0;
199
+ let most = 0, cellAt = 0;
200
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.stress[c][e] > most) { most = a.stress[c][e]; cellAt = e; }
201
+ const index = [cellAt % nx, Math.floor(cellAt / nx) % ny, Math.floor(cellAt / (nx * ny))];
202
+ const stressAt = origin.map((o, q) => round(o + (index[q] + 0.5) * h, 2)), d = a.deflection[c];
203
+ return {
204
+ name, force, deflection, stiffness: deflection ? force / deflection : Infinity, stress: most, stressAt,
205
+ movement: d.most, movementAt: d.at.map((x, q) => round(x + origin[q], 2)),
206
+ };
207
+ }
208
+
209
+ // How much of each cube the part fills, from 0 to 1, so a wall between cell centres counts for what it is (a 6 mm
210
+ // plate on 2.5 mm cubes, solid only where a cube's centre is inside, is 5 mm thick, and bends 40% more). Rays run up
211
+ // through each column of cubes, n × n of them (exact up the column, to within half their spacing across it); each enters the part through a face facing down and leaves through
212
+ // one facing up, and the lengths inside each cube are averaged.
213
+ export function solidFill(triangles, { nx, ny, nz, h }, origin, n = 4) {
214
+ const R = nx * n, hits = Array.from({ length: R * ny * n }, () => []), jx = h * 1e-4 * Math.SQRT2, jy = h * 1e-4 * Math.PI;
215
+ for (const [a, b, c] of triangles) {
216
+ const d = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
217
+ if (Math.abs(d) < 1e-12) continue; // a wall: the ray runs alongside it
218
+ const i0 = Math.max(0, Math.floor(((Math.min(a[0], b[0], c[0]) - origin[0]) / h) * n - 1)), i1 = Math.min(R - 1, Math.ceil(((Math.max(a[0], b[0], c[0]) - origin[0]) / h) * n));
219
+ const j0 = Math.max(0, Math.floor(((Math.min(a[1], b[1], c[1]) - origin[1]) / h) * n - 1)), j1 = Math.min(ny * n - 1, Math.ceil(((Math.max(a[1], b[1], c[1]) - origin[1]) / h) * n));
220
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
221
+ const x = origin[0] + ((i + 0.5) / n) * h + jx, y = origin[1] + ((j + 0.5) / n) * h + jy;
222
+ const w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / d, w1 = ((c[0] - x) * (a[1] - y) - (c[1] - y) * (a[0] - x)) / d, w2 = 1 - w0 - w1;
223
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
224
+ hits[j * R + i].push([w0 * a[2] + w1 * b[2] + w2 * c[2], Math.sign(d)]);
225
+ }
226
+ }
227
+ const density = new Float64Array(nx * ny * nz), share = 1 / (n * n * h);
228
+ hits.forEach((list, ray) => {
229
+ if (!list.length) return;
230
+ list.sort((p, q) => p[0] - q[0]);
231
+ const ci = Math.floor((ray % R) / n), cj = Math.floor(Math.floor(ray / R) / n);
232
+ let depth = 0, from = 0;
233
+ for (const [z, sign] of list) {
234
+ const was = depth; depth -= sign; // a face facing down (its normal's z below 0, counter-clockwise from above: sign -1) is the way in
235
+ if (was <= 0 && depth > 0) from = z;
236
+ else if (was > 0 && depth <= 0) for (let k = Math.max(0, Math.floor((from - origin[2]) / h)); k < nz && origin[2] + k * h < z; k++) {
237
+ const lo = Math.max(from, origin[2] + k * h), hi = Math.min(z, origin[2] + (k + 1) * h);
238
+ if (hi > lo) density[(k * ny + cj) * nx + ci] += (hi - lo) * share;
239
+ }
240
+ }
191
241
  });
192
- return { problem: r.ref, dim: 3, material: r.material, cases, volume: volume(triangles), grid: spec.grid, origin: spec.origin, density };
242
+ return density.map((x) => Math.min(1, x));
193
243
  }
194
244
 
195
245
  // How much of the thickness the part fills over each cell's centre: a ray straight up through the part enters it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
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": {
@@ -25,7 +25,21 @@
25
25
  "variants": { "type": "object", "additionalProperties": { "type": "object" } },
26
26
  "anchors": { "type": "object", "additionalProperties": { "$ref": "#/$defs/anchor" } },
27
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
+ "analysis": { "type": "array", "items": { "$ref": "#/$defs/analysis" }, "description": "Checks of how the part bends under a problem's loads (cad check)" },
29
+ "verification": {
30
+ "type": "array",
31
+ "description": "Tests or independent analyses of the part: a safety-critical part's analysis stays unverified without one",
32
+ "items": {
33
+ "type": "object", "required": ["kind", "date", "summary"], "additionalProperties": false,
34
+ "properties": {
35
+ "kind": { "enum": ["test", "analysis"], "description": "test: the part was loaded and measured; analysis: someone else analysed it independently" },
36
+ "date": { "type": "string" },
37
+ "by": { "type": "string" },
38
+ "summary": { "type": "string", "description": "What was done and what it showed, with numbers" },
39
+ "source": { "type": "string", "description": "Where the record is: a results file, a report, a link" }
40
+ }
41
+ }
42
+ }
29
43
  },
30
44
  "$defs": {
31
45
  "expr": { "type": ["number", "string"] },
@@ -61,7 +75,9 @@
61
75
  "volume": { "$ref": "#/$defs/expr", "description": "Fail if the part's volume differs from this (mm³) by more than tolerance" },
62
76
  "tolerance": { "type": "number", "description": "For volume: the share it may differ by (default 0.01)" },
63
77
  "rotate": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 3, "maxItems": 3, "description": "Turns the part into the problem's frame first, for a part drawn as it prints: degrees about x, then y, then z (as JSCAD's rotate)" },
64
- "move": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 3, "description": "Then moves it, in mm" }
78
+ "move": { "type": "array", "items": { "$ref": "#/$defs/expr" }, "minItems": 2, "maxItems": 3, "description": "Then moves it, in mm" },
79
+ "cell": { "$ref": "#/$defs/expr", "description": "Analyse on cells this size (mm) rather than the problem's: finer, to check a final shape" },
80
+ "min_safety": { "$ref": "#/$defs/expr", "description": "Fail if any load case's safety factor (strength, or fatigue strength where the material has one, over the peak stress) is below this" }
65
81
  }
66
82
  },
67
83
  "part": {
@@ -136,6 +136,10 @@
136
136
  }
137
137
  }
138
138
  },
139
+ "critical": {
140
+ "type": "boolean",
141
+ "description": "Safety-critical (a pedal, a lever, a bracket that holds people): parts analysed under it are reported unverified until a test or an independent analysis is recorded against them"
142
+ },
139
143
  "overhang": {
140
144
  "type": "string",
141
145
  "description": "3D: printable this way up ('+z', '-y', …), or a variable holding it, or 'none': only material supported from below at 45° or less"