Skip to content

armgit / SOMA

Public Imported from GitHub
0

Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice

App: Animation, Analyse, soma render und Video (E58)

Kai-Jungsthoefelaffc6e12580a
diff --git a/app/esbuild.config.mjs b/app/esbuild.config.mjs
index fbae19a..2d5ec15 100644
--- a/app/esbuild.config.mjs
+++ b/app/esbuild.config.mjs
@@ -9,12 +9,17 @@ await Promise.all([
external: ['electron', 'node-pty', 'dugite'] }),
build({ ...common, entryPoints: ['src/preload/preload.ts'], outfile: 'dist/preload/preload.js', platform: 'node', format: 'cjs',
external: ['electron'] }),
+ // Unsichtbares Render-Fenster für soma render (E58): eigener Preload und eigene Seite, derselbe Viewer
+ build({ ...common, entryPoints: ['src/preload/render-preload.ts'], outfile: 'dist/preload/render-preload.js', platform: 'node', format: 'cjs',
+ external: ['electron'] }),
+ build({ ...common, entryPoints: ['src/renderer/render.ts'], outfile: 'dist/renderer/render.js', platform: 'browser', format: 'iife' }),
build({ ...common, entryPoints: ['src/renderer/main.ts'], outfile: 'dist/renderer/main.js', platform: 'browser', format: 'iife' }),
// Worker von pdf.js als klassisches Skript: Module aus file:// lädt Chromium nicht (E54)
build({ ...common, sourcemap: false, entryPoints: ['node_modules/pdfjs-dist/build/pdf.worker.mjs'], outfile: 'dist/renderer/pdf.worker.js', platform: 'browser', format: 'iife' }),
]);
fs.mkdirSync('dist/renderer', { recursive: true });
fs.copyFileSync('src/renderer/index.html', 'dist/renderer/index.html');
+fs.copyFileSync('src/renderer/render.html', 'dist/renderer/render.html');
fs.copyFileSync('src/renderer/style.css', 'dist/renderer/style.css');
fs.copyFileSync(path.join('node_modules', '@xterm', 'xterm', 'css', 'xterm.css'), 'dist/renderer/xterm.css');
diff --git a/app/package-lock.json b/app/package-lock.json
index e1fd4e6..738d4da 100644
--- a/app/package-lock.json
+++ b/app/package-lock.json
@@ -23,6 +23,7 @@
"@xterm/xterm": "^6.0.0",
"dugite": "^3.2.3",
"marked": "^18.1.0",
+ "mediabunny": "^1.61.3",
"node-pty": "^1.1.0",
"pdfjs-dist": "^6.4.299",
"three": "^0.180.0",
@@ -1032,6 +1033,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/dom-mediacapture-transform": {
+ "version": "0.1.12",
+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/dom-webcodecs": "*"
+ }
+ },
+ "node_modules/@types/dom-webcodecs": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "22.20.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.4.tgz",
@@ -1387,6 +1403,24 @@
"node": ">= 20"
}
},
+ "node_modules/mediabunny": {
+ "version": "1.61.3",
+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.61.3.tgz",
+ "integrity": "sha512-kUqLKVXQVwHR62GkOJxYosAmXERJbqnXBgJDTtRlxHEYviVkMg/Evhl9XN6kedqS5LP1tV4kFKyzY/V4a4ofow==",
+ "license": "MPL-2.0",
+ "workspaces": [
+ ".",
+ "packages/*"
+ ],
+ "dependencies": {
+ "@types/dom-mediacapture-transform": "^0.1.11",
+ "@types/dom-webcodecs": "0.1.13"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/Vanilagy"
+ }
+ },
"node_modules/meshoptimizer": {
"version": "0.22.0",
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
diff --git a/app/package.json b/app/package.json
index 2c7d69c..911665e 100644
--- a/app/package.json
+++ b/app/package.json
@@ -17,8 +17,9 @@
"test:explode": "npm run build && node test/explode.mjs",
"test:skills": "npm run build && node test/skills.mjs",
"test:fasteners": "npm run build && node test/fasteners.mjs",
+ "test:animation": "npm run build && node test/animation.mjs",
"test:unit": "node test/unit.mjs",
- "test": "npm run build && node test/unit.mjs && node test/smoke.mjs && node test/versions.mjs && node test/editor.mjs && node test/measure.mjs && node test/groups.mjs && node test/section.mjs && node test/explode.mjs && node test/skills.mjs && node test/fasteners.mjs"
+ "test": "npm run build && node test/unit.mjs && node test/smoke.mjs && node test/versions.mjs && node test/editor.mjs && node test/measure.mjs && node test/groups.mjs && node test/section.mjs && node test/explode.mjs && node test/skills.mjs && node test/fasteners.mjs && node test/animation.mjs"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
@@ -36,6 +37,7 @@
"@xterm/xterm": "^6.0.0",
"dugite": "^3.2.3",
"marked": "^18.1.0",
+ "mediabunny": "^1.61.3",
"node-pty": "^1.1.0",
"pdfjs-dist": "^6.4.299",
"three": "^0.180.0",
diff --git a/app/resources/skills/3d-druck.md b/app/resources/skills/3d-druck.md
index f935c6e..53b94b2 100644
--- a/app/resources/skills/3d-druck.md
+++ b/app/resources/skills/3d-druck.md
@@ -94,5 +94,6 @@ def overhang_faces(part):
return [f for f in s.Faces() if f.geomType() == "PLANE" and f.normalAt().z < lim and f.Center().z > zmin + 0.01]
```
-Curved faces (holes, fillets underneath) are not covered: check them in the viewer. Export each printable part as STL or
-3MF: `soma export "Lid" --format 3mf`. References are not printed.
+Curved faces (holes, fillets underneath) are not covered here. `soma analyze overhang --threshold {{overhang}}` and
+`soma analyze thickness --threshold {{min_wall}}` check every spot, curved faces too (skill for analysis). Export each
+printable part as STL or 3MF: `soma export "Lid" --format 3mf`. References are not printed.
diff --git a/app/resources/skills/analyse.md b/app/resources/skills/analyse.md
new file mode 100644
index 0000000..0429ac2
--- /dev/null
+++ b/app/resources/skills/analyse.md
@@ -0,0 +1,46 @@
+---
+title: Analyse
+name: Analysis
+summary: Überhang, Wandstärke und Spalt zwischen Teilen als Wert an jeder Stelle der Oberfläche (soma analyze), als Text und farbiges Bild.
+order: 30
+category: Prüfen und Zeigen
+default: on-demand
+when: you check printability, wall thickness or gaps between parts, or the user asks for an analysis
+topics: Auswertungen; Ablauf; Grenzen; Rückmeldung
+---
+# Skill: Analysis
+
+`soma analyze` computes a value at every spot of the surface, prints a summary per part and writes
+`.soma/results/<name>.glb`. The user sees it in colour in the app (Analyse), you see it with `soma render --result`.
+
+| Command | Value | Critical by default |
+|---|---|---|
+| `soma analyze overhang` | angle of downward faces from vertical (0 = wall, 90 = ceiling), faces on the bed excluded | above 45° |
+| `soma analyze thickness` | wall thickness: distance from the surface to the opposite side of the material | below 1.2 mm |
+| `soma analyze clearance` | gap in front of the surface to the next other part, negative inside another part | below 0.5 mm |
+
+Options: `--threshold` (take it from the active skills: overhang, minimum wall, clearance, and say so), `--parts
+"Lid,Housing"` (names or groups, default all own parts without references and purchased parts), `--up z` for the
+print direction of overhangs, `--name` to keep a second result of the same kind. Parts that touch (gap 0) are not
+critical, overlaps are.
+
+## Workflow
+
+1. `soma build`, then the analysis. Read the summary: range per part, critical area, worst value and where.
+2. `soma render --result thickness` (add `--view bottom` for another side) and open the picture: colours green (fine),
+ yellow (close to the threshold), red (critical), legend at the bottom right.
+3. Change the model, build, analyse again. Report numbers: "thinnest wall 1.4 mm (was 0.8 mm)".
+
+## Limits
+
+- One value per small triangle. Curved faces carry the mesh tolerance, a few hundredths of a millimetre.
+- Thickness at sharp inner corners and on tiny features can be off. Check a suspicious spot before you change it.
+- 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 with
+ the skill for the process.
+- No strength analysis: loads and stresses need the skill for strength.
+
+## Feedback from the user
+
+`[Ergebnis: "Wandstärke" (.soma/results/thickness.glb, Grenzwert 1.20 mm), Bauteil "Lid": 0.80 mm bei (12.0, -5.0,
+26.0) mm]`: the user clicked that spot. A marking may say `zeigt das Ergebnis „Wandstärke“`: it shows the colours.
diff --git a/app/resources/skills/animation.md b/app/resources/skills/animation.md
new file mode 100644
index 0000000..29f8cca
--- /dev/null
+++ b/app/resources/skills/animation.md
@@ -0,0 +1,70 @@
+---
+title: Animation und Video
+name: Animation and video
+summary: Bewegungen, Kamerafahrten und Texte in animations/*.py, auf Kollisionen prüfen, als Standbilder ansehen, als MP4 ausgeben.
+order: 31
+category: Prüfen und Zeigen
+default: on-demand
+when: the user wants to see parts move, an assembly sequence, a camera flight, a video or a presentation of the model
+topics: Datei und Aufbau; Gelenke und Zeitleiste; Kamera; Texte; Bauen, prüfen, ansehen; Rückmeldung
+---
+# Skill: Animation and video
+
+An animation describes motion, camera and text over time. It is data, not a video: the app plays it in the 3D view,
+`soma render` turns it into pictures and an MP4. Write it in Python in `animations/<topic>.py`, several
+`Animation(...)` per file are fine. Do not change `model.py` for an animation.
+
+```python
+from soma.anim import Animation
+from model import HINGE_Y, HINGE_Z # reuse the model's constants (add_part has no effect here)
+
+a = Animation("Open the lid") # unique name, the user picks it in the app
+lid = a.hinge("Lid", (0, HINGE_Y, HINGE_Z), (1, HINGE_Y, HINGE_Z)) # axis through two points, like cq rotate()
+drawer = a.slider("Drawer", (1, 0, 0)) # moves along a direction (mm)
+a.camera.set(view="iso") # jumps; fits all parts over the whole motion
+a.title("Storage box", subtitle="Lid and drawer", duration=2)
+a.caption("The lid opens to 110°") # shown until the next caption
+a.play(lid.to(-110), run_time=2) # everything in one play() runs at the same time
+a.label("Hinge", part="Lid", at=(0, HINGE_Y, HINGE_Z))
+a.play(drawer.to(60), a.camera.orbit(45), run_time=1.5, ease="linear")
+a.wait(1)
+```
+
+## Joints and timeline
+
+- `hinge(parts, p1, p2)`: angle in degrees, right-hand rule around `p2 - p1`. `slider(parts, direction)`: way in mm.
+ `part(parts)`: free motion with `to(cq.Location(...))`, `translate((x, y, z))`, `rotate(p1, p2, angle)`.
+- `parts` is a name from `add_part`, a group (`"Housing"`, `"Housing/Screws"`) or a list. One joint per part. A joint
+ on a moving part gets `parent=lid`, its axis is given in the model position.
+- `joint.to(value)` (0 = as modelled), `joint.by(delta)`.
+- `play(*actions, run_time=1, ease="smooth")`, eases `smooth`, `linear`, `in`, `out`. `wait(seconds)`. `title()` also
+ takes time. `caption`, `label`, `highlight(parts, duration=)`, `hide`, `show`, `ghost(parts)` start now and take none.
+
+## Camera
+
+- `a.camera.set(view=, fit=, zoom=, target=, distance=)` jumps, `a.camera.move(...)` is a flight inside `play()`.
+ Views: iso, front, back, left, right, top, bottom or a direction from the target to the camera. `fit=["Lid"]`
+ frames these parts over their whole motion. `a.camera.orbit(degrees, tilt=0)` circles around Z, `zoom(factor)`.
+- Keep the moving parts in view, one camera move at a time, 1 to 3 s each. Without camera calls the user turns the
+ view freely.
+
+## Text
+
+Captions: one short sentence in the language the user speaks, about what moves and why. Labels: 1 to 3 words.
+
+## Build, check, look
+
+1. `soma anim build` (the app also builds when the file changes). Errors name file and line.
+2. `soma anim info "Open the lid"`: the timeline as text. Read it.
+3. `soma anim check "Open the lid" --gap 0.5`: parts that collide or come closer than the gap during the motion. Fix
+ collisions in the model or in the motion. Contacts that already exist in the model position are marked.
+4. `soma render --anim "Open the lid" --sheet`: one picture with 9 stills and their times, `--at 1.5` for one moment.
+ Open the picture and look at it.
+5. Only when the user wants a video: `soma render --anim "Open the lid" --video` writes `renders/<id>.mp4`
+ (1280x720, 30 fps), the captions as `.vtt` and an overview picture. You cannot watch the video, check the overview.
+
+## Feedback from the user
+
+`[Animation: "Name" (animations/x.py) bei 1.50 s]` and `[Video: renders/x.mp4 bei 00:03.20]` point to a moment. A
+marking may say `gezeichnet auf renders/x.mp4 bei 00:03.20` or `Animation „Name“ bei 1.50 s`: the picture shows that
+moment. Render it yourself (`soma render --anim "Name" --at 1.5`) before you change something.
diff --git a/app/resources/skills/baugruppen.md b/app/resources/skills/baugruppen.md
index 5708572..7af4ff1 100644
--- a/app/resources/skills/baugruppen.md
+++ b/app/resources/skills/baugruppen.md
@@ -47,7 +47,9 @@ for a in (0, 45, 90): # range of LID_ANGLE
```
The volume must be 0, the distance at least `MOTION_GAP`, except where parts are meant to touch (pin, guide). Remove
-the output afterwards.
+the output afterwards. For motions with several steps or parts, write an animation (skill for animation) and run
+`soma anim check "Name" --gap {{motion_gap}}`: it checks every moment. `soma analyze clearance` shows tight gaps in
+the model position.
## Parts list
diff --git a/app/resources/template/.gitignore b/app/resources/template/.gitignore
index 9de6e38..ecda416 100644
--- a/app/resources/template/.gitignore
+++ b/app/resources/template/.gitignore
@@ -12,3 +12,8 @@ __pycache__/
.soma/zip-info.json
.soma/feedback/
.soma/geometry/
+
+# Pictures and videos from soma render, built animations and analysis results (regenerated from the code)
+renders/
+.soma/anim/
+.soma/results/
diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.md
index 6e54b38..4f42b67 100644
--- a/app/resources/template/AGENTS.md
+++ b/app/resources/template/AGENTS.md
@@ -13,7 +13,9 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes
| `inputs/` | Files the user brought (STEP, images). Never modify them, load them from `model.py` |
| `output/model.step` | Main result with all parts, written by `soma build`. Never write it yourself |
| `exports/` | Single-part exports written by `soma export` |
-| `.soma/` | App data (viewer cache, build status, feedback images, skills). 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 |
+| `animations/` | Optional. Motion, camera flights and captions in Python (`soma.anim`), one file per topic. The skill for animation 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 |
## Rules for model.py
@@ -35,6 +37,9 @@ Run them in this terminal. They work without the app.
| `soma build` | Runs `model.py`, writes `output/model.step` and the viewer cache. **Run it after every change and read the result.** On errors it prints the file, line and message |
| `soma export <Part> --format stl` | Exports one part (formats: step, stl, 3mf, amf, brep, iges, obj, vrml, glb, gltf, dxf, svg) |
| `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 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.
@@ -59,6 +64,8 @@ The app pastes short notes into your input. The user adds their own words and se
- `[Markierung: .soma/feedback/markierung-20260930-1405.png]`: a picture of the 3D view (or a blank sketch) with the user's drawings: arrows, circles, handwritten text, often with dimensions. **Open the image file and look at it**, compare it with the model, then change the code. If the note says `zeigt den älteren Stand <hash>`, the picture shows that older commit, not the current code (`git show <hash>:model.py`). Leave the images where they are.
- `[Auswahl: Bauteil "…", model.py Zeile …]`: the part the user clicked, with the lines of its `add_part` call and the clicked face.
- `[Build-Fehler: …]`: the message of the last failed build.
+- `[Animation: "Name" (animations/x.py) bei 1.50 s]`, `[Video: renders/x.mp4 bei 00:03.20]`: a moment in an animation or a video. A marking can name it too (`gezeichnet auf renders/x.mp4 bei 00:03.20`).
+- `[Ergebnis: "Wandstärke" (.soma/results/…), Bauteil "…": 0.80 mm bei (x, y, z) mm]`: a spot in the colours of an analysis.
- `[Skill: .soma/skills/<name>.md]`: the user points you to this rule set, switched it on or changed its settings (the note may list them, they are already written into the file). Read the file again now and follow it from here on. When the user switches a skill off, it disappears from the list below: stop applying it.
The user can also edit files directly in the app's editor. Read a file again right before you change it, do not rely on an older copy.
diff --git a/app/src/main/animations.ts b/app/src/main/animations.ts
new file mode 100644
index 0000000..e140bd9
--- /dev/null
+++ b/app/src/main/animations.ts
@@ -0,0 +1,149 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import type { AnimBuildResult, AnimEntry, AnimFileError, AnimList, ResultEntry, ResultMeta } from '../shared/types';
+import { newestSourceMtime, runSoma } from './build';
+import { resolveInside } from './files';
+
+// Animationen und Ergebnisse im Projekt (E58). Gebaut und ausgewertet wird in Python (`soma anim build`, `soma analyze`),
+// die App liest nur deren Dateien: .soma/anim/index.json und die JSON-Teile der GLB-Dateien.
+
+/** JSON-Teil einer GLB-Datei, ohne die Binärdaten zu lesen. */
+export function readGlbJson(file: string): Record<string, unknown> | null {
+ let fd: number | null = null;
+ try {
+ fd = fs.openSync(file, 'r');
+ const head = Buffer.alloc(20);
+ if (fs.readSync(fd, head, 0, 20, 0) < 20 || head.readUInt32LE(0) !== 0x46546c67 || head.readUInt32LE(16) !== 0x4e4f534a) return null;
+ const len = head.readUInt32LE(12);
+ if (len > 64 * 1024 * 1024) return null;
+ const js = Buffer.alloc(len);
+ fs.readSync(fd, js, 0, len, 20);
+ return JSON.parse(js.toString('utf8')) as Record<string, unknown>;
+ } catch { return null; } finally { if (fd !== null) fs.closeSync(fd); }
+}
+
+const mtime = (f: string) => { try { return fs.statSync(f).mtimeMs; } catch { return 0; } };
+
+/** Liste aus .soma/anim/index.json. Veraltet: Modell oder Animationsdatei neuer als die gebaute Datei. */
+export function readAnimList(dir: string, building = false): AnimList {
+ let idx: { animations?: unknown[]; errors?: unknown[] } = {};
+ try { idx = JSON.parse(fs.readFileSync(path.join(dir, '.soma', 'anim', 'index.json'), 'utf8')); } catch { /* noch nichts gebaut */ }
+ const model = newestSourceMtime(dir);
+ const animations: AnimEntry[] = [];
+ for (const raw of Array.isArray(idx.animations) ? idx.animations : []) {
+ const a = raw as Partial<AnimEntry>;
+ if (typeof a.id !== 'string' || typeof a.name !== 'string' || typeof a.glb !== 'string' || typeof a.file !== 'string') continue;
+ let glb: string, src: string;
+ try { glb = resolveInside(dir, a.glb); src = resolveInside(dir, a.file); } catch { continue; }
+ if (!a.glb.startsWith('.soma/anim/') || !fs.existsSync(glb)) continue;
+ const built = mtime(glb);
+ animations.push({ id: a.id, name: a.name, file: a.file, line: typeof a.line === 'number' ? a.line : null, duration: Number(a.duration) || 0,
+ glb: a.glb, parts: Number(a.parts) || 0, stale: Math.max(model, mtime(src)) > built });
+ }
+ // Fehler gelöschter Dateien gelten nicht mehr (der Index wird erst beim nächsten Bauen bereinigt)
+ const exists = (rel: string) => { try { return fs.existsSync(resolveInside(dir, rel)); } catch { return false; } };
+ const errors: AnimFileError[] = (Array.isArray(idx.errors) ? idx.errors : []).map((e) => e as Partial<AnimFileError>)
+ .filter((e) => typeof e.file === 'string' && typeof e.message === 'string' && exists(e.file))
+ .map((e) => ({ file: e.file!, line: typeof e.line === 'number' ? e.line : null, message: e.message! }));
+ return { animations, errors, building };
+}
+
+/** Dateien in animations/, die (noch) nicht im Index stehen. */
+export function unbuiltAnimFiles(dir: string, list: AnimList): string[] {
+ let files: string[] = [];
+ try { files = fs.readdirSync(path.join(dir, 'animations')).filter((f) => f.endsWith('.py') && !f.startsWith('_')).map((f) => `animations/${f}`); } catch { return []; }
+ const known = new Set([...list.animations.map((a) => a.file), ...list.errors.map((e) => e.file)]);
+ return files.filter((f) => !known.has(f));
+}
+
+/**
+ * Baut Animationen im Hintergrund, eine nach der anderen. Kommt während eines Laufs ein weiterer Wunsch, folgt genau ein
+ * weiterer Lauf (für alle gewünschten Dateien), wie beim Modell (E20).
+ */
+export class AnimBuilder {
+ private running: Promise<AnimBuildResult> | null = null;
+ private pending: Set<string> | 'all' | null = null;
+ private disposed = false;
+
+ constructor(private readonly dir: string, private readonly changed: () => void) {}
+
+ get busy(): boolean { return this.running !== null; }
+
+ /** `file`: animations/x.py, null: alle. Liefert das Ergebnis des Laufs, der diesen Wunsch enthält. */
+ request(file: string | null): Promise<AnimBuildResult> {
+ if (this.running) {
+ if (file === null || this.pending === 'all') this.pending = 'all';
+ else { const p = this.pending ?? new Set<string>(); p.add(file); this.pending = p; }
+ return this.running.then(() => this.running ?? Promise.resolve(readAnimList(this.dir) as AnimBuildResult));
+ }
+ this.running = this.run(file === null ? null : [file]);
+ return this.running;
+ }
+
+ private async run(files: string[] | null): Promise<AnimBuildResult> {
+ this.changed();
+ let res: AnimBuildResult;
+ try {
+ const errors: string[] = [];
+ for (const f of files ?? [null]) {
+ const r = await runSoma(['anim', 'build', ...(f ? [f] : []), '--project', this.dir, '--json'], this.dir, 5 * 60 * 1000);
+ if (!r.out.trim().startsWith('{')) errors.push((r.err || r.out).trim().split(/\r?\n/).slice(-3).join('\n') || 'soma anim build ohne Ergebnis');
+ }
+ res = { ...readAnimList(this.dir), ok: errors.length === 0, ...(errors.length ? { error: errors.join('\n') } : {}) };
+ } catch (e) {
+ res = { ...readAnimList(this.dir), ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+ const next = this.pending;
+ this.pending = null;
+ this.running = next && !this.disposed ? this.run(next === 'all' ? null : [...next]) : null;
+ if (!this.running) this.changed();
+ return res;
+ }
+
+ dispose(): void { this.disposed = true; this.pending = null; }
+}
+
+const KINDS = new Set(['overhang', 'thickness', 'clearance']);
+
+/** Ergebnisse in .soma/results/. Veraltet: Der Code ist neuer als die Auswertung. */
+export function listResults(dir: string): ResultEntry[] {
+ const out: ResultEntry[] = [];
+ let files: string[] = [];
+ try { files = fs.readdirSync(path.join(dir, '.soma', 'results')).filter((f) => f.endsWith('.glb')).sort(); } catch { return out; }
+ const model = newestSourceMtime(dir);
+ 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 });
+ }
+ return out;
+}
+
+/**
+ * Dieselbe Auswertung noch einmal. Die Angaben stammen aus der Datei im Projekt, also nicht vertrauenswürdig: nur die
+ * bekannten Auswertungen und Schalter, Werte ohne Leerzeichen-Tricks (es gibt ohnehin keine Shell dazwischen).
+ */
+export async function rerunResult(dir: string, id: string): Promise<{ ok: boolean; error?: string }> {
+ const r = listResults(dir).find((x) => x.id === id);
+ if (!r) return { ok: false, error: `Kein Ergebnis „${id}“.` };
+ const 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)) {
+ // Immer als --schalter=wert: Werte wie -z oder -0.5 sind dann keine Schalter für argparse
+ const 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)}` };
+ args.push(a);
+ }
+ const res = await runSoma([...args, '--project', dir, '--json'], dir, 5 * 60 * 1000);
+ if (res.ok) return { ok: true };
+ return { ok: false, error: (res.err || res.out).trim().split(/\r?\n/).slice(-3).join('\n') || 'Auswertung fehlgeschlagen' };
+}
+
+/** Gleicher Ordner? Unter Windows ohne Groß- und Kleinschreibung, Kurznamen (NAME~1) aufgelöst. */
+export function samePath(a: string, b: string): boolean {
+ try {
+ const ra = fs.realpathSync.native(a), rb = fs.realpathSync.native(b);
+ return process.platform === 'win32' ? ra.toLowerCase() === rb.toLowerCase() : ra === rb;
+ } catch { return false; }
+}
diff --git a/app/src/main/bridge.ts b/app/src/main/bridge.ts
new file mode 100644
index 0000000..6c13e85
--- /dev/null
+++ b/app/src/main/bridge.ts
@@ -0,0 +1,66 @@
+import crypto from 'node:crypto';
+import http from 'node:http';
+
+/**
+ * Verbindung von `soma` im Terminal zur App (E58), etwa für `soma render`: ein HTTP-Dienst nur auf 127.0.0.1, mit einem
+ * zufälligen Port und einem Schlüssel je App-Start. Beides bekommen nur die Terminals der App als Umgebungsvariablen
+ * (SOMA_APP, SOMA_APP_TOKEN). Andere Programme kennen den Schlüssel nicht, Anfragen ohne ihn werden abgelehnt.
+ */
+export type BridgeHandler = (route: string, body: unknown) => Promise<{ status: number; body: unknown }>;
+
+const MAX_BODY = 1024 * 1024;
+
+let server: http.Server | null = null;
+let port = 0;
+const token = crypto.randomBytes(24).toString('hex');
+
+/** Startet den Dienst (einmal je App). Scheitert er, laufen die Terminals ohne SOMA_APP, `soma render` erklärt das dann. */
+export function startBridge(handler: BridgeHandler): Promise<void> {
+ if (server) return Promise.resolve();
+ return new Promise((resolve) => {
+ const srv = http.createServer((req, res) => void serve(req, res, handler));
+ srv.on('error', (e) => { console.error('[soma] Verbindung für soma render nicht verfügbar:', e); server = null; port = 0; resolve(); });
+ // Port 0: das System vergibt einen freien (ein fester Port kann schon belegt sein)
+ srv.listen(0, '127.0.0.1', () => {
+ const a = srv.address();
+ port = typeof a === 'object' && a ? a.port : 0;
+ server = srv;
+ resolve();
+ });
+ });
+}
+
+export function stopBridge(): void { server?.close(); server = null; port = 0; }
+
+/** Umgebungsvariablen für Terminals: Adresse und Schlüssel, leer ohne laufenden Dienst. */
+export function bridgeEnv(): Record<string, string> {
+ return port ? { SOMA_APP: `127.0.0.1:${port}`, SOMA_APP_TOKEN: token } : {};
+}
+
+function reply(res: http.ServerResponse, status: number, body: unknown): void {
+ const data = Buffer.from(JSON.stringify(body), 'utf8');
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': data.length });
+ res.end(data);
+}
+
+async function serve(req: http.IncomingMessage, res: http.ServerResponse, handler: BridgeHandler): Promise<void> {
+ try {
+ const given = String(req.headers['x-soma-token'] ?? '');
+ const ok = given.length === token.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(token));
+ if (!ok) { reply(res, 403, { ok: false, error: 'Falscher Schlüssel. Nur die Terminals der App dürfen die App ansprechen.' }); return; }
+ if (req.method !== 'POST' || !req.url?.startsWith('/v1/')) { reply(res, 404, { ok: false, error: 'Unbekannte Anfrage' }); return; }
+ const chunks: Buffer[] = [];
+ let size = 0;
+ for await (const c of req) {
+ size += (c as Buffer).length;
+ if (size > MAX_BODY) { reply(res, 413, { ok: false, error: 'Anfrage zu groß' }); return; }
+ chunks.push(c as Buffer);
+ }
+ let body: unknown;
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { reply(res, 400, { ok: false, error: 'Kein gültiges JSON' }); return; }
+ const r = await handler(req.url.slice(4), body);
+ reply(res, r.status, r.body);
+ } catch (e) {
+ reply(res, 500, { ok: false, error: e instanceof Error ? e.message : String(e) });
+ }
+}
diff --git a/app/src/main/main.ts b/app/src/main/main.ts
index f0ba24c..9fb9088 100644
--- a/app/src/main/main.ts
+++ b/app/src/main/main.ts
@@ -2,6 +2,7 @@ import { app, BrowserWindow, dialog, ipcMain, shell, type WebContents } from 'el
import fs from 'node:fs';
import path from 'node:path';
import { detectAgents } from './agents';
+import { bridgeEnv, startBridge, stopBridge } from './bridge';
import { choose, setTestAnswers } from './dialogs';
import { backupText, createEntry, entryPath, importInputs, listFiles, renameEntry, resolveInside, saveFeedbackImage, trashEntry, writeProjectText } from './files';
import { ProjectController } from './projects';
@@ -17,6 +18,8 @@ if (process.env.SOMA_USER_DATA) app.setPath('userData', process.env.SOMA_USER_DA
else if (process.platform === 'win32' && process.env.LOCALAPPDATA) app.setPath('userData', path.join(process.env.LOCALAPPDATA, 'soma'));
let win: BrowserWindow | null = null;
+/** Für Anfragen aus den Terminals (bridge.ts): das Projekt des Fensters. */
+let controller: ProjectController | null = null;
function registerIpc(ctl: ProjectController): void {
const dir = () => ctl.need().dir;
@@ -123,6 +126,11 @@ function registerIpc(ctl: ProjectController): void {
ipcMain.handle('skills:set', (_e, id: unknown, mode: unknown) => ctl.setSkill(id, mode));
ipcMain.handle('skills:configure', (_e, id: unknown, values: unknown) => ctl.configureSkill(id, values));
ipcMain.handle('skills:setDefault', (_e, id: unknown, mode: unknown) => ctl.setSkillDefault(id, mode));
+ ipcMain.handle('anim:list', () => ctl.animList());
+ ipcMain.handle('anim:build', (_e, file: unknown) => ctl.animBuild(file));
+ ipcMain.handle('results:list', () => ctl.results());
+ ipcMain.handle('results:rerun', (_e, id: unknown) => ctl.rerunResult(id));
+ ipcMain.handle('render:video', (_e, id: unknown) => ctl.renderVideo(id));
// Rückfragen aus dem Renderer (etwa ungespeicherte Eingaben im Editor) laufen über dieselben Dialoge wie im Hauptprozess
ipcMain.handle('dialog:choose', (_e, o: { title?: unknown; message?: unknown; detail?: unknown; buttons?: unknown }) => {
const buttons = Array.isArray(o?.buttons) ? o.buttons.slice(0, 4).map(String) : [];
@@ -133,6 +141,8 @@ function registerIpc(ctl: ProjectController): void {
// Nur im Testmodus: vorbereitete Antworten für Dialoge (siehe dialogs.ts)
if (process.env.SOMA_TEST === '1') {
ipcMain.handle('test:answers', (_e, a: unknown[]) => setTestAnswers(a));
+ // Adresse und Schlüssel für soma render, damit Tests es auch außerhalb eines Terminals aufrufen können
+ ipcMain.handle('test:bridge', () => bridgeEnv());
// Screenshot auch aus unsichtbaren Fenstern (CDP liefert dort kein Bild)
ipcMain.handle('test:screenshot', async (e, file: string) => {
const img = await e.sender.capturePage();
@@ -203,6 +213,7 @@ function createWindow(): void {
if (testWindowMode === 'offscreen') { win.setBounds({ x: -20000, y: -20000, width: 1600, height: 950 }); win.showInactive(); }
const wc = win.webContents;
const ctl = new ProjectController(() => win, wc);
+ controller = ctl;
registerIpc(ctl);
// Stürzt der Anzeigeprozess ab, steht der Grund im Protokoll (sonst bliebe nur ein schwarzes Fenster).
wc.on('render-process-gone', (_e, d) => onRendererGone(wc, d.reason, d.exitCode));
@@ -232,8 +243,16 @@ function createWindow(): void {
if (ok) { allowClose = true; win?.close(); }
})();
});
- win.on('closed', () => { ctl.close(); win = null; });
+ win.on('closed', () => { ctl.close(); ctl.renders.close(); controller = null; win = null; });
}
-app.whenReady().then(createWindow);
-app.on('window-all-closed', () => app.quit());
+// Erst die Verbindung für `soma render` (E58), dann das Fenster: Die Terminals bekommen Adresse und Schlüssel beim Anlegen
+app.whenReady().then(async () => {
+ await startBridge(async (route, body) => {
+ if (!controller) return { status: 503, body: { ok: false, error: 'Die App hat gerade kein Fenster.' } };
+ if (route === 'render') return controller.renderForAgent(body);
+ return { status: 404, body: { ok: false, error: `Unbekannte Anfrage: ${route}` } };
+ });
+ createWindow();
+});
+app.on('window-all-closed', () => { stopBridge(); app.quit(); });
diff --git a/app/src/main/projects.ts b/app/src/main/projects.ts
index 6cca8a6..2adc3fd 100644
--- a/app/src/main/projects.ts
+++ b/app/src/main/projects.ts
@@ -1,8 +1,14 @@
import { shell, type BrowserWindow, type WebContents } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
-import type { ExportResult, GitLog, MeasureEntity, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState, SkillInfo, SkillResult } from '../shared/types';
+import type {
+ AnimBuildResult, AnimList, ExportResult, GitLog, MeasureEntity, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult,
+ ProjectInfo, RenderResult, RestoreResult, ResultEntry, SaveResult, SaveState, SkillInfo, SkillResult,
+} from '../shared/types';
+import { affectsAnimation } from '../shared/editable';
+import { AnimBuilder, listResults, readAnimList, rerunResult, samePath } from './animations';
import { BuildManager, buildIsStale, newestSourceMtime, runSoma } from './build';
+import { checkRequest, RenderService, type RenderRequest } from './render';
import { choose, choosePath } from './dialogs';
import { GitRepo } from './git';
import { MeasureService } from './measure';
@@ -26,6 +32,9 @@ interface Session {
terminals: TerminalManager;
git: GitRepo;
measure: MeasureService;
+ /** Animationen bauen (E58), ausgelöst vom Watcher, der Oberfläche oder vor einem Video. */
+ anims: AnimBuilder;
+ animTimer?: NodeJS.Timeout;
stopWatch: () => void;
poll: NodeJS.Timeout;
signature: string;
@@ -42,6 +51,8 @@ const safeFileName = (n: string) => n.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').tri
*/
export class ProjectController {
session: Session | null = null;
+ /** Unsichtbares Fenster für Bilder und Videos (E58), eins für die App. */
+ readonly renders = new RenderService();
constructor(private readonly getWin: () => BrowserWindow | null, private readonly wc: WebContents) {}
@@ -60,7 +71,9 @@ export class ProjectController {
const s = this.session;
if (!s) return;
clearInterval(s.poll);
+ clearTimeout(s.animTimer);
s.stopWatch();
+ s.anims.dispose();
s.builds.dispose();
s.terminals.killAll();
s.measure.stop();
@@ -74,8 +87,10 @@ export class ProjectController {
const terminals = new TerminalManager(this.wc, dir);
const git = new GitRepo(dir);
builds.on('status', (st) => this.send('build:status', st));
- const stopWatch = watchProject(dir, (rel) => builds.sourceChanged(rel ? path.join(dir, rel) : null), () => this.send('fs:changed'));
- const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), stopWatch, signature: '', poll: setInterval(() => void this.pollGit(), POLL_MS) };
+ const anims = new AnimBuilder(dir, () => this.send('anim:changed'));
+ const stopWatch = watchProject(dir, (rel) => builds.sourceChanged(rel ? path.join(dir, rel) : null), () => this.send('fs:changed'),
+ (rel) => this.animFileChanged(rel));
+ const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), anims, stopWatch, signature: '', poll: setInterval(() => void this.pollGit(), POLL_MS) };
this.session = session;
setLastProject(id);
// Erster Build direkt beim Öffnen, damit der Viewer nicht leer ist (der Nutzer kann Auto-Build danach abschalten).
@@ -332,6 +347,82 @@ export class ProjectController {
}
}
+ // ---- Animationen, Ergebnisse, Bilder und Videos (E58) ------------------------------------------------------------
+
+ animList(): AnimList {
+ const s = this.need();
+ return readAnimList(s.dir, s.anims.busy);
+ }
+
+ /** Animationen bauen: eine Datei (animations/x.py) oder alle. */
+ animBuild(file: unknown): Promise<AnimBuildResult> {
+ const s = this.need();
+ const f = file == null ? null : String(file).replace(/\\/g, '/');
+ if (f !== null && !affectsAnimation(f)) return Promise.resolve({ ...readAnimList(s.dir), ok: false, error: 'Keine Animationsdatei (animations/*.py).' });
+ return s.anims.request(f);
+ }
+
+ /** Watcher: Eine Animationsdatei hat sich geändert. Mit Auto-Build gleich neu bauen (entprellt), sonst nur melden. */
+ private animFileChanged(rel: string): void {
+ const s = this.session;
+ if (!s) return;
+ clearTimeout(s.animTimer);
+ s.animTimer = setTimeout(() => {
+ if (this.session !== s) return;
+ if (s.builds.autoBuild && fs.existsSync(path.join(s.dir, rel))) void s.anims.request(rel);
+ else this.send('anim:changed');
+ }, 700);
+ }
+
+ results(): ResultEntry[] { return listResults(this.need().dir); }
+
+ rerunResult(id: unknown): Promise<{ ok: boolean; error?: string }> {
+ const s = this.need();
+ return rerunResult(s.dir, String(id ?? ''));
+ }
+
+ /** Bild oder Video rendern. Vorher den laufenden Build abwarten, damit das aktuelle Modell zu sehen ist. */
+ private async render(req: RenderRequest, byAgent: boolean): Promise<RenderResult> {
+ const s = this.need();
+ await s.builds.whenIdle();
+ const warnings: string[] = [];
+ if (s.builds.status.state === 'error') warnings.push('Der letzte Build ist fehlgeschlagen. Zu sehen ist der letzte erfolgreiche Stand.');
+ else if (s.builds.status.stale) warnings.push('Der Code ist neuer als der letzte Build (Auto-Build ist aus). Zu sehen ist der letzte Build.');
+ const r = await this.renders.run(s.dir, req, (f) => this.send('render:progress', f));
+ const res = { ...r, warnings: [...warnings, ...r.warnings] };
+ this.send('render:notice', { ...res, kind: req.kind, byAgent });
+ if (r.ok) this.send('fs:changed');
+ return res;
+ }
+
+ /** Auftrag von `soma render` aus einem Terminal der App (über bridge.ts). */
+ async renderForAgent(body: unknown): Promise<{ status: number; body: unknown }> {
+ const s = this.session;
+ if (!s) return { status: 409, body: { ok: false, error: 'In der App ist kein Modell offen.' } };
+ const project = String((body as { project?: unknown } | null)?.project ?? '');
+ if (!project || !samePath(project, s.dir)) {
+ return { status: 409, body: { ok: false, error: 'Dieser Ordner ist nicht das Modell, das in der App offen ist. soma render läuft nur im offenen Modell.' } };
+ }
+ const req = checkRequest(s.dir, body);
+ if (typeof req === 'string') return { status: 400, body: { ok: false, error: req } };
+ const r = await this.render(req, true);
+ return { status: r.ok ? 200 : 500, body: r };
+ }
+
+ /** Knopf „Video erzeugen“: Animation (falls veraltet) neu bauen, dann rendern nach renders/<id>.mp4. */
+ async renderVideo(animId: unknown): Promise<RenderResult> {
+ const s = this.need();
+ let entry = readAnimList(s.dir).animations.find((a) => a.id === animId);
+ if (!entry) return { ok: false, files: [], warnings: [], error: 'Diese Animation gibt es nicht (mehr).' };
+ if (entry.stale) {
+ const file = entry.file;
+ const b = await s.anims.request(file);
+ entry = b.animations.find((a) => a.id === animId);
+ if (!entry) return { ok: false, files: [], warnings: [], error: b.errors.find((e) => e.file === file)?.message ?? b.error ?? 'Die Animation ließ sich nicht neu bauen.' };
+ }
+ return this.render({ kind: 'video', size: [1280, 720], view: null, at: 0, grid: [3, 3], fps: 30, anim: entry.glb, result: null, out: `renders/${entry.id}.mp4` }, false);
+ }
+
// ---- Beenden ----------------------------------------------------------------------------------------------------
/**
diff --git a/app/src/main/render.ts b/app/src/main/render.ts
new file mode 100644
index 0000000..0f2f4b0
--- /dev/null
+++ b/app/src/main/render.ts
@@ -0,0 +1,174 @@
+import { BrowserWindow, ipcMain } from 'electron';
+import fs from 'node:fs';
+import path from 'node:path';
+import type { RenderJob, RenderOutput, RenderResult } from '../shared/types';
+import { resolveInside } from './files';
+
+/**
+ * Bilder und Videos des Modells (E58): ein unsichtbares Fenster mit demselben Viewer wie auf dem Bildschirm. Es entsteht
+ * beim ersten Auftrag und schließt sich nach einer Minute ohne Arbeit wieder (ein Renderer-Prozess kostet Speicher).
+ * Aufträge laufen nacheinander. Auftraggeber sind `soma render` im Terminal (über bridge.ts) und Knöpfe der App.
+ */
+export interface RenderRequest {
+ kind: 'still' | 'sheet' | 'video';
+ size: [number, number];
+ view: string | null;
+ at: number;
+ grid: [number, number];
+ fps: number;
+ /** Dateien im Projekt (relativ): Animation (.soma/anim/…glb), Ergebnis (.soma/results/…glb), Ziel. */
+ anim: string | null;
+ result: string | null;
+ out: string;
+}
+
+const VIEWS = ['iso', 'front', 'back', 'left', 'right', 'top', 'bottom'];
+const MAX_SIDE = 3840;
+const IDLE_MS = 60_000;
+
+/** Prüft einen Auftrag von außen (Terminal) und bringt ihn auf die erwartete Form. Fehler als Text. */
+export function checkRequest(root: string, raw: unknown): RenderRequest | string {
+ const r = (raw ?? {}) as Record<string, unknown>;
+ const kind = r.kind;
+ if (kind !== 'still' && kind !== 'sheet' && kind !== 'video') return 'Unbekannte Art (still, sheet oder video).';
+ const size = Array.isArray(r.size) ? r.size.map(Number) : [];
+ if (size.length !== 2 || !size.every((v) => Number.isInteger(v) && v >= 64 && v <= MAX_SIDE)) return `Größe zwischen 64 und ${MAX_SIDE} Pixeln.`;
+ const grid = Array.isArray(r.grid) ? r.grid.map(Number) : [3, 3];
+ if (grid.length !== 2 || !grid.every((v) => Number.isInteger(v) && v >= 1 && v <= 6)) return 'Übersicht: 1 bis 6 Spalten und Zeilen.';
+ const view = r.view == null ? null : String(r.view);
+ if (view && !VIEWS.includes(view)) return `Unbekannte Ansicht ${view}.`;
+ const at = r.at == null ? 0 : Number(r.at);
+ const fps = r.fps == null ? 30 : Number(r.fps);
+ if (!Number.isFinite(at) || at < 0) return 'Ungültiger Zeitpunkt.';
+ if (!Number.isInteger(fps) || fps < 1 || fps > 60) return 'Bilder je Sekunde zwischen 1 und 60.';
+ const file = (v: unknown, dir: string, what: string): string | null | Error => {
+ if (v == null) return null;
+ const p = String(v).replace(/\\/g, '/');
+ if (!p.startsWith(dir) || !p.endsWith('.glb') || p.includes('..')) return new Error(`${what} muss in ${dir} liegen.`);
+ try { if (!fs.statSync(resolveInside(root, p)).isFile()) throw new Error(); } catch { return new Error(`${what} ${p} gibt es nicht.`); }
+ return p;
+ };
+ const anim = file(r.anim, '.soma/anim/', 'Die Animation');
+ const result = file(r.result, '.soma/results/', 'Das Ergebnis');
+ if (anim instanceof Error) return anim.message;
+ if (result instanceof Error) return result.message;
+ if ((kind === 'sheet' || kind === 'video') && !anim) return 'Übersicht und Video brauchen eine Animation.';
+ const out = String(r.out ?? '').replace(/\\/g, '/');
+ const ext = kind === 'video' ? '.mp4' : '.png';
+ if (!out.toLowerCase().endsWith(ext)) return `Das Ziel muss auf ${ext} enden.`;
+ if (/^(\.git|\.soma)(\/|$)/i.test(out) || out.split('/').includes('..') || path.isAbsolute(out)) return 'Das Ziel muss im Projektordner liegen, nicht in .git/ oder .soma/.';
+ try { resolveInside(root, out); } catch { return 'Das Ziel liegt nicht im Projektordner.'; }
+ return { kind, size: [size[0], size[1]], view, at, grid: [grid[0], grid[1]], fps, anim, result, out };
+}
+
+export class RenderService {
+ private win: BrowserWindow | null = null;
+ private ready: Promise<void> | null = null;
+ private queue: Promise<unknown> = Promise.resolve();
+ private idle: NodeJS.Timeout | undefined;
+ private nextId = 1;
+ private waiting = new Map<number, { resolve: (o: RenderOutput) => void; progress?: (f: number) => void }>();
+
+ constructor() {
+ ipcMain.on('render:done', (e, id: number, out: RenderOutput) => {
+ if (e.sender !== this.win?.webContents) return;
+ this.waiting.get(id)?.resolve(out);
+ this.waiting.delete(id);
+ });
+ ipcMain.on('render:progress', (e, id: number, f: number) => {
+ if (e.sender === this.win?.webContents && Number.isFinite(f)) this.waiting.get(id)?.progress?.(f);
+ });
+ }
+
+ /** Auftrag ausführen, nach den laufenden. Schreibt die Dateien ins Projekt und gibt ihre Pfade zurück. */
+ run(dir: string, req: RenderRequest, progress?: (f: number) => void): Promise<RenderResult> {
+ const p = this.queue.then(() => this.execute(dir, req, progress));
+ this.queue = p.catch(() => undefined);
+ return p;
+ }
+
+ private async execute(dir: string, req: RenderRequest, progress?: (f: number) => void): Promise<RenderResult> {
+ clearTimeout(this.idle);
+ try {
+ const read = (rel: string) => { const b = fs.readFileSync(resolveInside(dir, rel)); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer; };
+ let model: ArrayBuffer;
+ try { model = read('.soma/model.glb'); } catch { return { ok: false, files: [], warnings: [], error: 'Noch kein gebautes Modell (soma build).' }; }
+ const id = this.nextId++;
+ const [w, h] = req.kind === 'video' ? [req.size[0] & ~1, req.size[1] & ~1] : req.size; // H.264 braucht gerade Maße
+ const job: RenderJob = {
+ id, kind: req.kind, width: w, height: h, view: req.view, at: req.at, grid: req.grid, fps: req.fps,
+ model, anim: req.anim ? read(req.anim) : null, result: req.result ? read(req.result) : null,
+ };
+ const win = await this.window();
+ const timeoutMs = req.kind === 'video' ? 20 * 60_000 : 2 * 60_000;
+ const out = await new Promise<RenderOutput>((resolve) => {
+ const timer = setTimeout(() => { this.waiting.delete(id); resolve({ ok: false, error: 'Zeitlimit beim Rendern überschritten.' }); }, timeoutMs);
+ this.waiting.set(id, { resolve: (o) => { clearTimeout(timer); resolve(o); }, progress });
+ win.webContents.send('render:job', job);
+ });
+ if (!out.ok) return { ok: false, files: [], warnings: out.warnings ?? [], error: out.error ?? 'Rendern fehlgeschlagen.' };
+ const files: string[] = [];
+ const write = (rel: string, data: ArrayBuffer | string) => {
+ const abs = resolveInside(dir, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ // Erst vollständig schreiben, dann ersetzen: Ein Player, der die alte Datei offen hat, sieht nie eine halbe
+ const tmp = `${abs}.part`;
+ fs.writeFileSync(tmp, typeof data === 'string' ? data : Buffer.from(data));
+ fs.renameSync(tmp, abs);
+ files.push(rel);
+ };
+ if (req.kind === 'video') {
+ if (!out.mp4) return { ok: false, files: [], warnings: [], error: 'Das Video ist leer.' };
+ write(req.out, out.mp4);
+ const stem = req.out.replace(/\.mp4$/i, '');
+ if (out.vtt) write(`${stem}.vtt`, out.vtt);
+ if (out.sheet) write(`${stem}-uebersicht.png`, out.sheet);
+ } else {
+ if (!out.png) return { ok: false, files: [], warnings: [], error: 'Das Bild ist leer.' };
+ write(req.out, out.png);
+ }
+ return { ok: true, files, warnings: out.warnings ?? [] };
+ } catch (e) {
+ return { ok: false, files: [], warnings: [], error: e instanceof Error ? e.message : String(e) };
+ } finally {
+ clearTimeout(this.idle);
+ this.idle = setTimeout(() => this.close(), IDLE_MS);
+ }
+ }
+
+ private window(): Promise<BrowserWindow> {
+ if (this.win && !this.win.isDestroyed() && this.ready) return this.ready.then(() => this.win!);
+ const win = new BrowserWindow({
+ show: false, width: 1280, height: 800, title: 'SOMA Render',
+ webPreferences: {
+ preload: path.join(__dirname, '..', 'preload', 'render-preload.js'),
+ contextIsolation: true, nodeIntegration: false, sandbox: true, backgroundThrottling: false,
+ },
+ });
+ this.win = win;
+ win.webContents.on('console-message', (_e, level, message) => { if (level >= 2) console.error(`[render] ${message}`); });
+ win.webContents.on('render-process-gone', (_e, d) => {
+ console.error(`[soma] Render-Fenster beendet: ${d.reason}`);
+ for (const [, w] of this.waiting) w.resolve({ ok: false, error: `Das Render-Fenster ist abgestürzt (${d.reason}).` });
+ this.waiting.clear();
+ this.close();
+ });
+ this.ready = new Promise<void>((resolve, reject) => {
+ const onReady = (e: Electron.IpcMainEvent) => { if (e.sender === win.webContents) { ipcMain.removeListener('render:ready', onReady); resolve(); } };
+ ipcMain.on('render:ready', onReady);
+ win.webContents.once('did-fail-load', (_e, code, desc) => { ipcMain.removeListener('render:ready', onReady); reject(new Error(`Render-Fenster lädt nicht: ${desc} (${code})`)); });
+ });
+ // Lädt es nicht, beim nächsten Auftrag ein neues versuchen statt ewig am alten zu scheitern
+ this.ready.catch(() => { if (this.win === win) this.close(); });
+ void win.loadFile(path.join(__dirname, '..', 'renderer', 'render.html'));
+ return this.ready.then(() => win);
+ }
+
+ close(): void {
+ clearTimeout(this.idle);
+ const w = this.win;
+ this.win = null;
+ this.ready = null;
+ if (w && !w.isDestroyed()) w.destroy();
+ }
+}
diff --git a/app/src/main/terminals.ts b/app/src/main/terminals.ts
index 47b2f9d..4e34d2c 100644
--- a/app/src/main/terminals.ts
+++ b/app/src/main/terminals.ts
@@ -1,11 +1,15 @@
import path from 'node:path';
import type { WebContents } from 'electron';
import * as pty from 'node-pty';
+import { bridgeEnv } from './bridge';
import { gitCmdDir, pythonBinDir } from './paths';
-/** Umgebung fuer Terminals: Python-Basisumgebung vorn im PATH, damit `python`, `pip` und `soma` gefunden werden. */
+/**
+ * Umgebung fuer Terminals: Python-Basisumgebung vorn im PATH, damit `python`, `pip` und `soma` gefunden werden. Dazu Adresse
+ * und Schluessel der App fuer `soma render` (E58).
+ */
export function terminalEnv(projectDir: string): NodeJS.ProcessEnv {
- const env: NodeJS.ProcessEnv = { ...process.env, PYTHONUTF8: '1', SOMA_PROJECT: projectDir };
+ const env: NodeJS.ProcessEnv = { ...process.env, PYTHONUTF8: '1', SOMA_PROJECT: projectDir, ...bridgeEnv() };
const key = Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';
const front: string[] = [];
const bin = pythonBinDir();
diff --git a/app/src/main/watcher.ts b/app/src/main/watcher.ts
index e32e655..f9a888c 100644
--- a/app/src/main/watcher.ts
+++ b/app/src/main/watcher.ts
@@ -1,5 +1,5 @@
import fs from 'node:fs';
-import { affectsBuild } from '../shared/editable';
+import { affectsAnimation, affectsBuild } from '../shared/editable';
/** Ordner, die nie einen Build oder eine Neuanzeige der Dateiliste ausloesen (Ausgaben wuerden sich sonst selbst anstossen). */
const IGNORED_TOP = new Set(['.git', '.soma', 'output', 'exports', '__pycache__', 'node_modules', '.venv', 'venv', 'env']);
@@ -12,17 +12,19 @@ const isIgnored = (rel: string) => IGNORED_TOP.has(topSegment(rel)) || rel.split
const isSource = affectsBuild;
/**
- * Beobachtet den Projektordner. `onSource` bei relevanten Aenderungen (fuer Auto-Build), `onFiles` fuer die Dateiliste.
- * Gibt eine Funktion zum Beenden zurueck. Fehler des Watchers werden verschluckt: ohne Watcher bleibt der Knopf.
+ * Beobachtet den Projektordner. `onSource` bei relevanten Aenderungen (fuer Auto-Build), `onFiles` fuer die Dateiliste,
+ * `onAnim` bei Aenderungen an animations/*.py (E58). Gibt eine Funktion zum Beenden zurueck. Fehler des Watchers werden
+ * verschluckt: ohne Watcher bleibt der Knopf.
*/
-export function watchProject(dir: string, onSource: (rel: string | null) => void, onFiles: () => void): () => void {
+export function watchProject(dir: string, onSource: (rel: string | null) => void, onFiles: () => void, onAnim: (rel: string) => void = () => {}): () => void {
let filesTimer: NodeJS.Timeout | null = null;
let watcher: fs.FSWatcher | null = null;
try {
watcher = fs.watch(dir, { recursive: true }, (_evt, filename) => {
const rel = filename ? String(filename) : '';
if (rel && isIgnored(rel) && !isFeedback(rel)) return;
- if (!rel || (isSource(rel) && !isFeedback(rel))) onSource(rel || null);
+ if (rel && affectsAnimation(rel)) onAnim(rel.replace(/\\/g, '/'));
+ else if (!rel || (isSource(rel) && !isFeedback(rel))) onSource(rel || null);
if (filesTimer) clearTimeout(filesTimer);
filesTimer = setTimeout(onFiles, 250);
});
diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.ts
index 5a0f0af..8a438f5 100644
--- a/app/src/preload/preload.ts
+++ b/app/src/preload/preload.ts
@@ -67,11 +67,25 @@ const api: SomaApi = {
configure: (id, values) => ipcRenderer.invoke('skills:configure', id, values),
setDefault: (id, mode) => ipcRenderer.invoke('skills:setDefault', id, mode),
},
+ anim: {
+ list: () => ipcRenderer.invoke('anim:list'),
+ build: (file) => ipcRenderer.invoke('anim:build', file ?? null),
+ onChanged: (cb) => { ipcRenderer.on('anim:changed', () => cb()); },
+ },
+ results: {
+ list: () => ipcRenderer.invoke('results:list'),
+ rerun: (id) => ipcRenderer.invoke('results:rerun', id),
+ },
+ render: {
+ video: (animId) => ipcRenderer.invoke('render:video', animId),
+ onProgress: (cb) => { ipcRenderer.on('render:progress', (_e, f) => cb(f)); },
+ onNotice: (cb) => { ipcRenderer.on('render:notice', (_e, n) => cb(n)); },
+ },
dialog: { choose: (o) => ipcRenderer.invoke('dialog:choose', o) },
openUrl: (url) => ipcRenderer.invoke('app:openUrl', url),
// Nur im Testmodus: vorbereitete Antworten für native Dialoge
test: process.env.SOMA_TEST === '1'
- ? { answers: (a) => ipcRenderer.invoke('test:answers', a), screenshot: (f) => ipcRenderer.invoke('test:screenshot', f) }
+ ? { answers: (a) => ipcRenderer.invoke('test:answers', a), screenshot: (f) => ipcRenderer.invoke('test:screenshot', f), bridge: () => ipcRenderer.invoke('test:bridge') }
: undefined,
};
diff --git a/app/src/preload/render-preload.ts b/app/src/preload/render-preload.ts
new file mode 100644
index 0000000..1796037
--- /dev/null
+++ b/app/src/preload/render-preload.ts
@@ -0,0 +1,12 @@
+import { contextBridge, ipcRenderer } from 'electron';
+import type { RenderApi } from '../shared/types';
+
+/** Unsichtbares Render-Fenster (E58): bekommt Aufträge mit allen Daten und gibt Bilder zurück. Kein Dateizugriff. */
+const api: RenderApi = {
+ onJob: (cb) => { ipcRenderer.on('render:job', (_e, job) => cb(job)); },
+ done: (id, out) => ipcRenderer.send('render:done', id, out),
+ progress: (id, f) => ipcRenderer.send('render:progress', id, f),
+ ready: () => ipcRenderer.send('render:ready'),
+};
+
+contextBridge.exposeInMainWorld('somaRender', api);
diff --git a/app/src/renderer/animdata.ts b/app/src/renderer/animdata.ts
new file mode 100644
index 0000000..d0cb083
--- /dev/null
+++ b/app/src/renderer/animdata.ts
@@ -0,0 +1,131 @@
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+
+// Animation aus .soma/anim/<id>.glb (E58, geschrieben von `soma anim build`): je bewegtem Bauteil ein Knoten mit Lage und
+// Drehung über die Zeit, dazu Kamera und Zielpunkt. Texte, Hervorhebungen und der Ablauf stehen in extras.soma_animation.
+// Viewer und Render-Fenster werten sie gleich aus, damit das Video aussieht wie die Ansicht.
+
+export interface AnimSpan { start: number; end: number }
+export interface AnimMeta {
+ version: number; id: string; name: string; file: string; line: number; duration: number; fps: number; fov: number;
+ /** Die Animation legt keine Kamera fest (dann Standardansicht, im Viewer bleibt die Kamera frei). */
+ cameraAuto: boolean;
+ parts: string[];
+ captions: (AnimSpan & { text: string })[];
+ titles: (AnimSpan & { text: string; subtitle?: string })[];
+ /** `at`: Punkt in der Lage im Modell, `part`: Bauteil, mit dem die Beschriftung wandert. */
+ labels: (AnimSpan & { text: string; part: string | null; at: number[] })[];
+ /** Zeitspannen je Bauteilname. */
+ states: { highlight: Record<string, number[][]>; hidden: Record<string, number[][]>; ghost: Record<string, number[][]> };
+ steps: (AnimSpan & { text: string })[];
+}
+
+/** Zustand zu einem Zeitpunkt. Lagen und Zustände nach Bauteilname. */
+export interface AnimFrame {
+ t: number;
+ poses: Map<string, THREE.Matrix4>;
+ camera: { position: THREE.Vector3; target: THREE.Vector3 };
+ caption: string | null;
+ title: { text: string; subtitle?: string } | null;
+ labels: { text: string; at: THREE.Vector3 }[];
+ hidden: Set<string>; ghost: Set<string>; highlight: Set<string>;
+}
+
+type Track = { evaluate(t: number): ArrayLike<number> };
+
+export class AnimData {
+ private constructor(
+ readonly meta: AnimMeta,
+ private readonly tracks: Map<string, { pos: Track; rot: Track }>,
+ private readonly cam: { pos: Track; target: Track },
+ ) {}
+
+ static async parse(glb: ArrayBuffer): Promise<AnimData> {
+ const gltf = await new GLTFLoader().parseAsync(glb, '');
+ const meta = (gltf.parser.json as { extras?: { soma_animation?: AnimMeta } }).extras?.soma_animation;
+ if (!meta || meta.version !== 1) throw new Error('Keine Animation von soma (extras.soma_animation fehlt)');
+ const clip = gltf.animations[0];
+ if (!clip) throw new Error('Die Datei enthält keine Bewegung');
+ // three.js benennt Knoten um (ohne Punkte, Doppelpunkte, Leerzeichen): Die Spuren heißen wie der Knoten, der echte
+ // Bauteilname steht in seinen extras
+ const byNode = new Map<string, { part?: string; camera?: boolean; target?: boolean }>();
+ gltf.scene.traverse((o) => {
+ const s = (o.userData as { soma?: { part?: string; camera?: boolean; cameraTarget?: boolean } }).soma;
+ if (s) byNode.set(o.name, { part: s.part, camera: s.camera, target: s.cameraTarget });
+ });
+ // Drehungen sphärisch, Lagen geradlinig zwischen den Abtastzeiten (wie glTF LINEAR)
+ const interp = (tr: THREE.KeyframeTrack): Track => {
+ const i = tr instanceof THREE.QuaternionKeyframeTrack
+ ? new THREE.QuaternionLinearInterpolant(tr.times, tr.values, tr.getValueSize())
+ : new THREE.LinearInterpolant(tr.times, tr.values, tr.getValueSize());
+ return { evaluate: (t) => i.evaluate(t) };
+ };
+ const tracks = new Map<string, { pos: Track; rot: Track }>();
+ const cam: Partial<{ pos: Track; target: Track }> = {};
+ const pending = new Map<string, Partial<{ pos: Track; rot: Track }>>();
+ for (const tr of clip.tracks) {
+ const dot = tr.name.lastIndexOf('.');
+ const node = tr.name.slice(0, dot), prop = tr.name.slice(dot + 1);
+ const info = byNode.get(node);
+ if (!info) continue;
+ if (info.camera && prop === 'position') cam.pos = interp(tr);
+ else if (info.target && prop === 'position') cam.target = interp(tr);
+ else if (info.part) {
+ const e = pending.get(info.part) ?? {};
+ if (prop === 'position') e.pos = interp(tr);
+ if (prop === 'quaternion') e.rot = interp(tr);
+ pending.set(info.part, e);
+ }
+ }
+ for (const [name, e] of pending) if (e.pos && e.rot) tracks.set(name, { pos: e.pos, rot: e.rot });
+ if (!cam.pos || !cam.target) throw new Error('Die Animation hat keine Kamera');
+ return new AnimData(meta, tracks, { pos: cam.pos, target: cam.target });
+ }
+
+ get duration(): number { return this.meta.duration; }
+
+ frame(time: number): AnimFrame {
+ const t = Math.max(0, Math.min(this.meta.duration, time));
+ const poses = new Map<string, THREE.Matrix4>();
+ for (const [name, tr] of this.tracks) {
+ const p = tr.pos.evaluate(t), q = tr.rot.evaluate(t);
+ poses.set(name, new THREE.Matrix4().compose(new THREE.Vector3(p[0], p[1], p[2]), new THREE.Quaternion(q[0], q[1], q[2], q[3]).normalize(), new THREE.Vector3(1, 1, 1)));
+ }
+ const cp = this.cam.pos.evaluate(t), ct = this.cam.target.evaluate(t);
+ const inSpan = (s: AnimSpan) => t >= s.start && (t < s.end || (t === s.end && s.end >= this.meta.duration));
+ const caption = this.meta.captions.find(inSpan)?.text ?? null;
+ const title = this.meta.titles.find(inSpan) ?? null;
+ const labels = this.meta.labels.filter(inSpan).map((l) => {
+ const at = new THREE.Vector3(l.at[0], l.at[1], l.at[2]);
+ const m = l.part ? poses.get(l.part) : undefined;
+ return { text: l.text, at: m ? at.applyMatrix4(m) : at };
+ });
+ const set = (rec: Record<string, number[][]>) => new Set(Object.entries(rec).filter(([, spans]) => spans.some(([a, b]) => t >= a && (t < b || b >= this.meta.duration))).map(([n]) => n));
+ return {
+ t, poses, caption, labels,
+ title: title ? { text: title.text, subtitle: title.subtitle } : null,
+ camera: { position: new THREE.Vector3(cp[0], cp[1], cp[2]), target: new THREE.Vector3(ct[0], ct[1], ct[2]) },
+ hidden: set(this.meta.states.hidden), ghost: set(this.meta.states.ghost), highlight: set(this.meta.states.highlight),
+ };
+ }
+
+ /** Untertitel als WebVTT (für Player außerhalb der App, im Video stehen sie ohnehin im Bild). */
+ vtt(): string | null {
+ if (!this.meta.captions.length) return null;
+ const ts = (s: number) => {
+ const ms = Math.round(s * 1000);
+ const h = Math.floor(ms / 3600000), m = Math.floor(ms / 60000) % 60, sec = Math.floor(ms / 1000) % 60, r = ms % 1000;
+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}.${String(r).padStart(3, '0')}`;
+ };
+ const cues = this.meta.captions.map((c, i) => `${i + 1}\n${ts(c.start)} --> ${ts(c.end)}\n${c.text.replace(/-->/g, '->')}`);
+ return `WEBVTT\n\n${cues.join('\n\n')}\n`;
+ }
+}
+
+/** Zeit für Anzeige und Agent: Sekunden mit zwei Stellen und Punkt (eindeutig für den Agenten). */
+export const fmtTime = (t: number) => `${t.toFixed(2)} s`;
+/** Zeitstempel im Video, wie Player ihn zeigen: mm:ss.cc */
+export function videoStamp(t: number): string {
+ const cs = Math.round(t * 100);
+ return `${String(Math.floor(cs / 6000)).padStart(2, '0')}:${String(Math.floor(cs / 100) % 60).padStart(2, '0')}.${String(cs % 100).padStart(2, '0')}`;
+}
diff --git a/app/src/renderer/animtool.ts b/app/src/renderer/animtool.ts
new file mode 100644
index 0000000..f11a7ef
--- /dev/null
+++ b/app/src/renderer/animtool.ts
@@ -0,0 +1,276 @@
+import * as THREE from 'three';
+import type { AnimEntry, AnimList, RenderResult } from '../shared/types';
+import { AnimData } from './animdata';
+import { icon } from './icons';
+import { paintOverlay } from './overlay';
+import { el } from './ui';
+import type { Viewer } from './viewer';
+
+// Animationen im Viewer (E58): auswählen, abspielen, an eine Stelle springen. Die Bauteile bewegen sich im echten Modell,
+// angehalten gehen Schnitt, Auswahl und Markieren. Untertitel und Beschriftungen stehen wie im Video über dem Bild.
+
+interface Ui {
+ card: HTMLElement; button: HTMLButtonElement; close: HTMLButtonElement;
+ select: HTMLSelectElement; play: HTMLButtonElement; range: HTMLInputElement; time: HTMLElement;
+ loop: HTMLButtonElement; follow: HTMLButtonElement; speed: HTMLSelectElement; hint: HTMLElement;
+ video: HTMLButtonElement; agent: HTMLButtonElement;
+ /** Bekommt die Klasse `animating`, solange die Karte offen ist. */
+ viewerEl: HTMLElement;
+}
+interface Deps {
+ viewer: Viewer;
+ list(): Promise<AnimList>;
+ build(file: string): Promise<unknown>;
+ readBinary(rel: string): Promise<ArrayBuffer>;
+ renderVideo(id: string): Promise<RenderResult>;
+ /** Vor dem Einschalten: Messen und Explosion beenden (beide brauchen die Einbaulage). */
+ beforeOn(): void;
+ insert(text: string): void;
+ toast(text: string, kind?: 'ok' | 'info' | 'error'): void;
+ /** Ein erzeugtes Video zeigen. */
+ showVideo(rel: string): void;
+}
+
+export class AnimTool {
+ private active = false;
+ private list: AnimList = { animations: [], errors: [], building: false };
+ private current: { entry: AnimEntry; data: AnimData; glb: string } | null = null;
+ private t = 0;
+ private playing = false;
+ private raf = 0;
+ private last = 0;
+ private follow = true;
+ private loop = false;
+ private rendering = false;
+ /** Für welche veraltete Animation schon ein Neubau angestoßen ist (nicht in jeder Runde erneut). */
+ private rebuilt = '';
+ private loading = 0;
+
+ constructor(private readonly ui: Ui, private readonly d: Deps) {
+ ui.button.addEventListener('click', () => this.setActive(!this.active));
+ ui.close.addEventListener('click', () => this.setActive(false));
+ ui.select.addEventListener('change', () => void this.choose(ui.select.value));
+ ui.play.addEventListener('click', () => (this.playing ? this.pause() : this.play()));
+ ui.range.addEventListener('input', () => { this.pause(); this.seek(Number(ui.range.value)); });
+ ui.loop.addEventListener('click', () => { this.loop = !this.loop; ui.loop.setAttribute('aria-pressed', String(this.loop)); });
+ ui.follow.addEventListener('click', () => this.setFollow(!this.follow));
+ ui.speed.addEventListener('change', () => { this.last = performance.now(); });
+ ui.video.addEventListener('click', () => void this.makeVideo());
+ ui.agent.addEventListener('click', () => { const t = this.agentNote(); if (t) d.insert(t); });
+ window.addEventListener('keydown', (e) => {
+ if (!this.active || (e.target as HTMLElement | null)?.closest?.('input, textarea, select, .cm-editor, #terminals')) return;
+ // Liegt ein Video oder die Zeichenfläche darüber, gehört ihnen die Leertaste
+ if (document.querySelector('#videoview:not([hidden]), #markup:not([hidden])')) return;
+ if (e.key === ' ' && !e.ctrlKey) { e.preventDefault(); if (this.playing) this.pause(); else this.play(); }
+ });
+ }
+
+ get isActive(): boolean { return this.active; }
+
+ setActive(on: boolean): void {
+ if (on === this.active) return;
+ if (on) this.d.beforeOn();
+ this.active = on;
+ this.ui.card.hidden = !on;
+ this.ui.button.setAttribute('aria-pressed', String(on));
+ this.ui.viewerEl.classList.toggle('animating', on);
+ if (on) { void this.refresh(); return; }
+ this.loading++; // ein noch laufendes Laden darf danach nichts mehr ins Modell setzen
+ this.pause();
+ this.d.viewer.setPoses(null);
+ this.d.viewer.setAnimState(null);
+ this.d.viewer.setPainter(null);
+ }
+
+ /** Liste neu lesen (Watcher, Build, Einschalten) und die gewählte Animation neu laden. */
+ async refresh(): Promise<void> {
+ if (!this.active) return;
+ const seq = ++this.loading;
+ try { this.list = await this.d.list(); } catch { return; }
+ if (seq !== this.loading || !this.active) return;
+ const anims = this.list.animations;
+ this.ui.select.replaceChildren(...anims.map((a) => el('option', { value: a.id, textContent: `${a.name} (${a.duration.toFixed(1).replace('.', ',')} s)` })));
+ this.ui.select.disabled = anims.length < 2;
+ const want = anims.find((a) => a.id === this.current?.entry.id) ?? anims[0];
+ if (want) {
+ this.ui.select.value = want.id;
+ // Veraltet (Code oder Animationsdatei geändert): einmal neu bauen lassen, die Liste kommt danach wieder
+ if (!want.stale) this.rebuilt = '';
+ else if (!this.list.building && this.rebuilt !== want.id) {
+ this.rebuilt = want.id;
+ void this.d.build(want.file);
+ }
+ await this.load(want, seq);
+ } else {
+ this.current = null;
+ this.d.viewer.setPoses(null);
+ this.d.viewer.setAnimState(null);
+ this.d.viewer.setPainter(null);
+ }
+ this.render();
+ }
+
+ /** Neues Modell geladen: Liste neu lesen (veraltet?) und die Lagen erneut anwenden, die Bauteile sind neu. */
+ modelChanged(): void { if (this.active) void this.refresh(); }
+
+ private async choose(id: string): Promise<void> {
+ const e = this.list.animations.find((a) => a.id === id);
+ if (!e) return;
+ this.pause();
+ this.t = 0;
+ await this.load(e, ++this.loading);
+ this.render();
+ }
+
+ private async load(entry: AnimEntry, seq: number): Promise<void> {
+ try {
+ const buf = await this.d.readBinary(entry.glb);
+ const data = await AnimData.parse(buf);
+ if (seq !== this.loading || !this.active) return;
+ const fresh = this.current?.entry.id !== entry.id;
+ this.current = { entry, data, glb: entry.glb };
+ if (fresh) this.setFollow(!data.meta.cameraAuto);
+ this.ui.range.max = String(data.duration);
+ this.ui.range.step = String(Math.min(0.01, data.duration / 1000));
+ this.t = Math.min(this.t, data.duration);
+ this.apply();
+ } catch (e) {
+ this.current = null;
+ this.d.toast(`Die Animation ließ sich nicht laden: ${e instanceof Error ? e.message : String(e)}`, 'error');
+ }
+ }
+
+ private setFollow(on: boolean): void {
+ this.follow = on;
+ this.ui.follow.setAttribute('aria-pressed', String(on));
+ if (on && this.current) this.apply();
+ }
+
+ private seek(t: number): void {
+ if (!this.current) return;
+ this.t = Math.max(0, Math.min(this.current.data.duration, t));
+ this.apply();
+ }
+
+ /** Stand zur aktuellen Zeit in den Viewer: Lagen, Zustände, Kamera (wenn sie folgt) und Texte. */
+ private apply(): void {
+ const c = this.current;
+ if (!c) return;
+ const f = c.data.frame(this.t);
+ const ids = new Map(this.d.viewer.partList().map((p) => [p.name, p.id]));
+ const byId = (names: Iterable<string>) => new Set([...names].map((n) => ids.get(n)).filter((x): x is string => !!x));
+ const poses = new Map<string, THREE.Matrix4>();
+ for (const [n, m] of f.poses) { const id = ids.get(n); if (id) poses.set(id, m); }
+ this.d.viewer.setPoses(poses);
+ this.d.viewer.setAnimState({ hidden: byId(f.hidden), ghost: byId(f.ghost), highlight: byId(f.highlight) });
+ if (this.follow) this.d.viewer.setCamera(f.camera.position, f.camera.target);
+ this.d.viewer.setPainter((g, w, h, project) => paintOverlay(g, w, h, {
+ caption: f.caption, title: f.title,
+ // Im Viewer steht unten links die Karte: Untertitel darüber, sonst verdeckt sie ihn (im Video steht er unten)
+ captionLift: this.ui.card.hidden ? 0 : (this.ui.card.offsetHeight + 24) * (w / Math.max(1, this.ui.viewerEl.clientWidth)),
+ labels: f.labels.map((l) => ({ text: l.text, p: project(l.at) })).filter((l) => l.p).map((l) => ({ text: l.text, x: l.p!.x, y: l.p!.y })),
+ }));
+ this.ui.range.value = String(this.t);
+ this.ui.time.textContent = `${this.t.toFixed(2).replace('.', ',')} / ${c.data.duration.toFixed(2).replace('.', ',')} s`;
+ }
+
+ play(): void {
+ if (!this.current || this.playing) return;
+ if (this.t >= this.current.data.duration - 1e-6) this.t = 0;
+ this.playing = true;
+ this.last = performance.now();
+ this.renderPlay();
+ const tick = () => {
+ if (!this.playing || !this.current) return;
+ const now = performance.now();
+ this.t += ((now - this.last) / 1000) * Number(this.ui.speed.value || 1);
+ this.last = now;
+ const dur = this.current.data.duration;
+ if (this.t >= dur) {
+ if (this.loop) this.t = this.t % Math.max(dur, 1e-3);
+ else { this.t = dur; this.apply(); this.pause(); return; }
+ }
+ this.apply();
+ this.raf = requestAnimationFrame(tick);
+ };
+ this.raf = requestAnimationFrame(tick);
+ }
+
+ pause(): void {
+ this.playing = false;
+ cancelAnimationFrame(this.raf);
+ this.renderPlay();
+ }
+
+ private renderPlay(): void {
+ this.ui.play.replaceChildren(icon(this.playing ? 'pause' : 'play', 16, 2));
+ this.ui.play.setAttribute('aria-label', this.playing ? 'Anhalten' : 'Abspielen');
+ this.ui.play.title = this.playing ? 'Anhalten (Leertaste)' : 'Abspielen (Leertaste)';
+ }
+
+ private render(): void {
+ const c = this.current, hint = this.ui.hint;
+ const err = this.list.errors[0];
+ const has = !!c;
+ for (const b of [this.ui.play, this.ui.agent, this.ui.video, this.ui.follow, this.ui.loop]) b.disabled = !has;
+ this.ui.range.disabled = !has;
+ this.ui.video.disabled = !has || this.rendering;
+ hint.classList.toggle('warn', !!err || !!c?.entry.stale);
+ if (this.rendering) return;
+ if (err) hint.textContent = `${err.file}${err.line ? `, Zeile ${err.line}` : ''}: ${err.message}`;
+ else if (this.list.building) hint.textContent = 'Animation wird gebaut …';
+ else if (c?.entry.stale) hint.textContent = 'Älter als der Code, wird neu gebaut …';
+ else if (c) hint.textContent = `${c.entry.file}, Zeile ${c.entry.line ?? 1} · ${c.entry.parts} bewegte${c.entry.parts === 1 ? 's' : ''} Bauteil${c.entry.parts === 1 ? '' : 'e'}`;
+ else hint.textContent = 'Noch keine Animation. Der Agent legt sie in animations/ an (Skill „Animation und Video“).';
+ if (!has) this.ui.time.textContent = '';
+ }
+
+ /** Fortschritt beim Erzeugen eines Videos (0 bis 1). */
+ progress(f: number): void {
+ if (!this.rendering) return;
+ this.ui.hint.classList.remove('warn');
+ this.ui.hint.textContent = `Video wird erzeugt … ${Math.round(f * 100)} %`;
+ }
+
+ private async makeVideo(): Promise<void> {
+ const c = this.current;
+ if (!c || this.rendering) return;
+ this.pause();
+ this.rendering = true;
+ this.ui.video.disabled = true;
+ this.progress(0);
+ try {
+ const r = await this.d.renderVideo(c.entry.id);
+ if (!r.ok) { this.d.toast(`Das Video ließ sich nicht erzeugen: ${r.error ?? 'unbekannter Fehler'}`, 'error'); return; }
+ const mp4 = r.files.find((f) => f.endsWith('.mp4'));
+ this.d.toast(`Video erzeugt: ${mp4}${r.warnings.length ? `\n${r.warnings.join('\n')}` : ''}`, r.warnings.length ? 'info' : 'ok');
+ if (mp4) this.d.showVideo(mp4);
+ } finally {
+ this.rendering = false;
+ this.render();
+ }
+ }
+
+ /** Für die Markierung: Welche Animation zu welcher Zeit zu sehen ist (null: keine). */
+ agentText(): string | null {
+ return this.active && this.current ? `Animation „${this.current.entry.name}“ bei ${this.t.toFixed(2)} s` : null;
+ }
+
+ private agentNote(): string | null {
+ const c = this.current;
+ return c ? `[Animation: "${c.entry.name}" (${c.entry.file}) bei ${this.t.toFixed(2)} s] ` : null;
+ }
+
+ /** Prüfhilfe: Zustand der Karte. */
+ state() {
+ return {
+ active: this.active, playing: this.playing, t: +this.t.toFixed(3), follow: this.follow, loop: this.loop,
+ name: this.current?.entry.name ?? null, duration: this.current?.data.duration ?? null,
+ options: [...this.ui.select.options].map((o) => o.textContent), hint: this.ui.hint.textContent, time: this.ui.time.textContent,
+ note: this.agentNote(), building: this.list.building, errors: this.list.errors.length,
+ };
+ }
+
+ /** Prüfhilfe: an diese Zeit springen (in unsichtbaren Fenstern läuft requestAnimationFrame nicht). */
+ testSeek(t: number): void { this.pause(); this.seek(t); }
+}
diff --git a/app/src/renderer/filetree.ts b/app/src/renderer/filetree.ts
index d9655a7..4a0ffc7 100644
--- a/app/src/renderer/filetree.ts
+++ b/app/src/renderer/filetree.ts
@@ -11,6 +11,8 @@ const FEEDBACK = '.soma/feedback';
export const TEXT_EXT = /\.(py|md|txt|json|toml|cfg|ini|yml|yaml|gitignore|csv)$|^[^.]*$/i;
/** Bilder, die die Zeichenfläche als Hintergrund laden kann (alles, was Chromium als <img> anzeigt). */
export const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|svg)$/i;
+/** Videos, die die App abspielt (E58). MOV meist nur, wenn H.264 darin steckt. */
+export const VIDEO_EXT = /\.(mp4|webm|m4v|mov)$/i;
/** Was der Baum vom Rest der App braucht. Die Aktionen liefern true, wenn das Namensfeld zugehen darf. */
export interface FileTreeDeps {
@@ -42,6 +44,7 @@ const FILE_ICONS: [RegExp, string][] = [
[/\.(stl|3mf|obj|glb|gltf|ply|amf)$/i, 'f-mesh'],
[/\.(dxf|dwg|svg)$/i, 'f-draw'],
[/\.(png|jpe?g|gif|webp|bmp|tiff?)$/i, 'f-image'],
+ [/\.(mp4|webm|m4v|mov)$/i, 'f-video'],
[/\.pdf$/i, 'f-pdf'],
[/\.(zip|7z|rar|tar|gz)$/i, 'f-zip'],
[/^\.gitignore$/i, 'f-lock'],
@@ -209,6 +212,7 @@ export class FileTree {
if (n && !n.dir) {
if (TEXT_EXT.test(n.name) || /\.pdf$/i.test(n.name)) items.push(menuItem('Öffnen', { icon: 'code', onClick: () => d.open(n) }));
if (IMAGE_EXT.test(n.name)) items.push(menuItem('Markieren', { icon: 'camera', onClick: () => d.mark(n.path) }));
+ if (VIDEO_EXT.test(n.name)) items.push(menuItem('Abspielen', { icon: 'play', onClick: () => d.open(n) }));
items.push(menuItem('Mit Standardprogramm öffnen', { icon: 'openext', onClick: () => d.openExternal(n.path) }));
}
items.push(menuItem('Im Explorer zeigen', { icon: 'folder', onClick: () => d.reveal(n?.path ?? '') }));
@@ -254,7 +258,8 @@ export class FileTree {
return b;
}
const b = this.button(depth, null, fileIcon(n.name), n.name, TAGS[n.path] ?? '', '');
- b.title = TEXT_EXT.test(n.name) || /\.pdf$/i.test(n.name) ? `${n.path} im Code-Panel öffnen` : IMAGE_EXT.test(n.name) ? `${n.path} zum Markieren öffnen` : n.path;
+ b.title = TEXT_EXT.test(n.name) || /\.pdf$/i.test(n.name) ? `${n.path} im Code-Panel öffnen` : IMAGE_EXT.test(n.name) ? `${n.path} zum Markieren öffnen`
+ : VIDEO_EXT.test(n.name) ? `${n.path} abspielen` : n.path;
b.dataset.path = n.path;
b.addEventListener('click', () => this.deps.open(n));
return b;
diff --git a/app/src/renderer/icons.ts b/app/src/renderer/icons.ts
index 60ee46d..6b43545 100644
--- a/app/src/renderer/icons.ts
+++ b/app/src/renderer/icons.ts
@@ -52,6 +52,13 @@ const PATHS: Record<string, string> = {
link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',
info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8v.01"/>', spin: '<path d="M12 3a9 9 0 1 1-9 9"/>',
play: '<path d="M7 5v14l11-7z"/>',
+ // Animation, Analyse und Video (E58)
+ pause: '<path d="M8 5v14M16 5v14"/>',
+ anim: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m10 9 5 3-5 3z"/>',
+ gauge: '<path d="M4.2 17a8.5 8.5 0 1 1 15.6 0"/><path d="m12 14 4.5-5"/><circle cx="12" cy="14" r="1.2"/>',
+ stepback: '<path d="M18 6v12l-8-6zM6 6v12"/>', stepfwd: '<path d="M6 6v12l8-6zM18 6v12"/>',
+ loop: '<path d="M17 3l3 3-3 3"/><path d="M4 11V9a3 3 0 0 1 3-3h13M7 21l-3-3 3-3"/><path d="M20 13v2a3 3 0 0 1-3 3H4"/>',
+ 'f-video': '<rect x="3" y="6" width="13" height="12" rx="2"/><path d="m16 10 5-3v10l-5-3z"/>',
// Werkzeuge der Markierung
pointer: '<path d="M6 3v16l4.2-4.1 2.9 6.2 2.6-1.2-2.9-6.1H18.5z"/>',
ghost: '<circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor" fill-opacity=".45"/>',
diff --git a/app/src/renderer/index.html b/app/src/renderer/index.html
index 0a3399b..60e223e 100644
--- a/app/src/renderer/index.html
+++ b/app/src/renderer/index.html
@@ -2,7 +2,7 @@
<html lang="de">
<head>
<meta charset="utf-8">
-<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:">
+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self' data:">
<title>SOMA</title>
<link rel="stylesheet" href="xterm.css">
<link rel="stylesheet" href="style.css">
@@ -90,6 +90,8 @@
<button id="btn-measure" aria-pressed="false" title="Messen: Fläche oder Kante anklicken, ein zweiter Klick misst Abstand und Winkel (exakte Werte)"><i data-icon="ruler"></i><span class="lbl">Messen</span></button>
<button id="btn-section" aria-pressed="false" title="Schnitt: das Modell an einer Ebene aufschneiden (senkrecht zu X, Y, Z oder parallel zu einer Fläche)"><i data-icon="section"></i><span class="lbl">Schnitt</span></button>
<button id="btn-explode" aria-pressed="false" title="Explosion: die Bauteile zur Darstellung auseinanderziehen, Normteile entlang ihrer Achse"><i data-icon="explode"></i><span class="lbl">Explosion</span></button>
+ <button id="btn-anim" aria-pressed="false" title="Animation: Bewegungen, Kamerafahrten und Texte aus animations/ abspielen, Video erzeugen"><i data-icon="anim"></i><span class="lbl">Animation</span></button>
+ <button id="btn-result" aria-pressed="false" title="Analyse: Ergebnisse von soma analyze farbig zeigen (Überhang, Wandstärke, Abstand)"><i data-icon="gauge"></i><span class="lbl">Analyse</span></button>
<span class="vsep"></span>
<button id="btn-mark" title="Viewer-Bild markieren und an den Agenten geben"><i data-icon="camera"></i><span class="lbl">Markieren</span></button>
</div>
@@ -162,6 +164,44 @@
</div>
</div>
+ <!-- Animation (E58, animtool.ts): Ablauf aus animations/*.py abspielen. Ändert nichts am Modell. -->
+ <div id="anim-card" class="float ancard" hidden>
+ <div class="mc-hd"><span class="mc-ico"><i data-icon="anim" data-size="16"></i></span><b>Animation</b>
+ <select id="anim-select" class="an-select" aria-label="Animation wählen"></select>
+ <button id="btn-anim-close" class="ibtn s" aria-label="Animation beenden" title="Animation beenden (das Modell steht wieder in Einbaulage)"><i data-icon="x" data-size="14" data-stroke="2"></i></button></div>
+ <div class="an-transport">
+ <button id="btn-anim-play" class="ibtn an-play" aria-label="Abspielen" title="Abspielen (Leertaste)"><i data-icon="play" data-size="16" data-stroke="2"></i></button>
+ <input id="anim-range" type="range" min="0" max="1" step="0.01" value="0" aria-label="Zeitpunkt in der Animation">
+ <span id="anim-time" class="an-time"></span>
+ </div>
+ <div class="an-opts">
+ <button id="btn-anim-follow" class="btn sm" aria-pressed="true" title="Kamera der Animation folgen. Aus: frei drehen, die Teile bewegen sich trotzdem"><i data-icon="camera" data-size="14" data-stroke="1.9"></i>Kamera folgen</button>
+ <button id="btn-anim-loop" class="btn sm" aria-pressed="false" title="Am Ende von vorn"><i data-icon="loop" data-size="14" data-stroke="1.9"></i>Schleife</button>
+ <span class="grow"></span>
+ <select id="anim-speed" class="an-speed" aria-label="Tempo" title="Tempo"><option value="0.25">0,25×</option><option value="0.5">0,5×</option><option value="1" selected>1×</option><option value="2">2×</option></select>
+ </div>
+ <div id="anim-hint" class="mc-hint"></div>
+ <div class="sc-actions">
+ <button id="btn-anim-video" class="btn sm" title="Video (MP4) dieser Animation nach renders/ schreiben und abspielen"><i data-icon="f-video" data-size="14" data-stroke="1.9"></i>Video erzeugen</button>
+ <button id="btn-anim-agent" class="btn sm acc" title="Name der Animation und Zeitpunkt in die Eingabe des Agenten einfügen"><i data-icon="send" data-size="14" data-stroke="1.9"></i>An Agent geben</button>
+ </div>
+ </div>
+
+ <!-- Analyse (E58, resulttool.ts): Ergebnisse von soma analyze farbig zeigen -->
+ <div id="result-card" class="float rscard" hidden>
+ <div class="mc-hd"><span class="mc-ico"><i data-icon="gauge" data-size="16"></i></span><b>Analyse</b>
+ <select id="result-select" class="an-select" aria-label="Ergebnis wählen"></select>
+ <button id="btn-result-close" class="ibtn s" aria-label="Analyse beenden" title="Analyse beenden (zeigt wieder das Modell)"><i data-icon="x" data-size="14" data-stroke="2"></i></button></div>
+ <div id="result-legend" class="rs-legend"></div>
+ <div id="result-summary" class="rs-summary"></div>
+ <div id="result-probe" class="rs-probe"></div>
+ <div id="result-hint" class="mc-hint"></div>
+ <div class="sc-actions">
+ <button id="btn-result-rerun" class="btn sm" title="Dieselbe Auswertung am aktuellen Modell noch einmal rechnen"><i data-icon="refresh" data-size="14" data-stroke="1.9"></i>Neu berechnen</button>
+ <button id="btn-result-agent" class="btn sm acc" title="Ergebnis und die angeklickte Stelle in die Eingabe des Agenten einfügen"><i data-icon="send" data-size="14" data-stroke="1.9"></i>An Agent geben</button>
+ </div>
+ </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>
<div class="ec-title"><b>Build fehlgeschlagen</b><span id="err-where" class="c2"></span></div><span class="grow"></span>
@@ -190,6 +230,22 @@
<button id="btn-restore" class="btn vio" title="Diesen Stand als neuen Stand übernehmen">Wiederherstellen</button>
</div>
+ <!-- Video (E58, videoview.ts): MP4 aus dem Projekt abspielen, Standbild markieren -->
+ <div id="videoview" class="videoview" hidden>
+ <video id="video-el" preload="auto" playsinline></video>
+ <div class="float vv-bar" role="toolbar" aria-label="Video">
+ <span class="vv-title"><i data-icon="f-video" data-size="15"></i><b id="video-title"></b></span><span class="vsep"></span>
+ <button id="btn-video-back" class="ibtn" aria-label="Ein Bild zurück" title="Ein Bild zurück (Pfeil links)"><i data-icon="stepback" data-size="15" data-stroke="1.9"></i></button>
+ <button id="btn-video-play" class="ibtn" aria-label="Abspielen" title="Abspielen oder anhalten (Leertaste)"><i data-icon="play" data-size="16" data-stroke="2"></i></button>
+ <button id="btn-video-fwd" class="ibtn" aria-label="Ein Bild vor" title="Ein Bild vor (Pfeil rechts)"><i data-icon="stepfwd" data-size="15" data-stroke="1.9"></i></button>
+ <input id="video-range" type="range" min="0" max="1" step="0.01" value="0" aria-label="Zeitpunkt im Video">
+ <span id="video-time" class="an-time"></span><span class="vsep"></span>
+ <button id="btn-video-mark" class="btn sm" title="Dieses Standbild auf der Zeichenfläche markieren und mit Zeitstempel an den Agenten geben"><i data-icon="camera" data-size="14" data-stroke="1.9"></i>Markieren</button>
+ <button id="btn-video-agent" class="btn sm acc" title="Datei und Zeitstempel in die Eingabe des Agenten einfügen"><i data-icon="send" data-size="14" data-stroke="1.9"></i>Zeit an Agent</button>
+ <button id="btn-video-close" class="ibtn" aria-label="Video schließen" title="Video schließen (Escape)"><i data-icon="x" data-size="15" data-stroke="2"></i></button>
+ </div>
+ </div>
+
<!-- Markierung (E16): eingefrorenes Bild des Viewers oder leere Fläche zum Zeichnen -->
<div id="markup" class="markup" hidden>
<canvas id="mark-canvas" aria-label="Zeichenfläche"></canvas>
diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.ts
index 28b430a..812eb7b 100644
--- a/app/src/renderer/main.ts
+++ b/app/src/renderer/main.ts
@@ -1,7 +1,8 @@
import { affectsBuild } from '../shared/editable';
import type { AgentInfo, BuildStatus, ModelMap, PartMap, PreviewResult, ProjectInfo, SaveState } from '../shared/types';
import { CodePanel, codeRows, isPdf, type Mark } from './code';
-import { FileTree, IMAGE_EXT, TEXT_EXT } from './filetree';
+import { AnimTool } from './animtool';
+import { FileTree, IMAGE_EXT, TEXT_EXT, VIDEO_EXT } from './filetree';
import { hydrateIcons, icon } from './icons';
import { Markup } from './markup';
import { MAX_QUOTE } from './pdfview';
@@ -10,9 +11,12 @@ import { SectionTool } from './sectiontool';
import { ExplodeTool } from './explodetool';
import { SkillsPanel } from './skills';
import { PartsCard } from './parts';
+import { ResultTool } from './resulttool';
+import { ResultLayer } from './resultview';
import { TerminalTabs } from './terminals';
import { $, el, fmtWhen, menuItem, menus, toast } from './ui';
import { VersionsBar } from './versions';
+import { VideoView } from './videoview';
import { PickResult, Viewer, ViewName } from './viewer';
hydrateIcons();
@@ -127,6 +131,7 @@ const files = new FileTree($('tab-files'), $('menu-ctx'), {
if (TEXT_EXT.test(n.name) || isPdf(n.name)) void openCode(n.path);
// Bilder (etwa Markierungen und Skizzen) öffnen auf der Zeichenfläche (E52), das Bildprogramm gibt es per Rechtsklick
else if (IMAGE_EXT.test(n.name)) void markImage(n.path);
+ else if (VIDEO_EXT.test(n.name)) void videoView.open(n.path);
else if (/\.(step|stp)$/i.test(n.name)) toast('Fremde STEP-Dateien im Viewer ansehen kommt in einem späteren Schritt. Der Agent kann sie schon jetzt im Skript einbinden.', 'info');
else toast('Für diesen Dateityp gibt es keine Ansicht in der App. Rechtsklick: „Mit Standardprogramm öffnen“.', 'info');
},
@@ -429,7 +434,7 @@ async function sendMarkup(): Promise<void> {
// Zeigt das Bild einen alten Stand, einen Schnitt oder eine Explosion, soll der Agent das wissen (sonst vergleicht er es mit dem
// aktuellen Code, hält die Schnittfläche für eine echte Fläche oder die auseinandergezogenen Teile für ihre Lage)
// Auf einem Bild aus dem Projekt gezeichnet: Der Agent soll das Original kennen, Stand und Schnitt spielen dann keine Rolle
- const cut = [sectionTool.agentText(), explodeTool.agentText()].filter(Boolean).join(', ');
+ const cut = [sectionTool.agentText(), explodeTool.agentText(), animTool.agentText(), resultTool.agentText()].filter(Boolean).join(', ');
const note = source ? `, gezeichnet auf ${source}`
: (old ? `, zeigt den älteren Stand ${old.short} "${old.subject.slice(0, 80)}"` : '') + (cut ? `, ${cut}` : '');
insertToAgent(`[Markierung: ${r.path}${note}] `, `Markierung gespeichert: ${r.path}`);
@@ -438,6 +443,47 @@ async function sendMarkup(): Promise<void> {
} finally { btn.disabled = false; }
}
+// ---- Animation, Analyse und Video (E58) -----------------------------------------------------------------------------
+
+const resultLayer = new ResultLayer(viewer);
+/** Messen, Explosion, Animation und Analyse schließen sich aus: Jedes braucht das Modell in seiner eigenen Lage. */
+const endOthers = (keep: 'measure' | 'explode' | 'anim' | 'result') => {
+ if (keep !== 'measure' && measureTool.isActive) measureTool.setActive(false);
+ if (keep !== 'explode' && explodeTool.isActive) explodeTool.setActive(false, false);
+ if (keep !== 'anim') animTool.setActive(false);
+ if (keep !== 'result') resultTool.setActive(false);
+};
+const animTool = new AnimTool({
+ card: $('anim-card'), button: $<HTMLButtonElement>('btn-anim'), close: $<HTMLButtonElement>('btn-anim-close'),
+ select: $<HTMLSelectElement>('anim-select'), play: $<HTMLButtonElement>('btn-anim-play'), range: $<HTMLInputElement>('anim-range'), time: $('anim-time'),
+ loop: $<HTMLButtonElement>('btn-anim-loop'), follow: $<HTMLButtonElement>('btn-anim-follow'), speed: $<HTMLSelectElement>('anim-speed'), hint: $('anim-hint'),
+ video: $<HTMLButtonElement>('btn-anim-video'), agent: $<HTMLButtonElement>('btn-anim-agent'), viewerEl: $('viewer'),
+}, {
+ viewer, list: () => api.anim.list(), build: (f) => api.anim.build(f), readBinary: (rel) => api.fs.readBinary(rel), renderVideo: (id) => api.render.video(id),
+ beforeOn: () => endOthers('anim'), insert: (t) => insertToAgent(t), toast, showVideo: (rel) => { void refreshFiles(); void videoView.open(rel); },
+});
+const resultTool = new ResultTool({
+ card: $('result-card'), button: $<HTMLButtonElement>('btn-result'), close: $<HTMLButtonElement>('btn-result-close'), select: $<HTMLSelectElement>('result-select'),
+ legend: $('result-legend'), summary: $('result-summary'), probe: $('result-probe'), hint: $('result-hint'),
+ rerun: $<HTMLButtonElement>('btn-result-rerun'), agent: $<HTMLButtonElement>('btn-result-agent'), viewerEl: $('viewer'),
+}, {
+ 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,
+});
+// Messen und Explosion schalten die beiden aus, bevor sie selbst anfangen (Lauscher in der Erfassungsphase laufen vor denen
+// der Werkzeuge): Beide rechnen mit der Einbaulage
+for (const [id, isOn] of [['btn-measure', () => measureTool.isActive], ['btn-explode', () => explodeTool.isActive]] as const) {
+ $(id).addEventListener('click', () => { if (!isOn()) { animTool.setActive(false); resultTool.setActive(false); } }, true);
+}
+const videoView = new VideoView({
+ root: $('videoview'), video: $<HTMLVideoElement>('video-el'), title: $('video-title'), play: $<HTMLButtonElement>('btn-video-play'),
+ back: $<HTMLButtonElement>('btn-video-back'), fwd: $<HTMLButtonElement>('btn-video-fwd'), range: $<HTMLInputElement>('video-range'), time: $('video-time'),
+ mark: $<HTMLButtonElement>('btn-video-mark'), agent: $<HTMLButtonElement>('btn-video-agent'), close: $<HTMLButtonElement>('btn-video-close'),
+}, {
+ readBinary: (rel) => api.fs.readBinary(rel), insert: (t) => insertToAgent(t), toast,
+ markFrame: (label, c) => markSource(label, c, c.width, c.height),
+});
+
$('btn-mark').addEventListener('click', startMarkup);
$('btn-ins-mark').addEventListener('click', startMarkup);
$('btn-mark-cancel').addEventListener('click', () => markup.close());
@@ -560,6 +606,8 @@ async function loadModel(): Promise<void> {
await viewer.load(glb);
measureTool.reset(); // neuer Build: die Nummern der Flächen und Kanten gelten nicht mehr
explodeTool.refresh(); // vor dem Schnitt: Dessen Bereich hängt von der Lage der Bauteile ab
+ animTool.modelChanged(); // neue Bauteile: Lagen erneut anwenden, eine veraltete Animation neu bauen lassen
+ if (resultTool.isActive) void resultTool.refresh();
sectionTool.refresh();
msg.className = ''; msg.textContent = '';
refreshPartsCard();
@@ -590,6 +638,8 @@ const versions = new VersionsBar({
}, {
async show(res: PreviewResult | null) {
if (!res) { await loadModel(); return; }
+ animTool.setActive(false);
+ resultTool.setActive(false);
try {
map = res.map;
textCache.clear();
@@ -618,6 +668,9 @@ async function onProject(p: ProjectInfo): Promise<void> {
if (measureTool.isActive) measureTool.setActive(false);
sectionTool.setActive(false);
explodeTool.setActive(false, false);
+ animTool.setActive(false);
+ resultTool.setActive(false);
+ videoView.close();
viewer.clear();
versions.reset();
terminals.closeAll();
@@ -977,6 +1030,14 @@ api.fs.onEditorRequest(async (action) => {
return { ok: await code.discardAll() };
});
api.versions.onChanged(() => void versions.refresh());
+api.anim.onChanged(() => void animTool.refresh());
+api.render.onProgress((f) => animTool.progress(f));
+// Bilder und Videos, die der Agent erzeugt hat: kurz Bescheid geben, ein Klick im Dateibaum öffnet sie
+api.render.onNotice((n) => {
+ if (!n.byAgent) return;
+ if (n.ok) toast(`Der Agent hat ${n.files.join(', ')} erzeugt.`, 'info');
+ void refreshFiles();
+});
api.project.onSaveState((st) => renderSaveState(st));
// Das Projekt kommt ausschließlich über das Ereignis (der Hauptprozess öffnet es beim Start). Ein zweiter Weg würde alles doppelt aufbauen.
@@ -1007,6 +1068,15 @@ if (api.testMode) {
measure: () => measureTool.state(),
section: () => sectionTool.state(),
explode: () => explodeTool.state(),
+ anim: () => animTool.state(),
+ animSeek: (t: number) => animTool.testSeek(t),
+ animRefresh: () => animTool.refresh(),
+ result: () => resultTool.state(),
+ resultRefresh: () => resultTool.refresh(),
+ resultPin: (x: number, y: number) => resultTool.testPin(x, y),
+ video: () => videoView.state(),
+ videoOpen: (rel: string) => videoView.open(rel),
+ videoSeek: (t: number) => videoView.testSeek(t),
skills: () => skills.state(),
pick: () => selection?.pick ?? null,
markPixel: (x: number, y: number) => markup.pixel(x, y),
diff --git a/app/src/renderer/overlay.ts b/app/src/renderer/overlay.ts
new file mode 100644
index 0000000..6e1115d
--- /dev/null
+++ b/app/src/renderer/overlay.ts
@@ -0,0 +1,159 @@
+import type { ResultMeta } from '../shared/types';
+
+// Texte über dem 3D-Bild (E58): Untertitel, Titelkarten und Beschriftungen von Animationen, die Legende eines Ergebnisses
+// und der Zeitstempel einer Übersicht. Gezeichnet auf einer 2D-Fläche, im Viewer wie im Video gleich: Was der Nutzer sieht,
+// steht so auch im Bild für den Agenten.
+
+export interface OverlayContent {
+ caption?: string | null;
+ title?: { text: string; subtitle?: string } | null;
+ /** Beschriftungen mit Bildpunkt (null: hinter der Kamera oder außerhalb). */
+ labels?: { text: string; x: number; y: number }[];
+ stamp?: string | null;
+ legend?: ResultMeta | null;
+ /** Untertitel so weit über dem unteren Rand (Pixel), im Viewer über der Karte der Animation. */
+ captionLift?: number;
+}
+
+const FONT = '"IBM Plex Sans", "Segoe UI", system-ui, sans-serif';
+
+function roundRect(g: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void {
+ g.beginPath();
+ g.moveTo(x + r, y);
+ g.arcTo(x + w, y, x + w, y + h, r);
+ g.arcTo(x + w, y + h, x, y + h, r);
+ g.arcTo(x, y + h, x, y, r);
+ g.arcTo(x, y, x + w, y, r);
+ g.closePath();
+}
+
+/** Zeilen umbrechen, damit lange Untertitel nicht aus dem Bild laufen. */
+function wrap(g: CanvasRenderingContext2D, text: string, max: number): string[] {
+ const words = text.split(/\s+/);
+ const lines: string[] = [];
+ let cur = '';
+ for (const w of words) {
+ const next = cur ? `${cur} ${w}` : w;
+ if (g.measureText(next).width > max && cur) { lines.push(cur); cur = w; } else cur = next;
+ }
+ if (cur) lines.push(cur);
+ return lines.slice(0, 4);
+}
+
+/** Zeichnet alles in eine Fläche der Größe w x h (Pixel). Die Schriftgröße folgt der Bildhöhe. */
+export function paintOverlay(g: CanvasRenderingContext2D, w: number, h: number, c: OverlayContent): void {
+ const unit = Math.max(10, Math.min(w, h * 1.6) / 60);
+ g.save();
+ g.textBaseline = 'middle';
+
+ for (const l of c.labels ?? []) {
+ g.font = `500 ${Math.round(unit * 0.95)}px ${FONT}`;
+ const pad = unit * 0.45, tw = g.measureText(l.text).width;
+ const bx = l.x + unit * 1.2, by = l.y - unit * 2.4, bw = tw + pad * 2, bh = unit * 1.7;
+ g.strokeStyle = 'rgba(230,232,235,.85)';
+ g.lineWidth = Math.max(1, unit * 0.09);
+ g.beginPath(); g.moveTo(l.x, l.y); g.lineTo(bx, by + bh / 2); g.stroke();
+ g.fillStyle = '#e6e8eb';
+ g.beginPath(); g.arc(l.x, l.y, unit * 0.28, 0, Math.PI * 2); g.fill();
+ g.fillStyle = 'rgba(18,20,23,.86)';
+ roundRect(g, bx, by, bw, bh, unit * 0.35); g.fill();
+ g.fillStyle = '#e6e8eb';
+ g.fillText(l.text, bx + pad, by + bh / 2);
+ }
+
+ if (c.caption) {
+ g.font = `500 ${Math.round(unit * 1.25)}px ${FONT}`;
+ const lines = wrap(g, c.caption, w * 0.8);
+ const lh = unit * 1.7, pad = unit * 0.8;
+ const bw = Math.max(...lines.map((s) => g.measureText(s).width)) + pad * 2, bh = lines.length * lh + pad;
+ const bx = (w - bw) / 2, by = h - bh - Math.max(unit * 1.6, c.captionLift ?? 0);
+ g.fillStyle = 'rgba(12,13,16,.78)';
+ roundRect(g, bx, by, bw, bh, unit * 0.4); g.fill();
+ g.fillStyle = '#f4f5f6';
+ g.textAlign = 'center';
+ lines.forEach((s, i) => g.fillText(s, w / 2, by + pad / 2 + lh * (i + 0.5)));
+ g.textAlign = 'left';
+ }
+
+ if (c.title) {
+ g.fillStyle = 'rgba(12,13,16,.62)';
+ g.fillRect(0, 0, w, h);
+ g.textAlign = 'center';
+ g.fillStyle = '#f4f5f6';
+ g.font = `600 ${Math.round(unit * 2.6)}px ${FONT}`;
+ const lines = wrap(g, c.title.text, w * 0.85);
+ const lh = unit * 3.3;
+ const top = h / 2 - (lines.length * lh) / 2 - (c.title.subtitle ? unit : 0);
+ lines.forEach((s, i) => g.fillText(s, w / 2, top + lh * (i + 0.5)));
+ if (c.title.subtitle) {
+ g.fillStyle = '#a3acb6';
+ g.font = `500 ${Math.round(unit * 1.3)}px ${FONT}`;
+ g.fillText(c.title.subtitle, w / 2, top + lh * lines.length + unit * 1.1);
+ }
+ g.textAlign = 'left';
+ }
+
+ if (c.stamp) {
+ g.font = `600 ${Math.round(unit * 1.15)}px ${FONT}`;
+ const pad = unit * 0.5, tw = g.measureText(c.stamp).width;
+ g.fillStyle = 'rgba(12,13,16,.8)';
+ roundRect(g, unit * 0.6, unit * 0.6, tw + pad * 2, unit * 1.8, unit * 0.3); g.fill();
+ g.fillStyle = '#f4f5f6';
+ g.fillText(c.stamp, unit * 0.6 + pad, unit * 1.5);
+ }
+
+ if (c.legend) paintLegend(g, w, h, unit, c.legend);
+ g.restore();
+}
+
+// Farben mit fester Bedeutung (wie --ok, --warn, --err in style.css): Grün unkritisch, Gelb nahe am Grenzwert, Rot kritisch.
+// Weit im unkritischen Bereich verblasst das Grün zu Grau, Berührung (Abstand 0) ist Blaugrau.
+const OK = [0x5c, 0xc9, 0x8b], WARN = [0xe8, 0xc5, 0x47], ERR = [0xf0, 0x74, 0x70], DEEP = [0xa8, 0x2c, 0x2c], FAR = [0x9a, 0xa4, 0xae], NEUTRAL = [0x6f, 0x8f, 0xb8];
+const mix = (a: number[], b: number[], t: number) => a.map((v, i) => v + (b[i] - v) * Math.max(0, Math.min(1, t)));
+
+/** Farbe eines Werts (RGB 0..255): kritisch rot (tiefer, je weiter), im Übergang gelb, sonst grün bis grau. */
+export function resultColor(v: number, m: Pick<ResultMeta, 'bad' | 'threshold' | 'range' | 'neutral'>): number[] {
+ if (m.neutral && v >= m.neutral[0] && v <= m.neutral[1]) return NEUTRAL;
+ const [lo, hi] = m.range;
+ // Abstand vom Grenzwert in Richtung „gut“ (positiv) bzw. „schlecht“ (negativ), auf die Spanne bezogen
+ const good = m.bad === 'low' ? v - m.threshold : m.threshold - v;
+ const spanGood = Math.max(1e-9, m.bad === 'low' ? hi - m.threshold : m.threshold - lo);
+ const spanBad = Math.max(1e-9, m.bad === 'low' ? m.threshold - lo : hi - m.threshold);
+ if (good < 0) return mix(ERR, DEEP, -good / spanBad);
+ const f = good / spanGood;
+ if (f < 0.15) return mix(WARN, OK, f / 0.15);
+ 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}`}`;
+
+/** Legende unten rechts: Farbverlauf über die Spanne, Grenzwert markiert. */
+function paintLegend(g: CanvasRenderingContext2D, w: number, h: number, unit: number, m: ResultMeta): 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 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);
+ const bx = x0 + pad, by = y0 + unit * 2.3;
+ const [lo, hi] = m.range;
+ for (let i = 0; i < bw; i++) {
+ const c = resultColor(lo + (hi - lo) * (i / Math.max(1, bw - 1)), m);
+ g.fillStyle = `rgb(${c.map(Math.round).join(',')})`;
+ g.fillRect(bx + i, by, 1.5, bh);
+ }
+ const tx = bx + ((m.threshold - lo) / (hi - lo || 1)) * bw;
+ g.fillStyle = '#f4f5f6';
+ g.fillRect(tx - 1, by - unit * 0.3, 2, bh + unit * 0.6);
+ g.font = `500 ${Math.round(unit * 0.85)}px ${FONT}`;
+ g.fillStyle = '#a3acb6';
+ g.fillText(fmt(lo, m.unit), bx, by + bh + unit * 1.0);
+ g.textAlign = 'right';
+ g.fillText(fmt(hi, m.unit), bx + bw, by + bh + unit * 1.0);
+ g.textAlign = 'center';
+ g.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';
+}
diff --git a/app/src/renderer/render.html b/app/src/renderer/render.html
new file mode 100644
index 0000000..4c500e2
--- /dev/null
+++ b/app/src/renderer/render.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<html lang="de">
+<head>
+<meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:">
+<title>SOMA Render</title>
+<style>
+ /* Unsichtbares Fenster für soma render (E58). Dieselbe Schrift wie die Oberfläche, für Untertitel und Beschriftungen. */
+ @font-face { font-family: 'IBM Plex Sans'; font-weight: 500; src: url(fonts/ibm-plex-sans-latin-500-normal.woff2) format('woff2'); }
+ @font-face { font-family: 'IBM Plex Sans'; font-weight: 600; src: url(fonts/ibm-plex-sans-latin-600-normal.woff2) format('woff2'); }
+ @font-face { font-family: 'IBM Plex Sans'; font-weight: 500; src: url(fonts/ibm-plex-sans-latin-ext-500-normal.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; }
+ @font-face { font-family: 'IBM Plex Sans'; font-weight: 600; src: url(fonts/ibm-plex-sans-latin-ext-600-normal.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; }
+ html, body { margin:0; background:#121417; overflow:hidden; }
+ #stage { position:absolute; left:0; top:0; }
+ .v-overlay { display:none; }
+</style>
+</head>
+<body>
+<div id="stage"></div>
+<script src="render.js"></script>
+</body>
+</html>
diff --git a/app/src/renderer/render.ts b/app/src/renderer/render.ts
new file mode 100644
index 0000000..95d5761
--- /dev/null
+++ b/app/src/renderer/render.ts
@@ -0,0 +1,136 @@
+import { BufferTarget, canEncodeVideo, CanvasSource, Mp4OutputFormat, Output, QUALITY_HIGH } from 'mediabunny';
+import type * as THREE from 'three';
+import type { RenderJob, RenderOutput, ResultMeta } from '../shared/types';
+import { AnimData, fmtTime } from './animdata';
+import { paintOverlay } from './overlay';
+import { ResultLayer } from './resultview';
+import { Viewer, type ViewName } from './viewer';
+
+// Unsichtbares Render-Fenster (E58): Bilder, Übersichten und Videos für `soma render` und die Knöpfe der App. Derselbe Viewer
+// wie auf dem Bildschirm, mit festen Maßen und einem Bildpunkt je Pixel. Gerendert wird Bild für Bild, nicht in Echtzeit.
+
+const api = window.somaRender;
+const viewer = new Viewer(document.getElementById('stage')!, { pixelRatio: 1 });
+const results = new ResultLayer(viewer);
+
+interface Scene { anim: AnimData | null; legend: ResultMeta | null; ids: Map<string, string>; view: ViewName }
+
+async function prepare(job: RenderJob): Promise<Scene> {
+ results.hide();
+ viewer.setPoses(null);
+ viewer.setAnimState(null);
+ viewer.setPainter(null);
+ viewer.clear();
+ viewer.resizeTo(job.width, job.height);
+ await viewer.load(job.model);
+ // Schrift erst laden lassen, sonst stehen im ersten Bild Ersatzschriften
+ await Promise.all(['500 20px "IBM Plex Sans"', '600 20px "IBM Plex Sans"'].map((f) => document.fonts.load(f).catch(() => [])));
+ const legend = job.result ? await results.show(job.result) : null;
+ const anim = job.anim ? await AnimData.parse(job.anim) : null;
+ const ids = new Map(viewer.partList().map((p) => [p.name, p.id]));
+ return { anim, legend, ids, view: (job.view as ViewName | null) ?? 'iso' };
+}
+
+/** 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 };
+ let labels: { text: string; at: THREE.Vector3 }[] = [];
+ if (s.anim) {
+ const f = s.anim.frame(t);
+ const byId = (names: Iterable<string>) => new Set([...names].map((n) => s.ids.get(n)).filter((x): x is string => !!x));
+ const poses = new Map<string, THREE.Matrix4>();
+ for (const [n, m] of f.poses) { const id = s.ids.get(n); if (id) poses.set(id, m); }
+ viewer.setPoses(poses);
+ viewer.setAnimState({ hidden: byId(f.hidden), ghost: byId(f.ghost), highlight: byId(f.highlight) });
+ if (forceView) viewer.setView(s.view);
+ else viewer.setCamera(f.camera.position, f.camera.target);
+ content = { ...content, caption: f.caption, title: f.title };
+ labels = f.labels;
+ } else viewer.setView(s.view);
+ viewer.setPainter((g, w, h, project) => paintOverlay(g, w, h, {
+ ...content, labels: labels.map((l) => ({ text: l.text, p: project(l.at) })).filter((l) => l.p).map((l) => ({ text: l.text, x: l.p!.x, y: l.p!.y })),
+ }));
+ return viewer.snapshot();
+}
+
+function png(c: HTMLCanvasElement): Promise<ArrayBuffer> {
+ return new Promise((resolve, reject) => c.toBlob((b) => (b ? b.arrayBuffer().then(resolve, reject) : reject(new Error('PNG ließ sich nicht erzeugen'))), 'image/png'));
+}
+
+/** Übersicht: Standbilder gleichmäßig über die Dauer, je mit Zeit, oben Name und Dauer der Animation. */
+async function sheet(s: Scene, job: RenderJob, cols: number, rows: number): Promise<ArrayBuffer> {
+ const anim = s.anim!;
+ const n = cols * rows, cw = job.width, ch = job.height, gap = 6, head = Math.round(Math.max(28, ch * 0.12));
+ const c = document.createElement('canvas');
+ c.width = cols * cw + (cols + 1) * gap;
+ c.height = head + rows * ch + (rows + 1) * gap;
+ const g = c.getContext('2d')!;
+ g.fillStyle = '#121417';
+ g.fillRect(0, 0, c.width, c.height);
+ g.fillStyle = '#e6e8eb';
+ g.font = `600 ${Math.round(head * 0.45)}px "IBM Plex Sans", "Segoe UI", sans-serif`;
+ g.textBaseline = 'middle';
+ g.fillText(`${anim.meta.name} · ${fmtTime(anim.duration)} · ${n} Standbilder`, gap * 2, head / 2 + gap / 2);
+ for (let i = 0; i < n; i++) {
+ const t = n === 1 ? 0 : (anim.duration * i) / (n - 1);
+ const img = frame(s, t, fmtTime(t), !!job.view);
+ g.drawImage(img, gap + (i % cols) * (cw + gap), head + gap + Math.floor(i / cols) * (ch + gap), cw, ch);
+ }
+ return png(c);
+}
+
+async function video(s: Scene, job: RenderJob, progress: (f: number) => void): Promise<{ mp4: ArrayBuffer; warnings: string[] }> {
+ const anim = s.anim!;
+ const warnings: string[] = [];
+ const c = document.createElement('canvas');
+ c.width = job.width;
+ c.height = job.height;
+ const g = c.getContext('2d')!;
+ let codec: 'avc' | 'vp9' = 'avc';
+ if (!(await canEncodeVideo('avc', { width: c.width, height: c.height }))) {
+ codec = 'vp9';
+ warnings.push('H.264 lässt sich auf diesem Rechner nicht kodieren, das Video ist VP9 (spielt in der App und in Browsern, nicht in jedem Player).');
+ }
+ const output = new Output({ format: new Mp4OutputFormat({ fastStart: 'in-memory' }), target: new BufferTarget() });
+ const source = new CanvasSource(c, { codec, bitrate: QUALITY_HIGH, keyFrameInterval: 1 });
+ output.addVideoTrack(source, { frameRate: job.fps });
+ await output.start();
+ const n = Math.max(1, Math.round(anim.duration * job.fps)) + 1;
+ for (let i = 0; i < n; i++) {
+ const t = Math.min(anim.duration, i / job.fps);
+ g.drawImage(frame(s, t, null, !!job.view), 0, 0);
+ await source.add(i / job.fps, 1 / job.fps);
+ if (i % 10 === 0) progress(i / n);
+ }
+ await output.finalize();
+ const buf = output.target.buffer;
+ if (!buf) throw new Error('Das Video ist leer.');
+ return { mp4: buf, warnings };
+}
+
+async function run(job: RenderJob): Promise<RenderOutput> {
+ const s = await prepare(job);
+ const warnings: string[] = [];
+ if (job.kind === 'still') {
+ const t = s.anim ? Math.min(job.at, s.anim.duration) : 0;
+ return { ok: true, png: await png(frame(s, t, null, !!job.view)), warnings };
+ }
+ if (!s.anim) return { ok: false, error: 'Übersicht und Video brauchen eine Animation.' };
+ if (job.kind === 'sheet') return { ok: true, png: await sheet(s, job, job.grid[0], job.grid[1]), warnings };
+ const v = await video(s, job, (f) => api.progress(job.id, f * 0.9));
+ // Übersicht zum Video, damit der Agent sieht, was darin steht (Videos kann er nicht ansehen)
+ const cw = 480, ch = Math.round(480 * job.height / job.width);
+ const sh = await sheet(s, { ...job, width: cw, height: ch }, 3, 3);
+ api.progress(job.id, 1);
+ return { ok: true, mp4: v.mp4, vtt: s.anim.vtt(), sheet: sh, warnings: [...warnings, ...v.warnings] };
+}
+
+let busy: Promise<void> = Promise.resolve();
+api.onJob((job) => {
+ busy = busy.then(async () => {
+ let out: RenderOutput;
+ try { out = await run(job); } catch (e) { out = { ok: false, error: e instanceof Error ? e.message : String(e) }; }
+ api.done(job.id, out);
+ });
+});
+api.ready();
diff --git a/app/src/renderer/resulttool.ts b/app/src/renderer/resulttool.ts
new file mode 100644
index 0000000..6ddfdc3
--- /dev/null
+++ b/app/src/renderer/resulttool.ts
@@ -0,0 +1,197 @@
+import type { ResultEntry } from '../shared/types';
+import { resultColor } from './overlay';
+import type { ResultLayer, 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.
+// Gerechnet wird in Python, hier wird nur gezeigt. Neu berechnen nutzt die Angaben, mit denen der Agent es erzeugt hat.
+
+interface Ui {
+ card: HTMLElement; button: HTMLButtonElement; close: HTMLButtonElement; select: HTMLSelectElement;
+ legend: HTMLElement; summary: HTMLElement; probe: HTMLElement; hint: HTMLElement;
+ rerun: HTMLButtonElement; agent: HTMLButtonElement;
+ viewerEl: HTMLElement;
+}
+interface Deps {
+ layer: ResultLayer;
+ list(): Promise<ResultEntry[]>;
+ rerun(id: string): Promise<{ ok: boolean; error?: string }>;
+ readBinary(rel: string): Promise<ArrayBuffer>;
+ beforeOn(): void;
+ insert(text: string): void;
+ toast(text: string, kind?: 'ok' | 'info' | 'error'): void;
+}
+
+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}`}`;
+
+export class ResultTool {
+ private active = false;
+ private list: ResultEntry[] = [];
+ private current: ResultEntry | null = null;
+ /** Zuletzt angeklickte Stelle (für „An Agent geben“). */
+ private pinned: ResultProbe | null = null;
+ private loading = 0;
+ private busy = false;
+
+ constructor(private readonly ui: Ui, private readonly d: Deps) {
+ ui.button.addEventListener('click', () => this.setActive(!this.active));
+ ui.close.addEventListener('click', () => this.setActive(false));
+ ui.select.addEventListener('change', () => { const e = this.list.find((r) => r.id === ui.select.value); if (e) void this.show(e); });
+ ui.rerun.addEventListener('click', () => void this.rerun());
+ ui.agent.addEventListener('click', () => { const t = this.agentNote(); if (t) d.insert(t); });
+ let queued = false, pos: [number, number] = [0, 0];
+ ui.viewerEl.addEventListener('pointermove', (e) => {
+ if (!this.active || e.buttons) return;
+ pos = [e.clientX, e.clientY];
+ if (queued) return;
+ queued = true;
+ requestAnimationFrame(() => { queued = false; this.showProbe(this.d.layer.probe(pos[0], pos[1]), false); });
+ });
+ let down: [number, number] | null = null;
+ ui.viewerEl.addEventListener('pointerdown', (e) => { down = [e.clientX, e.clientY]; });
+ ui.viewerEl.addEventListener('pointerup', (e) => {
+ if (!this.active || !down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4) return;
+ if ((e.target as HTMLElement).closest('.float')) return;
+ this.pinned = this.d.layer.probe(e.clientX, e.clientY);
+ this.showProbe(this.pinned, true);
+ });
+ }
+
+ get isActive(): boolean { return this.active; }
+
+ setActive(on: boolean): void {
+ if (on === this.active) return;
+ if (on) this.d.beforeOn();
+ this.active = on;
+ this.ui.card.hidden = !on;
+ this.ui.button.setAttribute('aria-pressed', String(on));
+ this.ui.viewerEl.classList.toggle('analyzing', on);
+ if (on) { void this.refresh(); return; }
+ this.loading++;
+ this.d.layer.hide();
+ this.current = null;
+ this.pinned = null;
+ }
+
+ /** Liste neu lesen (Einschalten, neuer Build, nach einer Auswertung) und das gewählte Ergebnis neu laden. */
+ async refresh(): Promise<void> {
+ if (!this.active) return;
+ const seq = ++this.loading;
+ try { this.list = await this.d.list(); } catch { return; }
+ if (seq !== this.loading || !this.active) return;
+ this.ui.select.replaceChildren(...this.list.map((r) => el('option', { value: r.id, textContent: r.id === r.kind ? r.title : `${r.title} (${r.id})` })));
+ this.ui.select.disabled = this.list.length < 2;
+ const want = this.list.find((r) => r.id === this.current?.id) ?? this.list[0];
+ if (want) await this.show(want, seq);
+ else { this.d.layer.hide(); this.current = null; this.render(); }
+ }
+
+ private async show(e: ResultEntry, seq = ++this.loading): Promise<void> {
+ try {
+ const buf = await this.d.readBinary(e.file);
+ if (seq !== this.loading || !this.active) return;
+ await this.d.layer.show(buf);
+ // Während des Ladens geschlossen oder ein anderes gewählt: nicht stehen lassen
+ if (!this.active) { this.d.layer.hide(); return; }
+ if (seq !== this.loading) return;
+ this.current = e;
+ this.ui.select.value = e.id;
+ this.pinned = null;
+ } catch (err) {
+ this.d.toast(`Das Ergebnis ließ sich nicht laden: ${err instanceof Error ? err.message : String(err)}`, 'error');
+ }
+ this.render();
+ }
+
+ private render(): void {
+ const r = this.current;
+ this.ui.rerun.disabled = !r || this.busy;
+ this.ui.agent.disabled = !r;
+ this.ui.legend.replaceChildren();
+ this.ui.summary.replaceChildren();
+ this.ui.probe.textContent = '';
+ 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).';
+ 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(' ')}`;
+ // Legende: Verlauf über die Spanne, Grenzwert als Strich
+ const [lo, hi] = r.range;
+ const stops = Array.from({ length: 24 }, (_, i) => {
+ const c = resultColor(lo + ((hi - lo) * i) / 23, r);
+ return `rgb(${c.map(Math.round).join(',')}) ${((i / 23) * 100).toFixed(1)}%`;
+ });
+ const bar = el('div', { className: 'rs-bar' });
+ bar.style.background = `linear-gradient(to right, ${stops.join(', ')})`;
+ const mark = el('div', { className: 'rs-mark' });
+ 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-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) })),
+ );
+ 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';
+ this.ui.summary.append(el('div', { className: 'rs-row' + (p.critical > 0 ? ' bad' : '') },
+ el('b', { textContent: p.name }), el('span', { textContent: `${range} · ${crit}` })));
+ }
+ this.showProbe(this.pinned, true);
+ }
+
+ private showProbe(p: ResultProbe | null, pinned: boolean): void {
+ const r = this.current;
+ if (!r) return;
+ if (!p) { if (!pinned || !this.pinned) this.ui.probe.textContent = this.pinned ? this.probeText(this.pinned, true) : 'Zeiger aufs Modell: Wert an der Stelle. Klick merkt sie für den Agenten.'; return; }
+ this.ui.probe.textContent = this.probeText(p, pinned);
+ }
+
+ 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('; ')})`;
+ }
+
+ private async rerun(): Promise<void> {
+ const r = this.current;
+ if (!r || this.busy) return;
+ this.busy = true;
+ this.render();
+ try {
+ const res = await this.d.rerun(r.id);
+ if (!res.ok) this.d.toast(`Neu berechnen ging nicht: ${res.error ?? 'unbekannter Fehler'}`, 'error');
+ } finally {
+ this.busy = false;
+ await this.refresh();
+ }
+ }
+
+ private agentNote(): string | null {
+ const r = this.current;
+ 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}] `;
+ }
+
+ /** Für die Markierung: Welches Ergebnis zu sehen ist (null: keines). */
+ agentText(): string | null {
+ return this.active && this.current ? `zeigt das Ergebnis „${this.current.title}“ (${this.current.file})` : null;
+ }
+
+ /** Prüfhilfe. */
+ state() {
+ return {
+ active: this.active, id: this.current?.id ?? null, stale: this.current?.stale ?? null, options: [...this.ui.select.options].map((o) => o.textContent),
+ 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,
+ };
+ }
+
+ /** Prüfhilfe: Stelle anklicken wie mit der Maus. */
+ testPin(x: number, y: number): ResultProbe | null { this.pinned = this.d.layer.probe(x, y); this.showProbe(this.pinned, true); return this.pinned; }
+}
diff --git a/app/src/renderer/resultview.ts b/app/src/renderer/resultview.ts
new file mode 100644
index 0000000..79d0651
--- /dev/null
+++ b/app/src/renderer/resultview.ts
@@ -0,0 +1,97 @@
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+import type { ResultMeta } from '../shared/types';
+import { resultColor } from './overlay';
+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. Der Schnitt gilt auch hier.
+
+interface ResultMesh { mesh: THREE.Mesh; name: string; values: THREE.BufferAttribute }
+
+export interface ResultProbe { name: string; value: number; point: number[] }
+
+export class ResultLayer {
+ meta: ResultMeta | null = null;
+ private group: THREE.Object3D | null = null;
+ private meshes: ResultMesh[] = [];
+
+ constructor(private readonly viewer: Viewer) {}
+
+ get active(): boolean { return !!this.group; }
+
+ async show(glb: ArrayBuffer): Promise<ResultMeta> {
+ const gltf = await new GLTFLoader().parseAsync(glb, '');
+ const meta = (gltf.parser.json as { extras?: { soma_result?: ResultMeta } }).extras?.soma_result;
+ if (!meta || !Array.isArray(meta.range)) throw new Error('Kein Ergebnis von soma (extras.soma_result fehlt)');
+ this.hide();
+ const meshes: ResultMesh[] = [];
+ gltf.scene.traverse((o) => {
+ const name = (o.userData as { soma?: { name?: string } }).soma?.name;
+ if (!name) return;
+ o.traverse((c) => {
+ const m = c as THREE.Mesh;
+ if (m.isMesh) {
+ const values = m.geometry.getAttribute('_value') as THREE.BufferAttribute | undefined;
+ if (!values) return;
+ m.material = new THREE.MeshStandardMaterial({
+ vertexColors: true, side: THREE.DoubleSide, roughness: 0.75, metalness: 0,
+ polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1, clippingPlanes: this.viewer.clipPlanes,
+ });
+ meshes.push({ mesh: m, name, values });
+ } else if ((c as THREE.LineSegments).isLineSegments) {
+ const l = c as THREE.LineSegments;
+ l.material = new THREE.LineBasicMaterial({ color: 0x1a1d22, clippingPlanes: this.viewer.clipPlanes });
+ }
+ });
+ });
+ this.meta = meta;
+ this.meshes = meshes;
+ this.group = gltf.scene;
+ this.recolor();
+ this.viewer.setModelHidden(true);
+ this.viewer.addLayer(this.group);
+ return meta;
+ }
+
+ /** Farben neu aus den Werten (etwa nach geänderter Spanne). */
+ recolor(): void {
+ if (!this.meta) return;
+ const c = new THREE.Color();
+ for (const m of this.meshes) {
+ const n = m.values.count;
+ const col = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) {
+ const rgb = resultColor(m.values.getX(i), this.meta);
+ c.setRGB(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255, THREE.SRGBColorSpace);
+ col[i * 3] = c.r; col[i * 3 + 1] = c.g; col[i * 3 + 2] = c.b;
+ }
+ m.mesh.geometry.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ }
+ this.viewer.requestRender();
+ }
+
+ hide(): void {
+ if (!this.group) return;
+ this.viewer.removeLayer(this.group);
+ this.group.traverse((o) => {
+ const m = o as THREE.Mesh;
+ m.geometry?.dispose();
+ (Array.isArray(m.material) ? m.material : m.material ? [m.material] : []).forEach((x) => x.dispose());
+ });
+ this.group = null;
+ this.meshes = [];
+ this.meta = null;
+ this.viewer.setModelHidden(false);
+ }
+
+ /** Wert unter dem Zeiger: Bauteil, Wert des Dreiecks und der Punkt (mm). */
+ probe(clientX: number, clientY: number): ResultProbe | null {
+ if (!this.group) return null;
+ const hit = this.viewer.pickObjects(clientX, clientY, this.meshes.map((m) => m.mesh));
+ if (!hit || 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)) };
+ }
+}
diff --git a/app/src/renderer/style.css b/app/src/renderer/style.css
index fe731dc..86ca3f4 100644
--- a/app/src/renderer/style.css
+++ b/app/src/renderer/style.css
@@ -428,6 +428,45 @@ code { font-family:var(--mono); font-size:.95em; }
.bn-text .tag { font-size:11px; padding:1px 7px; border-radius:9px; background:var(--vio-tint); color:#cdd2ff; }
#bn-sub { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
+/* ---- Animation, Analyse und Video (E58) ----------------------------------------------------------------------- */
+.v-paint { pointer-events:none; }
+/* Karten unten links statt der Auswahlkarte (wie beim Messen). Klicks wählen weiter Bauteile. */
+#viewer.animating #selcard, #viewer.analyzing #selcard { display:none; }
+.ancard { left:12px; bottom:12px; width:400px; overflow:hidden; }
+.rscard { left:12px; bottom:12px; width:356px; overflow:hidden; }
+.an-select { flex:1; min-width:0; height:26px; margin-left:4px; padding:0 6px; border-radius:6px; border:1px solid var(--line2); background:var(--term); color:var(--tx); font:inherit; font-size:12.5px; }
+.an-select:disabled { opacity:1; border-color:transparent; background:transparent; appearance:none; padding-left:2px; color:var(--tx2); }
+.an-transport { display:flex; align-items:center; gap:8px; padding:2px 12px 4px 8px; }
+.an-transport input[type=range], .vv-bar input[type=range] { flex:1; min-width:0; accent-color:var(--acc); height:18px; }
+.an-play { width:32px; height:32px; border-radius:8px; background:var(--acc-tint); color:var(--acc-tx); display:flex; align-items:center; justify-content:center; }
+.an-play:disabled { background:transparent; color:#5d6671; }
+.an-time { font:12px var(--mono); color:var(--tx2); white-space:nowrap; min-width:92px; text-align:right; }
+.an-opts { display:flex; align-items:center; gap:6px; padding:2px 12px 4px; }
+.an-opts .btn[aria-pressed=true] { background:var(--acc-tint); color:var(--acc-tx); border-color:var(--acc-line); }
+.an-speed { height:26px; padding:0 4px; border-radius:6px; border:1px solid var(--line2); background:var(--term); color:var(--tx); font:12px var(--mono); }
+.rs-legend { padding:2px 14px 6px; }
+.rs-q { font-size:12px; color:var(--tx2); margin-bottom:5px; }
+.rs-bar { position:relative; height:12px; border-radius:3px; }
+.rs-mark { position:absolute; top:-3px; bottom:-3px; width:2px; margin-left:-1px; background:var(--tx); border-radius:1px; }
+.rs-scale { display:flex; justify-content:space-between; gap:8px; margin-top:4px; font:11px var(--mono); color:var(--tx3); }
+.rs-scale .rs-thr { color:var(--tx2); font-family:var(--sans); }
+.rs-summary { padding:2px 0 2px; max-height:120px; overflow:auto; }
+.rs-row { display:flex; gap:8px; padding:2px 14px; font-size:12px; color:var(--tx2); min-width:0; }
+.rs-row b { color:var(--tx); font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:40%; }
+.rs-row span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+.rs-row.bad span { color:var(--err); }
+.rs-probe { margin:4px 12px 2px; padding:6px 8px; border-radius:6px; background:var(--term); font-size:12px; color:var(--tx2); min-height:28px; }
+.videoview { position:absolute; inset:0; z-index:7; background:#0d0f12; display:flex; align-items:center; justify-content:center; padding:12px 12px 64px; }
+.videoview video { max-width:100%; max-height:100%; background:#000; border-radius:6px; box-shadow:var(--shadow); }
+.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; }
+.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; }
+.vv-bar .ibtn:hover { background:var(--s3); }
+@container viewer (max-width: 760px) { .vv-title { display:none; } .ancard, .rscard { width:auto; right:12px; } }
+
/* ---- Markierung (E16) ----------------------------------------------------------------------------------------- */
#viewer.marking > .float, #viewer.marking > .cube, #viewer.marking > #viewer-msg { display:none; }
.markup { position:absolute; inset:0; z-index:8; background:var(--s2); }
diff --git a/app/src/renderer/videoview.ts b/app/src/renderer/videoview.ts
new file mode 100644
index 0000000..2588d07
--- /dev/null
+++ b/app/src/renderer/videoview.ts
@@ -0,0 +1,125 @@
+import { videoStamp } from './animdata';
+import { icon } from './icons';
+
+// Videos aus dem Projekt abspielen (E58), etwa die von `soma render --video`. Anhalten, Bild für Bild, und ein Standbild mit
+// Zeitstempel markieren oder nur die Zeit an den Agenten geben. Der Player liegt über dem Viewer, das Modell bleibt dahinter.
+
+interface Ui {
+ root: HTMLElement; video: HTMLVideoElement; title: HTMLElement;
+ play: HTMLButtonElement; back: HTMLButtonElement; fwd: HTMLButtonElement;
+ range: HTMLInputElement; time: HTMLElement; mark: HTMLButtonElement; agent: HTMLButtonElement; close: HTMLButtonElement;
+}
+interface Deps {
+ readBinary(rel: string): Promise<ArrayBuffer>;
+ /** Standbild auf der Zeichenfläche öffnen. `label` steht später in der Notiz an den Agenten. */
+ markFrame(label: string, frame: HTMLCanvasElement): Promise<void>;
+ insert(text: string): void;
+ toast(text: string, kind?: 'ok' | 'info' | 'error'): void;
+}
+
+/** Schritt für „Bild vor/zurück“: Videos von soma haben 30 Bilder je Sekunde. */
+const FRAME = 1 / 30;
+
+export class VideoView {
+ private file: string | null = null;
+ private url: string | null = null;
+
+ constructor(private readonly ui: Ui, private readonly d: Deps) {
+ const v = ui.video;
+ ui.play.addEventListener('click', () => (v.paused ? void v.play().catch(() => {}) : v.pause()));
+ ui.back.addEventListener('click', () => this.step(-1));
+ ui.fwd.addEventListener('click', () => this.step(1));
+ ui.range.addEventListener('input', () => { v.pause(); v.currentTime = Number(ui.range.value); });
+ ui.close.addEventListener('click', () => this.close());
+ ui.mark.addEventListener('click', () => void this.mark());
+ ui.agent.addEventListener('click', () => { if (this.file) d.insert(`[Video: ${this.file} bei ${videoStamp(v.currentTime)}] `); });
+ for (const ev of ['timeupdate', 'seeked', 'loadedmetadata', 'play', 'pause', 'ended']) v.addEventListener(ev, () => this.render());
+ v.addEventListener('click', () => (v.paused ? void v.play().catch(() => {}) : v.pause()));
+ v.addEventListener('error', () => { if (this.file) d.toast(`${this.file} lässt sich nicht abspielen (Format?). Rechtsklick im Dateibaum: „Mit Standardprogramm öffnen“.`, 'error'); });
+ window.addEventListener('keydown', (e) => {
+ if (ui.root.hidden || (e.target as HTMLElement | null)?.closest?.('input, textarea, select, .cm-editor, #terminals, #markup')) return;
+ if (e.key === ' ') { e.preventDefault(); if (v.paused) void v.play().catch(() => {}); else v.pause(); }
+ else if (e.key === 'ArrowLeft') { e.preventDefault(); this.step(-1); }
+ else if (e.key === 'ArrowRight') { e.preventDefault(); this.step(1); }
+ else if (e.key === 'Escape' && !document.querySelector('.menu:not([hidden])')) this.close();
+ });
+ }
+
+ get isOpen(): boolean { return !this.ui.root.hidden; }
+ get current(): string | null { return this.file; }
+
+ async open(rel: string): Promise<void> {
+ let data: ArrayBuffer;
+ try { data = await this.d.readBinary(rel); } catch (e) { this.d.toast(`${rel} lässt sich nicht lesen: ${e instanceof Error ? e.message : String(e)}`, 'error'); return; }
+ this.release();
+ this.file = rel;
+ this.url = URL.createObjectURL(new Blob([data], { type: /\.webm$/i.test(rel) ? 'video/webm' : 'video/mp4' }));
+ this.ui.video.src = this.url;
+ this.ui.title.textContent = rel;
+ this.ui.title.title = rel;
+ this.ui.root.hidden = false;
+ this.render();
+ }
+
+ close(): void {
+ this.ui.video.pause();
+ this.ui.root.hidden = true;
+ this.release();
+ this.file = null;
+ }
+
+ private release(): void {
+ this.ui.video.removeAttribute('src');
+ this.ui.video.load();
+ if (this.url) URL.revokeObjectURL(this.url);
+ this.url = null;
+ }
+
+ private step(dir: number): void {
+ const v = this.ui.video;
+ v.pause();
+ v.currentTime = Math.max(0, Math.min(v.duration || 0, v.currentTime + dir * FRAME));
+ }
+
+ private render(): void {
+ const v = this.ui.video;
+ const dur = Number.isFinite(v.duration) ? v.duration : 0;
+ this.ui.range.max = String(dur);
+ this.ui.range.step = String(FRAME / 2);
+ this.ui.range.value = String(v.currentTime);
+ this.ui.time.textContent = `${videoStamp(v.currentTime)} / ${videoStamp(dur)}`;
+ this.ui.play.replaceChildren(icon(v.paused ? 'play' : 'pause', 16, 2));
+ this.ui.play.setAttribute('aria-label', v.paused ? 'Abspielen' : 'Anhalten');
+ }
+
+ /** Das gerade gezeigte Bild in voller Auflösung. */
+ frame(): HTMLCanvasElement | null {
+ const v = this.ui.video;
+ if (!v.videoWidth || !v.videoHeight) return null;
+ const c = document.createElement('canvas');
+ c.width = v.videoWidth;
+ c.height = v.videoHeight;
+ c.getContext('2d')!.drawImage(v, 0, 0);
+ return c;
+ }
+
+ private async mark(): Promise<void> {
+ const v = this.ui.video;
+ v.pause();
+ const c = this.frame();
+ if (!c || !this.file) { this.d.toast('Das Video zeigt noch kein Bild.', 'error'); return; }
+ await this.d.markFrame(`${this.file} bei ${videoStamp(v.currentTime)}`, c);
+ }
+
+ /** Prüfhilfen. */
+ state() {
+ const v = this.ui.video;
+ return { open: this.isOpen, file: this.file, time: this.ui.time.textContent, width: v.videoWidth, height: v.videoHeight, duration: v.duration, ready: v.readyState, error: v.error?.code ?? null };
+ }
+ async testSeek(t: number): Promise<void> {
+ const v = this.ui.video;
+ v.pause();
+ await new Promise<void>((resolve) => { const done = () => { v.removeEventListener('seeked', done); resolve(); }; v.addEventListener('seeked', done); v.currentTime = t; setTimeout(done, 3000); });
+ this.render();
+ }
+}
diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.ts
index 2b95bfc..180e78f 100644
--- a/app/src/renderer/viewer.ts
+++ b/app/src/renderer/viewer.ts
@@ -25,8 +25,13 @@ interface PartEntry {
cap?: { stencils: THREE.Mesh[]; plate: THREE.Mesh };
/** Dreiecke in Weltkoordinaten, für die Schnittkontur und den Bereich des Schiebers (erst bei Bedarf berechnet). */
world?: { pos: Float32Array; idx: ArrayLike<number>; faces: boolean }[];
+ /** Lage aus einer Animation (E58), bezogen auf die Einbaulage. Fehlt: in Einbaulage. */
+ pose?: THREE.Matrix4;
}
+/** Zeichnet Texte über das Bild (E58). `project`: Weltpunkt → Bildpunkt in dieser Fläche, null hinter der Kamera. */
+export type OverlayPainter = (g: CanvasRenderingContext2D, w: number, h: number, project: (p: THREE.Vector3) => { x: number; y: number } | null) => void;
+
/** Treffer eines Strahls. `cut`: Er trifft die Schnittfläche (dort steckt er in der Schnittebene im Material). */
type Hit = THREE.Intersection & { cut?: boolean };
@@ -131,20 +136,35 @@ export class Viewer {
private showTrails = true;
/** Wartet auf einen Klick auf eine Fläche (Schnitt an Fläche ausrichten). */
private planePick: ((h: PlaneHit | null) => void) | null = null;
+ /** Animation (E58): ausgeblendete, durchsichtige und hervorgehobene Bauteile zu diesem Zeitpunkt (getrennt von den Einstellungen des Nutzers). */
+ private animHidden = new Set<string>();
+ private animGhost = new Set<string>();
+ private animHighlight = new Set<string>();
+ /** Ergebnisansicht (E58): Das Modell tritt zurück, eine eigene Ebene zeigt die gefärbten Netze. */
+ private modelHidden = false;
+ /** 2D-Fläche über dem Bild für Untertitel, Beschriftungen und Legende (E58). */
+ private paint: HTMLCanvasElement;
+ private painter: OverlayPainter | null = null;
onPick: (r: PickResult | null) => void = () => {};
/** Klick im Messmodus. null: daneben geklickt. */
onMeasurePick: (h: ProbeHit | null) => void = () => {};
/** Klick im Messmodus auf die Schnittfläche selbst (die hat keine exakte Geometrie). */
onMeasureCut: () => void = () => {};
- constructor(private container: HTMLElement) {
+ /** `pixelRatio`: fest statt der des Bildschirms (Render-Fenster: ein Bildpunkt je Pixel des Videos). */
+ constructor(private container: HTMLElement, private readonly opts: { pixelRatio?: number } = {}) {
// Durchsichtiger Hintergrund: den Verlauf dahinter zeichnet CSS, so passt er zur übrigen Oberfläche
// Schablonenpuffer (stencil) für die gefüllten Schnittflächen, seit three.js r163 nicht mehr von selbst da
this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true, alpha: true, stencil: true });
this.renderer.localClippingEnabled = true;
- this.renderer.setPixelRatio(window.devicePixelRatio);
+ this.renderer.setPixelRatio(opts.pixelRatio ?? window.devicePixelRatio);
this.renderer.setClearColor(0x000000, 0);
container.appendChild(this.renderer.domElement);
+ this.paint = document.createElement('canvas');
+ this.paint.className = 'v-paint';
+ // Liegt über dem Bild (#viewer > canvas zieht sie auf volle Größe), Klicks gehen durch auf die 3D-Ansicht
+ this.paint.style.pointerEvents = 'none';
+ container.appendChild(this.paint);
this.camera.up.set(0, 0, 1);
this.scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.6));
const sun = new THREE.DirectionalLight(0xffffff, 2.2);
@@ -292,7 +312,7 @@ export class Viewer {
get hiddenCount(): number { return this.hidden.size; }
private applyVisibility(): void {
- for (const [id, p] of this.parts) p.group.visible = !this.hidden.has(id);
+ for (const [id, p] of this.parts) p.group.visible = !this.hidden.has(id) && !this.animHidden.has(id) && !this.modelHidden;
this.syncTrails();
this.syncSection();
}
@@ -303,7 +323,7 @@ export class Viewer {
private applyDisplay(): void {
for (const [id, p] of this.parts) {
- const own = this.ghosted.has(id);
+ const own = this.ghosted.has(id) || this.animGhost.has(id);
for (const l of p.lines) {
l.visible = this.edges;
const lm = l.material as THREE.LineBasicMaterial;
@@ -535,7 +555,7 @@ export class Viewer {
partId: part.meta.partId, name: part.meta.name, role: part.meta.role,
faceId: face?.id ?? null, surface: face?.surface ?? null, area: face?.area ?? null,
// In Einbaulage: Die Explosionsansicht verschiebt nur die Darstellung, der Agent kennt nur das Modell
- point: hit.point.clone().sub(part.offset).toArray().map((v) => +v.toFixed(3)),
+ point: this.restPoint(part, hit.point).toArray().map((v) => +v.toFixed(3)),
...(hit.cut ? { cut: true } : {}),
};
}
@@ -916,7 +936,16 @@ export class Viewer {
/** Das ausgewählte Bauteil leuchtet leicht orange (Farbe der Auswahl in der ganzen Oberfläche). */
private applySelection(): void {
for (const [id, p] of this.parts) {
- for (const m of p.meshes) (m.material as THREE.MeshStandardMaterial).emissive?.setHex(id === this.selectedId ? 0x5a2e00 : 0x000000);
+ for (const m of p.meshes) {
+ const mat = m.material as THREE.MeshStandardMaterial;
+ mat.emissive?.setHex(id === this.selectedId ? 0x5a2e00 : 0x000000);
+ // Hervorhebung einer Animation (E58): Flächenfarbe deutlich nach Orange ziehen. Nur Leuchten färbte ein blaues Teil violett
+ // (Violett heißt in der Oberfläche Vorschau)
+ // (Material.clone() macht aus einer Farbe in userData ein einfaches Objekt: dann neu merken)
+ const stored = mat.userData.baseColor as unknown;
+ const base = stored instanceof THREE.Color ? stored : (mat.userData.baseColor = mat.color.clone());
+ if (this.animHighlight.has(id)) mat.color.copy(base).lerp(Viewer.highlightColor, 0.65); else mat.color.copy(base);
+ }
}
}
get selection(): string | null { return this.selectedId; }
@@ -927,6 +956,9 @@ export class Viewer {
const w = this.container.clientWidth, h = this.container.clientHeight;
if (!w || !h) return;
this.renderer.setSize(w, h, false);
+ const dpr = this.renderer.getPixelRatio();
+ this.paint.width = Math.round(w * dpr);
+ this.paint.height = Math.round(h * dpr);
for (const m of this.lineMats) m.resolution.set(w, h);
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
@@ -942,6 +974,7 @@ export class Viewer {
this.prepareSection();
this.renderer.render(this.scene, this.camera);
this.placeOverlay();
+ this.paintLive();
this.cube?.render();
});
}
@@ -993,6 +1026,7 @@ export class Viewer {
g.fillRect(-cx, -cy * rx / ry, w, h * rx / ry);
g.restore();
g.drawImage(src, 0, 0);
+ if (this.painter) this.painter(g, w, h, (p) => this.project(p, w, h));
}
/**
@@ -1329,6 +1363,129 @@ export class Viewer {
this.trails.add(l);
}
+ // ---- Animation und Ergebnisse (E58) ---------------------------------------------------------------------------
+
+ private static highlightColor = new THREE.Color(ORANGE);
+
+ /**
+ * Lage je Bauteil aus einer Animation (Matrix bezogen auf die Einbaulage, Schlüssel: partId). null oder fehlend: Einbaulage.
+ * Wie bei der Explosion arbeiten Klicks, Schnitt und Hervorhebungen danach mit der neuen Lage.
+ */
+ setPoses(poses: Map<string, THREE.Matrix4> | null): void {
+ const t = new THREE.Vector3(), q = new THREE.Quaternion(), sc = new THREE.Vector3();
+ let changed = false;
+ for (const p of this.parts.values()) {
+ const m = poses?.get(p.meta.partId) ?? null;
+ if (!m && !p.pose) continue;
+ if (m && p.pose && m.equals(p.pose)) continue;
+ p.pose = m ? m.clone() : undefined;
+ if (m) m.decompose(t, q, sc); else { t.set(0, 0, 0); q.identity(); }
+ p.group.position.copy(p.base).add(t).add(p.offset);
+ p.group.quaternion.copy(q);
+ p.group.updateMatrixWorld(true);
+ p.world = undefined;
+ changed = true;
+ }
+ if (!changed) return;
+ this.follow();
+ this.syncTrails();
+ this.syncSection();
+ this.fitClip();
+ this.requestRender();
+ }
+
+ /** Zustände einer Animation (Schlüssel: partId). null: keine. */
+ setAnimState(s: { hidden: Set<string>; ghost: Set<string>; highlight: Set<string> } | null): void {
+ const same = (a: Set<string>, b: Set<string>) => a.size === b.size && [...a].every((x) => b.has(x));
+ const next = s ?? { hidden: new Set<string>(), ghost: new Set<string>(), highlight: new Set<string>() };
+ if (same(next.hidden, this.animHidden) && same(next.ghost, this.animGhost) && same(next.highlight, this.animHighlight)) return;
+ this.animHidden = new Set(next.hidden);
+ this.animGhost = new Set(next.ghost);
+ this.animHighlight = new Set(next.highlight);
+ this.applyVisibility();
+ this.applyDisplay();
+ this.applySelection();
+ this.requestRender();
+ }
+
+ /** Kamera an diese Stelle, Blick auf `target` (Drehpunkt), Z bleibt oben. */
+ setCamera(position: THREE.Vector3, target: THREE.Vector3): void {
+ this.anim?.stop();
+ this.controls.target.copy(target);
+ this.camera.position.copy(position);
+ this.controls.update();
+ this.fitClip();
+ this.requestRender();
+ }
+
+ /** Malt Texte über das Bild (null: nichts). Wird bei jedem Zeichnen und im Schnappschuss aufgerufen. */
+ setPainter(p: OverlayPainter | null): void {
+ this.painter = p;
+ this.requestRender();
+ }
+
+ private project(p: THREE.Vector3, w: number, h: number): { x: number; y: number } | null {
+ const v = p.clone().project(this.camera);
+ if (v.z > 1) return null;
+ return { x: ((v.x + 1) / 2) * w, y: ((1 - v.y) / 2) * h };
+ }
+
+ private paintLive(): void {
+ const g = this.paint.getContext('2d');
+ if (!g) return;
+ g.clearRect(0, 0, this.paint.width, this.paint.height);
+ if (this.painter) this.painter(g, this.paint.width, this.paint.height, (p) => this.project(p, this.paint.width, this.paint.height));
+ }
+
+ /** Punkt in Einbaulage: ohne Explosion und Bewegung der Animation (der Agent kennt nur das Modell). */
+ private restPoint(part: PartEntry, p: THREE.Vector3): THREE.Vector3 {
+ const q = p.clone().sub(part.offset);
+ return part.pose ? q.applyMatrix4(part.pose.clone().invert()) : q;
+ }
+
+ /** Das Modell ausblenden, solange eine eigene Ebene (Ergebnis) es zeigt. */
+ setModelHidden(on: boolean): void {
+ if (this.modelHidden === on) return;
+ this.modelHidden = on;
+ this.applyVisibility();
+ this.requestRender();
+ }
+
+ /** Eigene Objekte in der Szene (Ergebnisse). Sie werden geschnitten, wenn ihre Materialien `clipPlanes` nutzen. */
+ addLayer(o: THREE.Object3D): void { this.scene.add(o); this.requestRender(); }
+ removeLayer(o: THREE.Object3D): void { this.scene.remove(o); this.requestRender(); }
+ /** Die Liste der Schnittebenen (leer ohne Schnitt). Dieselbe Liste für alle Materialien, sie ändert sich an Ort und Stelle. */
+ get clipPlanes(): THREE.Plane[] { return this.clip; }
+
+ /** Erster sichtbarer Treffer unter dem Zeiger auf diesen Objekten (was der Schnitt wegnimmt, zählt nicht). */
+ pickObjects(clientX: number, clientY: number, objects: THREE.Object3D[]): THREE.Intersection | null {
+ const r = this.renderer.domElement.getBoundingClientRect();
+ if (!r.width || !r.height) return null;
+ this.camera.updateMatrixWorld();
+ this.raycaster.setFromCamera(new THREE.Vector2(((clientX - r.left) / r.width) * 2 - 1, -((clientY - r.top) / r.height) * 2 + 1), this.camera);
+ return this.raycaster.intersectObjects(objects, true).find((h) => !this.clipped(h.point)) ?? null;
+ }
+
+ /** Feste Größe in CSS-Pixeln (Render-Fenster). */
+ resizeTo(w: number, h: number): void {
+ this.container.style.width = `${w}px`;
+ this.container.style.height = `${h}px`;
+ this.resize();
+ }
+
+ /** Lage eines Bauteils, für Tests: Mittelpunkt des Hüllquaders und Drehung (Quaternion). */
+ partPose(id: string): { center: number[]; quaternion: number[] } | null {
+ const p = this.parts.get(id);
+ if (!p) return null;
+ const c = new THREE.Box3().setFromObject(p.group).getCenter(new THREE.Vector3());
+ return { center: c.toArray().map((v) => +v.toFixed(3)), quaternion: p.group.quaternion.toArray().map((v) => +v.toFixed(4)) };
+ }
+
+ /** Zustand der Animation im Viewer, für Tests. */
+ animViewState() {
+ return { hidden: [...this.animHidden], ghost: [...this.animGhost], highlight: [...this.animHighlight], modelHidden: this.modelHidden, painter: !!this.painter };
+ }
+
// ---- Prüfhilfen (nur für Tests) -------------------------------------------------------------------------------
/** Verschiebung je Bauteil (nur verschobene) und Zahl der Wege, für Tests. */
diff --git a/app/src/shared/editable.ts b/app/src/shared/editable.ts
index a7ec906..b919ba2 100644
--- a/app/src/shared/editable.ts
+++ b/app/src/shared/editable.ts
@@ -37,5 +37,11 @@ export function fileOpBlockReason(rel: string, op: 'create' | 'rename' | 'delete
*/
export function affectsBuild(rel: string): boolean {
const p = rel.replace(/\\/g, '/');
+ if (affectsAnimation(p)) return false;
return /\.py$/i.test(p) || /^inputs\//i.test(p);
}
+
+/** Eine Animationsdatei (E58): Ihre Änderung baut die Animation neu, nicht das Modell. */
+export function affectsAnimation(rel: string): boolean {
+ return /^animations\/[^/]+\.py$/i.test(rel.replace(/\\/g, '/'));
+}
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index 99c5b31..958bf77 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -158,6 +158,41 @@ export interface GitLog { commits: CommitInfo[]; problems: string[]; head: strin
export interface PreviewResult { commit: CommitInfo | null; glb: ArrayBuffer; map: ModelMap; error?: string }
export interface RestoreResult { cancelled: boolean; commit?: string | null; safety?: string | null; error?: string }
+/** Animation aus animations/*.py (E58), gebaut nach `glb`. `stale`: Code oder Animationsdatei sind neuer. */
+export interface AnimEntry { id: string; name: string; file: string; line: number | null; duration: number; glb: string; parts: number; stale: boolean }
+/** Fehler einer Animationsdatei (sie hat dann keine Einträge). */
+export interface AnimFileError { file: string; line: number | null; message: string }
+export interface AnimList { animations: AnimEntry[]; errors: AnimFileError[]; building: boolean }
+export interface AnimBuildResult extends AnimList { ok: boolean; error?: string }
+
+/** Ergebnis einer Auswertung (`soma analyze`, E58), Metadaten aus extras.soma_result der GLB. */
+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;
+}
+export interface ResultMeta {
+ id: string; kind: string; title: string; quantity: string; unit: string;
+ /** Welche Seite des Grenzwerts kritisch ist. */
+ bad: 'high' | 'low';
+ threshold: number; range: [number, number];
+ /** Werte in diesem Band gelten als Berührung, nicht als kritisch (Abstand). */
+ neutral?: [number, number] | null;
+ parts: ResultPart[]; summary: string; created: number; command: string[];
+}
+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. */
+export interface RenderJob {
+ id: number; kind: 'still' | 'sheet' | 'video'; width: number; height: number;
+ view: string | null; at: number; grid: [number, number]; fps: number;
+ model: ArrayBuffer; anim: ArrayBuffer | null; result: ArrayBuffer | null;
+}
+/** Antwort des Render-Fensters. Video: MP4, Untertitel (WebVTT) und eine Übersicht als PNG. */
+export interface RenderOutput { ok: boolean; error?: string; warnings?: string[]; png?: ArrayBuffer; mp4?: ArrayBuffer; vtt?: string | null; sheet?: ArrayBuffer }
+export interface RenderResult { ok: boolean; files: string[]; warnings: string[]; error?: string }
+/** Meldung an das Hauptfenster: Bild oder Video fertig (auch auf Auftrag des Agenten). */
+export interface RenderNotice extends RenderResult { kind: 'still' | 'sheet' | 'video'; byAgent: boolean }
+
export interface SomaApi {
testMode: boolean;
project: {
@@ -183,7 +218,7 @@ export interface SomaApi {
onChanged(cb: () => void): void;
};
/** Nur im Testmodus (SOMA_TEST=1) vorhanden. */
- test?: { answers(a: unknown[]): Promise<void>; screenshot(file: string): Promise<{ width: number; height: number }> };
+ test?: { answers(a: unknown[]): Promise<void>; screenshot(file: string): Promise<{ width: number; height: number }>; bridge(): Promise<Record<string, string>> };
build: {
run(): Promise<void>;
cancel(): Promise<void>;
@@ -242,10 +277,37 @@ export interface SomaApi {
/** Stufe für neue Modelle festlegen (für die ganze App, das offene Modell bleibt, wie es ist). */
setDefault(id: string, mode: SkillMode): Promise<SkillResult>;
};
+ /** Animationen (E58): Liste aus .soma/anim/index.json, bauen über `soma anim build`. */
+ anim: {
+ list(): Promise<AnimList>;
+ /** `file` (animations/x.py) baut nur diese Datei, ohne alle. */
+ build(file?: string): Promise<AnimBuildResult>;
+ onChanged(cb: () => void): void;
+ };
+ /** Ergebnisse von `soma analyze` (E58). */
+ results: {
+ list(): Promise<ResultEntry[]>;
+ /** Dieselbe Auswertung noch einmal (mit den gespeicherten Angaben). */
+ rerun(id: string): Promise<{ ok: boolean; error?: string }>;
+ };
+ /** Bilder und Videos über das Render-Fenster (E58). */
+ render: {
+ video(animId: string): Promise<RenderResult>;
+ onProgress(cb: (fraction: number) => void): void;
+ onNotice(cb: (n: RenderNotice) => void): void;
+ };
/** Nativer Dialog mit Knöpfen, liefert den Index. Der letzte Knopf gilt als Abbrechen. Im Test über `test.answers` beantwortbar. */
dialog: { choose(o: { title: string; message: string; detail?: string; buttons: string[] }): Promise<number> };
/** Öffnet eine Web-Adresse (http, https, mailto) im Browser des Systems. Andere Adressen lehnt der Hauptprozess ab. */
openUrl(url: string): Promise<FileOpResult>;
}
-declare global { interface Window { soma: SomaApi } }
+/** Schnittstelle des unsichtbaren Render-Fensters (E58, render-preload.ts). */
+export interface RenderApi {
+ onJob(cb: (job: RenderJob) => void): void;
+ done(id: number, out: RenderOutput): void;
+ progress(id: number, fraction: number): void;
+ ready(): void;
+}
+
+declare global { interface Window { soma: SomaApi; somaRender: RenderApi } }
diff --git a/app/test/animation.mjs b/app/test/animation.mjs
new file mode 100644
index 0000000..323b481
--- /dev/null
+++ b/app/test/animation.mjs
@@ -0,0 +1,324 @@
+// Test von Animation, Analyse, soma render und Video (E58): Animationsdateien bauen (auch über den Watcher), Ablauf als Text,
+// Kollisionsprüfung, Fehler mit Datei und Zeile, Abspielen im Viewer (Lage, Hervorhebung, Kamera), Ausschluss mit Explosion
+// und Messen, soma render über die App (Bild, Übersicht, Video mit Untertiteln), Fehler der Verbindung, Video abspielen und
+// Standbild markieren, Auswertungen (Überhang, Wandstärke, Abstand) mit Anzeige, Wert unter dem Zeiger und Neu berechnen.
+// Aufruf: npm run test:animation (baut vorher). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder ab.
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+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');
+
+// Kasten mit Deckel (Scharnier hinten oben), dazu Teile für die Auswertungen: Halter mit Bohrung 6,4 und Stift 6 darin (Spalt 0,2),
+// Konsole mit waagerechter Unterseite in 10 mm Höhe (Überhang), Lasche 1 mm dünn, Störer 2 mm im Halter (Überschneidung)
+const MODEL = (tab = 1.0) => `import cadquery as cq
+from soma import add_part
+
+W, D, H, WALL = 60.0, 40.0, 25.0, 2.0
+body = cq.Workplane("XY").box(W, D, H, centered=(True, True, False)).faces(">Z").shell(-WALL)
+lid = cq.Workplane("XY").box(W, D, WALL, centered=(True, True, False)).translate((0, 0, H))
+holder = cq.Workplane("XY").box(20, 20, 10, centered=(True, True, False)).translate((50, 0, 0)).cut(
+ cq.Workplane("XY").circle(3.2).extrude(20).translate((50, 0, -5)))
+pin = cq.Workplane("XY").circle(3).extrude(14).translate((50, 0, -2))
+console = cq.Workplane("XY").box(6, 6, 10, centered=(True, True, False)).translate((-50, 0, 0)).union(
+ cq.Workplane("XY").box(20, 20, 4, centered=(True, True, False)).translate((-50, 0, 10)))
+tab = cq.Workplane("XY").box(20, ${tab}, 12, centered=(True, True, False)).translate((0, -40, 0))
+clash = cq.Workplane("XY").box(6, 6, 6, centered=(True, True, False)).translate((61, 0, 0))
+add_part("Body", body, color=(0.25, 0.45, 0.75))
+add_part("Lid", lid, color=(0.85, 0.85, 0.88))
+add_part("Halter", holder)
+add_part("Stift", pin, color=(0.6, 0.6, 0.62))
+add_part("Konsole", console)
+add_part("Lasche", tab, color=(0.8, 0.5, 0.3))
+add_part("Störer", clash, color=(0.7, 0.3, 0.3))
+`;
+
+const DECKEL = (extra = '') => `from soma.anim import Animation
+from model import D, H
+
+a = Animation("Deckel öffnen")
+lid = a.hinge("Lid", (0, D / 2, H), (1, D / 2, H))
+a.camera.set(view="iso")
+a.title("Kasten mit Deckel", subtitle="Scharnier hinten", duration=1)
+a.caption("Der Deckel öffnet bis 110°")
+a.play(lid.to(-110), run_time=2)
+a.label("Scharnier", part="Lid", at=(0, D / 2, H))
+a.wait(0.5)
+a.play(a.camera.orbit(90), run_time=2)
+a.caption(None)
+a.play(lid.to(0), a.camera.move(view="front", zoom=1.3), run_time=1.5, ease="linear")
+a.highlight("Body", duration=1)
+a.wait(1)
+${extra}`;
+
+// Drehachse durch die Mitte des Deckels: Er dreht in den Kasten hinein
+const FALSCH = `from soma.anim import Animation
+
+a = Animation("Deckel falsch")
+lid = a.hinge("Lid", (0, 0, 26), (1, 0, 26))
+a.play(lid.to(60), run_time=1)
+`;
+const KAPUTT = `from soma.anim import Animation
+a = Animation("Kaputt")
+a.hinge("Gibtsnicht", (0, 0, 0), (1, 0, 0))
+`;
+
+const near = (a, b, eps = 1e-3) => 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: 'animation' });
+ 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 proj = await ev(() => window.__t.project());
+ const dir = proj.dir;
+ fs.writeFileSync(path.join(dir, 'model.py'), MODEL());
+ await waitFor('Testmodell gebaut', () => window.__t.status().state === 'ok' && window.__t.partCount() === 7, 90000);
+ const ids = await ev(() => Object.fromEntries(window.__t.parts().map((p) => [p.name, p.id])));
+ const bridge = await ev(() => window.soma.test.bridge());
+ const env = { ...process.env, ...bridge, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' };
+ const soma = (args, opts = {}) => spawnSync(PY, ['-m', 'soma', ...args], { cwd: dir, env, encoding: 'utf8', timeout: 10 * 60 * 1000, ...opts });
+ const tid = await ev(() => window.__t.terminals.activeId);
+ const term = () => ev((id) => window.__t.termText(id), tid);
+ check('Verbindung für soma render: Adresse auf 127.0.0.1 und Schlüssel', /^127\.0\.0\.1:\d+$/.test(bridge.SOMA_APP ?? '') && (bridge.SOMA_APP_TOKEN ?? '').length >= 32, bridge.SOMA_APP);
+
+ // 1) Animationsdatei anlegen: Der Watcher baut sie, die Liste kennt sie
+ fs.mkdirSync(path.join(dir, 'animations'));
+ fs.writeFileSync(path.join(dir, 'animations', 'deckel.py'), DECKEL());
+ const list = () => ev(() => window.soma.anim.list());
+ await waitFor('Animation gebaut (Watcher)', () => window.soma.anim.list().then((l) => l.animations.some((a) => a.name === 'Deckel öffnen') && !l.building), 90000);
+ let l = await list();
+ let e = l.animations.find((a) => a.name === 'Deckel öffnen');
+ check('Watcher baut neue Animationsdatei: Name, Datei, Zeile 4, 8 s, ein bewegtes Teil, aktuell', e.id === 'deckel-oeffnen' && e.file === 'animations/deckel.py'
+ && e.line === 4 && near(e.duration, 8) && e.parts === 1 && !e.stale && fs.existsSync(path.join(dir, '.soma', 'anim', 'deckel-oeffnen.glb')), JSON.stringify(e));
+ check('Animationsdatei baut das Modell nicht neu (eigener Weg)', await ev(() => window.__t.buildStarts()) <= 2, String(await ev(() => window.__t.buildStarts())));
+
+ let r = soma(['anim', 'info', 'Deckel öffnen']);
+ check('soma anim info: Ablauf mit Zeiten, Gelenk, Kamera, Untertitel, Beschriftung', r.status === 0 && r.stdout.includes('Dauer 8.00 s')
+ && r.stdout.includes('1.00-3.00 s Lid: 0 -> -110 Grad') && r.stdout.includes('Kamera: Umlauf 90 Grad') && r.stdout.includes('"Der Deckel öffnet bis 110°"')
+ && r.stdout.includes('"Scharnier" an Lid') && r.stdout.includes('nicht geprueft'), r.stdout.slice(0, 300) + r.stderr);
+
+ // 2) Kollisionen: falsche Drehachse dreht den Deckel in den Kasten
+ fs.writeFileSync(path.join(dir, 'animations', 'falsch.py'), FALSCH);
+ await waitFor('zweite Animation', () => window.soma.anim.list().then((x) => x.animations.length === 2 && !x.building), 90000);
+ r = soma(['anim', 'check', 'Deckel falsch', '--step', '0.25']);
+ check('soma anim check meldet die Kollision Lid / Body mit Zeit und Volumen (Exit 1)', r.status === 1 && /Lid \/ Body: Kollision, Ueberschneidung bis \d/.test(r.stdout), r.stdout + r.stderr);
+ r = soma(['anim', 'check', 'Deckel öffnen', '--step', '0.5']);
+ check('Richtige Drehachse: keine Kollision (Exit 0), Berührung in der Lage im Modell nur mit Abstand als Hinweis', r.status === 0 && !r.stdout.includes('Kollision,'), r.stdout);
+ r = soma(['anim', 'info', 'Deckel falsch']);
+ check('Ergebnis der Prüfung steht danach in soma anim info', r.stdout.includes('Lid / Body: Kollision'), r.stdout.slice(-300));
+
+ // 3) Fehler in einer Animationsdatei: Datei, Zeile, Liste der Bauteile. Die anderen bleiben
+ fs.writeFileSync(path.join(dir, 'animations', 'kaputt.py'), KAPUTT);
+ await waitFor('Fehler gemeldet', () => window.soma.anim.list().then((x) => x.errors.length === 1 && !x.building), 90000);
+ l = await list();
+ check('Fehler mit Datei und Zeile 3, nennt das Bauteil und die vorhandenen, die anderen Animationen bleiben', l.errors[0].file === 'animations/kaputt.py'
+ && l.errors[0].line === 3 && l.errors[0].message.includes("'Gibtsnicht' gibt es im Modell nicht") && l.errors[0].message.includes("'Lid'") && l.animations.length === 2,
+ JSON.stringify(l.errors[0]));
+ r = soma(['anim', 'build', 'animations/kaputt.py']);
+ check('soma anim build: FEHLER mit Ort im Fehlerkanal, Exit 1', r.status === 1 && r.stderr.includes('Animation FEHLER (animations/kaputt.py:3)'), r.stderr.slice(0, 200));
+ fs.rmSync(path.join(dir, 'animations', 'kaputt.py'));
+ await waitFor('Fehler weg', () => window.soma.anim.list().then((x) => x.errors.length === 0), 20000).catch(() => {});
+ check('Gelöschte Datei: Ihr Fehler verschwindet aus der Liste', (await list()).errors.length === 0);
+
+ // 4) Abspielen im Viewer
+ await domClick('btn-anim');
+ await waitFor('Animation geladen', () => window.__t.anim().name !== null, 20000);
+ await ev(() => { const s = document.getElementById('anim-select'); s.value = 'deckel-oeffnen'; s.dispatchEvent(new Event('change')); });
+ await waitFor('Deckel öffnen gewählt', () => window.__t.anim().name === 'Deckel öffnen', 10000);
+ let s = await ev(() => window.__t.anim());
+ check('Karte „Animation“: zwei zur Auswahl, Dauer 8 s, Kamera folgt (eigene Kamera), Hinweis mit Datei', s.active && s.options.length === 2 && near(s.duration, 8)
+ && s.follow && s.hint.startsWith('animations/deckel.py, Zeile 4') && s.time === '0,00 / 8,00 s'
+ && await ev(() => document.getElementById('btn-anim').getAttribute('aria-pressed') === 'true'), JSON.stringify(s));
+ await ev(() => window.__t.animSeek(3));
+ let pose = await ev((id) => window.__t.viewer.partPose(id), ids.Lid);
+ const q = [-Math.sin(55 * Math.PI / 180), 0, 0, Math.cos(55 * Math.PI / 180)];
+ check('Bei 3 s: Deckel um 110° um die hintere Kante gedreht (Mitte und Drehung)', near(pose.center[1], 27.78, 0.05) && near(pose.center[2], 43.45, 0.05)
+ && pose.quaternion.every((v, i) => near(Math.abs(v), Math.abs(q[i]), 2e-3)), JSON.stringify(pose));
+ const body0 = await ev((id) => window.__t.viewer.partPose(id), ids.Body);
+ check('Andere Teile bleiben in Einbaulage', near(body0.center[2], 12.5, 1e-3) && body0.quaternion[3] === 1, JSON.stringify(body0));
+ await shot('anim-1-offen');
+ await ev(() => window.__t.animSeek(7.5));
+ let vs = await ev(() => window.__t.viewer.animViewState());
+ const view = await ev(() => window.__t.viewer.viewState());
+ check('Bei 7,5 s: Kasten hervorgehoben, Kamera von vorn, Texte werden gemalt', vs.highlight.includes(ids.Body) && vs.painter
+ && near(view.dir[0], 0, 0.02) && near(view.dir[1], -1, 0.02), JSON.stringify([vs, view.dir]));
+ s = await ev(() => window.__t.anim());
+ check('„An Agent geben“: Name, Datei und Zeit', s.note === '[Animation: "Deckel öffnen" (animations/deckel.py) bei 7.50 s] ', s.note);
+ await ev(() => window.__t.animSeek(2));
+ await shot('anim-2-halb');
+
+ // 5) Ausschluss: Explosion und Messen beenden die Animation, das Modell steht wieder in Einbaulage
+ await domClick('btn-explode');
+ await sleep(300);
+ s = await ev(() => window.__t.anim());
+ pose = await ev((id) => window.__t.viewer.partPose(id), ids.Lid);
+ check('Explosion beendet die Animation (Deckel ohne Drehung, Hervorhebung weg)', !s.active && pose.quaternion[3] === 1
+ && (await ev(() => window.__t.viewer.animViewState())).highlight.length === 0, JSON.stringify(pose));
+ await domClick('btn-anim');
+ await waitFor('Animation wieder an', () => window.__t.anim().active && window.__t.anim().name === 'Deckel öffnen', 10000);
+ check('Animation beendet die Explosion', !(await ev(() => window.__t.explode())).active);
+ await domClick('btn-measure');
+ await sleep(200);
+ check('Messen beendet die Animation', !(await ev(() => window.__t.anim())).active && (await ev(() => window.__t.measure())).active);
+ await domClick('btn-measure');
+
+ // 6) soma render: Fehler der Verbindung
+ r = soma(['render'], { env: { ...process.env, PYTHONUTF8: '1', SOMA_APP: '', SOMA_APP_TOKEN: '' } });
+ check('Ohne die Umgebung der App: verständliche Meldung', r.status === 1 && r.stderr.includes('braucht die laufende App'), r.stderr);
+ r = soma(['render'], { env: { ...env, SOMA_APP_TOKEN: 'x'.repeat(48) } });
+ check('Falscher Schlüssel: abgelehnt', r.status === 1 && r.stderr.includes('Falscher Schlüssel'), r.stderr);
+ const other = fs.mkdtempSync(path.join(os.tmpdir(), 'soma-anderes-'));
+ r = soma(['render', '--project', other]);
+ check('Anderer Ordner als das offene Modell: abgelehnt', r.status === 1 && r.stderr.includes('nicht das Modell'), r.stderr);
+ cleanup(other);
+ r = soma(['render', '--anim', 'Deckel öffnen', '--at', '99']);
+ check('Zeit außerhalb der Animation: Meldung mit der Dauer', r.status === 1 && r.stderr.includes('dauert 8 s'), r.stderr);
+
+ // 7) soma render: Bild, Animation zu einer Zeit, Übersicht, Video
+ r = soma(['render']);
+ const iso = path.join(dir, 'renders', 'ansicht-iso.png');
+ check('soma render: renders/ansicht-iso.png in 1280 x 800', r.status === 0 && r.stdout.includes('geschrieben: renders/ansicht-iso.png')
+ && JSON.stringify(pngSize(iso)) === '[1280,800]', r.stdout + r.stderr);
+ r = soma(['render', '--view', 'top', '--size', '640x400', '--out', 'renders/oben.png']);
+ check('--view, --size und --out', r.status === 0 && JSON.stringify(pngSize(path.join(dir, 'renders', 'oben.png'))) === '[640,400]', r.stdout + r.stderr);
+ r = soma(['render', '--anim', 'Deckel öffnen', '--at', '2']);
+ check('Animation zu einer Zeit: renders/deckel-oeffnen-2s.png', r.status === 0 && fs.existsSync(path.join(dir, 'renders', 'deckel-oeffnen-2s.png')), r.stdout + r.stderr);
+ r = soma(['render', '--anim', 'Deckel öffnen', '--sheet', '3x2', '--size', '320x200']);
+ const sheet = pngSize(path.join(dir, 'renders', 'deckel-oeffnen-uebersicht.png'));
+ check('Übersicht 3 x 2 Standbilder mit Kopfzeile', r.status === 0 && sheet && sheet[0] === 3 * 320 + 4 * 6 && sheet[1] > 2 * 200, JSON.stringify(sheet) + r.stderr);
+ const t0 = Date.now();
+ r = soma(['render', '--anim', 'Deckel öffnen', '--video']);
+ const mp4 = path.join(dir, 'renders', 'deckel-oeffnen.mp4');
+ const head = fs.existsSync(mp4) ? fs.readFileSync(mp4).subarray(4, 8).toString('ascii') : '';
+ const vtt = fs.existsSync(mp4.replace('.mp4', '.vtt')) ? fs.readFileSync(mp4.replace('.mp4', '.vtt'), 'utf8') : '';
+ check('Video: MP4, Untertitel als WebVTT, Übersicht für den Agenten', r.status === 0 && head === 'ftyp' && vtt.startsWith('WEBVTT')
+ && vtt.includes('00:00:01.000 --> 00:00:05.500') && vtt.includes('Der Deckel öffnet bis 110°') && r.stdout.includes('Uebersicht (PNG)'),
+ `${head} ${Date.now() - t0} ms ${r.stderr}`);
+ await waitFor('Hinweis im Fenster', () => window.__t.toast().text.includes('Der Agent hat renders/deckel-oeffnen.mp4'), 5000).catch(() => {});
+ check('Das Fenster meldet, was der Agent erzeugt hat', (await ev(() => window.__t.toast())).text.includes('Der Agent hat renders/deckel-oeffnen.mp4'));
+
+ // 8) Video abspielen, Zeit und Standbild an den Agenten
+ await ev(() => window.__t.showPanel('files'));
+ await waitFor('Video im Dateibaum', () => window.__t.fileRows().includes('deckel-oeffnen.mp4'), 10000).catch(() => {});
+ await ev(() => document.querySelector('#tab-files .frow[data-path="renders/deckel-oeffnen.mp4"]')?.click());
+ await waitFor('Video geladen', () => window.__t.video().ready >= 2 && window.__t.video().width > 0, 20000).catch(() => {});
+ let v = await ev(() => window.__t.video());
+ check('Klick im Dateibaum spielt das Video in der App: 1280 x 720, gut 8 s', v.open && v.file === 'renders/deckel-oeffnen.mp4' && v.width === 1280 && v.height === 720
+ && near(v.duration, 8.03, 0.1), JSON.stringify(v));
+ await ev(() => window.__t.videoSeek(2));
+ v = await ev(() => window.__t.video());
+ check('Springen auf 2 s: Zeitanzeige', v.time.startsWith('00:02.00 / 00:08'), v.time);
+ await shot('video-1');
+ await domClick('btn-video-agent');
+ await waitFor('Zeit im Terminal', (id) => window.__t.termText(id).includes('[Video: renders/deckel-oeffnen.mp4 bei 00:02.00]'), 8000, tid).catch(() => {});
+ check('„Zeit an Agent“: Datei und Zeitstempel in der Eingabe', (await term()).includes('[Video: renders/deckel-oeffnen.mp4 bei 00:02.00]'), (await term()).slice(-200));
+ await domClick('btn-video-mark');
+ await waitFor('Zeichenfläche', () => window.__t.markup().active, 8000);
+ const mk = await ev(() => window.__t.markup());
+ check('„Markieren“: Standbild auf der Zeichenfläche, Quelle mit Zeitstempel', mk.source === 'renders/deckel-oeffnen.mp4 bei 00:02.00', JSON.stringify(mk.source));
+ await shot('video-2-markieren');
+ await domClick('btn-mark-send');
+ await waitFor('Markierung im Terminal', (id) => window.__t.termText(id).includes('gezeichnet auf renders/deckel-oeffnen.mp4 bei 00:02.00]'), 10000, tid).catch(() => {});
+ check('Markierung des Standbilds: Pfad des Bilds, Video und Zeit in der Eingabe', /\[Markierung: \.soma\/feedback\/markierung-[\d-]+\.png, gezeichnet auf renders\/deckel-oeffnen\.mp4 bei 00:02\.00\]/.test(await term()),
+ (await term()).slice(-200));
+ await domClick('btn-video-close');
+ check('Schließen: Player weg', !(await ev(() => window.__t.video())).open);
+
+ // 9) Knopf „Video erzeugen“ in der Animation
+ await domClick('btn-anim');
+ await waitFor('Animation an', () => window.__t.anim().active && !!window.__t.anim().name, 10000);
+ fs.rmSync(mp4);
+ await domClick('btn-anim-video');
+ await waitFor('Video erzeugt und geöffnet', () => window.__t.video().open && window.__t.video().file === 'renders/deckel-oeffnen.mp4', 120000).catch(() => {});
+ check('„Video erzeugen“: MP4 entsteht und spielt in der App', fs.existsSync(mp4) && (await ev(() => window.__t.video())).open, JSON.stringify(await ev(() => window.__t.toast())));
+ await domClick('btn-video-close');
+ await domClick('btn-anim-close');
+
+ // 10) Auswertungen
+ r = soma(['analyze', 'overhang']);
+ check('Überhang: Konsole hat 3,64 cm² Überhang (Unterseite in 10 mm Höhe), Kasten keinen', r.status === 0
+ && /Konsole: 0\.0° bis 90\.0°, 3\.6\d cm² über 45\.0°/.test(r.stdout) && /Body: [^\n]*nichts über 45\.0°/.test(r.stdout), r.stdout + r.stderr);
+ r = soma(['analyze', 'thickness']);
+ check('Wandstärke: Lasche 1 mm unter dem Grenzwert 1,2, Kasten nicht', r.status === 0 && /Lasche: 1\.00 mm bis [^\n]*cm² unter 1\.20 mm/.test(r.stdout)
+ && /Body: 2\.00 mm bis [^\n]*nichts unter 1\.20 mm/.test(r.stdout), r.stdout + r.stderr);
+ r = soma(['analyze', 'clearance']);
+ check('Abstand: Stift mit 0,2 mm Spalt kritisch, Störer überschneidet sich, Deckel liegt nur auf', r.status === 0
+ && /Stift: [^\n]*unter 0\.50 mm/.test(r.stdout) && /Störer: -[^\n]*Ueberschneidung/.test(r.stdout) && /Lid: [^\n]*nichts unter 0\.50 mm[^\n]*Beruehrung/.test(r.stdout),
+ r.stdout + r.stderr);
+ await domClick('btn-result');
+ await waitFor('Ergebnis geladen', () => window.__t.result().id !== null, 20000);
+ await ev(() => { const s = document.getElementById('result-select'); s.value = 'thickness'; s.dispatchEvent(new Event('change')); });
+ await waitFor('Wandstärke gewählt', () => window.__t.result().id === 'thickness', 10000);
+ let rs = await ev(() => window.__t.result());
+ vs = await ev(() => window.__t.viewer.animViewState());
+ check('Karte „Analyse“: drei Ergebnisse, Wandstärke je Bauteil, Lasche kritisch, Modell tritt zurück', rs.active && rs.options.length === 3
+ && rs.rows.some((x) => x.startsWith('Lasche') && x.includes('kritisch') && !x.includes('nichts')) && rs.rows.some((x) => x.startsWith('Body') && x.includes('nichts kritisch'))
+ && vs.modelHidden && !rs.stale, JSON.stringify(rs.rows));
+ await ev(() => window.__t.viewer.setView('front'));
+ await sleep(300);
+ const at = await ev(() => window.__t.viewer.screenAt([0, -40.5, 6]));
+ const pin = await ev((p) => window.__t.resultPin(p.x, p.y), at);
+ rs = await ev(() => window.__t.result());
+ check('Klick auf die Lasche: Wert 1 mm an der Stelle, „An Agent geben“ nennt ihn', pin?.name === 'Lasche' && near(pin.value, 1, 0.02)
+ && rs.note.startsWith('[Ergebnis: "Wandstärke" (.soma/results/thickness.glb, Grenzwert 1.20 mm), Bauteil "Lasche": 1.00 mm bei ('), JSON.stringify([pin, rs.note]));
+ await ev(() => window.__t.viewer.setView('iso'));
+ await shot('analyse-1');
+ r = soma(['render', '--result', 'thickness']);
+ check('soma render --result: Bild mit Farben und Legende', r.status === 0 && JSON.stringify(pngSize(path.join(dir, 'renders', 'ergebnis-thickness.png'))) === '[1280,800]', r.stderr);
+ // Code ändern: Ergebnis veraltet, „Neu berechnen“ wertet das neue Modell aus
+ fs.writeFileSync(path.join(dir, 'model.py'), MODEL(2.0));
+ await waitFor('neuer Build', () => window.__t.status().state === 'ok' && window.__t.result().stale === true, 60000).catch(() => {});
+ rs = await ev(() => window.__t.result());
+ check('Nach Codeänderung: Ergebnis als veraltet gekennzeichnet', rs.stale && rs.hint.startsWith('Älter als der Code'), rs.hint);
+ await domClick('btn-result-rerun');
+ await waitFor('neu berechnet', () => window.__t.result().stale === false, 90000).catch(() => {});
+ rs = await ev(() => window.__t.result());
+ check('„Neu berechnen“: Lasche jetzt 2 mm, nichts kritisch', !rs.stale && rs.rows.some((x) => x.startsWith('Lasche') && x.includes('nichts kritisch')), JSON.stringify(rs.rows));
+ await domClick('btn-result-close');
+ check('Analyse aus: Modell wieder sichtbar', !(await ev(() => window.__t.viewer.animViewState())).modelHidden);
+
+ // 11) Animationsdatei ändern: Der Watcher baut neu, die Dauer ändert sich
+ fs.writeFileSync(path.join(dir, 'animations', 'deckel.py'), DECKEL('a.wait(1)\n'));
+ await waitFor('Animation neu gebaut', () => window.soma.anim.list().then((x) => x.animations.some((a) => a.id === 'deckel-oeffnen' && Math.abs(a.duration - 9) < 1e-6)), 90000).catch(() => {});
+ e = (await list()).animations.find((a) => a.id === 'deckel-oeffnen');
+ check('Geänderte Animationsdatei: neu gebaut, jetzt 9 s', near(e.duration, 9) && !e.stale, JSON.stringify(e));
+
+ // 12) Das Beispiel im Skill läuft so, wie es dasteht (Modell mit HINGE_Y, HINGE_Z und einer Schublade)
+ const skill = fs.readFileSync(path.join(APP, 'resources', 'skills', 'animation.md'), 'utf8');
+ const block = /```python\r?\n([\s\S]*?)\r?\n```/.exec(skill)?.[1] ?? '';
+ fs.writeFileSync(path.join(dir, 'model.py'), `${MODEL()}HINGE_Y, HINGE_Z = D / 2, H
+drawer = cq.Workplane("XY").box(20, 30, 8, centered=(True, True, False)).translate((-35, 0, 2))
+add_part("Drawer", drawer)
+`);
+ await waitFor('Modell mit Schublade', () => window.__t.status().state === 'ok' && window.__t.partCount() === 8, 60000).catch(() => {});
+ fs.writeFileSync(path.join(dir, 'animations', 'skill.py'), block);
+ // Der Watcher baut die Datei, danach liest soma anim info sie (ein zweiter Bau gleichzeitig würde um die Dateien konkurrieren)
+ await waitFor('Beispiel gebaut', () => window.soma.anim.list().then((x) => !x.building && (x.animations.some((a) => a.name === 'Open the lid') || x.errors.length > 0)), 90000).catch(() => {});
+ l = await list();
+ r = soma(['anim', 'info', 'Open the lid']);
+ check('Beispiel aus dem Skill „Animation und Video“ baut ohne Fehler, Ablauf mit Titel, Gelenk und Schublade', !l.errors.length
+ && r.status === 0 && r.stdout.includes('Lid: 0 -> -110 Grad') && r.stdout.includes('Drawer: 0 -> 60 mm') && r.stdout.includes('Titel: Storage box'),
+ JSON.stringify(l.errors) + r.stdout.slice(0, 200) + 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/skills.mjs b/app/test/skills.mjs
index e9fd93f..38593cc 100644
--- a/app/test/skills.mjs
+++ b/app/test/skills.mjs
@@ -59,16 +59,16 @@ 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';
+ const DEMAND_NEW = '3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation';
// 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';
+ const ORDER = 'konstruktionsablauf,cadquery,3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,normteile,festigkeit,baugruppen,analyse,animation';
const heads = await ev(() => [...document.querySelectorAll('#skills-list .sk-cat')].map((h) => h.textContent).join(','));
- check('Panel „Skills": Überschriften Arbeitsweise, Fertigungsverfahren, Konstruktionswissen, darunter die Skills nach `order`',
- s.skills.map((x) => x.id).join(',') === ORDER && heads === 'Arbeitsweise,Fertigungsverfahren,Konstruktionswissen'
+ 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'
&& s.text.includes('3D-Druck (FDM)') && s.text.includes('Laserschneiden'), `${heads} | ${s.skills.map((x) => x.id).join(',')}`);
await shot('skills-1-panel');
@@ -90,7 +90,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 === 12
+ && (await g('ls-files', '.soma/skills')).split('\n').length === 14
&& (await ev(() => window.__t.saveState())).dirtyFiles === 0, `${String((await ev(() => window.__t.saveState())).dirtyFiles)} | ${String(block()).slice(0, 200)}`);
check('Umschalter: drei Stufen je Karte, die eingestellte gewählt', await ev(() => {
const row = document.querySelector('#skills-list .sk-row[data-id="3d-druck"]');
@@ -302,12 +302,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'
+ JSON.stringify(pj2.skills) === '["cadquery","3d-druck","normteile"]' && pj2.skills_on_demand.join(',') === 'konstruktionsablauf,harz-pulver,cnc,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation'
&& !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 === 11
+ check('Neues Modell: Skills im Startcommit, nichts ungespeichert', (await exec(['ls-files', '.soma/skills'], p2.dir)).stdout.trim().split('\n').length === 13
&& (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.mjs
index 1f74aab..e3c6486 100644
--- a/app/test/unit.mjs
+++ b/app/test/unit.mjs
@@ -195,14 +195,14 @@ try {
check('Skill-Kopf: Kategorie, Stufe „always“ (auch „on“), „off“, ohne Angabe Bei Bedarf, Anlass ohne Punkt', kp.category === 'Arbeitsweise' && kp.defaultMode === 'always'
&& kp.when === 'the user asks' && ps.category === '' && ps.defaultMode === 'demand' && ps.when === '' && modeOf('on') === 'always' && modeOf('off') === 'off' && modeOf('on-demand') === 'demand');
const cats = [...new Set(shipped.map((s) => s.category))];
- check('Mitgelieferte Skills: jeder mit Kategorie, drei Kategorien', shipped.every((s) => s.category) && cats.length === 3, cats.join(','));
+ check('Mitgelieferte Skills: jeder mit Kategorie, vier Kategorien', shipped.every((s) => s.category) && cats.length === 4, cats.join(','));
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', JSON.stringify(dm));
+ && dm.demand.join(',') === '3d-druck,harz-pulver,cnc,laser,blech,toleranzen,verbindungen,festigkeit,baugruppen,analyse,animation', 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', JSON.stringify(dm2));
+ && dm2.demand.join(',') === 'konstruktionsablauf,harz-pulver,cnc,blech,verbindungen,festigkeit,baugruppen,analyse,animation', JSON.stringify(dm2));
// Bei Bedarf (E55): Hinweis unter der ersten Überschrift, Werte als Standard der App, vom Nutzer gesetzte mit Namen
const 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:**')
@@ -214,6 +214,14 @@ try {
check('AGENTS.md: zwei Listen, Bei Bedarf mit Anlass, ohne Skills ein Satz', blk.indexOf('### Always follow') < blk.indexOf('- `.soma/skills/a.md`: A')
&& blk.indexOf('- `.soma/skills/a.md`: A') < blk.indexOf('### Read when relevant') && blk.includes('- `.soma/skills/b.md`: B. Read when parts move.')
&& !skillsBlock([{ id: 'b', name: 'B', when: '', mode: 'demand' }]).includes('Always follow') && skillsBlock([]).includes('No skills are switched on'), blk);
+
+ // Animationsdateien (E58): bauen die Animation neu, nicht das Modell
+ const ed = path.join(tmp, 'editable.mjs');
+ await build({ entryPoints: [path.join(APP, 'src', 'shared', 'editable.ts')], outfile: ed, bundle: true, platform: 'node', format: 'esm', logLevel: 'silent' });
+ const { affectsBuild, affectsAnimation } = await import(pathToFileURL(ed).href);
+ check('animations/*.py: Animation, kein Model-Build. model.py, parts/, inputs/ bauen das Modell', affectsAnimation('animations/deckel.py') && affectsAnimation('animations\\x.py')
+ && !affectsBuild('animations/deckel.py') && affectsBuild('model.py') && affectsBuild('parts/lid.py') && affectsBuild('inputs/a.step')
+ && !affectsAnimation('animations/sub/x.py') && !affectsAnimation('model.py') && !affectsAnimation('animations/notes.md'));
} catch (e) {
console.log('ABBRUCH:', e.message);
t.fail();