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: Kontaktpressung im Ergebnis, Kontakt im Bericht (E84)
Kai-Jungsthoefel4cb34399c28d
diff --git a/app/resources/skills/fem.md b/app/resources/skills/fem.mdindex dffe17b..40d204e 100644--- a/app/resources/skills/fem.md+++ b/app/resources/skills/fem.md@@ -1,18 +1,18 @@---title: Strength with FEMname: Strength with FEM-summary: Stresses, safety factor and deformation under load with the finite element method (soma analyze fem), load case as a Python file, colored result in the app.+summary: Stresses, safety factor and deformation under load with the finite element method (soma analyze fem), also with parts pressing and sliding on each other (contact), load case as a Python file, colored result in the app.order: 32category: Check and presentdefault: on-demandwhen: 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: Load case; Compute and read; Check the result; Limits; Feedback+topics: Load case; Parts that touch; Compute and read; Check the result; Limits; Feedbackvar safety: 2 | | Safety factor | 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:+`soma analyze fem <study.py>` computes stresses and deflection of parts under load (linear-elastic finite elements,+solved with CalculiX), also with parts that press on each other and slide (contact), 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@@ -34,9 +34,8 @@ study.force("Bracket", faces=">X", N=(0, 0, -49)) # total force on the facePA, 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.+- Parts are named as in `add_part`. All parts in one study are meshed together and **bonded where they touch** (glued),+ unless `study.contact()` says otherwise (see below). `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=`.@@ -50,6 +49,28 @@ study.force("Bracket", faces=">X", N=(0, 0, -49)) # total force on the faceModel a screw by holding the face under its head or the inside of its hole. Put a load where it really acts: on theface the hand, the shelf or the shaft touches, not on a whole side.+## Parts that touch++The result lists every pair of parts that touch, with the area, as `touching: Lid – Housing (1240.0 mm²), bonded`.+Decide for each pair how it is really joined:++| The parts are | In the study |+|---|---|+| glued, welded, printed in one piece, press-fitted | nothing (bonded) |+| resting on each other, can lift off | `study.contact("Lid", "Housing")` |+| clamped or screwed together, sliding is the question | `study.contact("Lid", "Housing", friction=0.2)` |++- `study.contact(part_a, part_b, friction=0.0)`: the touching faces press on each other, can lift off and slide.+ Friction about 0.1 to 0.2 for steel or aluminium, 0.3 to 0.5 for plastics on plastics, 0.5 or more for rubber.+- Contact only works where faces **lie on each other in the model** (no gap, not just a line or a point). Model the+ parts touching as assembled.+- A part held only by a contact without friction can slide sideways: the command says so before it calculates. Give it+ friction, a `fix()` or leave it bonded. If a part slides or lifts off for good under the load, the calculation stops+ and says so.+- The result gives per contact the force it carries, the highest pressure, where it is open (gap) and where it slides+ at the friction limit. In the app, "Contact pressure" colours the touching faces.+- Contact takes longer: from about ten seconds to a few minutes, mostly with friction.+## Compute and read1. `soma build`, then `soma analyze fem analyses/bracket.py`. Takes from seconds to about a minute. The summary lists the@@ -74,8 +95,9 @@ face the hand, the shelf or the shaft touches, not on a whole side.## 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.+- Linear-elastic: no yielding, no buckling, no pre-tension of screws, no creep of plastics. Contact assumes small+ sliding (the faces stay opposite each other).+- Bearings, hinges and screws are modelled through supports, loads and contact, not as joints.- Even materials: printing infill, layer direction and wood grain are not modelled. Printed parts are therefore computedwith 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.diff --git a/app/src/main/about.ts b/app/src/main/about.tsindex 0330148..5f28b08 100644--- a/app/src/main/about.ts+++ b/app/src/main/about.ts@@ -38,7 +38,7 @@ def info(name):if not lic:lic = ', '.join(c.split('::')[-1].strip() for c in (md.get_all('Classifier') or []) if c.startswith('License ::'))return {'name': md.get('Name') or name, 'version': d.version, 'license': lic}-names = ['soma', 'cadquery', 'cadquery-ocp', 'ezdxf', 'numpy', 'scipy', 'matplotlib', 'vtk', 'pyamg']+names = ['soma', 'cadquery', 'cadquery-ocp', 'ezdxf', 'numpy', 'scipy', 'matplotlib', 'vtk', 'gmsh', 'pyamg']try:for r in m.requires('soma') or []:if 'extra ==' in r:@@ -56,6 +56,13 @@ try:p['version'] = soma.__version__except Exception:pass+try:+ # CalculiX ist kein Python-Paket: soma findet es neben der Umgebung (E84) und fragt es nach seiner Version+ from soma import ccx+ v = ccx.version()+ packages.append({'name': 'CalculiX (ccx)', 'version': v or ('not found' if ccx.find() is None else 'does not start'), 'license': 'GPL-2.0-or-later'})+except Exception:+ passprint(json.dumps({'version': sys.version.split()[0], 'executable': sys.executable, 'packages': packages}))`;diff --git a/app/src/renderer/analysispanel.ts b/app/src/renderer/analysispanel.tsindex 2cd62be..68d275e 100644--- a/app/src/renderer/analysispanel.ts+++ b/app/src/renderer/analysispanel.ts@@ -188,6 +188,24 @@ export class AnalysisPanel {if (fem.gravity && Math.hypot(...fem.gravity) > 0) {sec.append(...this.row('gravity', 'Gravity', `${loc(Math.hypot(...fem.gravity), 2)} m/s²`, direction(fem.gravity), [['Vector', `(${fem.gravity.map((x) => loc(x, 2)).join(', ')}) m/s²`], ['Mass', 'from the density of each material']]));}+ // Berührende Teile (E84): je Kontaktpaar eine Zeile, die verklebten zusammen in einer+ (fem.contacts ?? []).forEach((c, i) => {+ const pct = (a: number) => `${Math.round((100 * a) / Math.max(c.area, 1e-12))} %`;+ const det: [string, string | HTMLElement][] = [+ ['Faces', `${loc(c.area, 1)} mm²`], ['Carries', `${loc(c.force, 1)} N`],+ ['Highest pressure', `${loc(c.maxPressure.value, 2)} MPa`],+ ['Open', c.openArea > 0 ? `${pct(c.openArea)} of the faces, gap up to ${loc(c.maxGap, 3)} mm` : 'closed everywhere'],+ ];+ if (c.slideArea != null) det.push(['Sliding', c.slideArea > 0 ? el('span', { className: c.slideArea > 0.5 * c.area ? 'wc' : '', textContent: `${pct(c.slideArea)} at the friction limit` }) : 'sticks everywhere']);+ det.push(['Slip', `up to ${loc(c.maxSlip, 3)} mm`]);+ sec.append(...this.row(`contact${i}`, 'Contact', c.friction ? `Friction ${loc(c.friction, 2)}` : 'No friction', `${c.a} – ${c.b}`, det));+ });+ const bonded = (fem.touching ?? []).filter((t) => t.joint === 'bonded');+ if (bonded.length) {+ const det: [string, string][] = bonded.map((t) => [`${t.a} – ${t.b}`, `${loc(t.area, 1)} mm²`]);+ det.push(['Joined', 'glued where they touch; study.contact() makes it a contact']);+ sec.append(...this.row('bonded', 'Touching', 'Bonded', bonded.length === 1 ? `${bonded[0].a} – ${bonded[0].b}` : plural(bonded.length, 'pair'), det));+ }// Werkstoffe: je Werkstoff einmal, mit den Teilen dazuconst mats = new Map<string, { m: NonNullable<ResultPart['material']>; parts: string[] }>();for (const p of r.parts) if (p.material) {@@ -222,6 +240,7 @@ export class AnalysisPanel {['Element size', `${loc(mesh.size, 2)} mm${mesh.auto == null ? '' : mesh.auto ? ', automatic from the model size' : ', set in the study'}`],['Elements', `${mesh.elements.toLocaleString('en-US')} tetrahedra, 10 nodes`],...(mesh.nodes ? [['Nodes', mesh.nodes.toLocaleString('en-US')] as [string, string]] : []),+ ['Solver', mesh.solver],['Check', check],]));return sec;diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex 2efed30..8adb0f0 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -1579,7 +1579,7 @@ if (api.testMode) {resultRefresh: () => resultTool.refresh(),resultPin: (x: number, y: number) => resultTool.testPin(x, y),resultShow: (id: string) => resultTool.show(id),- resultField: (f: 'value' | 'stress' | 'disp') => resultTool.testField(f),+ resultField: (f: 'value' | 'stress' | 'disp' | 'press') => resultTool.testField(f),resultDeform: (sc: number) => resultTool.testDeform(sc),analysis: () => analysisPanel.state(),analysisToggle: (key: string) => analysisPanel.testToggle(key),diff --git a/app/src/renderer/resulttool.ts b/app/src/renderer/resulttool.tsindex ac86413..aa26c26 100644--- a/app/src/renderer/resulttool.ts+++ b/app/src/renderer/resulttool.ts@@ -45,8 +45,11 @@ export const safety = (v: number) => (v >= SAFETY_CAP ? `over ${SAFETY_CAP}` : lconst femAt = (p: ResultProbe, field: ResultField, label: boolean) => {const stress = p.stress != null ? `${loc(p.stress, 1)} MPa` : null;const disp = p.disp != null ? `${loc(p.disp, 3)} mm` : null;+ // Pressung nur, wo Kontakt ist (oder wenn sie die gezeigte Größe ist)+ const press = p.press != null && (p.press > 0 || field === 'press') ? `contact ${loc(p.press, 2)} MPa` : null;const sf = `${label || field !== 'value' ? 'Safety ' : ''}${safety(p.value)}`;- const parts = field === 'stress' ? [stress, sf, disp] : field === 'disp' ? [disp, sf, stress] : [sf, stress, disp];+ const parts = field === 'stress' ? [stress, sf, disp, press] : field === 'disp' ? [disp, sf, stress, press]+ : field === 'press' ? [press, sf, stress, disp] : [sf, stress, disp, press];return parts.filter(Boolean).join(' · ');};type RangeMode = 'auto' | 'minmax' | 'custom';@@ -55,7 +58,11 @@ const TIP_GAP = 14;/** Höhe des Verlaufs in der Legende (px). */const LEGEND_H = 160;const RANGE_LABEL: Record<RangeMode, string> = { auto: 'Auto', minmax: 'Min–max', custom: 'Custom' };-const FIELD_LABEL: Record<ResultField, string> = { value: 'Safety factor', stress: 'Stress', disp: 'Displacement' };+// Kurz, damit die Leiste mit vier Größen ins Bild passt (mit „Contact pressure“ fiel das × heraus), ausgeschrieben im Tooltip+const FIELD_LABEL: Record<ResultField, string> = { value: 'Safety factor', stress: 'Stress', disp: 'Displacement', press: 'Contact' };+const FIELD_TITLE: Record<ResultField, string> = { value: 'Safety factor', stress: 'von Mises stress', disp: 'Displacement', press: 'Contact pressure between parts' };+/** Die Kontaktflächen liegen zwischen den Teilen, im Bild sieht man sie erst, wenn ein Teil weg ist. */+const PRESS_HINT = 'The contact faces lie between the parts: hide one part in the structure tree or use a section to see them.';/** Kleinster Wert (kritisch darunter) oder größter (kritisch darüber) über alle Teile, mit dem Teil. */export function worstOf(r: ResultEntry): { part: string; value: number; at: number[] | null } | null {@@ -281,6 +288,7 @@ export class ResultTool {: v.ramp ? `Color across the range, limit ${withUnit(v.threshold, v.unit)}${weakest}`: `Red: ${v.bad === 'high' ? 'above' : 'below'} ${r.fem ? (this.d.layer.field === 'stress' ? 'allowable' : 'required') : 'the limit'}${weakest}`,this.d.layer.deformNote(),+ this.d.layer.field === 'press' ? PRESS_HINT : null,].filter((x): x is string => !!x);this.ui.legendFoot.replaceChildren(...foot.flatMap((t, i) => (i ? [el('br'), t] : [t])));this.ui.legend.title = foot.join('\n');@@ -297,13 +305,16 @@ export class ResultTool {this.ui.bcs.hidden = !fem;for (const sep of this.ui.bar.querySelectorAll<HTMLElement>('.vsep[data-fem]')) sep.hidden = !fem;if (!fem) return;- const fields: ResultField[] = ['value', ...(l.canStress ? ['stress' as const] : []), ...(l.canDisp ? ['disp' as const] : [])];+ const fields = (['value', 'stress', 'disp', 'press'] as const).filter((f) => l.available(f));this.ui.field.replaceChildren(...fields.map((f) => {- const b = el('button', { textContent: FIELD_LABEL[f], className: l.field === f ? 'on' : '' });+ const b = el('button', { textContent: FIELD_LABEL[f], className: l.field === f ? 'on' : '', title: FIELD_TITLE[f] });b.setAttribute('role', 'radio');b.setAttribute('aria-checked', String(l.field === f));b.dataset.field = f;- b.addEventListener('click', () => { this.field = f; this.applyScale(); this.renderLegend(); this.renderBar(); this.renderTags(); this.d.changed(); });+ b.addEventListener('click', () => {+ if (f === 'press' && this.field !== 'press') this.d.toast(PRESS_HINT, 'info');+ this.field = f; this.applyScale(); this.renderLegend(); this.renderBar(); this.renderTags(); this.d.changed();+ });return b;}));const scales: [number, string][] = [[0, 'Off'], [1, '1×']];@@ -360,6 +371,16 @@ export class ResultTool {};if (l.field === 'stress') peak('stress', 'MPa', 1);else if (l.field === 'disp') peak('displacement', 'mm', 3);+ else if (l.field === 'press') {+ // Höchste Pressung über alle Kontaktpaare, an der Stelle auf dem weicheren Teil (dort rechnet CalculiX sie)+ let best: { part: string; value: number; at: number[] } | null = null;+ for (const c of r.fem?.contacts ?? []) if (!best || c.maxPressure.value > best.value) best = { part: c.a, value: c.maxPressure.value, at: c.maxPressure.at };+ if (best && (visible(best.part) || r.fem?.contacts?.some((c) => visible(c.b)))) {+ const d = el('span', { className: 'dot' });+ d.style.background = 'var(--tx2)';+ tags.push({ el: el('div', { className: 'c3d pt' }, d, 'Max ', el('b', { textContent: `${loc(best.value, 2)} MPa` })), at: l.shownAt(best.part, best.at) });+ }+ }else if (w) spotTag(w.part, 'Min ', val(w.value));if (this.spot && this.spot !== w?.part) {const p = r.parts.find((x) => x.name === this.spot);@@ -388,7 +409,7 @@ export class ResultTool {private applyScale(): void {const l = this.d.layer, r = this.current;if (!l.meta || !r) return;- const field: ResultField = this.field === 'stress' && l.canStress ? 'stress' : this.field === 'disp' && l.canDisp ? 'disp' : 'value';+ const field: ResultField = l.available(this.field) ? this.field : 'value';let range: [number, number] | null = null;if (this.mode === 'minmax') range = l.dataRange(field);else if (this.mode === 'custom') {@@ -469,7 +490,8 @@ export class ResultTool {const head = `[Result: "${r.title}" (${r.file}, limit ${dot(r.threshold, r.unit)})`;const p = this.pinned;// 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 ? `, displacement ${p.disp.toFixed(3)} mm` : ''})` : '';+ const extra = p && p.stress != null ? ` (${p.stress.toFixed(1)} MPa${p.disp != null ? `, displacement ${p.disp.toFixed(3)} mm` : ''}`+ + `${p.press ? `, contact pressure ${p.press.toFixed(2)} MPa` : ''})` : '';return p ? `${head}, part "${p.name}": ${r.fem ? 'safety factor ' : ''}${r.fem && p.value >= SAFETY_CAP ? `over ${SAFETY_CAP}` : dot(p.value, r.unit)}${extra} at (${p.point.map((v) => v.toFixed(1)).join(', ')}) mm] ` : `${head}] `;}@@ -489,7 +511,7 @@ export class ResultTool {tags: [...this.ui.viewerEl.querySelectorAll('.v-overlay .c3d')].map((x) => x.textContent),// Nur was zu sehen ist (ohne FEM fehlen Größe, Verformung und Lastfall)bar: this.ui.bar.hidden ? null : [...this.ui.bar.children].filter((c) => !(c as HTMLElement).hidden).map((c) => c.textContent?.trim()).filter(Boolean).join(' · '),- scale: { field: l.field, mode: this.mode, canStress: l.canStress, canDisp: l.canDisp, range: l.view?.range ?? null,+ scale: { field: l.field, mode: this.mode, canStress: l.canStress, canDisp: l.canDisp, canPress: l.canPress, range: l.view?.range ?? null,threshold: l.view?.threshold ?? null, unit: l.view?.unit ?? null, legend: this.ui.legend.hidden ? '' : `${this.ui.legend.textContent ?? ''} ${this.ui.scaleMenu.textContent ?? ''}`.replace(/\s+/g, ' ').trim() },fem: this.current?.fem && this.active ? {deform: String(l.scale), options: [...this.ui.deform.querySelectorAll('button')].map((o) => o.textContent),diff --git a/app/src/renderer/resultview.ts b/app/src/renderer/resultview.tsindex d948491..d377f46 100644--- a/app/src/renderer/resultview.ts+++ b/app/src/renderer/resultview.ts@@ -9,9 +9,11 @@ import type { Viewer } from './viewer';// (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.+// Mit Kontakt (E84) kommt die Kontaktpressung je Ecke dazu (_PRESS, auf beiden Seiten der Berührfläche, sonst 0).interface ResultMesh {mesh: THREE.Mesh; name: string; values: THREE.BufferAttribute; stress?: THREE.BufferAttribute; disp?: THREE.BufferAttribute;+ press?: THREE.BufferAttribute;/** Betrag der Verschiebung je Ecke (mm), aus `disp` beim Laden berechnet. */dispMag?: THREE.BufferAttribute;}@@ -21,12 +23,15 @@ interface Arrow { obj: THREE.Object3D; base: THREE.Vector3; shift: THREE.Vector3export interface ResultProbe {name: string; value: number; point: number[];- /** FEM: Vergleichsspannung (MPa) und Betrag der Verschiebung (mm) an der Stelle. */- stress?: number; disp?: number;+ /** FEM: Vergleichsspannung (MPa), Betrag der Verschiebung (mm) und Kontaktpressung (MPa) an der Stelle. */+ stress?: number; disp?: number; press?: number;}-/** Gezeigte Größe: der Wert der Auswertung (bei FEM die Sicherheit), bei FEM auch die Vergleichsspannung nach von Mises oder der Betrag der Verschiebung. */-export type ResultField = 'value' | 'stress' | 'disp';+/**+ * Gezeigte Größe: der Wert der Auswertung (bei FEM die Sicherheit), bei FEM auch die Vergleichsspannung nach von Mises, der Betrag+ * der Verschiebung oder, mit Kontakt, die Kontaktpressung.+ */+export type ResultField = 'value' | 'stress' | 'disp' | 'press';/** Blau des Lastfalls: keine Statusfarbe, nicht Orange (Aktion) und nicht Violett (Vorschau). */const BC_COLOR = 0x5ea8ff;@@ -58,6 +63,8 @@ export class ResultLayer {get canStress(): boolean { return this.isFem && this.stressLimit > 0 && this.meshes.length > 0 && this.meshes.every((m) => m.stress); }/** Verschiebung zeigbar: FEM mit _DISP an jedem Netz. */get canDisp(): boolean { return this.isFem && this.meshes.length > 0 && this.meshes.every((m) => m.dispMag); }+ /** Kontaktpressung zeigbar: FEM mit Kontakt (_PRESS an jedem Netz). */+ get canPress(): boolean { return this.isFem && this.meshes.length > 0 && this.meshes.every((m) => m.press); }/** Grenze der Spannung gilt nur für den schwächsten von mehreren Werkstoffen. */get stressLimitMixed(): boolean { return this.stressMixed; }@@ -73,7 +80,9 @@ export class ResultLayer {? { ...m, quantity: 'von Mises stress', unit: 'MPa', bad: 'high', threshold: this.stressLimit, range: this.autoRange('stress') }: this.field === 'disp'? { ...m, quantity: 'Displacement', unit: 'mm', bad: 'high', threshold: NaN, range: this.autoRange('disp'), ramp: true }- : m;+ : this.field === 'press'+ ? { ...m, quantity: 'Contact pressure', unit: 'MPa', bad: 'high', threshold: NaN, range: this.autoRange('press'), ramp: true }+ : m;return this.range ? { ...base, range: this.range, ramp: true } : base;}@@ -83,7 +92,7 @@ export class ResultLayer {*/autoRange(field: ResultField): [number, number] {if (field === 'value' || !this.meta) return this.meta ? [...this.meta.range] as [number, number] : [0, 1];- if (field === 'disp') return [0, +Math.max(this.dataRange('disp')[1], 1e-6).toPrecision(3)];+ if (field === 'disp' || field === 'press') return [0, +Math.max(this.dataRange(field)[1], 1e-6).toPrecision(3)];const [, hi] = this.dataRange('stress');return [0, +Math.max(2 * this.stressLimit, Math.min(hi, 4 * this.stressLimit)).toPrecision(3)];}@@ -100,19 +109,25 @@ export class ResultLayer {/** Werte je Ecke für eine Größe (ohne sie: der Wert der Auswertung). */private attr(m: ResultMesh, field: ResultField): THREE.BufferAttribute {- return (field === 'stress' ? m.stress : field === 'disp' ? m.dispMag : undefined) ?? m.values;+ return (field === 'stress' ? m.stress : field === 'disp' ? m.dispMag : field === 'press' ? m.press : undefined) ?? m.values;}/** Größe und Spanne wählen (null: Spanne der Auswertung) und neu einfärben. */setDisplay(field: ResultField, range: [number, number] | null): void {- this.field = field === 'stress' && this.canStress ? 'stress' : field === 'disp' && this.canDisp ? 'disp' : 'value';+ this.field = this.available(field) ? field : 'value';this.range = range;this.recolor();}- /** Gezeigter Wert an einer Stelle (Spannung, Verschiebung oder der Wert der Auswertung). */+ /** Ob sich die Größe zeigen lässt (der Wert der Auswertung immer). */+ available(field: ResultField): boolean {+ return field === 'value' || (field === 'stress' && this.canStress) || (field === 'disp' && this.canDisp) || (field === 'press' && this.canPress);+ }++ /** Gezeigter Wert an einer Stelle (Spannung, Verschiebung, Pressung oder der Wert der Auswertung). */shown(p: ResultProbe): number {- return this.field === 'stress' && p.stress != null ? p.stress : this.field === 'disp' && p.disp != null ? p.disp : p.value;+ return this.field === 'stress' && p.stress != null ? p.stress : this.field === 'disp' && p.disp != null ? p.disp+ : this.field === 'press' && p.press != null ? p.press : p.value;}async show(glb: ArrayBuffer): Promise<ResultMeta> {@@ -165,7 +180,10 @@ export class ResultLayer {for (let i = 0; i < disp.count; i++) a[i] = Math.hypot(disp.getX(i), disp.getY(i), disp.getZ(i));dispMag = new THREE.BufferAttribute(a, 1);}- own.push({ mesh: m, name, values, stress: m.geometry.getAttribute('_stress') as THREE.BufferAttribute | undefined, disp, dispMag });+ own.push({+ mesh: m, name, values, stress: m.geometry.getAttribute('_stress') as THREE.BufferAttribute | undefined, disp, dispMag,+ press: m.geometry.getAttribute('_press') as THREE.BufferAttribute | undefined,+ });deformable(m.geometry);} else if ((c as THREE.LineSegments).isLineSegments) {const l = c as THREE.LineSegments;@@ -193,7 +211,7 @@ export class ResultLayer {this.stressLimit = limits.length ? Math.min(...limits) : 0;this.stressMixed = new Set(limits).size > 1;this.range = null;- if ((this.field === 'stress' && !this.canStress) || (this.field === 'disp' && !this.canDisp)) this.field = 'value';+ if (!this.available(this.field)) this.field = 'value';this.recolor();this.viewer.setModelHidden(true);this.viewer.addLayer(this.group);@@ -368,7 +386,7 @@ export class ResultLayer {}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 } : {}),+ ...(m.stress ? { stress: m.stress.getX(i) } : {}), ...(disp != null ? { disp } : {}), ...(m.press ? { press: m.press.getX(i) } : {}),};}}diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex c194354..7ca136d 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -303,12 +303,24 @@ export interface FemBc {kind: 'fix' | 'force' | 'pressure'; part: string; label: string; area: number; at: number[];axes?: string; reaction?: number[]; total?: number[]; value?: number;}+/** Teile, die sich berühren (E84): verklebt oder als Kontakt der Studie. Fläche in mm². */+export interface FemTouching { a: string; b: string; area: number; joint: 'bonded' | 'contact'; friction: number | null }+/**+ * Kontaktpaar (E84): getragene Kraft (N), höchste Pressung (MPa), offene Fläche (mm², hebt ab) mit größtem Spalt (mm),+ * größter Gleitweg (mm), mit Reibung die Fläche, die an der Haftgrenze gleitet.+ */+export interface FemContact {+ a: string; b: string; friction: number; area: number; force: number; maxPressure: { value: number; at: number[] };+ openArea: number; maxGap: number; maxSlip: number; slideArea?: number;+}export interface FemInfo {study: string; bcs: FemBc[]; applied: number[]; reaction: number[]; maxDisp: number; diag: number;/** `auto`: Die Studie gibt keine Netzgröße vor (fehlt bei älteren Ergebnissen). */mesh: { size: number; elements: number; dofs: number; solver: string; nodes?: number; auto?: boolean };/** Abweichung des Gleichgewichts (0.001 = 0.1 %), gröberes Netz der Prüfung, Schwerkraft (m/s², null: ohne). */balance?: number; coarse?: { size: number; elements: number } | null; gravity?: number[] | null;+ /** Berührende Teile und Kontaktpaare (E84, fehlen bei älteren Ergebnissen). */+ touching?: FemTouching[]; contacts?: FemContact[];}export interface ResultMeta {id: string; kind: string; title: string; quantity: string; unit: string;diff --git a/app/test/fem.mjs b/app/test/fem.mjsindex 672d03d..cdfbbdb 100644--- a/app/test/fem.mjs+++ b/app/test/fem.mjs@@ -46,6 +46,13 @@ study = Study("lose", material="PLA")study.fix("Fuss", faces="<Z", axes="z")study.force("Wand", faces=">Z", N=(-10, 0, 0))`;+// Kontakt (E84): Die Wand steht auf dem Fuß, oben gedrückt und leicht seitlich (20 N < 0,3 x 400 N: haftet)+const KONTAKT = (friction) => `from soma.fem import Study+study = Study("Wand steht auf", material="Aluminium 6082", check_mesh=False)+study.fix("Fuss", faces="<Z")+study.force("Wand", faces=">Z", N=(-20, 0, -400))+study.contact("Fuss", "Wand"${friction ? `, friction=${friction}` : ''})+`;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; };@@ -81,6 +88,12 @@ try {check('Netzprüfung: zweite Rechnung mit gröberem Netz genannt, Hinweis zur Spitze an der Einspannung', /with a coarser mesh \d+\.\d MPa/.test(r.stdout)&& r.stdout.includes('at the edge of a fixed support'), r.stdout);check('Ergebnisdatei .soma/results/balken.glb', fs.existsSync(path.join(dir, '.soma', 'results', 'balken.glb')));+ check('Gerechnet mit CalculiX (E84)', /unknowns, CalculiX \d/.test(r.stdout), r.stdout);+ // Rückfallweg ohne CalculiX: der eingebaute Solver, dieselbe Durchbiegung+ const r0 = spawnSync(PY, ['-m', 'soma', 'analyze', 'fem', 'analyses/balken.py', '--name=balken-eigen'], { cwd: dir, env: { ...env, SOMA_FEM_SOLVER: 'builtin' }, encoding: 'utf8', timeout: 10 * 60 * 1000 });+ check('Eingebauter Solver (SOMA_FEM_SOLVER=builtin): gleiche Durchbiegung, direkt gelöst', r0.status === 0 && /unknowns, direct/.test(r0.stdout)+ && near(Number(/largest displacement (\d+\.\d+) mm/.exec(r0.stdout)?.[1]), w, 0.002), r0.stdout + r0.stderr);+ fs.rmSync(path.join(dir, '.soma', 'results', 'balken-eigen.glb'), { force: true });// 2) Zwei verschmolzene Teile mit eigenem Werkstoff, Druck über near=, Eigengewichtstudy('winkel', WINKEL);@@ -89,6 +102,8 @@ try {&& /Fuss \(Aluminium 6082/.test(r.stdout) && /Wand \(Steel S235/.test(r.stdout) && /pressure: Wand near \(30, 100, 30\) \(1600\.0 mm²\), 0\.2 MPa, in total \(-320\.0, 0\.0, 0\.0\) N/.test(r.stdout)&& r.stdout.includes('self-weight') && r.stdout.includes('(in equilibrium)'), r.stdout + r.stderr);check('Winkel: Einspannung 2400 mm² trägt Druck und Gewicht', /fixed: Fuss <Z \(2400\.0 mm²\), reaction force \(320\.0, 0\.0, \d\.\d\) N/.test(r.stdout), r.stdout);+ check('Winkel: berührende Teile genannt, verklebt, mit Hinweis auf contact()', r.stdout.includes('touching: Fuss – Wand (200.0 mm²), bonded')+ && r.stdout.includes('add study.contact("A", "B")'), r.stdout);// 3) Fehler: verständlich, Exit 1, keine Ergebnisdateistudy('lose', LOSE);@@ -269,13 +284,47 @@ try {await ev(() => window.__t.viewer.setSection(null));await domClick('btn-result-close');- // 7) Das Beispiel im Skill läuft so, wie es dasteht+ // 7) Kontakt (E84): ohne Reibung hält nichts die Wand seitlich, mit Reibung steht sie+ study('kontakt', KONTAKT(0));+ r = soma(['analyze', 'fem', 'analyses/kontakt.py']);+ check('Kontakt ohne Reibung, seitlich frei: vor der Rechnung gemeldet', r.status === 1+ && /Wand: still free \([^)]*moving in X[^)]*\) \(held only by a contact without friction/.test(r.stderr + r.stdout), r.stderr + r.stdout);+ study('kontakt', KONTAKT(0.3));+ r = soma(['analyze', 'fem', 'analyses/kontakt.py']);+ const cf = Number(/contact: Fuss – Wand \(200\.0 mm², friction 0\.3\), carries (\d+\.\d) N/.exec(r.stdout)?.[1]);+ check('Kontakt mit Reibung: trägt die 400 N, im Gleichgewicht, mit Kontakt gerechnet', r.status === 0 && near(cf, 400, 8)+ && r.stdout.includes('linear elastic, with contact') && r.stdout.includes('(in equilibrium)') && /CalculiX [\d.]+, \d+ threads, \d+ load steps?/.test(r.stdout), r.stdout + r.stderr);+ await ev(() => window.__t.refreshViewLists());+ await ev(() => window.__t.resultShow('kontakt'));+ await waitFor('Ergebnis Kontakt geladen', () => window.__t.result().id === 'kontakt', 20000);+ await ev(() => window.__t.resultField('press'));+ rs = await ev(() => window.__t.result());+ check('Im Bild: Kontaktpressung wählbar, MPa ohne Grenzwert, Spanne bis zur größten', rs.fem.fields.join() === 'Safety factor,Stress,Displacement,Contact'+ && rs.scale.field === 'press' && rs.scale.unit === 'MPa' && rs.scale.threshold === null && rs.scale.range[1] > 0 && rs.scale.legend.includes('Contact pressure'), JSON.stringify(rs));+ // Die Kontaktfläche liegt zwischen den Teilen: Wand ausblenden, dann sieht man die Pressung auf dem Fuß+ const wandIds = await ev(() => window.__t.viewer.partList().filter((p) => p.name === 'Wand').map((p) => p.id));+ await ev((ids) => window.__t.viewer.setVisible(ids, false), wandIds);+ await ev(() => window.__t.viewer.setView('top'));+ await shot('fem-5-kontakt');+ await ev((ids) => window.__t.viewer.setVisible(ids, true), wandIds);+ await ev(() => window.__t.viewer.setView('iso'));+ await ev(() => window.__t.resultField('value'));+ await ev(() => window.__t.showPanel('analysis'));+ await waitFor('Bericht Kontakt', () => window.__t.analysis().title === 'Wand steht auf', 20000);+ await ev(() => window.__t.analysisToggle('contact0'));+ an = await ev(() => window.__t.analysis());+ check('Bericht: Zeile Kontakt mit Reibung, aufgeklappt Kraft und Pressung', an.inputs.some((x) => x.startsWith('ContactFriction 0.3 · Fuss – Wand'))+ && an.details.some((x) => x.includes('Carries') && x.includes('Highest pressure')), JSON.stringify(an));+ await domClick('btn-result-close');++ // 8) Das Beispiel im Skill läuft so, wie es dastehtconst 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 „Strength with 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);+ // Gleichgewicht: Die Knotenkräfte aus der frd von CalculiX lagen hier 5 % daneben, die Lagerkräfte rechnet soma selbst+ check('Beispiel aus dem Skill „Strength with FEM“ rechnet ohne Fehler, im Gleichgewicht', r.status === 0 && r.stdout.includes('FEM "Bracket, 5 kg on the arm"')+ && /Bracket \(PETG/.test(r.stdout) && r.stdout.includes('(in equilibrium)'), r.stdout.slice(0, 900) + r.stderr);} catch (e) {t.fail();console.log('ABBRUCH:', e);