feat: shape.wrapped is an OCP shape when OCP is installed

With the verify extra installed, wrapped returns an OCP TopoDS_Shape of the class of its kind (as CadQuery's does), so the
OCCT code an agent writes for verifier scripts runs as written.  It is a copy made through BinTools; without OCP it stays
the SDK's own OCCT shape, and SCA_WRAPPED=native|ocp chooses.  The SDK's own layers take _native_wrapped, and the
inspect.brep queries, the STEP export and the kernel geometry helpers accept either kind of shape.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-28 16:43:42 +08:00
parent e80468a704
commit da24f18888
10 changed files with 343 additions and 15 deletions
+6
View File
@@ -25,6 +25,12 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and
its cache belongs to.
### Changed
- `shape.wrapped` is an OCP shape when OCP is installed (the `verify` extra), of the class of its kind (`TopoDS_Solid`,
`TopoDS_Face`, ...), as it is in CadQuery: the OCCT code an agent writes for verifier scripts runs as written
(`BRepGProp.VolumeProperties_s(solid.wrapped, props)`). It is a copy made through BinTools; without OCP it stays the
SDK's own OCCT shape. `SCA_WRAPPED=native|ocp` chooses. The SDK's own Python layers take `shape._native_wrapped`, which
is always the native one, and the functions that take a raw shape (the `inspect.brep` queries, the STEP export, the
geometry helpers of `simplecadapi.kernel`) accept either.
- Editor kernel: the cells keep what they made (`simplecadapi.runtime.cache._CellMemory`, 12 results; `SCA_NO_CELL_MEMORY=1`
turns it off). marimo unpickles an entry while it answers the cache lookup, which is about a second for each of the
six-axis arm's assemblies; the kernel now asks its memory right after the cell's key is hashed and before the disk,
@@ -146,6 +146,27 @@ targeted check:
- Assemblies: solve residuals, coaxiality of mated axes, flush faces, repeated
occurrences at named positions (`assembly-positioning.md`).
## OCCT measurements on an SDK shape
When the checks need more than the SDK exposes (point-in-solid, minimum distance between shapes, Boolean overlap
volume, centroids and inertia), write them with OCP exactly as OCCT references and CadQuery do. With OCP installed (the
`verify` extra), `shape.wrapped` **is an OCP shape** of the class of its kind (`TopoDS_Solid`, `TopoDS_Face`,
`TopoDS_Edge`, ...), so this runs as written:
```python
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
props = GProp_GProps()
BRepGProp.VolumeProperties_s(solid.wrapped, props)
volume = props.Mass()
```
`wrapped` is a copy made through OpenCASCADE's binary format (milliseconds for a part); changing it does not change the
SDK shape, and a shape you build in OCP comes back into the SDK with `simplecadapi._glue.bridge.from_occt`. Without OCP
installed `wrapped` is the SDK's own OCCT shape, which OCP functions reject: install the extra for verifier scripts.
`SCA_WRAPPED=native` or `SCA_WRAPPED=ocp` forces one view.
## Visual review converts to deterministic checks
A visual concern found at review (misplaced feature, wrong silhouette) is not
+172 -8
View File
@@ -1,23 +1,187 @@
"""The ``.wrapped`` view of a native shape.
A native shape's ``wrapped`` is the OpenCASCADE shape (``TopoDS_Solid``, ...) it stands for, as the class of
``simplecadapi._cpp.occt``: the same OpenCASCADE, so nothing is copied or serialised. The layers that stay Python
(inspect, drawings, translators, scene meshing) take their OCCT view of a shape through it; ``from_occt`` is the
way back for a shape they made (a STEP read, a decoded BREP).
``shape.wrapped`` is the OpenCASCADE shape a native shape stands for, and which OpenCASCADE that is depends on what is
installed. With OCP importable (the ``verify`` extra) it is an **OCP** ``TopoDS_Shape``: the object every OCCT reference,
CadQuery and an agent's habits expect, so ``BRepGProp.VolumeProperties_s(solid.wrapped, props)`` works as written. It is a
copy made through OpenCASCADE's binary format (milliseconds for a part): changing it does not change the SDK shape.
Without OCP it is the OCCT shape of ``simplecadapi._cpp.occt`` (the same OpenCASCADE the SDK computes with, nothing
copied), which is what the SDK's own Python layers (inspect, drawings, translators, scene meshing) work on: they take
``shape._native_wrapped``, which is always that one.
``SCA_WRAPPED=native`` or ``SCA_WRAPPED=ocp`` chooses. The SDK functions that take a raw shape (the ``inspect.brep``
queries, the STEP export) accept either; ``from_occt`` is the way back for a shape made with either.
"""
from __future__ import annotations
from typing import Any
import functools
import io
import os
from typing import Any, Callable
_SHAPE_CLASSES: tuple[Any, ...] = ()
_ocp_present: bool | None = None
def from_occt(shape: Any) -> Any:
"""The native shape of an OCCT shape."""
def ocp_available() -> bool:
"""Whether OCP can be imported (looked up once)."""
global _ocp_present
if _ocp_present is None:
try:
import OCP # noqa: F401
except ImportError:
_ocp_present = False
else:
_ocp_present = True
return _ocp_present
def wrapped_mode() -> str:
"""``"ocp"`` or ``"native"``: what ``.wrapped`` returns now (``SCA_WRAPPED`` first, else OCP when it is installed)."""
forced = os.environ.get("SCA_WRAPPED", "").strip().lower()
if forced in ("native", "ocp"):
return forced
return "ocp" if ocp_available() else "native"
def is_ocp_shape(value: Any) -> bool:
"""Whether *value* is an OCP ``TopoDS_Shape`` (any subclass)."""
return type(value).__module__.startswith("OCP") and hasattr(value, "ShapeType")
def ocp_to_native(shape: Any) -> Any:
"""The SDK shape of an OCP shape (a copy, through BinTools)."""
from OCP.BinTools import BinTools
import simplecadapi._cpp as n
buffer = io.BytesIO()
BinTools.Write_s(shape, buffer)
return n.from_brep(buffer.getvalue())
def native_occt(value: Any) -> Any:
"""*value* as the OCCT shape the SDK's Python layers work on: an OCP shape is converted, anything else is kept."""
if is_ocp_shape(value):
return ocp_to_native(value)._native_wrapped
return value
def from_occt(shape: Any) -> Any:
"""The native shape of an OCCT shape (an OCP shape or one of ``simplecadapi._cpp.occt``)."""
import simplecadapi._cpp as n
if is_ocp_shape(shape):
return ocp_to_native(shape)
return n._from_occt(shape)
def accepts_ocp(function: Callable[..., Any]) -> Callable[..., Any]:
"""*function* taking OCP shapes where it takes OCCT shapes (a shape, or a list or tuple of them)."""
def convert(value: Any) -> Any:
if is_ocp_shape(value):
return native_occt(value)
if isinstance(value, (list, tuple)) and any(is_ocp_shape(item) for item in value):
return type(value)(native_occt(item) for item in value)
return value
@functools.wraps(function)
def wrapper(*args: Any, **kwargs: Any) -> Any:
return function(*(convert(arg) for arg in args), **{key: convert(value) for key, value in kwargs.items()})
return wrapper
def accepting_ocp(namespace: dict[str, Any], names: Any = None, *, reexported: bool = False) -> None:
"""Make the public functions of a module (its globals) take OCP shapes: ``accepting_ocp(globals())``.
Only functions defined in the module are wrapped (not what it imports), unless *reexported*: a package that
re-exports the functions of its submodules wraps its own names for them.
"""
module = namespace.get("__name__")
for name in list(names if names is not None else namespace.get("__all__") or namespace):
function = namespace.get(name)
if name.startswith("_") or not callable(function):
continue
if not reexported and getattr(function, "__module__", None) != module:
continue
if isinstance(function, type) or not hasattr(function, "__code__"):
continue
namespace[name] = accepts_ocp(function)
def native_to_ocp(shape: Any) -> Any:
"""The OCP ``TopoDS_Shape`` of an SDK shape (a copy, through BinTools)."""
from OCP.BinTools import BinTools
from OCP.TopoDS import TopoDS_Shape
if not hasattr(shape, "to_brep"):
raise TypeError(
f"expected an SDK shape (Solid, Face, Wire, Edge, Vertex, Compound, ...), got {type(shape).__name__}; "
"an OCP shape is already one"
)
result = TopoDS_Shape()
BinTools.Read_s(result, io.BytesIO(shape.to_brep()))
return _concrete(result)
def _concrete(shape: Any) -> Any:
"""*shape* as the class of its kind (``TopoDS_Edge``, ``TopoDS_Solid``, ...), as CadQuery's ``wrapped`` is.
OCP's functions take the concrete class where they mean one (``BRepAdaptor_Curve(edge)``), and BinTools reads a
generic ``TopoDS_Shape``.
"""
from OCP.TopAbs import TopAbs_ShapeEnum as kind
from OCP.TopoDS import TopoDS
casts = {
kind.TopAbs_COMPOUND: TopoDS.Compound_s,
kind.TopAbs_COMPSOLID: TopoDS.CompSolid_s,
kind.TopAbs_SOLID: TopoDS.Solid_s,
kind.TopAbs_SHELL: TopoDS.Shell_s,
kind.TopAbs_FACE: TopoDS.Face_s,
kind.TopAbs_WIRE: TopoDS.Wire_s,
kind.TopAbs_EDGE: TopoDS.Edge_s,
kind.TopAbs_VERTEX: TopoDS.Vertex_s,
}
cast = casts.get(shape.ShapeType())
return cast(shape) if cast is not None else shape
_to_ocp = native_to_ocp
def install(nat: Any) -> None:
"""Nothing to install: ``wrapped`` is a property of the C++ shape classes."""
"""Make ``wrapped`` follow :func:`wrapped_mode` on every shape class; ``_native_wrapped`` stays the SDK's own view."""
global _SHAPE_CLASSES
classes = []
for name in dir(nat):
cls = getattr(nat, name)
if isinstance(cls, type) and "wrapped" in cls.__dict__ and "_native_wrapped" not in cls.__dict__:
classes.append(cls)
for cls in classes:
native = cls.__dict__["wrapped"]
cls._native_wrapped = native
def wrapped(self: Any, _native: Any = native) -> Any:
if wrapped_mode() == "ocp":
return _to_ocp(self)
return _native.fget(self)
wrapped.__doc__ = (
"The OpenCASCADE shape of this shape: an OCP ``TopoDS_Shape`` (a copy) when OCP is installed, else the "
"OCCT shape of ``simplecadapi._cpp.occt``. See simplecadapi._glue.bridge."
)
cls.wrapped = property(wrapped)
_SHAPE_CLASSES = tuple(classes)
+5 -2
View File
@@ -149,6 +149,7 @@ from inspect import isfunction as _isfunction
import sys as _sys
from simplecadapi._cpp import get_active_session as _get_active_session
from simplecadapi._glue.bridge import accepts_ocp as _accepts_ocp
def _outside_model_graph(function):
@@ -168,8 +169,10 @@ for _public_name in __all__:
_public_value = globals()[_public_name]
if not _isfunction(_public_value):
continue
_checked_value = _outside_model_graph(_public_value)
# a raw shape may be an OCP one (`shape.wrapped` is, when OCP is installed): the queries work on the SDK's own
# OCCT, so such a shape is converted on the way in
_checked_value = _accepts_ocp(_outside_model_graph(_public_value))
globals()[_public_name] = _checked_value
setattr(_sys.modules[_public_value.__module__], _public_name, _checked_value)
del _checked_value, _isfunction, _outside_model_graph, _public_name, _public_value
del _accepts_ocp, _checked_value, _isfunction, _outside_model_graph, _public_name, _public_value
+7
View File
@@ -51,3 +51,10 @@ def export_stl_shape(shape: TopoDS_Shape, filename: str) -> None:
ok = writer.Write(shape, str(Path(filename)))
if ok is False:
raise ValueError("STL write failed")
# `shape.wrapped` is an OCP shape when OCP is installed: these helpers work on the SDK's own OCCT
from simplecadapi._glue.bridge import accepting_ocp as _accepting_ocp # noqa: E402
_accepting_ocp(globals())
del _accepting_ocp
@@ -266,3 +266,10 @@ def face_normal_at(face: TopoDS_Face, u: float = 0.5, v: float = 0.5) -> Vec3:
def edge_center(edge: TopoDS_Edge) -> Vec3:
return center_of_mass(edge)
# `shape.wrapped` is an OCP shape when OCP is installed: these helpers work on the SDK's own OCCT
from simplecadapi._glue.bridge import accepting_ocp as _accepting_ocp # noqa: E402
_accepting_ocp(globals())
del _accepting_ocp
+3 -3
View File
@@ -1579,7 +1579,7 @@ def _shape_geom_type(shape: AnyShape) -> Optional[str]:
)
if isinstance(shape, Edge):
curve_type = BRepAdaptor_Curve(shape.wrapped).GetType()
curve_type = BRepAdaptor_Curve(shape._native_wrapped).GetType()
mapping = {
GeomAbs_Line: "LINE",
GeomAbs_Circle: "CIRCLE",
@@ -1591,7 +1591,7 @@ def _shape_geom_type(shape: AnyShape) -> Optional[str]:
str(curve_type).replace("GeomAbs_CurveType.GeomAbs_", "").upper(),
)
if isinstance(shape, Face):
surface_type = BRepAdaptor_Surface(shape.wrapped).GetType()
surface_type = BRepAdaptor_Surface(shape._native_wrapped).GetType()
mapping = {
GeomAbs_Plane: "PLANE",
GeomAbs_Cylinder: "CYLINDER",
@@ -1620,7 +1620,7 @@ def _shape_bounding_box(shape: AnyShape) -> Any:
return SimpleNamespace(xmin=xmin, ymin=ymin, zmin=zmin, xmax=xmax, ymax=ymax, zmax=zmax)
from ..kernel.ocp_properties import bounding_box
return bounding_box(shape.wrapped)
return bounding_box(shape._native_wrapped)
def _bbox_score(shape: AnyShape, selector: Dict[str, Any]) -> float:
+2 -2
View File
@@ -146,7 +146,7 @@ def build_edge_mesh(
raise ValueError("edge entity count does not match the solid topology")
blocks = tuple(
_edge_block(
edge if hasattr(edge, "_polyline") else edge.wrapped,
edge if hasattr(edge, "_polyline") else edge._native_wrapped,
entity_id=entity_id,
linear_tolerance=linear_tolerance,
angular_tolerance=angular_tolerance,
@@ -191,7 +191,7 @@ def solid_asset_bounds(solid: Solid) -> tuple[tuple[float, float, float], tuple[
return ((float(xmin), float(ymin), float(zmin)), (float(xmax), float(ymax), float(zmax)))
from ..kernel.ocp_properties import bounding_box
box = bounding_box(solid.wrapped)
box = bounding_box(solid._native_wrapped)
return (
(float(box.xmin), float(box.ymin), float(box.zmin)),
(float(box.xmax), float(box.ymax), float(box.zmax)),
+5
View File
@@ -17,6 +17,11 @@ os.environ.setdefault("SCA_DIAGNOSTIC_RENDER_BUDGET", "60")
# run would only slow the rest of the suite down.
os.environ.setdefault("SCA_JOBS", "1")
# ``shape.wrapped`` is an OCP shape when OCP is installed (the ``verify`` extra). Most of the suite hands it to the
# SDK's own OCCT classes (``simplecadapi._cpp.occt``), which want the native one, whether or not OCP happens to be in
# the environment: tests about the OCP view (test_wrapped_ocp.py) ask for it themselves.
os.environ.setdefault("SCA_WRAPPED", "native")
# ---------------------------------------------------------------------------
# The C++ backend: failures that are known and classified.
+115
View File
@@ -0,0 +1,115 @@
"""``shape.wrapped`` is an OCP shape when OCP is installed, so the OCCT code an agent knows runs as written."""
from __future__ import annotations
import pytest
pytest.importorskip("OCP")
import simplecadapi as scad
from simplecadapi import ql
from simplecadapi._glue import bridge
@pytest.fixture(autouse=True)
def ocp_view(monkeypatch):
monkeypatch.delenv("SCA_WRAPPED", raising=False) # (the suite's default is the native view)
def box():
return scad.make_box_rsolid(2.0, 3.0, 4.0)
def test_wrapped_is_the_ocp_class_of_the_kind_of_shape() -> None:
from OCP.TopoDS import TopoDS_Edge, TopoDS_Face, TopoDS_Solid
solid = box()
edge = ql.select(ql.edges().resolve(solid)).all()[0]
face = ql.select(ql.faces().resolve(solid)).all()[0]
assert type(solid.wrapped) is TopoDS_Solid
assert type(edge.wrapped) is TopoDS_Edge
assert type(face.wrapped) is TopoDS_Face
assert type(solid.wrapped).__module__.startswith("OCP")
def test_the_code_an_agent_writes_for_cadquery_runs_as_written() -> None:
from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface
from OCP.BRepBndLib import BRepBndLib
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.BRepGProp import BRepGProp
from OCP.Bnd import Bnd_Box
from OCP.GProp import GProp_GProps
solid = box()
props = GProp_GProps()
BRepGProp.VolumeProperties_s(solid.wrapped, props)
assert props.Mass() == pytest.approx(solid.get_volume(), rel=1e-9)
bounds = Bnd_Box()
BRepBndLib.Add_s(solid.wrapped, bounds)
xmin, ymin, zmin, xmax, ymax, zmax = bounds.Get()
assert (xmax - xmin, ymax - ymin, zmax - zmin) == pytest.approx((2.0, 3.0, 4.0), abs=1e-6)
assert BRepCheck_Analyzer(solid.wrapped).IsValid()
edge = ql.select(ql.edges().resolve(solid)).all()[0]
face = ql.select(ql.faces().resolve(solid)).all()[0]
assert "Line" in str(BRepAdaptor_Curve(edge.wrapped).GetType())
assert "Plane" in str(BRepAdaptor_Surface(face.wrapped).GetType())
def test_each_access_is_a_copy_of_the_same_geometry() -> None:
from OCP.BRepGProp import BRepGProp
from OCP.GProp import GProp_GProps
solid = box()
first, second = solid.wrapped, solid.wrapped
assert first is not second
for shape in (first, second):
props = GProp_GProps()
BRepGProp.VolumeProperties_s(shape, props)
assert props.Mass() == pytest.approx(24.0)
def test_the_choice_can_be_made_either_way(monkeypatch) -> None:
monkeypatch.setenv("SCA_WRAPPED", "native")
assert type(box().wrapped).__module__.endswith("_occt")
monkeypatch.setenv("SCA_WRAPPED", "ocp")
assert type(box().wrapped).__module__.startswith("OCP")
assert box()._native_wrapped is not None # the SDK's own view does not depend on it
assert type(box()._native_wrapped).__module__.endswith("_occt")
def test_without_ocp_the_view_is_the_native_one(monkeypatch) -> None:
monkeypatch.setattr(bridge, "_ocp_present", False)
assert bridge.wrapped_mode() == "native"
assert type(box().wrapped).__module__.endswith("_occt")
def test_the_inspect_queries_take_an_ocp_shape_and_a_native_one(monkeypatch) -> None:
from simplecadapi.inspect import brep
solid = box()
from_ocp = brep.index_shape_rbrepmodel(solid.wrapped).summary()
monkeypatch.setenv("SCA_WRAPPED", "native")
from_native = brep.index_shape_rbrepmodel(solid.wrapped).summary()
assert from_ocp == from_native
def test_the_helpers_and_the_step_export_take_an_ocp_shape(tmp_path) -> None:
from simplecadapi.kernel.ocp_export import export_step_shapes
from simplecadapi.kernel.ocp_properties import bounding_box
solid = box()
bounds = bounding_box(solid.wrapped)
assert (bounds.xmax - bounds.xmin, bounds.zmax - bounds.zmin) == pytest.approx((2.0, 4.0), abs=1e-6)
target = tmp_path / "box.step"
export_step_shapes([solid.wrapped], str(target))
assert target.stat().st_size > 0
def test_the_way_back_from_an_ocp_shape_keeps_the_geometry() -> None:
back = bridge.from_occt(box().wrapped)
assert back.get_volume() == pytest.approx(24.0)
def test_something_that_is_not_a_shape_is_refused_with_a_reason() -> None:
with pytest.raises(TypeError, match="SDK shape"):
bridge.native_to_ocp(5)