Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice
TypeScript 3d-modeling3d-printing3d-printing-toolsagentagentic-aiai-cadcadcadqueryclaude-codecodexelectronfemllmmacdmakeropencodeparametric-designpythonsteptext-to-cad
App: FEM-Ergebnisse anzeigen, Skill „Festigkeit mit FEM“ (E65)
Kai-Jungsthoefeld9a3a439e290
diff --git a/app/resources/skills/analyse.md b/app/resources/skills/analyse.mdindex 2e89246..5feedd3 100644--- a/app/resources/skills/analyse.md+++ b/app/resources/skills/analyse.md@@ -43,7 +43,7 @@ accuracy of the threshold count as exactly at the threshold, not critical (a 45- Clearance is measured along the surface normal: a gap at an angle (a cone in a hole) reads larger than it is.- Overhang looks at the direction of the surface only. Bridges and small chamfers show as overhang, judge them withthe skill for the process.-- No strength analysis: loads and stresses need the skill for strength.+- No loads here: stresses and deflection under load are `soma analyze fem` (skill for FEM).## Feedback from the userdiff --git a/app/resources/skills/fem.md b/app/resources/skills/fem.mdnew file mode 100644index 0000000..21de7ed--- /dev/null+++ b/app/resources/skills/fem.md@@ -0,0 +1,87 @@+---+title: Festigkeit mit FEM+name: Strength with FEM+summary: Spannungen, Sicherheit und Verformung unter Last mit der Finite-Elemente-Methode (soma analyze fem), Lastfall als Python-Datei, Ergebnis farbig in der App.+order: 32+category: Prüfen und Zeigen+default: on-demand+when: a part carries a real load and the user wants to know whether it holds, where it is weakest or how far it bends+topics: Lastfall; Rechnen und lesen; Ergebnis prüfen; Grenzen; Rückmeldung+var safety: 2 | | Sicherheitsfaktor | 1..10+---+# Skill: Strength with FEM++`soma analyze fem <study.py>` computes stresses and deflection of parts under load (linear-elastic finite elements) and+colours the surface by the safety factor: strength divided by the von Mises stress. Required safety from the app:+`SAFETY = {{safety}}`. Red is below it, yellow just above, green fine. Units: mm, N, MPa (= N/mm²).++Use it after the design rules and the rough calculation of the strength skill, not instead of them. For parts that carry+people, hang overhead or lift loads, still say clearly that a real calculation and a test are needed.++## The load case++One file per load case in `analyses/`, for example `analyses/bracket.py`:++```python+from soma.fem import Study++study = Study("Bracket, 5 kg on the arm", material="PETG", safety=2)+study.fix("Bracket", faces="<Z") # held: the screwed-on bottom face+study.force("Bracket", faces=">X", N=(0, 0, -49)) # total force on the face, spread evenly+```++- `Study(title, material="PLA", safety=2, mesh=None, across_layers=True, parts=None)`. Materials: PLA, PETG, ABS, ASA,+ PA, POM, PMMA, Plywood, Aluminium 6082, Steel S235, Stainless 1.4301, or your own `dict(E=, nu=, strength=, density=)`+ (MPa, g/cm³). Printed plastics use the strength across the layers unless `across_layers=False`.+ `study.set_material("Shaft", "Steel S235")` for one part.+- Parts are named as in `add_part`. All parts in one study are meshed together and **bonded where they touch** (glued,+ no sliding, no gaps). Leave out parts that only bear on each other and replace them by `fix` and loads.+ `parts=["Cover"]` adds a part without loads.+- Faces: `faces=` takes a CadQuery selector on the part in its place in the model (`">Z"`, `"<X"`, `"%CYLINDER"`,+ `">Z[-2]"`), or a list of them. `near=(x, y, z)` takes the face closest to a point, also within the selected faces.+ When the user clicked a spot, use its coordinates with `near=`.+- `study.fix(part, faces=..., axes="xyz")` holds the faces. `axes="z"` holds only in Z (a part resting on a table).+ Every body needs enough support against moving and turning, otherwise the command says what is still free.+- `study.force(part, N=(fx, fy, fz), faces=...)`: total force in N. 1 kg weighs 9.81 N.+- `study.pressure(part, MPa=..., faces=...)`: pressure normal to the faces, positive presses into the material.+ 0.1 MPa = 1 bar.+- `study.gravity()`: the weight of the parts themselves (`direction="-z"`).++Model a screw by holding the face under its head or the inside of its hole. Put a load where it really acts: on the+face the hand, the shelf or the shaft touches, not on a whole side.++## Compute and read++1. `soma build`, then `soma analyze fem analyses/bracket.py`. Takes from seconds to about a minute. The summary lists the+ load case with areas (check them: wrong faces are the most common mistake), the support forces, per part the highest+ stress, smallest safety and largest deflection with their positions, the critical spots, then the checks.+2. `soma render --result bracket` and open the picture: colours by safety, the load case in blue (held faces strong,+ loaded faces light, forces as arrows), the deflection exaggerated as the legend says. Check that it bends the way you+ expect. A part that bends the wrong way has the wrong load or support.+3. Change the design, build, compute again. Report numbers: "smallest safety 2.4 (was 0.9), highest stress 8.3 MPa,+ deflection 0.6 mm at the tip".++## Check the result++- **Support forces** must carry the loads ("im Gleichgewicht"). If a support force is far from what you expect, the+ wrong faces are held.+- **Mesh check:** every run computes a second time with a coarser mesh. If the highest stress changes by more than 15 %,+ it says so: the peak sits at a sharp inner corner or at the edge of a support or load. There the value grows without+ limit with finer meshes. Add a fillet if it is a real corner, otherwise judge the stress a little away from it.+- `Study(..., mesh=1.0)` sets the element size in mm for thin walls or small details (default: about 1/30 of the size).+ Finer is slower.+- A large deflection (over 5 % of the size) is reported: then the linear calculation is only rough.++## Limits++- Linear-elastic: no yielding, no buckling, no contact, no sliding, no pre-tension of screws, no creep of plastics.+- Bonded parts, no joints. Bearings, hinges and screws are only modelled through supports and loads.+- Even materials: printing infill, layer direction and wood grain are not modelled. Printed parts are therefore computed+ with the weaker strength across layers. Infill below 100 % makes them weaker still.+- Static loads only. Impacts, vibration and fatigue need more safety or a test.++## Feedback from the user++`[Ergebnis: "Bracket, 5 kg on the arm" (.soma/results/bracket.glb, Grenzwert 2.00), Bauteil "Bracket": Sicherheit+0.90 (22.2 MPa, Verschiebung 0.412 mm) bei (12.0, -5.0, 26.0) mm]`: the user clicked that spot. The point is in the+undeformed model.diff --git a/app/resources/skills/festigkeit.md b/app/resources/skills/festigkeit.mdindex f3ae976..dcf8a3f 100644--- a/app/resources/skills/festigkeit.md+++ b/app/resources/skills/festigkeit.md@@ -11,7 +11,8 @@ var safety: 2 | | Sicherheitsfaktor | 1..10---# Skill: Strength and stiffness-No simulation: design for strength with rules and a rough calculation. Safety factor from the app:+Design for strength with rules and a rough calculation. To check a design under a real load, the skill for FEM+computes stresses and deflection (`soma analyze fem`). Safety factor from the app:`SAFETY = {{safety}}`. For parts that carry people, hang overhead or lift loads, say clearly that a real calculation anda test are needed.diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.mdindex 7911960..4ab3552 100644--- a/app/resources/template/AGENTS.md+++ b/app/resources/template/AGENTS.md@@ -14,6 +14,7 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes| `output/model.step` | Main result with all parts, written by `soma build`. Never write it yourself || `exports/` | Single-part exports written by `soma export` || `animations/` | Optional. Motion, camera flights and captions in Python (`soma.anim`), one file per topic. The skill for animation explains them |+| `analyses/` | Optional. Load cases for `soma analyze fem` in Python (`soma.fem`), one file per load case. The skill for FEM explains them || `renders/` | Pictures and videos written by `soma render`. Not in the version history || `.soma/` | App data (viewer cache, build status, feedback images, skills, built animations, analysis results). Do not edit. Read the skills in `.soma/skills/` as the list at the end of this file says, and files in `.soma/feedback/` when the user points you to them |@@ -39,6 +40,7 @@ Run them in this terminal. They work without the app.| `soma export --all --format step` | Exports all parts except references || `soma render` | Saves a picture of the current model to `renders/ansicht-iso.png` (`--view top`, `--size 1280x800`, `--out`). **Open the picture and look at it** to check your work. Works only in the terminals of the app, it renders with the app's viewer || `soma analyze overhang` (or `thickness`, `clearance`) | Value at every spot of the surface with a summary per part. Details in the skill for analysis |+| `soma analyze fem analyses/x.py` | Stresses, safety and deflection under a load case described in `analyses/x.py`. Details in the skill for FEM || `soma anim build`, `soma anim info "Name"` | Animations from `animations/`. Details in the skill for animation |If `soma build` fails, fix the error before doing anything else. Keep the model buildable at all times.diff --git a/app/src/main/animations.ts b/app/src/main/animations.tsindex e140bd9..6cca2e6 100644--- a/app/src/main/animations.ts+++ b/app/src/main/animations.ts@@ -103,7 +103,9 @@ export class AnimBuilder {dispose(): void { this.disposed = true; this.pending = null; }}-const KINDS = new Set(['overhang', 'thickness', 'clearance']);+const KINDS = new Set(['overhang', 'thickness', 'clearance', 'fem']);+/** Lastfall einer FEM-Studie: eine Python-Datei im Projekt (kommt aus der Ergebnisdatei, also prüfen). */+const STUDY = /^[\p{L}\p{N}_./ -]{1,200}\.py$/u;/** Ergebnisse in .soma/results/. Veraltet: Der Code ist neuer als die Auswertung. */export function listResults(dir: string): ResultEntry[] {@@ -114,7 +116,11 @@ export function listResults(dir: string): ResultEntry[] {for (const f of files) {const meta = (readGlbJson(path.join(dir, '.soma', 'results', f))?.extras as { soma_result?: ResultMeta } | undefined)?.soma_result;if (!meta || typeof meta.id !== 'string' || !Array.isArray(meta.range)) continue;- out.push({ ...meta, file: `.soma/results/${f}`, stale: model > (Number(meta.created) || 0) * 1000 });+ // FEM: auch die Datei mit dem Lastfall zählt (analyses/ gehört nicht zu den Quellen des Modells)+ let newest = model;+ const study = meta.fem?.study;+ if (typeof study === 'string' && STUDY.test(study)) try { newest = Math.max(newest, mtime(resolveInside(dir, study))); } catch { /* außerhalb: zählt nicht */ }+ out.push({ ...meta, file: `.soma/results/${f}`, stale: newest > (Number(meta.created) || 0) * 1000 });}return out;}@@ -129,7 +135,16 @@ export async function rerunResult(dir: string, id: string): Promise<{ ok: booleaconst cmd = Array.isArray(r.command) ? r.command.map(String) : [];if (cmd[0] !== 'analyze' || !KINDS.has(cmd[1])) return { ok: false, error: 'Unbekannte Auswertung in der Datei.' };const args = ['analyze', cmd[1]];- for (const a of cmd.slice(2)) {+ let rest = cmd.slice(2);+ if (cmd[1] === 'fem') {+ // Die Datei mit dem Lastfall: relativ, im Projekt, eine .py-Datei+ const study = rest[0] ?? '';+ if (!STUDY.test(study) || study.startsWith('-') || study.includes('..')) return { ok: false, error: `Unerwartete Studie in der Datei: ${study.slice(0, 60)}` };+ try { resolveInside(dir, study); } catch { return { ok: false, error: 'Die Studie liegt außerhalb des Projekts.' }; }+ args.push(study);+ rest = rest.slice(1);+ }+ for (const a of rest) {// Immer als --schalter=wert: Werte wie -z oder -0.5 sind dann keine Schalter für argparseconst m = /^(--parts|--threshold|--up|--name)=(.{1,400})$/s.exec(a);if (!m) return { ok: false, error: `Unerwartete Angabe in der Datei: ${a.slice(0, 60)}` };diff --git a/app/src/renderer/index.html b/app/src/renderer/index.htmlindex c901229..4378e5a 100644--- a/app/src/renderer/index.html+++ b/app/src/renderer/index.html@@ -236,6 +236,12 @@</div></div>+ <!-- Nur bei FEM (E65): Verformung überhöht zeigen, Lastfall ein- und ausblenden -->+ <div id="result-fem" class="an-opts rs-fem" hidden>+ <select id="result-deform" class="an-speed" aria-label="Verformung" title="Verformung: unverformt, in echter Größe oder überhöht, damit man sie sieht"></select>+ <span class="grow"></span>+ <button id="btn-result-bcs" class="btn sm" aria-pressed="true" title="Lastfall zeigen: eingespannte Flächen und Lasten in Blau, Kräfte als Pfeile"><i data-icon="arrow" data-size="14" data-stroke="1.9"></i>Lastfall</button>+ </div><div id="errcard" class="float errcard" hidden><div class="ec-hd"><span class="err-ico"><i data-icon="alert" data-size="18"></i></span>diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex 1a3a1ea..25e75a1 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -520,6 +520,7 @@ const resultTool = new ResultTool({layer: resultLayer, list: () => api.results.list(), rerun: (id) => api.results.rerun(id), readBinary: (rel) => api.fs.readBinary(rel),beforeOn: () => endOthers('result'), insert: (t) => insertToAgent(t), toast,changed: () => renderViewSwitch(),+ femRow: $('result-fem'), deform: $<HTMLSelectElement>('result-deform'), bcs: $<HTMLButtonElement>('btn-result-bcs'),});// Messen und Explosion schalten die beiden aus, bevor sie selbst anfangen (Lauscher in der Erfassungsphase laufen vor denen// der Werkzeuge): Beide rechnen mit der Einbaulagediff --git a/app/src/renderer/overlay.ts b/app/src/renderer/overlay.tsindex 6e1115d..f8b9b2a 100644--- a/app/src/renderer/overlay.ts+++ b/app/src/renderer/overlay.ts@@ -11,6 +11,8 @@ export interface OverlayContent {labels?: { text: string; x: number; y: number }[];stamp?: string | null;legend?: ResultMeta | null;+ /** Zusatzzeile unter der Legende, etwa die Überhöhung der Verformung (FEM). */+ legendNote?: string | null;/** Untertitel so weit über dem unteren Rand (Pixel), im Viewer über der Karte der Animation. */captionLift?: number;}@@ -102,7 +104,7 @@ export function paintOverlay(g: CanvasRenderingContext2D, w: number, h: number,g.fillText(c.stamp, unit * 0.6 + pad, unit * 1.5);}- if (c.legend) paintLegend(g, w, h, unit, c.legend);+ if (c.legend) paintLegend(g, w, h, unit, c.legend, c.legendNote ?? null);g.restore();}@@ -125,18 +127,18 @@ export function resultColor(v: number, m: Pick<ResultMeta, 'bad' | 'threshold' |return mix(OK, FAR, (f - 0.15) / 0.85);}-const fmt = (v: number, unit: string) => `${(+v.toFixed(unit === '°' ? 1 : 2)).toLocaleString('de-DE')}${unit === '°' ? '°' : ` ${unit}`}`;+const fmt = (v: number, unit: string) => `${(+v.toFixed(unit === '°' ? 1 : 2)).toLocaleString('de-DE')}${unit === '°' ? '°' : unit ? ` ${unit}` : ''}`;/** Legende unten rechts: Farbverlauf über die Spanne, Grenzwert markiert. */-function paintLegend(g: CanvasRenderingContext2D, w: number, h: number, unit: number, m: ResultMeta): void {+function paintLegend(g: CanvasRenderingContext2D, w: number, h: number, unit: number, m: ResultMeta, note: string | null): void {const bw = Math.min(w * 0.36, unit * 22), bh = unit * 0.9, pad = unit * 0.8;- const boxW = bw + pad * 2, boxH = unit * 6.3;+ const boxW = bw + pad * 2, boxH = unit * (note ? 7.5 : 6.3);const x0 = w - boxW - unit, y0 = h - boxH - unit;g.fillStyle = 'rgba(18,20,23,.88)';roundRect(g, x0, y0, boxW, boxH, unit * 0.4); g.fill();g.fillStyle = '#e6e8eb';g.font = `600 ${Math.round(unit * 1.0)}px ${FONT}`;- g.fillText(`${m.title} (${m.unit})`, x0 + pad, y0 + unit * 1.3);+ g.fillText(m.unit ? `${m.title} (${m.unit})` : `${m.title}: ${m.quantity}`, x0 + pad, y0 + unit * 1.3);const bx = x0 + pad, by = y0 + unit * 2.3;const [lo, hi] = m.range;for (let i = 0; i < bw; i++) {@@ -156,4 +158,8 @@ function paintLegend(g: CanvasRenderingContext2D, w: number, h: number, unit: nug.fillStyle = '#e6e8eb';g.fillText(`Grenze ${fmt(m.threshold, m.unit)}`, Math.min(Math.max(tx, bx + unit * 3), bx + bw - unit * 3), by + bh + unit * 2.1);g.textAlign = 'left';+ if (note) {+ g.fillStyle = '#a3acb6';+ g.fillText(note, bx, by + bh + unit * 3.3);+ }}diff --git a/app/src/renderer/render.ts b/app/src/renderer/render.tsindex 95d5761..177f3a8 100644--- a/app/src/renderer/render.ts+++ b/app/src/renderer/render.ts@@ -33,7 +33,8 @@ async function prepare(job: RenderJob): Promise<Scene> {/** Stand zur Zeit t (ohne Animation: die gewählte Ansicht) und ein Bild davon. */function frame(s: Scene, t: number, stamp: string | null, forceView: boolean): HTMLCanvasElement {- let content: Parameters<typeof paintOverlay>[3] = { legend: s.legend, stamp };+ // FEM: Das Bild zeigt die Verformung überhöht (wie der Viewer beim Öffnen), die Legende sagt, wie stark+ let content: Parameters<typeof paintOverlay>[3] = { legend: s.legend, legendNote: s.legend ? results.deformNote() : null, stamp };let labels: { text: string; at: THREE.Vector3 }[] = [];if (s.anim) {const f = s.anim.frame(t);diff --git a/app/src/renderer/resulttool.ts b/app/src/renderer/resulttool.tsindex b97d9a5..0f83b17 100644--- a/app/src/renderer/resulttool.ts+++ b/app/src/renderer/resulttool.ts@@ -1,6 +1,6 @@import type { ResultEntry } from '../shared/types';import { resultColor } from './overlay';-import type { ResultLayer, ResultProbe } from './resultview';+import { fmtScale, type ResultLayer, type ResultProbe } from './resultview';import { el } from './ui';// Ergebnisse von `soma analyze` im Viewer (E58): auswählen, farbig zeigen, Wert unter dem Zeiger, an den Agenten geben.@@ -10,6 +10,8 @@ interface Ui {card: HTMLElement; close: HTMLButtonElement; select: HTMLSelectElement;legend: HTMLElement; summary: HTMLElement; probe: HTMLElement; hint: HTMLElement;rerun: HTMLButtonElement; agent: HTMLButtonElement;+ /** Nur FEM: Überhöhung der Verformung und Lastfall ein/aus. */+ femRow: HTMLElement; deform: HTMLSelectElement; bcs: HTMLButtonElement;viewerEl: HTMLElement;}interface Deps {@@ -25,8 +27,14 @@ interface Deps {}const num = (v: number, unit: string) => (+v.toFixed(unit === '°' ? 1 : 2) + 0).toLocaleString('de-DE'); // + 0: kein „-0“-const withUnit = (v: number, unit: string) => `${num(v, unit)}${unit === '°' ? '°' : ` ${unit}`}`;-const dot = (v: number, unit: string) => `${v.toFixed(unit === '°' ? 1 : 2)}${unit === '°' ? '°' : ` ${unit}`}`;+// Ohne Einheit (Sicherheitsfaktor der FEM) steht die Zahl allein+const withUnit = (v: number, unit: string) => `${num(v, unit)}${unit === '°' ? '°' : unit ? ` ${unit}` : ''}`;+const dot = (v: number, unit: string) => `${v.toFixed(unit === '°' ? 1 : 2)}${unit === '°' ? '°' : unit ? ` ${unit}` : ''}`;+const de = (v: number, digits: number) => (+v.toFixed(digits) + 0).toLocaleString('de-DE');+/** Spannung und Verschiebung an einer Stelle (FEM). */+const femAt = (p: ResultProbe) => (p.stress != null ? ` · ${de(p.stress, 1)} MPa` : '') + (p.disp != null ? ` · ${de(p.disp, 3)} mm` : '');+/** Höchster Sicherheitsfaktor in der Datei (soma.fem VALUE_CAP): Dort ist kaum Spannung, der Wert selbst sagt nichts. */+const SAFETY_CAP = 99;/** Abstand des Schilds vom Zeiger (px): neben den Armen des Fadenkreuzes, nicht darauf. */const TIP_GAP = 14;@@ -52,6 +60,8 @@ export class ResultTool {ui.select.addEventListener('change', () => { const e = this.list.find((r) => r.id === ui.select.value); if (e) void this.load(e); });ui.rerun.addEventListener('click', () => void this.rerun());ui.agent.addEventListener('click', () => { const t = this.agentNote(); if (t) d.insert(t); });+ ui.deform.addEventListener('change', () => { d.layer.setScale(Number(ui.deform.value) || 0); this.hideTip(); });+ ui.bcs.addEventListener('click', () => { d.layer.setBcsVisible(!d.layer.bcsVisible); ui.bcs.setAttribute('aria-pressed', String(d.layer.bcsVisible)); });ui.viewerEl.append(this.tip);let queued = false, pos: [number, number] | null = null, away = true;// Zeiger nicht mehr über dem Bild: Schild weg, die Karte zeigt wieder die gemerkte Stelle (wichtig vor „An Agent geben“)@@ -160,7 +170,7 @@ export class ResultTool {this.hideTip();this.ui.hint.classList.toggle('warn', !!r?.stale);if (!r) {- this.ui.hint.textContent = 'Noch kein Ergebnis. Der Agent erzeugt es mit soma analyze (Überhang, Wandstärke, Abstand).';+ this.ui.hint.textContent = 'Noch kein Ergebnis. Der Agent erzeugt es mit soma analyze (Überhang, Wandstärke, Abstand, Festigkeit mit FEM).';return;}this.ui.hint.textContent = this.busy ? 'Wird neu berechnet …' : r.stale ? 'Älter als der Code. „Neu berechnen“ wertet das aktuelle Modell aus.' : `soma ${r.command.join(' ')}`;@@ -176,7 +186,7 @@ export class ResultTool {mark.style.left = `${Math.max(0, Math.min(100, ((r.threshold - lo) / (hi - lo || 1)) * 100))}%`;bar.append(mark);this.ui.legend.append(- el('div', { className: 'rs-q', textContent: `${r.quantity} (${r.unit})` }), bar,+ el('div', { className: 'rs-q', textContent: r.unit ? `${r.quantity} (${r.unit})` : r.quantity }), bar,el('div', { className: 'rs-scale' }, el('span', { textContent: withUnit(lo, r.unit) }),el('span', { className: 'rs-thr', textContent: `Grenze ${withUnit(r.threshold, r.unit)}, kritisch ${r.bad === 'high' ? 'darüber' : 'darunter'}` }),el('span', { textContent: withUnit(hi, r.unit) })),@@ -184,12 +194,40 @@ export class ResultTool {for (const p of r.parts) {const range = p.min != null && p.max != null ? `${withUnit(p.min, r.unit)} bis ${withUnit(p.max, r.unit)}` : 'keine Werte';const crit = p.critical > 0 ? `${(p.critical / 100).toLocaleString('de-DE', { maximumFractionDigits: 2 })} cm² kritisch` : 'nichts kritisch';+ // FEM: kleinste Sicherheit, höchste Spannung und größte Verschiebung sagen mehr als die Spanne+ // („kritisch“ nur, wenn es so ist: die Zeile ist schmal, und sie ist dann ohnehin rot)+ const text = r.fem && p.stress && p.displacement && p.min != null+ ? `Sicherheit ${de(p.min, 2)} · ${de(p.stress.value, 1)} MPa · ${de(p.displacement.value, 3)} mm${p.critical > 0 ? ` · ${crit}` : ''}`+ : `${range} · ${crit}`;this.ui.summary.append(el('div', { className: 'rs-row' + (p.critical > 0 ? ' bad' : '') },- el('b', { textContent: p.name }), el('span', { textContent: `${range} · ${crit}` })));+ el('b', { textContent: p.name }), el('span', { textContent: text })));}+ this.renderFem(r);this.showProbe(this.pinned, true);}+ /** FEM: Lastfall und Hinweise in der Karte, Wahl der Überhöhung. */+ private renderFem(r: ResultEntry): void {+ const fem = r.fem;+ this.ui.femRow.hidden = !fem;+ if (!fem) return;+ const n = (v: number[]) => `${de(Math.hypot(v[0], v[1], v[2]), 1)} N`;+ for (const b of fem.bcs) {+ const what = b.kind === 'fix' ? `fest${b.axes && b.axes !== 'xyz' ? ` (nur ${b.axes.toUpperCase().split('').join(', ')})` : ''}`+ : b.kind === 'force' ? 'Kraft' : 'Druck';+ const val = b.kind === 'fix' ? (b.reaction ? `Lagerkraft ${n(b.reaction)}` : '')+ : b.kind === 'pressure' ? `${de(b.value ?? 0, 3)} MPa, zusammen ${n(b.total ?? [0, 0, 0])}` : n(b.total ?? [0, 0, 0]);+ this.ui.summary.append(el('div', { className: 'rs-row bc' }, el('b', { textContent: what }), el('span', { textContent: `${b.label} · ${val}` })));+ }+ for (const t of r.notes ?? []) this.ui.summary.append(el('div', { className: 'rs-note', textContent: t }));+ const l = this.d.layer;+ const opts: [number, string][] = [[0, 'Unverformt'], [1, 'Echte Größe']];+ if (l.autoScale > 1) opts.push([l.autoScale, `${fmtScale(l.autoScale)}-fach überhöht`]);+ this.ui.deform.replaceChildren(...opts.map(([v, t]) => el('option', { value: String(v), textContent: t })));+ this.ui.deform.value = String(l.scale);+ this.ui.bcs.setAttribute('aria-pressed', String(l.bcsVisible));+ }+private showProbe(p: ResultProbe | null, pinned: boolean): void {const r = this.current;if (!r) return;@@ -210,7 +248,7 @@ export class ResultTool {private showTip(p: ResultProbe | null, at: [number, number]): void {const r = this.current;if (!p || !r) { this.hideTip(); return; }- this.tipVal.textContent = withUnit(p.value, r.unit);+ this.tipVal.textContent = (r.fem && p.value >= SAFETY_CAP ? `über ${SAFETY_CAP}` : withUnit(p.value, r.unit)) + femAt(p);this.tipName.textContent = p.name;this.tipDot.style.background = `rgb(${resultColor(p.value, r).map(Math.round).join(',')})`;this.tip.hidden = false;@@ -230,7 +268,8 @@ export class ResultTool {private probeText(p: ResultProbe, pinned: boolean): string {const r = this.current!;- return `${pinned ? 'Gewählt' : 'Zeiger'}: ${p.name}, ${withUnit(p.value, r.unit)} bei (${p.point.map((v) => (v + 0).toLocaleString('de-DE')).join('; ')})`;+ const what = r.fem ? `Sicherheit ${p.value >= SAFETY_CAP ? `über ${SAFETY_CAP}` : withUnit(p.value, r.unit)}${femAt(p)}` : withUnit(p.value, r.unit);+ return `${pinned ? 'Gewählt' : 'Zeiger'}: ${p.name}, ${what} bei (${p.point.map((v) => (v + 0).toLocaleString('de-DE')).join('; ')})`;}private async rerun(): Promise<void> {@@ -252,7 +291,9 @@ export class ResultTool {if (!r) return null;const head = `[Ergebnis: "${r.title}" (${r.file}, Grenzwert ${dot(r.threshold, r.unit)})`;const p = this.pinned;- return p ? `${head}, Bauteil "${p.name}": ${dot(p.value, r.unit)} bei (${p.point.map((v) => v.toFixed(1)).join(', ')}) mm] ` : `${head}] `;+ // FEM: Sicherheit mit Spannung und Verschiebung, damit der Agent die Stelle ohne neue Rechnung einordnen kann+ const extra = p && p.stress != null ? ` (${p.stress.toFixed(1)} MPa${p.disp != null ? `, Verschiebung ${p.disp.toFixed(3)} mm` : ''})` : '';+ return p ? `${head}, Bauteil "${p.name}": ${r.fem ? 'Sicherheit ' : ''}${r.fem && p.value >= SAFETY_CAP ? `über ${SAFETY_CAP}` : dot(p.value, r.unit)}${extra} bei (${p.point.map((v) => v.toFixed(1)).join(', ')}) mm] ` : `${head}] `;}/** Für die Markierung: Welches Ergebnis zu sehen ist (null: keines). */@@ -267,6 +308,11 @@ export class ResultTool {rows: [...this.ui.summary.querySelectorAll('.rs-row')].map((x) => x.textContent), probe: this.ui.probe.textContent, hint: this.ui.hint.textContent,note: this.agentNote(), meta: this.d.layer.meta ? { threshold: this.d.layer.meta.threshold, unit: this.d.layer.meta.unit } : null,tip: this.tip.hidden ? null : `${this.tipVal.textContent} · ${this.tipName.textContent}`,+ fem: this.ui.femRow.hidden ? null : {+ deform: this.ui.deform.value, options: [...this.ui.deform.options].map((o) => o.textContent), bcs: this.ui.bcs.getAttribute('aria-pressed') === 'true',+ scale: this.d.layer.scale, notes: [...this.ui.summary.querySelectorAll('.rs-note')].map((x) => x.textContent),+ bcRows: [...this.ui.summary.querySelectorAll('.rs-row.bc')].map((x) => x.textContent),+ },};}diff --git a/app/src/renderer/resultview.ts b/app/src/renderer/resultview.tsindex 64217af..3920da0 100644--- a/app/src/renderer/resultview.ts+++ b/app/src/renderer/resultview.ts@@ -7,19 +7,40 @@ import type { Viewer } from './viewer';// Ergebnis einer Auswertung (E58, .soma/results/<name>.glb von `soma analyze`): je Bauteil ein Netz mit einem Wert je Dreieck// (Attribut _VALUE) und seinen Kanten. Solange es angezeigt wird, tritt das Modell zurück und die Netze vertreten seine Bauteile// (Viewer.setStandIns): Ausblenden und Transparent aus der Seitenleiste gelten für sie, der Schnitt füllt sie wie das Modell.+// FEM (E65) bringt dazu je Ecke die Vergleichsspannung (_STRESS) und die Verschiebung (_DISP) mit, und den Lastfall als+// eigene Netze (extras.soma.marker): Die Verformung lässt sich überhöht zeigen, Einspannungen und Lasten sind markiert.-interface ResultMesh { mesh: THREE.Mesh; name: string; values: THREE.BufferAttribute }+interface ResultMesh { mesh: THREE.Mesh; name: string; values: THREE.BufferAttribute; stress?: THREE.BufferAttribute; disp?: THREE.BufferAttribute }+/** Verformbare Geometrie: Ausgangslage und Verschiebung je Ecke. */+interface Deformable { geo: THREE.BufferGeometry; base: Float32Array; disp: THREE.BufferAttribute }+interface Arrow { obj: THREE.Object3D; base: THREE.Vector3; shift: THREE.Vector3 }-export interface ResultProbe { name: string; value: number; point: number[] }+export interface ResultProbe {+ name: string; value: number; point: number[];+ /** FEM: Vergleichsspannung (MPa) und Betrag der Verschiebung (mm) an der Stelle. */+ stress?: number; disp?: number;+}++/** Blau des Lastfalls: keine Statusfarbe, nicht Orange (Aktion) und nicht Violett (Vorschau). */+const BC_COLOR = 0x5ea8ff;export class ResultLayer {meta: ResultMeta | null = null;private group: THREE.Object3D | null = null;private meshes: ResultMesh[] = [];+ private deformables: Deformable[] = [];+ private markers: THREE.Object3D[] = [];+ private arrows: Arrow[] = [];+ /** Überhöhung der Verformung (0: unverformt). */+ scale = 0;+ /** Vorschlag: die größte Verschiebung als 5 % der Modellgröße, auf eine runde Zahl. */+ autoScale = 0;+ private showBcs = true;constructor(private readonly viewer: Viewer) {}get active(): boolean { return !!this.group; }+ get isFem(): boolean { return !!this.meta?.fem; }async show(glb: ArrayBuffer): Promise<ResultMeta> {const gltf = await new GLTFLoader().parseAsync(glb, '');@@ -27,9 +48,32 @@ export class ResultLayer {if (!meta || !Array.isArray(meta.range)) throw new Error('Kein Ergebnis von soma (extras.soma_result fehlt)');this.hide();const meshes: ResultMesh[] = [];+ const deformables: Deformable[] = [];+ const markers: THREE.Object3D[] = [];const standIns: { mesh: THREE.Mesh; name: string; lines: THREE.LineSegments[] }[] = [];+ const deformable = (geo: THREE.BufferGeometry) => {+ const disp = geo.getAttribute('_disp') as THREE.BufferAttribute | undefined;+ if (disp) deformables.push({ geo, base: Float32Array.from((geo.getAttribute('position') as THREE.BufferAttribute).array as Float32Array), disp });+ };gltf.scene.traverse((o) => {- const name = (o.userData as { soma?: { name?: string } }).soma?.name;+ const soma = (o.userData as { soma?: { name?: string; marker?: string } }).soma;+ if (soma?.marker) {+ // Lastfall: eingespannte Flächen kräftig, Lastflächen schwächer, beide vor dem Ergebnis gezeichnet+ o.traverse((c) => {+ const m = c as THREE.Mesh;+ if (!m.isMesh) return;+ m.material = new THREE.MeshBasicMaterial({+ color: BC_COLOR, transparent: true, opacity: soma.marker === 'fix' ? 0.55 : 0.28, side: THREE.DoubleSide, depthWrite: false,+ polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, clippingPlanes: this.viewer.clipPlanes,+ });+ m.raycast = () => {}; // der Zeiger trifft das Ergebnis darunter+ m.renderOrder = 3;+ deformable(m.geometry);+ });+ markers.push(o);+ return;+ }+ const name = soma?.name;if (!name) return;const own: ResultMesh[] = [], lines: THREE.LineSegments[] = [];o.traverse((c) => {@@ -41,11 +85,14 @@ export class ResultLayer {vertexColors: true, side: THREE.DoubleSide, roughness: 0.75, metalness: 0,polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1, clippingPlanes: this.viewer.clipPlanes,});- own.push({ mesh: m, name, values });+ own.push({ mesh: m, name, values, stress: m.geometry.getAttribute('_stress') as THREE.BufferAttribute | undefined,+ disp: m.geometry.getAttribute('_disp') as THREE.BufferAttribute | undefined });+ deformable(m.geometry);} else if ((c as THREE.LineSegments).isLineSegments) {const l = c as THREE.LineSegments;l.material = new THREE.LineBasicMaterial({ color: 0x1a1d22, clippingPlanes: this.viewer.clipPlanes });lines.push(l);+ deformable(l.geometry);}});// Die Kanten stehen neben dem Netz im selben Knoten: Sie verschwinden mit ihm, wenn das Bauteil ausgeblendet wird@@ -54,14 +101,102 @@ export class ResultLayer {});this.meta = meta;this.meshes = meshes;+ this.deformables = deformables;+ this.markers = markers;this.group = gltf.scene;+ this.arrows = this.makeArrows(meta, markers);+ const maxDisp = meta.fem?.maxDisp ?? 0, diag = meta.fem?.diag ?? 0;+ this.autoScale = maxDisp > 0 && diag > 0 ? niceScale((0.05 * diag) / maxDisp) : 0;+ this.scale = 0;this.recolor();this.viewer.setModelHidden(true);this.viewer.addLayer(this.group);this.viewer.setStandIns(standIns);+ // Verformt zeigen, sobald es eine gibt: So sieht man sofort, ob Lager und Last so wirken wie gedacht+ if (this.autoScale > 0) this.setScale(this.autoScale);+ this.setBcsVisible(this.showBcs);return meta;}+ /** Pfeile für Kräfte und Druck: an der Mitte der Lastfläche, die Spitze auf der Fläche. Länge 15 % der Modellgröße. */+ private makeArrows(meta: ResultMeta, markers: THREE.Object3D[]): Arrow[] {+ const fem = meta.fem;+ if (!fem) return [];+ const len = Math.max(1, fem.diag * 0.15);+ const out: Arrow[] = [];+ fem.bcs.forEach((b, i) => {+ if (b.kind === 'fix' || !b.total) return;+ const dir = new THREE.Vector3(...(b.total as [number, number, number]));+ if (dir.lengthSq() < 1e-18) return;+ dir.normalize();+ const at = new THREE.Vector3(...(b.at as [number, number, number]));+ const base = at.clone().addScaledVector(dir, -len);+ // Körperhafter Pfeil, vor dem Modell gezeichnet: Eine Linie wäre 1 Pixel dünn, und eine Kraft quer zur Fläche (Kragarm)+ // läge mit der Spitze im Material+ const mat = new THREE.MeshBasicMaterial({ color: BC_COLOR, depthTest: false, transparent: true, opacity: 0.95 });+ const head = len * 0.26, shaft = new THREE.CylinderGeometry(len * 0.022, len * 0.022, len - head, 12);+ shaft.translate(0, (len - head) / 2, 0);+ const cone = new THREE.ConeGeometry(len * 0.075, head, 20);+ cone.translate(0, len - head / 2, 0);+ const a = new THREE.Group();+ for (const g of [shaft, cone]) {+ const m = new THREE.Mesh(g, mat);+ m.raycast = () => {};+ m.renderOrder = 5;+ a.add(m);+ }+ a.position.copy(base);+ a.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);+ // Mittlere Verschiebung der Lastfläche: Der Pfeil wandert mit der verformten Fläche+ const shift = new THREE.Vector3();+ const marker = markers.find((m) => (m.userData as { soma?: { bc?: number } }).soma?.bc === i);+ marker?.traverse((c) => {+ const d = (c as THREE.Mesh).geometry?.getAttribute('_disp') as THREE.BufferAttribute | undefined;+ if (!d || !d.count) return;+ for (let k = 0; k < d.count; k++) shift.add(new THREE.Vector3(d.getX(k), d.getY(k), d.getZ(k)));+ shift.divideScalar(d.count);+ });+ this.group!.add(a);+ out.push({ obj: a, base, shift });+ });+ return out;+ }++ /** Verformung überhöht zeigen (0: unverformt, 1: echte Größe). */+ setScale(s: number): void {+ if (!this.group) return;+ this.scale = s;+ for (const d of this.deformables) {+ const pos = d.geo.getAttribute('position') as THREE.BufferAttribute;+ const arr = pos.array as Float32Array;+ for (let i = 0; i < d.disp.count; i++) {+ arr[i * 3] = d.base[i * 3] + s * d.disp.getX(i);+ arr[i * 3 + 1] = d.base[i * 3 + 1] + s * d.disp.getY(i);+ arr[i * 3 + 2] = d.base[i * 3 + 2] + s * d.disp.getZ(i);+ }+ pos.needsUpdate = true;+ d.geo.computeBoundingBox();+ d.geo.computeBoundingSphere();+ }+ for (const a of this.arrows) a.obj.position.copy(a.base).addScaledVector(a.shift, s);+ this.viewer.requestRender();+ }++ /** Lastfall (Einspannungen, Lastflächen, Pfeile) ein- oder ausblenden. */+ setBcsVisible(on: boolean): void {+ this.showBcs = on;+ for (const m of this.markers) m.visible = on;+ for (const a of this.arrows) a.obj.visible = on;+ this.viewer.requestRender();+ }+ get bcsVisible(): boolean { return this.showBcs; }++ /** Zeile für die Legende im Bild: wie stark die Verformung überhöht ist. */+ deformNote(): string | null {+ if (!this.isFem || this.scale <= 0) return null;+ return this.scale === 1 ? 'Verformung in echter Größe' : `Verformung ${fmtScale(this.scale)}-fach überhöht`;+ }+/** Farben neu aus den Werten (etwa nach geänderter Spanne). */recolor(): void {if (!this.meta) return;@@ -91,13 +226,19 @@ export class ResultLayer {});this.group = null;this.meshes = [];+ this.deformables = [];+ this.markers = [];+ this.arrows = [];this.meta = null;+ this.scale = 0;+ this.autoScale = 0;this.viewer.setModelHidden(false);}/*** Wert unter dem Zeiger: Bauteil, Wert des Dreiecks und der Punkt (mm). Ausgeblendete Teile zählen nicht, durch transparente- * geht der Zeiger hindurch. Auf der Schnittfläche gibt es keinen Wert (die Werte gelten an der Oberfläche).+ * geht der Zeiger hindurch. Auf der Schnittfläche gibt es keinen Wert (die Werte gelten an der Oberfläche). Bei verformter+ * Anzeige gilt der Punkt in der Ausgangslage, so wie ihn der Agent im Modell findet.*/probe(clientX: number, clientY: number): ResultProbe | null {if (!this.group) return null;@@ -105,6 +246,27 @@ export class ResultLayer {if (!hit || hit.cut || hit.face == null) return null;const m = this.meshes.find((x) => x.mesh === hit.object);if (!m) return null;- return { name: m.name, value: m.values.getX(hit.face.a), point: hit.point.toArray().map((v) => +v.toFixed(2)) };+ const i = hit.face.a;+ const p = hit.point.clone();+ let disp: number | undefined;+ if (m.disp) {+ const d = new THREE.Vector3(m.disp.getX(i), m.disp.getY(i), m.disp.getZ(i));+ p.addScaledVector(d, -this.scale);+ disp = d.length();+ }+ return {+ name: m.name, value: m.values.getX(i), point: p.toArray().map((v) => +v.toFixed(2)),+ ...(m.stress ? { stress: m.stress.getX(i) } : {}), ...(disp != null ? { disp } : {}),+ };}}++/** Runde Überhöhung: 1, 2, 5, 10, 20, 50 … (nie kleiner als 1). */+export function niceScale(x: number): number {+ if (!(x > 1)) return 1;+ const e = Math.pow(10, Math.floor(Math.log10(x)));+ const f = x / e;+ return (f < 2 ? 1 : f < 5 ? 2 : 5) * e;+}++export const fmtScale = (s: number) => s.toLocaleString('de-DE', { maximumFractionDigits: 0 });diff --git a/app/src/renderer/style.css b/app/src/renderer/style.cssindex ed3eabb..d9c8c60 100644--- a/app/src/renderer/style.css+++ b/app/src/renderer/style.css@@ -520,6 +520,10 @@ code { font-family:var(--mono); font-size:.95em; }.vv-bar { left:50%; bottom:12px; transform:translateX(-50%); width:min(940px, calc(100% - 24px)); display:flex; align-items:center; gap:4px; padding:4px 6px; }.vv-bar input[type=range] { flex:1 1 140px; min-width:90px; }.vv-bar .an-time { flex-shrink:0; }+/* FEM (E65): Lastfall in Blau wie die Markierungen im Bild, Hinweise umbrechend und leiser */+.rs-fem select { font-family:var(--sans); }+.rs-row.bc b { color:var(--mk-blue); font-weight:500; }+.rs-note { padding:2px 14px; font-size:11.5px; line-height:1.35; color:var(--tx3); }.vv-title { display:flex; align-items:center; gap:7px; padding:0 6px; min-width:0; max-width:220px; flex-shrink:2; color:var(--tx2); }.vv-title b { color:var(--tx); font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }.vv-bar .ibtn { width:30px; height:30px; display:flex; align-items:center; justify-content:center; border-radius:6px; }diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex 67a9447..8823593 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -174,6 +174,18 @@ export interface ResultPart {name: string; group: string | null; area: number; critical: number; min?: number; max?: number;worst?: { value: number; at: number[] }; overlap?: number; contact?: number;}+ /** Nur FEM: höchste Vergleichsspannung (MPa), größte Verschiebung (mm), Werkstoff. */+ stress?: { value: number; at: number[] }; displacement?: { value: number; at: number[] };+ material?: { name: string; E: number; strength: number; note?: string | null };+}+/** Randbedingung einer FEM-Studie (soma analyze fem): fest, Kraft oder Druck auf Flächen eines Teils. */+export interface FemBc {+ kind: 'fix' | 'force' | 'pressure'; part: string; label: string; area: number; at: number[];+ axes?: string; reaction?: number[]; total?: number[]; value?: number;+}+export interface FemInfo {+ study: string; bcs: FemBc[]; applied: number[]; reaction: number[]; maxDisp: number; diag: number;+ mesh: { size: number; elements: number; dofs: number; solver: string };export interface ResultMeta {id: string; kind: string; title: string; quantity: string; unit: string;/** Welche Seite des Grenzwerts kritisch ist. */@@ -183,6 +195,9 @@ export interface ResultMeta {neutral?: [number, number] | null;parts: ResultPart[]; summary: string; created: number; command: string[];}+ /** Hinweise der Auswertung (FEM: Netzabhängigkeit, große Verformung, Werkstoff). */+ notes?: string[];+ fem?: FemInfo | null;export interface ResultEntry extends ResultMeta { file: string; stale: boolean }/** Auftrag an das unsichtbare Render-Fenster (E58). Die Dateien kommen als Inhalt mit, das Fenster liest selbst nichts. */diff --git a/app/test/fem.mjs b/app/test/fem.mjsnew file mode 100644index 0000000..9cb22d4--- /dev/null+++ b/app/test/fem.mjs@@ -0,0 +1,174 @@+// Test der FEM-Auswertung (E65): soma analyze fem mit einer Studie in analyses/, Vergleich mit der Balkenformel, verschmolzene+// Teile mit eigenem Werkstoff, Druck, Eigengewicht und near=, Fehlermeldungen (Lagerung, Bauteil, Selektor, kein fix), Anzeige in+// der App (Karte mit Lastfall, Überhöhung, Wert unter dem Zeiger in Ausgangslage, An Agent geben), soma render --result,+// veraltet nach Änderung der Studie, Neu berechnen und das Beispiel aus dem Skill.+// Aufruf: node test/run-all.mjs fem (baut vorher mit npm run build). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder ab.+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';++const t = checker();+const { check } = t;+let app;++const PY = process.env.SOMA_PYTHON || path.join(process.env.LOCALAPPDATA ?? '', 'cadide-phase0', 'venv-full', 'Scripts', 'python.exe');++// Kragbalken 100 x 10 x 10 entlang +X (Formel: w = 4 F L³ / (E b h³)), ein Winkel aus zwei Teilen, die sich berühren, und die+// Konsole aus dem Beispiel im Skill+const MODEL = `import cadquery as cq+from soma import add_part++add_part("Balken", cq.Workplane().box(100, 10, 10, centered=(False, True, True)))+fuss = cq.Workplane().box(60, 40, 5, centered=(True, True, False)).translate((0, 100, 0))+wand = cq.Workplane().box(5, 40, 40, centered=(True, True, False)).translate((27.5, 100, 5))+add_part("Fuss", fuss)+add_part("Wand", wand)+bracket = cq.Workplane().box(40, 20, 4, centered=(False, True, False)).union(+ cq.Workplane().box(4, 20, 30, centered=(False, True, False))).translate((0, -100, 0))+add_part("Bracket", bracket)+`;+const BALKEN = (n) => `from soma.fem import Study+study = Study("Balken unter Last", material="Aluminium 6082", safety=2)+study.fix("Balken", faces="<X")+study.force("Balken", faces=">X", N=(0, 0, ${-n}))+`;+const WINKEL = `from soma.fem import Study+study = Study("Winkel", material="Aluminium 6082", safety=1.5)+study.set_material("Wand", "Steel S235")+study.fix("Fuss", faces="<Z")+study.pressure("Wand", near=(30, 100, 30), MPa=0.2)+study.gravity()+`;+const LOSE = `from soma.fem import Study+study = Study("lose", material="PLA")+study.fix("Fuss", faces="<Z", axes="z")+study.force("Wand", faces=">Z", N=(-10, 0, 0))+`;++const near = (a, b, eps) => Math.abs(a - b) <= eps;+const pngSize = (f) => { const b = fs.readFileSync(f); return b.toString('ascii', 1, 4) === 'PNG' ? [b.readUInt32BE(16), b.readUInt32BE(20)] : null; };++try {+ app = await startApp({ name: 'fem' });+ const { ev, waitFor, domClick } = app;+ const shot = async (name) => {+ if (!process.env.SMOKE_SHOTS) return;+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });+ await sleep(900);+ await app.screenshot(path.join(APP, 'test', 'shots', `${name}.png`)).catch((e) => console.log('Screenshot:', e.message));+ };+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok' && window.__t.partCount() > 0);+ const dir = (await ev(() => window.__t.project())).dir;+ fs.writeFileSync(path.join(dir, 'model.py'), MODEL);+ await waitFor('Testmodell gebaut', () => window.__t.status().state === 'ok' && window.__t.partCount() === 4, 90000);+ const bridge = await ev(() => window.soma.test.bridge());+ const env = { ...process.env, ...bridge, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' };+ const soma = (args) => spawnSync(PY, ['-m', 'soma', ...args], { cwd: dir, env, encoding: 'utf8', timeout: 10 * 60 * 1000 });+ fs.mkdirSync(path.join(dir, 'analyses'));+ const study = (name, text) => fs.writeFileSync(path.join(dir, 'analyses', `${name}.py`), text);++ // 1) Kragbalken gegen die Formel: w = 4 * 50 * 100³ / (70000 * 10 * 10³) = 0,2857 mm, Spannung an der Einspannung 30 MPa+ study('balken', BALKEN(50));+ let r = soma(['analyze', 'fem', 'analyses/balken.py']);+ const w = Number(/größte Verschiebung (\d+\.\d+) mm/.exec(r.stdout)?.[1]);+ const s = Number(/höchste Vergleichsspannung (\d+\.\d) MPa/.exec(r.stdout)?.[1]);+ check('Kragbalken: Durchbiegung wie die Formel (0,286 mm, ±2 %)', r.status === 0 && near(w, 0.2857, 0.006), r.stdout + r.stderr);+ check('Kragbalken: Spannung an der Einspannung um 30 MPa, Sicherheit über 2, nichts kritisch', near(s, 30, 4) && /kleinste Sicherheit [5-9]\.\d\d, nichts unter 2/.test(r.stdout), r.stdout);+ check('Lastfall in der Ausgabe: fest 100 mm² mit Lagerkraft 50 N, Kraft 100 mm², im Gleichgewicht', /fest: Balken <X \(100\.0 mm²\), Lagerkraft \(0\.0, 0\.0, 50\.0\) N/.test(r.stdout)+ && /Kraft: Balken >X \(100\.0 mm²\), \(0\.0, 0\.0, -50\.0\) N/.test(r.stdout) && r.stdout.includes('(im Gleichgewicht)'), r.stdout);+ check('Netzprüfung: zweite Rechnung mit gröberem Netz genannt, Hinweis zur Spitze an der Einspannung', /mit gröberem Netz \d+\.\d MPa/.test(r.stdout)+ && r.stdout.includes('am Rand einer Einspannung'), r.stdout);+ check('Ergebnisdatei .soma/results/balken.glb', fs.existsSync(path.join(dir, '.soma', 'results', 'balken.glb')));++ // 2) Zwei verschmolzene Teile mit eigenem Werkstoff, Druck über near=, Eigengewicht+ study('winkel', WINKEL);+ r = soma(['analyze', 'fem', 'analyses/winkel.py']);+ check('Winkel: beide Teile mit ihrem Werkstoff, Druck 0,2 MPa auf 1600 mm² (320 N), Eigengewicht, im Gleichgewicht', r.status === 0+ && /Fuss \(Aluminium 6082/.test(r.stdout) && /Wand \(Steel S235/.test(r.stdout) && /Druck: Wand nahe \(30, 100, 30\) \(1600\.0 mm²\), 0\.2 MPa, zusammen \(-320\.0, 0\.0, 0\.0\) N/.test(r.stdout)+ && r.stdout.includes('Eigengewicht') && r.stdout.includes('(im Gleichgewicht)'), r.stdout + r.stderr);+ check('Winkel: Einspannung 2400 mm² trägt Druck und Gewicht', /fest: Fuss <Z \(2400\.0 mm²\), Lagerkraft \(320\.0, 0\.0, \d\.\d\) N/.test(r.stdout), r.stdout);++ // 3) Fehler: verständlich, Exit 1, keine Ergebnisdatei+ study('lose', LOSE);+ r = soma(['analyze', 'fem', 'analyses/lose.py']);+ check('Nur in Z gehalten: meldet, was noch frei ist', r.status === 1 && /Lagerung reicht nicht[^\n]*Fuss, Wand: noch frei beweglich \([^)]*Verschiebung in X/.test(r.stderr + r.stdout), r.stderr + r.stdout);+ study('kaputt', BALKEN(1).replace('fix("Balken"', 'fix("Gibtsnicht"'));+ r = soma(['analyze', 'fem', 'analyses/kaputt.py']);+ check('Unbekanntes Bauteil: nennt die vorhandenen', r.status === 1 && (r.stderr + r.stdout).includes("Bauteil 'Gibtsnicht' gibt es nicht") && (r.stderr + r.stdout).includes("'Balken'"), r.stderr + r.stdout);+ study('kaputt', BALKEN(1).replace('faces="<X"', 'faces="<Q"'));+ r = soma(['analyze', 'fem', 'analyses/kaputt.py']);+ check('Falscher Selektor: Fehler nennt ihn', r.status === 1 && (r.stderr + r.stdout).includes("Selektor '<Q'"), r.stderr + r.stdout);+ study('kaputt', BALKEN(1).replace(/study\.fix[^\n]*\n/, ''));+ r = soma(['analyze', 'fem', 'analyses/kaputt.py']);+ check('Ohne fix: verlangt eine Einspannung', r.status === 1 && (r.stderr + r.stdout).includes('Mindestens ein study.fix'), r.stderr + r.stdout);+ study('kaputt', 'from soma.fem import Study\nx = 1 / 0\n');+ r = soma(['analyze', 'fem', 'analyses/kaputt.py']);+ check('Fehler im Code der Studie: Datei und Zeile 2', r.status === 1 && (r.stderr + r.stdout).includes('analyses/kaputt.py (Zeile 2): ZeroDivisionError'), r.stderr + r.stdout);+ r = soma(['analyze', 'fem']);+ check('Ohne Studie: Hinweis auf die Datei', r.status === 1 && (r.stderr + r.stdout).includes('braucht die Datei mit dem Lastfall'), r.stderr + r.stdout);+ check('Fehler legen keine Ergebnisse an', !fs.existsSync(path.join(dir, '.soma', 'results', 'kaputt.glb')) && !fs.existsSync(path.join(dir, '.soma', 'results', 'lose.glb')));++ // 4) Anzeige in der App: Karte mit Lastfall und Überhöhung, Wert unter dem Zeiger in Ausgangslage+ await ev(() => window.__t.openViewMenu());+ await ev(() => { [...document.querySelectorAll('#menu-view .mi')].find((b) => b.textContent.includes('Balken unter Last')).click(); });+ await waitFor('FEM-Ergebnis geladen', () => window.__t.result().id === 'balken', 20000);+ let rs = await ev(() => window.__t.result());+ // Überhöhung: 5 % von 101 mm / 0,286 mm = 17,7, auf eine runde Zahl abgerundet 10+ check('Karte: Sicherheit, Spannung, Verschiebung je Teil, Lastfall in zwei Zeilen, verformt 10-fach', rs.active && rs.fem+ && rs.rows.some((x) => x.startsWith('Balken') && /Sicherheit \d+,\d+ · 30(,\d)? MPa · 0,28\d mm$/.test(x))+ && rs.fem.bcRows.length === 2 && rs.fem.bcRows[0].startsWith('fest') && rs.fem.bcRows[0].includes('Lagerkraft 50 N') && rs.fem.bcRows[1].startsWith('Kraft')+ && rs.fem.scale === 10 && rs.fem.options.includes('10-fach überhöht') && rs.fem.bcs === true && rs.meta.unit === '', JSON.stringify(rs));+ check('Hinweis in der Karte nennt den Befehl mit der Studie', rs.hint.startsWith('soma analyze fem analyses/balken.py'), rs.hint);+ await ev(() => window.__t.viewer.setView('front'));+ await sleep(300);+ // Vorderseite am Ende: um 10 x 0,28 mm nach unten verschoben gezeichnet, der Wert nennt die Stelle im unverformten Modell+ const at = await ev(() => window.__t.viewer.screenAt([97, -5, -2.8]));+ const pin = await ev((p) => window.__t.resultPin(p.x, p.y), at);+ check('Klick auf das verformte Balkenende: Stelle in Ausgangslage, Verschiebung um 0,28 mm, Spannung klein', pin?.name === 'Balken'+ && near(pin.point[0], 97, 1) && near(pin.point[2], 0, 1.2) && near(pin.disp, 0.28, 0.03) && pin.stress < 5 && pin.value > 20, JSON.stringify(pin));+ rs = await ev(() => window.__t.result());+ check('An Agent geben: Sicherheit, Spannung und Verschiebung', /^\[Ergebnis: "Balken unter Last" \(\.soma\/results\/balken\.glb, Grenzwert 2\.00\), Bauteil "Balken": Sicherheit (über 99|\d+\.\d\d) \(\d+\.\d MPa, Verschiebung 0\.2\d\d mm\) bei \(/.test(rs.note), rs.note);+ await ev(() => window.__t.viewer.setView('iso'));+ await shot('fem-1');+ await ev(() => { const s = document.getElementById('result-deform'); s.value = '0'; s.dispatchEvent(new Event('change')); });+ await domClick('btn-result-bcs');+ rs = await ev(() => window.__t.result());+ check('Unverformt und Lastfall aus', rs.fem.scale === 0 && rs.fem.bcs === false, JSON.stringify(rs.fem));+ await domClick('btn-result-bcs');++ // 5) soma render --result: Bild mit Legende+ r = soma(['render', '--result', 'balken']);+ check('soma render --result balken: Bild 1280 x 800', r.status === 0 && JSON.stringify(pngSize(path.join(dir, 'renders', 'ergebnis-balken.png'))) === '[1280,800]', r.stdout + r.stderr);++ // 6) Studie ändern: Ergebnis veraltet (die Studie zählt mit), Neu berechnen rechnet die neue Last+ await sleep(1100);+ study('balken', BALKEN(100));+ const stale = await ev(() => window.soma.results.list().then((l) => l.find((x) => x.id === 'balken')?.stale));+ check('Geänderte Studie: Ergebnis veraltet', stale === true, String(stale));+ await ev(() => window.__t.resultRefresh?.());+ await domClick('btn-result-rerun');+ await waitFor('neu berechnet', () => window.__t.result().stale === false && window.__t.result().fem?.bcRows?.[0]?.includes('100 N'), 120000).catch(() => {});+ rs = await ev(() => window.__t.result());+ check('Neu berechnen: Lagerkraft jetzt 100 N, Verschiebung doppelt', !rs.stale && rs.fem?.bcRows[0].includes('Lagerkraft 100 N')+ && rs.rows.some((x) => x.startsWith('Balken') && /0,5[67]\d mm/.test(x)), JSON.stringify(rs));+ await domClick('btn-result-close');+ check('Analyse aus: Modell wieder sichtbar', !(await ev(() => window.__t.viewer.animViewState())).modelHidden);++ // 7) Das Beispiel im Skill läuft so, wie es dasteht+ const skill = fs.readFileSync(path.join(APP, 'resources', 'skills', 'fem.md'), 'utf8');+ const block = /```python\r?\n([\s\S]*?)\r?\n```/.exec(skill)?.[1] ?? '';+ study('skill', block);+ r = soma(['analyze', 'fem', 'analyses/skill.py']);+ check('Beispiel aus dem Skill „Festigkeit mit FEM“ rechnet ohne Fehler', r.status === 0 && r.stdout.includes('FEM "Bracket, 5 kg on the arm"')+ && /Bracket \(PETG/.test(r.stdout), r.stdout.slice(0, 600) + r.stderr);+} catch (e) {+ t.fail();+ console.log('ABBRUCH:', e);+ console.log(app?.log().slice(-3000));+} finally {+ await app?.stop();+ if (app) cleanup(app.ud);+}+console.log(t.fails ? `\n${t.fails} PRÜFUNG(EN) FEHLGESCHLAGEN` : '\nALLE PRÜFUNGEN BESTANDEN');+process.exit(t.fails ? 1 : 0);diff --git a/app/test/run-all.mjs b/app/test/run-all.mjsindex ab35cb1..f445323 100644--- a/app/test/run-all.mjs+++ b/app/test/run-all.mjs@@ -9,7 +9,7 @@ import path from 'node:path';const DIR = import.meta.dirname;// Längste zuerst, damit sie nicht am Ende allein laufen-const ALL = ['animation', 'versions', 'smoke', 'editor', 'skills', 'explode', 'fasteners', 'section', 'measure', 'groups', 'unit'];+const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'explode', 'fasteners', 'section', 'measure', 'groups', 'unit'];const wanted = process.argv.slice(2);const unknown = wanted.filter((s) => !ALL.includes(s));if (unknown.length) { console.log(`Unbekannte Suite: ${unknown.join(', ')}. Vorhanden: ${ALL.join(', ')}`); process.exit(2); }diff --git a/app/test/skills.mjs b/app/test/skills.mjsindex a2fb242..542c018 100644--- a/app/test/skills.mjs+++ b/app/test/skills.mjs@@ -60,13 +60,13 @@ try {/** Die beiden Listen des Abschnitts: Immer vor „Read when relevant“, Bei Bedarf danach. */const always = () => (block() ?? '').split('### Read when relevant')[0];const demand = () => (block() ?? '').split('### Read when relevant')[1] ?? '';- const DEMAND_NEW = '3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation';+ const DEMAND_NEW = '3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation,fem';// 1) Panel: die mitgelieferten Skills nach Kategorien und `order`await ev(() => document.querySelector('#rail [data-panel="skills"]').click());await waitFor('Skills geladen', () => window.__t.skills().skills.length >= 3, 10000);let s = await st();- const ORDER = 'konstruktionsablauf,cadquery,3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,normteile,festigkeit,baugruppen,analyse,animation';+ const ORDER = 'konstruktionsablauf,cadquery,3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,normteile,festigkeit,baugruppen,analyse,animation,fem';const heads = await ev(() => [...document.querySelectorAll('#skills-list .sk-cat')].map((h) => h.textContent).join(','));check('Panel „Skills": Überschriften Arbeitsweise, Fertigungsverfahren, Konstruktionswissen, Prüfen und Zeigen, darunter die Skills nach `order`',s.skills.map((x) => x.id).join(',') === ORDER && heads === 'Arbeitsweise,Fertigungsverfahren,Konstruktionswissen,Prüfen und Zeigen'@@ -91,7 +91,7 @@ try {&& always().includes('- `.soma/skills/normteile.md`: Standard parts') && !always().includes('3d-druck')&& demand().includes('- `.soma/skills/3d-druck.md`: 3D printing (FDM). Read when the parts will be 3D printed on a filament printer (FDM).')&& DEMAND_NEW.split(',').every((id) => demand().includes(`.soma/skills/${id}.md`))- && (await g('ls-files', '.soma/skills')).split('\n').length === 14+ && (await g('ls-files', '.soma/skills')).split('\n').length === 15&& (await ev(() => window.__t.saveState())).dirtyFiles === 0, `${String((await ev(() => window.__t.saveState())).dirtyFiles)} | ${String(block()).slice(0, 200)}`);check('Zeile mit Stufen-Schalter, Klick auf die Zeile öffnet die Karte mit drei Stufen, die eingestellte gewählt', await ev(() => {document.querySelector('#skills-list .sk-row[data-id="3d-druck"] .sk-open').click();@@ -308,12 +308,12 @@ try {const fdm2 = fs.readFileSync(path.join(p2.dir, '.soma', 'skills', '3d-druck.md'), 'utf8');const ka2 = fs.readFileSync(path.join(p2.dir, '.soma', 'skills', 'konstruktionsablauf.md'), 'utf8');check('Neues Modell nach der Vorgabe: immer Sauber modellieren, 3D-Druck, Normteile, Laser aus, Konstruktionsablauf bei Bedarf, Standardwerte statt 55° und PETG',- JSON.stringify(pj2.skills) === '["cadquery","3d-druck","normteile"]' && pj2.skills_on_demand.join(',') === 'konstruktionsablauf,harz-pulver,cnc,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation'+ JSON.stringify(pj2.skills) === '["cadquery","3d-druck","normteile"]' && pj2.skills_on_demand.join(',') === 'konstruktionsablauf,harz-pulver,cnc,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation,fem'&& !pj2.skill_settings && fdm2.includes('Overhangs up to 45°') && fdm2.includes('| Material | PLA |') && !fdm2.includes('On demand') && ka2.includes('> **On demand:**')&& !fs.existsSync(path.join(p2.dir, '.soma', 'skills', 'laser.md'))&& norm(fs.readFileSync(path.join(p2.dir, 'AGENTS.md'), 'utf8')).includes('- `.soma/skills/3d-druck.md`: 3D printing (FDM)\n'), JSON.stringify(pj2));await waitFor('Speicherstand neu', () => window.__t.saveState() && !window.__t.saveState().unsaved, 10000).catch(() => {});- check('Neues Modell: Skills im Startcommit, nichts ungespeichert', (await exec(['ls-files', '.soma/skills'], p2.dir)).stdout.trim().split('\n').length === 13+ check('Neues Modell: Skills im Startcommit, nichts ungespeichert', (await exec(['ls-files', '.soma/skills'], p2.dir)).stdout.trim().split('\n').length === 14&& (await ev(() => window.__t.saveState())).dirtyFiles === 0, String((await ev(() => window.__t.saveState())).dirtyFiles));const relevant = page.errors.filter((e) => !/favicon/i.test(e));diff --git a/app/test/unit.mjs b/app/test/unit.mjsindex f37dc88..abc5d6f 100644--- a/app/test/unit.mjs+++ b/app/test/unit.mjs@@ -199,10 +199,10 @@ try {const SKD = path.join(APP, 'resources', 'skills');const dm = defaultModes(SKD, {});check('Neue Modelle: ohne Vorgabe des Nutzers Arbeitsweise und Normteile immer, alle übrigen bei Bedarf', dm.always.join(',') === 'konstruktionsablauf,cadquery,normteile'- && dm.demand.join(',') === '3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation', JSON.stringify(dm));+ && dm.demand.join(',') === '3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation,fem', JSON.stringify(dm));const dm2 = defaultModes(SKD, { konstruktionsablauf: 'demand', toleranzen: 'always', '3d-druck': 'always', laser: 'off' });check('Neue Modelle: Vorgabe des Nutzers geht vor, in der Reihenfolge des Panels, „Aus“ fehlt ganz', dm2.always.join(',') === 'cadquery,3d-druck,toleranzen,normteile'- && dm2.demand.join(',') === 'konstruktionsablauf,harz-pulver,cnc,blech,verbindungen,festigkeit,baugruppen,analyse,animation', JSON.stringify(dm2));+ && dm2.demand.join(',') === 'konstruktionsablauf,harz-pulver,cnc,blech,verbindungen,festigkeit,baugruppen,analyse,animation,fem', JSON.stringify(dm2));// Bei Bedarf (E55): Hinweis unter der ersten Überschrift, Werte als Standard der App, vom Nutzer gesetzte mit Namenconst rd = renderSkill(SRC, {}, 'demand');check('Bei Bedarf: Hinweis direkt unter der Überschrift, mit Leerzeilen, Werte als Standard der App, NOTES.md', rd.includes('# Skill\n\n> **On demand:**')