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: Render-Fenster mit Richtung, Ausblenden und Zoom, Hinweise für Agenten (E85)

Kai-Jungsthoefelcd3bb8b37936
diff --git a/app/README.md b/app/README.md
index f6cc563..8a88fc0 100644
--- a/app/README.md
+++ b/app/README.md
@@ -25,9 +25,9 @@ npm run test:section # Schnitt: X/Y/Z und an Fläche, Eingabe der Lage, Seite
npm run test:explode # Explosion: Demontage-Analyse (Richtung je Teil, Schrauben durch ihr Kernloch, Stift schräg aus seiner Bohrung, Baugruppe mit eingeschlossener Mutter, Elternteile), gleiche Lücke, Reihenfolge bei 100 %, Abspielen Schritt für Schritt, Reihenfolge an den Agenten, Auswahl in Einbaulage, Messen setzt zusammen, Schnitt dazu, neuer Build (39 Prüfungen)
npm run test:skills # Skills: Panel, Stufen Aus/Bei Bedarf/Immer (Kopie mit oder ohne Hinweis, project.json, zwei Listen in AGENTS.md), Einstellungen (Werte in der Kopie, Prüfung, Standard, vorab bei ausgeschaltetem Skill), Ansehen, Kopien im Dateibaum (Gruppe, nur lesen, Kopf als Quelltext), An Agent geben, Sicherung geänderter Kopien, fehlende Dateien und falsche Listen nur gemeldet, Snapshot und ZIP, Kategorien, Stufen für neue Modelle, Anleitung als Skill mit Bildern in .soma/help/, Hilfe-Fenster mit F1 (60 Prüfungen)
npm run test:fasteners # Normteile: Maße aus den Tabellen, Lage (at, direction, on, sunk), Bohrungen und Mutternfallen ohne Überschneidung, Einsätze, Fehlermeldungen, Rolle hardware, rotate/translate/moved, Codeblock des Skills „Normteile“, in der App Baum, Auswahl und export --all (37 Prüfungen)
-npm run test:drawing # Technische Zeichnungen (E76): Codeblock des Skills ohne Hinweise, Ansichten, Schnitt, Einzelheit, gemessene Maße, Kreise je Ansicht, DXF mit DIMENSION und Schraffur, bytegleich beim Neubau, Hinweise der Prüfung, Fehler mit Zeile, info und list, verwaiste PDF, kaputtes Modell, in der App PDF im Code-Panel und nichts ungespeichert (23 Prüfungen)
+npm run test:drawing # Technische Zeichnungen (E76): Codeblock des Skills ohne Hinweise, Ansichten, Schnitt, Einzelheit, gemessene Maße, Kreise je Ansicht, DXF mit DIMENSION und Schraffur, bytegleich beim Neubau, Hinweise der Prüfung, Fehler mit Zeile, info und list, verwaiste PDF, kaputtes Modell, in der App PDF im Code-Panel und nichts ungespeichert, Textbreite, Seite der Hinweislinie, Tabelle ohne Spaltenbreiten (37 Prüfungen)
npm run test:dxf # DXF-Ansicht (E80): soma dxfview mit Einheit, Größe, Layern, Kurven, Linientyp als Striche, Nicht-Zeichenbares, gleiche Ausgabe, kaputte Datei; in der App Öffnen per Klick im Dateibaum, Layer aus und ein (auch im Menü, ausgeschaltete aus der Datei), Zoom, Neuladen mit Ausschnitt, Mark up view mit Bereich, kaputte und gelöschte Datei (23 Prüfungen)
-npm run test:animation # Animation, Analyse, soma render und Video: Bauen über den Watcher, Ablauf als Text, Kollisionsprüfung, Fehler mit Ort, Abspielen im Viewer (Lage, Hervorhebung, Kamera), Ausschluss mit Explosion und Messen, Verbindung mit Schlüssel, Bild, Übersicht, MP4 mit WebVTT, Video abspielen und Standbild markieren, Überhang, Wandstärke, Abstand mit Anzeige und Neu berechnen, Beispiel des Skills, ohne App Grenzwert mit Netzgenauigkeit, Teil vor Gruppe, Problemstellen, bessere Druckrichtung, kurze Schritte als eine Zeile, Modell nur einmal ausgeführt (52 Prüfungen)
+npm run test:animation # Animation, Analyse, soma render und Video: Bauen über den Watcher, Ablauf als Text, Kollisionsprüfung, Fehler mit Ort, Abspielen im Viewer (Lage, Hervorhebung, Kamera), Ausschluss mit Explosion und Messen, Verbindung mit Schlüssel, Bild, Übersicht, MP4 mit WebVTT, Video abspielen und Standbild markieren, Überhang, Wandstärke, Abstand mit Anzeige und Neu berechnen, Beispiel des Skills, ohne App Grenzwert mit Netzgenauigkeit, Teil vor Gruppe, Problemstellen, bessere Druckrichtung, kurze Schritte als eine Zeile, Modell nur einmal ausgeführt soma render mit Richtung, Ausblenden, Einpassen und Zoom (65 Prüfungen)
npm run test:settings # Einstellungen (E81): Reiter, Mausbelegungen (SOMA, SolidWorks, Fusion, Onshape) mit Ziehen und Klick, Zoomrichtung, orthografisch (Bildgröße, Auswählen, verdeckte Kanten beim Messen), Nachkommastellen in der offenen Messung, Darstellung beim Öffnen, Speicherplatz und Vorschau-Cache leeren, About mit Versionen, Komponenten und Kopieren, Neustart, kaputte settings.json mit Sicherung (45 Prüfungen)
npm run test:packages # Projektumgebung: klein, pip im Terminal installiert dorthin, Basispakete vorhanden und in der Version festgelegt, requirements.txt aus den Importen des Builds, nicht in Git und ZIP, alter Stand mit eigener Liste, anderer Rechner installiert vor dem Build, Paket ohne Quelle als Hinweis (26 Prüfungen, ohne Netz mit lokalen Wheels)
npm run test:params # Parameter (E74): Panel aus der Leiste, Werte in parameters.json statt im Code, Zurücksetzen einzeln und alle, Komma, Bereich (rot, trotzdem gebaut), Schieber, Sprung in den Code, An Agent geben, Typen (Stepper, Schalter, Auswahl, Text), Gruppen, unpassende Werte und Werte ohne Parameter, gescheiterter Build mit „Back to“, Syntaxfehler vor den Parametern, kaputte Datei, Snapshot und ZIP, leerer Zustand, Bereich des Agenten in der Zeile, Auswertungen mit den Werten des Nutzers und veraltet nach einer Änderung (46 Prüfungen)
diff --git a/app/resources/skills/animation.md b/app/resources/skills/animation.md
index 6990629..78d94e9 100644
--- a/app/resources/skills/animation.md
+++ b/app/resources/skills/animation.md
@@ -34,7 +34,7 @@ a.wait(1)
- `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
+- `parts` is a name from `add_part`, a group (`"Housing"`, `"Housing/Screws"`), a part with its group (`"Housing/Lid"`) 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
@@ -45,6 +45,7 @@ a.wait(1)
- `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)`.
+ Wide motions (explosions) leave the parts small: give `fit` the parts that matter or a `zoom`.
- 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.
diff --git a/app/resources/skills/zeichnung.md b/app/resources/skills/zeichnung.md
index 6bc5c71..a9546ef 100644
--- a/app/resources/skills/zeichnung.md
+++ b/app/resources/skills/zeichnung.md
@@ -129,7 +129,7 @@ sh.text("Deburr all edges", (30, 30))
fitting dimensions.
- Item numbers with `view.leader(point_on_part, "1", at=..., end="dot")`, lined up in a row or column next to the
views and off the parts list, the same part always gets the same number.
-- Parts list with `sh.table(rows, at, widths)` on the title block: item, name, quantity, material or designation (for
+- Parts list with `sh.table(rows, at)` on the title block (columns as wide as their texts, or give `widths` in mm): item, name, quantity, material or designation (for
standard parts the designation of `soma.fasteners`, e.g. "ISO 4762 M5x16").
## Free drawing
@@ -141,6 +141,9 @@ sh.text("Deburr all edges", (30, 30))
symbols, datum triangles, a different title block.
- `sh.text(text, at, height=3.5, align=, rotation=)`. Several lines with `\n`: the first line at `at`, the others below,
leading spaces indent. Heights: 3.5 mm, view names 5 mm, never under 2.5 mm.
+- Place texts by measuring, not by trying: `sh.text_width(text, height)` is the width in mm before you build.
+ `leader(..., at=, side=)`: the text starts at `at` going right, or ends there with `side="left"`. Without `side`
+ it points away from the leader's point.
## Build and check
@@ -148,7 +151,7 @@ sh.text("Deburr all edges", (30, 30))
edges, on dimension, leader or cutting lines or on each other, things outside the frame or on the title block or a
table, texts too long for their cell or title block field, points on no edge, typed numbers that differ from the
model and uncommon scales. Fix them, or tell the user why one is fine.
-2. **Open the picture `.soma/drawings/<name>.png` and look at it.** It is large and gets scaled down when you open it:
+2. **Open the picture and look at it** (`.soma/drawings/<id>.png`, the build prints the path). It is large and gets scaled down when you open it:
crop parts of it (Pillow is installed) to read small texts and check every dimension and hatching.
3. `soma drawing info "Name"`: views with their place on the sheet, circles, every dimension with its value. Compare
with your plan: every feature dimensioned once, nothing crowded.
diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.md
index d3964bb..c37fedb 100644
--- a/app/resources/template/AGENTS.md
+++ b/app/resources/template/AGENTS.md
@@ -10,7 +10,7 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes
|---|---|
| `model.py` | Entry point. Builds the model and registers every part. Small models live only here |
| `parts/` | Optional. Move parts into modules here when `model.py` gets long, import them from `model.py` |
-| `inputs/` | Files the user brought (STEP, images). Never modify them, load them from `model.py` |
+| `inputs/` | Files the user brought (STEP, images, PDF). Never modify them, load them from `model.py`. Read PDFs with `pdfplumber` (text, lines and coordinates, `page.to_image()` for a picture) |
| `parameters.json` | Values the user set in the app's Parameters panel (rule 7). Written by the app |
| `output/model.step` | Main result with all parts, written by `soma build`. Never write it yourself |
| `exports/` | Single-part exports written by `soma export` |
@@ -27,7 +27,7 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes
3. Names are unique. Umlauts are fine, they are shown as written.
4. Group related parts with `group`: `add_part("Screw front", screw, group="Housing/Screws")` (nested with `/`). Groups show up in the part tree of the app and as sub-assemblies in `output/model.step`.
5. Mark a part the user brought (for example a circuit board) with `role="reference"`: it is shown semi-transparent and skipped by `soma export --all`. Cut clearances around it, but do not export it.
-6. Units are millimetres, Z is up. Put dimensions in named constants at the top of `model.py` so the user can ask for changes ("make the wall 3 mm"). Once parts live in `parts/`, the constants go to `parts/params.py`, and `model.py` and the part modules import them from there.
+6. Units are millimetres, Z is up, the front faces −Y (the front view looks from −Y), X points right. Put dimensions in named constants at the top of `model.py` so the user can ask for changes ("make the wall 3 mm"). Once parts live in `parts/`, the constants go to `parts/params.py`, and `model.py` and the part modules import them from there.
7. **Parameters for the user**: make the values the user would want to change themselves with `param()`: `BORE = param(38.0, "Cylinder bore", min=30, max=42, step=0.5, unit="mm", group="Crank train")`. They appear in the app's Parameters panel, where the user changes them without you. Good parameters are main dimensions, counts, options and positions (`CRANK = param(0, "Crank angle", min=0, max=360, unit="deg")`), usually 3 to 15 per model. Helper and derived values stay plain constants. Choose `min` and `max` so that the model builds and makes sense over the whole range. The default decides the field: `param(18, ...)` whole numbers, `param(True, ...)` a switch, `param("M3", ..., options=["M3", "M4"])` a choice. The user's values are kept in `parameters.json` and take the place of the defaults in the code, `soma build` lists them ("set by the user in the app"). So the number in the code is not always the one in the model. Do not edit `parameters.json` unless the user asks. If the user asks you for a new value of a parameter they set in the panel, change the default in the code and remove its entry from `parameters.json`, so that the code's value applies again.
8. Load user files with `import_step("inputs/board.step")`: this merges the whole file into one shape. If the file has several parts or sub-assemblies, keep them with `asm = import_assembly("inputs/board.step")` and `add_part("Board", asm, role="reference")`: every body becomes its own part with its name and color, the sub-assemblies become groups under "Board". Move an assembly with `asm.loc = cq.Location((x, y, z))`. STEP files often have their origin in a corner: check the bounding box and move the part deliberately.
9. Prefer simple, readable CadQuery. Check that operations produced solids. Do not use `show_object` or `cq_editor`.
@@ -41,7 +41,7 @@ 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/view-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 render` | Saves a picture of the current model to `renders/view-iso.png` (`--view top` or a direction `--view=1,-2,1`, `--hide`/`--only` parts or groups, `--fit` parts, `--zoom 2`, `--size 1280x800`, `--out`). **Open the picture and look at it** to check your work, also inside: hide what is in the way. Works only in the terminals of the app, it renders with the app's viewer |
| `soma analyze overhang` (or `thickness`, `clearance`) | Value at every spot of the surface with a summary per part. Details in the skill for analysis |
| `soma analyze fem analyses/x.py` | Stresses, safety and deflection under a load case described in `analyses/x.py`. Details in the skill for FEM |
| `soma anim build`, `soma anim info "Name"` | Animations from `animations/`. Details in the skill for animation |
diff --git a/app/src/main/projects.ts b/app/src/main/projects.ts
index 226f687..47d05f5 100644
--- a/app/src/main/projects.ts
+++ b/app/src/main/projects.ts
@@ -629,7 +629,7 @@ export class ProjectController {
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 ?? 'The animation could not be rebuilt.' };
}
- 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);
+ return this.render({ kind: 'video', size: [1280, 720], view: null, dir: null, hide: [], only: [], fit: [], zoom: 1, 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
index fae0b3f..c6a93db 100644
--- a/app/src/main/render.ts
+++ b/app/src/main/render.ts
@@ -13,6 +13,12 @@ export interface RenderRequest {
kind: 'still' | 'sheet' | 'video';
size: [number, number];
view: string | null;
+ /** Freie Blickrichtung statt `view`, Namen von Teilen oder Gruppen (aufgelöst im Render-Fenster), Zoom (1: eingepasst). */
+ dir: [number, number, number] | null;
+ hide: string[];
+ only: string[];
+ fit: string[];
+ zoom: number;
at: number;
grid: [number, number];
fps: number;
@@ -37,6 +43,17 @@ export function checkRequest(root: string, raw: unknown): RenderRequest | string
if (grid.length !== 2 || !grid.every((v) => Number.isInteger(v) && v >= 1 && v <= 6)) return 'Contact sheet: 1 to 6 columns and rows.';
const view = r.view == null ? null : String(r.view);
if (view && !VIEWS.includes(view)) return `Unknown view ${view}.`;
+ const dir = r.dir == null ? null : Array.isArray(r.dir) ? r.dir.map(Number) : [];
+ if (dir && (dir.length !== 3 || !dir.every(Number.isFinite) || Math.hypot(...dir) < 1e-9)) return 'The view direction needs three numbers, not all zero.';
+ const names = (v: unknown, what: string): string[] | Error => {
+ if (v == null) return [];
+ if (!Array.isArray(v) || v.length > 500 || !v.every((x) => typeof x === 'string' && x.trim() && x.length <= 300)) return new Error(`${what}: a list of part or group names.`);
+ return v as string[];
+ };
+ const hide = names(r.hide, 'Hide'), only = names(r.only, 'Only'), fit = names(r.fit, 'Fit');
+ for (const x of [hide, only, fit]) if (x instanceof Error) return x.message;
+ const zoom = r.zoom == null ? 1 : Number(r.zoom);
+ if (!Number.isFinite(zoom) || zoom < 0.05 || zoom > 50) return 'Zoom between 0.05 and 50.';
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 'Invalid time.';
@@ -58,7 +75,7 @@ export function checkRequest(root: string, raw: unknown): RenderRequest | string
if (!out.toLowerCase().endsWith(ext)) return `The target must end in ${ext}.`;
if (/^(\.git|\.soma)(\/|$)/i.test(out) || out.split('/').includes('..') || path.isAbsolute(out)) return 'The target must be in the project folder, not in .git/ or .soma/.';
try { resolveInside(root, out); } catch { return 'The target is not in the project folder.'; }
- return { kind, size: [size[0], size[1]], view, at, grid: [grid[0], grid[1]], fps, anim, result, out };
+ return { kind, size: [size[0], size[1]], view, dir: dir as [number, number, number] | null, hide: hide as string[], only: only as string[], fit: fit as string[], zoom, at, grid: [grid[0], grid[1]], fps, anim, result, out };
}
export class RenderService {
@@ -97,6 +114,7 @@ export class RenderService {
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,
+ dir: req.dir, hide: req.hide, only: req.only, fit: req.fit, zoom: req.zoom,
model, anim: req.anim ? read(req.anim) : null, result: req.result ? read(req.result) : null,
};
const win = await this.window();
diff --git a/app/src/renderer/render.ts b/app/src/renderer/render.ts
index 04b2c70..a45b2fd 100644
--- a/app/src/renderer/render.ts
+++ b/app/src/renderer/render.ts
@@ -1,5 +1,5 @@
import { BufferTarget, canEncodeVideo, CanvasSource, Mp4OutputFormat, Output, QUALITY_HIGH } from 'mediabunny';
-import type * as THREE from 'three';
+import * as THREE from 'three';
import type { RenderJob, RenderOutput, ResultMeta } from '../shared/types';
import { AnimData, fmtTime } from './animdata';
import { paintOverlay } from './overlay';
@@ -13,7 +13,34 @@ 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 }
+/** Kamera des Auftrags: Richtung, eingepasste Teile und Zoom. `forced`: gilt auch statt der Kamera einer Animation. */
+interface Look { dir: THREE.Vector3 | null; view: ViewName; fit: string[] | undefined; zoom: number; forced: boolean }
+interface Scene { anim: AnimData | null; legend: ResultMeta | null; ids: Map<string, string>; look: Look }
+
+/**
+ * Namen aus `--hide`, `--only` und `--fit` in Bauteil-IDs: Teilname, Gruppe ("Gehäuse", "Gehäuse/Schrauben", mit allem
+ * darunter) oder Teil mit Gruppe ("Gehäuse/Deckel"), wie in den Animationen. Unbekanntes ist ein Fehler mit den Namen.
+ */
+function resolveNames(specs: string[], what: string): string[] {
+ const parts = viewer.partList();
+ const out = new Set<string>();
+ for (const raw of specs) {
+ const spec = raw.trim().replace(/^\/+|\/+$/g, '');
+ let hit = parts.filter((p) => p.name === raw.trim());
+ if (!hit.length) hit = parts.filter((p) => p.group && (p.group === spec || p.group.startsWith(`${spec}/`)));
+ if (!hit.length) {
+ const i = spec.lastIndexOf('/');
+ if (i > 0) hit = parts.filter((p) => p.name === spec.slice(i + 1) && p.group === spec.slice(0, i));
+ }
+ if (!hit.length) {
+ const names = parts.slice(0, 30).map((p) => `'${p.name}'`).join(', ') + (parts.length > 30 ? ' ...' : '');
+ const groups = [...new Set(parts.flatMap((p) => (p.group ?? '').split('/').map((_, k, a) => a.slice(0, k + 1).join('/')).filter(Boolean)))].sort();
+ throw new Error(`${what} '${raw}' does not exist in the model. Parts: ${names}.${groups.length ? ` Groups: ${groups.map((g) => `'${g}'`).join(', ')}.` : ''}`);
+ }
+ for (const p of hit) out.add(p.id);
+ }
+ return [...out];
+}
async function prepare(job: RenderJob): Promise<Scene> {
results.hide();
@@ -28,7 +55,15 @@ async function prepare(job: RenderJob): Promise<Scene> {
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' };
+ // Ausblenden gilt zusätzlich zu dem, was eine Animation ausblendet. Eingepasst wird auf das Sichtbare
+ if (job.only.length) viewer.isolate(resolveNames(job.only, '--only'));
+ if (job.hide.length) viewer.setVisible(resolveNames(job.hide, '--hide'), false);
+ const fit = job.fit.length ? resolveNames(job.fit, '--fit') : undefined;
+ const look: Look = {
+ dir: job.dir ? new THREE.Vector3(...job.dir) : null, view: (job.view as ViewName | null) ?? 'iso', fit, zoom: job.zoom,
+ forced: !!job.view || !!job.dir || !!fit || job.zoom !== 1,
+ };
+ return { anim, legend, ids, look };
}
/** Stand zur Zeit t (ohne Animation: die gewählte Ansicht) und ein Bild davon. */
@@ -43,17 +78,24 @@ function frame(s: Scene, t: number, stamp: string | null, forceView: boolean): H
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);
+ if (forceView) place(s.look);
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);
+ } else place(s.look);
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();
}
+const VIEW_DIRS: Record<string, [number, number, number]> = {
+ iso: [0.8, -1.2, 0.9], front: [0, -1, 0], back: [0, 1, 0], top: [0, 0, 1], bottom: [0, 0, -1], right: [1, 0, 0], left: [-1, 0, 0],
+};
+function place(l: Look): void {
+ viewer.viewFrom(l.dir ?? new THREE.Vector3(...(VIEW_DIRS[l.view] ?? VIEW_DIRS.iso)), l.fit, l.zoom);
+}
+
function png(c: HTMLCanvasElement): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => c.toBlob((b) => (b ? b.arrayBuffer().then(resolve, reject) : reject(new Error('Could not create the PNG'))), 'image/png'));
}
@@ -74,7 +116,7 @@ async function sheet(s: Scene, job: RenderJob, cols: number, rows: number): Prom
g.fillText(`${anim.meta.name} · ${fmtTime(anim.duration)} · ${n} stills`, 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);
+ const img = frame(s, t, fmtTime(t), s.look.forced);
g.drawImage(img, gap + (i % cols) * (cw + gap), head + gap + Math.floor(i / cols) * (ch + gap), cw, ch);
}
return png(c);
@@ -99,7 +141,7 @@ async function video(s: Scene, job: RenderJob, progress: (f: number) => void): P
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);
+ g.drawImage(frame(s, t, null, s.look.forced), 0, 0);
await source.add(i / job.fps, 1 / job.fps);
if (i % 10 === 0) progress(i / n);
}
@@ -114,7 +156,7 @@ async function run(job: RenderJob): Promise<RenderOutput> {
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 };
+ return { ok: true, png: await png(frame(s, t, null, s.look.forced)), warnings };
}
if (!s.anim) return { ok: false, error: 'A contact sheet or video needs an animation.' };
if (job.kind === 'sheet') return { ok: true, png: await sheet(s, job, job.grid[0], job.grid[1]), warnings };
diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.ts
index ba03f3a..67a012f 100644
--- a/app/src/renderer/viewer.ts
+++ b/app/src/renderer/viewer.ts
@@ -531,17 +531,27 @@ export class Viewer {
}
setView(name: ViewName, ids?: string[]): void {
- const box = this.bounds(ids);
- if (box.isEmpty()) return;
- const center = box.getCenter(new THREE.Vector3());
- const radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 1);
- const dir = {
+ this.viewFrom({
iso: new THREE.Vector3(0.8, -1.2, 0.9), front: new THREE.Vector3(0, -1, 0), back: new THREE.Vector3(0, 1, 0),
top: new THREE.Vector3(0, -0.0001, 1), bottom: new THREE.Vector3(0, -0.0001, -1),
right: new THREE.Vector3(1, 0, 0), left: new THREE.Vector3(-1, 0, 0),
fit: this.camera.position.clone().sub(this.controls.target),
- }[name].clone().normalize();
- const dist = radius / Math.sin(THREE.MathUtils.degToRad(this.persp.fov / 2)) * 1.05;
+ }[name], ids);
+ }
+
+ /**
+ * Blick aus der Richtung `dir` (vom Modell zur Kamera) auf die Bauteile `ids` (ohne: alle sichtbaren), eingepasst.
+ * `zoom` größer 1 rückt näher. Für `soma render --view x,y,z --fit … --zoom …`.
+ */
+ viewFrom(dir0: THREE.Vector3, ids?: string[], zoom = 1): void {
+ const box = this.bounds(ids);
+ if (box.isEmpty() || dir0.lengthSq() < 1e-18) return;
+ const center = box.getCenter(new THREE.Vector3());
+ const radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 1);
+ // Genau von oben oder unten hätte die Kamera keine Richtung für „oben“: minimal kippen wie bei top und bottom
+ const dir = dir0.clone().normalize();
+ if (Math.abs(dir.z) > 0.99999) dir.set(0, -0.0001, Math.sign(dir.z)).normalize();
+ const dist = radius / Math.sin(THREE.MathUtils.degToRad(this.persp.fov / 2)) * 1.05 / Math.max(zoom, 0.01);
this.anim?.stop();
this.placeAt(center, dir, dist);
this.controls.update();
diff --git a/app/test/animation.mjs b/app/test/animation.mjs
index 5a0f03b..b4898ba 100644
--- a/app/test/animation.mjs
+++ b/app/test/animation.mjs
@@ -226,6 +226,17 @@ try {
&& 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);
+ // Freie Richtung, Ausblenden, nur zeigen, einpassen, Zoom: jedes Bild anders als das ohne Option
+ const look = (args, out) => { const res = soma(['render', '--size', '320x200', '--out', `renders/${out}.png`, ...args]); return { res, png: res.status === 0 ? fs.readFileSync(path.join(dir, 'renders', `${out}.png`)) : null }; };
+ const lPlain = look([], 'l-plain'), dirv = look(['--view=1,-2,1'], 'l-dir'), hid = look(['--hide', 'Body'], 'l-hide'),
+ only = look(['--only', 'Lid', '--fit', 'Lid'], 'l-only'), zoom = look(['--zoom', '3'], 'l-zoom');
+ const shots = [lPlain, dirv, hid, only, zoom];
+ check('soma render --view=x,y,z, --hide, --only mit --fit, --zoom: Bilder entstehen und unterscheiden sich', shots.every((x) => x.png)
+ && new Set(shots.map((x) => x.png.toString('base64'))).size === shots.length, shots.map((x) => x.res.stderr).join(' | ').slice(0, 300));
+ r = soma(['render', '--hide', 'Gibtsnicht']);
+ check('Unbekannter Name bei --hide: Fehler mit den Teilen', r.status === 1 && r.stderr.includes("'Gibtsnicht' does not exist") && r.stderr.includes("'Lid'"), r.stderr);
+ r = soma(['render', '--view', 'schraeg']);
+ check('Unbekannte Ansicht: Meldung nennt auch die Richtung x,y,z', r.status === 1 && r.stderr.includes('direction x,y,z'), 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']);
diff --git a/app/test/drawing.mjs b/app/test/drawing.mjs
index 6701e43..6016535 100644
--- a/app/test/drawing.mjs
+++ b/app/test/drawing.mjs
@@ -64,6 +64,11 @@ a = sh.section("Bracket", "front", path=[(-70, 17.5, 0), (-20, 17.5, 0), (-20, 0
at=(100, 110), letters_at=[(25, 225), (175, 225)])
sh.table([["1", "Bracket", "1"]], at=(230, 70), widths=[10, 40, 10])
top.leader((0, 0, 12), "1", at=(235, 65), end="dot")
+w = sh.text_width("Ra 3.2")
+assert 8 < w < 20 and sh.text_width("Ra 3.2\\nlonger second line") > 2 * w, w
+tb = sh.table([["Pos", "Name"], ["2", "Very long part name"]], at=(30, 50))
+assert abs((tb[2] - tb[0]) - (max(8, sh.text_width("Pos") + 4) + sh.text_width("Very long part name") + 4)) < 0.01, tb
+top.leader((20, -20, 12), "Ra 3.2", at=(200, 262), side="left")
`;
const BROKEN = `from soma.drawing import Sheet
@@ -129,6 +134,8 @@ try {
!fw.some((m) => /^([4-9]|1[0-2]): /.test(m)), fw.filter((m) => /^([4-9]|1[0-2]): /.test(m)).join(' | '));
check('Maße: Ø nicht doppelt ("Ø10 H7"), 80 bis zum Mittenkreuz, 120 über die Unterbrechung', ['"Ø10 H7"', '80', '120'].every((l) => fb?.dims.some((d) => d.label === l)),
fb?.dims.map((d) => d.label).join(' '));
+ check('text_width misst, Tabelle ohne widths passt sich den Texten an, Hinweislinie mit side="left": gebaut ohne Hinweise',
+ !!fb && !fw.some((m) => /^(1[6-9]|20): /.test(m)), fw.filter((m) => /^(1[6-9]|20): /.test(m)).join(' | ') || JSON.stringify(res?.errors)?.slice(0, 300));
const fbCheck = py(['-c', String.raw`
import json, sys, math, ezdxf
doc = ezdxf.readfile(sys.argv[1])
@@ -141,6 +148,7 @@ print(json.dumps(dict(
indent=any(t.startswith(" 1. Deburr") for t, _p in texts), mtext=len(msp.query("MTEXT")),
dimtext=[d.dxf.text for d in dia], ø=[e.plain_text() for e in mt], up=[round(e.dxf.insert.y - 200, 2) for e in mt],
letters=sorted(p for t, p in texts if t == "A"), label=[p for t, p in texts if t == "Shortened"],
+ ra=[p for t, p in texts if t == "Ra 3.2"],
breaks=len([p for p in msp.query("LWPOLYLINE[layer=='THIN']") if len(p) == 6]),
cut=[len(p) for p in msp.query("LWPOLYLINE[layer=='CUT']")], step=len(step))))
`, path.join(dir, 'output', 'drawings', 'Feedback.dxf')]);
@@ -149,6 +157,7 @@ print(json.dumps(dict(
check('Mehrzeiliger Text als Zeilen (kein MTEXT), Einrückung bleibt', fx?.indent === true && fx.mtext === 0, (fbCheck.stderr || fbCheck.stdout).slice(-200));
check('Durchmesser: "Ø<> H7" wird "Ø10 H7", der Text steht in Richtung angle=90 (über der Mitte)', fx?.dimtext?.[0] === '<> H7' && fx.ø[0] === 'Ø10 H7' && fx.up[0] > 5,
JSON.stringify(fx && { dimtext: fx.dimtext, ø: fx.ø, up: fx.up }));
+ check('Hinweislinie mit side="left": Text endet 1 mm vor at', JSON.stringify(fx?.ra) === '[[199,263]]', JSON.stringify(fx?.ra));
check('Buchstaben des Schnittverlaufs an letters_at, Titel an label_at', JSON.stringify(fx?.letters) === '[[25,225],[175,225]]' && JSON.stringify(fx?.label) === '[[300,255]]',
JSON.stringify(fx && { letters: fx.letters, label: fx.label }));
check('Stufenschnitt: Schnittverlauf mit 4 Punkten und zwei dicken Knicken, keine Kante an der Stufe; zwei Bruchlinien', JSON.stringify(fx?.cut) === '[4,3,3]' && fx.step === 0 && fx.breaks === 2,