Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ document in step. The *why* behind every shape here lives in `docs/adr/`.
The dependency graph is a DAG (the #138 / ADR 1 (was 0005) split is complete). Bottom to
top: strict rank-0 package leaves: `progress.py`, `layout.py` (including
semantic survival order), `registry.py`, `fonts/`,
`_geometry.py`,
`_geometry.py`, `fixed_ink_cache.py`,
`fits.py`,
`contract_values.py`, `measurement_support.py`, `sheet_metadata.py`,
`angular_geometry.py`, `family_table.py`, `recogniser_policy.py`,
Expand Down Expand Up @@ -55,6 +55,9 @@ contract, such as `reporting.py`, states and guards that contract at its own sea
corridor demand from approved model groups, and compose consumes that topology.
`recognition_cache.py` sits beside `analysis.py` at rank 3: both consume bottom-layer
recognition contracts, while `drawing_state.py` and `builder.py` consume the cache.
`fixed_ink_cache.py` is a rank-0 package leaf: its caller-owned, bounded face-mesh cache
uses exact located B-rep bytes and tessellation tolerance as the key. Annotation fixed-ink
validation and `Sheet.build()` consume it; it never owns placement or model state.
`test_rank_zero_modules_are_package_leaves` enforces that every rank-0 file has no
package import across runtime, type-only and lazy paths. `model/` shares a numerical
rank with `_core` but its separate fail-closed import allowlist still prohibits any
Expand Down
21 changes: 21 additions & 0 deletions docs/reference/sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,27 @@ The token associates features; it does not specify an annotation position or add
Generated scripts preserve this association using Draftwright-owned tokens instead of provider
keys. A groove can still be declared when the authored set omits all of that body's steps.

### Repeated editor builds

An editor that rebuilds a declared sheet after annotation-only edits may reuse a
caller-owned fixed-ink mesh cache:

```python
from draftwright import FixedInkMeshCache

mesh_cache = FixedInkMeshCache(max_entries=2048)
drawing = sheet.build(mesh_cache=mesh_cache)
# After a bounded layout edit, rebuild with the same cache.
sheet.layout_override("declaration:datum", side="left")
drawing = sheet.build(mesh_cache=mesh_cache)
```

This is optional; ordinary `build()` behavior is unchanged. Cache entries use the exact
located geometry of rendered annotation faces and the tessellation tolerance, so moving
an annotation or changing the part, scale or views cannot reuse stale ink. The cache is
bounded by entry count, can be cleared with `mesh_cache.clear()`, and only avoids face
tessellation; it does not skip the drawing's placement or validation solve.

## Build-scoped declaration selectors

An editable script can give a feature a declaration identity and later address that intent
Expand Down
3 changes: 3 additions & 0 deletions src/draftwright/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"BuildCancelled": "draftwright.progress",
"observe_build": "draftwright.progress",
"FeatureInfo": "draftwright.drawing",
"FixedInkMeshCache": "draftwright.fixed_ink_cache",
"ReportUnavailableError": "draftwright.reporting",
"INSPECTION_SCHEMA": "draftwright.inspection",
"INSPECTION_SCHEMA_VERSION": "draftwright.inspection",
Expand Down Expand Up @@ -103,6 +104,7 @@ def __getattribute__(self, name):
from draftwright.compose import choose_scale
from draftwright.document import Document, DocumentBuildError, DocumentResult
from draftwright.drawing import Drawing, FeatureInfo
from draftwright.fixed_ink_cache import FixedInkMeshCache
from draftwright.inspection import (
INSPECTION_SCHEMA,
INSPECTION_SCHEMA_VERSION,
Expand Down Expand Up @@ -143,6 +145,7 @@ def __dir__():
"DocumentBuildError",
"SoftDeprecationWarning",
"FeatureInfo",
"FixedInkMeshCache",
"InspectionUnavailableError",
"LeaderRegionPolicy",
"PmiExtractionReport",
Expand Down
19 changes: 18 additions & 1 deletion src/draftwright/annotations/_leader_fixed_ink.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from draftwright._geometry import _leader_ink_polygons, _stroke_polygon
from draftwright.annotations._common import DerivedViewReservation, _geom_box
from draftwright.fixed_ink_cache import _active_fixed_ink_mesh_cache
from draftwright.progress import checkpoint

_FIXED_INVENTORY_EXHAUSTED = object()
Expand Down Expand Up @@ -121,6 +122,16 @@ def _validated_face_mesh(face, tolerance):
"""Return one complete finite triangular mesh, or ``None`` when malformed."""

checkpoint()
cache = _active_fixed_ink_mesh_cache()
key = None
if cache is not None:
try:
key = cache._key(face, tolerance)
cached = cache.get(key)
if cached is not None:
return cached
except Exception: # noqa: BLE001 — optional cache must fail open to validation
key = None
try:
vertices, raw_triangles = face.tessellate(tolerance)
points = tuple((float(vertex.X), float(vertex.Y)) for vertex in vertices)
Expand All @@ -146,7 +157,13 @@ def _validated_face_mesh(face, tolerance):
)
except Exception: # noqa: BLE001 — optional placement must fail closed
return None
return points, tuple(triangles), edge_kinds
mesh = points, tuple(triangles), edge_kinds
if cache is not None and key is not None:
try:
cache.put(key, mesh)
except Exception: # noqa: BLE001 — cache failure must not fail ink validation
pass
return mesh


def _convex_hull(points):
Expand Down
96 changes: 96 additions & 0 deletions src/draftwright/fixed_ink_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Caller-owned exact-face cache for repeated fixed-ink validation (#2207).

The cached faces are rendered annotation ink, not merely projected part faces.
Part/scale/view identity therefore cannot prove reuse after a layout edit: the key
must contain the complete located face geometry as well as tessellation tolerance.
"""

from __future__ import annotations

from collections import OrderedDict
from contextlib import contextmanager
from contextvars import ContextVar
from io import BytesIO
from threading import Lock

from OCP.BRepTools import BRepTools
from OCP.TopTools import TopTools_FormatVersion

FaceMesh = tuple[
tuple[tuple[float, float], ...],
tuple[tuple[int, int, int], ...],
tuple[str, ...],
]


class FixedInkMeshCache:
"""Bounded, reusable cache for exact rendered face meshes.

Pass one instance to successive ``Sheet.build(mesh_cache=...)`` calls. The
cache is optional, never global, and safe to reuse across part/scale/view
changes because its key includes each *located* face's exact B-rep. A
failed key or malformed mesh is never cached; normal validation still runs.
"""

def __init__(self, *, max_entries: int = 2048) -> None:
if isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries < 1:
raise ValueError("max_entries must be a positive integer")
self.max_entries = max_entries
self._entries: OrderedDict[tuple[float, bytes], FaceMesh] = OrderedDict()
self._lock = Lock()
self.hits = 0
self.misses = 0

@staticmethod
def _key(face, tolerance: float) -> tuple[float, bytes]:
stream = BytesIO()
BRepTools.Write_s(
face.wrapped,
stream,
False,
False,
TopTools_FormatVersion.TopTools_FormatVersion_VERSION_3,
)
return float(tolerance), stream.getvalue()

def get(self, key: tuple[float, bytes]) -> FaceMesh | None:
with self._lock:
mesh = self._entries.get(key)
if mesh is None:
self.misses += 1
else:
self.hits += 1
self._entries.move_to_end(key)
return mesh

def put(self, key: tuple[float, bytes], mesh: FaceMesh) -> None:
with self._lock:
self._entries[key] = mesh
self._entries.move_to_end(key)
if len(self._entries) > self.max_entries:
self._entries.popitem(last=False)

def clear(self) -> None:
"""Release retained face geometry and reset counters."""

with self._lock:
self._entries.clear()
self.hits = self.misses = 0


_ACTIVE_MESH_CACHE: ContextVar[FixedInkMeshCache | None] = ContextVar(
"draftwright_fixed_ink_mesh_cache", default=None
)


@contextmanager
def _using_fixed_ink_mesh_cache(cache: FixedInkMeshCache | None):
token = _ACTIVE_MESH_CACHE.set(cache)
try:
yield
finally:
_ACTIVE_MESH_CACHE.reset(token)


def _active_fixed_ink_mesh_cache() -> FixedInkMeshCache | None:
return _ACTIVE_MESH_CACHE.get()
43 changes: 24 additions & 19 deletions src/draftwright/sheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
from draftwright.compose import _est_table_size
from draftwright.document_input import DocumentInput, physical_features
from draftwright.fits import fit_class
from draftwright.fixed_ink_cache import FixedInkMeshCache, _using_fixed_ink_mesh_cache
from draftwright.model import (
DefaultSurfaceFinish,
DimensionParameterId,
Expand Down Expand Up @@ -2826,10 +2827,13 @@ def model(self):
self._authored_set(),
)

def build(self):
def build(self, *, mesh_cache: FixedInkMeshCache | None = None):
"""Build the :class:`~draftwright.drawing.Drawing` — detection skipped; only the
declared features are drawn. Declared corner-block tables (:meth:`table`/:meth:`notes`)
are placed last, clear of everything already on the sheet."""
are placed last, clear of everything already on the sheet. A caller-held
``mesh_cache`` can reuse exact rendered-face tessellations across replays."""
if mesh_cache is not None and not isinstance(mesh_cache, FixedInkMeshCache):
raise TypeError("mesh_cache must be a FixedInkMeshCache or None")
self._prepare()
# `add_dimension` augments the planner's set, so the sheet must have asked for
# one (ADR 4 (was 0016)). Checked HERE rather than in the verb so intent stays
Expand Down Expand Up @@ -2885,23 +2889,24 @@ def place_declared_tables(dwg):
if not automatic_details:
opts["detail_view"] = False
try:
return build_drawing(
self._part,
model=self._build_model_input(),
_document_input=self._document_input,
decorations=self._decorations(
section_request,
suppress_auto_sections=self._derived_view_source == "authored",
),
requested=self._requested_dimensions(),
authored=self._authored_set(),
_post_build=place_declared_tables if self._tables else None,
_required_tables=required_tables,
_views=principal_views,
_include_iso=include_iso,
_view_constraints=constraints,
**opts,
)
with _using_fixed_ink_mesh_cache(mesh_cache):
return build_drawing(
self._part,
model=self._build_model_input(),
_document_input=self._document_input,
decorations=self._decorations(
section_request,
suppress_auto_sections=self._derived_view_source == "authored",
),
requested=self._requested_dimensions(),
authored=self._authored_set(),
_post_build=place_declared_tables if self._tables else None,
_required_tables=required_tables,
_views=principal_views,
_include_iso=include_iso,
_view_constraints=constraints,
**opts,
)
except ViewPlanIncomplete as exc:
if self._principal_view_source != "authored":
raise
Expand Down
6 changes: 5 additions & 1 deletion tests/_tier_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,14 @@ class ContractGroup:
),
),
"leader_fixed_ink": ContractGroup(
("src/draftwright/annotations/_leader_fixed_ink.py",),
(
"src/draftwright/annotations/_leader_fixed_ink.py",
"src/draftwright/fixed_ink_cache.py",
),
(
"test_issue_1166_cross_pass_feature_leaders.py",
"test_issue_1534_build_progress.py",
"test_issue_367_leader_ink.py",
"test_issue_798_silhouette_lint.py",
),
),
Expand Down
3 changes: 3 additions & 0 deletions tests/test_import_boundaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ def _tree(path: Path) -> ast.Module:
_LAYERS: dict[str, int] = {
# Bottom/shared declarations: every rank-0 entry is a strict package leaf.
"_geometry": 0,
# Caller-owned exact rendered-face meshes; imports no engine modules and is
# consumed by annotation validation and the Sheet facade.
"fixed_ink_cache": 0,
# Structured ISO 10303-21 facts only; XCAF correspondence remains in rank-2 pmi.py.
"_pmi_part21": 0,
# Warning categories only. Imports nothing at all — deliberately, because a category
Expand Down
Loading
Loading