api: remove the helpers that only existed for a Part of several bodies

DECISION: delete inspect_body_overlaps_rlist, BodyOverlap, BodyOverlapWarning, part_shape and
part_from_bodies from the SDK, and narrow the text of measure_part_mass_rmassreport to one body.

WHY - THE DISCUSSION (owner and assistant, 2026-11-10; full account in design-docs/part-holds-one-solid.md)
A Part is one solid again, because the several solids the editor needs side by side are notebook values, not
product items, and the multi-body Part made assembly hard. Each of these helpers answered a question that
only exists when a Part holds several bodies:
- inspect_body_overlaps_rlist / BodyOverlap / BodyOverlapWarning: "do two bodies of one Part share volume?"
  (a Part of one solid has none; checking loose solids against each other is a different, not requested,
  feature);
- part_shape: "the Part as one shape, a Compound for several bodies" (it is `part.body`);
- part_from_bodies: "the Part a notebook's named solids make" (the new rule is in runtime/projection.py:
  one open solid is the Part, several are an error that says what to do).
They were public (`scad.*`) only since the multi-body work (after 2.2.7), and were first shipped by the
withdrawn 2.2.8 release, so removing them breaks no supported release.

WHAT CHANGES
- product/bodies.py keeps body_display_color, body_appearance_fields, BodyMass, MassReport and
  measure_part_mass_rmassreport (the report has one row: the Part's body; `.bodies` is still a tuple so a
  caller that read `report.body(id)` or `report.bodies[0]` keeps working).
- scad.__init__, operators/*, _glue/modules.json, _glue/docstrings.json (one entry removed, the mass entry
  re-derived from the new docstring) and the replay table of recording/serializer.py (the diagnostic
  entry of the removed operation) no longer list them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ni Jingzhe
2026-11-10 03:55:34 +08:00
parent 2029beedea
commit 84aab45d96
7 changed files with 16 additions and 154 deletions
+1 -10
View File
@@ -414,15 +414,7 @@ from .core import TaggedMixin
from .errors import SimpleCADError
from simplecadapi._glue.session import GraphSession
from .operators import render_screenshot_rpath
from .product.bodies import (
BodyMass,
BodyOverlap,
BodyOverlapWarning,
MassReport,
inspect_body_overlaps_rlist,
measure_part_mass_rmassreport,
part_shape,
)
from .product.bodies import BodyMass, MassReport, measure_part_mass_rmassreport
from .product.placement import Placement
from .product.capture import CaptureResult, capture
from .product.packages import (
@@ -667,7 +659,6 @@ __all__ = [
"solve_assembly_constraints_rassembly",
"measure_constraint_residual_rconstraintresidual",
"measure_part_mass_rmassreport",
"inspect_body_overlaps_rlist",
"inspect_assembly_constraints_rconstraintreport",
# Sketch construction and constraints
"add_point_rsketch",
+1 -2
View File
@@ -349,8 +349,7 @@
"var": "Create a physical or legacy scalar variable.\n\n``tolerance=0.1`` declares a symmetric ``+/-0.1`` tolerance. Use a\n``(lower_deviation, upper_deviation)`` pair for an asymmetric tolerance.\n``tolerance_unit`` defaults to ``unit`` when a nominal unit is declared.\nValues are converted to canonical CAD units only when evaluated, so the\ndeclaration and serialized expression node preserve the user's units.\n\nVariables without ``unit`` retain legacy unitless behavior. A unit-aware\nexpression cannot mix declared-unit variables with legacy variables.",
"cut_rsolid_list": "Compute the boolean difference of solids and keep every piece.\n\nA cut can split the body (a slot through a bar leaves two parts) or consume it\n(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses\nsuch a result because it returns exactly one ``Solid``; this operator returns\nthem all. A tool is cut from every piece it meets, so several tools may split\na body into several parts.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, a tool that meets none of the current\n pieces is ignored; when False it raises.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n list[Solid]: Every piece of the cut, in kernel order; empty when the tools\n consume the base.\n\nRaises:\n SimpleCADError: An input is not a valid Solid, or the kernel could not\n compute the cut.\n\nUsage:\n ``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by\n a through slot. Use ``cut_rsolid`` when the result must be one solid.\n",
"Body": "One named solid of a Part.\n\n``Body(body_id, solid, name=None, color=None, opacity=None)``: ``body_id`` is an\nidentifier unique within the part, ``solid`` the body's Solid, ``name`` an optional\ndisplay name, ``color`` an optional display colour (RGB floats in [0, 1]) and\n``opacity`` an optional display opacity in [0, 1]. A one-body Part has one Body with\nthe id ``\"body\"``. The colour overrides the Part's material colour for display only;\nset it on an existing Part with ``set_body_appearance_rpart``.",
"measure_part_mass_rmassreport": "Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.\n\nArgs:\n part: The Part to measure (one body or several).\n density: Density to use instead of the material's; ``None`` uses the\n Part's material, and without a material density every mass is ``None``.\n density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,\n ``kg/mm^3`` or ``g/mm^3``.\n\nReturns:\n MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,\n ``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part\n (``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).\n\nRaises:\n SimpleCADError: The value is not a Part, or the density or its unit is invalid.\n\nUsage:\n ``scad.measure_part_mass_rmassreport(case).body(\"lid\").mass_kg`` is the mass of\n the lid body; ``.mass_kg`` the mass of the whole part. Every body has the\n Part's material.",
"inspect_body_overlaps_rlist": "List the pairs of bodies of a Part that share volume.\n\nOverlapping bodies are allowed (a Part does not fuse them), but mass counts the\nshared volume once per body and STEP holds both copies. Bodies that only touch\n(a face, an edge or a point in common) do not overlap.\n\nArgs:\n part: The Part to inspect; a one-body Part has no overlaps.\n min_volume_mm3: Shared volume below which a pair is not reported.\n\nReturns:\n list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order.\n\nRaises:\n SimpleCADError: The value is not a Part.\n\nUsage:\n ``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's\n definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning``\n for the same pairs.",
"measure_part_mass_rmassreport": "Measure the volume, mass and centre of mass of a Part.\n\nArgs:\n part: The Part to measure.\n density: Density to use instead of the material's; ``None`` uses the\n Part's material, and without a material density every mass is ``None``.\n density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,\n ``kg/mm^3`` or ``g/mm^3``.\n\nReturns:\n MassReport: ``bodies`` (the Part's one ``BodyMass``: ``body_id``, ``volume_mm3``,\n ``mass_kg``, ``centroid_mm``) and the totals of the part (``volume_mm3``,\n ``mass_kg``, ``centroid_mm``).\n\nRaises:\n SimpleCADError: The value is not a Part, or the density or its unit is invalid.\n\nUsage:\n ``scad.measure_part_mass_rmassreport(bracket).mass_kg`` is the mass of the part.\n The part's material gives the density unless ``density`` is passed.",
"inspect_curve_rcurvedata": "Read the NURBS data of an edge's curve: what the curve edits work on.\n\nReturns ``{type, analytic, editable, conversion, degree, poles, weights, knots, multiplicities, periodic, rational, closed, domain, reversed, parameter_range}``. ``poles`` are points in the current coordinate system, indices are 0-based (the ``moves`` of ``move_curve_poles_redge``); ``parameter_range`` is the edge's own range (where ``insert_curve_knot_redge`` may insert). For a line, circle or other analytic curve ``editable`` is false, ``conversion`` is ``\"convert_to_bspline_redge\"`` and the data is what that conversion would produce. Not recorded in the graph.",
"inspect_surface_rsurfacedata": "Read the NURBS data of a face's surface: what the surface edits work on.\n\nReturns ``{type, analytic, editable, conversion, u_degree, v_degree, poles, weights, u_knots, v_knots, u_multiplicities, v_multiplicities, u_periodic, v_periodic, rational, domain, reversed, trimmed, uv_bounds}``. ``poles`` is a grid of rows along U, each row running along V (as ``make_bezier_surface_rface`` takes it), in the current coordinate system; indices are 0-based ``(row, column)``. ``domain`` is the surface's ``[u1, u2, v1, v2]``, ``uv_bounds`` the face's; ``trimmed`` says whether the face is bounded by anything but the surface's own domain. For a plane, cylinder or other analytic surface ``editable`` is false, ``conversion`` is ``\"convert_to_bspline_rface\"`` and the data is what that conversion would produce. Not recorded in the graph.",
"convert_to_bspline_redge": "Convert an edge's curve to a B-spline, so the curve edits can work on it.\n\nThe explicit, recorded step for analytic edges (a line becomes a degree-1 B-spline, a circle or arc a rational quadratic); the shape does not change, its parameter range may. Returns a new Edge; the input is not changed. Recorded: the Edge continues in the node's history, so tags and references follow.",
-1
View File
@@ -189,7 +189,6 @@
"cut_rsolid": "simplecadapi.operators.boolean",
"cut_rsolid_list": "simplecadapi.operators.boolean",
"measure_part_mass_rmassreport": "simplecadapi.operators.product",
"inspect_body_overlaps_rlist": "simplecadapi.operators.product",
"cut_shapes": "simplecadapi.kernel.ocp_booleans",
"diagnose_blend_failure": "simplecadapi.operators._diagnostics",
"diagnose_boolean_failure": "simplecadapi.operators._diagnostics",
+1 -2
View File
@@ -250,7 +250,7 @@ from . import boolean # noqa: F401
from . import transform # noqa: F401
from . import selection # noqa: F401
from . import product # noqa: F401
from .product import inspect_body_overlaps_rlist, measure_part_mass_rmassreport # Python-defined (product/bodies.py)
from .product import measure_part_mass_rmassreport # Python-defined (product/bodies.py)
from . import sketch # noqa: F401
__all__ = [
@@ -346,7 +346,6 @@ __all__ = [
"insert_curve_knot_redge",
"insert_surface_knot_rface",
"inspect_assembly_constraints_rconstraintreport",
"inspect_body_overlaps_rlist",
"inspect_curve_rcurvedata",
"inspect_sketch_rsketchcrossings",
"inspect_sketch_rsketchprofiles",
+1 -2
View File
@@ -43,7 +43,7 @@ from simplecadapi._cpp import (
solve_assembly_constraints_rassembly,
unground_component_rassembly,
)
from ..product.bodies import inspect_body_overlaps_rlist, measure_part_mass_rmassreport # Python-defined
from ..product.bodies import measure_part_mass_rmassreport # Python-defined
__all__ = [
"add_belt_constraint_rassembly",
@@ -72,7 +72,6 @@ __all__ = [
"make_vertex_connector_rconnector",
"measure_constraint_residual_rconstraintresidual",
"measure_part_mass_rmassreport",
"inspect_body_overlaps_rlist",
"place_component_rassembly",
"set_body_appearance_rpart",
"set_public_connector_rassembly",
+11 -132
View File
@@ -1,18 +1,15 @@
"""The bodies of a Part: its shape as one value, and the mass of each body.
"""The body of a Part: its display colour and the mass report.
A Part holds one Solid or several named bodies (see ``Part.bodies``). Geometry consumers that do not care which body a
face belongs to (STEP, STL, MJCF meshes) read :func:`part_shape`; consumers that do (the preview, the package, mass
properties) walk ``part.bodies``.
A Part holds exactly one Solid (``Part.body``). ``Part.bodies`` is that body as a one-element tuple: a ``Body`` carries
the display name, colour and opacity (``set_body_appearance_rpart``).
"""
from __future__ import annotations
import warnings
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from simplecadapi._cpp import Compound, Part, Solid, make_part_rpart
from simplecadapi._cpp import Part
# density unit -> factor to kg/mm^3 (the model is in millimetres)
_DENSITY_TO_KG_MM3 = {
@@ -53,19 +50,6 @@ def body_appearance_fields(body: Any) -> dict[str, Any]:
return out
def part_shape(part: Part) -> Solid | Compound:
"""The Solid of a one-body Part, or a Compound of every body of a multi-body Part (in body order).
The Compound is a geometry view: it is a new shape root and does not carry the bodies' tags.
"""
if not isinstance(part, Part):
raise TypeError("part must be a Part")
if not part.multi_body:
return part.body
return Compound([body.solid for body in part.bodies])
@dataclass(frozen=True)
class BodyMass:
"""Volume, mass and centre of mass of one body (millimetres, kilograms)."""
@@ -135,27 +119,26 @@ def measure_part_mass_rmassreport(
density: float | None = None,
density_unit: str | None = None,
) -> MassReport:
"""Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.
"""Measure the volume, mass and centre of mass of a Part.
Args:
part: The Part to measure (one body or several).
part: The Part to measure.
density: Density to use instead of the material's; ``None`` uses the
Part's material, and without a material density every mass is ``None``.
density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,
``kg/mm^3`` or ``g/mm^3``.
Returns:
MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,
``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part
(``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).
MassReport: ``bodies`` (the Part's one ``BodyMass``: ``body_id``, ``volume_mm3``,
``mass_kg``, ``centroid_mm``) and the totals of the part (``volume_mm3``,
``mass_kg``, ``centroid_mm``).
Raises:
SimpleCADError: The value is not a Part, or the density or its unit is invalid.
Usage:
``scad.measure_part_mass_rmassreport(case).body("lid").mass_kg`` is the mass of
the lid body; ``.mass_kg`` the mass of the whole part. Every body has the
Part's material.
``scad.measure_part_mass_rmassreport(bracket).mass_kg`` is the mass of the part.
The part's material gives the density unless ``density`` is passed.
"""
if not isinstance(part, Part):
@@ -189,112 +172,8 @@ def measure_part_mass_rmassreport(
)
class BodyOverlapWarning(UserWarning):
"""Two bodies of one Part share volume: mass counts it twice and STEP holds both copies."""
@dataclass(frozen=True)
class BodyOverlap:
"""Two bodies of a Part that share volume (mm^3)."""
first: str
second: str
volume_mm3: float
def to_dict(self) -> dict[str, Any]:
return {"first": self.first, "second": self.second, "volume_mm3": self.volume_mm3}
def _boxes_meet(a: tuple[float, ...], b: tuple[float, ...], tol: float) -> bool:
return all(a[axis] <= b[axis + 3] + tol and b[axis] <= a[axis + 3] + tol for axis in range(3))
def inspect_body_overlaps_rlist(part: Part, *, min_volume_mm3: float = 1e-6) -> list[BodyOverlap]:
"""List the pairs of bodies of a Part that share volume.
Overlapping bodies are allowed (a Part does not fuse them), but mass counts the
shared volume once per body and STEP holds both copies. Bodies that only touch
(a face, an edge or a point in common) do not overlap.
Args:
part: The Part to inspect; a one-body Part has no overlaps.
min_volume_mm3: Shared volume below which a pair is not reported.
Returns:
list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order.
Raises:
SimpleCADError: The value is not a Part.
Usage:
``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's
definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning``
for the same pairs.
"""
import simplecadapi._cpp._native as native
if not isinstance(part, Part):
raise TypeError("part must be a Part")
occt = native._occt
bodies = list(part.bodies)
boxes = [body.solid._bounds() for body in bodies]
out: list[BodyOverlap] = []
for i in range(len(bodies)):
for j in range(i + 1, len(bodies)):
if not _boxes_meet(boxes[i], boxes[j], 1e-7):
continue
common = occt.BRepAlgoAPI_Common(bodies[i].solid.wrapped, bodies[j].solid.wrapped).Shape()
props = occt.GProp_GProps()
occt.BRepGProp.VolumeProperties_s(common, props)
volume = float(props.Mass())
if volume > min_volume_mm3:
out.append(BodyOverlap(bodies[i].body_id, bodies[j].body_id, volume))
return out
def warn_body_overlaps(part: Part, *, stacklevel: int = 2) -> list[BodyOverlap]:
"""Warn (``BodyOverlapWarning``) once per overlapping pair of bodies of *part*; returns the pairs."""
if not part.multi_body:
return []
overlaps = inspect_body_overlaps_rlist(part)
for item in overlaps:
warnings.warn(
f"part {part.part_id!r}: bodies {item.first!r} and {item.second!r} overlap by {item.volume_mm3:.6g} mm^3 "
"(mass counts it twice; union them, or cut one from the other, if they are one piece of material)",
BodyOverlapWarning,
stacklevel=stacklevel,
)
return overlaps
def part_from_bodies(part_id: str, bodies: Mapping[str, Solid | Sequence[Solid]], *, name: str | None = None) -> Part:
"""The Part of named solids, the way a notebook names them: one name and one Solid is a one-body Part (body id
``"body"``); otherwise every name is a body, and the pieces of a split cut (a list) are ``<name>_1 .. <name>_n``.
This is the rule of an implicit product (a ``kind = "part"`` notebook without a ``make_part_rpart`` cell: its open
bodies, by variable name) and of an editor product cell with several bodies.
"""
items = dict(bodies)
if not items:
raise ValueError("a Part needs at least one body")
if len(items) == 1:
(value,) = items.values()
if isinstance(value, Solid) or (isinstance(value, (list, tuple)) and len(value) == 1):
return make_part_rpart(part_id=part_id, body=value, name=name)
return make_part_rpart(part_id=part_id, bodies=items, name=name)
__all__ = [
"BodyMass",
"BodyOverlap",
"BodyOverlapWarning",
"MassReport",
"inspect_body_overlaps_rlist",
"measure_part_mass_rmassreport",
"part_from_bodies",
"part_shape",
"warn_body_overlaps",
]
+1 -5
View File
@@ -385,13 +385,9 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = {
"status": "diagnostic",
"reason": "Measures current constraint residuals without changing model state.",
},
"inspect_body_overlaps_rlist": {
"status": "diagnostic",
"reason": "Reports which bodies of a Part share volume without changing model state.",
},
"measure_part_mass_rmassreport": {
"status": "diagnostic",
"reason": "Measures volume and mass of each body without changing model state.",
"reason": "Measures volume and mass of a Part without changing model state.",
},
"inspect_assembly_constraints_rconstraintreport": {
"status": "diagnostic",