diff --git a/cadquery/occ_impl/shapes.py b/cadquery/occ_impl/shapes.py index 40dd9dccf..90eb086f7 100644 --- a/cadquery/occ_impl/shapes.py +++ b/cadquery/occ_impl/shapes.py @@ -1614,6 +1614,15 @@ def mesh(self, tolerance: float, angularTolerance: float = 0.1) -> None: def tessellate( self, tolerance: float, angularTolerance: float = 0.1 ) -> tuple[list[Vector], list[tuple[int, int, int]]]: + """ + Convert the shape to a triangle mesh. + + Triangles with coincident vertices are not returned. + + :param tolerance: Linear deflection, scaled by the size of the edge being meshed. + :param angularTolerance: Angular deflection in radians. Default is 0.1. + :return: Vertices and triangles given as vertex index triples. + """ self.mesh(tolerance, angularTolerance) @@ -1635,29 +1644,21 @@ def tessellate( ) # add vertices - vertices += [ - Vector(v.X(), v.Y(), v.Z()) - for v in ( - poly.Node(i).Transformed(Trsf) for i in range(1, poly.NbNodes() + 1) - ) + nodes = [ + poly.Node(i).Transformed(Trsf).Coord() + for i in range(1, poly.NbNodes() + 1) ] + vertices += [Vector(*p) for p in nodes] - # add triangles + # add triangles, skipping those with coincident vertices triangles += [ ( - ( - t.Value(1) + offset - 1, - t.Value(3) + offset - 1, - t.Value(2) + offset - 1, - ) + (i1 + offset - 1, i3 + offset - 1, i2 + offset - 1) if reverse - else ( - t.Value(1) + offset - 1, - t.Value(2) + offset - 1, - t.Value(3) + offset - 1, - ) + else (i1 + offset - 1, i2 + offset - 1, i3 + offset - 1) ) - for t in poly.Triangles() + for i1, i2, i3 in (t.Get() for t in poly.Triangles()) + if len({nodes[i1 - 1], nodes[i2 - 1], nodes[i3 - 1]}) == 3 ] offset += poly.NbNodes() diff --git a/tests/test_exporters.py b/tests/test_exporters.py index 0e5355a02..fa490c1f5 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -28,6 +28,7 @@ Vector, Color, Shape, + Solid, ) from cadquery.occ_impl.shapes import rect, face, compound @@ -854,6 +855,30 @@ def test_tessellate(box123): assert len(triangles) == 12 +@pytest.mark.parametrize( + "shape", + [ + Workplane().sphere(10).val(), + Solid.makeCone(6, 0, 10), + Solid.makeTorus(5, 5), + Workplane().box(10, 10, 10).edges().fillet(2).val(), + ], +) +def test_tessellate_degenerate(shape): + """ + Tessellates shapes with surfaces that collapse to a point and checks that + no zero-area triangles are returned. + """ + + verts, triangles = shape.tessellate(1e-2) + + assert triangles + + for t in triangles: + v1, v2, v3 = (verts[i] for i in t) + assert (v2 - v1).cross(v3 - v1).Length > 0 + + def _dxf_spline_max_degree(fname): dxf = ezdxf.readfile(fname)