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 af097bca..0024a533 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -433,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 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..b971f7e0 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. @@ -2547,9 +2544,7 @@ def try_without_iso(self): self.original_page, include_iso=False, reason="page_escalation_after_optional_iso", - fallback_views=tuple( - name for name in self.drawing.views if name != "iso" - ), + fallback_views=tuple(name for name in self.drawing.views if name != "iso"), require_axial_coverage=True, allow_recovery_detail=True, ) diff --git a/src/draftwright/compose.py b/src/draftwright/compose.py index d8c1c94a..c80bc812 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 model.pmi_annotations_enabled: + 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/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_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 442577bc..bd6f8860 100644 --- a/tests/test_pmi.py +++ b/tests/test_pmi.py @@ -242,6 +242,35 @@ def capture(_drawing, _ctx, options, _axis, _label, _record): ) 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 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