diff --git a/src/draftwright/_pmi_linear_geometry.py b/src/draftwright/_pmi_linear_geometry.py index 1f5ef826..e4bbd9d0 100644 --- a/src/draftwright/_pmi_linear_geometry.py +++ b/src/draftwright/_pmi_linear_geometry.py @@ -4,6 +4,11 @@ import math +from draftwright._pmi_topology import ( + _is_mixed_planar_bore, + _parallel_planar_reference_witness, + _planar_bore_axis_witness, +) from draftwright.model.ir import _linear_projection_view _LINEAR_AXIS_ABS_TOL = 0.005 @@ -13,6 +18,47 @@ _LINEAR_OBLIQUE_VALUE_ABS_TOL = 0.05 +def _proved_planar_linear(groups, stations, nominal, kind, frame, shape_bbox): + """Resolve the normal span and a face-supported projected witness together.""" + axis, view, witness = _parallel_planar_reference_witness(groups, frame, shape_bbox) + if witness is None: + return ( + tuple(point for point in stations if point is not None), + "?", + None, + ("parallel planar source faces have no proven shared witness",), + ) + if axis is None and kind == "linear" and _is_mixed_planar_bore(groups): + bore_support = _planar_bore_axis_witness(groups, frame, shape_bbox) + if bore_support is None: + points, dominant, reasons = _dimension_reference_stations( + tuple(stations), nominal, kind + ) + return ( + points, + dominant, + None, + ( + *reasons, + "plane-to-bore location has no proven face-supported axis witness", + ), + ) + stations, axis, view = bore_support + if witness: + stations = tuple( + tuple( + next((value for index, value in witness if index == i), point[i]) for i in range(3) + ) + if point is not None + else None + for point in stations + ) + points, dominant, reasons = _dimension_reference_stations( + tuple(stations), nominal, kind, plane_axis=axis + ) + return points, dominant, view, reasons + + def _linear_reference_stations( stations: tuple[tuple[float, float, float] | None, ...], nominal: float, diff --git a/src/draftwright/_pmi_topology.py b/src/draftwright/_pmi_topology.py index d71127eb..e468c9a9 100644 --- a/src/draftwright/_pmi_topology.py +++ b/src/draftwright/_pmi_topology.py @@ -6,7 +6,7 @@ from __future__ import annotations -from draftwright._pmi_datum_geometry import _frame_vector +from draftwright._pmi_datum_geometry import _frame_point, _frame_vector from draftwright._pmi_support_blockers import _failure_reason try: @@ -20,14 +20,21 @@ def _parallel_planar_reference_support(groups, frame, shape_bbox) -> tuple[str | None, str | None]: """Find the common principal normal and any required witness view.""" + axis, view, _witness = _parallel_planar_reference_witness(groups, frame, shape_bbox) + return axis, view + + +def _parallel_planar_reference_witness(groups, frame, shape_bbox): + """Prove a view and, when its default midpoint misses, a shared face witness.""" from OCP.BRepAdaptor import BRepAdaptor_Surface from OCP.GeomAbs import GeomAbs_Plane from OCP.TopoDS import TopoDS if len(groups) != 2 or not all(groups): - return None, None + return None, None, () axes: list[int] = [] group_boxes = [] + group_faces = [] for shapes in groups: group_axis = None group_station = None @@ -35,35 +42,209 @@ def _parallel_planar_reference_support(groups, frame, shape_bbox) -> tuple[str | for shape in shapes: try: if shape.ShapeType() != TopAbs_FACE: - return None, None + return None, None, () surface = BRepAdaptor_Surface(TopoDS.Face_s(shape)) if surface.GetType() != GeomAbs_Plane: - return None, None + return None, None, () direction = surface.Plane().Axis().Direction() local = _frame_vector((direction.X(), direction.Y(), direction.Z()), frame) axis_index = max(range(3), key=lambda index: abs(local[index])) if abs(abs(local[axis_index]) - 1.0) > 1e-6: - return None, None + return None, None, () if any(abs(local[index]) > 1e-6 for index in range(3) if index != axis_index): - return None, None + return None, None, () box = shape_bbox(shape) if frame is None else shape_bbox(shape, frame) boxes.append(box) station = (box[axis_index] + box[axis_index + 3]) / 2 if box[axis_index + 3] - box[axis_index] > 1e-5: - return None, None + return None, None, () except Exception: - return None, None + return None, None, () if group_axis is not None and group_axis != axis_index: - return None, None + return None, None, () if group_station is not None and abs(group_station - station) > 1e-5: - return None, None + return None, None, () group_axis, group_station = axis_index, station assert group_axis is not None # Each validated source group contains a face. axes.append(group_axis) group_boxes.append(boxes) + group_faces.append(shapes) if axes[0] != axes[1]: - return None, None - return _supported_planar_view("XYZ"[axes[0]], group_boxes) + return None, None, () + axis = "XYZ"[axes[0]] + if axis == "X": + return _principal_x_planar_witness(group_boxes, group_faces, frame) + view_axis, view = _supported_planar_view(axis, group_boxes) + return view_axis, view, () + + +def _principal_x_planar_witness(group_boxes, group_faces, frame): + # A front projection only needs both planes represented at the same Z; + # parallel face patches may be offset in Y (#2184). The plan fallback, + # however, claims one shared Y/Z point and must prove it on both trims. + if _midpoint_witness_supported(group_boxes, 2): + return "X", None, () + common = _common_x_face_witness(group_boxes, group_faces, frame) + if common is not None: + y, z = common + return "X", "plan", ((1, y), (2, z)) + return None, None, None + + +def _common_x_face_witness(group_boxes, group_faces, frame): + """Find a point in the interiors of both exact, trimmed X faces.""" + candidates = [ + ( + (min(a[4], b[4]) - max(a[1], b[1])) * (min(a[5], b[5]) - max(a[2], b[2])), + max(a[1], b[1]), + max(a[2], b[2]), + min(a[4], b[4]), + min(a[5], b[5]), + a, + b, + group_faces[0][i], + group_faces[1][j], + ) + for i, a in enumerate(group_boxes[0]) + for j, b in enumerate(group_boxes[1]) + if min(a[4], b[4]) >= max(a[1], b[1]) and min(a[5], b[5]) >= max(a[2], b[2]) + ] + for _area, y0, z0, y1, z1, a, b, first, second in sorted( + candidates, key=lambda item: (-item[0], item[1], item[2]) + ): + # Start at the overlap centre, then sample its interior deterministically. + # A bounding box may contain a face hole or a concavity; only OCC's + # trimmed-face classifier can establish a real common witness. + for y_fraction, z_fraction in ((0.5, 0.5),) + tuple( + (i / 10, j / 10) for i in range(1, 10) for j in range(1, 10) + ): + y = y0 + (y1 - y0) * y_fraction + z = z0 + (z1 - z0) * z_fraction + if all( + _point_inside_x_face(face, (box[0] + box[3]) / 2, y, z, frame) + for face, box in ((first, a), (second, b)) + ): + return y, z + return None + + +def _point_inside_x_face(face, x, y, z, frame): + from OCP.BRepClass import BRepClass_FaceClassifier + from OCP.gp import gp_Pnt + from OCP.TopAbs import TopAbs_IN + from OCP.TopoDS import TopoDS + + local = (x, y, z) + world = local if frame is None else frame.to_world(local) + classifier = BRepClass_FaceClassifier() + try: + classifier.Perform(TopoDS.Face_s(face), gp_Pnt(*world), 1e-7) + return classifier.State() == TopAbs_IN + except Exception: + return False + + +def _planar_bore_axis_witness(groups, frame, shape_bbox): + """Prove a location from one principal plane to one finite Z-bore axis. + + A cylindrical face's bbox centre is its axial *height*, not the location + station. The plane must actually contain the axis-aligned witness point; + a bounding-box overlap alone would invent a witness through a trimmed face. + """ + from OCP.BRepAdaptor import BRepAdaptor_Surface + from OCP.BRepClass import BRepClass_FaceClassifier + from OCP.GeomAbs import GeomAbs_Cylinder, GeomAbs_Plane + from OCP.gp import gp_Pnt + from OCP.TopAbs import TopAbs_IN, TopAbs_ON + from OCP.TopoDS import TopoDS + + if len(groups) != 2 or any(len(group) != 1 for group in groups): + return None + try: + faces = tuple(TopoDS.Face_s(group[0]) for group in groups) + surfaces = tuple(BRepAdaptor_Surface(face) for face in faces) + kinds = tuple(surface.GetType() for surface in surfaces) + if kinds not in ((GeomAbs_Plane, GeomAbs_Cylinder), (GeomAbs_Cylinder, GeomAbs_Plane)): + return None + plane_i = kinds.index(GeomAbs_Plane) + bore_i = 1 - plane_i + normal = surfaces[plane_i].Plane().Axis().Direction() + normal = _frame_vector((normal.X(), normal.Y(), normal.Z()), frame) + axis = max(range(3), key=lambda index: abs(normal[index])) + if axis not in (0, 1) or abs(abs(normal[axis]) - 1) > 1e-6: + return None + bore = surfaces[bore_i].Cylinder().Axis() + direction = bore.Direction() + direction = _frame_vector((direction.X(), direction.Y(), direction.Z()), frame) + if abs(abs(direction[2]) - 1) > 1e-6 or max(abs(value) for value in direction[:2]) > 1e-6: + return None + point = bore.Location() + centre = _frame_point((point.X(), point.Y(), point.Z()), frame) + boxes = tuple( + shape_bbox(group[0]) if frame is None else shape_bbox(group[0], frame) + for group in groups + ) + plane_box, bore_box = boxes[plane_i], boxes[bore_i] + z0 = max(plane_box[2], bore_box[2]) + z1 = min(plane_box[5], bore_box[5]) + if z1 - z0 <= 1e-6: + return None + station = (plane_box[axis] + plane_box[axis + 3]) / 2 + if plane_box[axis + 3] - plane_box[axis] > 1e-5: + return None + witness = list(centre) + witness[axis] = station + witness[2] = (z0 + z1) / 2 + world = witness if frame is None else frame.to_world(tuple(witness)) + classifier = BRepClass_FaceClassifier() + classifier.Perform(faces[plane_i], gp_Pnt(*world), 1e-7) + if classifier.State() not in (TopAbs_IN, TopAbs_ON): + return None + points = [tuple(witness), tuple(witness)] + bore_point = list(witness) + bore_point[axis] = centre[axis] + points[bore_i] = tuple(bore_point) + return tuple(points), "XYZ"[axis], "plan" + except Exception: + return None + + +def _is_mixed_planar_bore(groups): + """Recognise the mixed support even when its location proof fails.""" + from OCP.BRepAdaptor import BRepAdaptor_Surface + from OCP.GeomAbs import GeomAbs_Cylinder, GeomAbs_Plane + from OCP.TopoDS import TopoDS + + if len(groups) != 2 or any(len(group) != 1 for group in groups): + return False + try: + kinds = tuple(BRepAdaptor_Surface(TopoDS.Face_s(group[0])).GetType() for group in groups) + return kinds in ((GeomAbs_Plane, GeomAbs_Cylinder), (GeomAbs_Cylinder, GeomAbs_Plane)) + except Exception: + return False + + +def _common_principal_cylinder_axis(references): + """Return a shared principal axis only when every exact cylinder proves it.""" + axes = [] + for reference in references: + vector = reference.axis_direction + axis = max(range(3), key=lambda index: abs(vector[index])) + if abs(abs(vector[axis]) - 1.0) > 1e-6 or any( + abs(vector[index]) > 1e-6 for index in range(3) if index != axis + ): + return "" + axes.append("XYZ"[axis]) + return axes[0] if axes and len(set(axes)) == 1 else "" + + +def _optional_cylinder_support(probe): + """Keep an optional axis probe from erasing otherwise valid source PMI.""" + try: + references, reasons = probe() + return references if not reasons else () + except Exception: + return () def _supported_planar_view(axis: str, group_boxes) -> tuple[str | None, str | None]: diff --git a/src/draftwright/annotations/_common.py b/src/draftwright/annotations/_common.py index 74ea7a5c..8f7d8317 100644 --- a/src/draftwright/annotations/_common.py +++ b/src/draftwright/annotations/_common.py @@ -82,6 +82,7 @@ from draftwright.annotations._placement_occupancy import ( # noqa: F401 — stable _common imports _PAGE_SPANNING_RIDERS, CROSSABLE_TYPES, + DeferredCompactCandidate, annotation_ink_clear, annotation_ink_obstacles, annotation_obstacle_boxes, @@ -89,6 +90,7 @@ balloon_annotation_label_boxes, balloon_geometry_hits_annotation_labels, box_within_page_and_clear, + compact_probe_clear, corridor_blockers, full_strip_message, is_page_spanning_rider, @@ -2253,7 +2255,15 @@ def _compact_strip_candidate_ink(run) -> None: index = next((i for i, (key, _dim) in enumerate(solved) if key == name), None) original = solved[index][1] if index is not None else None others = [item for key, item in solved if key != name] - for candidate in alternatives(original): + for proposal in alternatives(original): + if isinstance(proposal, DeferredCompactCandidate): + if not compact_probe_clear( + dwg, proposal, others, (forbid or {}).get(name), label_clear + ): + continue + candidate = proposal.materialize() + else: + candidate = proposal if ( original is not None and hasattr(candidate, "arc_radius") diff --git a/src/draftwright/annotations/_gdt.py b/src/draftwright/annotations/_gdt.py index 5c98740b..440d03f8 100644 --- a/src/draftwright/annotations/_gdt.py +++ b/src/draftwright/annotations/_gdt.py @@ -22,6 +22,7 @@ from draftwright.annotations._common import ( PRIORITY, CorridorCandidate, + DeferredCompactCandidate, _anno_box, _box_hits, annotation_ink_clear, @@ -80,8 +81,7 @@ class _GdtDropState: def _gdt_glyph(item, draft): """Build the ISO 1101/5459/1302 glyph sketch for one GD&T IR item at the origin - (the :class:`Leader` repositions it). A fresh sketch per call — the leader translate - must not alias a shared object across the strip solve's repeated probe builds.""" + (the :class:`Leader` repositions a moved copy of it).""" if item.kind == "control_frame": tolerance = item.display_tolerance or item.tolerance if item.spherical_diameter: @@ -324,17 +324,30 @@ def _gdt_visual_finish(glyph, draft, value: str) -> str: return "" -def _attach_gdt_text_evidence(leader, glyph, item, draft) -> None: - """Keep the placed glyph's value beside PDF text for independent PMI lint.""" - leader.pdf_text_relative_specs = _gdt_pdf_text_specs(glyph, item, draft) +def _gdt_text_evidence(glyph, item, draft) -> dict[str, object]: + """Validate one immutable glyph once, independently of its leader position.""" + evidence: dict[str, object] = { + "pdf_text_relative_specs": _gdt_pdf_text_specs(glyph, item, draft) + } if item.kind == "finish": - leader.gdt_visual_finish = _gdt_visual_finish(glyph, draft, item.ra) + evidence["gdt_visual_finish"] = _gdt_visual_finish(glyph, draft, item.ra) if item.kind == "control_frame": zone = _gdt_visual_zone(glyph, draft) - leader.gdt_visual_tolerance = _gdt_visual_tolerance( - glyph, draft, zone, modifier=bool(item.modifier) - ) - leader.gdt_visual_zone = zone if leader.gdt_visual_tolerance else "" + tolerance = _gdt_visual_tolerance(glyph, draft, zone, modifier=bool(item.modifier)) + evidence["gdt_visual_tolerance"] = tolerance + evidence["gdt_visual_zone"] = zone if tolerance else "" + return evidence + + +def _apply_gdt_text_evidence(leader, evidence: dict[str, object]) -> None: + """Keep the validated glyph's value beside PDF text for independent PMI lint.""" + for name, value in evidence.items(): + setattr(leader, name, value) + + +def _attach_gdt_text_evidence(leader, glyph, item, draft) -> None: + """Attach independently checked glyph evidence to a placed leader.""" + _apply_gdt_text_evidence(leader, _gdt_text_evidence(glyph, item, draft)) def _gdt_retry_sides(side: str, *, normal_side_only: bool) -> tuple[str, ...]: @@ -538,7 +551,7 @@ def _retry(): def _gdt_compact_candidates( - original, build, strip, size, horizontal, item, site, tier, material_field + original, build, ink_at, strip, size, horizontal, item, site, tier, material_field ): """Nearest-first same-strip landings checked later against exact ink. @@ -564,14 +577,12 @@ def _gdt_compact_candidates( if travel >= distance - 1e-6: break pos = site + strip.direction * travel - candidate = build(pos) + proposal = ink_at(pos) # A symbol inside the whole-view box must sit in projected # whitespace, not on a blank face with no visible edge. The # shared postsolve also checks visible edges and exact ink. - if _datum_label_has_whitespace( - candidate.label_bbox, strip, horizontal, material_field - ): - yield candidate + if _datum_label_has_whitespace(proposal.label_bbox, strip, horizontal, material_field): + yield proposal near = strip.anchor + strip.direction * (strip.gap + extent / 2.0) distance = (original_pos - near) * strip.direction if distance <= 1e-6: @@ -583,44 +594,78 @@ def _gdt_compact_candidates( pos = near + strip.direction * travel if abs(pos - original_pos) <= 1e-6: return - yield build(pos) + yield ink_at(pos) def _gdt_candidate_builders( item, draft, leader_ctor, fallback_glyph, px, py, horizontal, strip, size, tier, material_field ): """Build one glyph's primary and fallback leaders plus bounded strip retries.""" + # Every retry moves the same validated glyph. Its value/zone checks are expensive + # OCC operations, but do not depend on the eventual leader elbow. + evidence = _gdt_text_evidence(fallback_glyph, item, draft) if item.kind != "note" else {} + glyph_box = fallback_glyph.bounding_box() - def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item): - g = _gdt_glyph(_it, draft) - tip = (_px, _py) + def _elbow(pos, _hz=horizontal): + # Keep the analytical preflight and actual helper's zero-shaft guard identical. + if _hz: + delta = pos - py + return px, pos if abs(delta) >= _MIN_LEADER else py + math.copysign( + _MIN_LEADER, delta or 1.0 + ) + delta = pos - px + return pos if abs(delta) >= _MIN_LEADER else px + math.copysign( + _MIN_LEADER, delta or 1.0 + ), py + + def _label_bbox_at(pos): + elbow_x, elbow_y = _elbow(pos) + shelf_dir = 1.0 if elbow_x >= px else -1.0 + anchor_x = glyph_box.min.X if shelf_dir > 0 else glyph_box.max.X + dx = elbow_x + shelf_dir * draft.pad_around_text - anchor_x + dy = elbow_y - (glyph_box.min.Y + glyph_box.max.Y) / 2.0 + return ( + glyph_box.min.X + dx, + glyph_box.min.Y + dy, + glyph_box.max.X + dx, + glyph_box.max.Y + dy, + ) + + def _ink_at(pos): + elbow = _elbow(pos) + shelf_dir = 1.0 if elbow[0] >= px else -1.0 + shelf_end = (elbow[0] + shelf_dir * draft.pad_around_text, elbow[1]) + return DeferredCompactCandidate( + label_bbox=_label_bbox_at(pos), + materialize=lambda _pos=pos: _build(_pos), + tip=(px, py), + elbow=elbow, + segments=(((px, py), elbow), (elbow, shelf_end)), + analytical_straight_leader=True, + ) + + def _build(pos, _hz=horizontal): + tip = (px, py) # A zero-length leader shaft (the projected site coincides with the solved tier — # `pos == py` above/below, `pos == px` left/right) makes OCC's edge builder raise, # which would crash the whole build on a public-IR declaration. Guarantee a # minimum shaft along the stacking axis (nudge outward; 0.05 mm is invisible) so # `_build` is total — the drop-don't-crash invariant holds for every build call. - if _hz: - dy = pos - _py - pos = pos if abs(dy) >= _MIN_LEADER else _py + math.copysign(_MIN_LEADER, dy or 1.0) - elbow = (_px, pos) - else: - dx = pos - _px - pos = pos if abs(dx) >= _MIN_LEADER else _px + math.copysign(_MIN_LEADER, dx or 1.0) - elbow = (pos, _py) + elbow = _elbow(pos, _hz) leader = leader_ctor( tip=tip, elbow=elbow, label="", draft=draft, - callout=g, - all_around=getattr(_it, "all_around", False), - all_over=getattr(_it, "all_over", False), + callout=fallback_glyph, + all_around=getattr(item, "all_around", False), + all_over=getattr(item, "all_over", False), ) - if _it.kind == "note": + if item.kind == "note": # The outer leader intentionally has label="" because the visible # payload is a TextBlock callout. Preserve the authored note and measure # the embedded Text renderer's face-dependent newline pitch for PDF. - leader.pdf_text = _font_safe_text(_it.text) + leader.pdf_text = _font_safe_text(item.text) leader.pdf_text_font_style = "REGULAR" leader.pdf_text_line_spacing = _text_line_spacing_em( draft.font_size, @@ -628,21 +673,21 @@ def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item): getattr(draft, "font", "Arial"), ) else: - _attach_gdt_text_evidence(leader, g, _it, draft) + _apply_gdt_text_evidence(leader, evidence) return leader - def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): + def _build_at(elbow): leader = leader_ctor( - tip=(_px, _py), + tip=(px, py), elbow=(*elbow, 0), label="", draft=draft, - callout=_g, - all_around=getattr(_it, "all_around", False), - all_over=getattr(_it, "all_over", False), + callout=fallback_glyph, + all_around=getattr(item, "all_around", False), + all_over=getattr(item, "all_over", False), ) - if _it.kind == "note": - leader.pdf_text = _font_safe_text(_it.text) + if item.kind == "note": + leader.pdf_text = _font_safe_text(item.text) leader.pdf_text_font_style = "REGULAR" leader.pdf_text_line_spacing = _text_line_spacing_em( draft.font_size, @@ -650,22 +695,22 @@ def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): getattr(draft, "font", "Arial"), ) else: - _attach_gdt_text_evidence(leader, _g, _it, draft) + _apply_gdt_text_evidence(leader, evidence) return leader - def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): + def _build_routed(bends, elbow): leader = RoutedLeader( - (_px, _py), + (px, py), bends, elbow, "", draft, - callout=_g, - all_around=getattr(_it, "all_around", False), - all_over=getattr(_it, "all_over", False), + callout=fallback_glyph, + all_around=getattr(item, "all_around", False), + all_over=getattr(item, "all_over", False), ) - if _it.kind == "note": - leader.pdf_text = _font_safe_text(_it.text) + if item.kind == "note": + leader.pdf_text = _font_safe_text(item.text) leader.pdf_text_font_style = "REGULAR" leader.pdf_text_line_spacing = _text_line_spacing_em( draft.font_size, @@ -673,13 +718,14 @@ def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): getattr(draft, "font", "Arial"), ) else: - _attach_gdt_text_evidence(leader, _g, _it, draft) + _apply_gdt_text_evidence(leader, evidence) return leader def _compact_candidates(original): return _gdt_compact_candidates( original, _build, + _ink_at, strip, size, horizontal, diff --git a/src/draftwright/annotations/_placement_occupancy.py b/src/draftwright/annotations/_placement_occupancy.py index 51da529b..cab4a174 100644 --- a/src/draftwright/annotations/_placement_occupancy.py +++ b/src/draftwright/annotations/_placement_occupancy.py @@ -7,11 +7,13 @@ import math from collections.abc import Iterable +from dataclasses import dataclass from itertools import chain +from typing import Any from build123d_drafting.helpers import Dimension, Leader, Note, SafeDimension -from draftwright._core import Analysis, _analysis_margins, place_annotation +from draftwright._core import Analysis, _analysis_margins, _drawing_bounds, place_annotation from draftwright._geometry import _boxes_overlap, _segment_clips_box, _segments_cross_or_overlap from draftwright.annotations._dimension_ink import DimensionInkCandidate from draftwright.annotations._placement_geometry import ( @@ -44,6 +46,43 @@ _PAGE_SPANNING_RIDERS = ("is_sheet_frame", "is_zone_grid") +@dataclass(frozen=True) +class DeferredCompactCandidate: + """Exact leader ink metadata before constructing a costly retry annotation.""" + + label_bbox: tuple[float, float, float, float] + materialize: Any + tip: tuple[float, float] | None = None + elbow: tuple[float, float] | None = None + segments: tuple = () + analytical_straight_leader: bool = False + + +def compact_probe_clear(dwg, proposal, others, forbid_box, label_clear) -> bool: + """Reject decisive label, page, furniture and straight-shaft collisions cheaply.""" + label = proposal.label_bbox + page = _drawing_bounds(dwg) + if ( + label[0] < page[0] + or label[1] < page[1] + or label[2] > page[2] + or label[3] > page[3] + or (forbid_box is not None and _box_hits(label, (forbid_box,))) + or (label_clear is not None and not label_clear(label)) + ): + return False + for item in (*others, *(annotation for _, annotation in dwg.iter_annotations())): + try: + foreign = getattr(item, "label_bbox", None) + except Exception: # noqa: BLE001 — the exact check fails closed below + continue + if foreign is not None and len(foreign) == 4 and _boxes_overlap(label, foreign): + return False + return not proposal.analytical_straight_leader or annotation_ink_clear( + dwg, proposal, additional=others + ) + + def is_page_spanning_rider(annotation) -> bool: """Is *annotation* one of the page-spanning riders (see :data:`_PAGE_SPANNING_RIDERS`)? @@ -613,7 +652,10 @@ def annotation_ink_clear(dwg, candidate, *, view=None, additional=(), against=No candidate_elbow = getattr(candidate, "elbow", None) annotation_elbow = getattr(annotation, "elbow", None) shares_leader_trunk = ( - type(candidate) is Leader + ( + type(candidate) is Leader + or getattr(candidate, "analytical_straight_leader", False) + ) and type(annotation) is Leader and candidate_tip is not None and annotation_tip is not None diff --git a/src/draftwright/annotations/_pmi_dimensions.py b/src/draftwright/annotations/_pmi_dimensions.py index 0e2d6628..0024a533 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -416,6 +416,12 @@ def _pmi_witness_from_bbox(rec, view: str, a: Analysis): p1 = (FX(lo), FZ((zmin + zmax) / 2), 0) p2 = (FX(hi), FZ((zmin + zmax) / 2), 0) avg_t = FZ((zmin + zmax) / 2) + elif view == "plan" and ax == "X": + lo, hi = min(point[0] for point in pts), max(point[0] for point in pts) + witness_y = sum(point[1] for point in pts) / len(pts) + p1 = (PX(lo), PY(witness_y), 0) + p2 = (PX(hi), PY(witness_y), 0) + avg_t = PY(witness_y) elif view == "front" and ax == "Z": lo, hi = min(point[2] for point in pts), max(point[2] for point in pts) p1 = (FX((xmin + xmax) / 2), FZ(lo), 0) @@ -427,11 +433,19 @@ def _pmi_witness_from_bbox(rec, view: str, a: Analysis): p2 = (SX(hi), SZ((zmin + zmax) / 2), 0) avg_t = SZ((zmin + zmax) / 2) elif view == "plan" and ax == "Y": - avg_x = (xmin + xmax) / 2 + # AP242 may attach broad plate faces to a local Y measurement. Their + # combined bbox can cover the whole part, so its midpoint collapses + # distinct witness pairs onto one X station. The proved reference points + # are the dimension's actual stations (as for plan/X above). + point_x = sum(point[0] for point in pts) / len(pts) + # Some authored records supply reference points on an abstract datum + # line outside their support box. Keep the support box as the fallback + # in that case; use the actual stations when they lie on the geometry. + witness_x = point_x if xmin - 1e-6 <= point_x <= xmax + 1e-6 else (xmin + xmax) / 2 lo, hi = min(point[1] for point in pts), max(point[1] for point in pts) - p1 = (PX(avg_x), PY(lo), 0) - p2 = (PX(avg_x), PY(hi), 0) - avg_t = PX(avg_x) + p1 = (PX(witness_x), PY(lo), 0) + p2 = (PX(witness_x), PY(hi), 0) + avg_t = PX(witness_x) else: return None @@ -1093,29 +1107,25 @@ def _pmi_front_linear( *, queue_options=_pmi_queue_options, ): - """An X- or Z-dominant linear PMI dim in the FRONT view (the two share one shape): the + """An X- or Z-dominant linear PMI dim in a principal view (the two share one shape): the witness spans the ref bbox; place ``[primary, secondary]`` when the perpendicular midpoint sits on the primary side of the view centre, else fall back to ``[secondary]`` alone. Returns True/False placed, or ``None`` for a degenerate (no-witness) reference so the caller can report it as a validation failure.""" draft = dwg.draft _pmi_queue_options = queue_options - wp = _pmi_witness_from_bbox(rec, "front", a) + view = "plan" if ax == "X" and rec.view == "plan" else "front" + wp = _pmi_witness_from_bbox(rec, view, a) if wp is None: return None p1, p2, avg = wp - zones = { - "above": a.fv_zones.above, - "below": a.fv_zones.below, - "right": a.fv_zones.right, - "left": a.fv_zones.left, - } + zones = a.pv_zones if view == "plan" else a.fv_zones if rec.side is not None: sides = [s for s in (primary, secondary) if rec.side == s] return _pmi_queue_options( dwg, ctx, - [_pmi_dim_spec(p1, p2, zones[s], label, name, "front", s, draft) for s in sides], + [_pmi_dim_spec(p1, p2, getattr(zones, s), label, name, view, s, draft) for s in sides], ax, label, rec, @@ -1126,8 +1136,10 @@ def _pmi_front_linear( dwg, ctx, [ - _pmi_dim_spec(p1, p2, zones[primary], label, name, "front", primary, draft), - _pmi_dim_spec(p1, p2, zones[secondary], label, name, "front", secondary, draft), + _pmi_dim_spec(p1, p2, getattr(zones, primary), label, name, view, primary, draft), + _pmi_dim_spec( + p1, p2, getattr(zones, secondary), label, name, view, secondary, draft + ), ], ax, label, @@ -1137,7 +1149,11 @@ def _pmi_front_linear( placed = _pmi_queue_options( dwg, ctx, - [_pmi_dim_spec(p1, p2, zones[secondary], label, name, "front", secondary, draft)], + [ + _pmi_dim_spec( + p1, p2, getattr(zones, secondary), label, name, view, secondary, draft + ) + ], ax, label, rec, @@ -1518,7 +1534,7 @@ def _place_pmi_record( name_x, "above", "below", - a.FV_Y, + a.PV_Y if rec.view == "plan" else a.FV_Y, queue_options=queue_options, ) if placed is None: diff --git a/src/draftwright/build_policy.py b/src/draftwright/build_policy.py index 2197ab3d..c299d02a 100644 --- a/src/draftwright/build_policy.py +++ b/src/draftwright/build_policy.py @@ -533,11 +533,12 @@ def _scale_attempt( def _principal_view_exceeds_page(scale, page, bounds, views) -> bool: - """Rule out a fixed-scale build whose unannotated principal cannot fit. + """Rule out a fixed-scale build whose bare principal projections cannot fit. - This uses only the part's world-space bounding box and the full page, leaving - margins and annotation footprints out of the bound. A rejected candidate - therefore cannot be rescued by a different arrangement or ink placement. + Use only the part's world-space box and the *full* page: omitting even the + mandatory gutters, margins and annotation footprints makes this a necessary + bound, never a speculative fit verdict. No ink solve can rescue a rejected + scale. """ extents = { "x": bounds.max.X - bounds.min.X, diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index 7973c809..6dfe04bf 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -2488,10 +2488,7 @@ def try_without_iso(self): except (ValueError, Standard_Failure) as exc: if not _is_expected_candidate_build_failure(exc): raise - _log.info( - "fixed-page optional-ISO replan rejected (build failed: %s)", - exc, - ) + _log.info("fixed-page optional-ISO replan rejected (build failed: %s)", exc) self.record_attempt( None, "error", @@ -2538,7 +2535,7 @@ def try_without_iso(self): # sequence of larger standard pages. Each page chooses its scale # through the established fixed-page policy and must pass the # same axial, structural, and required-outcome gates above. A - # A detail may be introduced or retained here: it is itself a + # detail may be introduced or retained here: it is itself a # semantic recovery view, and this correction must not reject a # complete candidate merely because removing the optional ISO # made room for that required detail. diff --git a/src/draftwright/compose.py b/src/draftwright/compose.py index d8c1c94a..d0fc55b5 100644 --- a/src/draftwright/compose.py +++ b/src/draftwright/compose.py @@ -788,6 +788,22 @@ def _reserve_planned_angles( ) +def _reserve_unhinted_linear_corridors(corridors, kind, axis) -> None: + """Reserve the same default/fallback strips the linear PMI renderer tries.""" + if kind == "linear" and axis == "X": + # Imported AP242 X dimensions commonly have no route hint. Without these + # bands even a required overall tolerance has a zero-capacity strip (#2192). + _reserve_corridor(corridors, "front", "above") + _reserve_corridor(corridors, "front", "below") + elif kind == "linear" and axis == "Y": + _reserve_corridor(corridors, "side", "above") + _reserve_corridor(corridors, "side", "below") + _reserve_corridor(corridors, "plan", "below") + elif kind not in ("diameter", "radius", "angular") and axis == "Z": + _reserve_corridor(corridors, "front", "left") + _reserve_corridor(corridors, "front", "right") + + def _reserve_authored_dimensions( model, boxes: list[AnnoBox], @@ -798,6 +814,10 @@ def _reserve_authored_dimensions( text_position: str, text_orientation: str, ) -> None: + # Report/off modes retain imported records for diagnostics but do not draw + # them. Their corridors must not enlarge the sheet for invisible ink. + if not getattr(model, "pmi_annotations_enabled", True): + return # Measured placement hints are semantic corridor requirements and therefore part of # compose-before-pack, not merely renderer filters. Resolve every valid explicit route; # a view-only hint conservatively reserves both supported sides, while the legacy @@ -821,11 +841,8 @@ def _reserve_authored_dimensions( if view_hint is None and side_hint is None and angular_reference is None: if kind == "linear" and axis == "?" and target_view is not None: pass - elif kind not in ("diameter", "radius", "angular") and axis == "Z": - _reserve_corridor(corridors, "front", "left") - _reserve_corridor(corridors, "front", "right") - continue else: + _reserve_unhinted_linear_corridors(corridors, kind, axis) continue if target_view is None: continue diff --git a/src/draftwright/model/detect.py b/src/draftwright/model/detect.py index a2cc5967..8be58007 100644 --- a/src/draftwright/model/detect.py +++ b/src/draftwright/model/detect.py @@ -389,7 +389,12 @@ def build_pmi_features( pmi_origin = ((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2) else: pmi_origin = (bbox.center().X, bbox.center().Y, bbox.center().Z) - ax = r.dominant_axis.lower() if r.dominant_axis in ("X", "Y", "Z") else "z" + proven_axis = ( + r.reference_axis + if r.source_category == "geometric_tolerance" and r.reference_axis + else r.dominant_axis + ) + ax = proven_axis.lower() if proven_axis in ("X", "Y", "Z") else "z" if r.kind in AUTHORED_DIMENSION_KINDS: out.append( AuthoredDimension( diff --git a/src/draftwright/model/dimension_intent.py b/src/draftwright/model/dimension_intent.py index 3d2bcdc3..01481517 100644 --- a/src/draftwright/model/dimension_intent.py +++ b/src/draftwright/model/dimension_intent.py @@ -102,7 +102,12 @@ def _validate_authored_dimension_placement( ) else: valid_pairs = { - "X": (("front", "above"), ("front", "below")), + "X": (("front", "above"), ("front", "below")) + + ( + (("plan", "above"), ("plan", "below")) + if dimension_kind in ("linear", "thickness") + else () + ), "Z": (("front", "right"), ("front", "left")), "Y": ( ("side", "above"), diff --git a/src/draftwright/pmi.py b/src/draftwright/pmi.py index 8c5cc9d3..31be34e2 100644 --- a/src/draftwright/pmi.py +++ b/src/draftwright/pmi.py @@ -51,12 +51,10 @@ from draftwright._pmi_linear_geometry import ( _LINEAR_VALUE_REL_TOL as _LINEAR_VALUE_REL_TOL, ) -from draftwright._pmi_linear_geometry import ( - _dimension_reference_stations, -) from draftwright._pmi_linear_geometry import ( _linear_reference_stations as _linear_reference_stations, ) +from draftwright._pmi_linear_geometry import _proved_planar_linear from draftwright._pmi_part21 import ( CommonLabelFact, DatumDefinitionFact, @@ -116,9 +114,11 @@ _without_direct_xcaf_reference_failures, ) from draftwright._pmi_topology import ( + _common_principal_cylinder_axis, _CommonLabelTopologyResolver, _DatumTopologyResolver, _DimensionSupportResolver, + _optional_cylinder_support, _SurfaceLabelTopologyResolver, ) from draftwright._pmi_topology import ( @@ -185,13 +185,13 @@ class PmiRecord: datum_contexts: Tolerance semantic names in which a datum definition is referenced. reference_item_ids: Exact Part21 representation items bound to a datum feature. reference_item_groups: Ordered Part21 support groups bound to a dimension. - reference_axis: Axis normal to a planar datum support or along a cylindrical one. + reference_axis: Principal datum normal or exact cylindrical GD&T support axis. reference_surface_kind: Proven datum support type, ``plane`` or ``cylinder``. reference_normal: Outward normal of a planar datum; empty for cylindrical supports. semantic_name: Stable source name for a semantic manufacturing requirement. shape_aspect_ids: Part21 shape aspects associating a semantic requirement to geometry. - cylindrical_refs: Canonical finite-cylinder topology referenced by a Size_Diameter - requirement. Empty for other dimension families or unresolved geometry. + cylindrical_refs: Exact finite-cylinder supports for Size_Diameter or GD&T; + empty when unsupported or unresolved. reference_bboxes: Per-item bounds for exact imported manufacturing supports. circular_refs: Canonical circular-edge topology referenced by a Size_Diameter requirement whose semantic association names edges rather than faces. @@ -432,8 +432,12 @@ def _make_label( # the - deviation stored as a positive magnitude. We add explicit signs # so the label is unambiguous on the drawing. if upper_tol is not None and lower_tol is not None: - if abs(upper_tol) == abs(lower_tol): + if abs(upper_tol) == abs(lower_tol) and abs(upper_tol) > 1e-9: base += f" ±{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" + elif abs(lower_tol) <= 1e-9: + base += f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}/0" + elif abs(upper_tol) <= 1e-9: + base += f" 0/-{_fmt_pmi_magnitude(abs(lower_tol), tolerance_decimals)}" else: base += ( f" +{_fmt_pmi_magnitude(abs(upper_tol), tolerance_decimals)}" @@ -1238,8 +1242,7 @@ def _dimension_record( if has_plus_minus_tolerance: try: candidate = float(obj.GetUpperTolValue()) - if abs(candidate) > 1e-9: - upper_tol = candidate + upper_tol = candidate except Exception as exc: reason = f"upper tolerance is unavailable ({_failure_reason(exc)})" partial_reasons.append(reason) @@ -1247,8 +1250,7 @@ def _dimension_record( try: candidate = float(obj.GetLowerTolValue()) - if abs(candidate) > 1e-9: - lower_tol = candidate + lower_tol = candidate except Exception as exc: reason = f"lower tolerance is unavailable ({_failure_reason(exc)})" partial_reasons.append(reason) @@ -1303,9 +1305,8 @@ def _dimension_record( angular_reference: AngularReference | None = None support_view = None if kind in ("linear", "thickness"): - plane_axis, support_view = _parallel_planar_reference_support(group_shapes, frame) - points, dominant_axis, station_reasons = _dimension_reference_stations( - group_stations, value, kind, plane_axis=plane_axis + points, dominant_axis, support_view, station_reasons = _proved_planar_linear( + group_shapes, group_stations, value, kind, frame, _shape_bbox ) rendering_blockers = _dimension_geometry_blockers(kind, reference_reasons, station_reasons) elif type_code == 15: # XCAFDimTolObjects_DimensionType_Size_Diameter @@ -1463,6 +1464,10 @@ def _geometric_tolerance_record( reference_geometry = _reference_geometry(label, shape_tool, frame) points, ref_bbox, dominant_axis, reference_reasons = reference_geometry partial_reasons.extend(reference_reasons) + # Exact cylinders, not their diameter-wide boxes, determine GD&T view axes. + cylinders = _optional_cylinder_support( + lambda: _cylindrical_references(label, shape_tool, frame) + ) datum_refs, datum_reasons = _datum_references(label, dim_tol_tool) partial_reasons.extend(datum_reasons) lowering_blockers = tuple(dict.fromkeys(partial_reasons)) @@ -1479,6 +1484,8 @@ def _geometric_tolerance_record( datum_refs=datum_refs, part21_id=part21_id, source_category="geometric_tolerance", + cylindrical_refs=cylinders, + reference_axis=_common_principal_cylinder_axis(cylinders), gtol_modifiers=gtol_modifiers, lowering_blockers=lowering_blockers, ), @@ -2062,12 +2069,8 @@ def _dimension_support_topology( ) continue - plane_axis, support_view = _parallel_planar_reference_support(tuple(group_shapes), frame) - points, dominant_axis, station_reasons = _dimension_reference_stations( - tuple(stations), - record.value, - record.kind, - plane_axis=plane_axis, + points, dominant_axis, support_view, station_reasons = _proved_planar_linear( + tuple(group_shapes), tuple(stations), record.value, record.kind, frame, _shape_bbox ) projected.append( replace( diff --git a/tests/_complexity_baseline.json b/tests/_complexity_baseline.json index 3d389234..97584806 100644 --- a/tests/_complexity_baseline.json +++ b/tests/_complexity_baseline.json @@ -110,7 +110,7 @@ "oriented_slot_contract.py:oriented_slot_provider_key": 19, "pdf_text.py:pdf_text_runs": 27, "pmi.py:_angular_reference_from_shapes": 18, - "pmi.py:_dimension_record": 28, + "pmi.py:_dimension_record": 26, "pmi.py:_dimension_support_topology": 18, "pmi.py:_extract_xcaf_dimensions": 23, "profile_angles.py:profile_angle_repetitions": 19, diff --git a/tests/_function_length_baseline.json b/tests/_function_length_baseline.json index 2b1495c3..96394fc9 100644 --- a/tests/_function_length_baseline.json +++ b/tests/_function_length_baseline.json @@ -38,7 +38,7 @@ "linting/turned_step_coverage.py:turned_step_requirement_outcomes": 232, "model/detect.py:_append_late_feature_families": 220, "pdf_text.py:pdf_text_runs": 229, - "pmi.py:_dimension_record": 220, + "pmi.py:_dimension_record": 217, "pmi.py:_extract_xcaf_dimensions": 249, "reporting.py:_raw_report_assessment": 218, "reporting.py:_requirements": 212, diff --git a/tests/test_dimension_intent_contract.py b/tests/test_dimension_intent_contract.py index ab8788b4..b6f2b6f7 100644 --- a/tests/test_dimension_intent_contract.py +++ b/tests/test_dimension_intent_contract.py @@ -36,6 +36,8 @@ def test_oblique_linear_span_needs_one_lossless_principal_projection(references, "kind,axis,view,side,extras", [ ("linear", "X", "front", "above", {}), + ("linear", "X", "plan", "above", {}), + ("thickness", "X", "plan", "below", {}), ("linear", "Y", "plan", "right", {}), ("linear", "Z", "front", "left", {}), ("linear", "?", "plan", "left", {"ref_pts": _OBLIQUE_XY}), @@ -69,6 +71,7 @@ def test_authored_hints_reject_corridors_without_a_renderer(kind, axis, view, si "kind,axis,view,side,angular,refs,expected", [ ("linear", "X", "front", "above", None, (), "front"), + ("linear", "X", "plan", "above", None, (), "plan"), ("angular", "Z", None, "right", _ANGULAR_Z, (), "plan"), ("linear", "?", None, "left", None, _OBLIQUE_XY, "plan"), ("linear", "X", None, None, None, (), None), diff --git a/tests/test_gdt_ink_shared.py b/tests/test_gdt_ink_shared.py index 4bee997d..9028754e 100644 --- a/tests/test_gdt_ink_shared.py +++ b/tests/test_gdt_ink_shared.py @@ -2,6 +2,7 @@ from types import SimpleNamespace +import pytest from build123d_drafting import FeatureControlFrame, Leader from build123d_drafting.helpers import Draft @@ -141,6 +142,31 @@ def _assert_capacity_fixture_fits_each_alone(monkeypatch, outer_limit): assert remaining == [] +def test_deferred_compaction_rejects_out_of_page_label_before_build(monkeypatch): + monkeypatch.setattr(_common, "strip_obstacles", lambda *_args, **_kwargs: []) + monkeypatch.setattr(_common, "pending_title_block_box", lambda _drawing: None) + drawing = _Drawing() + strip = Strip(anchor=0.0, outer_limit=50.0, direction=1.0, gap=8.0, spacing=3.0) + deferred = _common.DeferredCompactCandidate( + (101.0, 20.0, 110.0, 25.0), + lambda: pytest.fail("a provably off-page retry built CAD ink"), + ) + remaining = _common.place_strip_candidates( + drawing, + strip, + "plan", + "y", + [("frame", _frame)], + tier=5.0, + ctx=drawing, + force=True, + sizes={"frame": (10.0, 5.0)}, + compact_candidates={"frame": lambda _original: (deferred,)}, + ) + assert remaining == [] + assert [name for name, _item in drawing.added] == ["frame"] + + def test_frame_moves_as_whole_when_same_batch_dimension_crosses_its_glyph(monkeypatch): unchecked, unchecked_remaining = _solve(monkeypatch, repair=False, required=False) assert unchecked_remaining == [], [(name, item.pos) for name, item in unchecked.added] diff --git a/tests/test_gdt_placement.py b/tests/test_gdt_placement.py index 46a91b57..0c320af1 100644 --- a/tests/test_gdt_placement.py +++ b/tests/test_gdt_placement.py @@ -52,6 +52,93 @@ def _leader_path_length(leader): ) +def test_gdt_retry_reuses_validated_glyph_without_changing_placed_ink(monkeypatch): + from draftwright._core import Strip + from draftwright.annotations import _gdt + + draft = Draft(font_size=3.0) + frame = ControlFrame( + frame=Frame((0.0, 0.0, 0.0), "z"), + characteristic="position", + tolerance="0.1", + view="plan", + side="above", + datums=("A",), + diameter=True, + ) + glyph = _gdt._gdt_glyph(frame, draft) + origin_box = glyph.bounding_box() + strip = Strip(anchor=20.0, outer_limit=90.0, direction=1.0, gap=8.0, spacing=3.0) + real_visual_tolerance = _gdt._gdt_visual_tolerance + validated = [] + + def counted_visual_tolerance(*args, **kwargs): + validated.append(True) + return real_visual_tolerance(*args, **kwargs) + + monkeypatch.setattr(_gdt, "_gdt_visual_tolerance", counted_visual_tolerance) + build, _, _, compact, _ = _gdt._gdt_candidate_builders( + frame, + draft, + Leader, + glyph, + 30.0, + 20.0, + True, + strip, + (origin_box.size.X, origin_box.size.Y), + 5.0, + None, + ) + monkeypatch.setattr( + _gdt, "_gdt_glyph", lambda *_args: pytest.fail("placement rebuilt a validated glyph") + ) + assert len(validated) == 1 + for tier in (35.0, 45.0, 35.0): + placed = build(tier) + fresh = Leader( + tip=(30.0, 20.0), + elbow=(30.0, tier), + label="", + draft=draft, + callout=glyph, + ) + _gdt._attach_gdt_text_evidence(fresh, glyph, frame, draft) + assert placed.label_bbox == pytest.approx(fresh.label_bbox) + assert placed.segments == fresh.segments + assert placed.pdf_text_relative_specs + assert placed.pdf_text_relative_specs == fresh.pdf_text_relative_specs + # Only the direct reference attachment above adds validations; the three + # placement retries must reuse the builder's single checked result. + assert len(validated) == 4 + proposals = list(compact(build(55.0)))[:3] + assert proposals + other = build(55.0) + + class EmptyDrawing: + @staticmethod + def iter_annotations(): + return () + + @staticmethod + def view_of(_name): + return "plan" + + for proposal in proposals: + actual = proposal.materialize() + assert proposal.label_bbox == pytest.approx(actual.label_bbox) + assert proposal.segments == tuple(actual.segments) + assert proposal.tip == actual.tip + assert proposal.elbow == actual.elbow + assert _gdt.annotation_ink_clear( + EmptyDrawing(), proposal, additional=(other,) + ) == _gdt.annotation_ink_clear(EmptyDrawing(), actual, additional=(other,)) + unchanged = glyph.bounding_box() + assert (unchanged.min.X, unchanged.min.Y, unchanged.max.X, unchanged.max.Y) == pytest.approx( + (origin_box.min.X, origin_box.min.Y, origin_box.max.X, origin_box.max.Y) + ) + + def test_control_frame_places_first_class(): frame = ControlFrame( frame=Frame((0.0, 0.0, 0.0), "z"), diff --git a/tests/test_hole_table.py b/tests/test_hole_table.py index 5a3110f2..cac00476 100644 --- a/tests/test_hole_table.py +++ b/tests/test_hole_table.py @@ -440,7 +440,6 @@ def test_table_and_balloons_keep_lint_clean(self, method): dwg = build_drawing(_multi_hole_plate(), projection=method) before = {i.code for i in dwg.lint()} assert before == set() - assert dwg.scale == 1 dwg.add_hole_table("plan") assert len([n for n in dwg.annotations() if n.startswith("balloon_plan")]) == 3 assert {i.code for i in dwg.lint()} == before diff --git a/tests/test_issue_1209_linear_pmi_witnesses.py b/tests/test_issue_1209_linear_pmi_witnesses.py index 0e2a1817..3d972f4c 100644 --- a/tests/test_issue_1209_linear_pmi_witnesses.py +++ b/tests/test_issue_1209_linear_pmi_witnesses.py @@ -106,8 +106,8 @@ def test_offset_parallel_faces_use_their_proven_normal_issue_2184(monkeypatch): assert pmi_module._parallel_planar_reference_support(((first,), (detached,))) == (None, None) shifted_midpoint = (Pos(10, 0, 17) * Box(2, 10, 26)).faces().sort_by(Axis.X)[0].wrapped assert pmi_module._parallel_planar_reference_support(((first,), (shifted_midpoint,))) == ( - None, - None, + "X", + "plan", ) assert _linear_reference_stations(stations, 10, plane_axis=axis) == (stations, "X", ()) assert _linear_reference_stations(stations, 11, plane_axis=axis)[2] == ( diff --git a/tests/test_issue_1516_dimension_text.py b/tests/test_issue_1516_dimension_text.py index a5297611..0dd6c621 100644 --- a/tests/test_issue_1516_dimension_text.py +++ b/tests/test_issue_1516_dimension_text.py @@ -45,7 +45,7 @@ def test_plate_style_cases_cover_every_boundary_and_pair() -> None: @pytest.mark.parametrize("position,orientation,projection,scale", _PLATE_STYLE_CASES) -def test_style_preserves_complete_plate_measurements( +def test_style_preserves_plate_measurements_and_diagnostics( plate, position, orientation, projection, scale ): part, model = plate @@ -67,7 +67,17 @@ def test_style_preserves_complete_plate_measurements( assert all( dim.label_polygon[1][1] == pytest.approx(dim.label_polygon[0][1]) for dim in dimensions ) - assert not [issue for issue in drawing.lint() if issue.severity in {"warning", "error"}] + + # Automatic planning may report an incomplete sheet for this plate. Text + # styling must neither hide that loss nor introduce a new one. + def significant(dwg): + return [ + (issue.severity, issue.code, issue.message) + for issue in dwg.lint() + if issue.severity in {"warning", "error"} + ] + + assert significant(drawing) == significant(baseline) @pytest.mark.parametrize( diff --git a/tests/test_issue_563_placement_intent.py b/tests/test_issue_563_placement_intent.py index b4640949..87da5c8e 100644 --- a/tests/test_issue_563_placement_intent.py +++ b/tests/test_issue_563_placement_intent.py @@ -419,6 +419,27 @@ def test_compose_reserves_every_supported_measured_corridor_family(): assert footprint.sv_top > 0 and footprint.sv_bottom > 0 +def test_unhinted_source_linear_dimensions_reserve_their_render_routes_issue_2192(): + sheet = Sheet(Box(120, 80, 12)).authored_dimensions() + for axis, points in ( + ("X", ((-60, 0, 6), (60, 0, 6))), + ("Y", ((0, -40, 6), (0, 0, 6))), + ): + sheet.measured_dimension( + kind="linear", + value=120 if axis == "X" else 40, + label="120 ±0.05" if axis == "X" else "40", + dominant_axis=axis, + ref_bbox=(-60, -40, 0, 60, 40, 12), + ref_pts=points, + ) + + footprint = _footprint_from_boxes(_compose_anno_boxes(sheet.model(), n_steps=0)) + assert footprint.fv_top > 0 and footprint.fv_bottom > 0 + assert footprint.sv_top > 0 and footprint.sv_bottom > 0 + assert footprint.pv_bottom > 0 + + def test_compose_ignores_an_unresolved_defensive_target(monkeypatch): import draftwright.compose as compose diff --git a/tests/test_pmi.py b/tests/test_pmi.py index d9a0d113..61119334 100644 --- a/tests/test_pmi.py +++ b/tests/test_pmi.py @@ -50,6 +50,282 @@ def ctc04_extraction_report(): class TestExtractPmi: + def test_position_record_keeps_exact_cylinder_axis_issue_2192(self, monkeypatch): + import draftwright.pmi as pmi_module + + monkeypatch.setattr(pmi_module, "_geometric_tolerance_modifiers", lambda _obj: ((), ())) + monkeypatch.setattr(pmi_module, "_geometric_tolerance_qualifiers", lambda _obj: ((), ())) + monkeypatch.setattr(pmi_module, "_unpreserved_geometric_tolerance_fields", lambda _obj: ()) + monkeypatch.setattr( + pmi_module, + "_reference_geometry", + lambda *_args: (((0.0, 0.0, 4.0),), (-11, -11, 0, 11, 11, 8), "X", ()), + ) + monkeypatch.setattr( + pmi_module, + "_cylindrical_references", + lambda *_args: ((SimpleNamespace(axis_direction=(0.0, 0.0, 1.0)),), ()), + ) + monkeypatch.setattr(pmi_module, "_datum_references", lambda *_args: ((), ())) + record, reasons = pmi_module._geometric_tolerance_record( + object(), SimpleNamespace(GetValue=lambda: 2.0), 10, object(), object(), "gtol:bore" + ) + assert not reasons + assert record.dominant_axis == "X" and record.reference_axis == "Z" + assert len(record.cylindrical_refs) == 1 + + def test_position_frame_uses_proven_bore_axis_not_bbox_width_issue_2192(self): + from draftwright._pmi_topology import _common_principal_cylinder_axis + from draftwright.model import build_pmi_features + + z_bore = SimpleNamespace(axis_direction=(0.0, 0.0, 1.0)) + assert _common_principal_cylinder_axis((z_bore, z_bore)) == "Z" + assert ( + _common_principal_cylinder_axis( + (z_bore, SimpleNamespace(axis_direction=(1.0, 0.0, 0.0))) + ) + == "" + ) + record = PmiRecord( + kind="position", + type_code=8, + value=2.0, + source_category="geometric_tolerance", + source_id="geometric_tolerance:bore", + dominant_axis="X", # the 22 mm diameter exceeds the 8 mm axial height + reference_axis="Z", + ref_pts=((0.0, 0.0, 4.0),), + ref_bbox=(-11.0, -11.0, 0.0, 11.0, 11.0, 8.0), + ) + (frame,) = build_pmi_features((record,), Box(120, 80, 12).bounding_box()) + assert (frame.view, frame.frame.axis) == ("plan", "z") + + def test_plane_to_bore_axis_location_uses_exact_face_witness_issue_2192(self): + from build123d import Axis, Cylinder, GeomType, Pos, Rot + + from draftwright._pmi_linear_geometry import _proved_planar_linear + from draftwright.pmi import _shape_bbox + + plane = (Pos(-59, 0, 6) * Box(2, 80, 12)).faces().sort_by(Axis.X)[0].wrapped + bore = (Pos(0, 0, 4) * Cylinder(11, 8)).faces().filter_by(GeomType.CYLINDER)[0].wrapped + centres = ((-60.0, 0.0, 6.0), (0.0, 0.0, 4.0)) + points, axis, view, blockers = _proved_planar_linear( + ((plane,), (bore,)), centres, 60.0, "linear", None, _shape_bbox + ) + assert (axis, view, blockers) == ("X", "plan", ()) + assert points[0] == pytest.approx((-60.0, 0.0, 4.0)) + assert points[1] == pytest.approx((0.0, 0.0, 4.0)) + + # A matching nominal is not enough: the bore axis must touch the + # authored plane face and the cylindrical axis must be principal. + distant = (Pos(-59, 30, 6) * Box(2, 10, 12)).faces().sort_by(Axis.X)[0].wrapped + _, axis, _, blockers = _proved_planar_linear( + ((distant,), (bore,)), + ((-60.0, 30.0, 6.0), centres[1]), + 60.0, + "linear", + None, + _shape_bbox, + ) + assert axis == "?" and blockers + tilted = ( + (Pos(0, 0, 4) * Rot(Y=20) * Cylinder(11, 8)) + .faces() + .filter_by(GeomType.CYLINDER)[0] + .wrapped + ) + _, axis, view, _blockers = _proved_planar_linear( + ((plane,), (tilted,)), centres, 60.0, "linear", None, _shape_bbox + ) + assert (axis, view) != ("X", "plan") + + # A plane bbox can cover the axis while the trimmed face has a hole + # there. The oblique centre fallback must not silently certify it. + cut = Pos(-59, 0, 4) * Rot(Y=90) * Cylinder(3, 4) + holed_plane = ((Pos(-59, 0, 6) * Box(2, 80, 12)) - cut).faces().sort_by(Axis.X)[0].wrapped + _, _, _, blockers = _proved_planar_linear( + ((holed_plane,), (bore,)), centres, 60.0, "linear", None, _shape_bbox + ) + assert any("no proven face-supported axis witness" in reason for reason in blockers) + + def test_parallel_x_faces_do_not_use_bbox_overlap_through_a_hole_issue_2193(self): + from build123d import Axis, Pos + from OCP.BRepClass import BRepClass_FaceClassifier + from OCP.gp import gp_Pnt + from OCP.TopAbs import TopAbs_OUT + + from draftwright._pmi_linear_geometry import _proved_planar_linear + from draftwright.pmi import _shape_bbox + + ring = (Pos(0.5, 0, 0) * Box(1, 20, 20)) - (Pos(0.5, 0, 0) * Box(2, 10, 10)) + first = ring.faces().sort_by(Axis.X)[0].wrapped + second = (Pos(75.5, 0, 2) * Box(1, 2, 2)).faces().sort_by(Axis.X)[0].wrapped + classifier = BRepClass_FaceClassifier() + classifier.Perform(first, gp_Pnt(0, 0, 2), 1e-7) + assert classifier.State() == TopAbs_OUT # The bbox's centre is in the opening. + + _points, axis, view, blockers = _proved_planar_linear( + ((first,), (second,)), + ((0, 0, 0), (75, 0, 2)), + 75.0, + "linear", + None, + _shape_bbox, + ) + assert (axis, view) == ("?", None) + assert blockers == ("parallel planar source faces have no proven shared witness",) + + def test_parallel_x_faces_find_a_trimmed_overlap_away_from_bbox_centre_issue_2193(self): + from build123d import Axis, Pos + from OCP.BRepClass import BRepClass_FaceClassifier + from OCP.gp import gp_Pnt + from OCP.TopAbs import TopAbs_IN + + from draftwright._pmi_linear_geometry import _proved_planar_linear + from draftwright.pmi import _shape_bbox + + ring = (Pos(0.5, 0, 0) * Box(1, 20, 20)) - (Pos(0.5, 0, 0) * Box(2, 10, 10)) + first = ring.faces().sort_by(Axis.X)[0].wrapped + second = (Pos(75.5, 0, 2) * Box(1, 16, 2)).faces().sort_by(Axis.X)[0].wrapped + + points, axis, view, blockers = _proved_planar_linear( + ((first,), (second,)), + ((0, 0, 0), (75, 0, 2)), + 75.0, + "linear", + None, + _shape_bbox, + ) + assert (axis, view, blockers) == ("X", "plan", ()) + assert points[0][1:] == points[1][1:] + for face, point in zip((first, second), points, strict=True): + classifier = BRepClass_FaceClassifier() + classifier.Perform(face, gp_Pnt(*point), 1e-7) + assert classifier.State() == TopAbs_IN + + def test_offset_pocket_wall_uses_a_common_plan_witness_issue_2192(self, monkeypatch): + from build123d import Axis, Pos + from build123d_drafting.helpers import Draft + + import draftwright.pmi as pmi_module + from draftwright._core import Strip + from draftwright._pmi_linear_geometry import ( + _dimension_reference_stations, + _proved_planar_linear, + ) + from draftwright.annotations._pmi_dimensions import ( + _pmi_front_linear, + _pmi_witness_from_bbox, + ) + from draftwright.pmi import _make_label, _shape_bbox + + datum = (Pos(-59, 0, 6) * Box(2, 80, 12)).faces().sort_by(Axis.X)[0].wrapped + pocket_wall = (Pos(16, 26, 10) * Box(2, 10, 4)).faces().sort_by(Axis.X)[0].wrapped + centres = ((-60.0, 0.0, 6.0), (15.0, 26.0, 10.0)) + assert _dimension_reference_stations(centres, 75.0, "linear")[2], ( + "fixture must contain the offset-centre defect" + ) + + points, proven_axis, view, blockers = _proved_planar_linear( + ((datum,), (pocket_wall,)), centres, 75.0, "linear", None, _shape_bbox + ) + assert (proven_axis, view, blockers) == ("X", "plan", ()) + assert points == ((-60.0, 26.0, 10.0), (15.0, 26.0, 10.0)) + + def identity(value): + return value + + analysis = SimpleNamespace( + proj=SimpleNamespace( + front_x=identity, + front_z=identity, + side_x=identity, + side_z=identity, + plan_x=identity, + plan_y=identity, + ) + ) + bounds = (-60.0, -40.0, 0.0, 15.0, 40.0, 12.0) + monkeypatch.setattr( + pmi_module, + "_reference_geometry_with_groups", + lambda *_args: (centres, bounds, "?", (), centres, ((datum,), (pocket_wall,))), + ) + source = SimpleNamespace( + GetValue=lambda: 75.0, + IsDimWithPlusMinusTolerance=lambda: True, + GetUpperTolValue=lambda: 0.1, + GetLowerTolValue=lambda: 0.0, + IsDimWithRange=lambda: False, + GetSemanticName=lambda: None, + ) + record, reasons = pmi_module._dimension_record(object(), source, 2, object(), "source:75") + assert not reasons + assert (record.label, record.lower_tol, record.dominant_axis, record.view) == ( + "75 +0.1/0", + 0.0, + "X", + "plan", + ) + witness = _pmi_witness_from_bbox(record, view, analysis) + assert witness == ((-60.0, 26.0, 0), (15.0, 26.0, 0), 26.0) + assert _make_label("linear", 75.0, 0.1, 0.0) == record.label + + analysis.PV_Y = 0.0 + analysis.pv_zones = SimpleNamespace( + above=Strip(anchor=40.0, outer_limit=80.0, direction=1.0, gap=2.0), + below=Strip(anchor=10.0, outer_limit=0.0, direction=-1.0, gap=2.0), + ) + queued = [] + + def capture(_drawing, _ctx, options, _axis, _label, _record): + queued.extend(option for option in options if option is not None) + return True + + assert _pmi_front_linear( + SimpleNamespace(draft=Draft(font_size=3.0)), + analysis, + object(), + SimpleNamespace(**vars(record), side=None), + "X", + "75 +0.1/0", + "pmi_x", + "above", + "below", + 0.0, + queue_options=capture, + ) + assert queued and all(option["view"] == "plan" for option in queued) + + def test_plan_y_witness_uses_source_station_not_broad_face_bbox_issue_2192(self): + from draftwright.annotations._pmi_dimensions import _pmi_witness_from_bbox + + def identity(value): + return value + + analysis = SimpleNamespace( + proj=SimpleNamespace( + front_x=identity, + front_z=identity, + side_x=identity, + side_z=identity, + plan_x=identity, + plan_y=identity, + ) + ) + stations = (-25.0, 0.0, 25.0) + witnesses = [] + for station in stations: + record = SimpleNamespace( + dominant_axis="Y", + ref_pts=((station, -40.0, 6.0), (station, 0.0, 6.0)), + ref_bbox=(-60.0, -40.0, 0.0, 60.0, 40.0, 12.0), + ) + witnesses.append(_pmi_witness_from_bbox(record, "plan", analysis)) + + assert [witness[0][0] for witness in witnesses] == list(stations) + assert all(witness[0][1] == -40.0 and witness[1][1] == 0.0 for witness in witnesses) + def test_nist_ctc01_returns_records(self, ctc01_extraction_report): recs = ctc01_extraction_report.records assert len(recs) > 0 @@ -106,7 +382,7 @@ def test_unqualified_size_deviation_label_keeps_source_magnitude(self): assert 0.05 != 0.05004 assert 9.95 != 10.05 assert _make_label("diameter", 10.0, 0.09, None) == "ø10 +0.09" - assert _make_label("diameter", 10.0, 0.09, 0.0) == "ø10 +0.09/-0.0" + assert _make_label("diameter", 10.0, 0.09, 0.0) == "ø10 +0.09/0" assert _make_label("diameter", 10.0, 0.05, 0.05004) == "ø10 +0.05/-0.05004" assert _make_label("diameter", 10.0, 0.05, 0.05) == "ø10 ±0.05" assert ( diff --git a/tests/test_pmi_gtol_lowering.py b/tests/test_pmi_gtol_lowering.py index 1fc043dc..40cd2f01 100644 --- a/tests/test_pmi_gtol_lowering.py +++ b/tests/test_pmi_gtol_lowering.py @@ -20,7 +20,7 @@ from draftwright.builder import build_drawing, detect_part_model from draftwright.linting.pmi_coverage import lint_pmi_rendering from draftwright.model import build_pmi_features -from draftwright.model.ir import ControlFrame, Frame, PmiFeature +from draftwright.model.ir import ControlFrame, CylindricalReference, Frame, PmiFeature from draftwright.pmi import PmiExtractionReport, PmiRecord from draftwright.sheet_emit import _feature_block, _feature_line @@ -789,7 +789,13 @@ def _execute_feature_line(feature): sheet = SimpleNamespace(add=captured.append) exec( _feature_line(feature), - {"sheet": sheet, "ControlFrame": ControlFrame, "Frame": Frame, "PmiFeature": PmiFeature}, + { + "sheet": sheet, + "ControlFrame": ControlFrame, + "CylindricalReference": CylindricalReference, + "Frame": Frame, + "PmiFeature": PmiFeature, + }, ) (restored,) = captured return restored