Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Implement trim-aware BSpline surface tessellation

Yuechen Li1b0839d7bfac
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs
index 4552f890..1074ceb4 100644
--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/BrepDisplayTessellatorTests.cs
@@ -4,6 +4,7 @@ using Aetheris.Kernel.Core.Brep.Features;
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Topology;
@@ -177,6 +178,101 @@ public sealed class BrepDisplayTessellatorTests
Assert.NotEmpty(tessellation.Value.FacePatches);
}
+ [Fact]
+ public void Tessellate_TrimmedBsplineSurface_RespectsOuterLoopBounds()
+ {
+ var body = CreateTrimmedBsplineSurfaceBody(
+ outerBounds: (0.2d, 0.8d, 0.1d, 0.9d),
+ holeBounds: null);
+ var options = DisplayTessellationOptions.Create(double.Pi / 8d, 0.1d, minimumSegments: 12, maximumSegments: 12).Value;
+
+ var result = BrepDisplayTessellator.Tessellate(body, options);
+
+ Assert.True(result.IsSuccess);
+ Assert.Empty(result.Diagnostics);
+
+ var patch = Assert.Single(result.Value.FacePatches);
+ Assert.NotEmpty(patch.TriangleIndices);
+ Assert.All(GetTriangleCentroids(patch), centroid =>
+ {
+ Assert.InRange(centroid.X, 0.2d - 1e-6d, 0.8d + 1e-6d);
+ Assert.InRange(centroid.Y, 0.1d - 1e-6d, 0.9d + 1e-6d);
+ });
+ }
+
+ [Fact]
+ public void Tessellate_TrimmedBsplineSurfaceWithHole_PreservesHole()
+ {
+ var body = CreateTrimmedBsplineSurfaceBody(
+ outerBounds: (0.1d, 0.9d, 0.1d, 0.9d),
+ holeBounds: (0.35d, 0.65d, 0.3d, 0.7d));
+ var options = DisplayTessellationOptions.Create(double.Pi / 8d, 0.1d, minimumSegments: 12, maximumSegments: 12).Value;
+
+ var result = BrepDisplayTessellator.Tessellate(body, options);
+
+ Assert.True(result.IsSuccess);
+ Assert.Empty(result.Diagnostics);
+
+ var patch = Assert.Single(result.Value.FacePatches);
+ Assert.NotEmpty(patch.TriangleIndices);
+ Assert.All(GetTriangleCentroids(patch), centroid =>
+ Assert.False(IsInsideRectangle(centroid, 0.35d, 0.65d, 0.3d, 0.7d)));
+ }
+
+ [Fact]
+ public void Tessellate_TrimmedBsplineSurface_IsDeterministic()
+ {
+ var body = CreateTrimmedBsplineSurfaceBody(
+ outerBounds: (0.1d, 0.9d, 0.1d, 0.9d),
+ holeBounds: (0.35d, 0.65d, 0.3d, 0.7d));
+ var options = DisplayTessellationOptions.Create(double.Pi / 8d, 0.1d, minimumSegments: 12, maximumSegments: 12).Value;
+
+ var first = BrepDisplayTessellator.Tessellate(body, options);
+ var second = BrepDisplayTessellator.Tessellate(body, options);
+
+ Assert.True(first.IsSuccess);
+ Assert.True(second.IsSuccess);
+
+ var firstPatch = Assert.Single(first.Value.FacePatches);
+ var secondPatch = Assert.Single(second.Value.FacePatches);
+ Assert.Equal(firstPatch.Positions, secondPatch.Positions);
+ Assert.Equal(firstPatch.Normals, secondPatch.Normals);
+ Assert.Equal(firstPatch.TriangleIndices, secondPatch.TriangleIndices);
+ }
+
+ [Fact]
+ public void Tessellate_TrimmedBsplineSurface_WhenUvProjectionFails_EmitsWarningAndSkipsFace()
+ {
+ var body = CreateTrimmedBsplineSurfaceBody(
+ outerBounds: (0.1d, 0.9d, 0.1d, 0.9d),
+ holeBounds: null,
+ offsetOuterTopEdgeZ: 0.25d);
+
+ var result = BrepDisplayTessellator.Tessellate(body);
+
+ Assert.True(result.IsSuccess);
+ var diagnostic = Assert.Single(result.Diagnostics);
+ Assert.Equal(KernelDiagnosticCode.ValidationFailed, diagnostic.Code);
+ Assert.Equal("Viewer.Tessellation.TrimEvaluationFailed", diagnostic.Source);
+
+ var patch = Assert.Single(result.Value.FacePatches);
+ Assert.Empty(patch.Positions);
+ Assert.Empty(patch.TriangleIndices);
+ }
+
+ [Fact]
+ public void Tessellate_PlanarFacesRemainUnchanged()
+ {
+ var box = BrepPrimitives.CreateBox(2d, 3d, 4d);
+
+ var result = BrepDisplayTessellator.Tessellate(box.Value);
+
+ Assert.True(result.IsSuccess);
+ Assert.Equal(6, result.Value.FacePatches.Count);
+ Assert.DoesNotContain(result.Diagnostics, diagnostic => diagnostic.Source == "Viewer.Tessellation.TrimEvaluationFailed");
+ Assert.All(result.Value.FacePatches, patch => Assert.NotEmpty(patch.TriangleIndices));
+ }
+
private static void AssertPointEqualWithinTolerance(Point3D expected, Point3D actual, int precision)
{
Assert.Equal(expected.X, actual.X, precision);
@@ -204,4 +300,148 @@ public sealed class BrepDisplayTessellatorTests
return new BrepBody(builder.Model, geometry, bindings);
}
+
+ private static IEnumerable<Point3D> GetTriangleCentroids(DisplayFaceMeshPatch patch)
+ {
+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)
+ {
+ var a = patch.Positions[patch.TriangleIndices[i]];
+ var b = patch.Positions[patch.TriangleIndices[i + 1]];
+ var c = patch.Positions[patch.TriangleIndices[i + 2]];
+ yield return new Point3D(
+ (a.X + b.X + c.X) / 3d,
+ (a.Y + b.Y + c.Y) / 3d,
+ (a.Z + b.Z + c.Z) / 3d);
+ }
+ }
+
+ private static bool IsInsideRectangle(Point3D point, double minX, double maxX, double minY, double maxY)
+ => point.X > minX - 1e-6d
+ && point.X < maxX + 1e-6d
+ && point.Y > minY - 1e-6d
+ && point.Y < maxY + 1e-6d;
+
+ private static BrepBody CreateTrimmedBsplineSurfaceBody(
+ (double UMin, double UMax, double VMin, double VMax) outerBounds,
+ (double UMin, double UMax, double VMin, double VMax)? holeBounds,
+ double offsetOuterTopEdgeZ = 0d)
+ {
+ var builder = new TopologyBuilder();
+ var geometry = new BrepGeometryStore();
+ var bindings = new BrepBindingModel();
+ var vertexPoints = new Dictionary<VertexId, Point3D>();
+
+ var faceLoops = new List<LoopId>();
+ var curveId = 1;
+
+ var outerVertices = CreateRectangleVertices(outerBounds, offsetTopEdgeZ: offsetOuterTopEdgeZ);
+ faceLoops.Add(AddLoop(builder, geometry, bindings, vertexPoints, outerVertices, ref curveId));
+
+ if (holeBounds is { } hole)
+ {
+ var innerVertices = CreateRectangleVertices(hole, offsetTopEdgeZ: 0d);
+ faceLoops.Add(AddLoop(builder, geometry, bindings, vertexPoints, innerVertices, ref curveId));
+ }
+
+ var face = builder.AddFace(faceLoops);
+ var shell = builder.AddShell([face]);
+ builder.AddBody([shell]);
+
+ geometry.AddSurface(
+ new SurfaceGeometryId(1),
+ SurfaceGeometry.FromBSplineSurfaceWithKnots(CreateBilinearBsplineSurface()));
+ bindings.AddFaceBinding(new FaceGeometryBinding(face, new SurfaceGeometryId(1)));
+
+ return new BrepBody(builder.Model, geometry, bindings, vertexPoints);
+ }
+
+ private static LoopId AddLoop(
+ TopologyBuilder builder,
+ BrepGeometryStore geometry,
+ BrepBindingModel bindings,
+ Dictionary<VertexId, Point3D> vertexPoints,
+ IReadOnlyList<Point3D> vertices,
+ ref int curveId)
+ {
+ var vertexIds = vertices
+ .Select(point =>
+ {
+ var vertexId = builder.AddVertex();
+ vertexPoints[vertexId] = point;
+ return vertexId;
+ })
+ .ToArray();
+
+ var loopId = builder.AllocateLoopId();
+ var coedgeIds = new List<CoedgeId>(vertices.Count);
+ var edgeIds = new List<EdgeId>(vertices.Count);
+
+ for (var i = 0; i < vertices.Count; i++)
+ {
+ var start = vertexIds[i];
+ var end = vertexIds[(i + 1) % vertices.Count];
+ var edgeId = builder.AddEdge(start, end);
+ edgeIds.Add(edgeId);
+
+ var line = CreateLine(vertices[i], vertices[(i + 1) % vertices.Count], out var length);
+ var geometryId = new CurveGeometryId(curveId++);
+ geometry.AddCurve(geometryId, CurveGeometry.FromLine(line));
+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edgeId, geometryId, new ParameterInterval(0d, length)));
+ }
+
+ for (var i = 0; i < edgeIds.Count; i++)
+ {
+ coedgeIds.Add(builder.AllocateCoedgeId());
+ }
+
+ for (var i = 0; i < edgeIds.Count; i++)
+ {
+ var next = coedgeIds[(i + 1) % coedgeIds.Count];
+ var prev = coedgeIds[(i - 1 + coedgeIds.Count) % coedgeIds.Count];
+ builder.AddCoedge(new Coedge(coedgeIds[i], edgeIds[i], loopId, next, prev, IsReversed: false));
+ }
+
+ builder.AddLoop(new Loop(loopId, coedgeIds));
+ return loopId;
+ }
+
+ private static Line3Curve CreateLine(Point3D start, Point3D end, out double length)
+ {
+ var delta = end - start;
+ length = delta.Length;
+ return new Line3Curve(start, Direction3D.Create(delta));
+ }
+
+ private static Point3D[] CreateRectangleVertices(
+ (double UMin, double UMax, double VMin, double VMax) bounds,
+ double offsetTopEdgeZ)
+ {
+ var lowerLeft = EvaluateBilinearPoint(bounds.UMin, bounds.VMin, 0d);
+ var lowerRight = EvaluateBilinearPoint(bounds.UMax, bounds.VMin, 0d);
+ var upperRight = EvaluateBilinearPoint(bounds.UMax, bounds.VMax, offsetTopEdgeZ);
+ var upperLeft = EvaluateBilinearPoint(bounds.UMin, bounds.VMax, offsetTopEdgeZ);
+ return [lowerLeft, lowerRight, upperRight, upperLeft];
+ }
+
+ private static Point3D EvaluateBilinearPoint(double u, double v, double zOffset)
+ => new(u, v, (u * v) + zOffset);
+
+ private static BSplineSurfaceWithKnots CreateBilinearBsplineSurface()
+ => new(
+ degreeU: 1,
+ degreeV: 1,
+ controlPoints:
+ [
+ [new Point3D(0d, 0d, 0d), new Point3D(0d, 1d, 0d)],
+ [new Point3D(1d, 0d, 0d), new Point3D(1d, 1d, 1d)],
+ ],
+ surfaceForm: "UNSPECIFIED",
+ uClosed: false,
+ vClosed: false,
+ selfIntersect: false,
+ knotMultiplicitiesU: [2, 2],
+ knotMultiplicitiesV: [2, 2],
+ knotValuesU: [0d, 1d],
+ knotValuesV: [0d, 1d],
+ knotSpec: "UNSPECIFIED");
}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index f142ab86..6ad5485f 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -32,6 +32,7 @@ public static class BrepDisplayTessellator
private const string SphereTrimTwoCoedgeBsplineBiArcSurrogateSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeBsplineBiArcSurrogate";
private const string SphereTrimTwoCoedgeUnsupportedSource = "Viewer.Tessellation.SphereTrim.TwoCoedgeUnsupported";
private const string PlanarMultiLoopTriangulationSkippedSource = "Viewer.Tessellation.PlanarMultiLoopTriangulationSkipped";
+ private const string TrimEvaluationFailedSource = "Viewer.Tessellation.TrimEvaluationFailed";
public static KernelResult<DisplayTessellationResult> Tessellate(BrepBody body, DisplayTessellationOptions? options = null)
{
@@ -421,123 +422,46 @@ public static class BrepDisplayTessellator
private static KernelResult<DisplayFaceMeshPatch> TessellateBSplineSurfaceFace(BrepBody body, FaceId faceId, BSplineSurfaceWithKnots surface, DisplayTessellationOptions options)
{
var loopIds = body.GetLoopIds(faceId);
- if (loopIds.Count > 1)
+ if (loopIds.Count == 0)
{
- return KernelResult<DisplayFaceMeshPatch>.Failure([
- CreateNotImplemented($"Face {faceId.Value} BSpline surface tessellation currently supports zero or one trim loop. Observed {loopIds.Count} loops.", BSplineSurfaceTrimUnsupportedSource)]);
+ return KernelResult<DisplayFaceMeshPatch>.Success(CreateBoundedGridPatch(
+ faceId,
+ options.MinimumSegments,
+ options.MinimumSegments,
+ (u, v) => surface.Evaluate(u, v),
+ (u, v) => EvaluateBSplineNormal(surface, u, v),
+ surface.DomainStartU,
+ surface.DomainEndU,
+ surface.DomainStartV,
+ surface.DomainEndV));
}
- var uStart = surface.DomainStartU;
- var uEnd = surface.DomainEndU;
- var vStart = surface.DomainStartV;
- var vEnd = surface.DomainEndV;
-
- if (loopIds.Count == 1)
+ var uvLoopsResult = TryBuildTrimmedSurfaceUvLoops(
+ body,
+ faceId,
+ loopIds,
+ point => TryProjectPointToBSplineUv(surface, point),
+ options);
+ if (!uvLoopsResult.IsSuccess)
{
- var trimPatch = TryResolveBSplineTrimPatch(body, faceId, surface, loopIds[0]);
- if (!trimPatch.IsSuccess)
- {
- return KernelResult<DisplayFaceMeshPatch>.Failure(trimPatch.Diagnostics);
- }
-
- uStart = trimPatch.Value.UStart;
- uEnd = trimPatch.Value.UEnd;
- vStart = trimPatch.Value.VStart;
- vEnd = trimPatch.Value.VEnd;
+ return KernelResult<DisplayFaceMeshPatch>.Success(
+ CreateEmptyPlanarPatch(faceId),
+ [CreateValidationWarning(
+ $"Face {faceId.Value} BSpline trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry.",
+ TrimEvaluationFailedSource)]);
}
- var uSpan = uEnd - uStart;
- var vSpan = vEnd - vStart;
- var uSegments = System.Math.Max(options.MinimumSegments, System.Math.Clamp((int)double.Ceiling(double.Abs(uSpan) / options.AngularToleranceRadians), options.MinimumSegments, options.MaximumSegments));
- var vSegments = System.Math.Max(1, System.Math.Clamp((int)double.Ceiling(double.Abs(vSpan) / options.ChordTolerance), 1, options.MaximumSegments));
-
- return KernelResult<DisplayFaceMeshPatch>.Success(CreateBoundedGridPatch(
+ return TrimmedSurfaceTessellator.Tessellate(
faceId,
- uSegments,
- vSegments,
+ uvLoopsResult.Value,
(u, v) => surface.Evaluate(u, v),
(u, v) => EvaluateBSplineNormal(surface, u, v),
- uStart,
- uEnd,
- vStart,
- vEnd));
- }
-
- private static KernelResult<(double UStart, double UEnd, double VStart, double VEnd)> TryResolveBSplineTrimPatch(
- BrepBody body,
- FaceId faceId,
- BSplineSurfaceWithKnots surface,
- LoopId loopId)
- {
- const double minSpan = 1e-8d;
-
- var coedges = body.GetCoedgeIds(loopId).Select(id => body.Topology.GetCoedge(id)).ToArray();
- if (coedges.Length < 3)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} BSpline trim loop must contain at least three coedges. Observed {coedges.Length}.", BSplineSurfaceTrimUnsupportedSource)]);
- }
-
- var vertexPointsResult = BuildLoopVertexPointLookup(body, coedges, faceId);
- if (!vertexPointsResult.IsSuccess)
- {
- return KernelResult<(double, double, double, double)>.Failure(vertexPointsResult.Diagnostics);
- }
-
- var samples = new List<Point3D>();
- foreach (var coedge in coedges)
- {
- var endpoints = GetEdgeEndpoints(body, coedge.EdgeId, coedge.IsReversed, vertexPointsResult.Value);
- if (!endpoints.IsSuccess)
- {
- return KernelResult<(double, double, double, double)>.Failure(endpoints.Diagnostics);
- }
-
- samples.Add(endpoints.Value.Start);
- samples.Add(endpoints.Value.End);
-
- var edgePolyline = TessellateEdge(body, coedge.EdgeId, DisplayTessellationOptions.Default);
- if (!edgePolyline.IsSuccess)
- {
- continue;
- }
-
- var edgePoints = coedge.IsReversed
- ? edgePolyline.Value.Points.Reverse().ToArray()
- : edgePolyline.Value.Points;
- samples.AddRange(edgePoints);
- }
-
- if (samples.Count == 0)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} BSpline trim tessellation could not derive loop samples.", BSplineSurfaceTrimUnsupportedSource)]);
- }
-
- var uvSamples = samples
- .Select(point => TryProjectPointToBSplineUv(surface, point))
- .Where(result => result.HasValue)
- .Select(result => result!.Value)
- .ToArray();
-
- if (uvSamples.Length == 0)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} BSpline trim tessellation could not project loop samples into the BSpline parametric domain.", BSplineSurfaceTrimUnsupportedSource)]);
- }
-
- var uStart = System.Math.Max(surface.DomainStartU, uvSamples.Min(s => s.U));
- var uEnd = System.Math.Min(surface.DomainEndU, uvSamples.Max(s => s.U));
- var vStart = System.Math.Max(surface.DomainStartV, uvSamples.Min(s => s.V));
- var vEnd = System.Math.Min(surface.DomainEndV, uvSamples.Max(s => s.V));
-
- if ((uEnd - uStart) <= minSpan || (vEnd - vStart) <= minSpan)
- {
- return KernelResult<(double, double, double, double)>.Failure([
- CreateNotImplemented($"Face {faceId.Value} BSpline trim tessellation derived a degenerate UV span.", BSplineSurfaceTrimUnsupportedSource)]);
- }
-
- return KernelResult<(double, double, double, double)>.Success((uStart, uEnd, vStart, vEnd));
+ options,
+ surface.DomainStartU,
+ surface.DomainEndU,
+ surface.DomainStartV,
+ surface.DomainEndV,
+ CreateValidationWarning);
}
private static (double U, double V)? TryProjectPointToBSplineUv(BSplineSurfaceWithKnots surface, Point3D point)
@@ -547,7 +471,7 @@ public static class BrepDisplayTessellator
var vStart = surface.DomainStartV;
var vEnd = surface.DomainEndV;
- const int coarseSegments = 6;
+ const int coarseSegments = 10;
var bestU = uStart;
var bestV = vStart;
var bestDistanceSquared = double.PositiveInfinity;
@@ -575,7 +499,7 @@ public static class BrepDisplayTessellator
var uStep = (uEnd - uStart) / coarseSegments;
var vStep = (vEnd - vStart) / coarseSegments;
- for (var iteration = 0; iteration < 3; iteration++)
+ for (var iteration = 0; iteration < 6; iteration++)
{
var nextUStep = uStep * 0.5d;
var nextVStep = vStep * 0.5d;
@@ -608,9 +532,168 @@ public static class BrepDisplayTessellator
vStep = nextVStep;
}
+ var bestSample = surface.Evaluate(bestU, bestV);
+ var residual = bestSample - point;
+ var residualDistance = System.Math.Sqrt(residual.Dot(residual));
+ var tolerance = ComputeBSplineProjectionTolerance(surface);
+ if (residualDistance > tolerance)
+ {
+ return null;
+ }
+
return (bestU, bestV);
}
+ private static KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>> TryBuildTrimmedSurfaceUvLoops(
+ BrepBody body,
+ FaceId faceId,
+ IReadOnlyList<LoopId> loopIds,
+ Func<Point3D, (double U, double V)?> projectPointToUv,
+ DisplayTessellationOptions options)
+ {
+ var uvLoops = new List<IReadOnlyList<(double U, double V)>>(loopIds.Count);
+ foreach (var loopId in loopIds.OrderBy(id => id.Value))
+ {
+ var uvLoop = TryBuildTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options);
+ if (!uvLoop.IsSuccess)
+ {
+ return KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Failure(uvLoop.Diagnostics);
+ }
+
+ uvLoops.Add(uvLoop.Value);
+ }
+
+ return KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Success(uvLoops);
+ }
+
+ private static KernelResult<IReadOnlyList<(double U, double V)>> TryBuildTrimmedSurfaceUvLoop(
+ BrepBody body,
+ FaceId faceId,
+ LoopId loopId,
+ Func<Point3D, (double U, double V)?> projectPointToUv,
+ DisplayTessellationOptions options)
+ {
+ var coedges = body.GetCoedgeIds(loopId).Select(id => body.Topology.GetCoedge(id)).ToArray();
+ if (coedges.Length < 3)
+ {
+ return KernelResult<IReadOnlyList<(double U, double V)>>.Failure([
+ CreateNotImplemented(
+ $"Face {faceId.Value} parametric trim loop must contain at least three coedges. Observed {coedges.Length}.",
+ BSplineSurfaceTrimUnsupportedSource)]);
+ }
+
+ var vertexPointsResult = BuildLoopVertexPointLookup(body, coedges, faceId);
+ if (!vertexPointsResult.IsSuccess)
+ {
+ return KernelResult<IReadOnlyList<(double U, double V)>>.Failure(vertexPointsResult.Diagnostics);
+ }
+
+ var uvPoints = new List<(double U, double V)>();
+ foreach (var coedge in coedges)
+ {
+ var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options);
+ if (!sampledCurve.IsSuccess)
+ {
+ return KernelResult<IReadOnlyList<(double U, double V)>>.Failure(sampledCurve.Diagnostics);
+ }
+
+ foreach (var point in sampledCurve.Value)
+ {
+ var uv = projectPointToUv(point);
+ if (!uv.HasValue)
+ {
+ return KernelResult<IReadOnlyList<(double U, double V)>>.Failure([
+ CreateNotImplemented(
+ $"Face {faceId.Value} parametric trim tessellation could not project loop samples into the parametric domain.",
+ BSplineSurfaceTrimUnsupportedSource)]);
+ }
+
+ AppendUniqueUvPoint(uvPoints, uv.Value);
+ }
+ }
+
+ if (uvPoints.Count > 1 && UvPointsAlmostEqual(uvPoints[0], uvPoints[^1]))
+ {
+ uvPoints.RemoveAt(uvPoints.Count - 1);
+ }
+
+ return KernelResult<IReadOnlyList<(double U, double V)>>.Success(uvPoints);
+ }
+
+ private static KernelResult<IReadOnlyList<Point3D>> TrySampleCoedgeForTrimEvaluation(
+ BrepBody body,
+ FaceId faceId,
+ Coedge coedge,
+ IReadOnlyDictionary<VertexId, Point3D> vertexPoints,
+ DisplayTessellationOptions options)
+ {
+ var endpoints = GetEdgeEndpoints(body, coedge.EdgeId, coedge.IsReversed, vertexPoints);
+ if (!endpoints.IsSuccess)
+ {
+ return KernelResult<IReadOnlyList<Point3D>>.Failure(endpoints.Diagnostics);
+ }
+
+ var polylineResult = TessellateEdge(body, coedge.EdgeId, options);
+ if (!polylineResult.IsSuccess)
+ {
+ return KernelResult<IReadOnlyList<Point3D>>.Failure(polylineResult.Diagnostics);
+ }
+
+ var sampled = polylineResult.Value.Points.ToArray();
+ if (sampled.Length < 2)
+ {
+ return KernelResult<IReadOnlyList<Point3D>>.Failure([
+ CreateNotImplemented($"Face {faceId.Value} trim edge {coedge.EdgeId.Value} did not produce enough samples.", BSplineSurfaceTrimUnsupportedSource)]);
+ }
+
+ var directDistance = DistanceSquared(sampled[0], endpoints.Value.Start) + DistanceSquared(sampled[^1], endpoints.Value.End);
+ var reversedDistance = DistanceSquared(sampled[0], endpoints.Value.End) + DistanceSquared(sampled[^1], endpoints.Value.Start);
+ if (reversedDistance < directDistance)
+ {
+ Array.Reverse(sampled);
+ }
+
+ sampled[0] = endpoints.Value.Start;
+ sampled[^1] = endpoints.Value.End;
+ return KernelResult<IReadOnlyList<Point3D>>.Success(sampled);
+ }
+
+ private static void AppendUniqueUvPoint(List<(double U, double V)> points, (double U, double V) point)
+ {
+ if (points.Count == 0 || !UvPointsAlmostEqual(points[^1], point))
+ {
+ points.Add(point);
+ }
+ }
+
+ private static bool UvPointsAlmostEqual((double U, double V) left, (double U, double V) right)
+ => System.Math.Abs(left.U - right.U) <= LoopEndpointTolerance
+ && System.Math.Abs(left.V - right.V) <= LoopEndpointTolerance;
+
+ private static double DistanceSquared(Point3D left, Point3D right)
+ {
+ var delta = left - right;
+ return delta.Dot(delta);
+ }
+
+ private static double ComputeBSplineProjectionTolerance(BSplineSurfaceWithKnots surface)
+ {
+ var points = surface.ControlPoints.SelectMany(row => row).ToArray();
+ if (points.Length == 0)
+ {
+ return 1e-4d;
+ }
+
+ var minX = points.Min(point => point.X);
+ var minY = points.Min(point => point.Y);
+ var minZ = points.Min(point => point.Z);
+ var maxX = points.Max(point => point.X);
+ var maxY = points.Max(point => point.Y);
+ var maxZ = points.Max(point => point.Z);
+ var diagonal = new Vector3D(maxX - minX, maxY - minY, maxZ - minZ).Length;
+ return System.Math.Max(1e-5d, diagonal * 1e-4d);
+ }
+
private static Vector3D EvaluateBSplineNormal(BSplineSurfaceWithKnots surface, double u, double v)
{
var du = System.Math.Max((surface.DomainEndU - surface.DomainStartU) * 1e-4d, 1e-6d);
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
new file mode 100644
index 00000000..3b4593f5
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
@@ -0,0 +1,257 @@
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep.Tessellation;
+
+internal static class TrimmedSurfaceTessellator
+{
+ private const double PointOnSegmentTolerance = 1e-9d;
+ private const double SignedAreaTolerance = 1e-10d;
+
+ public static KernelResult<DisplayFaceMeshPatch> Tessellate(
+ FaceId faceId,
+ IReadOnlyList<IReadOnlyList<(double U, double V)>> uvLoops,
+ Func<double, double, Point3D> evaluate,
+ Func<double, double, Vector3D> evaluateNormal,
+ DisplayTessellationOptions options,
+ double uDomainStart,
+ double uDomainEnd,
+ double vDomainStart,
+ double vDomainEnd,
+ Func<string, string, KernelDiagnostic> createWarning)
+ {
+ if (uvLoops.Count == 0)
+ {
+ return KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPatch(faceId));
+ }
+
+ var normalizedLoops = new List<List<(double U, double V)>>(uvLoops.Count);
+ foreach (var loop in uvLoops)
+ {
+ var normalized = NormalizeLoop(loop);
+ if (normalized.Count < 3)
+ {
+ return KernelResult<DisplayFaceMeshPatch>.Success(
+ CreateEmptyPatch(faceId),
+ [createWarning(
+ $"Face {faceId.Value} parametric trim loop evaluation produced fewer than three unique UV points; skipping face patch.",
+ "Viewer.Tessellation.TrimEvaluationFailed")]);
+ }
+
+ normalizedLoops.Add(normalized);
+ }
+
+ var outerLoopIndex = SelectOuterLoop(normalizedLoops);
+ var outerLoop = normalizedLoops[outerLoopIndex];
+ var innerLoops = normalizedLoops
+ .Where((_, index) => index != outerLoopIndex)
+ .Cast<IReadOnlyList<(double U, double V)>>()
+ .ToArray();
+
+ var (uStartRaw, uEndRaw, vStartRaw, vEndRaw) = ComputeBounds(outerLoop);
+ var uStart = System.Math.Max(uDomainStart, uStartRaw);
+ var uEnd = System.Math.Min(uDomainEnd, uEndRaw);
+ var vStart = System.Math.Max(vDomainStart, vStartRaw);
+ var vEnd = System.Math.Min(vDomainEnd, vEndRaw);
+
+ if ((uEnd - uStart) <= SignedAreaTolerance || (vEnd - vStart) <= SignedAreaTolerance)
+ {
+ return KernelResult<DisplayFaceMeshPatch>.Success(
+ CreateEmptyPatch(faceId),
+ [createWarning(
+ $"Face {faceId.Value} parametric trim evaluation derived a degenerate UV domain; skipping face patch.",
+ "Viewer.Tessellation.TrimEvaluationFailed")]);
+ }
+
+ var uSegments = ResolveSegmentCount(uEnd - uStart, options);
+ var vSegments = ResolveSegmentCount(vEnd - vStart, options);
+
+ var positions = new List<Point3D>((uSegments + 1) * (vSegments + 1));
+ var normals = new List<Vector3D>((uSegments + 1) * (vSegments + 1));
+ var uvGrid = new List<(double U, double V)>((uSegments + 1) * (vSegments + 1));
+ var indices = new List<int>(uSegments * vSegments * 6);
+
+ for (var iv = 0; iv <= vSegments; iv++)
+ {
+ var tv = (double)iv / vSegments;
+ var v = vStart + ((vEnd - vStart) * tv);
+ for (var iu = 0; iu <= uSegments; iu++)
+ {
+ var tu = (double)iu / uSegments;
+ var u = uStart + ((uEnd - uStart) * tu);
+ uvGrid.Add((u, v));
+ positions.Add(evaluate(u, v));
+ normals.Add(evaluateNormal(u, v));
+ }
+ }
+
+ var rowWidth = uSegments + 1;
+ for (var iv = 0; iv < vSegments; iv++)
+ {
+ for (var iu = 0; iu < uSegments; iu++)
+ {
+ var i0 = (iv * rowWidth) + iu;
+ var i1 = i0 + 1;
+ var i2 = i0 + rowWidth;
+ var i3 = i2 + 1;
+
+ TryAppendTriangle(i0, i2, i1);
+ TryAppendTriangle(i1, i2, i3);
+ }
+ }
+
+ return KernelResult<DisplayFaceMeshPatch>.Success(new DisplayFaceMeshPatch(faceId, positions, normals, indices));
+
+ void TryAppendTriangle(int ia, int ib, int ic)
+ {
+ var centroid = (
+ (uvGrid[ia].U + uvGrid[ib].U + uvGrid[ic].U) / 3d,
+ (uvGrid[ia].V + uvGrid[ib].V + uvGrid[ic].V) / 3d);
+ if (!IsInsideTrimRegion(centroid, outerLoop, innerLoops))
+ {
+ return;
+ }
+
+ indices.Add(ia);
+ indices.Add(ib);
+ indices.Add(ic);
+ }
+ }
+
+ private static bool IsInsideTrimRegion(
+ (double U, double V) point,
+ IReadOnlyList<(double U, double V)> outerLoop,
+ IReadOnlyList<IReadOnlyList<(double U, double V)>> innerLoops)
+ {
+ if (!ContainsPoint(outerLoop, point))
+ {
+ return false;
+ }
+
+ foreach (var hole in innerLoops)
+ {
+ if (ContainsPoint(hole, point))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static int SelectOuterLoop(IReadOnlyList<IReadOnlyList<(double U, double V)>> loops)
+ {
+ var bestIndex = 0;
+ var bestArea = double.NegativeInfinity;
+ for (var i = 0; i < loops.Count; i++)
+ {
+ var area = System.Math.Abs(ComputeSignedArea(loops[i]));
+ if (area > bestArea + SignedAreaTolerance
+ || (System.Math.Abs(area - bestArea) <= SignedAreaTolerance && i < bestIndex))
+ {
+ bestArea = area;
+ bestIndex = i;
+ }
+ }
+
+ return bestIndex;
+ }
+
+ private static (double UMin, double UMax, double VMin, double VMax) ComputeBounds(IReadOnlyList<(double U, double V)> loop)
+ => (
+ loop.Min(point => point.U),
+ loop.Max(point => point.U),
+ loop.Min(point => point.V),
+ loop.Max(point => point.V));
+
+ private static List<(double U, double V)> NormalizeLoop(IReadOnlyList<(double U, double V)> loop)
+ {
+ var normalized = new List<(double U, double V)>(loop.Count);
+ foreach (var point in loop)
+ {
+ if (normalized.Count == 0 || !AlmostEqual(normalized[^1], point))
+ {
+ normalized.Add(point);
+ }
+ }
+
+ if (normalized.Count > 1 && AlmostEqual(normalized[0], normalized[^1]))
+ {
+ normalized.RemoveAt(normalized.Count - 1);
+ }
+
+ return normalized;
+ }
+
+ private static int ResolveSegmentCount(double span, DisplayTessellationOptions options)
+ {
+ var ratio = span / System.Math.Max(1e-6d, options.ChordTolerance);
+ var segmentCount = (int)double.Ceiling(ratio);
+ segmentCount = System.Math.Max(options.MinimumSegments, segmentCount);
+ return System.Math.Clamp(segmentCount, options.MinimumSegments, options.MaximumSegments);
+ }
+
+ private static bool ContainsPoint(IReadOnlyList<(double U, double V)> polygon, (double U, double V) point)
+ {
+ var inside = false;
+ for (var i = 0; i < polygon.Count; i++)
+ {
+ var a = polygon[i];
+ var b = polygon[(i + 1) % polygon.Count];
+
+ if (IsPointOnSegment(point, a, b))
+ {
+ return true;
+ }
+
+ var crosses = ((a.V > point.V) != (b.V > point.V))
+ && (point.U < (((b.U - a.U) * (point.V - a.V)) / (b.V - a.V)) + a.U);
+ if (crosses)
+ {
+ inside = !inside;
+ }
+ }
+
+ return inside;
+ }
+
+ private static bool IsPointOnSegment((double U, double V) point, (double U, double V) a, (double U, double V) b)
+ {
+ var cross = ((point.U - a.U) * (b.V - a.V)) - ((point.V - a.V) * (b.U - a.U));
+ if (System.Math.Abs(cross) > PointOnSegmentTolerance)
+ {
+ return false;
+ }
+
+ var dot = ((point.U - a.U) * (b.U - a.U)) + ((point.V - a.V) * (b.V - a.V));
+ if (dot < -PointOnSegmentTolerance)
+ {
+ return false;
+ }
+
+ var lengthSquared = ((b.U - a.U) * (b.U - a.U)) + ((b.V - a.V) * (b.V - a.V));
+ return dot <= lengthSquared + PointOnSegmentTolerance;
+ }
+
+ private static double ComputeSignedArea(IReadOnlyList<(double U, double V)> polygon)
+ {
+ var area = 0d;
+ for (var i = 0; i < polygon.Count; i++)
+ {
+ var current = polygon[i];
+ var next = polygon[(i + 1) % polygon.Count];
+ area += (current.U * next.V) - (next.U * current.V);
+ }
+
+ return area * 0.5d;
+ }
+
+ private static bool AlmostEqual((double U, double V) left, (double U, double V) right)
+ => System.Math.Abs(left.U - right.U) <= PointOnSegmentTolerance
+ && System.Math.Abs(left.V - right.V) <= PointOnSegmentTolerance;
+
+ private static DisplayFaceMeshPatch CreateEmptyPatch(FaceId faceId)
+ => new(faceId, Array.Empty<Point3D>(), Array.Empty<Vector3D>(), Array.Empty<int>());
+}