Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice
TypeScript 3d-modeling3d-printing3d-printing-toolsagentagentic-aiai-cadcadcadqueryclaude-codecodexelectronfemllmmacdmakeropencodeparametric-designpythonsteptext-to-cad
soma: technische Zeichnungen mit soma drawing (E76)
Kai-Jungsthoefel77a01c96e0f7
diff --git a/python/soma/cli.py b/python/soma/cli.pyindex 056c79e..b2b3c38 100644--- a/python/soma/cli.py+++ b/python/soma/cli.py@@ -1,4 +1,4 @@-"""Command line: `soma build`, `soma export`, `soma anim`, `soma analyze` and `soma render`."""+"""Command line: `soma build`, `soma export`, `soma anim`, `soma drawing`, `soma analyze` and `soma render`."""import argparseimport jsonimport os@@ -237,6 +237,74 @@ def cmd_anim(args):return _fail(str(e))+def cmd_drawing(args):+ """Technische Zeichnungen in drawings/*.py (E76): bauen, auflisten, beschreiben."""+ from . import drawrun+ root = Path(args.project).resolve()+ try:+ if args.action == "build":+ target = None+ if args.name and args.name.endswith(".py"):+ target = root / args.name+ if not target.is_file():+ return _fail(f"{args.name} does not exist")+ res = drawrun.build_all(root, target, args.dpi)+ if args.json:+ print(json.dumps(dict(built=res["built"], errors=res["errors"], orphans=res["orphans"]), ensure_ascii=False))+ else:+ for b in res["built"]:+ print(f"Drawing ok: \"{b['name']}\" ({b['size']}, {b['scale']}, {len(b['views'])} view(s), "+ f"{len(b['dims'])} dimension(s)) from {b['file']}")+ print(f" {b['pdf']}, {b['dxf']}")+ print(f" Picture: {b['png']} ({b['png_size'][0]} x {b['png_size'][1]} px). Open it to check the "+ "drawing, crop it to read small text.")+ for w in b["warnings"]:+ print(" " + drawrun.warning_text(w))+ for e in res["errors"]:+ where = f"{e['file']}{':' + str(e['line']) if e.get('line') else ''}"+ print(f"Drawing ERROR ({where}): {e['message']}", file=sys.stderr)+ if e.get("traceback"):+ print(e["traceback"], file=sys.stderr)+ for p in res["orphans"]:+ print(f"Note: {p} belongs to no sheet anymore (renamed or removed). Delete it if it is not needed.")+ if not res["built"] and not res["errors"]:+ print(f"No drawings: create a file in {drawrun.DRAW_DIR}/ (from soma.drawing import Sheet).")+ if args.name and not args.name.endswith(".py") and not drawrun.find(root, args.name):+ return _fail(f"No drawing {args.name!r} found")+ return 1 if res["errors"] else 0+ idx = drawrun.read_index(root)+ if args.action == "list":+ rows = [dict(x, stale=drawrun.is_stale(root, x)) for x in idx.get("drawings", [])]+ if args.json:+ print(json.dumps(dict(drawings=rows, errors=idx.get("errors", [])), ensure_ascii=False))+ return 0+ for x in rows:+ print(f"\"{x['name']}\" {x['size']} {x['scale']} {x['pdf']} from {x['file']}"+ + (" (outdated, soma drawing build)" if x["stale"] else "")+ + (f" {len(x['warnings'])} warning(s)" if x["warnings"] else ""))+ for e in idx.get("errors", []):+ print(f"ERROR {e['file']}{':' + str(e['line']) if e.get('line') else ''}: {e['message']}")+ if not rows and not idx.get("errors"):+ print("No drawing built yet (soma drawing build).")+ return 0+ entries = idx.get("drawings", [])+ if not args.name and len(entries) != 1:+ return _fail("soma drawing info needs the name of the sheet" + (+ f": {', '.join(repr(x['name']) for x in entries)}" if entries else " (none built yet: soma drawing build)"))+ entry = drawrun.find(root, args.name) if args.name else entries[0]+ if entry is None:+ return _fail(f"No drawing {args.name!r} found (soma drawing list)")+ if args.json:+ print(json.dumps(entry, ensure_ascii=False))+ else:+ print(drawrun.info_text(entry))+ if drawrun.is_stale(root, entry):+ print("\nOutdated: the model or the drawing changed since (soma drawing build).")+ return 0+ except drawrun.DrawingError as e:+ return _fail(str(e))++def cmd_analyze(args):"""Auswertung mit einem Wert je Stelle der Oberflaeche (E58)."""from . import analysis@@ -328,6 +396,14 @@ def main(argv=None):a.add_argument("--json", action="store_true")a.set_defaults(func=cmd_anim)+ d = sub.add_parser("drawing", help="build, list and describe technical drawings from drawings/*.py (DXF, PDF, PNG)")+ d.add_argument("action", choices=["build", "list", "info"])+ d.add_argument("name", nargs="?", help="name of the sheet (for build also a file drawings/x.py)")+ d.add_argument("--dpi", type=int, default=200, help="build: resolution of the picture (default 200)")+ d.add_argument("--project", default=".")+ d.add_argument("--json", action="store_true")+ d.set_defaults(func=cmd_drawing)+z = sub.add_parser("analyze", help="analysis: overhang (3D printing), thickness (wall thickness), clearance (gap to other parts), fem (strength)")z.add_argument("kind", choices=["overhang", "thickness", "clearance", "fem", "list"])z.add_argument("study", nargs="?", help="fem: file with the load case, e.g. analyses/bracket.py")diff --git a/python/soma/drawing.py b/python/soma/drawing.pynew file mode 100644index 0000000..1b49b23--- /dev/null+++ b/python/soma/drawing.py@@ -0,0 +1,1119 @@+"""Technical drawings (E76): sheets with views, sections, details, dimensions and free drawing, written as DXF, PDF and+PNG by `soma drawing build`. The agent decides what goes where; soma projects the geometry, measures the values and+reports problems.++ from soma.drawing import Sheet++ sh = Sheet("Bracket", size="A3", scale="1:2", material="AlMg3", tolerance="ISO 2768-m")+ front = sh.view("Bracket", "front", at=(150, 180))+ top = sh.view("Bracket", "top", at=(150, 90))+ front.dim((-60, 0, 0), (60, 0, 0), offset=-12)+ sh.msp.add_line((20, 20), (60, 20), dxfattribs={"layer": "THIN"}) # anything else directly with ezdxf++Coordinates on the sheet are millimetres from the lower left corner of the paper. Points of the model stay in model+millimetres, every view converts them with view.pt().+"""+import datetime+import inspect+import math+import re+from pathlib import Path++import cadquery as cq+import ezdxf+import numpy as np+from ezdxf.enums import TextEntityAlignment+from OCP.BRepAdaptor import BRepAdaptor_Curve+from OCP.BRepAlgoAPI import BRepAlgoAPI_Common+from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform+from OCP.BRepLib import BRepLib+from OCP.BRepTools import BRepTools_WireExplorer+from OCP.GCPnts import GCPnts_QuasiUniformDeflection+from OCP.GeomAbs import GeomAbs_Circle, GeomAbs_Ellipse, GeomAbs_Line+from OCP.gp import gp_Ax2, gp_Ax3, gp_Dir, gp_Pnt, gp_Trsf, gp_Vec+from OCP.HLRAlgo import HLRAlgo_Projector+from OCP.HLRBRep import HLRBRep_Algo, HLRBRep_HLRToShape+from OCP.TopAbs import TopAbs_REVERSED++from . import registry++__all__ = ["Sheet", "View"]++SHEETS = [] # Blaetter des laufenden Zeichnungsskripts, drawrun.py sammelt sie ein+_PARTS = None # Bauteile aus dem Build (Liste wie registry.REGISTRY), gesetzt von drawrun.py++# Papierformate nach ISO 5457 als (kurze, lange) Seite+SIZES = {"A4": (210, 297), "A3": (297, 420), "A2": (420, 594), "A1": (594, 841), "A0": (841, 1189)}+# Bevorzugte Maßstäbe nach ISO 5455, andere meldet die Prüfung nur als Hinweis+ISO_SCALES = [50, 20, 10, 5, 2, 1, 1 / 2, 1 / 5, 1 / 10, 1 / 20, 1 / 50, 1 / 100, 1 / 200, 1 / 500, 1 / 1000]+# Blickrichtung (vom Teil zum Betrachter) und die Richtung im Modell, die auf dem Blatt nach oben zeigt. Wie in der App+# und in soma.anim: front schaut von -Y, left von -X. top hat +Y oben, bottom -Y (Projektionsmethode 1 und 3 gleich)+VIEWS = {+ "front": ((0, -1, 0), (0, 0, 1)), "back": ((0, 1, 0), (0, 0, 1)),+ "left": ((-1, 0, 0), (0, 0, 1)), "right": ((1, 0, 0), (0, 0, 1)),+ "top": ((0, 0, 1), (0, 1, 0)), "bottom": ((0, 0, -1), (0, -1, 0)),+ "iso": ((1, -1, 1), (0, 0, 1)),+}+STANDARD_VIEWS = ("front", "back", "left", "right", "top", "bottom")++# Linienbreiten in 1/100 mm nach ISO 128 (Liniengruppe 0.5)+THICK, MEDIUM, THIN = 50, 35, 25+LAYERS = {+ # Name: (Farbe, Breite, Linienart, Bedeutung)+ "VISIBLE": (7, THICK, "Continuous", "visible edges"),+ "HIDDEN": (8, THIN, "SOMA_HIDDEN", "hidden edges"),+ "TANGENT": (8, THIN, "Continuous", "tangent edges (fillets)"),+ "CENTER": (3, THIN, "SOMA_CENTER", "center lines and axes"),+ "PHANTOM": (8, THIN, "SOMA_PHANTOM", "adjacent parts, extreme positions"),+ "THIN": (7, THIN, "Continuous", "thin continuous lines (detail circles, leaders, notes)"),+ "HATCH": (8, THIN, "Continuous", "hatching of cut faces"),+ "CUT": (3, THIN, "SOMA_CENTER", "cutting planes"),+ "DIM": (5, THIN, "Continuous", "dimensions"),+ "TEXT": (7, MEDIUM, "Continuous", "texts and labels"),+ "FRAME": (7, 70, "Continuous", "frame"),+ "TITLE": (7, MEDIUM, "Continuous", "title block"),+}+LINETYPES = {+ # Muster in Blatt-mm: Strich positiv, Luecke negativ, erste Zahl die Gesamtlaenge+ "SOMA_HIDDEN": ([4.0, 3.0, -1.0], "Hidden __ __ __"),+ "SOMA_CENTER": ([13.5, 10.0, -1.5, 0.5, -1.5], "Center ____ . ____"),+ "SOMA_PHANTOM": ([15.5, 10.0, -1.5, 0.5, -1.5, 0.5, -1.5], "Phantom ____ . . ____"),+}+TEXT_HEIGHT = 3.5 # Maßzahlen und Texte (ISO 3098, mindestens 2.5)+LABEL_HEIGHT = 5.0 # Bezeichnungen von Ansichten, Schnitten, Einzelheiten+FONT = "DejaVuSans.ttf" # liegt matplotlib bei, damit die PDF auf jedem Rechner gleich aussieht++TITLE_LABELS = {+ "en": dict(owner="Owner", title="Title", drawn="Drawn by", date="Date", number="Drawing number", revision="Rev.",+ material="Material", tolerance="General tolerances", scale="Scale", size="Size", projection="Projection",+ sheet="Sheet"),+ "de": dict(owner="Firma", title="Benennung", drawn="Gezeichnet", date="Datum", number="Zeichnungsnummer",+ revision="Index", material="Werkstoff", tolerance="Allgemeintoleranzen", scale="Maßstab", size="Format",+ projection="Projektion", sheet="Blatt"),+}+++# ---- Hilfen ---------------------------------------------------------------------------------------------------------++def _where():+ """Datei und Zeile des Aufrufs im Zeichnungsskript: der erste Rahmen ausserhalb des soma-Pakets."""+ here = Path(__file__).resolve().parent+ f = inspect.currentframe()+ while f is not None:+ try:+ inside = Path(f.f_code.co_filename).resolve().parent == here+ except (OSError, ValueError):+ inside = False+ if not inside and not f.f_code.co_filename.startswith("<"):+ return f.f_code.co_filename, f.f_lineno+ f = f.f_back+ return None, None+++def _vec(v, what):+ try:+ t = tuple(float(x) for x in v)+ except (TypeError, ValueError):+ t = ()+ if len(t) != 3 or not all(math.isfinite(x) for x in t):+ raise ValueError(f"{what} must be a point or direction (x, y, z), not {v!r}")+ return np.array(t)+++def _pt2(v, what):+ try:+ t = tuple(float(x) for x in v)+ except (TypeError, ValueError):+ t = ()+ if len(t) != 2 or not all(math.isfinite(x) for x in t):+ raise ValueError(f"{what} must be a point on the sheet (x, y) in mm, not {v!r}")+ return np.array(t)+++def _unit(v, what):+ v = _vec(v, what)+ n = float(np.linalg.norm(v))+ if n < 1e-12:+ raise ValueError(f"{what} must not be zero")+ return v / n+++def parse_scale(s, what="scale"):+ """"1:2" -> 0.5, "5:1" -> 5, 0.5 -> 0.5."""+ if isinstance(s, str):+ m = re.fullmatch(r"\s*([0-9.]+)\s*:\s*([0-9.]+)\s*", s)+ if not m:+ raise ValueError(f"{what} must be like \"1:2\" or \"5:1\" or a number, not {s!r}")+ try:+ a, b = float(m.group(1)), float(m.group(2))+ except ValueError:+ raise ValueError(f"{what} must be like \"1:2\" or \"5:1\", not {s!r}") from None+ v = a / b if b else 0.0+ else:+ try:+ v = float(s)+ except (TypeError, ValueError):+ raise ValueError(f"{what} must be like \"1:2\" or a number, not {s!r}") from None+ if not (v > 0 and math.isfinite(v)):+ raise ValueError(f"{what} must be greater than 0, not {s!r}")+ return v+++def fmt_scale(v):+ """0.5 -> "1:2", 5 -> "5:1", 0.4 -> "1:2.5"."""+ return f"{num(v)}:1" if v >= 1 else f"1:{num(1 / v)}"+++def num(v, dec=2):+ """Zahl wie auf der Zeichnung: 120.00 -> "120", 12.50 -> "12.5", Punkt als Dezimalzeichen."""+ s = f"{v:.{dec}f}".rstrip("0").rstrip(".")+ return "0" if s in ("-0", "") else s+++def _layer(name):+ if name not in LAYERS:+ raise ValueError(f"Unknown layer {name!r}. Layers: {', '.join(LAYERS)}")+ return name+++# ---- Bauteile -------------------------------------------------------------------------------------------------------++def _parts():+ if _PARTS is None:+ raise RuntimeError("Drawings run through `soma drawing build` (there soma knows the parts of the model), "+ "not directly with python.")+ return _PARTS+++def _resolve(spec):+ """Was eine Ansicht zeigt -> Liste (Name oder None, cq.Shape). Bauteilname, Gruppe ("Housing" oder+ "Housing/Screws"), "*" fuer alle Bauteile ohne Referenzen, eine Liste davon, oder eine eigene CadQuery-Form."""+ if isinstance(spec, (cq.Workplane, cq.Shape)) or hasattr(spec, "__soma_shape__"):+ return [(None, registry.to_shape(spec))]+ parts = _parts()+ if isinstance(spec, (list, tuple, set)):+ out = []+ for s in spec:+ for item in _resolve(s):+ if item[0] is None or all(item[0] != o[0] for o in out):+ out.append(item)+ if not out:+ raise ValueError("The list of parts is empty")+ return out+ if spec is None or spec == "*":+ out = [(p["name"], p["shape"]) for p in parts if p["role"] != "reference"]+ if not out:+ raise ValueError("The model has no parts besides references")+ return out+ if not isinstance(spec, str) or not spec.strip():+ raise ValueError(f"Expected a part name, a group, \"*\", a list of them or a CadQuery shape, not {spec!r}")+ hit = [(p["name"], p["shape"]) for p in parts if p["name"] == spec]+ if hit:+ return hit+ path = spec.strip("/")+ hit = [(p["name"], p["shape"]) for p in parts+ if p["group"] and ("/".join(p["group"]) == path or "/".join(p["group"]).startswith(path + "/"))]+ if hit:+ return hit+ names = ", ".join(repr(p["name"]) for p in parts[:30]) + (" ..." if len(parts) > 30 else "")+ groups = sorted({"/".join(p["group"][:i + 1]) for p in parts for i in range(len(p["group"]))})+ extra = f" Groups: {', '.join(repr(g) for g in groups)}." if groups else ""+ raise ValueError(f"Part {spec!r} does not exist in the model. Parts: {names}.{extra}")+++def _bbox(shapes):+ bb = None+ for s in shapes:+ b = s.BoundingBox()+ bb = b if bb is None else bb.add(b)+ return bb+++# ---- Projektion -----------------------------------------------------------------------------------------------------++def _basis(direction, up):+ """Blickrichtung -> (N zum Betrachter, X nach rechts, Y nach oben auf dem Blatt)."""+ if isinstance(direction, str):+ if direction not in VIEWS:+ raise ValueError(f"direction must be one of {', '.join(VIEWS)} or a vector (x, y, z) from the part to the "+ f"viewer, not {direction!r}")+ n, default_up = VIEWS[direction]+ else:+ n, default_up = direction, None+ n = _unit(n, "direction")+ if up is None:+ up = default_up if default_up is not None else ((0, 0, 1) if abs(n[2]) < 0.999 else (0, 1, 0))+ u = _unit(up, "up")+ x = np.cross(u, n)+ if np.linalg.norm(x) < 1e-9:+ raise ValueError("up must not be parallel to the viewing direction")+ x = x / np.linalg.norm(x)+ return n, x, np.cross(n, x)+++def _hlr(shape, n, x, hidden, tangent):+ """Verdeckte Kanten mit HLR aus OCP. Liefert Kanten in Ansichtskoordinaten (u nach X, v nach Y, w = 0)."""+ algo = HLRBRep_Algo()+ algo.Add(shape.wrapped)+ algo.Projector(HLRAlgo_Projector(gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(*map(float, n)), gp_Dir(*map(float, x)))))+ algo.Update()+ algo.Hide()+ h = HLRBRep_HLRToShape(algo)++ def edges(*getters):+ out = []+ for g in getters:+ s = g()+ if not s.IsNull():+ # HLR liefert nur Kurven in der Ebene. Ohne 3D-Kurven stuerzen Boolesche Operationen (Einzelheiten) ab+ BRepLib.BuildCurves3d_s(s, 1e-6)+ out += [e.wrapped for e in cq.Shape.cast(s).Edges()]+ return out++ return dict(visible=edges(h.VCompound, h.OutLineVCompound),+ tangent=edges(h.Rg1LineVCompound) if tangent else [],+ hidden=edges(h.HCompound, h.OutLineHCompound) if hidden else [])+++def _to_local(shape, n, x, w0=0.0):+ """Form in Ansichtskoordinaten: u = p.X, v = p.Y, w = p.N - w0 (Schnittflaechen liegen dann bei w = 0)."""+ t = gp_Trsf()+ t.SetTransformation(gp_Ax3(gp_Pnt(0, 0, 0), gp_Dir(*map(float, n)), gp_Dir(*map(float, x))))+ s = BRepBuilderAPI_Transform(shape, t, True).Shape()+ if abs(w0) > 0:+ t2 = gp_Trsf()+ t2.SetTranslation(gp_Vec(0, 0, -w0))+ s = BRepBuilderAPI_Transform(s, t2, True).Shape()+ return s+++def _common(shape, disc):+ op = BRepAlgoAPI_Common(shape, disc)+ if not op.IsDone():+ return None+ return op.Shape()+++def _sample(edge, defl):+ """Punkte (u, v) entlang einer Kante in ihrer Richtung im Draht."""+ c = BRepAdaptor_Curve(edge)+ u1, u2 = c.FirstParameter(), c.LastParameter()+ if c.GetType() == GeomAbs_Line:+ pts = [c.Value(u1), c.Value(u2)]+ else:+ d = GCPnts_QuasiUniformDeflection(c, max(defl, 1e-4), u1, u2)+ if d.IsDone() and d.NbPoints() >= 2:+ pts = [d.Value(i) for i in range(1, d.NbPoints() + 1)]+ else:+ pts = [c.Value(u1 + (u2 - u1) * k / 48) for k in range(49)]+ arr = np.array([(p.X(), p.Y()) for p in pts], dtype=float)+ return arr[::-1] if edge.Orientation() == TopAbs_REVERSED else arr+++def _straight(pts, tol=1e-4):+ """Liegen die Punkte auf ihrer Sehne? HLR liefert gerade Kanten manchmal als B-Spline."""+ if len(pts) < 3:+ return True+ a, b = pts[0], pts[-1]+ d = b - a+ n = float(np.linalg.norm(d))+ if n < 1e-9:+ return False+ off = np.abs(d[0] * (pts[:, 1] - a[1]) - d[1] * (pts[:, 0] - a[0])) / n+ return float(off.max()) < tol+++def _loops(face, defl):+ """Aussen- und Innenraender einer ebenen Flaeche in Ansichtskoordinaten als geschlossene Punktfolgen."""+ out = []+ f = cq.Face(face)+ for wire in [f.outerWire()] + f.innerWires():+ pts = []+ ex = BRepTools_WireExplorer(wire.wrapped)+ while ex.More():+ e = ex.Current()+ s = _sample(e, defl)+ if e.Orientation() != ex.Orientation():+ s = s[::-1]+ pts.extend(s if not pts else s[1:])+ ex.Next()+ if len(pts) >= 3:+ out.append(np.array(pts))+ return out+++class _Geometry:+ """Projizierte Geometrie einer Ansicht in Ansichtskoordinaten (mm im Modell, unabhaengig vom Maßstab).+ Einzelheiten schneiden daraus nur einen Kreis aus, statt neu zu projizieren."""++ def __init__(self, n, x, y, edges, hatch, shapes, center):+ self.n, self.x, self.y = n, x, y+ self.edges = edges # {"visible": [TopoDS_Edge], "hidden": [...], "tangent": [...]}+ self.hatch = hatch # [(TopoDS_Face in Ansichtskoordinaten, Stil)]+ self.shapes = shapes # gezeigte Formen im Modell (fuer circles())+ self.center = center # Mitte der Begrenzung im Modell, Standard fuer origin++ def clip(self, cu, cv, r):+ disc = cq.Face.makeFromWires(cq.Wire.makeCircle(r, cq.Vector(cu, cv, 0), cq.Vector(0, 0, 1))).wrapped+ edges = {}+ for k, es in self.edges.items():+ if not es:+ edges[k] = []+ continue+ res = _common(cq.Compound.makeCompound([cq.Edge(e) for e in es]).wrapped, disc)+ edges[k] = [e.wrapped for e in cq.Shape.cast(res).Edges()] if res is not None and not res.IsNull() else []+ hatch = []+ for face, style in self.hatch:+ res = _common(face, disc)+ if res is not None and not res.IsNull():+ hatch += [(f.wrapped, style) for f in cq.Shape.cast(res).Faces()]+ return _Geometry(self.n, self.x, self.y, edges, hatch, self.shapes, self.center)+++def _project(items, n, x, y, hidden, tangent, region=None, unhatched=(), hatch=None):+ """items: [(Name, Form)]. region: Koerper, der weggeschnitten wird (Schnitt), sonst None."""+ shapes, faces = [], []+ styles = _hatch_styles(hatch, [nm for nm, _s in items if nm not in unhatched])+ k = 0+ for nm, s in items:+ if region is None or (nm is not None and nm in unhatched):+ shapes.append(s)+ continue+ cut = s.cut(region)+ if not cut.Solids() and not cut.Faces():+ continue # ganz im weggeschnittenen Bereich+ shapes.append(cut)+ style = styles[k] if nm not in unhatched else None+ k += 1+ if style is None:+ continue+ for f in cut.Faces():+ if f.geomType() != "PLANE":+ continue+ c = f.Center()+ nrm = f.normalAt(c)+ if float(np.dot((nrm.x, nrm.y, nrm.z), n)) < 1 - 1e-6:+ continue # nur Flaechen, die zum Betrachter zeigen+ if region.distance(cq.Vertex.makeVertex(c.x, c.y, c.z)) > 1e-6:+ continue # nicht durch den Schnitt entstanden+ w0 = float(np.dot((c.x, c.y, c.z), n))+ faces.append((_to_local(f.wrapped, n, x, w0), style))+ if not shapes:+ raise ValueError("Nothing left to show: the section removes everything")+ comp = shapes[0] if len(shapes) == 1 else cq.Compound.makeCompound(shapes)+ edges = _hlr(comp, n, x, hidden, tangent)+ bb = _bbox([s for _n, s in items])+ center = np.array([(bb.xmin + bb.xmax) / 2, (bb.ymin + bb.ymax) / 2, (bb.zmin + bb.zmax) / 2])+ return _Geometry(n, x, y, edges, faces, shapes, center)+++def _hatch_styles(hatch, names):+ """Schraffur je geschnittenem Teil: benachbarte Teile abwechselnd 45 und 135 Grad, ab dem dritten mit groesserem+ Abstand (ISO 128-50). hatch: None (so), dict(angle=, spacing=, pattern=) fuer alle, "solid" oder {Teil: ...}."""+ out = []+ for i, nm in enumerate(names):+ base = dict(pattern="ANSI31", angle=45 if i % 2 == 0 else 135, spacing=2.5 * (1 + 0.6 * ((i // 2) % 2)))+ h = hatch+ if isinstance(hatch, dict) and nm is not None and nm in hatch:+ h = hatch[nm]+ elif isinstance(hatch, dict) and not ({"angle", "spacing", "pattern"} & set(hatch)):+ h = None # Zuordnung je Teil, dieses Teil nicht genannt+ if h is False:+ out.append(None)+ elif h == "solid":+ out.append(dict(pattern="SOLID"))+ elif isinstance(h, dict):+ unknown = set(h) - {"angle", "spacing", "pattern"}+ if unknown:+ raise ValueError(f"hatch knows angle, spacing and pattern, not {', '.join(sorted(unknown))}")+ out.append({**base, **h})+ elif h is None:+ out.append(base)+ else:+ raise ValueError(f"hatch must be None, \"solid\", False, dict(angle=, spacing=, pattern=) or a dict per part, not {h!r}")+ return out+++# ---- Ansicht --------------------------------------------------------------------------------------------------------++class View:+ """One view on the sheet. Created with Sheet.view(), Sheet.section() or Sheet.detail(). Converts model points to+ the sheet (pt) and places dimensions, center lines and leaders at model points, the values come from the geometry."""++ def __init__(self, sheet, geo, kind, name, at, scale, origin, clip, layer, file, line):+ self.sheet, self._geo, self.kind, self.name = sheet, geo, kind, name+ self.phantom = layer == "PHANTOM"+ self.at, self.scale = np.array(at, dtype=float), scale+ self.origin = np.array(origin, dtype=float)+ self._o = np.array([float(np.dot(self.origin, geo.x)), float(np.dot(self.origin, geo.y))])+ self.clip = clip # (u, v, r) in Ansichtskoordinaten oder None+ self.file, self.line = file, line+ self._lines = [] # [(Punkte auf dem Blatt, "visible" | "hidden" | "tangent")] fuer die Pruefung+ self._emit(layer)+ pts = np.concatenate([p for p, _k in self._lines]) if self._lines else self.at.reshape(1, 2)+ self.bbox = (float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max()))++ # -- Umrechnung++ @property+ def direction(self):+ """Direction from the part to the viewer (unit vector in the model)."""+ return tuple(float(v) for v in self._geo.n)++ def pt(self, p):+ """Model point (x, y, z) -> point on the sheet (x, y) in mm."""+ p = _vec(p, "point")+ u, v = float(np.dot(p, self._geo.x)), float(np.dot(p, self._geo.y))+ return (float(self.at[0] + self.scale * (u - self._o[0])), float(self.at[1] + self.scale * (v - self._o[1])))++ def _uv(self, u, v):+ return (self.at[0] + self.scale * (u - self._o[0]), self.at[1] + self.scale * (v - self._o[1]))++ def _sheet_pts(self, arr):+ return np.column_stack([self.at[0] + self.scale * (arr[:, 0] - self._o[0]),+ self.at[1] + self.scale * (arr[:, 1] - self._o[1])])++ # -- Geometrie zeichnen++ def _emit(self, layer):+ msp = self.sheet.msp+ defl = 0.01 / self.scale # 0.01 mm auf dem Blatt+ for face, style in self._geo.hatch:+ loops = _loops(face, defl)+ if not loops:+ continue+ h = msp.add_hatch(color=256, dxfattribs={"layer": "HATCH"})+ for lp in loops:+ h.paths.add_polyline_path([tuple(p) for p in self._sheet_pts(lp)], is_closed=True)+ if style["pattern"] == "SOLID":+ h.set_solid_fill(color=256)+ else:+ # ANSI31 hat 3.175 mm Abstand bei 45 Grad+ h.set_pattern_fill(style["pattern"], color=256, scale=style["spacing"] / 3.175, angle=style["angle"] - 45)+ layers = {"visible": layer or "VISIBLE", "hidden": "HIDDEN", "tangent": "TANGENT"}+ for kind, edges in self._geo.edges.items():+ for e in edges:+ pts = self._edge(msp, e, layers[kind], defl)+ if pts is not None:+ self._lines.append((pts, kind))++ def _edge(self, msp, e, layer, defl):+ """Eine projizierte Kante als LINE, ARC, CIRCLE, ELLIPSE oder LWPOLYLINE. Liefert die Punkte auf dem Blatt."""+ c = BRepAdaptor_Curve(e)+ u1, u2 = c.FirstParameter(), c.LastParameter()+ if not (math.isfinite(u1) and math.isfinite(u2)) or abs(u2 - u1) < 1e-12:+ return None+ t = c.GetType()+ s = self.scale+ att = {"layer": layer}+ if t == GeomAbs_Circle:+ circ = c.Circle()+ ctr, r = circ.Location(), circ.Radius()+ cx, cy = self._uv(ctr.X(), ctr.Y())+ if abs(u2 - u1 - 2 * math.pi) < 1e-9:+ msp.add_circle((cx, cy), r * s, dxfattribs=att)+ else:+ a1 = math.degrees(math.atan2(c.Value(u1).Y() - ctr.Y(), c.Value(u1).X() - ctr.X()))+ a2 = math.degrees(math.atan2(c.Value(u2).Y() - ctr.Y(), c.Value(u2).X() - ctr.X()))+ if circ.Axis().Direction().Z() < 0:+ a1, a2 = a2, a1+ msp.add_arc((cx, cy), r * s, a1, a2, dxfattribs=att)+ return self._sheet_pts(_sample(e, defl))+ if t == GeomAbs_Ellipse:+ el = c.Ellipse()+ ctr, xd = el.Location(), el.XAxis().Direction()+ cx, cy = self._uv(ctr.X(), ctr.Y())+ a, b = el.MajorRadius(), el.MinorRadius()+ if a > 1e-12:+ if el.Axis().Direction().Z() < 0:+ p1, p2 = -u2, -u1+ else:+ p1, p2 = u1, u2+ full = abs(u2 - u1 - 2 * math.pi) < 1e-9+ msp.add_ellipse((cx, cy), (xd.X() * a * s, xd.Y() * a * s, 0), min(1.0, b / a),+ 0 if full else p1, 2 * math.pi if full else p2, dxfattribs=att)+ return self._sheet_pts(_sample(e, defl))+ pts = _sample(e, defl)+ sp = self._sheet_pts(pts)+ if t == GeomAbs_Line or _straight(sp):+ msp.add_line(tuple(sp[0]), tuple(sp[-1]), dxfattribs=att)+ return sp[[0, -1]]+ msp.add_lwpolyline([tuple(p) for p in sp], dxfattribs=att)+ return sp++ # -- Abfragen++ def circles(self, diameter=None, arcs=False):+ """Circles of the shown geometry seen as circles in this view (axis along the viewing direction): holes,+ pins, round outlines. Returns [(center (x, y, z), radius)], each center and radius once. diameter= filters,+ arcs=True also returns arcs (rounded corners, fillets seen end-on)."""+ return [(c, r) for c, r, full in self._circles(diameter) if full or arcs]++ def _circles(self, diameter=None):+ seen, out = {}, []+ n = self._geo.n+ for s in self._geo.shapes:+ for e in s.Edges():+ if e.geomType() != "CIRCLE":+ continue+ ad = BRepAdaptor_Curve(e.wrapped)+ full = abs(ad.LastParameter() - ad.FirstParameter() - 2 * math.pi) < 1e-6+ c = ad.Circle()+ ax = c.Axis().Direction()+ if abs(abs(ax.X() * n[0] + ax.Y() * n[1] + ax.Z() * n[2]) - 1) > 1e-6:+ continue+ p = np.array([c.Location().X(), c.Location().Y(), c.Location().Z()])+ r = c.Radius()+ if diameter is not None and abs(2 * r - float(diameter)) > 1e-6:+ continue+ u, v = float(np.dot(p, self._geo.x)), float(np.dot(p, self._geo.y))+ if self.clip and math.hypot(u - self.clip[0], v - self.clip[1]) > self.clip[2] + 1e-9:+ continue+ key = (round(u, 4), round(v, 4), round(r, 4), full)+ item = (tuple(round(float(x), 6) + 0.0 for x in p), round(r, 6), full)+ # Gleiche Mitte in der Ansicht (Ober- und Unterkante einer Bohrung): die Lage naeher am Betrachter+ if key in seen:+ i = seen[key]+ if float(np.dot(p, n)) > float(np.dot(out[i][0], n)) + 1e-9:+ out[i] = item+ continue+ seen[key] = len(out)+ out.append(item)+ # Ein Vollkreis verdeckt Boegen mit gleicher Mitte und gleichem Radius (Bohrung, die eine Fase anschneidet)+ fulls = {(round(float(np.dot(c, self._geo.x)), 4), round(float(np.dot(c, self._geo.y)), 4), round(r, 4))+ for c, r, f in out if f}+ out = [(c, r, f) for c, r, f in out if f or (round(float(np.dot(c, self._geo.x)), 4),+ round(float(np.dot(c, self._geo.y)), 4), round(r, 4)) not in fulls]+ return sorted(out, key=lambda c: (not c[2], -c[1], c[0]))++ # -- Maße++ def dim(self, p1, p2, offset=10, direction=None, text=None, tol=None, text_at=None):+ """Linear dimension between two model points; the value is measured, not typed.++ offset distance in mm on the sheet from the outer point to the dimension line. Positive: above (horizontal)+ or right (vertical), negative: below or left. For "aligned": positive is left of p1 -> p2+ direction "h" horizontal, "v" vertical or "aligned" on the sheet. Default: "h" if the points are further+ apart horizontally than vertically, else "v"+ text None: the measured value. "<>" stands for it, e.g. "Ø<> H7", "<> ±0.1", "2x <>"+ tol 0.1 for ±0.1 or (0.1, -0.05) for +0.1/-0.05 in small text after the value+ text_at optional point on the sheet for the text instead of the middle"""+ file, line = _where()+ a, b = np.array(self.pt(p1)), np.array(self.pt(p2))+ d = b - a+ if direction is None:+ direction = "h" if abs(d[0]) >= abs(d[1]) else "v"+ offset = float(offset)+ msp = self.sheet.msp+ if direction == "h":+ y = (max(a[1], b[1]) + offset) if offset >= 0 else (min(a[1], b[1]) + offset)+ dim = msp.add_linear_dim(base=((a[0] + b[0]) / 2, y), p1=tuple(a), p2=tuple(b), angle=0, **self._dimargs(text))+ measured = abs(d[0]) / self.scale+ elif direction == "v":+ x = (max(a[0], b[0]) + offset) if offset >= 0 else (min(a[0], b[0]) + offset)+ dim = msp.add_linear_dim(base=(x, (a[1] + b[1]) / 2), p1=tuple(a), p2=tuple(b), angle=90, **self._dimargs(text))+ measured = abs(d[1]) / self.scale+ elif direction == "aligned":+ if np.linalg.norm(d) < 1e-9:+ raise ValueError("The two points coincide in this view")+ dim = msp.add_aligned_dim(p1=tuple(a), p2=tuple(b), distance=offset, **self._dimargs(text))+ measured = float(np.linalg.norm(d)) / self.scale+ else:+ raise ValueError(f"direction must be \"h\", \"v\" or \"aligned\", not {direction!r}")+ return self._finish(dim, "linear", measured, text, tol, text_at, [p1, p2], file, line)++ def diameter(self, center, radius, angle=45, text=None, tol=None, text_at=None):+ """Diameter dimension of a circle seen as a circle in this view (center in the model, radius in mm).+ angle: direction of the dimension line on the sheet in degrees. Ø is added automatically."""+ file, line = _where()+ r = float(radius)+ dim = self.sheet.msp.add_diameter_dim(center=self.pt(center), radius=r * self.scale, angle=float(angle),+ **self._dimargs(text))+ return self._finish(dim, "diameter", 2 * r, text, tol, text_at, [center], file, line, radius=r)++ def radius(self, center, radius, angle=45, text=None, tol=None, text_at=None):+ """Radius dimension of an arc seen as an arc in this view. R is added automatically."""+ file, line = _where()+ r = float(radius)+ dim = self.sheet.msp.add_radius_dim(center=self.pt(center), radius=r * self.scale, angle=float(angle),+ **self._dimargs(text))+ return self._finish(dim, "radius", r, text, tol, text_at, [center], file, line, radius=r)++ def angle(self, vertex, p1, p2, distance=15, text=None, text_at=None):+ """Angle between the lines vertex -> p1 and vertex -> p2 (model points), the arc at distance mm on the sheet+ from the vertex. The value is the angle on the sheet: use it in views where both lines lie in the paper."""+ file, line = _where()+ c, a, b = (np.array(self.pt(p)) for p in (vertex, p1, p2))+ da, db = a - c, b - c+ if np.linalg.norm(da) < 1e-9 or np.linalg.norm(db) < 1e-9:+ raise ValueError("p1 and p2 must differ from the vertex in this view")+ mid = da / np.linalg.norm(da) + db / np.linalg.norm(db)+ mid = mid / np.linalg.norm(mid) if np.linalg.norm(mid) > 1e-9 else np.array([-da[1], da[0]]) / np.linalg.norm(da)+ base = c + mid * float(distance)+ dim = self.sheet.msp.add_angular_dim_3p(base=tuple(base), center=tuple(c), p1=tuple(a), p2=tuple(b),+ **self._dimargs(text))+ cosv = float(np.dot(da, db) / (np.linalg.norm(da) * np.linalg.norm(db)))+ measured = math.degrees(math.acos(max(-1.0, min(1.0, cosv))))+ return self._finish(dim, "angle", measured, text, None, text_at, [vertex, p1, p2], file, line)++ def _dimargs(self, text):+ if text is not None and not isinstance(text, str):+ raise ValueError(f"text must be a text like \"Ø<> H7\", not {text!r}")+ return dict(text="<>" if text is None else text, dimstyle="ISO",+ override={"dimlfac": 1.0 / self.scale}, dxfattribs={"layer": "DIM"})++ def _finish(self, dim, kind, measured, text, tol, text_at, points, file, line, radius=None):+ if tol is not None:+ if isinstance(tol, (int, float)):+ dim.set_tolerance(abs(float(tol)))+ else:+ try:+ up, lo = (float(v) for v in tol)+ except (TypeError, ValueError):+ raise ValueError(f"tol must be 0.1 (for ±0.1) or (upper, lower) like (0.1, -0.05), not {tol!r}") from None+ dim.set_tolerance(up, -lo)+ if text_at is not None:+ dim.set_location(tuple(_pt2(text_at, "text_at")), leader=False)+ dim.render()+ rec = dict(kind=kind, value=measured, text=text, view=self, points=[tuple(_vec(p, "point")) for p in points],+ radius=radius, entity=dim.dimension, file=file, line=line)+ self.sheet._dims.append(rec)+ return dim.dimension++ # -- Mittellinien, Hinweise++ def center_mark(self, center, radius, extend=2.5):+ """Center lines across a circle seen in this view (center in the model, radius in mm), extend mm beyond it.+ Small circles (under 5 mm on the sheet) get thin continuous lines as in ISO 128."""+ cx, cy = self.pt(center)+ r = float(radius) * self.scale + float(extend)+ layer = "CENTER" if float(radius) * self.scale >= 2.5 else "THIN"+ msp = self.sheet.msp+ msp.add_line((cx - r, cy), (cx + r, cy), dxfattribs={"layer": layer})+ msp.add_line((cx, cy - r), (cx, cy + r), dxfattribs={"layer": layer})++ def center_marks(self, diameter=None, extend=2.5):+ """center_mark() for every circle of circles(diameter)."""+ for c, r in self.circles(diameter):+ self.center_mark(c, r, extend)++ def centerline(self, p1, p2, extend=2.5):+ """Axis or symmetry line from model point p1 to p2, extend mm beyond both ends on the sheet."""+ a, b = np.array(self.pt(p1)), np.array(self.pt(p2))+ d = b - a+ n = float(np.linalg.norm(d))+ if n < 1e-9:+ raise ValueError("The two points of the center line coincide in this view")+ d = d / n * float(extend)+ self.sheet.msp.add_line(tuple(a - d), tuple(b + d), dxfattribs={"layer": "CENTER"})++ def leader(self, point, text, at, end="arrow", height=TEXT_HEIGHT):+ """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)+++# ---- 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.++ name unique name, also the file name+ size "A4" (portrait), "A3", "A2", "A1", "A0" (landscape) or (width, height) in mm+ scale scale of the views unless a view sets its own: "1:2", "2:1", 1+ landscape True/False to override the orientation of a standard size+ title, number, material, author, date, tolerance, owner, revision, sheet+ fields of the title block. date: default today. tolerance e.g. "ISO 2768-m"+ projection "first" (ISO, Europe) or "third" (ASME): symbol in the title block, None without+ language "en" or "de" for the captions of the title block+ titleblock False: no title block (draw your own), frame: False: no frame++ The ezdxf document is sh.doc, its model space sh.msp: everything not covered here can be drawn directly in sheet+ coordinates (mm). Layers: VISIBLE, HIDDEN, TANGENT, CENTER, PHANTOM, THIN, HATCH, CUT, DIM, TEXT, FRAME, TITLE.+ Dimension style "ISO", text style "ISO"."""++ def __init__(self, name, size="A3", scale=1, *, landscape=None, title=None, number=None, material=None,+ author=None, date=None, tolerance=None, owner=None, revision=None, sheet="1/1", projection="first",+ language="en", titleblock=True, frame=True):+ self.file, self.line = _where()+ if not isinstance(name, str) or not name.strip():+ raise ValueError("The sheet needs a name, e.g. Sheet(\"Bracket\")")+ self.name = name.strip()+ self.id = registry.ascii_name(self.name)+ if any(s.id == self.id for s in SHEETS):+ raise ValueError(f"There is already a sheet named {name!r} (names must be unique, also as file names)")+ if isinstance(size, str):+ key = size.strip().upper()+ if key not in SIZES:+ raise ValueError(f"size must be one of {', '.join(SIZES)} or (width, height) in mm, not {size!r}")+ short, long_ = SIZES[key]+ land = (key != "A4") if landscape is None else bool(landscape)+ self.width, self.height = (long_, short) if land else (short, long_)+ self.size = key+ else:+ w, h = _pt2(size, "size")+ if w < 50 or h < 50 or w > 5000 or h > 5000:+ raise ValueError(f"size must be between 50 and 5000 mm, not {size!r}")+ self.width, self.height = float(w), float(h)+ self.size = f"{num(w)} x {num(h)}"+ self.scale = parse_scale(scale)+ if projection not in ("first", "third", None):+ raise ValueError(f"projection must be \"first\", \"third\" or None, not {projection!r}")+ if language not in TITLE_LABELS:+ raise ValueError(f"language must be one of {', '.join(TITLE_LABELS)}, not {language!r}")+ self.projection = projection+ self._dims, self.views, self._labels = [], [], []+ self._new_doc()+ left = 20.0 if frame else 0.0+ m = 10.0 if frame else 0.0+ # Zeichenflaeche innerhalb des Rahmens (ISO 5457: links 20 mm Heftrand, sonst 10 mm)+ self.area = (left, m, self.width - m, self.height - m)+ if frame:+ self._frame(titleblock)+ self.titleblock = None+ if titleblock:+ fields = dict(owner=owner, title=self.name if title is None else title, drawn=author,+ date=datetime.date.today().isoformat() if date is None else date, number=number,+ revision=revision, material=material, tolerance=tolerance, scale=fmt_scale(self.scale),+ size=self.size, sheet=sheet)+ self.titleblock = self._title_block(fields, TITLE_LABELS[language])+ SHEETS.append(self)++ # -- Dokument++ def _new_doc(self):+ # Feste Kennung "erstellt von ezdxf" statt Uhrzeit: gleiche Zeichnung, gleiche Datei (siehe drawrun.save_dxf)+ old = ezdxf.options.write_fixed_meta_data_for_testing+ ezdxf.options.write_fixed_meta_data_for_testing = True+ try:+ doc = ezdxf.new("R2018", units=4)+ finally:+ ezdxf.options.write_fixed_meta_data_for_testing = old+ doc.header["$MEASUREMENT"] = 1+ doc.header["$LWDISPLAY"] = 1+ doc.header["$LTSCALE"] = 1.0+ for nm, (pattern, desc) in LINETYPES.items():+ doc.linetypes.add(nm, pattern=pattern, description=desc)+ for nm, (color, lw, lt, desc) in LAYERS.items():+ layer = doc.layers.add(nm, color=color, lineweight=lw, linetype=lt)+ layer.description = desc+ doc.styles.add("ISO", font=FONT)+ ds = doc.dimstyles.new("ISO")+ for k, v in dict(dimtxsty="ISO", dimtxt=TEXT_HEIGHT, dimasz=3.0, dimexe=2.0, dimexo=0.0, dimgap=1.0, dimtad=1,+ dimtih=0, dimtoh=0, dimdec=2, dimzin=8, dimtzin=8, dimtdec=2, dimadec=1, dimazin=2,+ dimdsep=ord("."), dimclrd=256,+ dimclre=256, dimclrt=256, dimlwd=-1, dimlwe=-1, dimtfac=0.7).items():+ ds.set_dxf_attrib(k, v)+ doc.header["$DIMSTYLE"] = "ISO"+ self.doc, self.msp = doc, doc.modelspace()++ def _frame(self, titleblock):+ x0, y0, x1, y1 = self.area+ msp = self.msp+ msp.add_lwpolyline([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], close=True, dxfattribs={"layer": "FRAME"})+ # Mittenmarken von der Blattkante bis 5 mm in den Rahmen, unten nicht ins Schriftfeld (A4 hoch: volle Breite)+ cx, cy = self.width / 2, self.height / 2+ bottom = y0 if titleblock and cx >= x1 - 180 else y0 + 5+ for a, b in (((cx, 0), (cx, bottom)), ((cx, self.height), (cx, y1 - 5)),+ ((0, cy), (x0 + 5, cy)), ((self.width, cy), (x1 - 5, cy))):+ msp.add_line(a, b, dxfattribs={"layer": "FRAME"})++ def _title_block(self, f, lab):+ """Schriftfeld 180 mm breit unten rechts im Rahmen (ISO 7200). Liefert seinen Rahmen (x0, y0, x1, y1)."""+ x1, y0 = self.area[2], self.area[1]+ w, rh = 180.0, 10.0+ x0 = x1 - w+ msp = self.msp+ rows = [ # von unten: (Feld, Breite)+ [("material", 50), ("tolerance", 40), ("scale", 20), ("size", 20), ("projection", 20), ("sheet", 30)],+ [("drawn", 50), ("date", 40), ("number", 60), ("revision", 30)],+ [("owner", 50), ("title", 130)],+ ]+ heights = [rh, rh, 14.0]+ y = y0+ for row, h in zip(rows, heights):+ x = x0+ for key, cw in row:+ msp.add_lwpolyline([(x, y), (x + cw, y), (x + cw, y + h), (x, y + h)], close=True,+ dxfattribs={"layer": "TITLE"})+ self.text(lab[key], (x + 1.2, y + h - 1.2 - 1.8), height=1.8, layer="TITLE", _check=False)+ if key == "projection":+ if self.projection:+ self._projection_symbol(x + cw / 2, y + (h - 2.5) / 2)+ else:+ val = f.get(key)+ if val is not None and str(val) != "":+ th = 5.0 if key == "title" else TEXT_HEIGHT+ self.text(str(val), (x + 1.5, y + 1.6), height=th, layer="TITLE", _check=False)+ x += cw+ y += h+ msp.add_lwpolyline([(x0, y0), (x1, y0), (x1, y), (x0, y)], close=True,+ dxfattribs={"layer": "FRAME", "lineweight": THICK})+ return (x0, y0, x1, y)++ def _projection_symbol(self, cx, cy):+ """Symbol der Projektionsmethode (ISO 5456-2): Kegelstumpf und seine Stirnansicht, das kleine Ende des Kegels+ zeigt bei Methode 1 von den Kreisen weg, bei Methode 3 zu ihnen hin."""+ msp, att = self.msp, {"layer": "TITLE", "lineweight": THIN}+ r1, r2 = 1.6, 3.0+ cone_l = 6.0+ if self.projection == "first":+ kx, ky = cx - 5.0, cy+ circles = (cx + 4.5, cy)+ msp.add_lwpolyline([(kx - cone_l / 2, ky - r1), (kx + cone_l / 2, ky - r2), (kx + cone_l / 2, ky + r2),+ (kx - cone_l / 2, ky + r1)], close=True, dxfattribs=att)+ else:+ kx, ky = cx + 5.0, cy+ circles = (cx - 4.5, cy)+ msp.add_lwpolyline([(kx - cone_l / 2, ky - r1), (kx + cone_l / 2, ky - r2), (kx + cone_l / 2, ky + r2),+ (kx - cone_l / 2, ky + r1)], close=True, dxfattribs=att)+ msp.add_circle(circles, r2, dxfattribs=att)+ msp.add_circle(circles, r1, dxfattribs=att)+ msp.add_line((cx - 10, cy), (cx + 9, cy), dxfattribs={"layer": "CENTER"})++ # -- Geometrie aus dem Modell++ def shape(self, what):+ """The geometry of parts as one CadQuery shape (in model position), to change it before showing it:+ sh.view(sh.shape("Housing").cut(...), ...). what: part name, group, "*" or a list."""+ items = _resolve(what)+ shapes = [s for _n, s in items]+ return shapes[0] if len(shapes) == 1 else cq.Compound.makeCompound(shapes)++ def view(self, what, direction="front", at=None, scale=None, *, origin=None, up=None, hidden=None, tangent=False,+ style=None, label=None):+ """Projects parts onto the sheet with visible (and hidden) edges.++ what part name, group ("Housing", "Housing/Screws"), "*" (all parts without references), a list of+ them, or any CadQuery shape built here+ direction "front", "back", "left", "right", "top", "bottom", "iso" or a vector (x, y, z) from the part to+ the viewer+ at point (x, y) on the sheet in mm where `origin` lands+ scale own scale ("2:1"), default the scale of the sheet+ origin model point placed at `at`, default the middle of the bounding box. Views of the same parts with+ the default origin line up when they share x (or y) of `at`+ up model direction pointing up on the sheet (default Z, for top/bottom Y)+ hidden hidden edges dashed (default: in the six standard views, not in iso and other directions)+ tangent thin lines where fillets meet faces (default False)+ style None, or "phantom" for adjacent parts and extreme positions (thin, dash-double-dot)+ label text above the view, e.g. "View X"++ Returns a View: view.pt(), view.dim() ..."""+ file, line = _where()+ items = _resolve(what)+ n, x, y = _basis(direction, up)+ if hidden is None:+ hidden = isinstance(direction, str) and direction in STANDARD_VIEWS+ geo = _project(items, n, x, y, bool(hidden), bool(tangent))+ return self._add_view(geo, "view", direction, at, scale, origin, None, style, label, file, line)++ def section(self, what, direction="front", through=(0, 0, 0), at=None, scale=None, *, region=None, origin=None,+ up=None, name=None, parent=None, unhatched=(), hatch=None, hidden=False, label=True):+ """Section view: like view(), but the material between the viewer and a plane through `through`+ (perpendicular to the viewing direction) is removed. Cut faces are hatched.++ region instead of the plane: any solid that is removed (half section, local break-out). Flat faces of the+ cut that face the viewer are hatched+ name letter of the section, e.g. "A": label "A-A" above the view+ parent view in which the cutting plane is drawn (chain line, thick ends, arrows, letters)+ unhatched parts that are not cut (screws, shafts, pins, rolling elements, ribs in ISO 128-40)+ hatch None (45/135 degrees alternating per part, 2.5 mm), "solid" (thin walls), False, dict(angle=,+ spacing=, pattern=) for all, or {part: one of these}+ label True: "A-A" (plus the scale if it differs from the sheet), a text, or False"""+ file, line = _where()+ items = _resolve(what)+ n, x, y = _basis(direction, up)+ unhatched = tuple([unhatched] if isinstance(unhatched, str) else unhatched)+ for u in unhatched:+ if all(nm != u for nm, _s in items):+ raise ValueError(f"unhatched: {u!r} is not among the parts of this section")+ if parent is not None and region is not None:+ raise ValueError("parent= draws a straight cutting plane. With region= draw the cutting line yourself "+ "(sh.msp, layer CUT)")+ if region is None:+ p = _vec(through, "through")+ bb = _bbox([s for _n, s in items])+ size = 4 * max(bb.DiagonalLength, 1.0)+ face = cq.Face.makePlane(size, size, basePnt=cq.Vector(*p), dir=cq.Vector(*n))+ region = cq.Solid.extrudeLinear(face, cq.Vector(*(n * size)))+ else:+ region = registry.to_shape(region)+ geo = _project(items, n, x, y, bool(hidden), False, region, unhatched, hatch)+ lab = None+ if label is True and name:+ sc = parse_scale(scale) if scale is not None else self.scale+ lab = f"{name}-{name}" + (f" ({fmt_scale(sc)})" if abs(sc - self.scale) > 1e-9 else "")+ elif isinstance(label, str):+ lab = label+ v = self._add_view(geo, "section", direction, at, scale, origin, None, None, lab, file, line)+ v.name = f"{name}-{name}" if name else v.name+ if parent is not None:+ if not name:+ raise ValueError("parent= draws the cutting plane with its letter: give the section a name, e.g. name=\"A\"")+ self._cutting_line(parent, n, _vec(through, "through"), name)+ return v++ def detail(self, parent, center, radius, at, scale, *, name=None, label=True, border=True):+ """Detail view: a circle of `radius` (model mm) around the model point `center` of view `parent`, enlarged to+ `scale` (e.g. "5:1"), placed with its center at `at`. Draws the thin circle and the letter in the parent view,+ "B (5:1)" above the detail and (border=True) a thin circle around it."""+ file, line = _where()+ if not isinstance(parent, View):+ raise ValueError("parent must be a view of this sheet")+ r = float(radius)+ if not r > 0:+ raise ValueError("radius must be greater than 0")+ c = _vec(center, "center")+ cu, cv = float(np.dot(c, parent._geo.x)), float(np.dot(c, parent._geo.y))+ geo = parent._geo.clip(cu, cv, r)+ sc = parse_scale(scale)+ lab = None+ if label is True and name:+ lab = f"{name} ({fmt_scale(sc)})"+ elif isinstance(label, str):+ lab = label+ v = View(self, geo, "detail", name or f"detail {len(self.views) + 1}", _pt2(at, "at"), sc, c,+ (cu, cv, r), None, file, line)+ self.views.append(v)+ if border:+ self.msp.add_circle(tuple(v.at), r * sc, dxfattribs={"layer": "THIN"})+ v.bbox = (v.at[0] - r * sc, v.at[1] - r * sc, v.at[0] + r * sc, v.at[1] + r * sc)+ if lab:+ self._view_label(v, lab, file, line)+ # Kreis und Buchstabe in der Ausgangsansicht+ px, py = parent.pt(c)+ rr = r * parent.scale+ self.msp.add_circle((px, py), rr, dxfattribs={"layer": "THIN"})+ if name:+ d = math.sqrt(0.5)+ self.text(name, (px + (rr + 1.5) * d, py + (rr + 1.5) * d), height=LABEL_HEIGHT, layer="TEXT")+ return v++ def _add_view(self, geo, kind, direction, at, scale, origin, clip, style, label, file, line):+ if at is None:+ raise ValueError("at=(x, y) is missing: where on the sheet (mm) the view goes")+ at = _pt2(at, "at")+ sc = parse_scale(scale, "scale") if scale is not None else self.scale+ org = _vec(origin, "origin") if origin is not None else geo.center+ if style not in (None, "phantom"):+ raise ValueError(f"style must be None or \"phantom\", not {style!r}")+ name = direction if isinstance(direction, str) else "view"+ if any(w.name == name for w in self.views):+ name = f"{name} {sum(1 for w in self.views if w.name.split(' ')[0] == name) + 1}"+ v = View(self, geo, kind, name, at, sc, org, clip,+ "PHANTOM" if style == "phantom" else None, file, line)+ self.views.append(v)+ if label:+ self._view_label(v, label, file, line)+ return v++ def _view_label(self, v, text, file, line):+ x0, _y0, x1, y1 = v.bbox+ self.text(str(text), ((x0 + x1) / 2, y1 + 5), height=LABEL_HEIGHT, align="center", layer="TEXT")++ def _cutting_line(self, parent, n, through, name):+ """Schnittverlauf in der Ausgangsansicht nach ISO 128-44: duenne Strichpunktlinie, dicke Enden, Pfeile in+ Blickrichtung, Buchstaben."""+ if not isinstance(parent, View):+ raise ValueError("parent must be a view of this sheet")+ pn = np.array(parent._geo.n)+ if abs(float(np.dot(pn, n))) > 1e-6:+ raise ValueError("The cutting plane must be seen edge-on in the parent view (section direction "+ "perpendicular to the parent's viewing direction)")+ d3 = np.cross(n, pn)+ d = np.array([float(np.dot(d3, parent._geo.x)), float(np.dot(d3, parent._geo.y))])+ d = d / np.linalg.norm(d)+ look = -np.array([float(np.dot(n, parent._geo.x)), float(np.dot(n, parent._geo.y))])+ look = look / np.linalg.norm(look)+ p = np.array(parent.pt(through))+ x0, y0, x1, y1 = parent.bbox+ ts = [float(np.dot(np.array(c) - p, d)) for c in ((x0, y0), (x1, y0), (x0, y1), (x1, y1))]+ a, b = p + d * (min(ts) - 4), p + d * (max(ts) + 4)+ msp = self.msp+ msp.add_line(tuple(a), tuple(b), dxfattribs={"layer": "CUT"})+ for end, out in ((a, -d), (b, d)):+ inner = end - out * 6+ msp.add_line(tuple(end), tuple(inner), dxfattribs={"layer": "CUT", "linetype": "Continuous", "lineweight": 70})+ tail = end - out * 2.5+ tip = tail + look * 7+ side = np.array([-look[1], look[0]])+ msp.add_line(tuple(tail), tuple(tip - look * 3), dxfattribs={"layer": "THIN"})+ msp.add_solid([tuple(tip), tuple(tip - look * 3 + side * 0.9), tuple(tip - look * 3 - side * 0.9)],+ dxfattribs={"layer": "THIN"})+ self.text(name, tuple(tail + look * 4 + out * 4), height=LABEL_HEIGHT, align="middle", layer="TEXT")++ # -- Text, Hinweise, Tabellen++ def text(self, text, at, height=TEXT_HEIGHT, align="left", rotation=0, layer="TEXT", _check=True):+ """Text at the sheet point `at` (mm). align: "left", "center", "right" (on the baseline) or "middle" (centered+ both ways). Several lines with "\\n". Returns the ezdxf entity."""+ if not isinstance(text, str):+ text = str(text)+ at = tuple(_pt2(at, "at"))+ h = float(height)+ if not h > 0:+ raise ValueError("height must be greater than 0")+ aligns = {"left": TextEntityAlignment.LEFT, "center": TextEntityAlignment.CENTER,+ "right": TextEntityAlignment.RIGHT, "middle": TextEntityAlignment.MIDDLE_CENTER}+ if align not in aligns:+ raise ValueError(f"align must be one of {', '.join(aligns)}, not {align!r}")+ att = {"layer": _layer(layer), "style": "ISO"}+ if "\n" in text:+ attach = {"left": 7, "center": 8, "right": 9, "middle": 5}[align] # unten links/mitte/rechts, Mitte+ e = self.msp.add_mtext(text.replace("\n", "\\P"), dxfattribs={**att, "char_height": h})+ e.set_location(at, rotation=float(rotation), attachment_point=attach)+ else:+ e = self.msp.add_text(text, height=h, rotation=float(rotation), dxfattribs=att)+ e.set_placement(at, align=aligns[align])+ if _check:+ f, ln = _where()+ self._labels.append(dict(entity=e, text=text, height=h, file=f, line=ln))+ return e++ def leader(self, point, text, at, end="arrow", height=TEXT_HEIGHT):+ """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."""+ 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}")+ msp = self.msp+ left = a[0] < p[0]+ e = self.text(text, (a[0] - 1 if left else a[0] + 1, a[1] + 1), height=height, align="right" if left else "left")+ try:+ from ezdxf.tools.text_size import text_size+ width = text_size(e).width+ except Exception: # Schrift nicht messbar: ungefaehre Breite+ width = 0.6 * height * len(text)+ shoulder = a + np.array([-(width + 2) if left else width + 2, 0])+ msp.add_line(tuple(p), tuple(a), dxfattribs={"layer": "THIN"})+ msp.add_line(tuple(a), tuple(shoulder), dxfattribs={"layer": "THIN"})+ d = a - p+ if np.linalg.norm(d) > 1e-9 and end == "arrow":+ d = d / np.linalg.norm(d)+ side = np.array([-d[1], d[0]])+ msp.add_solid([tuple(p), tuple(p + d * 3 + side * 0.9), tuple(p + d * 3 - side * 0.9)], dxfattribs={"layer": "THIN"})+ elif end == "dot":+ h = msp.add_hatch(color=256, dxfattribs={"layer": "THIN"})+ h.paths.add_edge_path().add_arc(tuple(p), 0.6, 0, 360)+ h.set_solid_fill(color=256)+ return e++ def table(self, rows, at, widths, 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)."""+ x0, y_top = _pt2(at, "at")+ widths = [float(w) for w in widths]+ y = y_top+ for row in rows:+ if len(row) > len(widths):+ raise ValueError(f"The row {row!r} has more cells than widths")+ x = x0+ for cell, w in zip(row, widths):+ self.msp.add_lwpolyline([(x, y - row_height), (x + w, y - row_height), (x + w, y), (x, y)], close=True,+ dxfattribs={"layer": "TITLE"})+ if cell is not None and str(cell) != "":+ self.text(str(cell), (x + 1.5, y - row_height + (row_height - text_height) / 2), height=text_height)+ x += w+ y -= row_height+ return (x0, y, x0 + sum(widths), y_top)diff --git a/python/soma/drawrun.py b/python/soma/drawrun.pynew file mode 100644index 0000000..e511ce1--- /dev/null+++ b/python/soma/drawrun.py@@ -0,0 +1,542 @@+"""`soma drawing`: Zeichnungsskripte (drawings/*.py) ausfuehren, pruefen und als DXF, PDF und PNG schreiben (E76).++Ergebnis je Blatt: output/drawings/<id>.dxf und .pdf (Lieferdateien, im Verlauf wie output/model.step),+.soma/drawings/<id>.png (Bild fuer den Agenten, eine Datei in hoher Aufloesung) und .soma/drawings/index.json mit+Ansichten, Maßen und Hinweisen fuer `soma drawing info`. Die Pruefung meldet nur und aendert nichts (E28).+"""+import json+import math+import os+import random+import re+import runpy+import sys+import time+import types+from pathlib import Path++import numpy as np++from . import build, drawing++DRAW_DIR = "drawings"+OUT_DIR = Path("output") / "drawings"+CACHE_DIR = Path(".soma") / "drawings"+DPI = 200+MAX_PX = 7000 # laengste Seite des Bildes, A0 mit 200 dpi waeren 9400 px und 250 MB im Speicher+ON_EDGE = 0.05 # mm auf dem Blatt: so nah muss ein Maßpunkt an einer Kante der Ansicht liegen+++class DrawingError(Exception):+ pass+++def _rel(p, root):+ return build._rel(p, root)+++def drawing_files(root):+ d = Path(root) / DRAW_DIR+ return sorted(p for p in d.glob("*.py") if p.is_file() and not p.name.startswith("_")) if d.is_dir() else []+++def read_index(root):+ try:+ return json.loads((Path(root) / CACHE_DIR / "index.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return dict(version=1, drawings=[], errors=[])+++# ---- Ausfuehren -----------------------------------------------------------------------------------------------------++def _run_file(root, path):+ """Fuehrt ein Zeichnungsskript aus und liefert seine Blaetter. `from model import ...` fuehrt das Modell nicht noch+ einmal aus: Sein Namensraum vom Build wird das Modul (wie bei den Animationen)."""+ drawing.SHEETS.clear()+ old_cwd = os.getcwd()+ os.chdir(root)+ sys.path.insert(0, str(root))+ from . import registry+ registry.IGNORE_ADD = True+ mod_name, old_mod = None, None+ if build.LAST_RUN and Path(build.LAST_RUN[0]).resolve().parent == Path(root).resolve() and build.LAST_RUN[0].stem.isidentifier():+ script, ns = build.LAST_RUN+ mod_name, old_mod = script.stem, sys.modules.get(script.stem)+ mod = types.ModuleType(mod_name)+ mod.__dict__.update(ns)+ mod.__name__, mod.__file__ = mod_name, str(script)+ sys.modules[mod_name] = mod+ try:+ runpy.run_path(str(path), run_name="__main__")+ except SystemExit as e:+ if e.code not in (None, 0):+ raise build.BuildError(f"{_rel(path, root)} exited with code {e.code}", file=_rel(path, root), kind="SystemExit")+ except BaseException as e:+ raise build._error_from_exception(e, root)+ finally:+ registry.IGNORE_ADD = False+ if mod_name:+ if old_mod is None:+ sys.modules.pop(mod_name, None)+ else:+ sys.modules[mod_name] = old_mod+ os.chdir(old_cwd)+ if sys.path and sys.path[0] == str(root):+ sys.path.pop(0)+ found = list(drawing.SHEETS)+ drawing.SHEETS.clear()+ if not found:+ raise build.BuildError(f"{_rel(path, root)} creates no sheet. Start with sh = Sheet(\"Name\") "+ "(from soma.drawing import Sheet).", file=_rel(path, root), kind="NoSheet")+ return found+++# ---- Pruefen --------------------------------------------------------------------------------------------------------++def _box(entity):+ import ezdxf.bbox+ try:+ bb = ezdxf.bbox.extents([entity], fast=False)+ except Exception: # Messen scheitert (z. B. fehlende Schrift): dann ohne diese Pruefung+ return None+ if not bb.has_data:+ return None+ return (bb.extmin.x, bb.extmin.y, bb.extmax.x, bb.extmax.y)+++def _overlap(a, b, shrink=0.0):+ return (min(a[2], b[2]) - max(a[0], b[0]) > 2 * shrink) and (min(a[3], b[3]) - max(a[1], b[1]) > 2 * shrink)+++def _segments(views):+ """Alle Kanten der Ansichten als Strecken (a, b) auf dem Blatt, mit Ansicht und Art."""+ out = []+ for v in views:+ for pts, kind in v._lines:+ if len(pts) >= 2:+ out.append((pts[:-1], pts[1:], v, kind))+ return out+++def _crosses_box(a, b, box):+ """Welche Strecken a[i] -> b[i] schneiden das Rechteck box (x0, y0, x1, y1)?"""+ x0, y0, x1, y1 = box+ lo, hi = np.minimum(a, b), np.maximum(a, b)+ near = (hi[:, 0] >= x0) & (lo[:, 0] <= x1) & (hi[:, 1] >= y0) & (lo[:, 1] <= y1)+ if not near.any():+ return near+ d = b - a+ corners = np.array([(x0, y0), (x1, y0), (x0, y1), (x1, y1)])+ # Vorzeichen der Ecken zur Geraden: alle auf einer Seite -> kein Schnitt+ s = np.stack([d[:, 0] * (c[1] - a[:, 1]) - d[:, 1] * (c[0] - a[:, 0]) for c in corners], axis=1)+ return near & ~((s > 0).all(axis=1) | (s < 0).all(axis=1))+++def _dist_to_lines(p, segs):+ """Kleinster Abstand des Blattpunkts p zu den Strecken, getrennt nach sichtbar und verdeckt."""+ best = {"visible": math.inf, "hidden": math.inf}+ for a, b, _v, kind in segs:+ d = b - a+ L = (d * d).sum(axis=1)+ t = np.where(L > 1e-18, ((p - a) * d).sum(axis=1) / np.where(L > 1e-18, L, 1), 0.0).clip(0, 1)+ q = a + d * t[:, None]+ m = float(np.sqrt(((q - p) ** 2).sum(axis=1)).min()) if len(q) else math.inf+ key = "hidden" if kind == "hidden" else "visible"+ best[key] = min(best[key], m)+ return best+++def check(sheet):+ """Hinweise zum Blatt: nur melden, nichts aendern. Liefert [dict(message, file, line)]."""+ _fonts() # Texte mit der Schrift messen, mit der sie gezeichnet werden+ warn = []++ def add(msg, file=None, line=None):+ warn.append(dict(message=msg, file=file, line=line))++ x0, y0, x1, y1 = sheet.area+ tb = sheet.titleblock+ if not sheet.views and not sheet._dims and not sheet._labels:+ add("The sheet is empty: no view, dimension or text.", sheet.file, sheet.line)++ def place(what, box, file, line):+ if box is None:+ return+ out = max(x0 - box[0], y0 - box[1], box[2] - x1, box[3] - y1)+ if out > 0.05:+ add(f"{what} reaches {out:.1f} mm beyond the frame.", file, line)+ if tb and _overlap(box, tb, 0.05):+ add(f"{what} overlaps the title block.", file, line)++ for v in sheet.views:+ place(f"View {v.name}", v.bbox, v.file, v.line)+ for i, v in enumerate(sheet.views):+ for w in sheet.views[i + 1:]:+ if v.phantom or w.phantom:+ continue # Nachbarteile liegen absichtlich ueber einer anderen Ansicht+ if _overlap(v.bbox, w.bbox, 0.5):+ add(f"View {v.name} (line {v.line}) and view {w.name} (line {w.line}) overlap.", w.file, w.line)++ texts = [] # (Rechteck, Beschreibung, Datei, Zeile)+ for t in sheet._labels:+ box = _box(t["entity"])+ what = f"Text \"{_short(t['text'])}\""+ place(what, box, t["file"], t["line"])+ if box:+ texts.append((box, what, t["file"], t["line"]))+ if t["height"] < 2.5:+ add(f"{what} is {t['height']:g} mm high, use at least 2.5 mm (ISO 3098).", t["file"], t["line"])+ for d in sheet._dims:+ what = f"Dimension {_dim_label(d)}"+ place(what, _box(d["entity"]), d["file"], d["line"])+ try:+ parts = list(d["entity"].virtual_entities())+ except Exception:+ parts = []+ for e in parts:+ if e.dxftype() in ("MTEXT", "TEXT"):+ box = _box(e)+ if box:+ texts.append((box, what, d["file"], d["line"]))++ # Texte uebereinander und Texte auf Kanten der Ansichten+ for i, (a, wa, fa, la) in enumerate(texts):+ for b, wb, fb, lb in texts[i + 1:]:+ if _overlap(a, b, 0.2):+ add(f"{wb} overlaps {wa} (line {la}).", fb, lb)+ segs = _segments(sheet.views)+ for box, what, f, ln in texts:+ shrunk = (box[0] + 0.3, box[1] + 0.3, box[2] - 0.3, box[3] - 0.3)+ if shrunk[0] >= shrunk[2] or shrunk[1] >= shrunk[3]:+ continue+ hit = {v.name for a, b, v, kind in segs if kind != "tangent" and _crosses_box(a, b, shrunk).any()}+ if hit:+ add(f"{what} lies on edges of view {', '.join(sorted(hit))}.", f, ln)++ # Maße: Punkte auf Kanten, Kreise vorhanden, feste Zahlen wie gemessen+ for d in sheet._dims:+ v = d["view"]+ what = f"Dimension {_dim_label(d)}"+ vsegs = [s for s in segs if s[2] is v]+ if d["kind"] in ("diameter", "radius"):+ c = np.array(d["points"][0])+ found = any(np.allclose(np.array(cc), c, atol=1e-3) and abs(r - d["radius"]) < 1e-3+ for cc, r in v.circles(arcs=True))+ if not found:+ add(f"{what}: view {v.name} has no circle with radius {drawing.num(d['radius'], 3)} around "+ f"{_p3(c)}.", d["file"], d["line"])+ else:+ centers = None+ for p in d["points"]:+ q = np.array(v.pt(p))+ dist = _dist_to_lines(q, vsegs)+ if dist["visible"] <= ON_EDGE:+ continue+ # Mitten von Bohrungen und Bögen sind uebliche Bezugspunkte, auch ohne Kante+ if centers is None:+ centers = [np.array(v.pt(c)) for c, _r in v.circles(arcs=True)]+ if any(float(np.linalg.norm(q - c)) <= ON_EDGE for c in centers):+ continue+ if dist["hidden"] <= ON_EDGE:+ add(f"{what}: the point {_p3(p)} lies only on a hidden edge (dimension visible edges, ISO 129).",+ d["file"], d["line"])+ else:+ add(f"{what}: the point {_p3(p)} lies on no edge of view {v.name} "+ f"({min(dist.values()):.2f} mm away on the sheet). A rounded or chamfered corner? Then take a "+ "point on the straight edge.", d["file"], d["line"])+ t = d["text"]+ if t is not None and "<>" not in t:+ nums = [float(x.replace(",", ".")) for x in re.findall(r"\d+(?:[.,]\d+)?", t)]+ value = round(d["value"], 2)+ if nums and not any(abs(x - value) < 0.005 for x in nums):+ add(f"{what}: the text \"{t}\" differs from the measured {drawing.num(d['value'])}. Use \"<>\" for the "+ "measured value.", d["file"], d["line"])++ scales = sorted({v.scale for v in sheet.views} | {sheet.scale})+ for s in scales:+ if not any(abs(s - iso) / iso < 1e-6 for iso in drawing.ISO_SCALES):+ add(f"Scale {drawing.fmt_scale(s)} is not a preferred scale of ISO 5455 (1:2, 1:5, 1:10, 2:1, 5:1 ...).",+ sheet.file, sheet.line)+ return warn+++def _short(t, n=30):+ t = " ".join(str(t).split())+ return t if len(t) <= n else t[:n - 3] + "..."+++def _dim_label(d):+ val = drawing.num(d["value"])+ if d["kind"] == "diameter":+ val = "Ø" + val+ elif d["kind"] == "radius":+ val = "R" + val+ elif d["kind"] == "angle":+ val += "°"+ if d["text"] is not None:+ return f"\"{_short(d['text'].replace('<>', val))}\""+ return val+++def _p3(p):+ return "(" + ", ".join(drawing.num(float(x), 3) for x in p) + ")"+++# ---- Ausgabe --------------------------------------------------------------------------------------------------------++_FONTS_READY = False+++def _fonts():+ """Die Schrift der Zeichnungen liegt matplotlib bei, ezdxf kennt den Ordner aber nicht von sich aus."""+ global _FONTS_READY+ if _FONTS_READY:+ return+ import matplotlib+ from ezdxf.fonts import fonts+ try:+ fonts.font_manager.scan_folder(Path(matplotlib.get_data_path(), "fonts", "ttf"))+ except Exception: # ohne sie nimmt ezdxf eine Ersatzschrift+ pass+ _FONTS_READY = True+++def render(sheet, pdf_path, png_path, dpi):+ """PDF und PNG aus derselben DXF (Zeichenmodul von ezdxf mit matplotlib), Papier exakt im Format des Blatts."""+ from ezdxf.addons.drawing import Frontend, RenderContext+ from ezdxf.addons.drawing import config as dcfg+ from ezdxf.addons.drawing.matplotlib import MatplotlibBackend+ from ezdxf.npshapes import to_matplotlib_path+ from matplotlib.backends.backend_agg import FigureCanvasAgg+ from matplotlib.figure import Figure+ from matplotlib.patches import PathPatch++ class Backend(MatplotlibBackend):+ # ezdxf sucht in gefuellten Pfaden Loecher ueber Verschachtelung. Bei Zeichen aus sich kreuzenden Konturen+ # (Ø in jeder Schrift) wird daraus ein schwarzer Fleck. Text deshalb mit der Fuellregel der Schrift+ text_mode = False++ def draw_filled_paths(self, paths, properties):+ if not self.text_mode:+ return super().draw_filled_paths(paths, properties)+ try:+ patch = PathPatch(to_matplotlib_path(paths, detect_holes=False), color=properties.color, linewidth=0,+ fill=True, zorder=self._get_z())+ except ValueError:+ return+ self.ax.add_patch(patch)++ _fonts()+ w, h = sheet.width, sheet.height+ fig = Figure(figsize=(w / 25.4, h / 25.4))+ FigureCanvasAgg(fig)+ ax = fig.add_axes((0, 0, 1, 1))+ ax.set_axis_off()+ cfg = dcfg.Configuration(background_policy=dcfg.BackgroundPolicy.WHITE, color_policy=dcfg.ColorPolicy.BLACK,+ lineweight_policy=dcfg.LineweightPolicy.ABSOLUTE, line_policy=dcfg.LinePolicy.ACCURATE,+ lineweight_scaling=72 / 25.4, min_lineweight=0.13 * 72 / 25.4)+ be = Backend(ax)+ fe = Frontend(RenderContext(sheet.doc), be, config=cfg)+ draw_text = fe.pipeline.draw_text++ def text(*a, **k):+ be.text_mode = True+ try:+ draw_text(*a, **k)+ finally:+ be.text_mode = False++ fe.pipeline.draw_text = text+ # ezdxf verschiebt Schraffurlinien um einen kleinen Zufallswert (gegen Treffer genau auf Ecken). Fester Startwert:+ # gleiche Zeichnung, gleiche PDF+ state = random.getstate()+ random.seed(76)+ try:+ fe.draw_layout(sheet.msp, finalize=False)+ finally:+ random.setstate(state)+ ax.set_xlim(0, w)+ ax.set_ylim(0, h)+ ax.set_aspect("equal")+ dpi = min(float(dpi), MAX_PX / (max(w, h) / 25.4))+ _atomic(pdf_path, lambda p: fig.savefig(p, format="pdf", metadata={"CreationDate": None}))+ _atomic(png_path, lambda p: fig.savefig(p, format="png", dpi=dpi, facecolor="white"))+ return (round(w / 25.4 * dpi), round(h / 25.4 * dpi))+++def _atomic(path, write):+ """Erst vollstaendig schreiben, dann ersetzen: Die App liest die PDF nie halb geschrieben."""+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(path.name + ".part")+ write(tmp)+ os.replace(tmp, path)+++def save_dxf(sheet, path):+ import ezdxf+ old = ezdxf.options.write_fixed_meta_data_for_testing+ # Feste Zeitstempel und GUIDs: gleiche Zeichnung, gleiche Datei. Sonst aendert jeder Lauf die Datei im Verlauf+ ezdxf.options.write_fixed_meta_data_for_testing = True+ # Die Klassen kommen bei ezdxf aus einer Menge, ihre Reihenfolge wechselt von Lauf zu Lauf: sortiert schreiben+ classes = sheet.doc.classes+ export = classes.export_dxf++ def sorted_export(tagwriter):+ classes.classes = dict(sorted(classes.classes.items()))+ export(tagwriter)++ classes.export_dxf = sorted_export+ try:+ _atomic(path, lambda p: sheet.doc.saveas(p))+ finally:+ ezdxf.options.write_fixed_meta_data_for_testing = old+++def _entry(root, sheet, warnings, px):+ rel = lambda p: p.relative_to(root).as_posix()+ views = []+ for v in sheet.views:+ circles = v._circles()+ views.append(dict(name=v.name, kind=v.kind, scale=drawing.fmt_scale(v.scale), line=v.line,+ file=_rel(v.file, root) if v.file else None, direction=[round(x, 4) + 0.0 for x in v.direction],+ at=[round(float(x), 2) for x in v.at], bbox=[round(x, 2) for x in v.bbox],+ circles=[dict(center=list(c), diameter=round(2 * r, 4), arc=not full) for c, r, full in circles[:60]],+ circles_total=len(circles)))+ dims = [dict(kind=d["kind"], value=round(d["value"], 4), text=d["text"], label=_dim_label(d), view=d["view"].name,+ line=d["line"], file=_rel(d["file"], root) if d["file"] else None) for d in sheet._dims]+ return dict(id=sheet.id, name=sheet.name, file=_rel(sheet.file, root) if sheet.file else None, line=sheet.line,+ size=sheet.size, width=sheet.width, height=sheet.height, scale=drawing.fmt_scale(sheet.scale),+ area=[round(x, 2) for x in sheet.area], titleblock=[round(x, 2) for x in sheet.titleblock] if sheet.titleblock else None,+ pdf=rel(root / OUT_DIR / f"{sheet.id}.pdf"), dxf=rel(root / OUT_DIR / f"{sheet.id}.dxf"),+ png=rel(root / CACHE_DIR / f"{sheet.id}.png"), png_size=list(px), views=views, dims=dims,+ warnings=[dict(w, file=_rel(w["file"], root) if w.get("file") else None) for w in warnings],+ built=time.time())+++def build_all(root, only=None, dpi=DPI):+ """Baut alle Zeichnungen (oder die einer Datei). Liefert dict(built=[...], errors=[...], orphans=[...]). errors sind die+ Fehler dieses Laufs, der Index behaelt auch die anderer Dateien, die nicht neu gebaut wurden."""+ root = Path(root).resolve()+ old = read_index(root)+ try:+ parts = build.run_model(root)+ except build.BuildError as e:+ raise DrawingError(f"The model does not build, so no drawing does either: {e.message}"+ + (f" ({e.file}:{e.line})" if e.file and e.line else "")) from None+ drawing._PARTS = parts+ files = drawing_files(root)+ if only is not None:+ files = [f for f in files if f.resolve() == Path(only).resolve()]+ done_files = {_rel(f, root) for f in files}+ keep = [x for x in old.get("drawings", []) if x.get("file") not in done_files and (root / x.get("file", "")).is_file()]+ old_errors = [x for x in old.get("errors", []) if x.get("file") not in done_files and (root / x.get("file", "")).is_file()]+ errors = []+ taken = {x["id"]: x["file"] for x in keep}+ built = []+ try:+ for f in files:+ rel = _rel(f, root)+ try:+ sheets = _run_file(root, f)+ except build.BuildError as e:+ errors.append(dict(file=e.file or rel, line=e.line, message=e.message, traceback=e.tb))+ continue+ for sh in sheets:+ try:+ if sh.id in taken:+ raise build.BuildError(f"The sheet {sh.name!r} already exists (in {taken[sh.id]}). Names must be "+ "unique.", file=rel, line=sh.line, kind="DuplicateName")+ taken[sh.id] = rel+ warnings = check(sh)+ save_dxf(sh, root / OUT_DIR / f"{sh.id}.dxf")+ px = render(sh, root / OUT_DIR / f"{sh.id}.pdf", root / CACHE_DIR / f"{sh.id}.png", dpi)+ built.append(_entry(root, sh, warnings, px))+ except build.BuildError as e:+ errors.append(dict(file=e.file or rel, line=e.line, message=e.message, traceback=e.tb))+ except Exception as e: # Fehler beim Pruefen oder Schreiben+ err = build._error_from_exception(e, root)+ errors.append(dict(file=err.file or rel, line=err.line, message=err.message, traceback=err.tb))+ finally:+ drawing._PARTS = None+ # Blaetter, die es nicht mehr gibt: das Bild ist Zwischenstand der App und geht, PDF und DXF bleiben (nichts still+ # loeschen), die Ausgabe nennt sie+ ids = {x["id"] for x in keep} | {x["id"] for x in built}+ orphans = []+ for x in old.get("drawings", []):+ if x["id"] in ids:+ continue+ try:+ (root / CACHE_DIR / f"{x['id']}.png").unlink()+ except OSError:+ pass+ orphans += [p for p in (x.get("pdf"), x.get("dxf")) if p and (root / p).is_file()]+ index = dict(version=1, drawings=sorted(keep + built, key=lambda x: (x["file"] or "", x["line"] or 0)), errors=old_errors + errors)+ (root / CACHE_DIR).mkdir(parents=True, exist_ok=True)+ (root / CACHE_DIR / "index.json").write_text(json.dumps(index, indent=1, ensure_ascii=False), encoding="utf-8")+ return dict(built=built, errors=errors, orphans=orphans, index=index)+++def find(root, name):+ for x in read_index(root).get("drawings", []):+ if name in (x["name"], x["id"]) or Path(name).as_posix() in (x["file"], x["pdf"], x["dxf"]):+ return x+ return None+++def is_stale(root, entry):+ from .animrun import newest_source+ try:+ built = (Path(root) / entry["pdf"]).stat().st_mtime+ except OSError:+ return True+ return newest_source(root, [Path(root) / entry["file"]] if entry.get("file") else []) > built+++# ---- Text fuer den Agenten ------------------------------------------------------------------------------------------++def warning_text(w):+ where = f"{w['file']}:{w['line']}" if w.get("file") and w.get("line") else (w.get("file") or "")+ return f"Warning ({where}): {w['message']}" if where else f"Warning: {w['message']}"+++def info_text(entry):+ e = entry+ x0, y0, x1, y1 = e["area"]+ lines = [f"Drawing \"{e['name']}\" ({e['file']} line {e['line']}): {e['size']}, {drawing.num(e['width'])} x "+ f"{drawing.num(e['height'])} mm, scale {e['scale']}",+ f"Files: {e['pdf']}, {e['dxf']}; picture {e['png']} ({e['png_size'][0]} x {e['png_size'][1]} px)",+ f"Drawing area inside the frame: x {drawing.num(x0)} to {drawing.num(x1)}, y {drawing.num(y0)} to {drawing.num(y1)} mm"+ + (f"; title block x {drawing.num(e['titleblock'][0])} to {drawing.num(e['titleblock'][2])}, y "+ f"{drawing.num(e['titleblock'][1])} to {drawing.num(e['titleblock'][3])}" if e.get("titleblock") else ""),+ "", "Views:"]+ if not e["views"]:+ lines.append(" none")+ for v in e["views"]:+ b = v["bbox"]+ lines.append(f" {v['name']} ({v['kind']}, line {v['line']}): scale {v['scale']}, on the sheet x {drawing.num(b[0])} "+ f"to {drawing.num(b[2])}, y {drawing.num(b[1])} to {drawing.num(b[3])}")+ for arc, title in ((False, "circles"), (True, "arcs")):+ groups = {}+ for c in v["circles"]:+ if bool(c.get("arc")) == arc:+ groups.setdefault(c["diameter"], []).append(_p3(c["center"]))+ if not groups:+ continue+ sym = (lambda d: "R" + drawing.num(d / 2, 3)) if arc else (lambda d: "Ø" + drawing.num(d, 3))+ txt = "; ".join(f"{sym(d)} x{len(cs)} at {', '.join(cs[:6])}{' ...' if len(cs) > 6 else ''}"+ for d, cs in sorted(groups.items(), key=lambda g: -g[0]))+ lines.append(f" {title}: {txt}")+ if v["circles_total"] > len(v["circles"]):+ lines.append(f" ... and {v['circles_total'] - len(v['circles'])} more circles and arcs")+ lines += ["", "Dimensions:"]+ if not e["dims"]:+ lines.append(" none")+ for d in e["dims"]:+ lines.append(f" line {d['line']}: {d['label']} ({d['kind']}, {d['view']})")+ lines += [""]+ if e["warnings"]:+ lines += ["Warnings:"] + [" " + warning_text(w) for w in e["warnings"]]+ else:+ lines.append("Warnings: none")+ return "\n".join(lines)