diff --git a/design-docs/optional-drawing-workflow.md b/design-docs/optional-drawing-workflow.md new file mode 100644 index 00000000..2b3f394f --- /dev/null +++ b/design-docs/optional-drawing-workflow.md @@ -0,0 +1,31 @@ +# Optional single-part drawing workflow + +## Decision + +In the 2026-11-18 integration request, the user asked to turn dxf-exporter into +a reviewable SimpleCADAPI contribution and compare it with the existing drawing +tool. Integrate the workflow behind `sca drawing` and reuse the existing +declarative engine. The optional workflow selects inputs for that engine and +preserves its independent measurements and verification. + +`SheetPlan` can accept a different projection implementation through a protected +view hook. Both paths use a single vector DXF builder. The direct `SheetPlan` +entry point continues to accept its existing declarations, and its rendering +continues to use its existing behavior. The workflow can add decorations, +verify the saved DXF, and rasterize it once at a bounded resolution. + +## Capabilities and ownership + +| Decision | Reason | +| --- | --- | +| Separate `dxf_engine.workflow` and one CLI group | Preserve the existing low-level solver contract and keep the STEP/notebook entry discoverable alongside `sca run`. | +| Measure the physical solid | AP242 presentation geometry can be part of the imported compound. Extents are calculated on the solid and dimension geometry is read back. | +| Cache projections within one plan | View scoring, dimension proposals and fit trials reuse geometry without global caches or changes to owner state. | +| Use the existing optional `verify` dependency for polygonal HLR | Some spline-heavy parts have expensive exact projections. Point and face measurements still come from the original B-Rep. The workflow reports the approximation. | +| Preserve a notebook STEP and parameter ledger | The agent can edit and replay a declaration while the SDK measures the feature. A missing or mismatched binding remains an explicit review item. | +| Keep inspection workflows separate from drafting decisions | Shared-layout DXFs and overlays preserve the geometry inspection use case. | + +The contribution avoids a second solver, a separate DXF writer for core +entities, new mandatory dependencies and generated CAD assets in Git. Templates +are drafting starting points. Manufacturing completeness, PMI ingestion and +assembly drawings remain separate work. diff --git a/docs/skill/references/docs/api/render_plan.md b/docs/skill/references/docs/api/render_plan.md index aac8a49c..6c9e7df5 100644 --- a/docs/skill/references/docs/api/render_plan.md +++ b/docs/skill/references/docs/api/render_plan.md @@ -14,8 +14,4 @@ def render_plan(plan, dxf_path, png_path) ## Description -Render the solved SheetPlan as a GB-layer DXF + PNG pair, then read the DXF back and verify its dimensions. - -The DXF goes through ezdxf (GB layers 01_THICK_SOLID/08_DASHED/05_CENTER/DIMENSION/TEXT, native DIMENSION -entities in style "GB"); the PNG is produced from the DXF through PyMuPdf for multimodal cross-checking. -Returns {"dxf", "png", "entities", "dimensions", "issues"}; the issues also enter `plan.issues()` and `report()`. +Render the solved SheetPlan as a GB-layer DXF + PNG pair and verify it. diff --git a/docs/skill/references/workflows/engineering-drawing.md b/docs/skill/references/workflows/engineering-drawing.md index 16bd6fc7..803efd98 100644 --- a/docs/skill/references/workflows/engineering-drawing.md +++ b/docs/skill/references/workflows/engineering-drawing.md @@ -1,5 +1,28 @@ # Workflow: Engineering Drawing Generation +## Start from STEP or a single-part notebook + +Install `simplecadapi[drawing]`, then use `sca drawing --step part.step --out part.dxf --plan-only` to +propose orthographic views, a useful planar cut, a sheet and core dimensions. The plan records geometry +evidence, placement warnings and unbound design inputs. Review the generated `part.drawing.json` +and replay it with `sca drawing --mode engineering --step part.step --drawing-json part.drawing.json +--out reviewed.dxf`. `--pdf` adds a true-scale vector print page. `--mode inspection` produces the seven +geometry inspection views at model scale, with optional shared `--layout-json`. + +`sca drawing --notebook part.py --out part.dxf` executes a trusted notebook and keeps a STEP snapshot. +In `DRAWING_INTENT`, a `dimensions` entry connects a top-level `parameter` to existing geometry with +`of`, `between` or `extent`. Use `view` and `semantic` to select the drawing view and measurement. +`cylinder` identifies one bounded cylindrical face, `plane` uses a point on the trimmed face and a +normal, and `circle` uses a center, axis and radius. Dimensions and optional presentation requirements +such as a fit or tolerance come from explicit inputs. The planner checks the measured value against +the evaluated notebook value and reports each parameter's status. The [stepped mount example](../../../../examples/dxf_exporter/) +shows an override and an independent replay. + +Auto mode selects the ordinary exact hidden-line method for most parts. For spline-heavy profiles, +install `simplecadapi[drawing,verify]` to use polygonal review views with the original B-Rep envelope +dimensions. Check the reported method. Use `--hlr exact` when the output needs analytic contours in +all views, or `--hlr polygonal` to explicitly request the review path. + Produce a GB-standard engineering drawing sheet set (DXF + PNG) from an already-validated part or product. This is a preliminary workflow; drawing is an output stage, so geometry must be final before entry. Layout follows the diff --git a/examples/README.md b/examples/README.md index aac6e796..355db72f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -4,6 +4,9 @@ Every example is a self-contained folder: the model notebooks, the plain modules they import, export and verification scripts, and fresh artifacts in its own `out/` folder (`examples//out/`, ignored by git). +[Single-part drawing](dxf_exporter/README.md) shows automatic STEP drafting and +geometry-checked notebook dimensions on a stepped mounting plate. + ## How an example is laid out - **Part notebooks** (`.py`): one marimo notebook per part, one FTC diff --git a/examples/dxf_exporter/README.md b/examples/dxf_exporter/README.md new file mode 100644 index 00000000..951dde9c --- /dev/null +++ b/examples/dxf_exporter/README.md @@ -0,0 +1,32 @@ +# Single-part DXF drawing + +Install `simplecadapi[drawing]`. Use `simplecadapi[drawing,verify]` for the +optional polygonal hidden-line projection on spline-heavy geometry. + +```sh +sca drawing --notebook examples/dxf_exporter/stepped_mount.py \ + --primary-view top --no-section --sheet A3 \ + --out examples/dxf_exporter/out/base.dxf +sca drawing --notebook examples/dxf_exporter/stepped_mount.py \ + --set HOLE_DIAMETER=8 --set HOLE_PITCH=36 \ + --primary-view top --no-section --sheet A3 \ + --out examples/dxf_exporter/out/variant.dxf +sca drawing --step examples/dxf_exporter/out/variant.model.step \ + --mode engineering --drawing-json examples/dxf_exporter/out/variant.drawing.json \ + --out examples/dxf_exporter/out/replay.dxf --pdf +``` + +The base drawing carries a 31 mm spacing, a diameter 6 H7 hole and an 8 mm +ledge with +0.10/-0.05 deviations. The variant changes the first two marks to +36 mm and diameter 8 H7. Verify the named parameters, measurements and unbound +construction variables in `design_intent` inside each `*.plan.json`. + +The notebook gives geometric selectors for two cylinder axes and two planar +faces. The SDK derives the actual values from geometry and reads the native DXF +dimensions back. The notebook supplies the expected values and requirements. +Changing only the expected pitch blocks a new DXF export. + +For STEP without a notebook, `sca drawing --step part.step --out part.dxf` +proposes the drawing, and `--plan-only` exposes the plan for agent review. +`--templates` lists metric single-part drafting presets and review prompts. +See [the drawing workflow](../../docs/skill/references/workflows/engineering-drawing.md). diff --git a/examples/dxf_exporter/stepped_mount.py b/examples/dxf_exporter/stepped_mount.py new file mode 100644 index 00000000..1a820ff6 --- /dev/null +++ b/examples/dxf_exporter/stepped_mount.py @@ -0,0 +1,111 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["simplecadapi==2.3.0.post1"] +# [tool.simplecadapi] +# id = "stepped-mount" +# kind = "part" +# /// + +import marimo + +app = marimo.App() + + +@app.cell +def _(): + import simplecadapi as scad + + return (scad,) + + +@app.cell +def _(scad): + # ---- params: hole pattern ---- + HOLE_DIAMETER = scad.var("hole_diameter", 6.0, unit="mm") + HOLE_PITCH = scad.var("hole_pitch", 31.0, unit="mm") + return HOLE_DIAMETER, HOLE_PITCH + + +@app.cell +def _(scad): + # ---- params: ledge ---- + LEDGE_THICKNESS = scad.var( + "ledge_thickness", 8.0, unit="mm", tolerance=(-0.05, 0.10) + ) + TOOL_CLEARANCE = 4.0 + return LEDGE_THICKNESS, TOOL_CLEARANCE + + +@app.cell +def _(HOLE_DIAMETER, HOLE_PITCH, LEDGE_THICKNESS, TOOL_CLEARANCE, scad): + blank = scad.make_box_rsolid(width=80, height=50, depth=12) + cutter = scad.make_box_rsolid( + width=24, height=52, depth=12, bottom_face_center=(32, 0, LEDGE_THICKNESS) + ) + body = scad.cut_rsolid(blank, cutter, on_split="error") + for x in (-23, -23 + HOLE_PITCH): + tool = scad.make_cylinder_rsolid( + radius=HOLE_DIAMETER / 2, + height=12 + 2 * TOOL_CLEARANCE, + bottom_face_center=(x, 3, -TOOL_CLEARANCE), + ) + body = scad.cut_rsolid(body, tool, on_split="error") + part = scad.make_part_rpart(part_id=scad.notebook_id(), body=body) + return (part,) + + +@app.cell +def _(HOLE_DIAMETER, HOLE_PITCH, LEDGE_THICKNESS): + hole_a = { + "cylinder": { + "axis_point": [-23, 3, 6], + "axis": [0, 0, 1], + "radius_mm": float(HOLE_DIAMETER) / 2, + } + } + hole_b = { + "cylinder": { + "axis_point": [-23 + float(HOLE_PITCH), 3, 6], + "axis": [0, 0, 1], + "radius_mm": float(HOLE_DIAMETER) / 2, + } + } + lower_plane = {"plane": {"point": [30, 0, 0], "normal": [0, 0, 1]}} + ledge_plane = { + "plane": {"point": [30, 0, float(LEDGE_THICKNESS)], "normal": [0, 0, 1]} + } + DRAWING_INTENT = { + "dimensions": [ + { + "parameter": "HOLE_DIAMETER", + "view": "front", + "semantic": "diameter", + "of": hole_a, + "fit": "H7", + "at": 155, + "out": 12, + }, + { + "parameter": "HOLE_PITCH", + "view": "front", + "semantic": "linear", + "between": [hole_a, hole_b], + "axis": "x", + "side": "top", + }, + { + "parameter": "LEDGE_THICKNESS", + "view": "top", + "semantic": "linear", + "between": [lower_plane, ledge_plane], + "axis": "y", + "side": "right", + "use_parameter_tolerance": True, + }, + ], + } + return (DRAWING_INTENT,) + + +if __name__ == "__main__": + app.run() diff --git a/pyproject.toml b/pyproject.toml index 486708c5..86551a90 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,7 @@ editor = [ # simplecadapi.inspect.brep is part of the default install; this extra is kept empty so that # `pip install "simplecadapi[inspect]"` from older instructions still works. inspect = [] -# Verifier scripts measure models with OCP; the SDK itself never imports it (simplecadapi.verify bridges the two). +# Verification and the optional polygonal drawing projection import OCP on demand. # The build without VTK (same `OCP` import, no 100 MB VTK) and the OCCT generation the SDK ships (7.9): OCP 8 renames # the casts and changes signatures. verify = [ @@ -102,6 +102,8 @@ sdist.include = [ "/src/simplecadapi/editor/webui", "/skillproj.toml", "/docs/skill", + "/examples/dxf_exporter/README.md", + "/examples/dxf_exporter/stepped_mount.py", "/examples/u_link_motor_mount/u_link.py", "/examples/u_link_motor_mount/shell.py", "/examples/u_link_motor_mount/u_link_motor_mount.py", diff --git a/src/simplecadapi/cli.py b/src/simplecadapi/cli.py index e10bc6d8..793f2e3e 100644 --- a/src/simplecadapi/cli.py +++ b/src/simplecadapi/cli.py @@ -7,6 +7,7 @@ sca addon add|update|remove|list|use sca skill targets|where|install sca export [--format ...] + sca drawing --step part.step --out part.dxf sca run [--set NAME=VALUE] [--out ...] sca ls [DIR] | sca params sca ops [NAME] [--json] # every SDK operation and what its parameters mean @@ -37,6 +38,7 @@ def build_parser() -> argparse.ArgumentParser: from . import catalog as catalog_cli from .addon import cli as addon_cli from .editor import cli as editor_cli + from .dxf_engine.workflow import cli as drawing_cli from .example import cli as example_cli from .exporter import cli as exporter_cli from .runtime import cli as runtime_cli @@ -53,6 +55,7 @@ def build_parser() -> argparse.ArgumentParser: subparsers = parser.add_subparsers(dest="group", required=True) addon_cli.configure(subparsers) catalog_cli.configure(subparsers) + drawing_cli.configure(subparsers) editor_cli.configure(subparsers) example_cli.configure(subparsers) exporter_cli.configure(subparsers) diff --git a/src/simplecadapi/dxf_engine/planner.py b/src/simplecadapi/dxf_engine/planner.py index 8b8520c0..f1052096 100644 --- a/src/simplecadapi/dxf_engine/planner.py +++ b/src/simplecadapi/dxf_engine/planner.py @@ -115,12 +115,16 @@ def _reg_seg(self, key, p, q): self.segments.append((key, p, q)) # ---------- views ---------- + def _build_view(self, view): + """Project one declared view. Higher-level workflows may cache this step.""" + return _views.build_view(view) + def _solve_views(self): d = self.d if d.front not in self.by_name: raise ValueError(f"front={d.front!r} is not one of the declared views {sorted(self.by_name)}") order = [d.front] + [v.name for v in d.views if v.name != d.front] - built = {name: _views.build_view(self.by_name[name]) for name in order} + built = {name: self._build_view(self.by_name[name]) for name in order} lay = {name: (built[name]["lbox"], self.by_name[name].align) for name in order} if self.s is None: self.s = _sheet.choose_scale(lay, d.front, self.fmt) @@ -140,7 +144,7 @@ def _solve_views(self): for _ad, pts, _vis in b["edges"]: sh = [(p[0] * s + ox, p[1] * s + oy) for p in pts] pairs.extend(zip(sh, sh[1:])) - self.views[name] = {"ox": ox, "oy": oy, + self.views[name] = {**b, "ox": ox, "oy": oy, "bbox": Box(ox + lb[0] * s, oy + lb[1] * s, ox + lb[2] * s, oy + lb[3] * s), "edges": b["edges"], "pairs": pairs, "lbox": lb, "hatch": b["hatch"], "frame": b["frame"], diff --git a/src/simplecadapi/dxf_engine/render.py b/src/simplecadapi/dxf_engine/render.py index 3d36b53d..5fa60e31 100644 --- a/src/simplecadapi/dxf_engine/render.py +++ b/src/simplecadapi/dxf_engine/render.py @@ -327,18 +327,8 @@ def verify_dxf(plan, dxf_path, handles): return out -def render_plan(plan, dxf_path, png_path): - """Render the solved SheetPlan as a GB-layer DXF + PNG pair, then read the DXF back and verify its dimensions. - - The DXF goes through ezdxf (GB layers 01_THICK_SOLID/08_DASHED/05_CENTER/DIMENSION/TEXT, native DIMENSION - entities in style "GB"); the PNG is produced from the DXF through PyMuPdf for multimodal cross-checking. - Returns {"dxf", "png", "entities", "dimensions", "issues"}; the issues also enter `plan.issues()` and `report()`. - """ - t0 = time.time() - dxf_path, png_path = Path(dxf_path), Path(png_path) # a str path is as good as a Path - import matplotlib - matplotlib.use("Agg") - +def build_dxf(plan): + """Build the editable vector drawing and return it with dimension handles.""" doc = ezdxf.new("R2010", setup=True) doc.header["$INSUNITS"] = 4 doc.header["$LWDISPLAY"] = 1 @@ -372,7 +362,17 @@ def render_plan(plan, dxf_path, png_path): _sheet.draw_frame(msp, plan) _sheet.draw_notes(msp, plan) _render_general_rough(msp, plan) + return doc, handles + + +def render_plan(plan, dxf_path, png_path): + """Render the solved SheetPlan as a GB-layer DXF + PNG pair and verify it.""" + t0 = time.time() + dxf_path, png_path = Path(dxf_path), Path(png_path) + import matplotlib + matplotlib.use("Agg") + doc, handles = build_dxf(plan) doc.saveas(dxf_path) plan.render_issues = verify_dxf(plan, dxf_path, handles) chk = ezdxf.readfile(dxf_path) diff --git a/src/simplecadapi/dxf_engine/workflow/__init__.py b/src/simplecadapi/dxf_engine/workflow/__init__.py new file mode 100644 index 00000000..ebb12231 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/__init__.py @@ -0,0 +1 @@ +"""Optional single-part drawing workflows built on the declarative engine.""" diff --git a/src/simplecadapi/dxf_engine/workflow/auto.py b/src/simplecadapi/dxf_engine/workflow/auto.py new file mode 100644 index 00000000..8aa78f67 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/auto.py @@ -0,0 +1,710 @@ +"""Propose a reviewable engineering drawing from a single STEP solid.""" + +from __future__ import annotations + +import hashlib +import json +import math +from importlib.metadata import version +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from tempfile import TemporaryDirectory + +import numpy as np +from simplecadapi._cpp.occt.BRepAdaptor import BRepAdaptor_Surface +from simplecadapi._cpp.occt.GeomAbs import GeomAbs_Circle, GeomAbs_Cylinder +from simplecadapi._cpp.occt.TopAbs import TopAbs_REVERSED +from simplecadapi.dxf_engine import ViewDecl +from simplecadapi.dxf_engine.refs import project, view_frame +from simplecadapi.dxf_engine.views import BIG, _cut_near_half, _section_loops +from simplecadapi.inspect import brep +from simplecadapi.inspect.brep.model import _bounding_box + +from .declaration import ( + apply_drawing_action, + build_plan, + load_engineering_shape, + write_engineering_sheet, +) +from .projection import ( + DrawingProjection, + MESH_DEFLECTION_MM, + physical_shape, + projection_mode, +) +from .inspection import frames + +SHEETS = ("A4", "A3", "A2", "A1", "A0") +ORTHOGRAPHIC_FRAMES = tuple(name for name in frames() if name != "iso") +ALGORITHM = "1.1.0" + + +@dataclass(frozen=True) +class Bore: + entity: str + center: tuple[float, float, float] + axis: tuple[float, float, float] + radius: float + length: float + + +def find_bores(model, faces): + bores, unresolved = [], [] + for face in faces: + surface = BRepAdaptor_Surface(face) + if ( + surface.GetType() != GeomAbs_Cylinder + or face.Orientation() != TopAbs_REVERSED + ): + continue + cylinder = surface.Cylinder() + first, last = surface.FirstVParameter(), surface.LastVParameter() + sweep = surface.LastUParameter() - surface.FirstUParameter() + entity = model.id_for_shape("face", face) + if sweep < math.tau - 1e-5 or last - first < 1e-6: + unresolved.append(entity) + continue + axis = cylinder.Axis().Direction().Coord() + center = tuple( + x + (first + last) / 2 * d + for x, d in zip(cylinder.Location().Coord(), axis) + ) + bores.append(Bore(entity, center, axis, cylinder.Radius(), last - first)) + return bores, unresolved + + +def visible_bores(view, bores): + """Require an end-on cylindrical face and matching visible HLR circle/arc evidence.""" + circles = [] + for adaptor, _, visible in view["edges"]: + if visible and adaptor.GetType() == GeomAbs_Circle: + circle = adaptor.Circle() + circles.append((circle.Location().Coord()[:2], circle.Radius())) + result = [] + for bore in bores: + if abs(np.dot(bore.axis, view["frame"][2])) < 1 - 1e-8: + continue + center = project(bore.center, view["frame"]) + tolerance = max(1e-5, min(0.025, bore.radius * 0.02)) + if any( + abs(radius - bore.radius) <= tolerance + and math.dist(center, point) <= tolerance + for point, radius in circles + ): + result.append((bore, center)) + return result + + +def choose_views(projector, bores, primary, projection, layout): + observations = [] + for name, basis in frames().items(): + if name == "iso": + continue + n, right = tuple(basis["projector_normal"]), tuple(basis["right"]) + view = projector.view(ViewDecl(name, projector.shape, n, right)) + x0, y0, x1, y1 = view["lbox"] + width, height = x1 - x0, y1 - y0 + hidden = math.fsum( + math.dist(a, b) + for _, pts, visible in view["edges"] + if not visible + for a, b in zip(pts, pts[1:]) + ) + total = math.fsum( + math.dist(a, b) for _, pts, _ in view["edges"] for a, b in zip(pts, pts[1:]) + ) + observations.append( + dict( + frame=name, + normal=n, + right=right, + area_mm2=width * height, + bounds_mm=view["lbox"], + visible_bores=len(visible_bores(view, bores)), + visible_fraction=1 - hidden / total if total else 0.0, + ) + ) + max_area = max(o["area_mm2"] for o in observations) + for o in observations: + # Round the score so tiny kernel noise cannot change an otherwise tied ordering. + o["score"] = round( + 2 * o["visible_bores"] + + 2 * o["area_mm2"] / max_area + + o["visible_fraction"], + 6, + ) + observations.sort(key=lambda o: -o["score"]) + selected = ( + next(o for o in observations if o["frame"] == primary) + if primary + else observations[0] + ) + x0, y0, x1, y1 = selected["bounds_mm"] + longitudinal = y1 - y0 > 1.6 * (x1 - x0) + r, u, n = view_frame(selected["normal"], selected["right"]) + if longitudinal: + r, u = u, tuple(-component for component in r) + vertical, horizontal = ( + ("below", "left") if projection == "first" else ("above", "right") + ) + gap = 24 if layout == "compact" else 30 + views = [ + dict(name="front", normal=n, right=r), + dict( + name="top", + normal=u, + right=r, + align=dict(to="front", side=vertical, gap=gap), + ), + dict( + name="right", + normal=r, + right=tuple(-v for v in n), + align=dict(to="front", side=horizontal, gap=gap + 2), + ), + ] + decision = dict( + primary_source_frame=selected["frame"], + forced=primary is not None, + rolled_to_landscape=longitudinal, + rule="Rank six STEP axis views by visible end-on bores, projected area and visible edge fraction.", + candidates=observations, + ) + return views, decision + + +def choose_section(shape, bounds, views, bores): + if max(bounds["size"]) >= BIG: + return None, dict( + status="not_proposed", + reason="Model span exceeds the SDK section cutter range.", + candidates=[], + ) + center = np.array(bounds["center"]) + records = [] + for base in views[1:]: + frame = view_frame(base["normal"], base["right"]) + normal = np.array(frame[2]) + start, end = sorted( + float(normal @ endpoint) for endpoint in (bounds["min"], bounds["max"]) + ) + span = end - start + if span < 1e-6: + continue + parallel_axes = [ + bore for bore in bores if abs(float(normal @ bore.axis)) < 1e-8 + ] + bore_planes = defaultdict(list) + for bore in parallel_axes: + offset = float(normal @ bore.center) + if start + 0.05 * span < offset < end - 0.05 * span: + bore_planes[round(offset, 4)].append(offset) + ordered = sorted( + bore_planes.values(), + key=lambda group: (-len(group), abs(group[0] - (start + end) / 2)), + ) + offsets = [start + fraction * span for fraction in (0.5, 0.25, 0.75)] + [ + group[0] for group in ordered[:2] + ] + offsets = list(dict.fromkeys(round(offset, 6) for offset in offsets)) + for offset in offsets: + point = tuple( + (center + normal * (offset - float(normal @ center))).tolist() + ) + record = dict( + sibling=base["name"], + point_mm=point, + offset_mm=offset, + distance_from_middle_mm=abs(offset - (start + end) / 2), + ) + try: + cut = _cut_near_half(shape, point, frame) + loops = _section_loops(cut, point, frame) + except (ValueError, RuntimeError) as error: + records.append(record | dict(status="cut_failed", reason=str(error))) + continue + axis_hits = [ + b.entity + for b in parallel_axes + if abs(float(normal @ b.center) - offset) < max(0.001, 0.05 * b.radius) + ] + perimeter = math.fsum( + math.dist(a, b) + for loop in loops + for a, b in zip(loop, loop[1:] + loop[:1]) + ) + # A single ordinary hatch loop by itself is also what a rectangular block would show. + useful = bool(loops and (axis_hits or len(loops) > 1)) + records.append( + record + | dict( + status="candidate" if useful else "limited_evidence", + hatch_loops=len(loops), + perimeter_mm=round(perimeter, 4), + bore_axis_refs=axis_hits, + ) + ) + useful = [record for record in records if record["status"] == "candidate"] + if not useful: + return None, dict( + status="not_proposed", + reason="No cut crossed a verified bore axis or produced multiple material boundary loops.", + candidates=records, + ) + picked = max( + useful, + key=lambda row: ( + len(row["bore_axis_refs"]), + row["hatch_loops"], + row["perimeter_mm"], + -row["distance_from_middle_mm"], + ), + ) + base = next(v for v in views if v["name"] == picked["sibling"]) + declaration = dict( + name="section", + normal=base["normal"], + right=base["right"], + align=dict(to=base["name"], side=base["align"]["side"], gap=34), + section=dict(label="A", mark_in="front", point=picked["point_mm"]), + ) + return declaration, dict( + status="proposed", + selected=picked, + candidates=records, + rule="Rank cuts by intersected bore axes, hatch boundary loops, boundary perimeter and centrality.", + ) + + +def propose_dimensions(projector, views, bores, policy): + dims = [] + if policy != "none": + depth = ( + ("top", "y", "right") + if any(row["name"] == "top" for row in views) + else ("right", "x", "top") + ) + for caption, view, axis, side in [ + ("overall width", "front", "x", "top"), + ("overall height", "front", "y", "right"), + ("overall depth", *depth), + ]: + dims.append( + dict( + caption=caption, + kind="overall", + view=view, + semantic="linear", + extent=axis, + side=side, + ) + ) + groups = defaultdict(list) + for bore in bores: + groups[round(2 * bore.radius, 4)].append(bore) + candidates = defaultdict(list) + if policy == "auto": + for row in views: + if "section" in row: + continue + name = row["name"] + drawing = projector.view( + ViewDecl(name, projector.shape, row["normal"], row["right"]) + ) + x0, y0, x1, y1 = drawing["lbox"] + for bore, (x, y) in visible_bores(drawing, bores): + side = "left" if x - x0 < x1 - x else "right" + edge_clearance = min(x - x0, x1 - x) + angles = (200, 160) if side == "left" else (340, 20) + angle = angles[y >= (y0 + y1) / 2] + candidates[round(2 * bore.radius, 4)].append( + (max(0, edge_clearance), name, bore.entity, angle) + ) + coverage = [] + for diameter, group in sorted(groups.items()): + options = sorted(candidates[diameter]) + entry = dict( + diameter_mm=diameter, + model_faces=[bore.entity for bore in group], + visible_options=len(options), + status="not_visible" if policy == "auto" else "disabled_by_policy", + ) + if options: + _, name, entity, angle = options[0] + caption = f"bore diameter {diameter:g}" + entry.update(status="proposed", entity=entity, view=name, caption=caption) + decimals = len(f"{diameter:.4f}".rstrip("0").partition(".")[2]) + dims.append( + dict( + caption=caption, + kind="size", + view=name, + semantic="diameter", + of=dict(entity=entity), + at=angle, + dec=decimals, + ) + ) + coverage.append(entry) + return dims, dict( + policy=policy, + bore_groups=coverage, + rule="Measure three extents and one geometrically verified example per visible bore diameter. No quantity is inferred.", + ) + + +def adjust_diameter_labels(plan, issues): + """Try SDK-validated angle changes only for reported diameter placement issues.""" + warned = set() + for issue in issues: + if issue.severity == "warning": + warned.add(issue.element) + warned.update(issue.data.get("with", [])) + actions = [] + for resolved in plan.resolved: + if ( + resolved.kind != "dim" + or resolved.draw.get("kind") != "dia-man" + or f"dim:{resolved.name}" not in warned + ): + continue + initial = resolved.draw["at"] + angles = sorted( + (0, 15, 30, 45, 135, 150, 165, 180, 195, 210, 225, 315, 330, 345), + key=lambda angle: abs((angle - initial + 180) % 360 - 180), + ) + proposals = ( + dict(op="dia", name=resolved.name, at=angle, extend_mm=extension) + for extension in (6, 12, 20) + for angle in angles + ) + accepted = next( + ( + action + for action in proposals + if apply_drawing_action(plan, action)["ok"] + ), + None, + ) + if accepted: + actions.append(accepted) + return actions + + +def fit_sheet(shape, spec, sheet, preferred_scale, projector): + attempts = [] + best = None + for fmt in (sheet,) if sheet else SHEETS: + for gap_delta in (0, 8): + # Freeze the actual per-view gaps and sheet scale for replay. + trial_views = [ + v | {"align": v["align"] | {"gap": v["align"]["gap"] + gap_delta}} + if "align" in v + else v + for v in spec["views"] + ] + declaration = spec | dict( + sheet=spec["sheet"] | dict(sheet=fmt), views=trial_views + ) + try: + plan = build_plan( + shape, declaration, spec["sheet"]["title"], projector=projector + ) + except (ValueError, RuntimeError) as error: + attempts.append( + dict(sheet=fmt, gap_delta_mm=gap_delta, error=str(error)) + ) + continue + issues = plan.issues() + actions = ( + adjust_diameter_labels(plan, issues) + if plan.s >= preferred_scale + else [] + ) + if actions: + declaration["actions"] = actions + issues = plan.issues() + errors = sum(i.severity == "error" for i in issues) + warnings = [ + i.code + for i in issues + if i.severity == "warning" and i.code != "UNDIMENSIONED_CYLINDER" + ] + unreadable = plan.s < preferred_scale + outside = warnings.count("OUTSIDE_FRAME") + warnings.count( + "IN_KEEPOUT_ZONE" + ) + score = ( + errors, + outside, + unreadable, + len(warnings), + SHEETS.index(fmt), + -plan.s, + gap_delta, + ) + attempts.append( + dict( + sheet=fmt, + gap_delta_mm=gap_delta, + scale=plan.s, + errors=errors, + layout_warnings=warnings, + meets_preferred_scale=not unreadable, + actions=actions, + ) + ) + if best is None or score < best[0]: + best = (score, declaration, plan, len(attempts) - 1) + if errors == 0 and not warnings and (plan.s >= preferred_scale or sheet): + break + if best and best[0][:4] == (0, 0, False, 0): + break + if best is None: + reasons = dict.fromkeys(row["error"] for row in attempts) + raise ValueError( + "No sheet with resolved drawing geometry: " + " | ".join(reasons) + ) + _, declaration, plan, index = best + declaration["sheet"]["scale"] = plan.s + return ( + declaration, + plan, + dict( + preferred_scale=preferred_scale, + selected_attempt=index, + attempts=attempts, + rule="Prefer valid placement inside the sheet, then readable scale, fewer warning conflicts and the smaller sheet.", + ), + ) + + +def auto_drawing( + step, + output, + *, + primary=None, + sheet=None, + section=True, + dimensions="auto", + projection=None, + layout=None, + section_view=None, + template=None, + plan_only=False, + transform=None, + pdf=False, + hlr="auto", + design_intent=None, +): + step, output = Path(step).resolve(), Path(output).resolve() + if output.suffix.lower() != ".dxf": + raise ValueError("Automatic drawing output must have a .dxf extension") + if primary not in (*ORTHOGRAPHIC_FRAMES, None) or sheet not in (*SHEETS, None): + raise ValueError("Unknown primary view or sheet format") + if dimensions not in ("auto", "overall", "none"): + raise ValueError("dimensions must be auto, overall or none") + entry = None + if template: + from .inspection import drawing_templates + + entry = drawing_templates()["templates"].get(template) + if entry is None: + raise ValueError( + f"Unknown drawing template {template!r}; use --templates to list choices" + ) + defaults = entry["options"] if entry else {} + projection_label = projection or defaults.get("projection") + projection = projection_label or "first" + layout_preset = layout or defaults.get("layout", "aligned") + section_view = section_view or defaults.get("section_view", "full") + if ( + projection not in ("first", "third") + or layout_preset not in ("aligned", "compact") + or section_view not in ("full", "removed") + ): + raise ValueError("Invalid projection, layout preset or section kind") + shape = load_engineering_shape(step, transform) + model = brep.index_shape_rbrepmodel(shape=shape) + if len(model.bodies) != 1: + raise ValueError( + f"Automatic engineering drawing requires one solid; found {len(model.bodies)}. Use a part STEP or declare views manually." + ) + solid = physical_shape(shape, model) + solid_model = brep.index_shape_rbrepmodel(shape=solid) + recommended, complexity = projection_mode(solid_model) + if hlr not in ("auto", "exact", "polygonal"): + raise ValueError("Unknown HLR mode") + mode = recommended if hlr == "auto" else hlr + projector = DrawingProjection(solid, mode, MESH_DEFLECTION_MM) + bounds = _bounding_box(solid) + bores, unresolved = find_bores(model, solid_model.faces) + views, view_decision = choose_views( + projector, bores, primary, projection, layout_preset + ) + if section and mode == "exact": + cut, section_decision = choose_section(solid, bounds, views, bores) + else: + cut, section_decision = ( + None, + dict( + status="deferred_for_polygonal_review" + if section + else "disabled_by_option", + candidates=[], + ), + ) + if cut: + cut["section"]["kind"] = section_view + sibling = section_decision["selected"]["sibling"] + if layout_preset == "compact" and section_view == "full": + index = next(i for i, row in enumerate(views) if row["name"] == sibling) + cut["align"] = views[index]["align"].copy() + # The section is that view, cut: it keeps the view's name so dimensions and datums + # declared on it (notebook design intent included) still resolve. + cut["name"] = sibling + views[index] = cut + section_decision["replaces_view"] = sibling + else: + views.append(cut) + dims, coverage = propose_dimensions(projector, views, bores, dimensions) + coverage["unresolved_partial_inner_cylinders"] = unresolved + source_name = ( + design_intent["source"]["product_id"] + if design_intent is not None + else step.stem + ) + number, _, name = source_name.partition("_") + title = name if number.isdecimal() and name else source_name + spec = dict( + sheet=dict( + title=title.replace("_", " "), + dwg_no=number if number.isdecimal() else "", + front="front", + scale=None, + ), + views=views, + dimensions=dims, + ) + if design_intent is not None: + intent_dims = design_intent["dimensions"] + intent_extents = { + (d["view"], d["extent"]) for d in intent_dims if "extent" in d + } + spec["dimensions"] = [ + d for d in dims if (d["view"], d.get("extent")) not in intent_extents + ] + intent_dims + spec["datums"] = design_intent["datums"] + spec["design_intent"] = {k: design_intent[k] for k in ("source", "parameters")} + if mode != "exact": + spec["hlr"] = mode + spec["sheet"]["notes"] = ["TESSELLATED REVIEW VIEWS", "VERIFY THREAD CALLOUTS"] + if projection_label: + spec["sheet"]["projection"] = projection_label + preferred_scale = 1.0 if max(bounds["size"]) <= 500 else 0.5 + spec, plan, layout = fit_sheet(shape, spec, sheet, preferred_scale, projector) + issues = [issue.as_dict() for issue in plan.issues()] + coverage["measured"] = [ + dict(caption=dim.caption, view=dim.view, value_mm=dim._measured) + for dim in plan.dims + ] + status = ( + "needs_revision" + if any(issue["severity"] == "error" for issue in issues) + else "review_required" + ) + spec_path, report_path = ( + output.with_suffix(".drawing.json"), + output.with_suffix(".plan.json"), + ) + report = dict( + schema_version=1, + algorithm_version=ALGORITHM, + sdk_version=version("simplecadapi"), + status=status, + source=dict( + step=str(step), + sha256=hashlib.sha256(step.read_bytes()).hexdigest(), + transform=transform, + ), + options=dict( + primary_view=primary, + sheet=sheet, + section=section, + section_view=section_view, + dimensions=dimensions, + projection=projection, + layout=layout_preset, + ), + declaration=str(spec_path), + view_selection=view_decision, + section=section_decision, + hlr=dict( + requested=hlr, + mode=mode, + recommended=recommended, + complexity=complexity, + mesh_deflection_mm=MESH_DEFLECTION_MM if mode == "polygonal" else None, + representation="solid-only", + projection_bounds=plan.projection_bounds(), + ), + dimensions=coverage, + layout=layout, + issues=issues, + review=[ + "Confirm the primary view, section and dimension scheme against design intent.", + "Supply any needed datums, fits, tolerances, thread and hole-depth semantics explicitly.", + "Regenerate proposals for a new STEP revision before reusing model entity IDs.", + ], + ) + if entry: + report["template"] = dict(id=template, **entry) + if plan.design_intent is not None: + report["design_intent"] = plan.design_intent + output.parent.mkdir(parents=True, exist_ok=True) + result = dict( + status=status, + declaration=str(spec_path), + plan=str(report_path), + sheet=plan.fmt.name, + scale=plan.s, + views=list(plan.views), + dimension_count=len(plan.dims), + ) + render_error = None + if not plan_only and status != "needs_revision": + try: + metadata = write_engineering_sheet( + step, output, spec, plan, transform=transform, pdf=pdf + ) + except Exception as error: + # The declaration and the plan are still written below: they are what the + # reviewer edits and replays after a rendering failure. + render_error = error + report["render"] = {"error": str(error)} + else: + report["issues"] = metadata["issues"] + result.update( + dxf=str(output), + preview=str(output.with_suffix(".png")), + audit=metadata["reopen_audit"], + ) + if pdf: + result["pdf"] = metadata["output_pdf"] + report["render"] = { + key: result[key] + for key in ("dxf", "preview", "pdf", "audit") + if key in result + } + with TemporaryDirectory(dir=output.parent) as folder: + for path, data in ((spec_path, spec), (report_path, report)): + staged = Path(folder) / path.name + staged.write_text( + json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False), + encoding="utf-8", + ) + staged.replace(path) + if render_error is not None: + raise render_error + return result diff --git a/src/simplecadapi/dxf_engine/workflow/cli.py b/src/simplecadapi/dxf_engine/workflow/cli.py new file mode 100644 index 00000000..562c2f96 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/cli.py @@ -0,0 +1,227 @@ +"""Command-line entry for the single-part drawing workflow.""" + +from contextlib import redirect_stdout +import json +from pathlib import Path +import sys + + +def configure(subparsers): + parser = subparsers.add_parser( + "drawing", help="Plan or export a single-part DXF drawing" + ) + source = parser.add_mutually_exclusive_group() + source.add_argument("--step", type=Path, help="Single-part STEP") + source.add_argument( + "--notebook", type=Path, help="Run a trusted SimpleCADAPI part notebook" + ) + parser.add_argument("--out", type=Path, help="Output .dxf path") + parser.add_argument( + "--mode", choices=("auto", "engineering", "inspection"), default="auto" + ) + parser.add_argument( + "--templates", action="store_true", help="List drafting templates" + ) + parser.add_argument( + "--drawing-json", type=Path, help="Replay a declarative engineering drawing" + ) + parser.add_argument("--template", help="Drafting template ID") + parser.add_argument( + "--set", + action="append", + default=[], + metavar="NAME=VALUE", + help="Notebook parameter override", + ) + parser.add_argument( + "--plan-only", action="store_true", help="Write the plan and declaration only" + ) + parser.add_argument( + "--pdf", action="store_true", help="Also write a true-scale vector PDF" + ) + parser.add_argument("--sheet", choices=("A4", "A3", "A2", "A1", "A0")) + parser.add_argument("--projection", choices=("first", "third")) + parser.add_argument("--layout", choices=("aligned", "compact")) + parser.add_argument("--no-section", action="store_true") + parser.add_argument("--section-view", choices=("full", "removed")) + parser.add_argument( + "--primary-view", choices=("front", "rear", "top", "bottom", "left", "right") + ) + parser.add_argument("--dimensions", choices=("auto", "overall", "none")) + parser.add_argument( + "--hlr", + choices=("auto", "exact", "polygonal"), + help="Polygonal HLR requires the verify extra", + ) + parser.add_argument( + "--layout-json", type=Path, help="Shared seven-view inspection layout" + ) + parser.add_argument( + "--transform-json", type=Path, help="Explicit rigid placement of a STEP" + ) + parser.add_argument( + "--deflection", type=float, help="Inspection curve chordal deflection in mm" + ) + parser.set_defaults(handler=handle, printer=print_json) + + +def print_json(report): + print(json.dumps(report, ensure_ascii=True, allow_nan=False)) + + +def _read(path): + return json.loads(path.read_text(encoding="utf-8-sig")) if path else None + + +def _validate(args): + if ( + args.out is None + or args.out.suffix.lower() != ".dxf" + or not (args.step or args.notebook) + ): + raise ValueError("Use --step or --notebook with --out ") + reserved = { + args.out.resolve().with_suffix(ext) + for ext in ( + ".dxf", + ".png", + ".svg", + ".pdf", + ".json", + ".txt", + ".drawing.json", + ".plan.json", + ".model.step", + ) + } + if any( + p and p.resolve() in reserved + for p in ( + args.step, + args.notebook, + args.drawing_json, + args.transform_json, + args.layout_json, + ) + ): + raise ValueError("Choose an output stem distinct from the inputs") + if args.set and not args.notebook: + raise ValueError("--set requires --notebook") + if args.notebook and (args.mode != "auto" or args.transform_json): + raise ValueError("--notebook requires auto mode and uses notebook coordinates") + if args.plan_only and args.pdf: + raise ValueError("--plan-only cannot emit PDF") + if args.mode != "auto" and any( + ( + args.plan_only, + args.template, + args.sheet, + args.primary_view, + args.dimensions, + args.layout, + args.section_view, + args.hlr, + args.no_section, + ) + ): + raise ValueError("Automatic drawing options require --mode auto") + if args.mode != "inspection" and (args.layout_json or args.deflection is not None): + raise ValueError( + "Shared layout and deflection options require --mode inspection" + ) + if args.mode == "engineering" and (not args.drawing_json or args.projection): + raise ValueError( + "Engineering mode requires --drawing-json and reads projection from the declaration" + ) + if args.mode != "engineering" and args.drawing_json: + raise ValueError("--drawing-json requires --mode engineering") + if args.mode == "inspection" and args.pdf: + raise ValueError("--pdf requires an engineering drawing mode") + + +def handle(args): + try: + from .inspection import drawing_templates + + if args.templates: + return drawing_templates(), 0 + _validate(args) + with redirect_stdout(sys.stderr): + result = _draw(args) + except (ImportError, OSError, RuntimeError, TypeError, ValueError) as exc: + return {"status": "error", "error": str(exc)}, 2 + return result, int(result.get("status") == "needs_revision" and not args.plan_only) + + +def _draw(args): + transform = _read(args.transform_json) + if args.mode == "inspection": + from .inspection import export_sheet, project_step + + project = project_step( + args.step, + transform=transform, + deflection=0.03 if args.deflection is None else args.deflection, + ) + result = export_sheet( + project, + args.out, + layout=_read(args.layout_json), + projection=args.projection or "first", + ) + return { + "dxf": str(args.out.resolve()), + "views": len(project["views"]), + "audit": result["reopen_audit"], + } + if args.mode == "engineering": + from .declaration import export_engineering_sheet + + meta = export_engineering_sheet( + args.step, + args.out, + _read(args.drawing_json), + transform=transform, + pdf=args.pdf, + ) + return { + "dxf": meta["output_dxf"], + "views": meta["views"], + "dimensions": meta["dimensions"], + "issues": meta["issues"], + "audit": meta["reopen_audit"], + } + + from .auto import auto_drawing + + step, intent = args.step, None + if args.notebook: + from .notebook import overrides_from_args, prepare_notebook + + step = args.out.resolve().with_suffix(".model.step") + intent = prepare_notebook( + args.notebook.resolve(), step, overrides_from_args(args.set) + ) + dimensions = args.dimensions or ( + "overall" if intent and intent["dimensions"] else "auto" + ) + result = auto_drawing( + step, + args.out, + primary=args.primary_view, + sheet=args.sheet, + section=not args.no_section, + dimensions=dimensions, + projection=args.projection, + layout=args.layout, + section_view=args.section_view, + template=args.template, + plan_only=args.plan_only, + transform=transform, + pdf=args.pdf, + hlr=args.hlr or "auto", + design_intent=intent, + ) + if args.notebook: + result["model_step"] = str(step) + return result diff --git a/src/simplecadapi/dxf_engine/workflow/control_frames.py b/src/simplecadapi/dxf_engine/workflow/control_frames.py new file mode 100644 index 00000000..a0d0994f --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/control_frames.py @@ -0,0 +1,128 @@ +"""Place and draw explicit, single-segment geometric tolerance frames.""" + +from __future__ import annotations + +from decimal import Decimal + +from ezdxf.enums import TextEntityAlignment +from simplecadapi.dxf_engine.collide import conflicts + + +SYMBOLS = { + "flatness": (((-1.7, -0.8), (1.0, -0.8), (1.7, 0.8), (-1.0, 0.8), (-1.7, -0.8)),), + "parallelism": (((-1.6, -1), (-0.3, 1)), ((0.3, -1), (1.6, 1))), + "perpendicularity": (((0, 1.2), (0, -1.1)), ((-1.6, -1.1), (1.6, -1.1))), + "position": (((-1.8, 0), (1.8, 0)), ((0, -1.8), (0, 1.8))), +} + + +def place_control_frames(plan, declarations): + placed = [] + for row in declarations: + value = format(Decimal(str(row["value"])).normalize(), "f") + cells = [ + 7.0, + max(10.0, 2.5 * len(value) + (7 if row["diameter_zone"] else 3)), + ] + [7.0] * len(row["datums"]) + width, height = sum(cells), 6.0 + anchor = plan.tx(row["view"], row["anchor"]) + dx, dy = row["offset"] + offsets = [(dx, dy), (-dx, dy), (dx, -dy), (-dx, -dy)] + problems = set() + key = f"fcf:{row['name']}" + for xoff, yoff in offsets: + x = anchor[0] + xoff - (width if xoff < 0 else 0) + y = anchor[1] + yoff - height / 2 + center = (x + width / 2, y + height / 2) + knee = (anchor[0], center[1]) + join = (x + (width if xoff < 0 else 0), center[1]) + segments = [(anchor, knee), (knee, join)] + hits = conflicts( + plan, key, row["view"], *center, width, height, 0, segments + ) + # The boxed control frame should stay completely outside the view it annotates. + if plan._obb_sat( + *center, width, height, 0, plan.views[row["view"]]["bbox"].inflate(0.5) + ): + problems.add(f"view:{row['view']}") + continue + if hits: + problems.update(hit["id"] for hit in hits) + continue + plan.text_obbs.append((key, *center, width, height, 0)) + for start, end in segments: + plan._reg_seg(key, start, end) + placed.append( + row + | dict( + x=x, + y=y, + height=height, + cells=cells, + display_value=value, + leader=(anchor, knee, join), + ) + ) + break + else: + raise ValueError( + f"Feature control frame {row['name']}: adjust offset to clear {', '.join(sorted(problems))}" + ) + return placed + + +def draw_control_frames(doc, frames): + if not frames: + return False + layer = "FEATURE_CONTROL" + doc.layers.new(layer, dxfattribs={"color": 7, "lineweight": 18}) + msp = doc.modelspace() + attributes = {"layer": layer} + for row in frames: + x, y, height = row["x"], row["y"], row["height"] + end = x + sum(row["cells"]) + msp.add_lwpolyline( + [(x, y), (end, y), (end, y + height), (x, y + height)], + close=True, + dxfattribs=attributes, + ) + anchor, knee, join = row["leader"] + msp.add_lwpolyline([anchor, knee, join], dxfattribs=attributes) + # The first segment is vertical, leaving room for a filled arrow at the witness. + arrow_y = anchor[1] + (2 if knee[1] > anchor[1] else -2) + msp.add_solid( + [anchor, (anchor[0] - 0.65, arrow_y), (anchor[0] + 0.65, arrow_y)], + dxfattribs=attributes, + ) + middle_y = y + height / 2 + symbol_center = (x + row["cells"][0] / 2, middle_y) + for stroke in SYMBOLS[row["characteristic"]]: + msp.add_lwpolyline( + [(symbol_center[0] + dx, symbol_center[1] + dy) for dx, dy in stroke], + dxfattribs=attributes, + ) + if row["characteristic"] == "position": + msp.add_circle(symbol_center, 1.3, dxfattribs=attributes) + + cursor = x + row["cells"][0] + for index, (width, text) in enumerate( + zip(row["cells"][1:], (row["display_value"], *row["datums"]), strict=True) + ): + msp.add_line((cursor, y), (cursor, y + height), dxfattribs=attributes) + middle_x = cursor + width / 2 + if index == 0 and row["diameter_zone"]: + symbol_x = cursor + 2.5 + msp.add_circle((symbol_x, middle_y), 0.95, dxfattribs=attributes) + msp.add_line( + (symbol_x - 1.3, middle_y - 1.3), + (symbol_x + 1.3, middle_y + 1.3), + dxfattribs=attributes, + ) + middle_x += 1.8 + msp.add_text( + text, dxfattribs=attributes | {"height": 2.5, "style": "CJK"} + ).set_placement( + (middle_x, middle_y), align=TextEntityAlignment.MIDDLE_CENTER + ) + cursor += width + return True diff --git a/src/simplecadapi/dxf_engine/workflow/declaration.py b/src/simplecadapi/dxf_engine/workflow/declaration.py new file mode 100644 index 00000000..dcc57004 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/declaration.py @@ -0,0 +1,780 @@ +"""Build and audit a declared engineering drawing from STEP.""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from collections import Counter +from importlib.metadata import version +from pathlib import Path +from tempfile import TemporaryDirectory + +import ezdxf +import numpy as np +from simplecadapi.inspect import brep + +from .inspection import frames, rigid_shape +from .details import place_details, render_print_page, use_diameter_font + + +def validate_intent(plan, declaration): + from simplecadapi.dxf_engine.bind import fmt_number + from simplecadapi.dxf_engine.checks import Issue + + if declaration is None: + return None, [] + measured = {d.caption: d for d in plan.dims} + declared = {d.caption: d for d in plan.d.dims} + parameters, issues = [], [] + for entry in declaration["parameters"]: + linked = [] + for row in entry.get("dimensions", []): + cap, expected = row["caption"], row["expected_mm"] + dim = measured.get(cap) + actual = dim._measured if dim is not None else None + matches = actual is not None and abs(actual - expected) <= 0.001 + # Keeping the declaration, the SDK measurement and the original binding together + # makes removal/edits of a carrier dimension visible on replay. + matches = ( + matches + and entry["name"] in declared[cap].covers + and dim._bound + and fmt_number(actual, dim.dec) == fmt_number(expected, dim.dec) + ) + linked.append(row | dict(measured_mm=actual, matches=matches)) + if not matches: + issues.append( + Issue( + "DESIGN_INTENT_MISMATCH", + "error", + f"dim:{cap}", + f"{entry['name']} expects {expected:g} mm from its bound geometry; got {actual}", + "Correct the model or feature reference, then regenerate the notebook declaration.", + ) + ) + state = ( + ("verified" if all(d["matches"] for d in linked) else "mismatch") + if linked + else entry["status"] + ) + parameters.append(entry | dict(status=state, dimensions=linked)) + return dict(source=declaration["source"], parameters=parameters), issues + + +def fields(value, allowed, label): + if not isinstance(value, dict): + raise ValueError(f"{label} must be a JSON object") + unknown = value.keys() - set(allowed.split()) + if unknown: + raise ValueError(f"{label}: unknown fields {', '.join(sorted(unknown))}") + return value + + +def vector(value, size, label): + if not isinstance(value, (tuple, list)) or len(value) != size: + raise ValueError(f"{label} must have {size} coordinates") + if not all( + isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) + for x in value + ): + raise ValueError(f"{label} must contain finite numbers") + return tuple(float(x) for x in value) + + +def positive(value, label): + (number,) = vector([value], 1, label) + if number <= 0: + raise ValueError(f"{label} must be positive") + return number + + +def view_definition(row, shape, standard_frames): + from simplecadapi.dxf_engine import ViewDecl + + fields(row, "name frame normal right align section auxiliary", "view") + name = row.get("name") + if not isinstance(name, str) or not name.strip(): + raise ValueError("Each view needs a nonempty name") + frame = row.get("frame") + if frame is not None: + if frame not in standard_frames or "normal" in row or "right" in row: + raise ValueError(f"{name}: use one named frame, or normal and right") + normal, right = ( + tuple(standard_frames[frame][key]) for key in ("projector_normal", "right") + ) + else: + normal = vector(row.get("normal"), 3, f"{name}.normal") + right = vector(row.get("right"), 3, f"{name}.right") + if ( + math.hypot(*normal) == 0 + or math.hypot(*right) == 0 + or abs(np.dot(normal, right)) + > 1e-8 * math.hypot(*normal) * math.hypot(*right) + ): + raise ValueError( + f"{name}: normal and right must be nonzero and perpendicular" + ) + normal = tuple(x / math.hypot(*normal) for x in normal) + right = tuple(x / math.hypot(*right) for x in right) + + align = fields(row.get("align", {}), "to side gap", f"{name}.align") + if align and ( + not align.get("to") + or align.get("side", "below") not in ("below", "above", "left", "right") + ): + raise ValueError(f"{name}.align requires a parent and a valid side") + if "gap" in align: + positive(align["gap"], f"{name}.align.gap") + options = {} + if "section" in row: + section = fields(row["section"], "point label mark_in kind", f"{name}.section") + if section.get("kind", "full") not in ("full", "removed"): + raise ValueError(f"{name}.section.kind must be full or removed") + label = section.get("label") + if ( + not isinstance(label, str) + or not label.strip() + or not section.get("mark_in") + ): + raise ValueError( + f"{name}.section requires a label and a mark_in parent view" + ) + options = dict( + section=vector(section.get("point"), 3, f"{name}.section.point"), + label=label, + mark_in=section["mark_in"], + ) + return ViewDecl(name, shape, normal, right, align=align, **options) + + +def cylinder_reference(model, spec): + from simplecadapi._cpp.occt.BRepAdaptor import BRepAdaptor_Surface + from simplecadapi._cpp.occt.GeomAbs import GeomAbs_Cylinder + + fields(spec, "axis_point axis radius_mm tolerance_mm", "cylinder reference") + point = np.array(vector(spec.get("axis_point"), 3, "cylinder.axis_point")) + axis = np.array(vector(spec.get("axis"), 3, "cylinder.axis")) + length = math.hypot(*axis) + if length == 0: + raise ValueError("cylinder.axis must be nonzero") + axis /= length + tol = positive(spec.get("tolerance_mm", 0.01), "cylinder.tolerance_mm") + radius = ( + positive(spec["radius_mm"], "cylinder.radius_mm") + if "radius_mm" in spec + else None + ) + matches = [] + for face in model.faces: + surface = BRepAdaptor_Surface(face) + if surface.GetType() != GeomAbs_Cylinder: + continue + cylinder = surface.Cylinder() + loc = np.array(cylinder.Location().Coord()) + direction = np.array(cylinder.Axis().Direction().Coord()) + offset = point - loc + depth = float(offset @ direction) + if ( + abs(float(axis @ direction)) >= 1 - 1e-8 + and np.linalg.norm(np.cross(offset, direction)) <= tol + and surface.FirstVParameter() - tol + <= depth + <= surface.LastVParameter() + tol + and (radius is None or abs(cylinder.Radius() - radius) <= tol) + ): + matches.append(face) + if len(matches) != 1: + ids = [model.id_for_shape("face", face) for face in matches] + raise ValueError( + f"cylinder reference matches {len(matches)} model faces {ids}; specify a point inside a unique axial span, a radius filter, or an entity ID" + ) + return matches[0] + + +def reference_resolver(shape): + model = None + + def resolve(ref): + nonlocal model + fields(ref, "entity cylinder plane circle", "model reference") + if len(ref) != 1: + raise ValueError( + "A model reference needs one entity ID or a cylinder, plane or circle selector" + ) + if model is None: + model = brep.index_shape_rbrepmodel(shape=shape) + if "entity" in ref: + kind, _, entity = model.resolve_entity(ref["entity"]) + if kind == "body": + raise ValueError("A dimension reference must be a face, edge or vertex") + return kind, entity + if "cylinder" in ref: + return "face", cylinder_reference(model, ref["cylinder"]) + kind = next(iter(ref)) + return analytic_reference(model, kind, ref[kind]) + + return resolve + + +def analytic_reference(model, kind, spec): + from simplecadapi._cpp.occt.BRepAdaptor import ( + BRepAdaptor_Curve, + BRepAdaptor_Surface, + ) + from simplecadapi._cpp.occt.BRepBuilderAPI import BRepBuilderAPI_MakeVertex + from simplecadapi._cpp.occt.BRepExtrema import BRepExtrema_DistShapeShape + from simplecadapi._cpp.occt.GeomAbs import GeomAbs_Circle, GeomAbs_Plane + from simplecadapi._cpp.occt.gp import gp_Pnt + + plane = kind == "plane" + fields( + spec, + "point normal tolerance_mm" if plane else "center axis radius_mm tolerance_mm", + kind, + ) + tol = positive(spec.get("tolerance_mm", 0.001), f"{kind}.tolerance_mm") + point = vector(spec.get("point" if plane else "center"), 3, f"{kind} point") + direction = np.array( + vector(spec.get("normal" if plane else "axis"), 3, f"{kind} direction") + ) + norm = np.linalg.norm(direction) + if norm < 1e-9: + raise ValueError(f"{kind}: select a nonzero direction") + direction /= norm + witness = BRepBuilderAPI_MakeVertex(gp_Pnt(*point)).Vertex() if plane else None + radius = None if plane else positive(spec.get("radius_mm"), "circle.radius_mm") + matches = [] + for entity in model.faces if plane else model.edges: + adaptor = BRepAdaptor_Surface(entity) if plane else BRepAdaptor_Curve(entity) + if adaptor.GetType() != (GeomAbs_Plane if plane else GeomAbs_Circle): + continue + geom = adaptor.Plane() if plane else adaptor.Circle() + if abs(np.dot(direction, geom.Axis().Direction().Coord())) < 1 - 1e-8: + continue + if plane: + distance = BRepExtrema_DistShapeShape(witness, entity) + matched = distance.IsDone() and distance.Value() <= tol + else: + matched = ( + math.dist(geom.Location().Coord(), point) <= tol + and abs(geom.Radius() - radius) <= tol + ) + if matched: + matches.append(entity) + if len(matches) != 1: + raise ValueError( + f"{kind} selector at {point} resolved to {len(matches)} entities, expected one" + ) + return ("face" if plane else "edge"), matches[0] + + +def dimension_declarations(rows, views, resolve): + from simplecadapi.dxf_engine import DimDecl + + dims = [] + names = set() + for row in rows: + values = fields( + row, + "kind view semantic caption value of between axis extent tol fit count at datum side row out dec prefix covers name", + "dimension", + ).copy() + caption = values.get("caption") + if not isinstance(caption, str) or not caption.strip() or caption in names: + raise ValueError("Every dimension needs a unique nonempty caption") + names.add(caption) + if values.get("view") not in views or values.get("kind") not in ( + "overall", + "size", + "position", + ): + raise ValueError( + f"{caption}: specify a declared view and kind overall, size or position" + ) + if values.get("value") is not None: + (values["value"],) = vector([values["value"]], 1, f"{caption}.value") + if values.get("tol") is not None: + values["tol"] = vector(values["tol"], 2, f"{caption}.tol") + if "of" in values: + values["of"] = resolve(values["of"])[1] + if "between" in values: + refs = values["between"] + if not isinstance(refs, list) or len(refs) != 2: + raise ValueError(f"{caption}.between requires two model references") + values["between"] = tuple(resolve(ref)[1] for ref in refs) + dims.append(DimDecl(**values)) + return dims + + +def apply_drawing_action(plan, action): + """Apply an SDK action, with a paper-space extension for outside diameter text.""" + if action.get("op") != "dia" or "extend_mm" not in action: + (result,) = plan.apply([action])["results"] + return result + + from simplecadapi.dxf_engine.agent import _place + from simplecadapi.dxf_engine.dims import dia_geometry, dia_segs + + caption = action.get("name") + dimension = next( + ( + dim + for dim in plan.dims + if dim.caption == caption and dim.semantic == "diameter" + ), + None, + ) + if dimension is None: + raise ValueError(f"Unknown diameter dimension {caption!r}") + extension = positive(action["extend_mm"], "dia.extend_mm") + (angle,) = vector([action.get("at")], 1, "dia.at") + resolved = next( + item for item in plan.resolved if item.kind == "dim" and item.name == caption + ) + geometry = dia_geometry(plan, dimension, angle, "outside", resolved.draw["text"]) + direction = math.cos(math.radians(angle)), math.sin(math.radians(angle)) + + def extend(point): + return tuple(x + extension * d for x, d in zip(point, direction)) + + geometry["anchor"] = extend(geometry["anchor"]) + geometry["insert"] = extend(geometry["insert"]) + start, end = geometry["line"] + geometry["line"] = start, extend(end) + # Preserve circle contacts and measurement. The solver checks the new text and full line before committing. + checked_action = dict(op="dia", name=caption, at=angle) + _, result = _place( + plan, + checked_action, + f"dim:{caption}", + dimension, + geometry, + dia_segs(geometry), + f"at={angle:g}° outside, extend={extension:g} mm", + ) + return result + + +def annotation_declarations(spec, views, resolve): + from simplecadapi.dxf_engine import CenterDecl, DatumDecl, LeaderDecl, RoughDecl + from simplecadapi.dxf_engine.refs import project, view_frame + + def table(key, allowed): + for row in spec.get(key, []): + values = fields(row, allowed, key).copy() + if values.get("view") not in views: + raise ValueError(f"{key} requires a declared view") + yield values + + def anchor(point, view, label): + if isinstance(point, (list, tuple)) and len(point) == 3: + frame = view_frame(views[view].n, views[view].xd) + return project(vector(point, 3, label), frame) + return vector(point, 2, label) + + datums, roughs, leaders, centers = [], [], [], [] + for row in table("datums", "letter kind view at box_off desc"): + row["at"] = anchor(row.get("at"), row["view"], "datum.at") + datums.append(DatumDecl(**row)) + for row in table("roughness", "view on text name"): + if not isinstance(row.get("text"), str) or not row["text"].strip(): + raise ValueError("roughness.text requires an explicit surface requirement") + value = row.get("on") + row["on"] = ( + resolve(value)[1] + if isinstance(value, dict) + else anchor(value, row["view"], "roughness.on") + ) + roughs.append(RoughDecl(**row)) + for row in table("leaders", "view anchor lines off alt_offs dx_dir name"): + lines = row.get("lines") + if ( + not isinstance(lines, list) + or not lines + or not all( + isinstance(line, str) + and line.strip() + and "\n" not in line + and "\r" not in line + for line in lines + ) + ): + raise ValueError( + "leaders.lines requires one or more nonempty single-line strings" + ) + row["anchor"] = anchor(row.get("anchor"), row["view"], "leader.anchor") + if "off" in row: + row["off"] = vector(row["off"], 2, "leader.off") + if "alt_offs" in row: + row["alt_offs"] = [ + vector(off, 2, "leader.alt_offs") for off in row["alt_offs"] + ] + row.setdefault("name", f"note-{len(leaders) + 1}") + leaders.append(LeaderDecl(**row)) + for row in table("centerlines", "view p1 p2 arc"): + if "arc" in row: + row["arc"] = vector(row["arc"], 5, "centerline.arc") + if row.keys() & {"p1", "p2"} or row["arc"][2] <= 0: + raise ValueError( + "A centerline arc requires a positive radius and no p1/p2" + ) + else: + row["p1"] = anchor(row.get("p1"), row["view"], "centerline.p1") + row["p2"] = anchor(row.get("p2"), row["view"], "centerline.p2") + if math.dist(row["p1"], row["p2"]) < 1e-8: + raise ValueError("Centerline endpoints must be distinct in the view") + centers.append(CenterDecl(**row)) + controls = [] + if spec.get("control_frames"): + from .control_frames import SYMBOLS + + names = set() + known_datums = {datum.letter for datum in datums} + for row in table( + "control_frames", + "name view anchor characteristic value datums diameter_zone offset", + ): + name, characteristic = row.get("name"), row.get("characteristic") + if ( + not isinstance(name, str) + or not name.strip() + or name in names + or characteristic not in SYMBOLS + ): + raise ValueError( + "Control frames require a unique name and supported characteristic" + ) + names.add(name) + ordered = row.get("datums", []) + if not isinstance(ordered, list) or not all( + isinstance(datum, str) and datum in known_datums for datum in ordered + ): + raise ValueError(f"{name}: use datum letters declared on this sheet") + if len(ordered) > 3 or len(set(ordered)) != len(ordered): + raise ValueError(f"{name}: use at most three distinct datum references") + if characteristic == "flatness" and ordered: + raise ValueError(f"{name}: flatness has no datum reference") + if characteristic in ("parallelism", "perpendicularity") and not ordered: + raise ValueError(f"{name}: specify a datum reference") + diameter_zone = row.get("diameter_zone", False) + if not isinstance(diameter_zone, bool) or ( + diameter_zone and characteristic != "position" + ): + raise ValueError( + f"{name}: diameter_zone is available on a position frame" + ) + offset = vector(row.get("offset", [22, 16]), 2, "control frame offset") + if abs(offset[0]) < 1e-8 or abs(offset[1]) < 2.5: + raise ValueError( + f"{name}: use a nonzero horizontal offset and at least 2.5 mm vertically for the arrow" + ) + controls.append( + row + | dict( + value=positive(row.get("value"), "control frame value"), + anchor=anchor( + row.get("anchor"), row["view"], "control frame anchor" + ), + datums=ordered, + diameter_zone=diameter_zone, + offset=offset, + ) + ) + return dict( + datums=datums, roughs=roughs, leaders=leaders, centers=centers + ), controls + + +def build_plan(shape, spec, title, *, projector=None): + from simplecadapi.dxf_engine import SheetDecl + from simplecadapi.inspect.brep.io import measure_shape_mass_rtuple + from .control_frames import place_control_frames + from .projection import DrawingProjection, MESH_DEFLECTION_MM, physical_shape + from .sheet import ExtendedSheetPlan, auxiliary_frame, removed_section + + fields( + spec, + "sheet views dimensions datums details actions roughness leaders centerlines control_frames hlr design_intent", + "drawing", + ) + hlr = spec.get("hlr", "exact") + if hlr not in ("exact", "polygonal"): + raise ValueError("drawing.hlr must be exact or polygonal") + if projector is None: + projector = DrawingProjection(physical_shape(shape), hlr, MESH_DEFLECTION_MM) + view_rows = spec.get("views") + if not isinstance(view_rows, list) or not view_rows: + raise ValueError("drawing.views must be a nonempty list") + sheet = fields( + spec.get("sheet", {}), + "title dwg_no scale front anchor sheet notes params material designer revision auto_centers general_rough projection", + "sheet", + ) + defaults = dict(title=title, dwg_no=title, scale=None, anchor=None) + options = defaults | sheet + projection = options.pop("projection", None) + if projection not in (None, "first", "third"): + raise ValueError("sheet.projection must be first or third") + if options["scale"] is not None: + positive(options["scale"], "sheet.scale") + if options["anchor"] is not None: + options["anchor"] = vector(options["anchor"], 2, "sheet.anchor") + standard_frames = frames() + views, by_name, auxiliary, removed = [], {}, {}, {} + resolve = reference_resolver(shape) + volume = None + for row in view_rows: + fields(row, "name frame normal right align section auxiliary", "view") + if "auxiliary" in row: + aux = fields(row["auxiliary"], "mark_in label face reverse", "auxiliary") + label, parent = aux.get("label"), aux.get("mark_in") + if ( + "section" in row + or parent not in by_name + or not isinstance(label, str) + or not re.fullmatch(r"[A-Z][A-Z0-9]{0,5}", label) + ): + raise ValueError( + "Auxiliary views require a unique label and an earlier mark_in view" + ) + if "face" in aux: + if row.keys() & {"frame", "normal", "right"}: + raise ValueError( + "Use a planar face reference or an explicit auxiliary direction" + ) + if not isinstance(aux.get("reverse", False), bool): + raise ValueError("auxiliary.reverse must be a boolean") + n, r = auxiliary_frame( + resolve(aux["face"]), + by_name[parent], + reverse=aux.get("reverse", False), + ) + row = row | dict(normal=n, right=r) + elif "reverse" in aux: + raise ValueError( + "auxiliary.reverse applies to a face-derived direction" + ) + view = view_definition(row, projector.shape, standard_frames) + if "auxiliary" in row: + if abs(np.dot(by_name[parent].n, view.n)) > 1e-8: + raise ValueError( + f"{view.name}: auxiliary mark_in must see the target direction edge-on" + ) + auxiliary[view.name] = parent, label + if "section" in row and row["section"].get("kind") == "removed": + if volume is None: + volume, _ = measure_shape_mass_rtuple(projector.shape, kind="volume") + point = view.section + view, loops, bounds = removed_section(view, volume) + removed[view.name] = point, loops, bounds + views.append(view) + by_name[view.name] = view + front = options.setdefault("front", views[0].name) + if len(views) != len(by_name) or front not in by_name or by_name[front].align: + raise ValueError( + "Views need unique names and a declared front view without align" + ) + positioned = {front} + for view in views: + if view.name != front and view.align.get("to") not in positioned: + raise ValueError( + f"{view.name}.align must name the front or an earlier view" + ) + positioned.add(view.name) + if view.section is not None or view.name in removed: + parent = by_name.get(view.mark_in) + if parent is None or abs(np.dot(parent.n, view.n)) > 1e-8: + raise ValueError( + f"{view.name}.section.mark_in must name a view perpendicular to the section view" + ) + labels = [v.label.upper() for v in views if v.label] + [ + label for _, label in auxiliary.values() + ] + if len(labels) != len(set(labels)): + raise ValueError("Section and auxiliary labels must be unique") + for key in ( + "dimensions", + "datums", + "details", + "actions", + "roughness", + "leaders", + "centerlines", + "control_frames", + ): + if not isinstance(spec.get(key, []), list): + raise ValueError(f"drawing.{key} must be a list") + annotations, controls = annotation_declarations(spec, by_name, resolve) + dims = dimension_declarations(spec.get("dimensions", []), by_name, resolve) + plan = ExtendedSheetPlan( + SheetDecl(**options, views=views, dims=dims, **annotations), + removed, + auxiliary, + projection, + projector, + ).solve() + plan.design_intent, plan.intent_issues = validate_intent( + plan, spec.get("design_intent") + ) + if actions := spec.get("actions"): + if not all(isinstance(action, dict) for action in actions): + raise ValueError("drawing.actions must contain SDK action objects") + for action in actions: + result = apply_drawing_action(plan, action) + if not result["ok"]: + reason = result.get("error", result.get("violations", [])) + raise ValueError( + f"Drawing action rejected for {action.get('name', 'unknown element')}: {reason}" + ) + plan.control_frames = place_control_frames(plan, controls) + return plan + + +def check_issues(plan): + issues = [issue.as_dict() for issue in plan.issues()] + errors = [ + f"{i['code']}: {i['message']}" for i in issues if i["severity"] == "error" + ] + if errors: + raise ValueError("Engineering drawing failed validation: " + " | ".join(errors)) + return issues + + +def detail_declarations(rows, plan): + labels = {view.label.upper() for view in plan.by_name.values() if view.label} + labels.update(label for _, label in plan.auxiliary.values()) + for row in rows: + fields(row, "label parent center size_mm position_mm scale hidden", "detail") + label, parent = row.get("label"), row.get("parent") + if ( + not isinstance(label, str) + or not re.fullmatch(r"[A-Z][A-Z0-9]{0,5}", label) + or label in labels + ): + raise ValueError( + "Detail labels must be unique uppercase letters or letter-number labels, separate from section labels" + ) + labels.add(label) + if ( + parent not in plan.views + or plan.by_name[parent].section is not None + or parent in plan.removed + ): + raise ValueError(f"Detail {label} needs an ordinary parent view") + center = vector(row.get("center"), 3, f"detail {label}.center") + size = vector(row.get("size_mm"), 2, f"detail {label}.size_mm") + if min(size) <= 0: + raise ValueError(f"Detail {label}: both crop dimensions must be positive") + at = vector(row.get("position_mm"), 2, f"detail {label}.position_mm") + scale = positive(row.get("scale"), f"detail {label}.scale") + if scale <= plan.s: + raise ValueError( + f"Detail {label}: scale must be larger than the parent scale {plan.s:g}" + ) + hidden = row.get("hidden", False) + if not isinstance(hidden, bool): + raise ValueError(f"Detail {label}: hidden must be a boolean") + yield dict( + label=label, + parent=parent, + center=center, + size=size, + at=at, + scale=scale, + hidden=hidden, + ) + + +def load_engineering_shape(step, transform=None): + shape = brep.load_step_rshape( + path=step, require_single_root=False, require_valid=True + ) + return shape if transform is None else rigid_shape(shape, transform) + + +def export_engineering_sheet(step, output, spec, *, transform=None, pdf=False): + """Export an engineering DXF, its reopened preview and a reproducible declaration audit.""" + step = Path(step).resolve() + shape = load_engineering_shape(step, transform) + plan = build_plan(shape, spec, step.stem) + return write_engineering_sheet( + step, output, spec, plan, transform=transform, pdf=pdf + ) + + +def write_engineering_sheet(step, output, spec, plan, *, transform=None, pdf=False): + from simplecadapi.dxf_engine.render import verify_dxf + from .control_frames import draw_control_frames + from ..render import build_dxf + from .sheet import decorate_views + + step, output = Path(step).resolve(), Path(output).resolve() + if output.suffix.lower() != ".dxf": + raise ValueError("Engineering output must have a .dxf extension") + check_issues(plan) + declared_details = list(detail_declarations(spec.get("details", []), plan)) + + output.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=output.parent) as temp: + staged = Path(temp) / output.name + doc, handles = build_dxf(plan) + use_diameter_font(doc) + decorate_views(doc, plan) + draw_control_frames(doc, plan.control_frames) + details = place_details(doc, plan, declared_details) if declared_details else [] + doc.saveas(staged) + plan.render_issues = verify_dxf(plan, staged, handles) + issues = check_issues(plan) + doc = ezdxf.readfile(staged) + audit = doc.audit() + if audit.has_errors: + raise ValueError(f"Engineering DXF audit errors: {len(audit.errors)}") + preview = render_print_page(doc, staged, plan.fmt, pdf=pdf) + counts = Counter(entity.dxftype() for entity in doc.modelspace()) + metadata = dict( + mode="engineering", + sdk_version=version("simplecadapi"), + source_step=str(step), + source_sha256=hashlib.sha256(step.read_bytes()).hexdigest(), + output_dxf=str(output), + transform=transform, + declaration=spec, + sheet=plan.fmt.name, + scale=plan.s, + units="mm", + sheet_size_mm=[plan.fmt.w, plan.fmt.h], + views=list(plan.views), + issues=issues, + details=details, + projection=plan.draft_projection or "first", + preview=preview, + hlr=plan.projector.mode, + projection_bounds=plan.projection_bounds(), + control_frames=plan.control_frames, + dimensions=[ + dict(caption=d.caption, view=d.view, value_mm=d._measured) + for d in plan.dims + ], + reopen_audit=dict( + entity_count=sum(counts.values()), + entity_types=dict(counts), + audit_errors=0, + ), + ) + if pdf: + metadata["output_pdf"] = str(output.with_suffix(".pdf")) + if plan.design_intent is not None: + metadata["design_intent"] = plan.design_intent + staged.with_suffix(".json").write_text( + json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8" + ) + staged.with_suffix(".txt").write_text(plan.report(), encoding="utf-8") + staged.replace(output) + suffixes = ( + (".pdf", ".png", ".txt", ".json") if pdf else (".png", ".txt", ".json") + ) + for suffix in suffixes: + staged.with_suffix(suffix).replace(output.with_suffix(suffix)) + return metadata diff --git a/src/simplecadapi/dxf_engine/workflow/details.py b/src/simplecadapi/dxf_engine/workflow/details.py new file mode 100644 index 00000000..465e7688 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/details.py @@ -0,0 +1,211 @@ +"""Add scaled details to a solved engineering sheet and render its print page.""" + +from __future__ import annotations + +import math + +from ezdxf.enums import TextEntityAlignment +from ezdxf.math import BoundingBox2d, Vec2 +from ezdxf.math.clipping import CohenSutherlandLineClipping2d +from ezdxf.xclip import XClip + +PREVIEW_LONG_SIDE_PX = 3600 +DIAMETER_STYLE = "DXF_EXPORTER_DIM_SYMBOL" + + +def rectangle(center, size): + half = size / 2 + return BoundingBox2d((center - half, center + half)) + + +def draw_rectangle(msp, box, layer): + x0, y0 = box.extmin + x1, y1 = box.extmax + msp.add_lwpolyline( + [(x0, y0), (x1, y0), (x1, y1), (x0, y1)], + close=True, + dxfattribs={"layer": layer}, + ) + + +def place_details(doc, plan, rows): + from simplecadapi.dxf_engine.refs import project + from simplecadapi.dxf_engine.render import _draw_view_edges + from simplecadapi.dxf_engine.sheet import scale_text + + outlines = "DETAIL_OUTLINE" + doc.layers.new( + outlines, dxfattribs={"color": 7, "lineweight": 18, "linetype": "DASHED_GB"} + ) + doc.header["$XCLIPFRAME"] = ( + 0 # The separate outline remains available as DXF geometry. + ) + msp = doc.modelspace() + free = BoundingBox2d((plan.fmt.free[:2], plan.fmt.free[2:])) + occupied = [ + BoundingBox2d(((box.x0, box.y0), (box.x1, box.y1))) + for box in (view["bbox"] for view in plan.views.values()) + ] + for _, x, y, width, height, angle in plan.text_obbs: + theta = math.radians(angle) + c, s = abs(math.cos(theta)), abs(math.sin(theta)) + occupied.append( + rectangle(Vec2(x, y), Vec2(width * c + height * s, width * s + height * c)) + ) + + records = [] + for row in rows: + label, parent, center, scale, hidden = ( + row[key] for key in ("label", "parent", "center", "scale", "hidden") + ) + size, at = Vec2(row["size"]), Vec2(row["at"]) + source = plan.views[parent] + source_uv = Vec2(project(center, source["frame"])) + source_local = rectangle(source_uv, size) + clip = CohenSutherlandLineClipping2d(source_local.extmin, source_local.extmax) + selected = [ + (ad, pts, visible) + for ad, pts, visible in source["edges"] + if (visible or hidden) + and any(clip.clip_line(a, b) for a, b in zip(pts, pts[1:])) + ] + if not selected: + raise ValueError(f"Detail {label}: crop contains no projected geometry") + + detail_box = rectangle(at, size * scale) + # Include space for the centered title below the detail frame. + title_width = len(f"DETAIL {label} {scale_text(scale)}") * 2.0 + reserved = BoundingBox2d( + ( + detail_box.extmin - (2, 9), + detail_box.extmax + (2, 2), + (at.x - title_width / 2, detail_box.extmin.y - 9), + (at.x + title_width / 2, detail_box.extmin.y - 9), + ) + ) + if not all(free.inside(p) for p in (reserved.extmin, reserved.extmax)): + raise ValueError( + f"Detail {label}: detail and title must fit within the drawing area" + ) + box_clip = CohenSutherlandLineClipping2d(reserved.extmin, reserved.extmax) + if any(reserved.has_intersection(box) for box in occupied) or any( + box_clip.clip_line(p, q) for _, p, q in plan.segments + ): + raise ValueError( + f"Detail {label}: choose a position clear of views, dimensions and other details" + ) + occupied.append(reserved) + + source_sheet = rectangle(Vec2(plan.tx(parent, source_uv)), size * plan.s) + name = f"DXF_EXPORTER_DETAIL_{label}" + block = doc.blocks.new(name, base_point=plan.tx(parent, source_uv)) + _draw_view_edges(block, plan, {**source, "edges": selected}) + factor = scale / plan.s + insert = msp.add_blockref( + name, at, dxfattribs={"xscale": factor, "yscale": factor, "zscale": factor} + ) + XClip(insert).set_wcs_clipping_path((detail_box.extmin, detail_box.extmax)) + draw_rectangle(msp, source_sheet, outlines) + draw_rectangle(msp, detail_box, "TEXT") + msp.add_text(label, dxfattribs={"layer": "TEXT", "height": 3.5}).set_placement( + source_sheet.extmax + (2, 1) + ) + msp.add_text( + f"DETAIL {label} {scale_text(scale)}", + dxfattribs={"layer": "TEXT", "height": 3.5}, + ).set_placement( + (at.x, detail_box.extmin.y - 6), align=TextEntityAlignment.MIDDLE_CENTER + ) + records.append( + dict( + label=label, + parent=parent, + center_model_mm=center, + source_center_uv_mm=tuple(source_uv), + size_model_mm=tuple(size), + scale=scale, + position_sheet_mm=tuple(at), + keeps_hidden_lines=hidden, + block=name, + source_edges=len(block), + clip_sheet_mm=[tuple(detail_box.extmin), tuple(detail_box.extmax)], + ) + ) + return records + + +def use_diameter_font(doc): + """Use a diameter-capable font for numeric diameter labels in the saved DXF.""" + style = DIAMETER_STYLE + for dimension in doc.modelspace().query("DIMENSION"): + block = doc.blocks.get(dimension.dxf.geometry) + for text in block.query("TEXT"): + label = text.dxf.text + if "%%c" not in label.lower() or not all( + c.isascii() or c in "×±" for c in label + ): + continue + if style not in doc.styles: + doc.styles.new(style, dxfattribs={"font": "DejaVuSans.ttf"}) + text.dxf.style = style + override = dimension.override() + override["dimtxsty"] = style + override.commit() + return style in doc.styles + + +def render_print_page(doc, path, fmt, *, pdf): + from pathlib import Path + + import matplotlib + from simplecadapi.inspect.drawing._pymupdf import pymupdf + from ezdxf.addons.drawing import ( + Frontend, + RenderContext, + config, + layout, + pymupdf as backend_module, + ) + from ezdxf.fonts import fonts + + if DIAMETER_STYLE in doc.styles: + fonts.font_manager.scan_folder( + Path(matplotlib.get_data_path()) / "fonts" / "ttf" + ) + + backend = backend_module.PyMuPdfBackend() + style = config.Configuration( + background_policy=config.BackgroundPolicy.WHITE, + color_policy=config.ColorPolicy.BLACK, + ) + Frontend(RenderContext(doc), backend, config=style).draw_layout(doc.modelspace()) + page = layout.Page(fmt.w, fmt.h, layout.Units.mm) + paper = BoundingBox2d(((0, 0), (fmt.w, fmt.h))) + width_pt, height_pt = (value * 72 / 25.4 for value in (fmt.w, fmt.h)) + # ezdxf 1.4.5 truncates page points and uses that integer for content scaling. + # Correct that scaling, then place those vectors on the exact page at unit magnification. + long_side_pt = max(width_pt, height_pt) + settings = layout.Settings( + fit_page=False, + scale=long_side_pt / int(long_side_pt), + page_alignment=layout.PageAlignment.TOP_LEFT, + ) + data = backend.get_pdf_bytes(page, render_box=paper, settings=settings) + with ( + pymupdf.open(stream=data, filetype="pdf") as source, + pymupdf.open() as document, + ): + printed = document.new_page(width=width_pt, height=height_pt) + printed.show_pdf_page(source[0].rect, source, 0) + dpi = min(180, math.floor((PREVIEW_LONG_SIDE_PX - 1) * 72 / long_side_pt)) + pixmap = printed.get_pixmap(dpi=dpi, alpha=False) + pixmap.save(path.with_suffix(".png")) + preview = dict( + dpi=dpi, + pixels=[pixmap.width, pixmap.height], + long_side_limit_px=PREVIEW_LONG_SIDE_PX, + ) + del pixmap + if pdf: + document.save(path.with_suffix(".pdf"), deflate=True) + return preview diff --git a/src/simplecadapi/dxf_engine/workflow/drawing_templates.json b/src/simplecadapi/dxf_engine/workflow/drawing_templates.json new file mode 100644 index 00000000..ca6ab9ab --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/drawing_templates.json @@ -0,0 +1,55 @@ +{ + "schema_version": 1, + "verified_on": "2026-11-18", + "renderer_scope": "Single part. Metric A-series sheet. Layout presets and drafting guidance only.", + "templates": { + "gb-machining": { + "label": "GB general machined part", + "options": {"projection": "first", "layout": "aligned", "section_view": "full"}, + "sources": ["GB/T 14692-2008", "GB/T 4458.4-2003", "GB/T 17452-1998", "GB/T 1182-2018"], + "review": ["Confirm the primary view and the dimension datums from the functional faces", "Review hole depths, hole-pattern positions, fits and surface requirements"] + }, + "iso-machining": { + "label": "ISO GPS general machined part", + "options": {"projection": "first", "layout": "aligned", "section_view": "full"}, + "sources": ["ISO 128-3:2022", "ISO 129-1:2018/Amd 1:2020", "ISO 1101:2017", "ISO 5459:2024", "ISO 21920-1:2021"], + "review": ["Confirm the projection method and sheet size against the contract", "Datums, tolerances and surface texture come from the drawing requirements"] + }, + "iso-sheet-metal": { + "label": "Sheet-metal and stamped part", + "options": {"projection": "first", "layout": "compact", "section_view": "removed"}, + "sources": ["ISO 128-3:2022", "DIN 6930-2:2011-10", "DIN 6935:2011-10", "ISO 9013:2017/Amd 1:2024"], + "review": ["Distinguish the formed drawing from a verified flat pattern; record thickness and bend direction", "Cite stamping, bending or thermal-cutting standards only where the process and contract apply", "Flat-pattern layout and bend allowances must come from approved data"] + }, + "iso-casting": { + "label": "Casting blank and machined casting", + "options": {"projection": "first", "layout": "aligned", "section_view": "full"}, + "sources": ["ISO 128-3:2022", "ISO 8062-3:2023", "ASME Y14.8-2022"], + "review": ["Check wall thickness, cavities and passages in section", "Distinguish the casting blank from the machined state; review which surfaces keep machining allowance", "ASME Y14.8 belongs to another contract system option"] + }, + "iso-weld-prep": { + "label": "Single-part bevel and weld preparation", + "options": {"projection": "first", "layout": "compact", "section_view": "removed"}, + "sources": ["ISO 128-3:2022", "ISO 2553:2019", "AWS A2.4:2020"], + "review": ["Check the single-part bevel, land and root dimensions on an end view or section", "The welding-symbol system is set by the contract; AWS A2.4 can serve as the other system's reference", "This template is for single-part preparation drawings"] + }, + "asme-machining": { + "label": "Metric review sketch for North American machining projects", + "options": {"projection": "third", "layout": "aligned", "section_view": "full"}, + "sources": ["ASME Y14.3-2012", "ASME Y14.5-2018 (R2024)", "ASME Y14.1-2020", "ASME Y14.100-2017"], + "review": ["Check sheet size, units, projection and annotation against the contract", "The preset writes metric A-series sheets; use an approved template for ANSI sheets or inches before formal delivery"] + }, + "asme-aerospace": { + "label": "Metric review sketch for aerospace or high-traceability single parts", + "options": {"projection": "third", "layout": "aligned", "section_view": "full"}, + "sources": ["ASME Y14.5-2018 (R2024)", "ASME Y14.41-2026", "ASME Y14.100-2017"], + "review": ["Confirm the precedence and revisions of the controlled drawing, data set and customer requirements", "Review key characteristics, material lot requirements, special processes and inspection notes", "Y14.41 applies to digital product definition processes the contract invokes"] + }, + "asme-additive": { + "label": "Metric review sketch for additively manufactured single parts", + "options": {"projection": "third", "layout": "aligned", "section_view": "full"}, + "sources": ["ASME Y14.46-2022", "ASME Y14.5-2018 (R2024)"], + "review": ["Check internal channels and inspectable regions in section", "Distinguish as-printed from post-processed states; give build orientation and surface finish from approved data"] + } + } +} diff --git a/src/simplecadapi/dxf_engine/workflow/inspection.py b/src/simplecadapi/dxf_engine/workflow/inspection.py new file mode 100644 index 00000000..00c3e61b --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/inspection.py @@ -0,0 +1,462 @@ +"""Single STEP -> editable DXF inspection sheet, powered by SimpleCADAPI HLR. + +No reference model or drawing is needed. All view frames are explicit. +""" + +from __future__ import annotations + +import hashlib +import json +import math +from collections import Counter +from pathlib import Path + +import ezdxf +import numpy as np +from simplecadapi.inspect import brep +from simplecadapi.dxf_engine.hlr import hlr_project, discretize_edge, arc_angles +from simplecadapi._cpp.occt.GeomAbs import GeomAbs_Circle, GeomAbs_Line + +VERSION = "1.0.0" + + +def frames(): + """d points observer -> object. SDK projector normal is -d.""" + definitions = [ + ("front", (0, 1, 0), (1, 0, 0)), + ("top", (0, 0, -1), (1, 0, 0)), + ("right", (-1, 0, 0), (0, 1, 0)), + ("left", (1, 0, 0), (0, -1, 0)), + ("bottom", (0, 0, 1), (1, 0, 0)), + ("rear", (0, -1, 0), (-1, 0, 0)), + ("iso", (-1, 1, -1), (1, 1, 0)), + ] + out = {} + for name, d, r in definitions: + d = np.array(d, dtype=float) + d /= np.linalg.norm(d) + r = np.array(r, dtype=float) + r /= np.linalg.norm(r) + u = np.cross(-d, r) + assert np.allclose(np.cross(r, u), -d) + out[name] = dict( + direction=d.tolist(), + right=r.tolist(), + up=u.tolist(), + projector_normal=(-d).tolist(), + ) + return out + + +def rigid_shape(shape, transform): + from simplecadapi._cpp.occt.BRepBuilderAPI import BRepBuilderAPI_Transform + from simplecadapi._cpp.occt.gp import gp_Trsf + from simplecadapi._glue.bridge import native_occt + + missing = [key for key in ("rotation", "translation_mm") if key not in transform] + if missing: + raise ValueError(f"Transform needs {', '.join(missing)} (rotation: 3x3, translation_mm: 3 values)") + r = np.asarray(transform["rotation"], float) + t = np.asarray(transform["translation_mm"], float) + if ( + r.shape != (3, 3) + or t.shape != (3,) + or not np.isfinite(r).all() + or not np.isfinite(t).all() + ): + raise ValueError("Expected finite 3x3 rotation and 3-vector translation_mm") + if not np.allclose(r.T @ r, np.eye(3), atol=1e-8) or not np.isclose( + np.linalg.det(r), 1, atol=1e-8 + ): + raise ValueError( + "Only proper rigid transforms are allowed: no scale/shear/reflection" + ) + tr = gp_Trsf() + tr.SetValues(*[float(v) for v in np.column_stack((r, t)).ravel()]) + return BRepBuilderAPI_Transform(native_occt(shape), tr, True).Shape() + + +def edge_record(edge, deflection): + ad, points = discretize_edge(edge=edge, deflection=deflection) + if len(points) < 2: + # Exact HLR sometimes returns an edge collapsed along the camera axis. + # Confirm its projected extent, retain it as an audited DXF POINT. + ts = np.linspace(ad.FirstParameter(), ad.LastParameter(), 33) + samples = [(ad.Value(float(t)).X(), ad.Value(float(t)).Y()) for t in ts] + span = float(np.max(np.ptp(np.asarray(samples), axis=0))) + if span <= 1e-6: + return dict( + kind="POINT", + points=[list(samples[0])], + projected_extent_mm=span, + reason="HLR edge projects to a point within 1e-6 mm", + ) + points = samples + record = dict(points=[list(map(float, p)) for p in points]) + if ad.GetType() == GeomAbs_Line: + record.update(kind="LINE", start=record["points"][0], end=record["points"][-1]) + elif ( + ad.GetType() == GeomAbs_Circle + and abs(ad.Circle().Axis().Direction().Z()) > 0.999999 + ): + c = ad.Circle() + center = c.Location() + t0, t1 = ad.FirstParameter(), ad.LastParameter() + record.update(center=[center.X(), center.Y()], radius=c.Radius()) + if abs(t1 - t0) >= 2 * math.pi - 1e-7: + record["kind"] = "CIRCLE" + else: + a0, a1 = arc_angles(ad=ad, cxy=record["center"], t0=t0, t1=t1) + record.update(kind="ARC", start_angle=a0, end_angle=a1) + else: + record["kind"] = "LWPOLYLINE" + return record + + +def project_step(step, *, transform=None, deflection=0.03): + step = Path(step).resolve() + if not math.isfinite(deflection) or deflection <= 0: + raise ValueError("deflection must be positive and finite") + shape = brep.load_step_rshape( + path=step, require_single_root=False, require_valid=True + ) + if transform is not None: + shape = rigid_shape(shape, transform) + views = {} + for name, frame in frames().items(): + vis, hid = hlr_project( + shape=shape, view_dir=frame["projector_normal"], x_dir=frame["right"] + ) + edges = [] + seen = set() + duplicates = 0 + for visible, values in ((True, vis), (False, hid)): + for index, edge in enumerate(values): + try: + record = edge_record(edge, deflection) + except Exception as exc: + raise RuntimeError( + f"{step.name}/{name}/{visible}/{index}: edge export failed" + ) from exc + # Same analytic entity may be emitted as both HLR edge and outline. + key = json.dumps( + {k: v for k, v in record.items() if k != "points"}, sort_keys=True + ) + if record["kind"] in ("LWPOLYLINE", "POINT"): + key = json.dumps(np.round(record["points"], 8).tolist()) + key = (visible, key) + if key in seen: + duplicates += 1 + continue + seen.add(key) + record["visible"] = visible + edges.append(record) + if not edges: + raise ValueError(f"Empty HLR view: {name}") + xy = np.asarray([p for e in edges for p in e["points"]]) + views[name] = dict( + **frame, + edges=edges, + bounds=[xy.min(axis=0).tolist(), xy.max(axis=0).tolist()], + input_hlr_edges=len(vis) + len(hid), + duplicate_edges_removed=duplicates, + ) + return dict( + version=VERSION, + source_step=str(step), + source_sha256=hashlib.sha256(step.read_bytes()).hexdigest(), + units="mm", + transform=transform, + deflection_mm=deflection, + views=views, + limitations=[ + "Geometry inspection sheet; no inferred manufacturing dimensions or sections", + "Axes are explicit input/world axes, not recovered original drawing axes", + ], + ) + + +def sheet_layout(projects, projection="first"): + if projection not in ("first", "third"): + raise ValueError("projection must be first or third") + # Same model origin, shared union bounds and gap for EVERY compared sheet. + max_span = max( + float(np.max(np.subtract(v["bounds"][1], v["bounds"][0]))) + for p in projects + for v in p["views"].values() + ) + gap = max(8.0, max_span * 0.14) + label = max(2.0, max_span * 0.025) + if projection == "first": + cells = dict( + front=(1, 1), + top=(1, 0), + right=(0, 1), + left=(2, 1), + bottom=(1, 2), + rear=(3, 1), + iso=(3, 0), + ) + else: + cells = dict( + front=(1, 1), + top=(1, 2), + right=(2, 1), + left=(0, 1), + bottom=(1, 0), + rear=(3, 1), + iso=(3, 2), + ) + # Center all views on one projected world point, not each silhouette separately. + union = {} + for name in cells: + bounds = np.asarray([p["views"][name]["bounds"] for p in projects]) + union[name] = (bounds[:, 0, :].min(axis=0), bounds[:, 1, :].max(axis=0)) + widths = [ + max(union[n][1][0] - union[n][0][0] for n, c in cells.items() if c[0] == x) + + 2 * gap + for x in range(4) + ] + heights = [ + max(union[n][1][1] - union[n][0][1] for n, c in cells.items() if c[1] == y) + + 2 * gap + + 3 * label + for y in range(3) + ] + xs = np.r_[0, np.cumsum(widths)] + ys = np.r_[0, np.cumsum(heights)] + offsets = {} + rects = {} + for name, cell in cells.items(): + center = (union[name][0] + union[name][1]) / 2 + x, y = cell + w, h = widths[x], heights[y] + offsets[name] = [ + float(xs[x] + w / 2 - center[0]), + float(ys[y] + (h - 3 * label) / 2 - center[1]), + ] + rects[name] = [float(xs[x]), float(ys[y]), float(w), float(h)] + return dict( + projection=projection, + scale=1.0, + units="mm", + cell_rectangles=rects, + label_height=label, + sheet_size=[float(xs[-1]), float(ys[-1])], + cells=cells, + offsets=offsets, + common_origin_and_scale=True, + frame_contract="right cross up = minus(observer-to-object direction)", + ) + + +def new_document(layout): + doc = ezdxf.new("R2010") + doc.units = ezdxf.units.MM + doc.header["$MEASUREMENT"] = 1 + doc.linetypes.new( + "HIDDEN_MODEL", + dxfattribs={"description": "Hidden edges", "pattern": [3.0, 2.0, -1.0]}, + ) + for name, color, lt, weight in [ + ("VISIBLE", 7, "Continuous", 35), + ("HIDDEN", 8, "HIDDEN_MODEL", 15), + ("LABELS", 7, "Continuous", 15), + ("FRAME", 8, "Continuous", 13), + ("REFERENCE", 4, "Continuous", 25), + ("CANDIDATE", 1, "Continuous", 25), + ]: + doc.layers.new( + name, dxfattribs={"color": color, "linetype": lt, "lineweight": weight} + ) + doc.set_modelspace_vport( + height=layout["sheet_size"][1] * 1.06, + center=(layout["sheet_size"][0] / 2, layout["sheet_size"][1] / 2), + ) + return doc + + +def add_geometry(msp, project, layout, *, overlay_layer=None, hidden=True): + for name, view in project["views"].items(): + ox, oy = layout["offsets"][name] + + def point(p): + return (p[0] + ox, p[1] + oy) + + for e in view["edges"]: + if not hidden and not e["visible"]: + continue + attrs = { + "layer": overlay_layer or ("VISIBLE" if e["visible"] else "HIDDEN") + } + if e["kind"] == "LINE": + msp.add_line(point(e["start"]), point(e["end"]), dxfattribs=attrs) + elif e["kind"] == "POINT": + msp.add_point(point(e["points"][0]), dxfattribs=attrs) + elif e["kind"] == "CIRCLE": + msp.add_circle(point(e["center"]), e["radius"], dxfattribs=attrs) + elif e["kind"] == "ARC": + msp.add_arc( + point(e["center"]), + e["radius"], + e["start_angle"], + e["end_angle"], + dxfattribs=attrs, + ) + else: + msp.add_lwpolyline([point(p) for p in e["points"]], dxfattribs=attrs) + + +def axis_label(v): + return "(" + ",".join(f"{float(x):+.2g}" for x in v) + ")" + + +def add_labels(msp, project, layout, title): + th = layout["label_height"] + for name, cell in layout["cells"].items(): + x, y, w, h = layout["cell_rectangles"][name] + f = project["views"][name] + msp.add_lwpolyline( + [(x, y), (x + w, y), (x + w, y + h), (x, y + h)], + close=True, + dxfattribs={"layer": "FRAME"}, + ) + for i, text in enumerate( + [ + name.upper() + " d=" + axis_label(f["direction"]), + "r=" + axis_label(f["right"]) + " u=" + axis_label(f["up"]), + ] + ): + msp.add_text( + text, dxfattribs={"layer": "LABELS", "height": th * 0.62} + ).set_placement((x + th, y + h - th * (1 + i))) + msp.add_text( + title[:100], dxfattribs={"layer": "LABELS", "height": th} + ).set_placement((th, -th * 1.5)) + msp.add_text( + f"{layout['projection'].upper()} ANGLE / mm / 1:1 / geometry inspection, no inferred dimensions", + dxfattribs={"layer": "LABELS", "height": th * 0.7}, + ).set_placement((th, -th * 2.8)) + + +def render_saved_dxf(path): + """Both previews come from the reopened, editable DXF.""" + import matplotlib + + matplotlib.use("Agg") + from ezdxf.addons.drawing import RenderContext, Frontend, layout + from ezdxf.addons.drawing.config import Configuration, ColorPolicy, BackgroundPolicy + from ezdxf.addons.drawing.svg import SVGBackend + from ezdxf.addons.drawing.matplotlib import qsave + + doc = ezdxf.readfile(path) + audit = doc.audit() + if audit.has_errors: + raise ValueError(f"DXF audit errors: {len(audit.errors)}") + config = Configuration( + background_policy=BackgroundPolicy.WHITE, color_policy=ColorPolicy.COLOR + ) + qsave( + doc.modelspace(), + Path(path).with_suffix(".png"), + dpi=130, + size_inches=(16, 11), + bg="#ffffff", + config=config, + ) + backend = SVGBackend() + Frontend(RenderContext(doc), backend, config=config).draw_layout( + doc.modelspace(), finalize=True + ) + svg = backend.get_string( + layout.Page(0, 0, layout.Units.mm), settings=layout.Settings(scale=1) + ) + Path(path).with_suffix(".svg").write_text(svg, encoding="utf-8") + return dict( + entity_count=len(doc.modelspace()), + entity_types=dict(Counter(e.dxftype() for e in doc.modelspace())), + audit_errors=len(audit.errors), + ) + + +def export_sheet(project, output, *, layout=None, projection="first", title=None): + output = Path(output) + output.parent.mkdir(parents=True, exist_ok=True) + layout = layout or sheet_layout([project], projection) + # Accept the metadata this exporter writes (layout nested under "layout"), so a layout can be + # shared by passing one sheet's .json to the next (--layout-json). + layout = layout.get("layout", layout) + if layout.get("scale") != 1: + raise ValueError("This exporter keeps DXF modelspace at 1:1") + doc = new_document(layout) + msp = doc.modelspace() + add_geometry(msp, project, layout) + add_labels(msp, project, layout, title or Path(project["source_step"]).stem) + doc.saveas(output) + audit = render_saved_dxf(output) + metadata = dict( + **project, layout=layout, output_dxf=str(output.resolve()), reopen_audit=audit + ) + output.with_suffix(".json").write_text( + json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8" + ) + return metadata + + +def export_overlay(reference, candidate, output, *, layout): + output = Path(output) + output.parent.mkdir(parents=True, exist_ok=True) + doc = new_document(layout) + msp = doc.modelspace() + add_geometry(msp, reference, layout, overlay_layer="REFERENCE", hidden=False) + add_geometry(msp, candidate, layout, overlay_layer="CANDIDATE", hidden=False) + add_labels( + msp, + reference, + layout, + "Visible edges: CYAN = reference / RED = candidate; common frame, no extra fitting", + ) + doc.saveas(output) + return render_saved_dxf(output) + + +def drawing_templates(): + return json.loads( + Path(__file__).with_name("drawing_templates.json").read_text(encoding="utf-8") + ) + + +def export_view_previews(dxf_path, layout, output_dir): + """Write separate SVG windows from a saved shared-layout DXF.""" + import copy + + from ezdxf.addons.drawing import ( + Frontend, + RenderContext, + config, + layout as page_layout, + ) + from ezdxf.addons.drawing.svg import SVGBackend + from ezdxf.math import BoundingBox2d + + doc = ezdxf.readfile(dxf_path) + output = Path(output_dir) + output.mkdir(parents=True, exist_ok=True) + backend = SVGBackend() + style = config.Configuration(background_policy=config.BackgroundPolicy.WHITE) + Frontend(RenderContext(doc), backend, config=style).draw_layout(doc.modelspace()) + paths = {} + cells = layout.get("layout", layout)["cell_rectangles"] + for name in frames(): + if name not in cells: + continue + x, y, w, h = cells[name] + svg = copy.deepcopy(backend).get_string( + page_layout.Page(0, 0, page_layout.Units.mm), + settings=page_layout.Settings(scale=1, crop_at_margins=True), + render_box=BoundingBox2d([(x, y), (x + w, y + h)]), + ) + path = output / f"{name}.svg" + path.write_text(svg, encoding="utf-8") + paths[name] = path + return paths diff --git a/src/simplecadapi/dxf_engine/workflow/notebook.py b/src/simplecadapi/dxf_engine/workflow/notebook.py new file mode 100644 index 00000000..983d5df3 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/notebook.py @@ -0,0 +1,171 @@ +"""Read evaluated SimpleCADAPI parameters and explicit drawing intent from a part notebook.""" + +import ast +import hashlib +import math +from pathlib import Path +from tempfile import TemporaryDirectory + + +def overrides_from_args(entries): + overrides = {} + for entry in entries: + name, sep, value = entry.partition("=") + if not sep or not name.isidentifier() or name in overrides: + raise ValueError(f"Expected a unique --set NAME=VALUE: {entry!r}") + try: + parsed = ast.literal_eval(value) + except (SyntaxError, ValueError): + parsed = value + if not isinstance(parsed, (int, float, bool, str)) or ( + isinstance(parsed, float) and not math.isfinite(parsed) + ): + raise ValueError( + f"{name}: a finite numeric, boolean or string override is required" + ) + overrides[name] = parsed + return overrides + + +def parameter_value(value, unit, name): + from simplecadapi.params.expr import Var, get_unit + + if isinstance(value, Var) and value.unit is not None: + return ( + float(value), + value.unit.symbol, + (value.dimension.length == 1 and value.dimension.angle == 0), + ) + if isinstance(value, Var): + if unit is None: + return float(value), None, False + value = float(value) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return ( + value if isinstance(value, (bool, str, int, float)) else None, + unit, + False, + ) + resolved = get_unit(unit) if unit else None + if resolved is not None and ( + resolved.dimension.length, + resolved.dimension.angle, + ) != (1, 0): + return value, unit, False + return ( + (resolved.to_canonical(value) if resolved is not None else float(value)), + unit or "mm", + True, + ) + + +def prepare_notebook(path, step, overrides): + from simplecadapi import Part + from simplecadapi.kernel.ocp_export import export_step_shapes + from simplecadapi.params.expr import Var + from simplecadapi.runtime import run_notebook + from simplecadapi.runtime.params import list_parameters + + if step.suffix.lower() != ".step" or step.resolve() == path.resolve(): + raise ValueError("Notebook STEP snapshot must be a distinct .step path") + run = run_notebook(path, overrides=overrides, cache=False) + if not isinstance(run.product, Part): + raise ValueError("Notebook drawing requires a single SimpleCADAPI Part") + declared = {spec.name: spec for spec in list_parameters(path)} + intent = run.values.get("DRAWING_INTENT", {}) + if not isinstance(intent, dict) or intent.keys() - {"dimensions", "datums"}: + raise ValueError("DRAWING_INTENT accepts dimensions and datums lists") + rows, datums = intent.get("dimensions", []), intent.get("datums", []) + if not isinstance(rows, (list, tuple)) or not isinstance(datums, (list, tuple)): + raise ValueError("DRAWING_INTENT dimensions and datums must be lists") + ledger = {} + for name, spec in declared.items(): + value, unit, length = parameter_value(run.values.get(name), spec.unit, name) + if isinstance(value, float) and not math.isfinite(value): + raise ValueError(f"{name}: the evaluated parameter must be finite") + field = "evaluated_mm" if length else "evaluated" + ledger[name] = dict( + name=name, + group=spec.group, + unit=unit, + status="unbound" if length else "non_length", + ) + ledger[name][field] = value + dims = [] + for row in rows: + if not isinstance(row, dict): + raise ValueError("Each design-intent dimension must be a dictionary") + values = row.copy() + name = values.pop("parameter", None) + if not isinstance(name, str) or name not in run.values: + raise ValueError(f"Unknown notebook parameter {name!r}") + if "value" in values: + raise ValueError( + f"{name}: the dimension expectation comes from the notebook parameter" + ) + factor = values.pop("factor", 1) + if ( + isinstance(factor, bool) + or not isinstance(factor, (int, float)) + or not math.isfinite(factor) + or factor <= 0 + ): + raise ValueError(f"{name}: factor must be a positive finite number") + unit_hint = values.pop("unit", None) or ( + declared[name].unit if name in declared else None + ) + expected, unit, length = parameter_value(run.values[name], unit_hint, name) + if not length or not math.isfinite(expected * factor): + raise ValueError( + f"{name}: a model length is required for a linear, diameter or radius dimension" + ) + values.setdefault("caption", name) + values.setdefault("kind", "size") + values["value"] = expected * factor + values.setdefault( + "dec", max(0, len(f"{values['value']:.6f}".rstrip("0").partition(".")[2])) + ) + if values.pop("use_parameter_tolerance", False): + var = run.values[name] + if ( + not isinstance(var, Var) + or var.canonical_tolerance is None + or values.get("tol") is not None + ): + raise ValueError( + f"{name}: select either explicit tol or a tolerance declared on the evaluated Var" + ) + limit = var.canonical_tolerance + values["tol"] = [ + limit.upper_deviation * factor, + limit.lower_deviation * factor, + ] + values["covers"] = list(dict.fromkeys([name, *values.get("covers", [])])) + dims.append(values) + item = ledger.setdefault( + name, dict(name=name, group="", unit=unit, evaluated_mm=expected) + ) + item.pop("evaluated", None) + item.update(unit=unit, evaluated_mm=expected) + item["status"] = "declared" + item.setdefault("dimensions", []).append( + dict(caption=values["caption"], expected_mm=values["value"], factor=factor) + ) + + step.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=step.parent) as temp: + staged = Path(temp) / step.name + export_step_shapes([run.product.body._native_wrapped], str(staged)) + staged.replace(step) + return dict( + dimensions=dims, + datums=list(datums), + parameters=list(ledger.values()), + source=dict( + notebook=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + overrides=overrides, + product_id=run.config.id, + content_hash=run.definition.content_hash, + ), + ) diff --git a/src/simplecadapi/dxf_engine/workflow/polygonal_hlr.py b/src/simplecadapi/dxf_engine/workflow/polygonal_hlr.py new file mode 100644 index 00000000..81767511 --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/polygonal_hlr.py @@ -0,0 +1,68 @@ +"""OCCT polygonal HLR for spline-heavy review drawings.""" + +from io import BytesIO +import math + + +def mesh_shape(shape, deflection): + try: + from OCP.BRep import BRep_Builder + from OCP.BRepMesh import BRepMesh_IncrementalMesh + from OCP.BRepTools import BRepTools + from OCP.TopoDS import TopoDS_Shape + except ImportError as exc: + raise RuntimeError( + "Polygonal projection requires the SimpleCADAPI verify extra: pip install simplecadapi[drawing,verify]" + ) from exc + from simplecadapi._cpp.occt.BRepTools import BRepTools as SourceBRepTools + + stream = BytesIO() + SourceBRepTools.Write_s(shape, stream) + stream.seek(0) + mesh = TopoDS_Shape() + BRepTools.Read_s(mesh, stream, BRep_Builder()) + if mesh.IsNull(): + raise RuntimeError("Polygonal projection could not read the source solid") + build = BRepMesh_IncrementalMesh(mesh, deflection, False, 0.16, False) + if not build.IsDone(): + raise RuntimeError("Polygonal projection could not mesh the source solid") + return mesh + + +def projected_segments(mesh, frame): + from OCP.BRepAdaptor import BRepAdaptor_Curve + from OCP.HLRAlgo import HLRAlgo_Projector + from OCP.HLRBRep import HLRBRep_PolyAlgo, HLRBRep_PolyHLRToShape + from OCP.TopAbs import TopAbs_EDGE + from OCP.TopExp import TopExp_Explorer + from OCP.TopoDS import TopoDS + from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt + + right, _, normal = frame + algo = HLRBRep_PolyAlgo() + algo.Load(mesh) + algo.Projector( + HLRAlgo_Projector(gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(*normal), gp_Dir(*right))) + ) + algo.Update() + output = HLRBRep_PolyHLRToShape() + output.Update(algo) + seen = set() + for compound, visible in [ + (output.VCompound(), True), + (output.OutLineVCompound(), True), + (output.HCompound(), False), + (output.OutLineHCompound(), False), + ]: + explorer = TopExp_Explorer(compound, TopAbs_EDGE) + while explorer.More(): + edge = BRepAdaptor_Curve(TopoDS.Edge_s(explorer.Current())) + a, b = ( + edge.Value(t) for t in (edge.FirstParameter(), edge.LastParameter()) + ) + points = [(a.X(), a.Y()), (b.X(), b.Y())] + key = tuple(sorted(tuple(round(v, 7) for v in p) for p in points)) + if math.dist(*points) > 1e-7 and key not in seen: + seen.add(key) + yield points, visible + explorer.Next() diff --git a/src/simplecadapi/dxf_engine/workflow/projection.py b/src/simplecadapi/dxf_engine/workflow/projection.py new file mode 100644 index 00000000..cf9608ad --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/projection.py @@ -0,0 +1,148 @@ +"""Physical model projection and cached view geometry for engineering sheets.""" + +from dataclasses import replace + +from simplecadapi._cpp.occt.BRep import BRep_Builder +from simplecadapi._cpp.occt.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface +from simplecadapi._cpp.occt.BRepBndLib import BRepBndLib +from simplecadapi._cpp.occt.Bnd import Bnd_Box +from simplecadapi._cpp.occt.GeomAbs import ( + GeomAbs_BSplineCurve, + GeomAbs_BSplineSurface, + GeomAbs_Line, +) +from simplecadapi._cpp.occt.TopAbs import TopAbs_SOLID +from simplecadapi._cpp.occt.TopoDS import TopoDS_Compound +from simplecadapi.dxf_engine.refs import view_frame +from simplecadapi.dxf_engine.views import build_view, _cut_near_half, _section_loops +from simplecadapi.inspect import brep + +from .inspection import rigid_shape + +MESH_DEFLECTION_MM = 0.02 + + +def physical_shape(shape, model=None): + """Exclude free PMI presentation or construction geometry from drawing measures.""" + if shape.ShapeType() == TopAbs_SOLID: + return shape + model = model or brep.index_shape_rbrepmodel(shape=shape) + if not model.bodies: + return shape + if len(model.bodies) == 1: + return model.bodies[0] + compound = TopoDS_Compound() + builder = BRep_Builder() + builder.MakeCompound(compound) + for body in model.bodies: + builder.Add(compound, body) + return compound + + +def projected_bounds(shape, frame): + projected = rigid_shape(shape, dict(rotation=frame, translation_mm=(0, 0, 0))) + box = Bnd_Box() + BRepBndLib.AddOptimal_s(projected, box, False, False) + x0, y0, _, x1, y1, _ = box.Get() + return x0, y0, x1, y1 + + +def projection_mode(model): + spline_faces = sum( + BRepAdaptor_Surface(face).GetType() == GeomAbs_BSplineSurface + for face in model.faces + ) + spline_edges = sum( + BRepAdaptor_Curve(edge).GetType() == GeomAbs_BSplineCurve + for edge in model.edges + ) + # Repeated spline flanks with many spline intersections are costly for + # exact HLR in some cameras, even when the solid has few faces. + approximate = ( + spline_faces >= 6 + and spline_edges >= 32 + and spline_edges * 2 >= len(model.edges) + ) + return ("polygonal" if approximate else "exact"), dict( + faces=len(model.faces), + edges=len(model.edges), + spline_faces=spline_faces, + spline_edges=spline_edges, + ) + + +class ProjectedLine: + def GetType(self): + return GeomAbs_Line + + +LINE = ProjectedLine() + + +class DrawingProjection: + def __init__(self, shape, mode="exact", deflection_mm=None): + self.shape = shape + self.mode = mode + self.deflection_mm = deflection_mm + self.cache = {} + self.mesh = None + + def view(self, view, bounds=None): + key = ( + view.shape, + tuple(view.n), + tuple(view.xd), + tuple(view.section) if view.section is not None else None, + ) + cached = self.cache.get(key) + if cached is None: + frame = view_frame(view.n, view.xd) + projected = view.shape + hatch = [] + if view.section is not None: + projected = _cut_near_half(view.shape, view.section, frame) + hatch = _section_loops(projected, view.section, frame) + if not hatch: + raise ValueError( + f"{view.name}: the cutting plane does not pass through the part" + ) + if self.mode == "polygonal": + from .polygonal_hlr import mesh_shape, projected_segments + + if projected is self.shape: + if self.mesh is None: + self.mesh = mesh_shape(projected, self.deflection_mm) + mesh = self.mesh + else: + mesh = mesh_shape(projected, self.deflection_mm) + edges = [ + (LINE, points, visible) + for points, visible in projected_segments(mesh, frame) + if visible or view.section is None + ] + if not edges: + raise ValueError( + f"{view.name}: polygonal HLR produced no projected edges" + ) + xs, ys = zip(*(point for _, points, _ in edges for point in points)) + rendered = (min(xs), min(ys), max(xs), max(ys)) + else: + projection = build_view(replace(view, shape=projected, section=None)) + edges = [ + row for row in projection["edges"] if row[2] or view.section is None + ] + # SDK's full section computes its bounds from visible edges only. + xs, ys = zip(*(point for _, points, _ in edges for point in points)) + rendered = (min(xs), min(ys), max(xs), max(ys)) + measured = ( + bounds if bounds is not None else projected_bounds(projected, frame) + ) + cached = dict( + edges=edges, + lbox=measured, + outline_box=rendered, + hatch=hatch, + frame=frame, + ) + self.cache[key] = cached + return cached diff --git a/src/simplecadapi/dxf_engine/workflow/sheet.py b/src/simplecadapi/dxf_engine/workflow/sheet.py new file mode 100644 index 00000000..7a122efe --- /dev/null +++ b/src/simplecadapi/dxf_engine/workflow/sheet.py @@ -0,0 +1,182 @@ +"""Additional view types for the pinned SimpleCADAPI sheet engine.""" + +from __future__ import annotations + +import math +from dataclasses import replace + +import numpy as np +from simplecadapi._cpp.occt.BRep import BRep_Builder +from simplecadapi._cpp.occt.BRepAdaptor import BRepAdaptor_Surface +from simplecadapi._cpp.occt.GeomAbs import GeomAbs_Plane +from simplecadapi._cpp.occt.TopAbs import TopAbs_REVERSED +from simplecadapi._cpp.occt.TopoDS import TopoDS_Compound +from simplecadapi.dxf_engine import SheetPlan +from simplecadapi.dxf_engine.collide import conflicts +from simplecadapi.dxf_engine.geom2d import Box +from simplecadapi.dxf_engine.refs import view_frame +from simplecadapi.dxf_engine.views import _cut_near_half, _faces, _section_loops +from simplecadapi.inspect.brep.io import measure_shape_mass_rtuple +from simplecadapi.inspect.brep.model import _bounding_box + +from .inspection import rigid_shape + + +def auxiliary_frame(reference, parent, *, reverse=False): + kind, face = reference + if kind != "face": + raise ValueError("An auxiliary face reference must name a planar model face") + surface = BRepAdaptor_Surface(face) + if surface.GetType() != GeomAbs_Plane: + raise ValueError("An auxiliary face reference must name a planar model face") + normal = np.array(surface.Plane().Axis().Direction().Coord()) + if (face.Orientation() == TopAbs_REVERSED) != reverse: + normal *= -1 + hinge = np.cross(parent.n, normal) + length = math.hypot(*hinge) + if length < 1e-8: + raise ValueError( + "An auxiliary view needs a parent that sees the target face edge-on" + ) + return tuple(normal.tolist()), tuple((hinge / length).tolist()) + + +def removed_section(view, volume): + """Use actual cut faces as the projected shape, and preserve their hole loops.""" + frame = view_frame(view.n, view.xd) + point = view.section + cut = _cut_near_half(view.shape, point, frame) + retained, _ = measure_shape_mass_rtuple(cut, kind="volume") + margin = max(1e-9, abs(volume) * 1e-10) + if not margin < retained < volume - margin: + raise ValueError( + f"{view.name}: removed section plane must pass through the solid with material on both sides" + ) + loops = _section_loops(cut, point, frame) + builder = BRep_Builder() + faces = TopoDS_Compound() + builder.MakeCompound(faces) + count = 0 + n = frame[2] + for face in _faces(cut): + surface = BRepAdaptor_Surface(face) + if surface.GetType() != GeomAbs_Plane: + continue + plane = surface.Plane() + axis = plane.Axis().Direction().Coord() + offset = np.subtract(plane.Location().Coord(), point) + if abs(np.dot(axis, n)) > 1 - 1e-8 and abs(np.dot(offset, n)) < 1e-6: + builder.Add(faces, face) + count += 1 + if not count or not loops: + raise ValueError(f"{view.name}: removed section has no usable material loops") + projected = rigid_shape(faces, dict(rotation=frame, translation_mm=(0, 0, 0))) + bounds = _bounding_box(projected) + paper_bounds = (*bounds["min"][:2], *bounds["max"][:2]) + return replace(view, shape=faces, section=None), loops, paper_bounds + + +class ExtendedSheetPlan(SheetPlan): + def __init__(self, decl, removed, auxiliary, projection, projector): + super().__init__(decl) + self.removed = removed + self.auxiliary = auxiliary + self.draft_projection = projection + self.projector = projector + self.auxiliary_marks = [] + self.intent_issues = [] + + def issues(self): + return super().issues() + self.intent_issues + + def _build_view(self, view): + bounds = self.removed[view.name][2] if view.name in self.removed else None + return self.projector.view(view, bounds) + + def _solve_sections(self): + # Reuse the SDK's cutting-plane marks, while only the cut faces enter HLR. + for name, (point, loops, bounds) in self.removed.items(): + # Sampled HLR points can miss a circle's extrema. Use kernel bounds for section extent dimensions. + view = self.views[name] + view["hatch"] = loops + view["lbox"] = bounds + view["bbox"] = Box(*self.tx(name, bounds[:2]), *self.tx(name, bounds[2:])) + self.by_name[name].section = point + try: + super()._solve_sections() + finally: + for name in self.removed: + self.by_name[name].section = None + + self.auxiliary_marks = [] + for name, (parent, label) in self.auxiliary.items(): + target = self.views[name]["bbox"] + source = self.views[parent]["bbox"] + right, up, _ = self.views[parent]["frame"] + n = self.by_name[name].n + u, v = float(np.dot(n, right)), float(np.dot(n, up)) + half = ((source.x1 - source.x0) / 2, (source.y1 - source.y0) / 2) + center = ((source.x1 + source.x0) / 2, (source.y1 + source.y0) / 2) + border = min(a / abs(d) for a, d in zip(half, (u, v)) if abs(d) > 1e-9) + tip = center[0] + (border + 2) * u, center[1] + (border + 2) * v + tail = tip[0] + 7 * u, tip[1] + 7 * v + caption = f"AUX {label}" + positions = [ + ((tail[0] - 4 * v, tail[1] + 4 * u), label, parent), + (((target.x0 + target.x1) / 2, target.y1 + 5), caption, name), + ] + for index, (point, text, view) in enumerate(positions): + key = f"aux:{name}:{index}" + height, width = 3.5, max(3.5, len(text) * 2.5) + line = [(tip, tail)] if index == 0 else [] + hits = conflicts(self, key, view, *point, width, height, 0, line) + if hits: + obstacle = ", ".join(sorted({hit["id"] for hit in hits})) + raise ValueError( + f"Auxiliary mark {label}: adjust view placement to clear {obstacle}" + ) + self.text_obbs.append((key, *point, width, height, 0)) + for start, end in line: + self._reg_seg(key, start, end) + self.auxiliary_marks.append((tip, tail, (u, v), positions)) + + def projection_bounds(self): + return { + name: { + "brep_bounds_mm": view["lbox"], + "sampled_outline_bounds_mm": view["outline_box"], + "max_outline_gap_mm": max( + abs(a - b) for a, b in zip(view["lbox"], view["outline_box"]) + ), + } + for name, view in self.views.items() + } + + +def decorate_views(doc, plan): + """Write solved auxiliary marks and the explicitly selected projection label.""" + from ezdxf.enums import TextEntityAlignment + + msp = doc.modelspace() + changed = bool(plan.auxiliary_marks or plan.draft_projection is not None) + if plan.draft_projection is not None: + cell = (plan.fmt.title[0] + 46.5, plan.fmt.title[1] + 18.0) + text = next( + entity + for entity in msp.query("TEXT") + if math.dist(tuple(entity.dxf.insert)[:2], cell) < 1e-7 + ) + text.dxf.text = f"mm · {plan.draft_projection}-angle" + for tip, tail, (u, v), labels in plan.auxiliary_marks: + layer = {"layer": "DIMENSION"} + base = tip[0] + 2.5 * u, tip[1] + 2.5 * v + msp.add_line(base, tail, dxfattribs=layer) + msp.add_solid( + [tip, (base[0] - v, base[1] + u), (base[0] + v, base[1] - u)], + dxfattribs=layer, + ) + for point, label, _ in labels: + msp.add_text( + label, dxfattribs={"layer": "TEXT", "height": 3.5} + ).set_placement(point, align=TextEntityAlignment.MIDDLE_CENTER) + return changed diff --git a/test/test_dxf_workflow_auto_drawing.py b/test/test_dxf_workflow_auto_drawing.py new file mode 100644 index 00000000..790c4090 --- /dev/null +++ b/test/test_dxf_workflow_auto_drawing.py @@ -0,0 +1,165 @@ +import hashlib +import json +import subprocess +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path + +import ezdxf +import simplecadapi as scad +from ezdxf.lldxf.tagwriter import TagCollector +from simplecadapi.kernel.ocp_export import export_step_shapes + + +class AutomaticDrawingTests(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.root = Path(folder.name) + self.step = self.root / "plate.step" + + def make_plate(self, *, hole=False): + solid = scad.make_box_rsolid(width=30, height=20, depth=10) + if hole: + cylinder = scad.make_cylinder_rsolid( + radius=2, height=12, bottom_face_center=(3, 1, -1) + ) + solid = scad.cut_rsolid(solid, cylinder, on_split="error") + export_step_shapes([solid.wrapped], str(self.step)) + + def cli(self, out, *args): + return subprocess.run( + [ + sys.executable, + "-m", + "simplecadapi.cli", + "drawing", + "--step", + str(self.step), + "--out", + str(out), + *args, + ], + capture_output=True, + text=True, + encoding="utf-8", + timeout=45, + check=True, + ) + + def test_plan_only_emits_machine_readable_decisions_and_skips_unhelpful_cut(self): + self.make_plate() + output = self.root / "planned.dxf" + result = json.loads( + self.cli( + output, + "--mode", + "auto", + "--plan-only", + "--primary-view", + "front", + "--sheet", + "A4", + "--dimensions", + "overall", + ).stdout + ) + report = json.loads(Path(result["plan"]).read_text(encoding="utf-8")) + self.assertEqual(report["section"]["status"], "not_proposed") + self.assertEqual(report["view_selection"]["primary_source_frame"], "front") + self.assertTrue(report["view_selection"]["forced"]) + self.assertEqual(len(report["view_selection"]["candidates"]), 6) + self.assertEqual( + report["source"]["sha256"], + hashlib.sha256(self.step.read_bytes()).hexdigest(), + ) + self.assertEqual( + sorted(d["value_mm"] for d in report["dimensions"]["measured"]), + [10, 20, 30], + ) + self.assertFalse(output.exists()) + self.assertFalse(output.with_suffix(".png").exists()) + + def test_visible_bore_drives_view_cut_and_dimension_and_declaration_replays(self): + self.make_plate(hole=True) + output = self.root / "auto.dxf" + result = json.loads(self.cli(output, "--mode", "auto").stdout) + report = json.loads(Path(result["plan"]).read_text(encoding="utf-8")) + self.assertIn( + report["view_selection"]["primary_source_frame"], ("top", "bottom") + ) + self.assertEqual(report["section"]["status"], "proposed") + self.assertEqual(len(report["section"]["selected"]["bore_axis_refs"]), 1) + self.assertEqual(result["dimension_count"], 4) + self.assertEqual(report["dimensions"]["bore_groups"][0]["status"], "proposed") + self.assertEqual(report["render"]["audit"]["audit_errors"], 0) + + replay = self.root / "replay.dxf" + self.cli( + replay, "--mode", "engineering", "--drawing-json", result["declaration"] + ) + geometry = [] + for path in (output, replay): + doc = ezdxf.readfile(path) + entities = doc.modelspace() + self.assertGreater(len(entities.query("HATCH")), 0) + measurements = [ + abs(dim.get_measurement()) + * doc.dimstyles.get(dim.dxf.dimstyle).dxf.dimlfac + for dim in entities.query("DIMENSION") + ] + self.assertEqual( + sorted(round(value, 5) for value in measurements), [4, 10, 20, 30] + ) + # The PNG backend jitters hatch rasterization slightly. Compare the exported DXF geometry. + geometry.append( + Counter( + tuple( + ( + tag.code, + round(tag.value, 8) + if isinstance(tag.value, float) + else tag.value, + ) + for tag in TagCollector.dxftags(entity) + if tag.code not in (5, 330) + ) + for entity in entities + ) + ) + self.assertTrue(path.with_suffix(".png").is_file()) + self.assertEqual(*geometry) + + def test_template_records_basis_and_compact_third_angle_layout(self): + self.make_plate(hole=True) + out = self.root / "compact.dxf" + result = json.loads( + self.cli( + out, + "--mode", + "auto", + "--template", + "asme-machining", + "--layout", + "compact", + "--section-view", + "full", + ).stdout + ) + report = json.loads(Path(result["plan"]).read_text(encoding="utf-8")) + decl = json.loads(Path(result["declaration"]).read_text(encoding="utf-8")) + self.assertEqual(report["template"]["id"], "asme-machining") + self.assertEqual(decl["sheet"]["projection"], "third") + self.assertIn(report["section"]["replaces_view"], ("top", "right")) + self.assertEqual(len(decl["views"]), 3) + self.assertEqual( + {row["align"]["side"] for row in decl["views"] if "align" in row}, + {"above", "right"}, + ) + doc = ezdxf.readfile(out) + self.assertIn( + "mm · third-angle", + [label.dxf.text for label in doc.modelspace().query("TEXT")], + ) diff --git a/test/test_dxf_workflow_engineering_drawing.py b/test/test_dxf_workflow_engineering_drawing.py new file mode 100644 index 00000000..96d19453 --- /dev/null +++ b/test/test_dxf_workflow_engineering_drawing.py @@ -0,0 +1,352 @@ +import copy +import subprocess +import sys +import math +import tempfile +import unittest +from pathlib import Path + +import ezdxf +import simplecadapi as scad +from ezdxf.math import BoundingBox2d +from ezdxf.xclip import XClip +from PIL import Image +from simplecadapi.kernel.ocp_export import export_step_shapes + +from simplecadapi.dxf_engine.workflow.declaration import ( + build_plan, + export_engineering_sheet, + load_engineering_shape, +) +from simplecadapi.dxf_engine.workflow.inspection import rigid_shape + + +class EngineeringDrawingTests(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.root = Path(folder.name) + self.spec = { + "sheet": {"scale": 0.5, "auto_centers": False}, + "views": [ + {"name": "top", "frame": "top"}, + { + "name": "cut", + "frame": "front", + "align": {"to": "top", "gap": 28}, + "section": {"point": [0, 1, 5], "label": "A", "mark_in": "top"}, + }, + ], + "dimensions": [ + { + "caption": "width", + "kind": "overall", + "view": "top", + "semantic": "linear", + "extent": "x", + }, + { + "caption": "bore", + "kind": "size", + "view": "top", + "semantic": "diameter", + "of": {"cylinder": {"axis_point": [3, 1, 5], "axis": [0, 0, 1]}}, + }, + ], + } + + def step_with_hole(self, radius): + block = scad.make_box_rsolid(width=30, height=20, depth=10) + cylinder = scad.make_cylinder_rsolid( + radius=radius, height=12, bottom_face_center=(3, 1, -1) + ) + part = scad.cut_rsolid(block, cylinder, on_split="error") + source = self.root / f"plate-{radius}.step" + export_step_shapes([part.wrapped], str(source)) + return source + + def test_section_and_bound_diameter_follow_edited_step(self): + for radius in (2, 3): + output = self.root / f"drawing-{radius}.dxf" + meta = export_engineering_sheet( + self.step_with_hole(radius), output, self.spec + ) + self.assertEqual(meta["reopen_audit"]["audit_errors"], 0) + self.assertEqual( + {d["caption"]: d["value_mm"] for d in meta["dimensions"]}, + {"width": 30, "bore": 2 * radius}, + ) + doc = ezdxf.readfile(output) + self.assertGreater(len(doc.modelspace().query("HATCH")), 0) + dimensions = doc.modelspace().query("DIMENSION") + self.assertEqual(len(dimensions), 2) + diameter = next(d for d in dimensions if d.dimtype == 3) + scale_factor = doc.dimstyles.get(diameter.dxf.dimstyle).dxf.dimlfac + self.assertAlmostEqual( + diameter.get_measurement() * scale_factor, 2 * radius + ) + self.assertEqual(diameter.override()["dimtxsty"], "DXF_EXPORTER_DIM_SYMBOL") + self.assertTrue(output.with_suffix(".png").is_file()) + self.assertFalse(output.with_suffix(".pdf").exists()) + + def test_dimension_conflict_stops_before_publication(self): + spec = copy.deepcopy(self.spec) + spec["dimensions"][1]["value"] = 30 + output = self.root / "rejected.dxf" + with self.assertRaisesRegex(ValueError, "DIM_VALUE_MISMATCH"): + export_engineering_sheet(self.step_with_hole(2), output, spec) + self.assertFalse(any(self.root.glob("rejected.*"))) + + def test_detail_clipping_and_printed_scale(self): + import pymupdf + + spec = copy.deepcopy(self.spec) + spec["details"] = [ + { + "label": "B", + "parent": "top", + "center": [6, 5, 10], + "size_mm": [16, 14], + "position_mm": [305, 210], + "scale": 2, + } + ] + output = self.root / "detail.dxf" + meta = export_engineering_sheet(self.step_with_hole(2), output, spec, pdf=True) + expected = (289, 196), (321, 224) + self.assertEqual(meta["details"][0]["clip_sheet_mm"], list(expected)) + doc = ezdxf.readfile(output) + insert = doc.modelspace().query("INSERT").first + crop = XClip(insert) + self.assertTrue(crop.is_clipping_enabled) + bounds = BoundingBox2d(crop.get_wcs_clipping_path().vertices) + self.assertEqual((tuple(bounds.extmin), tuple(bounds.extmax)), expected) + self.assertEqual(insert.dxf.xscale, 4) + self.assertGreater(len(doc.blocks[insert.dxf.name].query("CIRCLE")), 0) + + mm_per_point = 25.4 / 72 + with pymupdf.open(output.with_suffix(".pdf")) as pdf: + self.assertEqual(len(pdf), 1) + page = pdf[0] + self.assertAlmostEqual(page.rect.width * mm_per_point, 420, places=3) + self.assertAlmostEqual(page.rect.height * mm_per_point, 297, places=3) + self.assertFalse(page.get_images()) + expected_border = (289, 297 - 224, 321, 297 - 196) + self.assertTrue( + any( + all( + abs(value * mm_per_point - coordinate) < 0.01 + for value, coordinate in zip(drawing["rect"], expected_border) + ) + for drawing in page.get_drawings() + ) + ) + + spec["details"][0]["position_mm"] = [210, 210] + with self.assertRaisesRegex(ValueError, "clear of views"): + export_engineering_sheet( + self.root / "plate-2.step", self.root / "overlap.dxf", spec + ) + self.assertFalse(any(self.root.glob("overlap.*"))) + + def test_removed_section_omits_rear_edges_and_keeps_analytic_profile(self): + block = scad.make_box_rsolid(width=30, height=20, depth=10) + boss = scad.make_cylinder_rsolid( + radius=5, height=9, bottom_face_center=(0, 0, 9) + ) + raised = scad.union_rsolid(block, boss) + bore = scad.make_cylinder_rsolid( + radius=2, height=20, bottom_face_center=(0, 0, -1) + ) + part = scad.cut_rsolid(raised, bore, on_split="error") + step = self.root / "raised.step" + export_step_shapes([part.wrapped], str(step)) + cut = { + "name": "profile", + "frame": "top", + "align": {"to": "front", "side": "below", "gap": 33}, + "section": {"point": [0, 0, 13], "label": "A", "mark_in": "front"}, + } + spec = {"views": [{"name": "front", "frame": "front"}, cut]} + shape = load_engineering_shape(step) + full = build_plan(shape, spec, "Raised boss") + cut["section"]["kind"] = "removed" + profile = build_plan(shape, spec, "Raised boss") + self.assertEqual(len(profile.views["profile"]["hatch"]), 2) + self.assertAlmostEqual( + full.views["profile"]["lbox"][2] - full.views["profile"]["lbox"][0], 30 + ) + self.assertAlmostEqual( + profile.views["profile"]["lbox"][2] - profile.views["profile"]["lbox"][0], + 10, + ) + out = self.root / "removed.dxf" + export_engineering_sheet(step, out, spec) + entities = ezdxf.readfile(out).modelspace() + self.assertEqual(len(entities.query("HATCH").first.paths.paths), 2) + self.assertEqual( + sorted( + round(circle.dxf.radius / profile.s, 5) + for circle in entities.query("CIRCLE") + ), + [2, 5], + ) + + def test_a0_preview_is_capped_and_vector_pdf_stays_full_size(self): + import pymupdf + from simplecadapi.dxf_engine.workflow.details import PREVIEW_LONG_SIDE_PX + from unittest.mock import patch + + solid = scad.make_box_rsolid(width=30, height=20, depth=10) + step = self.root / "large-sheet.step" + export_step_shapes([solid.wrapped], str(step)) + out = self.root / "a0.dxf" + spec = dict( + sheet={"sheet": "A0", "scale": 1}, + views=[{"name": "front", "frame": "front"}], + ) + with patch( + "simplecadapi.dxf_engine.planner.SheetPlan.render", + side_effect=AssertionError("intermediate PNG"), + ): + result = export_engineering_sheet(step, out, spec, pdf=True) + self.assertEqual(result["reopen_audit"]["audit_errors"], 0) + with Image.open(out.with_suffix(".png")) as preview: + self.assertEqual(list(preview.size), result["preview"]["pixels"]) + self.assertLessEqual(max(preview.size), PREVIEW_LONG_SIDE_PX) + with pymupdf.open(out.with_suffix(".pdf")) as pdf: + self.assertAlmostEqual(pdf[0].rect.width * 25.4 / 72, 1189, places=3) + self.assertAlmostEqual(pdf[0].rect.height * 25.4 / 72, 841, places=3) + + def test_extent_ignores_presentation_wire_and_uses_solid(self): + from simplecadapi._cpp.occt.BRep import BRep_Builder + from simplecadapi._cpp.occt.BRepBuilderAPI import BRepBuilderAPI_MakeEdge + from simplecadapi._cpp.occt.TopoDS import TopoDS_Compound + from simplecadapi._cpp.occt.gp import gp_Pnt + + solid = scad.make_box_rsolid(width=30, height=20, depth=10) + model = TopoDS_Compound() + builder = BRep_Builder() + builder.MakeCompound(model) + builder.Add(model, solid._native_wrapped) + builder.Add( + model, BRepBuilderAPI_MakeEdge(gp_Pnt(0, 0, 30), gp_Pnt(0, 5, 30)).Edge() + ) + spec = { + "views": [{"name": "front", "frame": "front"}], + "dimensions": [ + { + "caption": "z height", + "view": "front", + "kind": "overall", + "semantic": "linear", + "extent": "y", + } + ], + } + plan = build_plan(model, spec, "Solid with presentation edge") + self.assertAlmostEqual(plan.dims[0]._measured, 10) + self.assertAlmostEqual( + plan.projection_bounds()["front"]["max_outline_gap_mm"], 0 + ) + + def test_a_transform_without_translation_is_a_clear_error(self): + block = scad.make_box_rsolid(width=30, height=20, depth=10) + with self.assertRaisesRegex(ValueError, "translation_mm"): + rigid_shape(block.wrapped, dict(rotation=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])) + + def test_an_inspection_sheet_reuses_the_layout_the_cli_wrote(self): + block = scad.make_box_rsolid(width=30, height=20, depth=10) + step = self.root / "block.step" + export_step_shapes([block.wrapped], str(step)) + first, second = self.root / "first.dxf", self.root / "second.dxf" + for out, extra in ((first, []), (second, ["--layout-json", str(first.with_suffix(".json"))])): + result = subprocess.run( + [sys.executable, "-m", "simplecadapi.cli", "drawing", "--mode", "inspection", + "--step", str(step), "--out", str(out)] + extra, + capture_output=True, text=True, encoding="utf-8", timeout=120, + ) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + self.assertTrue(second.exists()) + + def test_face_auxiliary_and_explicit_annotations_export_in_third_angle(self): + from simplecadapi._cpp.occt.BRepAdaptor import BRepAdaptor_Surface + from simplecadapi.inspect import brep + + block = scad.make_box_rsolid(width=30, height=20, depth=10) + c, s = math.cos(math.pi / 6), math.sin(math.pi / 6) + shape = rigid_shape( + block.wrapped, + dict(rotation=[[c, 0, s], [0, 1, 0], [-s, 0, c]], translation_mm=[0, 0, 0]), + ) + step = self.root / "sloping.step" + export_step_shapes([shape], str(step)) + shape = load_engineering_shape(step) + model = brep.index_shape_rbrepmodel(shape=shape) + face = next( + f + for f in model.faces + if abs(abs(BRepAdaptor_Surface(f).Plane().Axis().Direction().Z()) - c) + < 1e-6 + ) + spec = { + "sheet": { + "projection": "third", + "scale": 1, + "auto_centers": False, + "notes": ["Review geometry."], + }, + "views": [ + {"name": "front", "frame": "front"}, + { + "name": "face_view", + "align": {"to": "front", "side": "left", "gap": 42}, + "auxiliary": { + "mark_in": "front", + "label": "B", + "face": {"entity": model.id_for_shape("face", face)}, + }, + }, + ], + "roughness": [ + {"view": "front", "on": [10 * s, 0, 10 * c], "text": "Ra 3.2"} + ], + "leaders": [ + { + "view": "front", + "anchor": [15 * c, 0, -15 * s], + "off": [36, -24], + "lines": ["INSPECT EDGE"], + } + ], + "centerlines": [{"view": "front", "p1": [-5, 0, 4], "p2": [5, 0, 4]}], + "control_frames": [ + { + "view": "front", + "name": "face-flatness", + "anchor": [-15 * c + 10 * s, 0, 15 * s + 10 * c], + "characteristic": "flatness", + "value": 0.05, + "offset": [38, 26], + } + ], + } + plan = build_plan(shape, spec, "Sloping plate") + axis = BRepAdaptor_Surface(face).Plane().Axis().Direction().Coord() + self.assertAlmostEqual( + abs(sum(a * b for a, b in zip(axis, plan.by_name["face_view"].n))), 1.0 + ) + out = self.root / "aux.dxf" + meta = export_engineering_sheet(step, out, spec) + self.assertEqual(meta["projection"], "third") + doc = ezdxf.readfile(out) + symbols = {label.dxf.text for label in doc.modelspace().query("TEXT")} + self.assertTrue( + {"AUX B", "Ra 3.2", "INSPECT EDGE", "mm · third-angle", "0.05"} <= symbols + ) + self.assertTrue(doc.modelspace().query('LWPOLYLINE[layer=="FEATURE_CONTROL"]')) + self.assertTrue(doc.modelspace().query('LINE[layer=="05_CENTER"]')) + self.assertEqual(meta["control_frames"][0]["value"], 0.05) + spec["control_frames"][0]["datums"] = ["Q"] + with self.assertRaisesRegex(ValueError, "declared on this sheet"): + build_plan(shape, spec, "Sloping plate") diff --git a/test/test_dxf_workflow_model_to_dxf.py b/test/test_dxf_workflow_model_to_dxf.py new file mode 100644 index 00000000..6bf70168 --- /dev/null +++ b/test/test_dxf_workflow_model_to_dxf.py @@ -0,0 +1,147 @@ +import tempfile +import unittest +from pathlib import Path + +import numpy as np +import ezdxf +import simplecadapi as scad +from simplecadapi.kernel.ocp_export import export_step_shapes +from simplecadapi.dxf_engine.workflow import inspection as tool + + +class ModelDrawingTests(unittest.TestCase): + def test_collapsed_HLR_edges_are_retained_as_audited_points(self): + from unittest.mock import patch + from types import SimpleNamespace + + class Point: + def X(self): + return 1.0 + + def Y(self): + return 2.0 + + ad = SimpleNamespace( + FirstParameter=lambda: 0.0, + LastParameter=lambda: 1.0, + Value=lambda t: Point(), + ) + with patch.object(tool, "discretize_edge", return_value=(ad, [(1.0, 2.0)])): + edge = tool.edge_record(object(), 0.03) + self.assertEqual(edge["kind"], "POINT") + self.assertEqual(edge["projected_extent_mm"], 0.0) + fake = { + "views": { + n: dict(bounds=[[0, 0], [20, 10]], edges=[dict(edge, visible=True)]) + for n in tool.frames() + } + } + layout = tool.sheet_layout([fake]) + doc = tool.new_document(layout) + tool.add_geometry(doc.modelspace(), fake, layout) + self.assertEqual(len(list(doc.modelspace().query("POINT"))), 7) + + def test_frames_are_proper_and_projection_layout_is_explicit(self): + for f in tool.frames().values(): + np.testing.assert_allclose( + np.cross(f["right"], f["up"]), -np.asarray(f["direction"]), atol=1e-10 + ) + fake = {"views": {n: dict(bounds=[[0, 0], [20, 10]]) for n in tool.frames()}} + first = tool.sheet_layout([fake], "first") + third = tool.sheet_layout([fake], "third") + self.assertLess(first["cells"]["top"][1], first["cells"]["front"][1]) + self.assertLess(first["cells"]["right"][0], first["cells"]["front"][0]) + self.assertGreater(third["cells"]["top"][1], third["cells"]["front"][1]) + self.assertGreater(third["cells"]["right"][0], third["cells"]["front"][0]) + + def test_real_offset_blind_hole_visibility_curves_and_independent_export(self): + box = scad.make_box_rsolid(width=20.0, height=14.0, depth=10.0) + cutter = scad.make_cylinder_rsolid( + radius=2.0, height=3.0, bottom_face_center=(3.0, 1.0, 7.0) + ) + solid = scad.cut_rsolid(box, cutter, on_split="error") + with tempfile.TemporaryDirectory() as folder: + folder = Path(folder) + source = folder / "hole.step" + export_step_shapes([solid.wrapped], str(source)) + p = tool.project_step(source) + circles = lambda v: [ + e + for e in p["views"][v]["edges"] + if e["kind"] == "CIRCLE" and abs(e["radius"] - 2) < 1e-6 + ] + self.assertTrue(any(e["visible"] for e in circles("top"))) + self.assertFalse(any(e["visible"] for e in circles("bottom"))) + self.assertTrue(any(not e["visible"] for e in circles("bottom"))) + np.testing.assert_allclose( + circles("top")[0]["center"], [3.0, 1.0], atol=1e-6 + ) + np.testing.assert_allclose( + circles("bottom")[0]["center"], [3.0, -1.0], atol=1e-6 + ) + q = tool.project_step( + source, + transform=dict( + rotation=np.eye(3).tolist(), translation_mm=[4.0, 5.0, 6.0] + ), + ) + qc = [ + e + for e in q["views"]["top"]["edges"] + if e["kind"] == "CIRCLE" and abs(e["radius"] - 2) < 1e-6 + ] + np.testing.assert_allclose(qc[0]["center"], [7.0, 6.0], atol=1e-6) + layout = tool.sheet_layout([p, q]) + meta = tool.export_sheet(p, folder / "sheet.dxf", layout=layout) + self.assertEqual(meta["reopen_audit"]["audit_errors"], 0) + doc = ezdxf.readfile(folder / "sheet.dxf") + self.assertTrue(list(doc.modelspace().query("CIRCLE"))) + self.assertTrue(list(doc.modelspace().query("LINE"))) + for suffix in [".png", ".svg", ".json"]: + self.assertTrue((folder / ("sheet" + suffix)).exists()) + previews = list( + tool.export_view_previews( + folder / "sheet.dxf", layout, folder / "sheet_views" + ).values() + ) + self.assertEqual(len(previews), 7) + import xml.etree.ElementTree as ET + + for preview in previews: + root = ET.parse(preview).getroot() + self.assertTrue(root.attrib.get("viewBox")) + # Common layout must preserve the deliberate translation, not re-center q. + np.testing.assert_allclose( + np.asarray(qc[0]["center"]) - circles("top")[0]["center"], [4, 5] + ) + for r in [np.diag([-1.0, 1.0, 1.0]), np.eye(3) * 2]: + with self.assertRaises(ValueError): + tool.rigid_shape( + solid.wrapped, + dict(rotation=r.tolist(), translation_mm=[0, 0, 0]), + ) + self.assertTrue( + all( + v["input_hlr_edges"] + == len(v["edges"]) + v["duplicate_edges_removed"] + for v in p["views"].values() + ) + ) + plain = folder / "missing_hole.step" + export_step_shapes([box.wrapped], str(plain)) + missing = tool.project_step(plain) + self.assertFalse( + any(e["kind"] == "CIRCLE" for e in missing["views"]["top"]["edges"]) + ) + tool.export_overlay(p, missing, folder / "overlay.dxf", layout=layout) + overlay = ezdxf.readfile(folder / "overlay.dxf") + self.assertTrue( + list(overlay.modelspace().query('CIRCLE[layer=="REFERENCE"]')) + ) + self.assertFalse( + list(overlay.modelspace().query('CIRCLE[layer=="CANDIDATE"]')) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_dxf_workflow_notebook_drawing.py b/test/test_dxf_workflow_notebook_drawing.py new file mode 100644 index 00000000..dde343ae --- /dev/null +++ b/test/test_dxf_workflow_notebook_drawing.py @@ -0,0 +1,133 @@ +import json +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest + +import ezdxf + + +class NotebookDrawingTests(unittest.TestCase): + def test_dimensionless_vars_and_explicit_units(self): + import simplecadapi as scad + from simplecadapi.dxf_engine.workflow.notebook import parameter_value + + count = scad.var("bolt_count", 8) + self.assertEqual(parameter_value(count, None, "BOLT_COUNT"), (8.0, None, False)) + legacy_length = scad.var("slot_width", 34.0) + self.assertEqual( + parameter_value(legacy_length, "mm", "SLOT_W"), (34.0, "mm", True) + ) + metric_value = scad.var("bearing_width", 2.0, unit="cm") + self.assertEqual( + parameter_value(metric_value, None, "bearing_width"), (20.0, "cm", True) + ) + + def test_compact_layout_section_keeps_the_replaced_view_for_design_intent(self): + # With the compact layout a full section replaces one of the views; the notebook's design + # intent names that view, so the section must keep its name for the dimensions to resolve. + directory = Path(__file__).resolve().parent + sample = directory.parent / "examples/dxf_exporter/stepped_mount.py" + with TemporaryDirectory() as tmp: + out = Path(tmp) / "compact.dxf" + result = subprocess.run( + [sys.executable, "-m", "simplecadapi.cli", "drawing", "--notebook", str(sample), + "--layout", "compact", "--out", str(out)], + capture_output=True, text=True, encoding="utf-8", timeout=120, + ) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + spec = json.loads(out.with_suffix(".drawing.json").read_text(encoding="utf-8")) + sections = [view for view in spec["views"] if "section" in view] + self.assertEqual(len(sections), 1) + self.assertIn(sections[0]["name"], {"top", "right"}) + self.assertTrue(out.exists()) + + def test_notebook_overrides_rebuild_native_dimensions_and_audit_unbound_parameter( + self, + ): + directory = Path(__file__).resolve().parent + sample = directory.parent / "examples/dxf_exporter/stepped_mount.py" + with TemporaryDirectory() as tmp: + root = Path(tmp) + args = [ + sys.executable, + "-m", + "simplecadapi.cli", + "drawing", + "--primary-view", + "top", + "--no-section", + "--sheet", + "A3", + ] + for name, wanted, overrides in [ + ("base", {6, 31, 8}, []), + ( + "changed", + {8, 36}, + ["--set", "HOLE_DIAMETER=8", "--set", "HOLE_PITCH=36"], + ), + ]: + out = root / f"{name}.dxf" + result = subprocess.run( + args + ["--notebook", str(sample), "--out", str(out)] + overrides, + capture_output=True, + text=True, + encoding="utf-8", + timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + data = json.loads(out.with_suffix(".json").read_text(encoding="utf-8")) + coverage = data["design_intent"]["parameters"] + self.assertEqual( + { + d["measured_mm"] + for p in coverage + if p["status"] == "verified" + for d in p["dimensions"] + }, + wanted, + ) + self.assertEqual( + [p["name"] for p in coverage if p["status"] == "unbound"], + ["TOOL_CLEARANCE"], + ) + doc = ezdxf.readfile(out) + dimensions = doc.modelspace().query("DIMENSION") + self.assertEqual(len(dimensions), 6) + actual = { + round( + abs(d.get_measurement()) + * doc.dimstyles.get(d.dxf.dimstyle).dxf.dimlfac, + 6, + ) + for d in dimensions + } + self.assertEqual(actual, wanted | {50, 80, 12}) + + # Keep the geometry unchanged and offset the expected dimension by + # less than the SDK's generic mismatch threshold of 0.005 mm. + bad_model = root / "bad_model.py" + source = sample.read_text(encoding="utf-8") + source = source.replace( + '"parameter": "HOLE_PITCH",', + '"parameter": "HOLE_PITCH", "factor": 1.0001,', + ) + bad_model.write_text(source, encoding="utf-8") + rejected = root / "rejected.dxf" + failure = subprocess.run( + args + ["--notebook", str(bad_model), "--out", str(rejected)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=60, + ) + self.assertEqual(failure.returncode, 1, failure.stderr + failure.stdout) + self.assertFalse(rejected.exists()) + plan = json.loads( + rejected.with_suffix(".plan.json").read_text(encoding="utf-8") + ) + self.assertIn( + "DESIGN_INTENT_MISMATCH", [issue["code"] for issue in plan["issues"]] + )