Files
make-cad/test/test_boolean_clean.py
Ni Jingzhe 35a4e5efa9 fix(kernel): cut and intersect unify what they leave split, and a blend never returns an invalid solid (#88)
DECISION: three changes, in this order of importance, each independent of the others.
(1) a fillet or chamfer whose result OCCT calls invalid is an error; (2) cut_rsolid, cut_rsolid_list and
intersect_rsolid unify the same-domain faces and edges of their result by default, with `clean=False` to keep the raw
result, as union already does; (3) the diagnosis names split faces instead of blaming the radius. No compatibility
shim for records made before `clean` existed: replay requires the parameter, like every other recorded one.

PROBLEM (reproduced on the issue's two cases, current dev build on Windows, OCCT 7.9.3)
A cut through the side of a box with a cylinder splits the cylinder wall along the cylinder's parametric seam into two
faces, and the top edge of the notch into a long and a short arc. union unified (ShapeUpgrade_UnifySameDomain) and cut
did not. OCCT then fillets that top edge wrongly:
- case A: BRepCheck-invalid solid, volume 28305.59 (should be 29604.46), no error at all: `fillet_rsolid` checked only
  IsDone and volume > 0;
- case B: refusal, and the diagnosis said "the radius exceeds the 2.5 mm of face room" - the half of the wall the seam cut
  off - so the advised radius was not the limit.
Same geometry, other libraries: CadQuery and build123d clean after a boolean by default and give 29604.46 / 29811.31.

(1) THE EXIT CHECK IS THE MOST IMPORTANT
`assert_blend_valid`, next to the volume check in `finish_blend` (fillet and chamfer): BRepCheck_Analyzer on the result;
invalid while the input was valid is a BlendValidityViolation, which leads the error message ("the kernel returned broken
geometry"), like the existing volume violation. Not raised when the input was already invalid (an imported solid is not
the blend's fault). It turns "wrong volume found three operations later" into an error at the operation that caused it,
whatever else is or is not done about cleaning.

(2) CLEAN BY DEFAULT, WITH THE HISTORY FOLLOWING
SDK booleans go through `tracked_cut` / `tracked_intersect`, which ask the kernel's history what became of every face
(that is how tags and lineage survive), so cleaning only the shape would break tracking. `BooleanOptions::clean` makes
`run_boolean` unify the result, merge the unifier's history into the boolean's, and follow the section edges through it;
the section-edge following was lifted out of `fuse_shapes_with_history` into one helper both use (fuse behaves as
before). The unified shape replaces the result only when it has the same number of solids and is valid whenever the raw
result was; otherwise the raw result stands. FreeCAD and build123d fall back the same way, and replicad's unconditional
SimplifyResult has been seen to invalidate results (BarbourSmith/Abundance#1934), so the fallback is not decoration.
`clean` is a keyword of the three functions (default True), recorded as params.clean like union's. C++ `cut_shapes`,
`common_shapes` and `tracked_*` keep `clean=false` as their default so other callers (diagnosis, set booleans, std
parts) are unchanged.
Not done on purpose: OCCT's own SimplifyResult(true, true) that the issue suggests: the explicit unifier already gives
the same merge and history, with a fallback we control.

REPLAY: NO LEGACY BRANCH (owner's rule: do not keep old formats alive)
`flag(p, "clean")` and `ctx.require_params(..., "clean")` fail on a graph recorded before this change, as they do for
any missing parameter. Such a graph has to be recorded again.

(3) THE DIAGNOSIS
`classify_split_faces`, before the face-room probe: unify the solid, carry the selected edges over with the unifier's
history, blend again with the same size; if that works the split faces are the cause, and the message says so and how to
fix it (clean=True, or union_rsolid(clean=True)). The room probe stays for a radius that really is too large (test:
radius 50 on the cleaned case is still reported as too large).

EVIDENCE
- Both cases now give valid fillets with volumes 29604.46 and 29811.31, equal to CadQuery's.
- clean=False: A raises "not a valid solid" (it was returned), B raises "faces ... split on a surface ... clean=True".
- test/test_boolean_clean.py (10 tests): face counts 8 against 9, volume unchanged by cleaning, cut_list and intersect,
  both cases, both clean=False diagnoses, a really-too-large radius, `clean` recorded, replay giving 8 / 9 faces.
- A random sample, 120 cases of the issue's recipe (box minus 2-4 vertical boxes/cylinders on a grid, top edges, r 1-3),
  both modes: 240 results, none invalid and returned (clean=True 84 valid / 36 errors, clean=False 83 / 37).
- Full Python suite on this machine: 2674 passed; 22 failed and 9 errors, none touching booleans (Windows paths,
  encodings, file locks, addon and shell integration, missing OCP, a math-library last digit in test_tolerance).

NOT DONE / NOT KNOWN
- The C++ unit tests (ctest) were not built or run here (SCAD_BUILD_TESTS is off for the wheel build). CutOptions::clean
  defaults to true, so a C++ test that compares a cut's topology may need its expectation updated: CI will say.
- The issue's 16000-case run was not repeated, only the small sample above; it shows that no invalid result is
  returned, not the 0.4% rate of the issue (there is no old binary here to compare with).
- A stored artifact or fingerprint of a model with a cut that left split faces changes: the faces are fewer. That is the
  point of the change; rebuild such models.
- Unifying can still make a later blend worse on rare inputs (the issue saw 6 segfaults after unify in other libraries
  too); here the unify is inside the boolean, so a crash would show in the boolean.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:31:21 +08:00

129 lines
5.7 KiB
Python

"""cut / intersect unify what they leave split, and a blend never hands back an invalid solid (issue #88).
A cut through the side of a box with a cylinder splits the cylinder wall along the cylinder's parametric seam into two
faces, and the top edge of the notch into a long and a short arc. OCCT then fillets that top edge wrongly: it returns
an invalid solid with a volume that is too small (case A), or refuses and the diagnosis blames the radius (case B).
The same geometry fillets fine once the faces are unified, which is what union already did and cut did not.
"""
from __future__ import annotations
import unittest
import simplecadapi as scad
from simplecadapi import ql
from simplecadapi._cpp.occt.BRepCheck import BRepCheck_Analyzer
from simplecadapi.errors import SimpleCADError
from simplecadapi.recording.graph import GraphSession
# the issue's two placements of the cylinder; volumes are what CadQuery and build123d (which clean by default) give
CASE_A = (0.0, 17.5)
CASE_B = (-12.5, -17.5)
VOLUME_A = 29604.46
VOLUME_B = 29811.31
def notch(cx: float, cy: float, **options):
box = scad.make_box_rsolid(width=40, height=40, depth=20, bottom_face_center=(0, 0, 0))
cylinder = scad.make_cylinder_rsolid(radius=10, height=40, bottom_face_center=(cx, cy, 10))
return scad.cut_rsolid(box, cylinder, **options)
def top_edges(solid, z: float = 20.0):
return [
edge
for edge in ql.edges().resolve(solid)
if abs(edge.get_start_vertex().get_coordinates()[2] - z) < 1e-6
and abs(edge.get_end_vertex().get_coordinates()[2] - z) < 1e-6
]
def is_valid(solid) -> bool:
return bool(BRepCheck_Analyzer(solid.wrapped).IsValid())
def face_count(solid) -> int:
return len(ql.faces().resolve(solid))
class TestCutCleans(unittest.TestCase):
def test_cut_unifies_the_wall_the_seam_split(self):
self.assertEqual(face_count(notch(*CASE_A)), 8)
self.assertEqual(face_count(notch(*CASE_A, clean=False)), 9)
def test_the_cleaned_cut_keeps_its_volume(self):
self.assertAlmostEqual(notch(*CASE_A).get_volume(), notch(*CASE_A, clean=False).get_volume(), places=3)
def test_cut_list_and_intersect_clean_by_default_too(self):
box = scad.make_box_rsolid(width=40, height=40, depth=20, bottom_face_center=(0, 0, 0))
cylinder = scad.make_cylinder_rsolid(radius=10, height=40, bottom_face_center=(0, 17.5, 10))
(piece,) = scad.cut_rsolid_list(box, cylinder)
self.assertEqual(face_count(piece), 8)
(raw,) = scad.cut_rsolid_list(box, cylinder, clean=False)
self.assertEqual(face_count(raw), 9)
# the part of the box inside the cylinder: a cylinder wall cut along its seam is two faces unless unified
inside = scad.intersect_rsolid(box, cylinder)
raw_inside = scad.intersect_rsolid(box, cylinder, clean=False)
self.assertLess(face_count(inside), face_count(raw_inside))
self.assertAlmostEqual(inside.get_volume(), raw_inside.get_volume(), places=3)
class TestFilletAfterCut(unittest.TestCase):
def test_case_a_fillets_to_a_valid_solid_with_the_right_volume(self):
cut = notch(*CASE_A)
filleted = scad.fillet_rsolid(solid=cut, edges=top_edges(cut), radius=3.0)
self.assertTrue(is_valid(filleted))
self.assertAlmostEqual(filleted.get_volume(), VOLUME_A, delta=0.05)
def test_case_b_fillets_with_the_radius_the_diagnosis_called_too_large(self):
cut = notch(*CASE_B)
filleted = scad.fillet_rsolid(solid=cut, edges=top_edges(cut), radius=3.0)
self.assertTrue(is_valid(filleted))
self.assertAlmostEqual(filleted.get_volume(), VOLUME_B, delta=0.05)
def test_an_unclean_cut_no_longer_yields_an_invalid_fillet(self):
"""Case A without the clean-up: OCCT's fillet is invalid. It used to be returned; now it is an error."""
cut = notch(*CASE_A, clean=False)
with self.assertRaises(SimpleCADError) as raised:
scad.fillet_rsolid(solid=cut, edges=top_edges(cut), radius=3.0)
self.assertIn("not a valid solid", str(raised.exception))
def test_an_unclean_cut_names_the_split_faces_not_the_radius(self):
"""Case B without the clean-up: the kernel refuses, and the diagnosis says why instead of 'reduce the radius'."""
cut = notch(*CASE_B, clean=False)
with self.assertRaises(SimpleCADError) as raised:
scad.fillet_rsolid(solid=cut, edges=top_edges(cut), radius=3.0)
message = str(raised.exception)
self.assertIn("split on a surface", message)
self.assertIn("clean=True", message)
self.assertNotIn("Reduce the radius", message)
def test_a_radius_that_really_is_too_large_is_still_reported_as_such(self):
cut = notch(*CASE_A)
with self.assertRaises(SimpleCADError) as raised:
scad.fillet_rsolid(solid=cut, edges=top_edges(cut), radius=50.0)
self.assertNotIn("split on a surface", str(raised.exception))
class TestRecordedClean(unittest.TestCase):
"""``clean`` is a recorded parameter like ``skip_non_intersecting``; replay reads it, there is no default for a
record that lacks it."""
def record(self, **options):
with GraphSession() as session:
notch(*CASE_A, **options)
return session
def test_the_flag_is_recorded(self):
self.assertTrue(self.record().graph.leaf_nodes()[0].params["clean"])
self.assertFalse(self.record(clean=False).graph.leaf_nodes()[0].params["clean"])
def test_replay_reproduces_the_recorded_result(self):
for options, faces in (({}, 8), ({"clean": False}, 9)):
(replayed,) = scad.replay_graph(self.record(**options).graph) # the leaf: the cut
self.assertEqual(face_count(replayed), faces, options)
if __name__ == "__main__":
unittest.main()