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

soma: render mit Richtung, Ausblenden und Zoom, Zeichnungen messen Texte, pdfplumber (E85)

Kai-Jungsthoefel97120bc81a1d
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index fca143e..c194354 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -330,6 +330,8 @@ export interface ResultEntry extends ResultMeta { file: string; stale: boolean }
export interface RenderJob {
id: number; kind: 'still' | 'sheet' | 'video'; width: number; height: number;
view: string | null; at: number; grid: [number, number]; fps: number;
+ /** Freie Blickrichtung (vom Modell zur Kamera) statt `view`, Teile oder Gruppen ausblenden, nur zeigen, einpassen, Zoom. */
+ dir: [number, number, number] | null; hide: string[]; only: string[]; fit: string[]; zoom: number;
model: ArrayBuffer; anim: ArrayBuffer | null; result: ArrayBuffer | null;
}
/** Antwort des Render-Fensters. Video: MP4, Untertitel (WebVTT) und eine Übersicht als PNG. */
diff --git a/prototype/phase0/requirements-phase0.txt b/prototype/phase0/requirements-phase0.txt
index 1df8609..c706e06 100644
--- a/prototype/phase0/requirements-phase0.txt
+++ b/prototype/phase0/requirements-phase0.txt
@@ -6,7 +6,10 @@ cadquery==2.8.0
cadquery-ocp==7.9.3.1.1
cadquery-ocp-proxy==7.9.3.1.1
casadi==3.8.1
+cffi==2.1.1
+charset-normalizer==3.5.2
contourpy==1.4.0
+cryptography==50.0.2
cycler==0.12.1
ezdxf==1.4.4
fonttools==4.66.0
@@ -24,11 +27,15 @@ nlopt==2.11.0
numba==0.67.0
numpy==2.5.3
packaging==26.3
+pdfminer-six==20260107
+pdfplumber==0.11.10
pillow==12.3.0
pip==26.2.1
propcache==0.5.4
pyamg==5.3.0
+pycparser==3.11
pyparsing==3.3.3
+pypdfium2==5.14.0
python-dateutil==2.9.0.post0
pyyaml==6.0.3
runtype==0.5.3
diff --git a/python/soma/anim.py b/python/soma/anim.py
index b39d0ef..0414149 100644
--- a/python/soma/anim.py
+++ b/python/soma/anim.py
@@ -186,6 +186,11 @@ def _resolve(spec, what="Part"):
return [spec]
path = spec.strip("/")
hit = [p["name"] for p in parts if p["group"] and ("/".join(p["group"]) == path or "/".join(p["group"]).startswith(path + "/"))]
+ if hit:
+ return hit
+ # Teil mit Gruppenpfad davor ("Raum/Dachschräge"), so wie es im Strukturbaum steht
+ group, _, name = path.rpartition("/")
+ hit = [p["name"] for p in parts if group and p["name"] == name and "/".join(p["group"]) == group]
if hit:
return hit
names = ", ".join(repr(p["name"]) for p in parts[:30]) + (" ..." if len(parts) > 30 else "")
diff --git a/python/soma/cli.py b/python/soma/cli.py
index 55b3f75..650a76b 100644
--- a/python/soma/cli.py
+++ b/python/soma/cli.py
@@ -430,7 +430,12 @@ def main(argv=None):
z.set_defaults(func=cmd_analyze)
r = sub.add_parser("render", help="picture or video of the model (through the app), to renders/")
- r.add_argument("--view", help="iso, front, back, left, right, top, bottom (default iso, for animations their camera)")
+ r.add_argument("--view", help="iso, front, back, left, right, top, bottom or a direction x,y,z from the model to the camera "
+ "(--view=-1,0,0 with a leading minus; default iso, for animations their camera)")
+ r.add_argument("--hide", action="append", metavar="NAME", help="hide a part or group (\"Housing\", \"Housing/Lid\"), repeatable")
+ r.add_argument("--only", action="append", metavar="NAME", help="show only these parts or groups, repeatable")
+ r.add_argument("--fit", action="append", metavar="NAME", help="frame these parts or groups, repeatable (default: all visible)")
+ r.add_argument("--zoom", type=float, help="closer than framed (2 = twice as close), 0.05 to 50")
r.add_argument("--size", help="width x height in pixels, e.g. 1280x800")
r.add_argument("--anim", help="name of an animation")
r.add_argument("--at", type=float, help="moment in the animation (seconds)")
diff --git a/python/soma/drawing.py b/python/soma/drawing.py
index 7d714f8..6a3fdf2 100644
--- a/python/soma/drawing.py
+++ b/python/soma/drawing.py
@@ -998,17 +998,19 @@ class View:
self._refs.append(ln)
self.sheet._annotate([ln], ("center",), f"a center line (line {_where()[1]})")
- def leader(self, point, text, at, end="arrow", height=TEXT_HEIGHT):
+ def leader(self, point, text, at, end="arrow", height=TEXT_HEIGHT, side=None):
"""Leader from a model point to a text at the sheet point `at`. end: "arrow" (ends on an edge), "dot" (ends
- inside a surface) or "none". The text sits on a short horizontal line at `at`."""
- return self.sheet.leader(self.pt(point), text, at, end, height)
+ inside a surface) or "none". The text sits on a short horizontal line at `at`, on the side given by `side`
+ (see Sheet.leader)."""
+ return self.sheet.leader(self.pt(point), text, at, end, height, side)
# ---- Blatt ----------------------------------------------------------------------------------------------------------
class Sheet:
"""A drawing sheet with frame and title block (ISO 5457 and ISO 7200). Every Sheet(...) in drawings/*.py becomes
- output/drawings/<name>.pdf and .dxf plus a picture .soma/drawings/<name>.png. output/drawings.pdf holds all sheets
+ output/drawings/<id>.pdf and .dxf plus a picture .soma/drawings/<id>.png, <id> being the name in ASCII with "_"
+ for spaces ("Disc small" -> Disc_small; soma drawing build prints the paths). output/drawings.pdf holds all sheets
of the model in one file.
name unique name, also the file name
@@ -1479,17 +1481,47 @@ class Sheet:
what=_what or f"Text \"{_short(t)}\"", hint=_hint))
return out if len(lines) > 1 else (out[0] if out else None)
- def leader(self, point, text, at, end="arrow", height=TEXT_HEIGHT):
+ def text_width(self, text, height=TEXT_HEIGHT):
+ """Width in mm that `text` takes on the sheet at this height (the widest line for several lines), measured with
+ the font of the drawing. Use it to place texts, leaders and table columns before building."""
+ if not isinstance(text, str):
+ text = str(text)
+ h = float(height)
+ if not h > 0:
+ raise ValueError("height must be greater than 0")
+ width = 0.0
+ for t in text.expandtabs(4).split("\n"):
+ if t.strip():
+ width = max(width, self._measure(t, h))
+ return width
+
+ def _measure(self, t, h):
+ """Breite einer Textzeile: probeweise als TEXT anlegen, messen, wieder entfernen."""
+ e = self.msp.add_text(t, height=h, dxfattribs={"layer": "TEXT", "style": "ISO"})
+ try:
+ from ezdxf.tools.text_size import text_size
+ return float(text_size(e).width)
+ except Exception: # Schrift nicht messbar: ungefaehre Breite
+ return 0.6 * h * len(t)
+ finally:
+ self.msp.delete_entity(e)
+
+ def leader(self, point, text, at, end="arrow", height=TEXT_HEIGHT, side=None):
"""Leader from the sheet point `point` to a text at `at` (both in mm on the sheet). end: "arrow", "dot" or
- "none". View.leader() takes a model point instead. Several lines stack above the short horizontal line."""
+ "none". View.leader() takes a model point instead. Several lines stack above the short horizontal line.
+ side: "right" puts the text right of `at` (starting there), "left" left of it (ending there). Default: away
+ from `point`, so right when `at` is right of `point` (or straight above or below it), else left.
+ sh.text_width(text) tells how much room the text needs."""
p, a = _pt2(point, "point"), _pt2(at, "at")
if end not in ("arrow", "dot", "none"):
raise ValueError(f"end must be \"arrow\", \"dot\" or \"none\", not {end!r}")
+ if side not in (None, "left", "right"):
+ raise ValueError(f"side must be \"left\" or \"right\", not {side!r}")
if not isinstance(text, str):
text = str(text)
msp = self.msp
owner = self._new_owner("leader")
- left = a[0] < p[0]
+ left = side == "left" if side else a[0] < p[0]
up = (text.count("\n")) * LINE_SPACING * float(height) # die letzte Zeile steht auf der Linie
e = self.text(text, (a[0] - 1 if left else a[0] + 1, a[1] + 1 + up), height=height,
align="right" if left else "left", _owner=owner)
@@ -1515,11 +1547,23 @@ class Sheet:
h.set_solid_fill(color=256)
return e
- def table(self, rows, at, widths, row_height=7.0, text_height=TEXT_HEIGHT):
+ def table(self, rows, at, widths=None, row_height=7.0, text_height=TEXT_HEIGHT):
"""Table, e.g. a parts list: rows is a list of rows (lists of texts), at the top left corner on the sheet,
- widths the column widths in mm. Returns the bounding box (x0, y0, x1, y1). Nothing else may lie on it, and its
- texts must fit their cells (the check reports both)."""
+ widths the column widths in mm. Without widths, or with None for a column, the column gets as wide as its
+ longest text plus 4 mm (at least 8 mm). Returns the bounding box (x0, y0, x1, y1). Nothing else may lie on it,
+ and its texts must fit their cells (the check reports both)."""
x0, y_top = _pt2(at, "at")
+ rows = [list(r) for r in rows]
+ ncol = max((len(r) for r in rows), default=0)
+ if widths is None:
+ widths = [None] * ncol
+ widths = list(widths)
+ if len(widths) < ncol:
+ raise ValueError(f"{len(widths)} widths for {ncol} columns. Give one per column, None for automatic")
+ for i, w in enumerate(widths):
+ if w is None:
+ texts = [str(r[i]) for r in rows if i < len(r) and r[i] is not None and str(r[i]) != ""]
+ widths[i] = max([8.0] + [self.text_width(t, text_height) + 4.0 for t in texts])
widths = [float(w) for w in widths]
owner = self._new_owner("table")
file, line = _where()
diff --git a/python/soma/render.py b/python/soma/render.py
index 645bfba..d587270 100644
--- a/python/soma/render.py
+++ b/python/soma/render.py
@@ -61,9 +61,28 @@ def _num(t):
def prepare(root, args):
"""Auftrag fuer die App aus den Argumenten. Baut eine veraltete Animation vorher neu."""
root = Path(root).resolve()
- job = dict(project=str(root), view=args.view or None, warnings=[])
- if args.view and args.view not in VIEWS:
- raise RenderError(f"--view {args.view!r} does not exist. Possible: {', '.join(VIEWS)}")
+ job = dict(project=str(root), view=None, warnings=[])
+ view = (getattr(args, "view", None) or "").strip()
+ if view and view not in VIEWS:
+ try:
+ d = [float(x) for x in view.split(",")]
+ except ValueError:
+ d = []
+ if len(d) != 3 or not any(d):
+ raise RenderError(f"--view {view!r} does not exist. Possible: {', '.join(VIEWS)} or a direction x,y,z "
+ "from the model to the camera, e.g. 1,-2,1")
+ job["dir"] = d
+ elif view:
+ job["view"] = view
+ for key in ("hide", "only", "fit"):
+ names = [n for n in (getattr(args, key, None) or []) if n.strip()]
+ if names:
+ job[key] = names
+ zoom = getattr(args, "zoom", None)
+ if zoom is not None:
+ if not 0.05 <= zoom <= 50:
+ raise RenderError("--zoom between 0.05 and 50")
+ job["zoom"] = zoom
modes = [x for x in ("at", "sheet", "video") if getattr(args, x) not in (None, False)]
if modes and not args.anim:
raise RenderError(f"--{modes[0]} belongs to an animation: --anim \"Name\"")
@@ -112,7 +131,7 @@ def prepare(root, args):
else:
job["kind"] = "still"
job["size"] = _size(args.size, (1280, 800))
- name = f"result-{Path(job['result']).stem}" if args.result else f"view-{args.view or 'iso'}"
+ name = f"result-{Path(job['result']).stem}" if args.result else f"view-{job['view'] or ('custom' if 'dir' in job else 'iso')}"
job["out"] = _out(root, args.out, f"renders/{name}.png", ".png")
return job