Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support non-convex planar loop triangulation

Yuechen Li826178734180
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs
index 4c14c9b9..ea0beba7 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs
@@ -1,5 +1,6 @@
using System.Text;
using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Step242;
namespace Aetheris.Kernel.Core.Tests.Step242;
@@ -30,6 +31,42 @@ public sealed class Step242TessellationRobustnessTests
}
}
+ [Fact]
+ public void Step242_Tessellate_PlanarFace_NonConvexSingleLoop_SucceedsAndProducesTriangles()
+ {
+ var text = LoadFixture("testdata/step242/tessellation-robustness/planar-nonconvex-single-loop.step");
+
+ var import = Step242Importer.ImportBody(text);
+
+ Assert.True(import.IsSuccess);
+
+ var tessellation = BrepDisplayTessellator.Tessellate(import.Value);
+
+ Assert.True(tessellation.IsSuccess);
+
+ var facePatch = Assert.Single(tessellation.Value.FacePatches);
+ Assert.True(facePatch.TriangleIndices.Count > 0);
+ Assert.DoesNotContain(tessellation.Diagnostics, d => d.Message.Contains("requires a convex polygon", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Step242_Tessellate_PlanarFace_DegenerateLoop_FailsDeterministically()
+ {
+ var text = LoadFixture("testdata/step242/tessellation-robustness/planar-degenerate-loop.step");
+
+ var import = Step242Importer.ImportBody(text);
+
+ Assert.True(import.IsSuccess);
+
+ var tessellation = BrepDisplayTessellator.Tessellate(import.Value);
+
+ Assert.False(tessellation.IsSuccess);
+
+ var diagnostic = Assert.Single(tessellation.Diagnostics);
+ Assert.Equal(KernelDiagnosticCode.InvalidArgument, diagnostic.Code);
+ Assert.Equal("Viewer.Tessellation.PlanarPolygonDegenerate", diagnostic.Source);
+ }
+
private static string LoadFixture(string relativePath)
{
var path = Path.Combine(Step242CorpusManifestRunner.RepoRoot(), relativePath.Replace('/', Path.DirectorySeparatorChar));
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index f8ed0349..0871d742 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -103,10 +103,17 @@ public static class BrepDisplayTessellator
return KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} planar loop must contain at least three line coedges.")]);
}
- var indices = BuildPlanarTriangleIndices(polygonPoints, plane.Normal.ToVector());
- if (indices is null)
+ if (!PlanarPolygonTriangulator.TryTriangulate(polygonPoints, plane.Normal.ToVector(), out var indices, out var failure))
{
- return KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} planar loop triangulation requires a convex polygon.")]);
+ return failure switch
+ {
+ PlanarPolygonTriangulationFailure.Degenerate => KernelResult<DisplayFaceMeshPatch>.Failure([
+ CreateInvalidArgument($"Face {faceId.Value} planar loop is degenerate and cannot be triangulated.", "Viewer.Tessellation.PlanarPolygonDegenerate")]),
+ PlanarPolygonTriangulationFailure.NonSimple => KernelResult<DisplayFaceMeshPatch>.Failure([
+ CreateNotImplemented($"Face {faceId.Value} planar loop triangulation failed because the polygon is not simple.", "Viewer.Tessellation.PlanarNonConvexTriangulationFailed")]),
+ _ => KernelResult<DisplayFaceMeshPatch>.Failure([
+ CreateNotImplemented($"Face {faceId.Value} planar loop triangulation failed.", "Viewer.Tessellation.PlanarNonConvexTriangulationFailed")]),
+ };
}
return KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, polygonPoints, plane.Normal.ToVector(), indices), successDiagnostics);
@@ -504,68 +511,6 @@ public static class BrepDisplayTessellator
return matchIndex;
}
- private static IReadOnlyList<int>? BuildPlanarTriangleIndices(IReadOnlyList<Point3D> polygonPoints, Vector3D expectedNormal)
- {
- if (!IsConvexPolygon(polygonPoints, expectedNormal))
- {
- return null;
- }
-
- var indices = new List<int>((polygonPoints.Count - 2) * 3);
- for (var i = 1; i < polygonPoints.Count - 1; i++)
- {
- indices.Add(0);
- indices.Add(i);
- indices.Add(i + 1);
- }
-
- if (indices.Count >= 3)
- {
- var firstNormal = (polygonPoints[indices[1]] - polygonPoints[indices[0]])
- .Cross(polygonPoints[indices[2]] - polygonPoints[indices[0]]);
- if (firstNormal.Dot(expectedNormal) < 0d)
- {
- for (var i = 0; i < indices.Count; i += 3)
- {
- (indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]);
- }
- }
- }
-
- return indices;
- }
-
- private static bool IsConvexPolygon(IReadOnlyList<Point3D> polygonPoints, Vector3D expectedNormal)
- {
- var referenceSign = 0;
- for (var i = 0; i < polygonPoints.Count; i++)
- {
- var a = polygonPoints[i];
- var b = polygonPoints[(i + 1) % polygonPoints.Count];
- var c = polygonPoints[(i + 2) % polygonPoints.Count];
- var cross = (b - a).Cross(c - b);
- var dot = cross.Dot(expectedNormal);
- if (double.Abs(dot) <= LoopEndpointTolerance)
- {
- continue;
- }
-
- var sign = dot > 0d ? 1 : -1;
- if (referenceSign == 0)
- {
- referenceSign = sign;
- continue;
- }
-
- if (referenceSign != sign)
- {
- return false;
- }
- }
-
- return referenceSign != 0;
- }
-
private static bool PointsAlmostEqual(Point3D left, Point3D right)
=> (left - right).LengthSquared <= (LoopEndpointTolerance * LoopEndpointTolerance);
@@ -736,11 +681,11 @@ public static class BrepDisplayTessellator
return System.Math.Clamp(segments, options.MinimumSegments, options.MaximumSegments);
}
- private static KernelDiagnostic CreateInvalidArgument(string message)
- => new(KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, message);
+ private static KernelDiagnostic CreateInvalidArgument(string message, string? source = null)
+ => new(KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, message, source);
- private static KernelDiagnostic CreateNotImplemented(string message)
- => new(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message);
+ private static KernelDiagnostic CreateNotImplemented(string message, string? source = null)
+ => new(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source);
private static KernelDiagnostic CreateValidationWarning(string message, string source)
=> new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning, message, source);
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.cs
new file mode 100644
index 00000000..0120634f
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarPolygonTriangulator.cs
@@ -0,0 +1,266 @@
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Kernel.Core.Brep.Tessellation;
+
+internal enum PlanarPolygonTriangulationFailure
+{
+ Degenerate,
+ NonSimple,
+ TriangulationFailed
+}
+
+internal static class PlanarPolygonTriangulator
+{
+ private const double Epsilon = 1e-9d;
+
+ public static bool TryTriangulate(
+ IReadOnlyList<Point3D> polygonPoints,
+ Vector3D planeNormal,
+ out IReadOnlyList<int> indices,
+ out PlanarPolygonTriangulationFailure? failure)
+ {
+ indices = Array.Empty<int>();
+ failure = null;
+
+ if (polygonPoints.Count < 3)
+ {
+ failure = PlanarPolygonTriangulationFailure.Degenerate;
+ return false;
+ }
+
+ if (!planeNormal.TryNormalize(out var normal))
+ {
+ failure = PlanarPolygonTriangulationFailure.Degenerate;
+ return false;
+ }
+
+ var projected = ProjectToStablePlane(polygonPoints, normal);
+ if (!ValidatePolygon(projected))
+ {
+ failure = PlanarPolygonTriangulationFailure.Degenerate;
+ return false;
+ }
+
+ if (HasSelfIntersection(projected))
+ {
+ failure = PlanarPolygonTriangulationFailure.NonSimple;
+ return false;
+ }
+
+ var winding = SignedArea(projected);
+ if (double.Abs(winding) <= Epsilon)
+ {
+ failure = PlanarPolygonTriangulationFailure.Degenerate;
+ return false;
+ }
+
+ var working = Enumerable.Range(0, polygonPoints.Count).ToList();
+ var result = new List<int>((polygonPoints.Count - 2) * 3);
+ var isCounterClockwise = winding > 0d;
+
+ while (working.Count > 3)
+ {
+ var earFound = false;
+ for (var i = 0; i < working.Count; i++)
+ {
+ var prevIndex = working[(i + working.Count - 1) % working.Count];
+ var currentIndex = working[i];
+ var nextIndex = working[(i + 1) % working.Count];
+
+ if (!IsConvex(projected[prevIndex], projected[currentIndex], projected[nextIndex], isCounterClockwise))
+ {
+ continue;
+ }
+
+ var containsVertex = false;
+ for (var j = 0; j < working.Count; j++)
+ {
+ var candidate = working[j];
+ if (candidate == prevIndex || candidate == currentIndex || candidate == nextIndex)
+ {
+ continue;
+ }
+
+ if (PointInTriangle(projected[candidate], projected[prevIndex], projected[currentIndex], projected[nextIndex]))
+ {
+ containsVertex = true;
+ break;
+ }
+ }
+
+ if (containsVertex)
+ {
+ continue;
+ }
+
+ result.Add(prevIndex);
+ result.Add(currentIndex);
+ result.Add(nextIndex);
+ working.RemoveAt(i);
+ earFound = true;
+ break;
+ }
+
+ if (!earFound)
+ {
+ failure = PlanarPolygonTriangulationFailure.TriangulationFailed;
+ return false;
+ }
+ }
+
+ result.Add(working[0]);
+ result.Add(working[1]);
+ result.Add(working[2]);
+
+ var expectedNormal = normal;
+ if (result.Count >= 3)
+ {
+ var firstNormal = (polygonPoints[result[1]] - polygonPoints[result[0]])
+ .Cross(polygonPoints[result[2]] - polygonPoints[result[0]]);
+ if (firstNormal.Dot(expectedNormal) < 0d)
+ {
+ for (var i = 0; i < result.Count; i += 3)
+ {
+ (result[i + 1], result[i + 2]) = (result[i + 2], result[i + 1]);
+ }
+ }
+ }
+
+ indices = result;
+ return true;
+ }
+
+ private static List<Point2> ProjectToStablePlane(IReadOnlyList<Point3D> polygonPoints, Vector3D normal)
+ {
+ var referenceAxis = double.Abs(normal.Z) < 0.9d
+ ? new Vector3D(0d, 0d, 1d)
+ : new Vector3D(1d, 0d, 0d);
+
+ var uAxis = referenceAxis.Cross(normal);
+ if (!uAxis.TryNormalize(out uAxis))
+ {
+ referenceAxis = new Vector3D(0d, 1d, 0d);
+ uAxis = referenceAxis.Cross(normal);
+ uAxis.TryNormalize(out uAxis);
+ }
+
+ var vAxis = normal.Cross(uAxis);
+ vAxis.TryNormalize(out vAxis);
+ var origin = polygonPoints[0];
+
+ return polygonPoints
+ .Select(point =>
+ {
+ var offset = point - origin;
+ return new Point2(offset.Dot(uAxis), offset.Dot(vAxis));
+ })
+ .ToList();
+ }
+
+ private static bool ValidatePolygon(IReadOnlyList<Point2> points)
+ {
+ for (var i = 0; i < points.Count; i++)
+ {
+ var next = points[(i + 1) % points.Count];
+ if (DistanceSquared(points[i], next) <= Epsilon * Epsilon)
+ {
+ return false;
+ }
+ }
+
+ var uniqueCount = points.Distinct().Count();
+ return uniqueCount >= 3;
+ }
+
+ private static bool HasSelfIntersection(IReadOnlyList<Point2> points)
+ {
+ for (var i = 0; i < points.Count; i++)
+ {
+ var a0 = points[i];
+ var a1 = points[(i + 1) % points.Count];
+ for (var j = i + 1; j < points.Count; j++)
+ {
+ var b0 = points[j];
+ var b1 = points[(j + 1) % points.Count];
+ if (i == j || (i + 1) % points.Count == j || i == (j + 1) % points.Count)
+ {
+ continue;
+ }
+
+ if (SegmentsIntersect(a0, a1, b0, b1))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private static bool SegmentsIntersect(Point2 a0, Point2 a1, Point2 b0, Point2 b1)
+ {
+ var o1 = Orientation(a0, a1, b0);
+ var o2 = Orientation(a0, a1, b1);
+ var o3 = Orientation(b0, b1, a0);
+ var o4 = Orientation(b0, b1, a1);
+
+ if ((o1 * o2 < -Epsilon) && (o3 * o4 < -Epsilon))
+ {
+ return true;
+ }
+
+ if (double.Abs(o1) <= Epsilon && OnSegment(a0, b0, a1)) return true;
+ if (double.Abs(o2) <= Epsilon && OnSegment(a0, b1, a1)) return true;
+ if (double.Abs(o3) <= Epsilon && OnSegment(b0, a0, b1)) return true;
+ if (double.Abs(o4) <= Epsilon && OnSegment(b0, a1, b1)) return true;
+ return false;
+ }
+
+ private static bool IsConvex(Point2 a, Point2 b, Point2 c, bool isCounterClockwise)
+ {
+ var cross = Orientation(a, b, c);
+ return isCounterClockwise ? cross > Epsilon : cross < -Epsilon;
+ }
+
+ private static bool PointInTriangle(Point2 p, Point2 a, Point2 b, Point2 c)
+ {
+ var o1 = Orientation(a, b, p);
+ var o2 = Orientation(b, c, p);
+ var o3 = Orientation(c, a, p);
+
+ var hasNeg = o1 < -Epsilon || o2 < -Epsilon || o3 < -Epsilon;
+ var hasPos = o1 > Epsilon || o2 > Epsilon || o3 > Epsilon;
+ return !(hasNeg && hasPos);
+ }
+
+ private static double SignedArea(IReadOnlyList<Point2> points)
+ {
+ var area = 0d;
+ for (var i = 0; i < points.Count; i++)
+ {
+ var current = points[i];
+ var next = points[(i + 1) % points.Count];
+ area += (current.X * next.Y) - (next.X * current.Y);
+ }
+
+ return area * 0.5d;
+ }
+
+ private static double Orientation(Point2 a, Point2 b, Point2 c)
+ => ((b.X - a.X) * (c.Y - a.Y)) - ((b.Y - a.Y) * (c.X - a.X));
+
+ private static bool OnSegment(Point2 a, Point2 p, Point2 b)
+ => p.X >= double.Min(a.X, b.X) - Epsilon
+ && p.X <= double.Max(a.X, b.X) + Epsilon
+ && p.Y >= double.Min(a.Y, b.Y) - Epsilon
+ && p.Y <= double.Max(a.Y, b.Y) + Epsilon;
+
+ private static double DistanceSquared(Point2 a, Point2 b)
+ {
+ var dx = a.X - b.X;
+ var dy = a.Y - b.Y;
+ return (dx * dx) + (dy * dy);
+ }
+
+ private readonly record struct Point2(double X, double Y);
+}
diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.json
index f279c1e7..20d6ea20 100644
--- a/testdata/step242/manifests/nist.v0.report.json
+++ b/testdata/step242/manifests/nist.v0.report.json
@@ -56,7 +56,7 @@
"firstDiagnostic": {
"code": "NotImplemented",
"source": "",
- "messagePrefix": "Face 61 planar loop triangulation requires a convex polygon."
+ "messagePrefix": "Face 72 planar tessellation supports only all-line loops or a single circle loop."
},
"diagnosticCount": 1,
"exceptionEscaped": false,
diff --git a/testdata/step242/tessellation-robustness/planar-degenerate-loop.step b/testdata/step242/tessellation-robustness/planar-degenerate-loop.step
new file mode 100644
index 00000000..0967e8a7
--- /dev/null
+++ b/testdata/step242/tessellation-robustness/planar-degenerate-loop.step
@@ -0,0 +1,37 @@
+ISO-10303-21;
+HEADER;
+ENDSEC;
+DATA;
+#1=MANIFOLD_SOLID_BREP('solid',#2);
+#2=CLOSED_SHELL($,(#3));
+#3=ADVANCED_FACE((#4),#6,.T.);
+#4=FACE_OUTER_BOUND($,#7,.T.);
+#6=PLANE($,#9);
+#7=EDGE_LOOP($,(#10,#11,#12));
+#9=AXIS2_PLACEMENT_3D($,#90,#91,#92);
+#10=ORIENTED_EDGE($,$,$,#20,.T.);
+#11=ORIENTED_EDGE($,$,$,#21,.T.);
+#12=ORIENTED_EDGE($,$,$,#22,.T.);
+#20=EDGE_CURVE($,#30,#31,#40,.T.);
+#21=EDGE_CURVE($,#31,#32,#41,.T.);
+#22=EDGE_CURVE($,#32,#30,#42,.T.);
+#30=VERTEX_POINT($,#50);
+#31=VERTEX_POINT($,#51);
+#32=VERTEX_POINT($,#52);
+#40=LINE($,#50,#80);
+#41=LINE($,#51,#81);
+#42=LINE($,#52,#82);
+#50=CARTESIAN_POINT($,(0,0,0));
+#51=CARTESIAN_POINT($,(1,0,0));
+#52=CARTESIAN_POINT($,(2,0,0));
+#80=VECTOR($,#100,1.0);
+#81=VECTOR($,#101,1.0);
+#82=VECTOR($,#102,1.0);
+#90=CARTESIAN_POINT($,(0,0,0));
+#91=DIRECTION($,(0,0,1));
+#92=DIRECTION($,(1,0,0));
+#100=DIRECTION($,(1,0,0));
+#101=DIRECTION($,(1,0,0));
+#102=DIRECTION($,(-1,0,0));
+ENDSEC;
+END-ISO-10303-21;
diff --git a/testdata/step242/tessellation-robustness/planar-nonconvex-single-loop.step b/testdata/step242/tessellation-robustness/planar-nonconvex-single-loop.step
new file mode 100644
index 00000000..77fe863c
--- /dev/null
+++ b/testdata/step242/tessellation-robustness/planar-nonconvex-single-loop.step
@@ -0,0 +1,72 @@
+ISO-10303-21;
+HEADER;
+ENDSEC;
+DATA;
+#1=MANIFOLD_SOLID_BREP('solid',#2);
+#2=CLOSED_SHELL($,(#3));
+#3=ADVANCED_FACE((#4),#6,.T.);
+#4=FACE_OUTER_BOUND($,#7,.T.);
+#6=PLANE($,#9);
+#7=EDGE_LOOP($,(#10,#11,#12,#13,#14,#15,#16,#17));
+#9=AXIS2_PLACEMENT_3D($,#90,#91,#92);
+#10=ORIENTED_EDGE($,$,$,#20,.T.);
+#11=ORIENTED_EDGE($,$,$,#21,.T.);
+#12=ORIENTED_EDGE($,$,$,#22,.T.);
+#13=ORIENTED_EDGE($,$,$,#23,.T.);
+#14=ORIENTED_EDGE($,$,$,#24,.T.);
+#15=ORIENTED_EDGE($,$,$,#25,.T.);
+#16=ORIENTED_EDGE($,$,$,#26,.T.);
+#17=ORIENTED_EDGE($,$,$,#27,.T.);
+#20=EDGE_CURVE($,#30,#31,#40,.T.);
+#21=EDGE_CURVE($,#31,#32,#41,.T.);
+#22=EDGE_CURVE($,#32,#33,#42,.T.);
+#23=EDGE_CURVE($,#33,#34,#43,.T.);
+#24=EDGE_CURVE($,#34,#35,#44,.T.);
+#25=EDGE_CURVE($,#35,#36,#45,.T.);
+#26=EDGE_CURVE($,#36,#37,#46,.T.);
+#27=EDGE_CURVE($,#37,#30,#47,.T.);
+#30=VERTEX_POINT($,#50);
+#31=VERTEX_POINT($,#51);
+#32=VERTEX_POINT($,#52);
+#33=VERTEX_POINT($,#53);
+#34=VERTEX_POINT($,#54);
+#35=VERTEX_POINT($,#55);
+#36=VERTEX_POINT($,#56);
+#37=VERTEX_POINT($,#57);
+#40=LINE($,#50,#80);
+#41=LINE($,#51,#81);
+#42=LINE($,#52,#82);
+#43=LINE($,#53,#83);
+#44=LINE($,#54,#84);
+#45=LINE($,#55,#85);
+#46=LINE($,#56,#86);
+#47=LINE($,#57,#87);
+#50=CARTESIAN_POINT($,(0,0,0));
+#51=CARTESIAN_POINT($,(6,0,0));
+#52=CARTESIAN_POINT($,(6,2,0));
+#53=CARTESIAN_POINT($,(2,2,0));
+#54=CARTESIAN_POINT($,(2,4,0));
+#55=CARTESIAN_POINT($,(6,4,0));
+#56=CARTESIAN_POINT($,(6,6,0));
+#57=CARTESIAN_POINT($,(0,6,0));
+#80=VECTOR($,#100,1.0);
+#81=VECTOR($,#101,1.0);
+#82=VECTOR($,#102,1.0);
+#83=VECTOR($,#103,1.0);
+#84=VECTOR($,#104,1.0);
+#85=VECTOR($,#105,1.0);
+#86=VECTOR($,#106,1.0);
+#87=VECTOR($,#107,1.0);
+#90=CARTESIAN_POINT($,(0,0,0));
+#91=DIRECTION($,(0,0,1));
+#92=DIRECTION($,(1,0,0));
+#100=DIRECTION($,(1,0,0));
+#101=DIRECTION($,(0,1,0));
+#102=DIRECTION($,(-1,0,0));
+#103=DIRECTION($,(0,1,0));
+#104=DIRECTION($,(1,0,0));
+#105=DIRECTION($,(0,1,0));
+#106=DIRECTION($,(-1,0,0));
+#107=DIRECTION($,(0,-1,0));
+ENDSEC;
+END-ISO-10303-21;