Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
analytical recovery and other bug fixes by Claude.
Yuechen Lie84f16f31e88
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.csnew file mode 100644index 00000000..3aef778a--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.cs@@ -0,0 +1,127 @@+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;++/// <summary>+/// Every NIST PMI corpus model must import and display without dropping a single face. Each entry here was, at+/// some point, silently missing faces in the viewer (tolerance too tight for fillet edges, weights dropped from+/// rational surfaces, per-loop projection axes, reversed same_sense edges, torus bands, ...).+/// </summary>+public sealed class NistDisplayCorpusRegressionTests+{+ public static TheoryData<string> Files => new()+ {+ "CTC/nist_ctc_01_asme1_ap242-e1.stp",+ "CTC/nist_ctc_02_asme1_ap242-e2.stp",+ "CTC/nist_ctc_03_asme1_ap242-e2.stp",+ "CTC/nist_ctc_04_asme1_ap242-e1.stp",+ "CTC/nist_ctc_05_asme1_ap242-e1.stp",+ "FTC/nist_ftc_07_asme1_ap242-e2.stp",+ "FTC/nist_ftc_08_asme1_ap242-e2.stp",+ "FTC/nist_ftc_09_asme1_ap242-e1.stp",+ "FTC/nist_ftc_10_asme1_ap242-e2.stp",+ "FTC/nist_ftc_11_asme1_ap242-e2.stp",+ "STC/nist_stc_07_asme1_ap242-e3.stp",+ "STC/nist_stc_08_asme1_ap242-e3.stp",+ "STC/nist_stc_09_asme1_ap242-e3.stp",+ "STC/nist_stc_10_asme1_ap242-e2.stp",+ };++ [Theory]+ [MemberData(nameof(Files))]+ public void NistModel_DisplaysEveryFace_WithoutTessellationWarnings(string relativePath)+ {+ var import = Step242Importer.ImportBody(File.ReadAllText(Path.Combine(FindRepoRoot(), "testdata", "step242", "nist", relativePath)));+ Assert.True(import.IsSuccess, string.Join(" | ", import.Diagnostics.Select(d => d.Message)));++ var display = DisplayPreparationFallbackBuilder.Build(import.Value, null);++ Assert.True(display.IsSuccess, string.Join(" | ", display.Diagnostics.Select(d => d.Message)));+ var warnings = display.Diagnostics.Where(d => d.Severity != KernelDiagnosticSeverity.Info).Select(d => d.Message).ToArray();+ Assert.True(warnings.Length == 0, string.Join(Environment.NewLine, warnings.Take(5)));+ Assert.DoesNotContain(display.Value.FacePatches, patch => patch.TriangleIndices.Count == 0);+ }++ [Fact]+ public void RationalBSplineSurface_ImportKeepsWeights_SoTheFaceMatchesItsBoundaryEdges()+ {+ var import = Step242Importer.ImportBody(File.ReadAllText(Path.Combine(FindRepoRoot(), "testdata", "step242", "nist", "CTC", "nist_ctc_05_asme1_ap242-e1.stp")));+ Assert.True(import.IsSuccess);++ var rational = import.Value.Topology.Faces+ .Select(face => import.Value.TryGetFaceSurfaceGeometry(face.Id, out var geometry) ? geometry.BSplineSurfaceWithKnots : null)+ .Where(surface => surface is not null)+ .ToArray();++ Assert.NotEmpty(rational);+ Assert.Contains(rational, surface => surface!.IsRational);+ }++ [Fact]+ public void RationalBSplineSurface_SurvivesStepRoundTrip()+ {+ var import = Step242Importer.ImportBody(File.ReadAllText(Path.Combine(FindRepoRoot(), "testdata", "step242", "nist", "CTC", "nist_ctc_05_asme1_ap242-e1.stp")));+ Assert.True(import.IsSuccess);+ var exported = Step242Exporter.ExportBody(import.Value);+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(d => d.Message)));+ Assert.Contains("RATIONAL_B_SPLINE_SURFACE", exported.Value);++ var reimport = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimport.IsSuccess, string.Join(" | ", reimport.Diagnostics.Select(d => d.Message)));++ static int RationalCount(Aetheris.Kernel.Core.Brep.BrepBody body) => body.Topology.Faces.Count(face =>+ body.TryGetFaceSurfaceGeometry(face.Id, out var geometry) && geometry.BSplineSurfaceWithKnots is { IsRational: true });+ Assert.Equal(RationalCount(import.Value), RationalCount(reimport.Value));+ }++ [Fact]+ public void RationalBSplineSurface_EvaluatesExactCircularArc()+ {+ // Quarter cylinder r=1: rational quadratic in u, linear in v.+ var w = double.Sqrt(0.5d);+ IReadOnlyList<IReadOnlyList<Point3D>> net =+ [+ [new Point3D(1, 0, 0), new Point3D(1, 0, 1)],+ [new Point3D(1, 1, 0), new Point3D(1, 1, 1)],+ [new Point3D(0, 1, 0), new Point3D(0, 1, 1)],+ ];+ IReadOnlyList<IReadOnlyList<double>> weights = [[1d, 1d], [w, w], [1d, 1d]];+ var surface = new BSplineSurfaceWithKnots(2, 1, net, "UNSPECIFIED", false, false, false, [3, 3], [2, 2], [0d, 1d], [0d, 1d], "UNSPECIFIED", weights);++ Assert.True(surface.IsRational);+ for (var i = 0; i <= 10; i++)+ {+ var point = surface.Evaluate(i / 10d, 0.5d);+ Assert.Equal(1d, double.Sqrt((point.X * point.X) + (point.Y * point.Y)), 1e-12);+ }++ // The same net without weights is a different (polynomial) surface, which is what dropping weights used to do.+ var polynomial = surface.WithWeights(null).Evaluate(0.5d, 0.5d);+ Assert.True(double.Abs(double.Sqrt((polynomial.X * polynomial.X) + (polynomial.Y * polynomial.Y)) - 1d) > 1e-2);+ }++ [Fact]+ public void UnitWeights_AreCanonicalizedToAPolynomialSurface()+ {+ IReadOnlyList<IReadOnlyList<Point3D>> net = [[new Point3D(0, 0, 0), new Point3D(0, 1, 0)], [new Point3D(1, 0, 0), new Point3D(1, 1, 0)]];+ var surface = new BSplineSurfaceWithKnots(1, 1, net, "UNSPECIFIED", false, false, false, [2, 2], [2, 2], [0d, 1d], [0d, 1d], "UNSPECIFIED", [[1d, 1d], [1d, 1d]]);++ Assert.False(surface.IsRational);+ }++ private static string FindRepoRoot()+ {+ var dir = AppContext.BaseDirectory;+ while (!string.IsNullOrWhiteSpace(dir))+ {+ if (File.Exists(Path.Combine(dir, "Aetheris.slnx"))) return dir;+ dir = Directory.GetParent(dir)?.FullName ?? string.Empty;+ }++ throw new DirectoryNotFoundException("Could not locate repository root.");+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SeamlessBandTessellationTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SeamlessBandTessellationTests.csnew file mode 100644index 00000000..96cb7030--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SeamlessBandTessellationTests.cs@@ -0,0 +1,64 @@+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;++public sealed class SeamlessBandTessellationTests+{+ // A cylinder wall bounded by two full circles and no seam edge (how many CAD systems write hole walls and bosses).+ private const string SeamlessCylinderBand = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=MANIFOLD_SOLID_BREP('solid',#2);\n#2=CLOSED_SHELL($,(#3));\n#3=ADVANCED_FACE((#4,#5),#6,.T.);\n#4=FACE_OUTER_BOUND($,#7,.T.);\n#5=FACE_BOUND($,#8,.T.);\n#6=CYLINDRICAL_SURFACE($,#9,5.0);\n#7=EDGE_LOOP($,(#10));\n#8=EDGE_LOOP($,(#11));\n#9=AXIS2_PLACEMENT_3D($,#12,#13,#14);\n#10=ORIENTED_EDGE($,$,$,#20,.T.);\n#11=ORIENTED_EDGE($,$,$,#21,.F.);\n#20=EDGE_CURVE($,#30,#30,#40,.T.);\n#21=EDGE_CURVE($,#31,#31,#41,.T.);\n#30=VERTEX_POINT($,#50);\n#31=VERTEX_POINT($,#51);\n#40=CIRCLE($,#9,5.0);\n#41=CIRCLE($,#15,5.0);\n#15=AXIS2_PLACEMENT_3D($,#16,#13,#14);\n#50=CARTESIAN_POINT($,(5,0,0));\n#51=CARTESIAN_POINT($,(5,0,3));\n#12=CARTESIAN_POINT($,(0,0,0));\n#13=DIRECTION($,(0,0,1));\n#14=DIRECTION($,(1,0,0));\n#16=CARTESIAN_POINT($,(0,0,3));\nENDSEC;\nEND-ISO-10303-21;";++ [Fact]+ public void CylinderBoundedByTwoFullCircles_IsTessellatedAsTheStripBetweenThem()+ {+ var body = Step242Importer.ImportBody(SeamlessCylinderBand);+ Assert.True(body.IsSuccess, string.Join(" | ", body.Diagnostics.Select(d => d.Message)));++ var result = BrepDisplayTessellator.Tessellate(body.Value);++ Assert.True(result.IsSuccess);+ Assert.DoesNotContain(result.Diagnostics, d => d.Source == "Viewer.Tessellation.TrimEvaluationFailed");+ var patch = Assert.Single(result.Value.FacePatches);+ Assert.NotEmpty(patch.TriangleIndices);+ Assert.Equal(2d * double.Pi * 5d * 3d, SurfaceArea(patch), 0);+ }++ [Fact]+ public void EarCutFallback_TriangulatesPolygonWithHole_CounterClockwiseAboutTheNormal()+ {+ var plane = new PlaneSurface(Point3D.Origin, Direction3D.Create(new Vector3D(0d, 0d, 1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ var outer = new[] { new Point3D(0, 0, 0), new Point3D(10, 0, 0), new Point3D(10, 10, 0), new Point3D(0, 10, 0) };+ IReadOnlyList<Point3D> hole = [new Point3D(3, 3, 0), new Point3D(3, 7, 0), new Point3D(7, 7, 0), new Point3D(7, 3, 0)];++ Assert.True(BrepDisplayTessellator.TryEarCutPlanarLoops(plane, outer, [hole], out var points, out var indices));++ var signedArea = 0d;+ for (var i = 0; i + 2 < indices.Count; i += 3)+ {+ var a = points[indices[i]];+ var b = points[indices[i + 1]];+ var c = points[indices[i + 2]];+ var cross = ((b.X - a.X) * (c.Y - a.Y)) - ((b.Y - a.Y) * (c.X - a.X));+ Assert.True(cross > 0d, "triangle is not counter-clockwise about +Z");+ signedArea += cross * 0.5d;+ }++ Assert.Equal(100d - 16d, signedArea, 9);+ }++ private static double SurfaceArea(DisplayFaceMeshPatch patch)+ {+ var area = 0d;+ for (var i = 0; i + 2 < 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]];+ area += (b - a).Cross(c - a).Length * 0.5d;+ }++ return area;+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.csindex ade86574..57357a3a 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs@@ -200,7 +200,9 @@ public sealed class SurfaceMeshIrTestsAssert.NotEmpty(mesh.HardEdges);var legacy = BrepDisplayTessellator.TessellateLegacyForComparison(body.Value);Assert.True(legacy.IsSuccess);- Assert.True(topology.TriangleCount < legacy.Value.FacePatches.Sum(patch => patch.TriangleIndices.Count / 3));+ // The legacy route now emits a single axial row per straight-generator wall, so it is no longer larger than the+ // watertight IR mesh; the IR only has to stay within an order of magnitude of it.+ Assert.True(topology.TriangleCount <= 10 * legacy.Value.FacePatches.Sum(patch => patch.TriangleIndices.Count / 3));// Focused evidence assertion keeps the comparison on the real legacy route.var displayed = BrepDisplayTessellator.TessellateSurfaceMeshIr(body.Value);diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.csnew file mode 100644index 00000000..3667691f--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.cs@@ -0,0 +1,199 @@+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Step242;++/// <summary>+/// Aetheris keeps an analytic B-rep, so a spline face that is really a primitive has to be imported as one. These+/// cover the generalized recovery lane: the exact rational sweeps every exporter writes are recovered, and the+/// free-form blends that merely resemble them are not.+/// </summary>+public sealed class Step242BsplineSurfaceRecoveryTests+{+ private static readonly double ArcWeight = double.Sqrt(0.5d);++ [Fact]+ public void ExactRationalCone_IsRecoveredAsAnAnalyticCone()+ {+ var decision = Step242BsplineSurfaceRecoveryLane.Decide(CreateExactRationalCone(baseRadius: 4d, topRadius: 8d, height: 8d));++ Assert.Equal("analytic_cone", decision.CandidateName);+ var cone = Assert.IsType<ConeSurface>(decision.RecoveredSurface!.Cone);+ Assert.Equal(double.Atan(0.5d), cone.SemiAngleRadians, 9);+ Assert.Equal(0d, cone.Axis.ToVector().Cross(new Vector3D(0d, 0d, 1d)).Length, 9);+ }++ [Fact]+ public void ExactRationalSphereOctant_IsRecoveredAsAnAnalyticSphere()+ {+ var decision = Step242BsplineSurfaceRecoveryLane.Decide(CreateExactRationalSphereOctant(radius: 7d));++ Assert.Equal("analytic_sphere", decision.CandidateName);+ var sphere = Assert.IsType<SphereSurface>(decision.RecoveredSurface!.Sphere);+ Assert.Equal(7d, sphere.Radius, 9);+ Assert.Equal(0d, (sphere.Center - Point3D.Origin).Length, 9);+ }++ [Fact]+ public void ExactRationalTorusPatch_IsRecoveredAsAnAnalyticTorus()+ {+ var decision = Step242BsplineSurfaceRecoveryLane.Decide(CreateExactRationalTorusPatch(majorRadius: 20d, minorRadius: 3d));++ Assert.Equal("analytic_torus", decision.CandidateName);+ var torus = Assert.IsType<TorusSurface>(decision.RecoveredSurface!.Torus);+ Assert.Equal(20d, torus.MajorRadius, 8);+ Assert.Equal(3d, torus.MinorRadius, 8);+ }++ /// <summary>+ /// The exactness gate is what separates an encoded primitive from a blend, so a sweep that is a circle only to+ /// within a modelling tolerance must stay a spline however closely it fits.+ /// </summary>+ [Fact]+ public void NearlyCircularSweep_IsRejectedBecauseItsSectionsAreNotExact()+ {+ var nudged = CreateExactRationalTorusPatch(majorRadius: 20d, minorRadius: 3d);+ var controlPoints = nudged.ControlPoints+ .Select((row, rowIndex) => (IReadOnlyList<Point3D>)row+ .Select((point, columnIndex) => rowIndex == 1 && columnIndex == 1+ ? new Point3D(point.X + 1e-4d, point.Y, point.Z)+ : point)+ .ToArray())+ .ToArray();+ var perturbed = new BSplineSurfaceWithKnots(+ nudged.DegreeU, nudged.DegreeV, controlPoints, nudged.SurfaceForm, nudged.UClosed, nudged.VClosed,+ nudged.SelfIntersect, nudged.KnotMultiplicitiesU, nudged.KnotMultiplicitiesV, nudged.KnotValuesU,+ nudged.KnotValuesV, nudged.KnotSpec, nudged.Weights);++ var decision = Step242BsplineSurfaceRecoveryLane.Decide(perturbed);++ Assert.Equal("reject", decision.CandidateName);+ Assert.Contains("exact", decision.Reason, StringComparison.OrdinalIgnoreCase);+ }++ /// <summary>+ /// The free-form blends of CTC-02 fit a torus to a few thousandths of a millimetre, which is close enough that a+ /// tolerance-based test would swap them for one. They are spline faces and must stay spline faces.+ /// </summary>+ [Fact]+ public void NistCtc02FreeFormBlends_AreNotRecovered()+ {+ var import = Step242Importer.ImportBody(ReadFixture("testdata/step242/nist/CTC/nist_ctc_02_asme1_ap242-e2.stp"));++ Assert.True(import.IsSuccess);+ Assert.Equal(34, CountFaceSurfaces(import.Value, SurfaceGeometryKind.BSplineSurfaceWithKnots));+ Assert.DoesNotContain(import.Diagnostics, diagnostic => (diagnostic.Source ?? string.Empty).Contains("BsplineSurfaceRecovery", StringComparison.Ordinal));+ }++ /// <summary>+ /// CTC-05's rational faces are five-sided vertex blends, not primitives. Import keeps them and says so with the+ /// measurement it rejected them on, rather than leaving a silent NURBS in an otherwise analytic body.+ /// </summary>+ [Fact]+ public void NistCtc05VertexBlends_AreRetainedWithAMeasuredReason()+ {+ var import = Step242Importer.ImportBody(ReadFixture("testdata/step242/nist/CTC/nist_ctc_05_asme1_ap242-e1.stp"));++ Assert.True(import.IsSuccess);+ var retained = import.Diagnostics+ .Where(diagnostic => (diagnostic.Source ?? string.Empty).Contains("RationalBSplineRetained", StringComparison.Ordinal))+ .ToArray();+ Assert.Equal(4, retained.Length);+ Assert.All(retained, diagnostic => Assert.Contains("analytic_torus", diagnostic.Message, StringComparison.Ordinal));+ }++ [Fact]+ public void RecoveredSurfaces_ReportWhatTheyReplacedAndHowCloselyTheyMatch()+ {+ var import = Step242Importer.ImportBody(ReadFixture("testdata/step242/OCCT/rod.step"));++ Assert.True(import.IsSuccess);+ var recovered = import.Diagnostics+ .Where(diagnostic => (diagnostic.Source ?? string.Empty).Contains("BsplineSurfaceRecovery", StringComparison.Ordinal))+ .ToArray();+ Assert.Equal(2, recovered.Length);+ Assert.All(recovered, diagnostic => Assert.Contains("reproduces the spline to", diagnostic.Message, StringComparison.Ordinal));+ }++ private static int CountFaceSurfaces(Aetheris.Kernel.Core.Brep.BrepBody body, SurfaceGeometryKind kind)+ => body.Topology.Faces.Count(face => body.TryGetFaceSurfaceGeometry(face.Id, out var geometry) && geometry!.Kind == kind);++ /// <summary>Quarter-circle rings as exact rational quadratics, blended linearly so the radius varies with height.</summary>+ private static BSplineSurfaceWithKnots CreateExactRationalCone(double baseRadius, double topRadius, double height)+ => new(+ degreeU: 1,+ degreeV: 2,+ controlPoints: [QuarterArcRing(baseRadius, 0d), QuarterArcRing(topRadius, height)],+ surfaceForm: "CONICAL_SURF",+ uClosed: false,+ vClosed: false,+ selfIntersect: false,+ knotMultiplicitiesU: [2, 2],+ knotMultiplicitiesV: [3, 3],+ knotValuesU: [0d, 1d],+ knotValuesV: [0d, 1d],+ knotSpec: "PIECEWISE_BEZIER_KNOTS",+ weights: [ArcWeights(), ArcWeights()]);++ /// <summary>A quarter meridian revolved through a quarter turn: the octant every exporter writes for a sphere.</summary>+ private static BSplineSurfaceWithKnots CreateExactRationalSphereOctant(double radius)+ {+ Point3D[] meridian = [new(0d, 0d, radius), new(radius, 0d, radius), new(radius, 0d, 0d)];+ double[] meridianWeights = [1d, ArcWeight, 1d];+ return Revolve(meridian, meridianWeights, degreeU: 2, "SPHERICAL_SURF");+ }++ /// <summary>A quarter of the minor circle revolved through a quarter turn about the torus axis.</summary>+ private static BSplineSurfaceWithKnots CreateExactRationalTorusPatch(double majorRadius, double minorRadius)+ {+ Point3D[] minorArc =+ [+ new(majorRadius + minorRadius, 0d, 0d),+ new(majorRadius + minorRadius, 0d, minorRadius),+ new(majorRadius, 0d, minorRadius)+ ];+ double[] minorWeights = [1d, ArcWeight, 1d];+ return Revolve(minorArc, minorWeights, degreeU: 2, "TOROIDAL_SURF");+ }++ /// <summary>Revolves a profile in the xz plane through a quarter turn about z as an exact rational surface.</summary>+ private static BSplineSurfaceWithKnots Revolve(IReadOnlyList<Point3D> profile, IReadOnlyList<double> profileWeights, int degreeU, string surfaceForm)+ {+ var controlPoints = profile+ .Select(point => (IReadOnlyList<Point3D>)new Point3D[]+ {+ new(point.X, 0d, point.Z),+ new(point.X, point.X, point.Z),+ new(0d, point.X, point.Z)+ })+ .ToArray();+ var weights = profileWeights+ .Select(weight => (IReadOnlyList<double>)new[] { weight, weight * ArcWeight, weight })+ .ToArray();++ return new BSplineSurfaceWithKnots(+ degreeU: degreeU,+ degreeV: 2,+ controlPoints: controlPoints,+ surfaceForm: surfaceForm,+ uClosed: false,+ vClosed: false,+ selfIntersect: false,+ knotMultiplicitiesU: [degreeU + 1, degreeU + 1],+ knotMultiplicitiesV: [3, 3],+ knotValuesU: [0d, 1d],+ knotValuesV: [0d, 1d],+ knotSpec: "PIECEWISE_BEZIER_KNOTS",+ weights: weights);+ }++ private static IReadOnlyList<Point3D> QuarterArcRing(double radius, double z)+ => [new Point3D(radius, 0d, z), new Point3D(radius, radius, z), new Point3D(0d, radius, z)];++ private static IReadOnlyList<double> ArcWeights() => [1d, ArcWeight, 1d];++ private static string ReadFixture(string relativePath)+ => File.ReadAllText(Path.Combine(Step242CorpusManifestRunner.RepoRoot(), relativePath.Replace('/', Path.DirectorySeparatorChar)));+}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ConicalSurfaceRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ConicalSurfaceRegressionTests.csindex 4e504650..874f8594 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ConicalSurfaceRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ConicalSurfaceRegressionTests.cs@@ -150,9 +150,9 @@ public sealed class Step242ConicalSurfaceRegressionTests"No diagnostics.")][InlineData("testdata/step242/nist/STC/nist_stc_10_asme1_ap242-e2.stp",- "importer-topology",- "Importer.LoopRole.DisconnectedCoedges",- "Planar loop contains disconnected consecutive coedges")]+ "",+ "Audit.None",+ "No diagnostics.")]public void Step242_NistTargets_AdvancePastCircleTrim_AndKeepDeterministicNextBlocker(string relativePath,string expectedLayer,diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.csindex 9df64368..26d74e0c 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.cs@@ -297,13 +297,15 @@ internal static class Step242CorpusManifestRunnerprivate static Step242AuditDiagnostic FirstDiagnostic(IReadOnlyList<KernelDiagnostic> diagnostics){- if (diagnostics.Count == 0)+ // The audit uses this to name what blocked a file, so it reports the first finding. Informational notes -+ // such as import recording that a spline face was recovered as a primitive - are not blockers and are skipped.+ var finding = diagnostics.FirstOrDefault(diagnostic => diagnostic.Severity != KernelDiagnosticSeverity.Info);+ if (finding is null){return new Step242AuditDiagnostic("Unknown", "Audit.None", "No diagnostics.");}- var d = diagnostics[0];- return new Step242AuditDiagnostic(d.Code.ToString(), NormalizeSource(d.Source ?? string.Empty), StableMessagePrefix(d.Message));+ return new Step242AuditDiagnostic(finding.Code.ToString(), NormalizeSource(finding.Source ?? string.Empty), StableMessagePrefix(finding.Message));}private static string DetermineImportFailureLayer(IReadOnlyList<KernelDiagnostic> diagnostics)diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242CylinderTrimDualSingleCoedgeClosedCircleRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242CylinderTrimDualSingleCoedgeClosedCircleRegressionTests.csindex 217f242b..14b2bd3a 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242CylinderTrimDualSingleCoedgeClosedCircleRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242CylinderTrimDualSingleCoedgeClosedCircleRegressionTests.cs@@ -44,7 +44,7 @@ public sealed class Step242CylinderTrimDualSingleCoedgeClosedCircleRegressionTes}[Fact]- public void Step242_Ftc11_AdvancesPastCylinderTrimDegenerate_ToNextExplicitBlocker_Deterministically()+ public void Step242_Ftc11_TessellatesDualSingleCoedgeClosedCircleCylinders_AndReachesPickerSuccess_Deterministically(){const string relativePath = "testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp";var first = Step242CorpusManifestRunner.RunOne(new Step242CorpusManifestEntry("ftc11", relativePath, "nist-regression", null, null, null, null, null), includeDisplayAudit: true);@@ -52,10 +52,9 @@ public sealed class Step242CylinderTrimDualSingleCoedgeClosedCircleRegressionTesAssert.Equal("success", first.Status);Assert.Equal(string.Empty, first.FirstFailureLayer);- Assert.Equal("pickerBlockedByTessellationSkip", first.DisplayStatus);- Assert.Equal("picker", first.DisplayFirstFailureLayer);- Assert.Equal("Audit.Picker", first.DisplayFirstDiagnostic.Source);- Assert.Equal("Picker smoke ray produced no hit.", first.DisplayFirstDiagnostic.MessagePrefix);+ // Seamless dual-circle cylinder walls used to be skipped by tessellation, which starved the picker. They now tessellate.+ Assert.Equal("success", first.DisplayStatus);+ Assert.Equal(string.Empty, first.DisplayFirstFailureLayer);Assert.Equal(first.DisplayStatus, second.DisplayStatus);Assert.Equal(first.DisplayFirstFailureLayer, second.DisplayFirstFailureLayer);diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242LoopRoleNormalizationRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242LoopRoleNormalizationRegressionTests.csindex 281543a3..89c79f5d 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242LoopRoleNormalizationRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242LoopRoleNormalizationRegressionTests.cs@@ -54,10 +54,10 @@ public sealed class Step242LoopRoleNormalizationRegressionTests}[Theory]- [InlineData("testdata/step242/nist/FTC/nist_ftc_08_asme1_ap242-e2.stp", false)]- [InlineData("testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp", true)]- [InlineData("testdata/step242/nist/STC/nist_stc_06_asme1_ap242-e3.stp", true)]- public void Step242_CylinderLoopRole_ProjectionDiagnostics_AreDeterministic_AndExplicit(string relativePath, bool expectDiagnostics)+ [InlineData("testdata/step242/nist/FTC/nist_ftc_08_asme1_ap242-e2.stp", true, false)]+ [InlineData("testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp", true, true)]+ [InlineData("testdata/step242/nist/STC/nist_stc_06_asme1_ap242-e3.stp", true, true)]+ public void Step242_CylinderLoopRole_ProjectionDiagnostics_AreDeterministic_AndExplicit(string relativePath, bool expectDiagnostics, bool expectDegeneracy){var first = CaptureCylinderProjectionDiagnostics(relativePath);var second = CaptureCylinderProjectionDiagnostics(relativePath);@@ -66,11 +66,13 @@ public sealed class Step242LoopRoleNormalizationRegressionTestsif (expectDiagnostics){Assert.NotEmpty(first);- Assert.Contains(first, d => !string.Equals(d.Degeneracy, "None", StringComparison.Ordinal));+ if (expectDegeneracy)+ {+ Assert.Contains(first, d => !string.Equals(d.Degeneracy, "None", StringComparison.Ordinal));+ }}else{- // This file is rejected by an earlier planar-bound safety check.Assert.Empty(first);}}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242NistAuditHarnessTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242NistAuditHarnessTests.csindex a37a85d3..95f7003b 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242NistAuditHarnessTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242NistAuditHarnessTests.cs@@ -67,7 +67,7 @@ public sealed class Step242NistAuditHarnessTests}[Fact]- public void NistCorpus_RepresentativeDisplayBlocker_RemainsVisibleInDisplayLane()+ public void NistCorpus_FormerDisplayBlocker_Ftc11_NowPassesDisplayLane(){const string relativePath = "testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp";var entry = BuildNistEntry(relativePath);@@ -77,8 +77,8 @@ public sealed class Step242NistAuditHarnessTestsAssert.Equal("success", first.Status);Assert.Equal(string.Empty, first.FirstFailureLayer);- Assert.Equal("pickerBlockedByTessellationSkip", first.DisplayStatus);- Assert.Equal("picker", first.DisplayFirstFailureLayer);+ Assert.Equal("success", first.DisplayStatus);+ Assert.Equal(string.Empty, first.DisplayFirstFailureLayer);Assert.Equal(first.DisplayStatus, second.DisplayStatus);Assert.Equal(first.DisplayFirstFailureLayer, second.DisplayFirstFailureLayer);Assert.Equal(first.DisplayFirstDiagnostic.Source, second.DisplayFirstDiagnostic.Source);diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242OcctCylinderRecoveryTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242OcctCylinderRecoveryTests.csindex 37d9503f..9e884354 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242OcctCylinderRecoveryTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242OcctCylinderRecoveryTests.cs@@ -27,47 +27,57 @@ public sealed class Step242OcctCylinderRecoveryTestsAssert.Equal(0, import.Value.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots));}+ /// <summary>+ /// A polynomial cubic through the corners of a half-circle looks like a cylinder to any test that only reads the+ /// control net, but it bulges 2.5 mm away from one. Recovery has to measure the surface it would replace, not the+ /// shape of its net, or it silently swaps a blend for a primitive that is nowhere near it.+ /// </summary>[Fact]- public void BsplineRecoveryLane_NonRationalCylinderLikeSurface_ExplicitlyRejectsRecovery()+ public void BsplineRecoveryLane_PolynomialApproximationOfAHalfCircle_IsRejectedInsteadOfSnappedToACylinder(){- var decision = Step242BsplineSurfaceRecoveryLane.Decide(- CreateNonRationalSurfaceEntity(),- CreateCylinderLikeSurface());+ var decision = Step242BsplineSurfaceRecoveryLane.Decide(CreateCylinderLikeSurface());Assert.Equal("reject", decision.CandidateName);Assert.Null(decision.RecoveredSurface);- Assert.Contains("not a rational", decision.Reason, StringComparison.OrdinalIgnoreCase);+ Assert.Contains("exact", decision.Reason, StringComparison.OrdinalIgnoreCase);}[Fact]- public void BsplineRecoveryLane_RationalCylinderLikeSurface_UsesJudgmentToSelectAnalyticCylinder()+ public void BsplineRecoveryLane_ExactRationalCylinder_UsesJudgmentToSelectAnalyticCylinder(){- var decision = Step242BsplineSurfaceRecoveryLane.Decide(- CreateRationalSurfaceEntity(),- CreateCylinderLikeSurface());+ var decision = Step242BsplineSurfaceRecoveryLane.Decide(CreateExactRationalCylinder(radius: 5d, height: 10d));Assert.Equal("analytic_cylinder", decision.CandidateName);Assert.NotNull(decision.RecoveredSurface);Assert.Equal(SurfaceGeometryKind.Cylinder, decision.RecoveredSurface!.Kind);+ Assert.Equal(5d, decision.RecoveredSurface.Cylinder!.Value.Radius, 9);}- private static Step242ParsedEntity CreateRationalSurfaceEntity()+ /// <summary>Quarter circle as a rational quadratic - the exact NURBS arc every exporter writes - swept along z.</summary>+ internal static BSplineSurfaceWithKnots CreateExactRationalCylinder(double radius, double height){- var constructors = new[]- {- new Step242EntityConstructor("B_SPLINE_SURFACE_WITH_KNOTS", []),- new Step242EntityConstructor("RATIONAL_B_SPLINE_SURFACE", [new Step242ListValue([])]),- new Step242EntityConstructor("SURFACE", [])- };-- return new Step242ParsedEntity(1, new Step242ComplexEntityInstance(constructors));- }+ var weight = double.Sqrt(0.5d);+ IReadOnlyList<Point3D> Ring(double z) =>+ [+ new Point3D(radius, 0d, z),+ new Point3D(radius, radius, z),+ new Point3D(0d, radius, z)+ ];- private static Step242ParsedEntity CreateNonRationalSurfaceEntity()- {- return new Step242ParsedEntity(- 1,- new Step242SimpleEntityInstance(new Step242EntityConstructor("B_SPLINE_SURFACE_WITH_KNOTS", [])));+ return new BSplineSurfaceWithKnots(+ degreeU: 1,+ degreeV: 2,+ controlPoints: [Ring(0d), Ring(height)],+ surfaceForm: "CYLINDRICAL_SURF",+ uClosed: false,+ vClosed: false,+ selfIntersect: false,+ knotMultiplicitiesU: [2, 2],+ knotMultiplicitiesV: [3, 3],+ knotValuesU: [0d, 1d],+ knotValuesV: [0d, 1d],+ knotSpec: "PIECEWISE_BEZIER_KNOTS",+ weights: [[1d, weight, 1d], [1d, weight, 1d]]);}private static BSplineSurfaceWithKnots CreateCylinderLikeSurface()diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.csindex d68e1421..0b680ade 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242TessellationRobustnessTests.cs@@ -82,7 +82,7 @@ public sealed class Step242TessellationRobustnessTests[Fact][Trait("Category", "SlowCorpus")]- public void Step242_Tessellate_UnsupportedComplexPlanarMultiLoop_DoesNotFallbackToOuterLoopFill()+ public void Step242_Tessellate_ComplexPlanarMultiLoop_IsResolvedByEarCutFallback_WithoutOuterLoopFill(){var text = LoadFixture("testdata/step242/nist/CTC/nist_ctc_02_asme1_ap242-e2.stp");@@ -94,17 +94,24 @@ public sealed class Step242TessellationRobustnessTestsAssert.True(tessellation.IsSuccess);- var diagnostics = tessellation.Diagnostics- .Where(d => string.Equals(d.Source, "Viewer.Tessellation.PlanarMultiLoopTriangulationSkipped", StringComparison.Ordinal))- .ToArray();- Assert.NotEmpty(diagnostics);- var diagnostic = Assert.Single(diagnostics, d => d.Message.Contains("Face 2 ", StringComparison.Ordinal));- Assert.Equal(KernelDiagnosticCode.ValidationFailed, diagnostic.Code);- Assert.Contains("skipping face patch", diagnostic.Message, StringComparison.Ordinal);-- var skippedPatch = Assert.Single(tessellation.Value.FacePatches, patch => patch.FaceId.Value == 2);- Assert.Empty(skippedPatch.Positions);- Assert.Empty(skippedPatch.TriangleIndices);+ // The primary planar triangulator declines this long multi-loop face; the earcut fallback resolves it instead of+ // the face being skipped.+ Assert.DoesNotContain(tessellation.Diagnostics, d =>+ string.Equals(d.Source, "Viewer.Tessellation.PlanarMultiLoopTriangulationSkipped", StringComparison.Ordinal)+ && d.Message.Contains("Face 2 ", StringComparison.Ordinal));++ var patch = Assert.Single(tessellation.Value.FacePatches, p => p.FaceId.Value == 2);+ Assert.NotEmpty(patch.TriangleIndices);+ var area = 0d;+ for (var i = 0; i + 2 < 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]];+ area += (b - a).Cross(c - a).Length * 0.5d;+ }++ Assert.True(area > 0d);}[Fact]diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242UnsupportedSurfaceForHolesRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242UnsupportedSurfaceForHolesRegressionTests.csindex 454ce912..09ec9a28 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242UnsupportedSurfaceForHolesRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242UnsupportedSurfaceForHolesRegressionTests.cs@@ -7,10 +7,10 @@ public sealed class Step242UnsupportedSurfaceForHolesRegressionTests[Theory][InlineData("testdata/step242/nist/FTC/nist_ftc_08_asme1_ap242-e2.stp",- "importer-topology",+ "","Topology.GraphValidator",- "Importer.LoopRole.DisconnectedCoedges",- "Planar loop contains disconnected consecutive coedges")]+ "Audit.None",+ "No diagnostics.")][InlineData("testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp",null,diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.csindex 814107a6..84a10d6b 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BoundaryConformingTrimTessellator.cs@@ -19,7 +19,9 @@ namespace Aetheris.Kernel.Core.Brep.Tessellation;/// </summary>internal static class BoundaryConformingTrimTessellator{- private const int MaxTriangles = 200_000;+ // Soft cap: refinement stops (leaving a valid, conforming, slightly coarser mesh) once a face reaches this size,+ // so dense B-spline faces cannot consume the whole display budget.+ private const int MaxTriangles = 12_000;// Never split edges shorter than this fraction of a nominal grid cell (guarantees termination).private const double MinimumSplitLength = 0.125d;// Safety net: triangles with an edge longer than this many nominal grid cells are always split.@@ -35,7 +37,8 @@ internal static class BoundaryConformingTrimTessellatordouble cellU,double cellV,DisplayTessellationOptions options,- Action? checkBudget)+ Action? checkBudget,+ double maximumCellLength = MaximumCellLength){if (!(cellU > 0d) || !(cellV > 0d) || !double.IsFinite(cellU) || !double.IsFinite(cellV)){@@ -108,7 +111,7 @@ internal static class BoundaryConformingTrimTessellatorreturn null;}- var mesh = new RefinableMesh(cellU, cellV, evaluate, evaluateNormal, options.ChordTolerance, options.AngularToleranceRadians);+ var mesh = new RefinableMesh(cellU, cellV, evaluate, evaluateNormal, options.ChordTolerance, options.AngularToleranceRadians, maximumCellLength);var pointMap = new int[seedPoints.Count];for (var i = 0; i < seedPoints.Count; i++){@@ -235,6 +238,7 @@ internal static class BoundaryConformingTrimTessellatorprivate readonly Func<double, double, Vector3D> _evaluateNormal;private readonly double _chordTolerance;private readonly double _angularTolerance;+ private readonly double _maximumCellLength;private readonly List<Point3D?> _positions = new();private readonly List<Vector3D?> _normals = new();private readonly List<(double U, double V)> _vertices = new();@@ -251,7 +255,8 @@ internal static class BoundaryConformingTrimTessellatorFunc<double, double, Point3D> evaluate,Func<double, double, Vector3D> evaluateNormal,double chordTolerance,- double angularTolerance)+ double angularTolerance,+ double maximumCellLength){_cellU = cellU;_cellV = cellV;@@ -259,6 +264,7 @@ internal static class BoundaryConformingTrimTessellator_evaluateNormal = evaluateNormal;_chordTolerance = chordTolerance;_angularTolerance = angularTolerance;+ _maximumCellLength = maximumCellLength;}public Point3D Position(int index)@@ -347,7 +353,7 @@ internal static class BoundaryConformingTrimTessellatorif (_alive.Count > MaxTriangles){- return false;+ return true;}var t = _work.Pop();@@ -395,7 +401,7 @@ internal static class BoundaryConformingTrimTessellatorreturn false;}- if (longest > MaximumCellLength)+ if (longest > _maximumCellLength){return true;}diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.csindex 10554ae3..dca42ed7 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs@@ -364,6 +364,14 @@ public static class BrepDisplayTessellatorvar triangulationResult = ExecuteWithinOptionalBudget(() =>{+ // The hole-bridging triangulator is super-linear in the number of holes and can exhaust the whole+ // display budget on a plate with dozens of holes; earcut handles those directly and cheaply.+ if (holes.Length >= ManyHolesEarCutThreshold+ && TryEarCutPlanarLoops(plane, outerLoop, holes, out var manyHolesPoints, out var manyHolesIndices))+ {+ return KernelResult<(IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices, PlanarPolygonTriangulationFailure? Failure)>.Success((manyHolesPoints, manyHolesIndices, null));+ }+if (!PlanarPolygonTriangulator.TryTriangulateWithHoles(outerLoop,holes,@@ -372,6 +380,13 @@ public static class BrepDisplayTessellatorout var indices,out var failure)){+ // The primary triangulator declines some long, finely sampled but simple loops; earcut is the second opinion.+ if (failure == PlanarPolygonTriangulationFailure.TriangulationFailed+ && TryEarCutPlanarLoops(plane, outerLoop, holes, out var earCutPoints, out var earCutIndices))+ {+ return KernelResult<(IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices, PlanarPolygonTriangulationFailure? Failure)>.Success((earCutPoints, earCutIndices, null));+ }+return KernelResult<(IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices, PlanarPolygonTriangulationFailure? Failure)>.Failure([CreateValidationWarning($"Face {faceId.Value} planar multi-loop tessellation could not be resolved ({failure?.ToString() ?? "Unknown"}); skipping face patch to avoid misleading filled geometry.",@@ -398,6 +413,66 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, triangulationResult.Value.Points, plane.Normal.ToVector(), triangulationResult.Value.Indices));}+ private const int ManyHolesEarCutThreshold = 8;++ internal static bool TryEarCutPlanarLoops(+ PlaneSurface plane,+ IReadOnlyList<Point3D> outerLoop,+ IReadOnlyList<IReadOnlyList<Point3D>> holes,+ out IReadOnlyList<Point3D> points,+ out IReadOnlyList<int> indices)+ {+ points = Array.Empty<Point3D>();+ indices = Array.Empty<int>();+ var uAxis = plane.UAxis.ToVector();+ var vAxis = plane.VAxis.ToVector();+ var origin = plane.Origin;+ (double X, double Y) Project(Point3D point)+ {+ var offset = point - origin;+ return (offset.Dot(uAxis), offset.Dot(vAxis));+ }++ var outer2d = outerLoop.Select(Project).ToList();+ var holes2d = holes.Select(hole => (IReadOnlyList<(double X, double Y)>)hole.Select(Project).ToList()).ToList();+ if (!EarCutTriangulator.TryTriangulate(outer2d, holes2d, out var points2d, out var earCutIndices))+ {+ return false;+ }++ var points3d = outerLoop.Concat(holes.SelectMany(hole => hole)).ToArray();+ if (points3d.Length != points2d.Count)+ {+ return false;+ }++ // Emit every triangle counter-clockwise about the plane normal.+ var oriented = new List<int>(earCutIndices.Count);+ for (var i = 0; i + 2 < earCutIndices.Count; i += 3)+ {+ var a = points2d[earCutIndices[i]];+ var b = points2d[earCutIndices[i + 1]];+ var c = points2d[earCutIndices[i + 2]];+ var cross = ((b.X - a.X) * (c.Y - a.Y)) - ((b.Y - a.Y) * (c.X - a.X));+ if (cross >= 0d)+ {+ oriented.Add(earCutIndices[i]);+ oriented.Add(earCutIndices[i + 1]);+ oriented.Add(earCutIndices[i + 2]);+ }+ else+ {+ oriented.Add(earCutIndices[i]);+ oriented.Add(earCutIndices[i + 2]);+ oriented.Add(earCutIndices[i + 1]);+ }+ }++ points = points3d;+ indices = oriented;+ return true;+ }+private static KernelResult<DisplayFaceMeshPatch> TriangulatePlanarPatch(FaceId faceId, PlaneSurface plane, IReadOnlyList<Point3D> polygonPoints){if (!PlanarPolygonTriangulator.TryTriangulate(polygonPoints, plane.Normal.ToVector(), out var indices, out var failure))@@ -590,6 +665,15 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellateCylinderFace(BrepBody body, FaceId faceId, CylinderSurface cylinder, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){var loopIds = body.GetLoopIds(faceId);+ if (loopIds.Count == 2+ && TryResolveDualSingleCoedgeClosedCircleCylinderTrimPatch(body, faceId, cylinder, loopIds, cylinder.Axis.ToVector(), 1e-8d).IsSuccess)+ {+ // A seamless cylindrical band (hole wall or boss) is bounded by two full circles. In UV those are two+ // zero-area lines, not an outer loop plus a hole, so the generic multi-loop trim path derives a degenerate+ // domain and drops the face. The dedicated dual-circle resolution knows the band is the strip between them.+ return TessellateLegacyCylinderFace(body, faceId, cylinder, options);+ }+if (loopIds.Count > 1){var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToCylinderUv(cylinder, point), options, executionBudget, SurfaceGeometryKind.Cylinder);@@ -598,7 +682,7 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPlanarPatch(faceId),[CreateValidationWarning(- $"Face {faceId.Value} cylinder trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry.",+ $"Face {faceId.Value} cylinder trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry. Cause: {uvLoopsResult.Diagnostics.FirstOrDefault()?.Message}",TrimEvaluationFailedSource)]);}@@ -636,7 +720,7 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPlanarPatch(faceId),[CreateValidationWarning(- $"Face {faceId.Value} cone trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry.",+ $"Face {faceId.Value} cone trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry. Cause: {uvLoopsResult.Diagnostics.FirstOrDefault()?.Message}",TrimEvaluationFailedSource)]);}@@ -747,7 +831,8 @@ public static class BrepDisplayTessellator}var angularSegments = CalculateSegmentCount(2d * double.Pi, ordered.Max(level => level.Radius), options);- var axialSegments = CalculateAxialSegments(ordered[0].Axial, ordered[1].Axial, options);+ // Cone generators are straight and the normal is constant along them: one row of quads is exact.+ var axialSegments = 1;patch = CreatePeriodicGridPatch(faceId,angularSegments,@@ -787,10 +872,11 @@ public static class BrepDisplayTessellatoraxialParameterFromPoint: point => (point - cylinder.Origin).Dot(cylinder.Axis.ToVector()));if (periodicParameters.IsSuccess){+ // Cylinder generators are straight: axial subdivision adds triangles but no accuracy.return KernelResult<DisplayFaceMeshPatch>.Success(CreatePeriodicGridPatch(faceId,periodicParameters.Value.AngularSegments,- periodicParameters.Value.AxialSegments,+ 1,(u, v) => cylinder.Evaluate(u, v),(u, _) => cylinder.Normal(u).ToVector(),periodicParameters.Value.VStart,@@ -800,7 +886,7 @@ public static class BrepDisplayTessellator}var angularSegments = CalculateSegmentCount(angularSpan, System.Math.Max(1e-6d, cylinder.Radius), options);- var axialSegments = System.Math.Max(1, System.Math.Clamp((int)double.Ceiling(axialSpan / options.ChordTolerance), 1, options.MaximumSegments));+ const int axialSegments = 1;return KernelResult<DisplayFaceMeshPatch>.Success(CreateBoundedGridPatch(faceId,@@ -832,7 +918,7 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Success(CreatePeriodicGridPatch(faceId,parameters.Value.AngularSegments,- parameters.Value.AxialSegments,+ 1,(u, v) => cone.Evaluate(u, v),(u, _) => cone.Normal(u).ToVector(),parameters.Value.VStart,@@ -1399,6 +1485,55 @@ public static class BrepDisplayTessellatorreturn KernelResult<double>.Success(wrappedValue + currentOffset);}+ /// <summary>+ /// Recognizes a torus face bounded by exactly two single-edge full-circle loops that are coaxial with the torus+ /// (constant minor angle v). The band between them is the shorter tube arc; a face wider than half the tube is+ /// ambiguous without orientation analysis and is left to the generic path.+ /// </summary>+ private static bool TryResolveCoaxialCirclePairTorusBand(BrepBody body, TorusSurface torus, IReadOnlyList<LoopId> loopIds, out double vStart, out double vEnd)+ {+ vStart = 0d;+ vEnd = 0d;+ var angles = new double[2];+ for (var i = 0; i < 2; i++)+ {+ var coedgeIds = body.GetCoedgeIds(loopIds[i]);+ if (coedgeIds.Count != 1)+ {+ return false;+ }++ var edge = body.Topology.GetCoedge(coedgeIds[0]).EdgeId;+ var curve = body.GetEdgeCurve(edge);+ if (curve.Kind != CurveGeometryKind.Circle3 || curve.Circle3 is not { } circle)+ {+ return false;+ }++ var axis = torus.Axis.ToVector();+ var offset = circle.Center - torus.Center;+ var alongAxis = offset.Dot(axis);+ var offAxis = (offset - (axis * alongAxis)).Length;+ if (offAxis > 1e-6d || double.Abs(circle.Normal.ToVector().Dot(axis)) < 1d - 1e-9d)+ {+ return false;+ }++ angles[i] = TorusMinorAngleOf(torus, circle.Evaluate(0d));+ }++ var delta = angles[1] - angles[0];+ delta -= 2d * double.Pi * double.Round(delta / (2d * double.Pi));+ if (double.Abs(delta) < 1e-9d || double.Abs(delta) > double.Pi - 1e-6d)+ {+ return false;+ }++ vStart = delta > 0d ? angles[0] : angles[1];+ vEnd = vStart + double.Abs(delta);+ return true;+ }+private static (double U, double V)? TryProjectPointToTorusUv(TorusSurface torus, Point3D point){var axis = torus.Axis.ToVector();@@ -1433,7 +1568,10 @@ public static class BrepDisplayTessellatorvar residual = torus.Evaluate(u, v) - point;var residualDistance = System.Math.Sqrt(residual.Dot(residual));- var tolerance = System.Math.Max(1e-5d, System.Math.Max(torus.MajorRadius, torus.MinorRadius) * 1e-4d);+ // Boundary curves of fillet/blend faces are frequently B-spline approximations of the true intersection and+ // sit up to ~1e-3 mm off the analytic torus; this is a display projection, so accept deviations well below+ // visual resolution instead of dropping the face.+ var tolerance = System.Math.Max(AnalyticProjectionDeviationFloor, System.Math.Max(System.Math.Max(torus.MajorRadius, torus.MinorRadius) * 1e-4d, torus.MinorRadius * 1e-2d));if (!double.IsFinite(residualDistance) || residualDistance > tolerance){return null;@@ -1442,6 +1580,10 @@ public static class BrepDisplayTessellatorreturn (u, v);}+ // Boundary edges of fillet/blend faces are often B-spline approximations of the true intersection and sit a few+ // 1e-3 mm off the analytic surface. UV projection here is for display, so accept anything below visual resolution.+ private const double AnalyticProjectionDeviationFloor = 1e-2d;+private static (double U, double V)? TryProjectPointToCylinderUv(CylinderSurface cylinder, Point3D point){var axis = cylinder.Axis.ToVector();@@ -1451,7 +1593,7 @@ public static class BrepDisplayTessellatorvar axial = offset.Dot(axis);var radial = offset - (axis * axial);var radialLength = radial.Length;- var tolerance = System.Math.Max(1e-5d, cylinder.Radius * 1e-4d);+ var tolerance = System.Math.Max(AnalyticProjectionDeviationFloor, cylinder.Radius * 1e-4d);if (!double.IsFinite(radialLength) || System.Math.Abs(radialLength - cylinder.Radius) > tolerance){return null;@@ -1486,7 +1628,7 @@ public static class BrepDisplayTessellatorvar radial = offset - (axis * axial);var radialLength = radial.Length;var expectedRadius = axial * double.Tan(cone.SemiAngleRadians);- var tolerance = System.Math.Max(1e-5d, expectedRadius * 1e-4d);+ var tolerance = System.Math.Max(AnalyticProjectionDeviationFloor, expectedRadius * 1e-4d);if (System.Math.Abs(radialLength - expectedRadius) > tolerance){return null;@@ -1672,9 +1814,10 @@ public static class BrepDisplayTessellatorvar diagonal = new Vector3D(maxX - minX, maxY - minY, maxZ - minZ).Length;// Vendor STEP files carry edge curves that only agree with their face surfaces to the exporting CAD// system's accuracy; measured on a McMaster bevel pinion the worst edge-to-surface gap is about 7 microns.- // Loop samples that close to a surface are still unambiguously on it, so the tolerance has a 20 micron- // floor (model units are mm after import normalization).- return System.Math.Max(2e-2d, diagonal * 1e-4d);+ // Loop samples that close to a surface are still unambiguously on it, so the tolerance has a 50 micron+ // floor (model units are mm after import normalization). NIST rational patches sit up to ~20 microns off+ // their boundary edges even with exact NURBS evaluation.+ return System.Math.Max(5e-2d, diagonal * 1e-4d);}private static Vector3D EvaluateBSplineNormal(BSplineSurfaceWithKnots surface, double u, double v)@@ -1739,6 +1882,20 @@ public static class BrepDisplayTessellatorprivate static KernelResult<DisplayFaceMeshPatch> TessellateTorusFace(BrepBody body, FaceId faceId, TorusSurface torus, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null){var loopIds = body.GetLoopIds(faceId);+ if (loopIds.Count == 2 && TryResolveCoaxialCirclePairTorusBand(body, torus, loopIds, out var bandVStart, out var bandVEnd))+ {+ // Two full parallel circles bound a band of the tube: the generic trim path sees two degenerate+ // (zero-area) loops in UV, so tessellate the band directly as a periodic grid.+ return KernelResult<DisplayFaceMeshPatch>.Success(CreatePeriodicGridPatch(+ faceId,+ CalculateSegmentCount(2d * double.Pi, System.Math.Max(1e-6d, torus.MajorRadius + torus.MinorRadius), options),+ CalculateSegmentCount(bandVEnd - bandVStart, System.Math.Max(1e-6d, torus.MinorRadius), options),+ (u, v) => torus.Evaluate(u, v),+ (u, v) => torus.Normal(u, v).ToVector(),+ bandVStart,+ bandVEnd));+ }+if (loopIds.Count > 0){var uvLoopsResult = TryBuildDoublyPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToTorusUv(torus, point), options, executionBudget, SurfaceGeometryKind.Torus);@@ -1747,7 +1904,7 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPlanarPatch(faceId),[CreateValidationWarning(- $"Face {faceId.Value} torus trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry.",+ $"Face {faceId.Value} torus trim evaluation failed; skipping face patch to avoid misleading untrimmed geometry. Cause: {uvLoopsResult.Diagnostics.FirstOrDefault()?.Message}",TrimEvaluationFailedSource)]);}@@ -1775,7 +1932,7 @@ public static class BrepDisplayTessellatorreturn KernelResult<DisplayFaceMeshPatch>.Success(CreatePeriodicGridPatch(faceId,parameters.Value.AngularSegments,- parameters.Value.AxialSegments,+ CalculateSegmentCount(parameters.Value.VEnd - parameters.Value.VStart, System.Math.Max(1e-6d, torus.MinorRadius), options),(u, v) => torus.Evaluate(u, v),(u, v) => torus.Normal(u, v).ToVector(),parameters.Value.VStart,@@ -2962,14 +3119,14 @@ public static class BrepDisplayTessellator{return KernelResult<(double, double, double, double)>.Success(generalResolution.Value,- [CreateValidationWarning(+ [CreateClassificationInfo($"Face {faceId.Value} spherical two-coedge trim classified as bi-arc circle lune with two shared vertices (edges {coedges[0].EdgeId.Value}/{coedges[1].EdgeId.Value}).",SphereTrimTwoCoedgeBiArcLuneSource)]);}return KernelResult<(double, double, double, double)>.Success(generalResolution.Value,- [CreateValidationWarning(+ [CreateClassificationInfo($"Face {faceId.Value} spherical two-coedge trim classified as bspline bi-arc surrogate pair with two shared vertices (edges {coedges[0].EdgeId.Value}/{coedges[1].EdgeId.Value}).",SphereTrimTwoCoedgeBsplineBiArcSurrogateSource)]);}@@ -3144,7 +3301,7 @@ public static class BrepDisplayTessellatorreturn KernelResult<(double, double, double, double)>.Success((0d, 2d * double.Pi, vStart, vEnd),- [CreateValidationWarning(+ [CreateClassificationInfo($"Face {faceId.Value} spherical single-coedge trim classified as closed full-wrap constant-latitude cap (edge {coedge.EdgeId.Value}, latitude {latitude:R}, pole {(pole > 0d ? "+pi/2" : "-pi/2")}).",SphereTrimSingleCoedgeLatitudeCapSource)]);}@@ -3738,6 +3895,74 @@ public static class BrepDisplayTessellatorreturn KernelResult<IReadOnlyList<Point3D>>.Success(pointsFallback);}+ /// <summary>+ /// Cuts an open sampled polyline at the points nearest to <paramref name="start"/> and <paramref name="end"/>,+ /// returning the portion between them in start-to-end order, or null when that is ambiguous or degenerate.+ /// </summary>+ private static Point3D[]? TrimPolylineBetween(Point3D[] samples, Point3D start, Point3D end)+ {+ if (samples.Length < 2)+ {+ return null;+ }++ static (int Segment, double T, double Distance) Locate(Point3D[] points, Point3D target)+ {+ var best = (Segment: 0, T: 0d, Distance: double.PositiveInfinity);+ for (var i = 0; i + 1 < points.Length; i++)+ {+ var edge = points[i + 1] - points[i];+ var lengthSquared = edge.Dot(edge);+ var t = lengthSquared <= 0d ? 0d : double.Clamp((target - points[i]).Dot(edge) / lengthSquared, 0d, 1d);+ var closest = points[i] + (edge * t);+ var distance = (target - closest).Length;+ if (distance < best.Distance)+ {+ best = (i, t, distance);+ }+ }++ return best;+ }++ var startLocation = Locate(samples, start);+ var endLocation = Locate(samples, end);+ const double locateTolerance = 5e-2d;+ if (startLocation.Distance > locateTolerance || endLocation.Distance > locateTolerance)+ {+ return null;+ }++ var startPosition = startLocation.Segment + startLocation.T;+ var endPosition = endLocation.Segment + endLocation.T;+ if (double.Abs(endPosition - startPosition) < 1e-9d)+ {+ return null;+ }++ var forward = startPosition < endPosition;+ var lowPosition = forward ? startPosition : endPosition;+ var highPosition = forward ? endPosition : startPosition;+ var slice = new List<Point3D>();+ var firstWhole = (int)double.Floor(lowPosition) + 1;+ var lastWhole = (int)double.Ceiling(highPosition) - 1;+ for (var i = firstWhole; i <= lastWhole && i < samples.Length; i++)+ {+ slice.Add(samples[i]);+ }++ slice.Insert(0, start);+ slice.Add(end);+ if (!forward)+ {+ // slice is currently [start, interior (ascending), end]; interior must run from start toward end.+ var interior = slice.Skip(1).Take(slice.Count - 2).Reverse().ToList();+ slice = [start, .. interior, end];+ }++ return slice.Count >= 2 ? slice.ToArray() : null;+ }+private static KernelResult<IReadOnlyList<Point3D>> SamplePlanarBSpline(BrepBody body,Coedge coedge,@@ -3771,6 +3996,24 @@ public static class BrepDisplayTessellatorCreateInvalidArgument($"Edge {coedge.EdgeId.Value} planar BSpline flattening produced an invalid sample set.", PlanarCurveFlatteningFailedSource)]);}+ // Orientation flags (coedge sense, edge sense, chain swap) can disagree with the curve's own parameter+ // direction. The snap below would then pin the wrong ends and leave a spike that self-intersects the loop,+ // so let the geometry have the last word for open curves.+ var forwardMisfit = (sampled[0] - start).Length + (sampled[^1] - end).Length;+ var reversedMisfit = (sampled[^1] - start).Length + (sampled[0] - end).Length;+ if (reversedMisfit + 1e-9d < forwardMisfit)+ {+ Array.Reverse(sampled);+ }++ if (System.Math.Min(forwardMisfit, reversedMisfit) > 1e-3d+ && TrimPolylineBetween(sampled, start, end) is { } trimmed)+ {+ // The edge only covers part of its B-spline curve and no trim interval was recorded, so sampling the+ // whole domain and snapping the ends would spike across the loop. Cut the polyline at the vertices.+ sampled = trimmed;+ }+sampled[0] = start;sampled[^1] = end;@@ -4374,6 +4617,10 @@ public static class BrepDisplayTessellatorprivate static KernelDiagnostic CreateValidationError(string message, string source)=> new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source);+ // A successful, informational classification of a trim (not a skipped or degraded face): must not surface as a warning.+ private static KernelDiagnostic CreateClassificationInfo(string message, string source)+ => new(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info, 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/PlanarDisplayLoopClassifier.cs b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarDisplayLoopClassifier.csindex 9a60261b..c11eaab1 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarDisplayLoopClassifier.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarDisplayLoopClassifier.cs@@ -45,9 +45,13 @@ internal sealed class PlanarDisplayLoopClassifierpublic IReadOnlyList<PlanarLoopClassification> Classify(int sourceFaceId, IReadOnlyList<(int LoopId, IReadOnlyList<Point3D> Points)> loops){+ // All loops of a face lie in one plane, so they must share one 2D projection. Choosing the dropped axis per+ // loop (from each loop's own Newell normal) puts loops into unrelated coordinate systems whenever the plane+ // is oblique, and holes then appear "outside" the primary loop.+ var projectionAxis = SelectProjectionAxis(loops.Select(loop => loop.Points).ToArray());var descriptors = loops.OrderBy(loop => loop.LoopId)- .Select(loop => Describe(sourceFaceId, loop.LoopId, loop.Points))+ .Select(loop => Describe(sourceFaceId, loop.LoopId, loop.Points, projectionAxis)).ToArray();if (descriptors.Length == 0)@@ -107,7 +111,7 @@ internal sealed class PlanarDisplayLoopClassifier}).ToArray();}- private static PlanarLoop2D Describe(int sourceFaceId, int loopId, IReadOnlyList<Point3D> points)+ private static PlanarLoop2D Describe(int sourceFaceId, int loopId, IReadOnlyList<Point3D> points, int projectionAxis){var diagnostics = new List<string>();if (points.Count < 3)@@ -116,7 +120,7 @@ internal sealed class PlanarDisplayLoopClassifierreturn new PlanarLoop2D(loopId, sourceFaceId, Array.Empty<PlanarDisplayPoint2D>(), points, 0d, PlanarDisplayLoopOrientation.Degenerate, default, PlanarDisplayLoopRole.Degenerate, diagnostics);}- var points2D = Project(points);+ var points2D = Project(points, projectionAxis);var area = SignedArea(points2D);for (var i = 0; i < points2D.Count; i++){@@ -147,15 +151,40 @@ internal sealed class PlanarDisplayLoopClassifierprivate static PlanarDisplayBoundingBox Bounds(IReadOnlyList<PlanarDisplayPoint2D> points) => new(points.Min(p => p.X), points.Min(p => p.Y), points.Max(p => p.X), points.Max(p => p.Y));- private static IReadOnlyList<PlanarDisplayPoint2D> Project(IReadOnlyList<Point3D> points)+ /// <summary>Returns the coordinate axis (0=X, 1=Y, 2=Z) to drop, from the loop with the largest Newell normal.</summary>+ private static int SelectProjectionAxis(IReadOnlyList<IReadOnlyList<Point3D>> loops)+ {+ var bestMagnitude = -1d;+ var bestAxis = 2;+ foreach (var points in loops)+ {+ if (points.Count < 3)+ {+ continue;+ }++ var normal = NewellNormal(points);+ var magnitude = (normal.X * normal.X) + (normal.Y * normal.Y) + (normal.Z * normal.Z);+ if (magnitude <= bestMagnitude)+ {+ continue;+ }++ bestMagnitude = magnitude;+ var ax = System.Math.Abs(normal.X);+ var ay = System.Math.Abs(normal.Y);+ var az = System.Math.Abs(normal.Z);+ bestAxis = az >= ax && az >= ay ? 2 : ay >= ax ? 1 : 0;+ }++ return bestAxis;+ }++ private static IReadOnlyList<PlanarDisplayPoint2D> Project(IReadOnlyList<Point3D> points, int projectionAxis){- var normal = NewellNormal(points);- var ax = System.Math.Abs(normal.X);- var ay = System.Math.Abs(normal.Y);- var az = System.Math.Abs(normal.Z);return points.Select(point =>- az >= ax && az >= ay ? new PlanarDisplayPoint2D(point.X, point.Y) :- ay >= ax ? new PlanarDisplayPoint2D(point.X, point.Z) :+ projectionAxis == 2 ? new PlanarDisplayPoint2D(point.X, point.Y) :+ projectionAxis == 1 ? new PlanarDisplayPoint2D(point.X, point.Z) :new PlanarDisplayPoint2D(point.Y, point.Z)).ToArray();}diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.csindex a669d017..4842ca88 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs@@ -73,14 +73,30 @@ internal static class TrimmedSurfaceTessellator// Prefer a boundary-conforming triangulation: the uniform-grid mask below leaves a staircase along every// trim curve and a gap of up to one cell between neighbouring faces. It stays as the fallback for loop sets// that are not a simple "outer minus holes" region (for example periodic wrap-around rings).+ // The conforming mesh refines by bisecting the longest edge in cell-normalized UV space. If the cells are+ // isotropic in UV although the surface only curves in one direction (a cone or cylinder), every needed split+ // across the curved direction also forces the same number of splits along the straight one. Size the cells+ // from the surface's actual turning in each direction instead.+ // Free-form B-spline patches can curve anywhere between the sampled iso-curves, so they keep the uniform+ // seed grid; the estimate is only trusted for analytic surfaces whose curvature is constant per direction.+ var (curvedU, curvedV) = surfaceKind == SurfaceGeometryKind.BSplineSurfaceWithKnots+ ? (uSegments, vSegments)+ : EstimateCurvatureSegments(evaluate, evaluateNormal, uStart, uEnd, vStart, vEnd, options);+ // Sampled straight trim edges (cone generators, cylinder rulings) arrive as many UV-collinear points. They+ // add nothing but sliver triangles, so drop vertices that lie exactly on the segment between their neighbours.+ var cellUForSimplify = (uEnd - uStart) / curvedU;+ var cellVForSimplify = (vEnd - vStart) / curvedV;+ var simplifiedLoops = normalizedLoops+ .Select(loop => RemoveCollinearVertices(loop, cellUForSimplify, cellVForSimplify))+ .ToList();var conformingPatch = BoundaryConformingTrimTessellator.TryTessellate(faceId,- normalizedLoops,+ simplifiedLoops,outerLoopIndex,evaluate,evaluateNormal,- (uEnd - uStart) / uSegments,- (vEnd - vStart) / vSegments,+ (uEnd - uStart) / curvedU,+ (vEnd - vStart) / curvedV,options,() => executionBudget?.ThrowIfExpired("TrimmedSurface.Conforming", faceId, surfaceKind));if (conformingPatch is not null)@@ -270,6 +286,116 @@ internal static class TrimmedSurfaceTessellatorreturn normalized;}+ /// <summary>+ /// Estimates how many segments each parameter direction needs to satisfy the angular and chord tolerances, from+ /// the normal turning along a few sampled iso-curves. A direction with no curvature needs a single segment.+ /// </summary>+ private static (int USegments, int VSegments) EstimateCurvatureSegments(+ Func<double, double, Point3D> evaluate,+ Func<double, double, Vector3D> evaluateNormal,+ double uStart,+ double uEnd,+ double vStart,+ double vEnd,+ DisplayTessellationOptions options)+ {+ const int samples = 16;+ const int rows = 5;++ int Estimate(bool alongU)+ {+ var bestSegments = 1;+ for (var row = 0; row < rows; row++)+ {+ var fixedT = (row + 0.5d) / rows;+ var turning = 0d;+ var length = 0d;+ Point3D? previousPoint = null;+ Vector3D? previousNormal = null;+ for (var i = 0; i <= samples; i++)+ {+ var t = (double)i / samples;+ var u = alongU ? uStart + ((uEnd - uStart) * t) : uStart + ((uEnd - uStart) * fixedT);+ var v = alongU ? vStart + ((vEnd - vStart) * fixedT) : vStart + ((vEnd - vStart) * t);+ var point = evaluate(u, v);+ var normal = evaluateNormal(u, v);+ if (previousPoint is { } p)+ {+ length += (point - p).Length;+ }++ if (previousNormal is { } n && n.Length > 1e-12d && normal.Length > 1e-12d)+ {+ turning += double.Acos(double.Clamp(n.Dot(normal) / (n.Length * normal.Length), -1d, 1d));+ }++ previousPoint = point;+ previousNormal = normal;+ }++ if (turning <= 1e-6d)+ {+ continue;+ }++ var byAngle = (int)double.Ceiling(turning / options.AngularToleranceRadians);+ var radius = length / turning;+ var ratio = double.Clamp(1d - (options.ChordTolerance / System.Math.Max(radius, 1e-9d)), -1d, 1d);+ var halfStep = double.Acos(ratio);+ var byChord = halfStep > 0d ? (int)double.Ceiling(turning / (2d * halfStep)) : 1;+ bestSegments = System.Math.Max(bestSegments, System.Math.Max(byAngle, byChord));+ }++ // Sampling can miss localized curvature; keep a small floor so bumpy patches still get a usable seed grid.+ return System.Math.Clamp(bestSegments, 1, options.MaximumSegments);+ }++ return (Estimate(alongU: true), Estimate(alongU: false));+ }++ private static List<(double U, double V)> RemoveCollinearVertices(List<(double U, double V)> loop, double cellU, double cellV)+ {+ if (loop.Count <= 3 || !(cellU > 0d) || !(cellV > 0d))+ {+ return loop;+ }++ var kept = new List<(double U, double V)>(loop);+ var changed = true;+ while (changed && kept.Count > 3)+ {+ changed = false;+ for (var i = 0; i < kept.Count && kept.Count > 3; i++)+ {+ var previous = kept[(i + kept.Count - 1) % kept.Count];+ var current = kept[i];+ var next = kept[(i + 1) % kept.Count];++ // Work in cell units so anisotropic (radians x millimetres) parameter spaces compare fairly.+ var ax = (next.U - previous.U) / cellU;+ var ay = (next.V - previous.V) / cellV;+ var bx = (current.U - previous.U) / cellU;+ var by = (current.V - previous.V) / cellV;+ var chordLengthSquared = (ax * ax) + (ay * ay);+ if (chordLengthSquared <= 1e-24d)+ {+ continue;+ }++ var along = ((ax * bx) + (ay * by)) / chordLengthSquared;+ var deviation = double.Abs((ax * by) - (ay * bx)) / double.Sqrt(chordLengthSquared);+ if (along > 0d && along < 1d && deviation <= 1e-7d)+ {+ kept.RemoveAt(i);+ i--;+ changed = true;+ }+ }+ }++ return kept;+ }+private static int ResolveSegmentCount(double span, DisplayTessellationOptions options){var ratio = span / System.Math.Max(1e-6d, options.ChordTolerance);diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.csindex d1679886..0e447feb 100644--- a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs@@ -16,7 +16,8 @@ public sealed record BSplineSurfaceWithKnotsIReadOnlyList<int> knotMultiplicitiesV,IReadOnlyList<double> knotValuesU,IReadOnlyList<double> knotValuesV,- string knotSpec)+ string knotSpec,+ IReadOnlyList<IReadOnlyList<double>>? weights = null){if (degreeU < 1 || degreeV < 1){@@ -64,8 +65,46 @@ public sealed record BSplineSurfaceWithKnotsEnsureNonDecreasing(fullKnotsU, "U");EnsureNonDecreasing(fullKnotsV, "V");+ if (weights is not null)+ {+ if (weights.Count != controlPoints.Count)+ {+ throw new ArgumentException("Weight net must have the same U cardinality as the control net.", nameof(weights));+ }++ for (var i = 0; i < weights.Count; i++)+ {+ if (weights[i] is null || weights[i].Count != controlCountV)+ {+ throw new ArgumentException("Weight net rows must have the same V cardinality as the control net.", nameof(weights));+ }++ if (weights[i].Any(w => !double.IsFinite(w) || w <= 0d))+ {+ throw new ArgumentException("Weights must be finite and strictly positive.", nameof(weights));+ }+ }++ // All-unit weights are an ordinary polynomial surface; keep that representation canonical.+ if (weights.All(row => row.All(w => double.Abs(w - 1d) <= 1e-12d)))+ {+ weights = null;+ }+ }+DegreeU = degreeU;DegreeV = degreeV;+ if (weights is not null)+ {+ Weights = weights.Select(row => row.ToArray()).ToArray();+ _weightedNet = controlPoints+ .Select((row, i) => (IReadOnlyList<Point3D>)row.Select((p, j) => new Point3D(p.X * weights[i][j], p.Y * weights[i][j], p.Z * weights[i][j])).ToArray())+ .ToArray();+ _weightNet = weights+ .Select(row => (IReadOnlyList<Point3D>)row.Select(w => new Point3D(w, 0d, 0d)).ToArray())+ .ToArray();+ }+ControlPoints = controlPoints.Select(row => row.ToArray()).ToArray();SurfaceForm = surfaceForm;UClosed = uClosed;@@ -80,6 +119,19 @@ public sealed record BSplineSurfaceWithKnotsKnotSpec = knotSpec;}+ private readonly IReadOnlyList<IReadOnlyList<Point3D>>? _weightedNet;+ private readonly IReadOnlyList<IReadOnlyList<Point3D>>? _weightNet;++ /// <summary>Rational (NURBS) weights parallel to <see cref="ControlPoints"/>; null for a polynomial surface.</summary>+ public IReadOnlyList<IReadOnlyList<double>>? Weights { get; }++ public bool IsRational => Weights is not null;++ /// <summary>Returns a copy of this surface carrying the given weight net.</summary>+ public BSplineSurfaceWithKnots WithWeights(IReadOnlyList<IReadOnlyList<double>>? weights) => new(+ DegreeU, DegreeV, ControlPoints, SurfaceForm, UClosed, VClosed, SelfIntersect,+ KnotMultiplicitiesU, KnotMultiplicitiesV, KnotValuesU, KnotValuesV, KnotSpec, weights);+public int DegreeU { get; }public int DegreeV { get; }public IReadOnlyList<IReadOnlyList<Point3D>> ControlPoints { get; }@@ -113,16 +165,28 @@ public sealed record BSplineSurfaceWithKnotsvar uClamped = ClampToDomain(u, DomainStartU, DomainEndU);var vClamped = ClampToDomain(v, DomainStartV, DomainEndV);+ if (_weightedNet is not null && _weightNet is not null)+ {+ var numerator = EvaluateNet(_weightedNet, uClamped, vClamped);+ var weight = EvaluateNet(_weightNet, uClamped, vClamped).X;+ return new Point3D(numerator.X / weight, numerator.Y / weight, numerator.Z / weight);+ }++ return EvaluateNet(ControlPoints, uClamped, vClamped);+ }++ private Point3D EvaluateNet(IReadOnlyList<IReadOnlyList<Point3D>> net, double uClamped, double vClamped)+ {if (double.Abs(uClamped - DomainEndU) <= 1e-12d && double.Abs(vClamped - DomainEndV) <= 1e-12d){- return ControlPoints[^1][^1];+ return net[^1][^1];}- var rowPoints = new Point3D[ControlPoints.Count];- for (var i = 0; i < ControlPoints.Count; i++)+ var rowPoints = new Point3D[net.Count];+ for (var i = 0; i < net.Count; i++){rowPoints[i] = EvaluateCurve(- ControlPoints[i],+ net[i],DegreeV,FullKnotsV,DomainStartV,diff --git a/Aetheris.Kernel.Core/Step242/Step242BsplineSurfaceRecoveryLane.cs b/Aetheris.Kernel.Core/Step242/Step242BsplineSurfaceRecoveryLane.csindex 5aaf65c7..f63c1d51 100644--- a/Aetheris.Kernel.Core/Step242/Step242BsplineSurfaceRecoveryLane.cs+++ b/Aetheris.Kernel.Core/Step242/Step242BsplineSurfaceRecoveryLane.cs@@ -5,171 +5,649 @@ using Aetheris.Kernel.Core.Math;namespace Aetheris.Kernel.Core.Step242;+/// <summary>+/// Recovers the analytic surface a vendor exporter encoded as a B-spline.+/// <para>+/// Aetheris keeps an analytic B-rep, so a spline face that is really a cylinder, cone, sphere, torus or plane must be+/// imported as that primitive; otherwise every later stage (trim evaluation, display, export, preflight) pays for a+/// representation the part never needed, and the file round-trips as NURBS. Exporters encode analytic geometry the+/// same way every time: one parametric direction is an exact rational circular section, the other sweeps it.+/// </para>+/// <para>+/// What separates an encoded primitive from a free-form blend that merely resembles one is exactness, not closeness.+/// Measured across the corpus, encoded primitives reproduce their sections to about 1e-14 of the part size while+/// genuine blends manage only about 1e-5 - eight orders of magnitude apart - so the section gate is set far below any+/// modelling tolerance. A candidate derived from the section family is then verified against the spline it would+/// replace, at the accuracy the source file itself declares, before it is accepted.+/// </para>+/// </summary>internal static class Step242BsplineSurfaceRecoveryLane{private const string AnalyticCylinderCandidate = "analytic_cylinder";+ private const string AnalyticConeCandidate = "analytic_cone";+ private const string AnalyticSphereCandidate = "analytic_sphere";+ private const string AnalyticTorusCandidate = "analytic_torus";private const string RejectCandidate = "reject";- private const double AxisParallelTolerance = 1e-6d;- private const double RadiusTolerance = 1e-5d;++ /// <summary>Samples taken along one candidate circular section.</summary>+ private const int SectionSampleCount = 9;++ /// <summary>Sections taken across the sweep direction.</summary>+ private const int SectionCount = 7;++ /// <summary>Grid resolution used to verify a recovered surface against the spline it replaces.</summary>+ private const int VerificationSamples = 13;++ /// <summary>Relative exactness a section must reach to count as an encoded circle rather than a blend.</summary>+ private const double SectionExactnessRelativeTolerance = 1e-9d;++ /// <summary>Ceiling on a file-declared accuracy, so one sloppy header cannot admit a wrong surface.</summary>+ private const double DeclaredAccuracyRelativeCeiling = 1e-3d;++ /// <summary>Model tolerance used when the source file declares no distance accuracy.</summary>+ private const double UndeclaredAccuracyRelativeTolerance = 1e-6d;++ private const double MinimumTolerance = 1e-12d;++ private const string NoSectionsReason = "spline sweeps no exact circular section.";++ /// <summary>A radius slope below this is a constant-radius sweep, which belongs to the cylinder candidate.</summary>+ private const double ConeMinimumRadiusSlope = 1e-9d;++ /// <summary>Fixed power iterations used to fit the sweep axis; the centres are near-collinear, so this converges at once.</summary>+ private const int AxisFitIterations = 32;internal readonly record struct RecoveryDecision(string CandidateName,SurfaceGeometry? RecoveredSurface,string Reason);- public static RecoveryDecision Decide(- Step242ParsedEntity sourceEntity,- BSplineSurfaceWithKnots surface)+ /// <summary>+ /// Decides whether <paramref name="surface"/> is an encoded analytic primitive.+ /// <paramref name="declaredAccuracyMillimetres"/> is the source file's own distance accuracy when it states one.+ /// </summary>+ public static RecoveryDecision Decide(BSplineSurfaceWithKnots surface, double? declaredAccuracyMillimetres = null){- var probe = ProbeCylinderRecovery(surface);- var context = new RecoveryContext(- IsRationalLike: Step242SubsetDecoder.TryGetConstructor(sourceEntity.Instance, "RATIONAL_B_SPLINE_SURFACE") is not null,- CylinderProbe: probe);-+ var context = RecoveryContext.Create(surface, declaredAccuracyMillimetres);var engine = new JudgmentEngine<RecoveryContext>();var judgment = engine.Evaluate(context, BuildCandidates());- if (!judgment.IsSuccess || !judgment.Selection.HasValue)- {- var reason = judgment.Rejections.Count == 0- ? "No bounded analytic recovery candidate was admissible."- : string.Join(" ", judgment.Rejections.Select(r => $"{r.CandidateName}: {r.Reason}."));- return new RecoveryDecision(RejectCandidate, null, reason);- }- if (string.Equals(judgment.Selection.Value.Candidate.Name, AnalyticCylinderCandidate, StringComparison.Ordinal)- && context.CylinderProbe.Cylinder.HasValue)+ if (judgment.Selection is { } selection){- return new RecoveryDecision(- AnalyticCylinderCandidate,- SurfaceGeometry.FromCylinder(context.CylinderProbe.Cylinder.Value),- "Recovered analytic cylinder from rational B-spline surface.");+ var probe = context.Select(selection.Candidate.Name);+ return new RecoveryDecision(selection.Candidate.Name, probe.Surface, probe.Reason);}- var rejectReason = context.IsRationalLike- ? context.CylinderProbe.Reason- : "Surface is not a rational B-spline/NURBS-like representation.";- return new RecoveryDecision(RejectCandidate, null, rejectReason);+ // Every candidate carries why it was not admissible; that list is the whole account of the decision, so it is+ // reported verbatim rather than collapsed into "unsupported".+ var reasons = judgment.Rejections+ .Select(rejection => $"{rejection.CandidateName}: {rejection.Reason}")+ .ToArray();+ return new RecoveryDecision(+ RejectCandidate,+ null,+ reasons.Length == 0 ? "No analytic recovery candidate was admissible." : string.Join(" ", reasons));}private static IReadOnlyList<JudgmentCandidate<RecoveryContext>> BuildCandidates(){+ // Scores descend with representational complexity so the simplest primitive that verifies wins.return[- new JudgmentCandidate<RecoveryContext>(- Name: AnalyticCylinderCandidate,- IsAdmissible: When.All<RecoveryContext>(- context => context.IsRationalLike,- context => context.CylinderProbe.Cylinder.HasValue),- Score: _ => 100d,- RejectionReason: context => context.IsRationalLike- ? context.CylinderProbe.Reason- : "Surface is not a rational B-spline/NURBS-like representation.",- TieBreakerPriority: 0),- new JudgmentCandidate<RecoveryContext>(- Name: RejectCandidate,- IsAdmissible: _ => true,- Score: _ => -1d,- RejectionReason: context => context.CylinderProbe.Reason,- TieBreakerPriority: 1)+ Candidate(AnalyticCylinderCandidate, context => context.Cylinder, 103d, 0),+ Candidate(AnalyticConeCandidate, context => context.Cone, 102d, 1),+ Candidate(AnalyticSphereCandidate, context => context.Sphere, 101d, 2),+ Candidate(AnalyticTorusCandidate, context => context.Torus, 100d, 3)];}- private static CylinderProbe ProbeCylinderRecovery(BSplineSurfaceWithKnots surface)+ private static JudgmentCandidate<RecoveryContext> Candidate(+ string name,+ Func<RecoveryContext, SurfaceProbe> select,+ double score,+ int priority)+ => new(+ Name: name,+ IsAdmissible: context => select(context).IsAdmissible,+ Score: _ => score,+ RejectionReason: context => select(context).Reason,+ TieBreakerPriority: priority);++ private readonly record struct SurfaceProbe(SurfaceGeometry? Surface, double Deviation, string Reason)+ {+ public bool IsAdmissible => Surface is not null;++ public static SurfaceProbe Rejected(string reason) => new(null, double.NaN, reason);+ }++ private readonly record struct CircularSection(Point3D Center, double Radius, Direction3D Normal, Point3D Start);++ private readonly record struct RecoveryContext(+ SurfaceProbe Cylinder,+ SurfaceProbe Cone,+ SurfaceProbe Sphere,+ SurfaceProbe Torus){- if (!TryReadTwoRingCubicProfile(surface, out var ring0, out var ring1))+ public SurfaceProbe Select(string candidateName) => candidateName switch+ {+ AnalyticCylinderCandidate => Cylinder,+ AnalyticConeCandidate => Cone,+ AnalyticSphereCandidate => Sphere,+ AnalyticTorusCandidate => Torus,+ _ => SurfaceProbe.Rejected($"Unknown candidate '{candidateName}'.")+ };++ public static RecoveryContext Create(BSplineSurfaceWithKnots surface, double? declaredAccuracyMillimetres){- return new CylinderProbe(null, "Surface does not match bounded 2x4 linear-by-cubic profile required for cylinder recovery.");+ var diagonal = ControlNetDiagonal(surface);+ var exactness = double.Max(diagonal * SectionExactnessRelativeTolerance, MinimumTolerance);+ var model = ResolveModelTolerance(diagonal, declaredAccuracyMillimetres);+ // Either parametric direction can carry the swept circle, and on a sphere or torus both do. Which one is+ // useful depends on the primitive - a torus is only recognisable from its minor sections - so every+ // family that passes the exactness gate is probed and the first primitive that verifies wins.+ var cylinder = SurfaceProbe.Rejected(NoSectionsReason);+ var cone = cylinder;+ var sphere = cylinder;+ var torus = cylinder;+ var probed = false;++ foreach (var alongU in new[] { true, false })+ {+ if (!TryExtractCircularSections(surface, alongU, exactness, out var sections, out var sectionReason))+ {+ if (!probed)+ {+ var rejected = SurfaceProbe.Rejected(sectionReason);+ cylinder = Preferred(cylinder, rejected);+ cone = Preferred(cone, rejected);+ sphere = Preferred(sphere, rejected);+ torus = Preferred(torus, rejected);+ }++ continue;+ }++ probed = true;+ cylinder = Preferred(cylinder, ProbeCylinder(surface, sections, model));+ cone = Preferred(cone, ProbeCone(surface, sections, model));+ sphere = Preferred(sphere, ProbeSphere(surface, sections, model));+ torus = Preferred(torus, ProbeTorus(surface, sections, model));+ }++ return new RecoveryContext(cylinder, cone, sphere, torus);}+ }++ /// <summary>Keeps an admissible probe, and otherwise the most recent account of why none was.</summary>+ private static SurfaceProbe Preferred(SurfaceProbe current, SurfaceProbe candidate)+ => current.IsAdmissible ? current : candidate;- var center0 = Midpoint(ring0[0], ring0[3]);- var center1 = Midpoint(ring1[0], ring1[3]);- var axisVector = center1 - center0;- if (axisVector.Length <= RadiusTolerance || !Direction3D.TryCreate(axisVector, out var axis))+ private static double ResolveModelTolerance(double diagonal, double? declaredAccuracyMillimetres)+ {+ var ceiling = double.Max(diagonal * DeclaredAccuracyRelativeCeiling, MinimumTolerance);+ if (declaredAccuracyMillimetres is { } declared && double.IsFinite(declared) && declared > 0d){- return new CylinderProbe(null, "Cylinder recovery requires non-degenerate axial separation between profile rings.");+ return double.Min(declared, ceiling);}- var radius0Start = (ring0[0] - center0).Length;- var radius0End = (ring0[3] - center0).Length;- var radius1Start = (ring1[0] - center1).Length;- var radius1End = (ring1[3] - center1).Length;- var radius = (radius0Start + radius0End + radius1Start + radius1End) * 0.25d;- if (!double.IsFinite(radius) || radius <= RadiusTolerance)+ return double.Max(diagonal * UndeclaredAccuracyRelativeTolerance, MinimumTolerance);+ }++ private static double ControlNetDiagonal(BSplineSurfaceWithKnots surface)+ {+ var points = surface.ControlPoints.SelectMany(row => row).ToArray();+ if (points.Length == 0){- return new CylinderProbe(null, "Cylinder recovery requires a strictly positive finite radius.");+ return 0d;}- if (double.Abs(radius0Start - radius) > RadiusTolerance- || double.Abs(radius0End - radius) > RadiusTolerance- || double.Abs(radius1Start - radius) > RadiusTolerance- || double.Abs(radius1End - radius) > RadiusTolerance)+ return new Vector3D(+ points.Max(point => point.X) - points.Min(point => point.X),+ points.Max(point => point.Y) - points.Min(point => point.Y),+ points.Max(point => point.Z) - points.Min(point => point.Z)).Length;+ }++ private static bool TryExtractCircularSections(+ BSplineSurfaceWithKnots surface,+ bool alongU,+ double exactness,+ out IReadOnlyList<CircularSection> sections,+ out string reason)+ {+ var found = new List<CircularSection>(SectionCount);+ sections = found;+ var label = alongU ? "u" : "v";+ var sweepStart = alongU ? surface.DomainStartU : surface.DomainStartV;+ var sweepEnd = alongU ? surface.DomainEndU : surface.DomainEndV;+ var acrossStart = alongU ? surface.DomainStartV : surface.DomainStartU;+ var acrossEnd = alongU ? surface.DomainEndV : surface.DomainEndU;+ var worst = 0d;++ for (var sectionIndex = 0; sectionIndex < SectionCount; sectionIndex++){- return new CylinderProbe(null, "Cylinder recovery requires ring endpoint radii to match within tolerance.");+ var across = Lerp(acrossStart, acrossEnd, sectionIndex / (double)(SectionCount - 1));+ var samples = new Point3D[SectionSampleCount];+ for (var sampleIndex = 0; sampleIndex < SectionSampleCount; sampleIndex++)+ {+ var sweep = Lerp(sweepStart, sweepEnd, sampleIndex / (double)(SectionSampleCount - 1));+ samples[sampleIndex] = alongU ? surface.Evaluate(sweep, across) : surface.Evaluate(across, sweep);+ }++ if (!TryCircleThroughPoints(samples[0], samples[SectionSampleCount / 2], samples[^1], out var center, out var radius, out var normal))+ {+ reason = $"a {label} section is straight or degenerate, so the spline sweeps no circle.";+ return false;+ }++ var axis = normal.ToVector();+ foreach (var sample in samples)+ {+ var radial = RadialDistance(sample, center, axis, out var axial);+ var deviation = double.Sqrt(((radial - radius) * (radial - radius)) + (axial * axial));+ worst = double.Max(worst, deviation);+ if (deviation > exactness)+ {+ reason = $"a {label} section departs from an exact circle by {deviation:G4} mm, above the {exactness:G4} mm exactness gate, so the spline is free-form rather than an encoded primitive.";+ return false;+ }+ }++ if (found.Count > 0 && axis.Dot(found[0].Normal.ToVector()) < 0d)+ {+ normal = Direction3D.Create(axis * -1d);+ }++ found.Add(new CircularSection(center, radius, normal, samples[0]));+ }++ reason = $"{label} sections are exact circles to {worst:G4} mm.";+ return true;+ }++ private static SurfaceProbe ProbeCylinder(BSplineSurfaceWithKnots surface, IReadOnlyList<CircularSection> sections, double tolerance)+ {+ var radius = sections.Average(section => section.Radius);+ var spread = sections.Max(section => double.Abs(section.Radius - radius));+ if (spread > tolerance)+ {+ return SurfaceProbe.Rejected($"section radii vary by {spread:G4} mm, above the {tolerance:G4} mm model tolerance, so the sweep is not a cylinder.");+ }++ if (!TryFitSweepAxis(sections, out var axis, out var origin))+ {+ return SurfaceProbe.Rejected("section centres coincide, so the sweep has no cylinder axis.");+ }++ if (!TryPerpendicularReference(sections[0].Start - origin, axis, out var reference))+ {+ return SurfaceProbe.Rejected("first section has no usable reference direction.");+ }++ try+ {+ var geometry = SurfaceGeometry.FromCylinder(new CylinderSurface(origin, axis, radius, reference));+ return Verified(surface, geometry, tolerance, $"cylinder of radius {radius:G6} mm");+ }+ catch (ArgumentException exception)+ {+ return SurfaceProbe.Rejected($"cylinder frame is degenerate ({exception.Message}).");+ }+ }++ private static SurfaceProbe ProbeCone(BSplineSurfaceWithKnots surface, IReadOnlyList<CircularSection> sections, double tolerance)+ {+ if (!TryFitSweepAxis(sections, out var axis, out var origin))+ {+ return SurfaceProbe.Rejected("section centres coincide, so the sweep has no cone axis.");}- var mid0RadiusA = (ring0[1] - center0).Length;- var mid0RadiusB = (ring0[2] - center0).Length;- var mid1RadiusA = (ring1[1] - center1).Length;- var mid1RadiusB = (ring1[2] - center1).Length;- if (mid0RadiusA <= radius || mid0RadiusB <= radius || mid1RadiusA <= radius || mid1RadiusB <= radius)+ var axials = AxialCoordinates(sections, axis, origin);+ var radii = sections.Select(section => section.Radius).ToArray();+ var (slope, radiusAtOrigin) = FitLine(axials, radii);+ if (double.Abs(slope) <= ConeMinimumRadiusSlope){- return new CylinderProbe(null, "Cylinder recovery requires rational arc control points that bulge beyond circle radius.");+ return SurfaceProbe.Rejected("sweep radius is constant, so the sweep is a cylinder rather than a cone.");}- for (var i = 0; i < 4; i++)+ for (var index = 0; index < sections.Count; index++){- var span = ring1[i] - ring0[i];- if (!Direction3D.TryCreate(span, out var spanDir))+ var expected = radiusAtOrigin + (slope * axials[index]);+ if (double.Abs(radii[index] - expected) > tolerance)+ {+ return SurfaceProbe.Rejected($"section radii are not linear along the axis (off by {double.Abs(radii[index] - expected):G4} mm, above {tolerance:G4} mm), so the sweep is not a cone.");+ }+ }++ // The cone axis runs from the apex towards the widening end; flipping it negates the axial coordinate, so the+ // radius at the origin is unchanged and only the sign of the slope moves.+ if (slope < 0d)+ {+ axis = Direction3D.Create(axis.ToVector() * -1d);+ slope = -slope;+ }++ if (radiusAtOrigin <= 0d)+ {+ return SurfaceProbe.Rejected("fitted radius at the axis origin is not positive, so no cone placement is defined.");+ }++ var semiAngle = double.Atan(slope);+ if (!TryPerpendicularReference(sections[0].Start - origin, axis, out var reference))+ {+ return SurfaceProbe.Rejected("first section has no usable reference direction.");+ }++ try+ {+ var geometry = SurfaceGeometry.FromCone(new ConeSurface(origin, axis, radiusAtOrigin, semiAngle, reference));+ return Verified(surface, geometry, tolerance, $"cone of semi-angle {semiAngle:G6} rad");+ }+ catch (ArgumentException exception)+ {+ return SurfaceProbe.Rejected($"cone frame is degenerate ({exception.Message}).");+ }+ }++ private static SurfaceProbe ProbeSphere(BSplineSurfaceWithKnots surface, IReadOnlyList<CircularSection> sections, double tolerance)+ {+ // Meridian sections of a sphere are concentric great circles: they share the sphere's own centre and radius,+ // and fix no axis of their own, so they are read directly rather than through a sweep.+ var centreSpread = sections.Max(section => (section.Center - sections[0].Center).Length);+ if (centreSpread <= tolerance)+ {+ var meridianRadius = sections.Average(section => section.Radius);+ var meridianSpread = sections.Max(section => double.Abs(section.Radius - meridianRadius));+ if (meridianSpread > tolerance)+ {+ return SurfaceProbe.Rejected($"concentric section radii vary by {meridianSpread:G4} mm, above the {tolerance:G4} mm model tolerance, so the sweep is not a sphere.");+ }++ if (!TryPerpendicularReference(sections[0].Start - sections[0].Center, sections[0].Normal, out var meridianReference)){- return new CylinderProbe(null, "Cylinder recovery requires non-degenerate rail spans between profile rings.");+ return SurfaceProbe.Rejected("concentric sections have no usable reference direction.");}- var parallel = double.Abs(spanDir.ToVector().Dot(axis.ToVector()));- if (parallel < 1d - AxisParallelTolerance)+ try{- return new CylinderProbe(null, "Cylinder recovery requires profile rails to be axis-parallel.");+ var meridianGeometry = SurfaceGeometry.FromSphere(new SphereSurface(sections[0].Center, sections[0].Normal, meridianRadius, meridianReference));+ return Verified(surface, meridianGeometry, tolerance, $"sphere of radius {meridianRadius:G6} mm");}+ catch (ArgumentException exception)+ {+ return SurfaceProbe.Rejected($"sphere frame is degenerate ({exception.Message}).");+ }+ }++ if (!TryFitSweepAxis(sections, out var axis, out var origin))+ {+ return SurfaceProbe.Rejected("section centres coincide, so the sweep has no sphere axis.");+ }++ // Latitude sections of a sphere satisfy (h - hCentre)^2 + r^2 = R^2, which is linear in h once expanded:+ // h^2 + r^2 = 2*hCentre*h + (R^2 - hCentre^2). Fitting that line gives the centre height and the radius.+ var axials = AxialCoordinates(sections, axis, origin);+ var squares = sections.Select((section, index) => (axials[index] * axials[index]) + (section.Radius * section.Radius)).ToArray();+ var (slope, intercept) = FitLine(axials, squares);+ var centreHeight = slope * 0.5d;+ var radiusSquared = intercept + (centreHeight * centreHeight);+ if (!(radiusSquared > 0d) || !double.IsFinite(radiusSquared))+ {+ return SurfaceProbe.Rejected("section radii do not resolve a finite sphere radius.");+ }++ var radius = double.Sqrt(radiusSquared);+ var center = origin + (axis.ToVector() * centreHeight);+ if (!TryPerpendicularReference(sections[0].Start - center, axis, out var reference))+ {+ return SurfaceProbe.Rejected("sphere has no usable reference direction.");+ }++ try+ {+ var geometry = SurfaceGeometry.FromSphere(new SphereSurface(center, axis, radius, reference));+ return Verified(surface, geometry, tolerance, $"sphere of radius {radius:G6} mm");+ }+ catch (ArgumentException exception)+ {+ return SurfaceProbe.Rejected($"sphere frame is degenerate ({exception.Message}).");+ }+ }++ private static SurfaceProbe ProbeTorus(BSplineSurfaceWithKnots surface, IReadOnlyList<CircularSection> sections, double tolerance)+ {+ if (sections.Count < 3)+ {+ return SurfaceProbe.Rejected("fewer than three sections, so no spine circle can be derived.");+ }++ var minorRadius = sections.Average(section => section.Radius);+ var spread = sections.Max(section => double.Abs(section.Radius - minorRadius));+ if (spread > tolerance)+ {+ return SurfaceProbe.Rejected($"minor radii vary by {spread:G4} mm, above the {tolerance:G4} mm model tolerance, so the sweep is not a torus.");+ }++ // The section centres of a torus ride its spine circle, whose plane normal is the torus axis.+ if (!TryCircleThroughPoints(sections[0].Center, sections[sections.Count / 2].Center, sections[^1].Center, out var center, out var majorRadius, out var axis))+ {+ return SurfaceProbe.Rejected("section centres are collinear, so they trace no spine circle.");+ }++ var axisVector = axis.ToVector();+ var angularTolerance = tolerance / double.Max(majorRadius, tolerance);+ foreach (var section in sections)+ {+ if (double.Abs(axisVector.Dot(section.Normal.ToVector())) > angularTolerance)+ {+ return SurfaceProbe.Rejected("section planes do not contain the spine axis, so the sweep is not a torus.");+ }++ var offAxis = double.Abs((center - section.Center).Dot(section.Normal.ToVector()));+ if (offAxis > tolerance)+ {+ return SurfaceProbe.Rejected($"spine centre lies {offAxis:G4} mm off a section plane, above the {tolerance:G4} mm model tolerance.");+ }+ }++ if (!Direction3D.TryCreate(sections[0].Center - center, out var reference))+ {+ return SurfaceProbe.Rejected("torus has no usable reference direction.");+ }++ try+ {+ var geometry = SurfaceGeometry.FromTorus(new TorusSurface(center, axis, majorRadius, minorRadius, reference));+ return Verified(surface, geometry, tolerance, $"torus of radii {majorRadius:G6}/{minorRadius:G6} mm");+ }+ catch (ArgumentException exception)+ {+ return SurfaceProbe.Rejected($"torus frame is degenerate ({exception.Message}).");+ }+ }++ private static SurfaceProbe Verified(BSplineSurfaceWithKnots surface, SurfaceGeometry geometry, double tolerance, string description)+ {+ if (!TryVerify(surface, geometry, tolerance, out var deviation))+ {+ return SurfaceProbe.Rejected($"{description} reproduces the spline only to {deviation:G4} mm, above the {tolerance:G4} mm model tolerance.");}- if (!Direction3D.TryCreate(ring0[0] - center0, out var referenceAxis))+ return new SurfaceProbe(geometry, deviation, $"{description}; reproduces the spline to {deviation:G4} mm within the {tolerance:G4} mm accuracy the source file declares.");+ }++ private static bool TryVerify(BSplineSurfaceWithKnots surface, SurfaceGeometry geometry, double tolerance, out double deviation)+ {+ deviation = 0d;+ for (var uIndex = 0; uIndex < VerificationSamples; uIndex++){- return new CylinderProbe(null, "Cylinder recovery requires a non-degenerate reference axis.");+ var u = Lerp(surface.DomainStartU, surface.DomainEndU, uIndex / (double)(VerificationSamples - 1));+ for (var vIndex = 0; vIndex < VerificationSamples; vIndex++)+ {+ var v = Lerp(surface.DomainStartV, surface.DomainEndV, vIndex / (double)(VerificationSamples - 1));+ var distance = DistanceTo(geometry, surface.Evaluate(u, v));+ if (!double.IsFinite(distance))+ {+ deviation = double.PositiveInfinity;+ return false;+ }++ deviation = double.Max(deviation, distance);+ }}- return new CylinderProbe(new CylinderSurface(center0, axis, radius, referenceAxis), "Bounded cylinder candidate is admissible.");+ return deviation <= tolerance;+ }++ private static double DistanceTo(SurfaceGeometry geometry, Point3D point)+ {+ switch (geometry.Kind)+ {+ case SurfaceGeometryKind.Plane when geometry.Plane is { } plane:+ return double.Abs((point - plane.Origin).Dot(plane.Normal.ToVector()));+ case SurfaceGeometryKind.Cylinder when geometry.Cylinder is { } cylinder:+ return double.Abs(RadialDistance(point, cylinder.Origin, cylinder.Axis.ToVector(), out _) - cylinder.Radius);+ case SurfaceGeometryKind.Cone when geometry.Cone is { } cone:+ {+ var radial = RadialDistance(point, cone.Apex, cone.Axis.ToVector(), out var axial);+ // Points behind the apex belong to the mirrored nappe, which is not the recovered face.+ return axial < 0d+ ? double.PositiveInfinity+ : double.Abs((radial * double.Cos(cone.SemiAngleRadians)) - (axial * double.Sin(cone.SemiAngleRadians)));+ }+ case SurfaceGeometryKind.Sphere when geometry.Sphere is { } sphere:+ return double.Abs((point - sphere.Center).Length - sphere.Radius);+ case SurfaceGeometryKind.Torus when geometry.Torus is { } torus:+ {+ var radial = RadialDistance(point, torus.Center, torus.Axis.ToVector(), out var axial);+ var fromSpine = radial - torus.MajorRadius;+ return double.Abs(double.Sqrt((fromSpine * fromSpine) + (axial * axial)) - torus.MinorRadius);+ }+ default:+ return double.PositiveInfinity;+ }}- private static bool TryReadTwoRingCubicProfile(BSplineSurfaceWithKnots surface, out Point3D[] ring0, out Point3D[] ring1)+ private static double RadialDistance(Point3D point, Point3D origin, Vector3D axis, out double axial){- ring0 = [];- ring1 = [];+ var delta = point - origin;+ axial = delta.Dot(axis);+ return (delta - (axis * axial)).Length;+ }- if (surface.DegreeU == 1- && surface.DegreeV == 3- && surface.ControlPoints.Count == 2- && surface.ControlPoints[0].Count == 4)+ private static bool TryCircleThroughPoints(+ Point3D first,+ Point3D second,+ Point3D third,+ out Point3D center,+ out double radius,+ out Direction3D normal)+ {+ center = first;+ radius = 0d;+ var firstSpan = second - first;+ var secondSpan = third - first;+ var cross = firstSpan.Cross(secondSpan);+ var crossLengthSquared = cross.LengthSquared;+ if (!(crossLengthSquared > 0d) || !double.IsFinite(crossLengthSquared) || !Direction3D.TryCreate(cross, out normal)){- ring0 = [surface.ControlPoints[0][0], surface.ControlPoints[0][1], surface.ControlPoints[0][2], surface.ControlPoints[0][3]];- ring1 = [surface.ControlPoints[1][0], surface.ControlPoints[1][1], surface.ControlPoints[1][2], surface.ControlPoints[1][3]];- return true;+ normal = default;+ return false;}- if (surface.DegreeU == 3- && surface.DegreeV == 1- && surface.ControlPoints.Count == 4- && surface.ControlPoints[0].Count == 2)+ var offset = ((secondSpan * firstSpan.LengthSquared) - (firstSpan * secondSpan.LengthSquared)).Cross(cross)+ * (1d / (2d * crossLengthSquared));+ center = first + offset;+ radius = offset.Length;+ return double.IsFinite(radius) && radius > 0d;+ }++ /// <summary>+ /// Fits the sweep axis through the section centres by least squares. Taking only the first and last centre makes+ /// the axis hostage to two samples' approximation error, which on a vendor cylinder was enough to push a true+ /// primitive past the file's own declared accuracy.+ /// </summary>+ private static bool TryFitSweepAxis(IReadOnlyList<CircularSection> sections, out Direction3D axis, out Point3D origin)+ {+ axis = default;+ origin = new Point3D(+ sections.Average(section => section.Center.X),+ sections.Average(section => section.Center.Y),+ sections.Average(section => section.Center.Z));++ double xx = 0d, xy = 0d, xz = 0d, yy = 0d, yz = 0d, zz = 0d;+ foreach (var section in sections){- ring0 = [surface.ControlPoints[0][0], surface.ControlPoints[1][0], surface.ControlPoints[2][0], surface.ControlPoints[3][0]];- ring1 = [surface.ControlPoints[0][1], surface.ControlPoints[1][1], surface.ControlPoints[2][1], surface.ControlPoints[3][1]];- return true;+ var delta = section.Center - origin;+ xx += delta.X * delta.X;+ xy += delta.X * delta.Y;+ xz += delta.X * delta.Z;+ yy += delta.Y * delta.Y;+ yz += delta.Y * delta.Z;+ zz += delta.Z * delta.Z;}- return false;+ var seed = sections[^1].Center - sections[0].Center;+ if (!Direction3D.TryCreate(seed, out var seeded))+ {+ return false;+ }++ var vector = seeded.ToVector();+ for (var iteration = 0; iteration < AxisFitIterations; iteration++)+ {+ var next = new Vector3D(+ (xx * vector.X) + (xy * vector.Y) + (xz * vector.Z),+ (xy * vector.X) + (yy * vector.Y) + (yz * vector.Z),+ (xz * vector.X) + (yz * vector.Y) + (zz * vector.Z));+ if (!(next.LengthSquared > 0d) || !double.IsFinite(next.LengthSquared))+ {+ break;+ }++ vector = next * (1d / next.Length);+ }++ if (vector.Dot(seed) < 0d)+ {+ vector *= -1d;+ }++ return Direction3D.TryCreate(vector, out axis);}- private static Point3D Midpoint(Point3D a, Point3D b) => new((a.X + b.X) * 0.5d, (a.Y + b.Y) * 0.5d, (a.Z + b.Z) * 0.5d);+ private static double[] AxialCoordinates(IReadOnlyList<CircularSection> sections, Direction3D axis, Point3D origin)+ {+ var axisVector = axis.ToVector();+ return sections.Select(section => (section.Center - origin).Dot(axisVector)).ToArray();+ }- private readonly record struct RecoveryContext(bool IsRationalLike, CylinderProbe CylinderProbe);+ private static (double Slope, double Intercept) FitLine(IReadOnlyList<double> xs, IReadOnlyList<double> ys)+ {+ var meanX = xs.Average();+ var meanY = ys.Average();+ var sxx = 0d;+ var sxy = 0d;+ for (var index = 0; index < xs.Count; index++)+ {+ var dx = xs[index] - meanX;+ sxx += dx * dx;+ sxy += dx * (ys[index] - meanY);+ }++ if (!(sxx > 0d))+ {+ return (0d, meanY);+ }++ var slope = sxy / sxx;+ return (slope, meanY - (slope * meanX));+ }++ private static bool TryPerpendicularReference(Vector3D candidate, Direction3D axis, out Direction3D reference)+ {+ var axisVector = axis.ToVector();+ return Direction3D.TryCreate(candidate - (axisVector * candidate.Dot(axisVector)), out reference);+ }- private readonly record struct CylinderProbe(CylinderSurface? Cylinder, string Reason);+ private static double Lerp(double start, double end, double fraction) => start + ((end - start) * fraction);}diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex 07372344..41a193fc 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -708,6 +708,23 @@ public static class Step242Exportervar knotValuesU = surface.KnotValuesU.Select(Step242TextWriter.Number).ToArray();var knotValuesV = surface.KnotValuesV.Select(Step242TextWriter.Number).ToArray();+ if (surface.Weights is { } weights)+ {+ // Rational surfaces are a complex entity; the weights must survive the round trip or the face changes shape.+ var degreeU = surface.DegreeU.ToString(System.Globalization.CultureInfo.InvariantCulture);+ var degreeV = surface.DegreeV.ToString(System.Globalization.CultureInfo.InvariantCulture);+ var weightRows = weights.Select(row => Step242TextWriter.List(row.Select(Step242TextWriter.Number).ToArray())).ToArray();+ var pointNet = Step242TextWriter.List(controlPointRows);+ var flags = $"{Step242TextWriter.Enum(surface.SurfaceForm)},{Step242TextWriter.BooleanLogical(surface.UClosed)},{Step242TextWriter.BooleanLogical(surface.VClosed)},{Step242TextWriter.BooleanLogical(surface.SelfIntersect)}";+ return writer.AddRawEntity(+ "(BOUNDED_SURFACE()"+ + $"B_SPLINE_SURFACE({degreeU},{degreeV},{pointNet},{flags})"+ + $"B_SPLINE_SURFACE_WITH_KNOTS({Step242TextWriter.List(multiplicitiesU)},{Step242TextWriter.List(multiplicitiesV)},{Step242TextWriter.List(knotValuesU)},{Step242TextWriter.List(knotValuesV)},{Step242TextWriter.Enum(surface.KnotSpec)})"+ + "GEOMETRIC_REPRESENTATION_ITEM()"+ + $"RATIONAL_B_SPLINE_SURFACE({Step242TextWriter.List(weightRows)})"+ + "REPRESENTATION_ITEM('')SURFACE())");+ }+return writer.AddEntity("B_SPLINE_SURFACE_WITH_KNOTS","$",diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex e99c5f3b..36637ab8 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -140,6 +140,9 @@ public static class Step242Importer&& !string.Equals(brepEntity.Name, "BREP_WITH_VOIDS", StringComparison.OrdinalIgnoreCase))return Step242ImportSharedUtilities.NotImplementedFailure<BrepBody>($"Entity #{rigidRootEntityId} is not an exact rigid BRep root.", "Importer.Assembly.ProductDefinitionGeometry");var shellRoleDiagnostics = new List<KernelDiagnostic>();+ // Surface binding reports what it did with each spline face (recovered as a primitive, or retained); those+ // findings are the record of how faithfully the file was read, so they travel with the imported body.+ var surfaceBindingDiagnostics = new List<KernelDiagnostic>();var shellFaceEntityIds = new List<IReadOnlyList<int>>();var isBrepWithVoids = string.Equals(brepEntity.Name, "BREP_WITH_VOIDS", StringComparison.OrdinalIgnoreCase);@@ -265,6 +268,8 @@ public static class Step242Importerreturn KernelResult<BrepBody>.Failure(bindSurfaceResult.Diagnostics);}+ surfaceBindingDiagnostics.AddRange(bindSurfaceResult.Diagnostics);+var loopData = new List<LoopBuildData>(boundRefsResult.Value.Count);foreach (var boundRef in boundRefsResult.Value){@@ -575,7 +580,7 @@ public static class Step242Importerreturn KernelResult<BrepBody>.Failure(validation.Diagnostics);}- return KernelResult<BrepBody>.Success(body, validation.Diagnostics.Concat(shellRoleDiagnostics).ToArray());+ return KernelResult<BrepBody>.Success(body, validation.Diagnostics.Concat(shellRoleDiagnostics).Concat(surfaceBindingDiagnostics).ToArray());}private static KernelResult<IReadOnlyList<int>> ReadShellFaceIds(Step242ParsedDocument document, int shellEntityId, string role, ICollection<KernelDiagnostic> diagnostics)@@ -1199,18 +1204,55 @@ public static class Step242Importerreturn KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(surfaceResult.Diagnostics);}- var recoveryDecision = Step242BsplineSurfaceRecoveryLane.Decide(surfaceToDecode, surfaceResult.Value);- if (string.Equals(recoveryDecision.CandidateName, "analytic_cylinder", StringComparison.Ordinal)- && recoveryDecision.RecoveredSurface is not null)+ var bSplineSurface = surfaceResult.Value;+ var rationalSurface = Step242SubsetDecoder.TryGetConstructor(surfaceToDecode.Instance, "RATIONAL_B_SPLINE_SURFACE");+ if (rationalSurface is not null)+ {+ // The weights have to be read before recovery runs: dropping them turns a NURBS face into a+ // different polynomial surface, and recovery would then be judging geometry the file never stated.+ var weightsResult = Step242SubsetDecoder.ReadRationalBSplineSurfaceWeights(WithConstructor(surfaceToDecode, rationalSurface));+ if (!weightsResult.IsSuccess)+ {+ return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Failure(weightsResult.Diagnostics);+ }++ try+ {+ bSplineSurface = bSplineSurface.WithWeights(weightsResult.Value);+ }+ catch (ArgumentException ex)+ {+ return FailureSurfaceBinding($"RATIONAL_B_SPLINE_SURFACE weights are inconsistent with the control net: {ex.Message}", SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineSurface"));+ }+ }++ var recoveryDecision = Step242BsplineSurfaceRecoveryLane.Decide(bSplineSurface, document.SourceDistanceAccuracyMillimetres);+ if (recoveryDecision.RecoveredSurface is { } recoveredSurface){- return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((- geometryId,- recoveryDecision.RecoveredSurface));+ return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(+ (geometryId, recoveredSurface),+ [new KernelDiagnostic(+ KernelDiagnosticCode.Unknown,+ KernelDiagnosticSeverity.Info,+ $"Spline surface #{surfaceToDecode.Id} was recovered as an analytic {recoveredSurface.Kind}: {recoveryDecision.Reason}",+ SourceFor(surfaceToDecode.Id, "Importer.Geometry.BsplineSurfaceRecovery"))]);}+ var retentionDiagnostics = bSplineSurface.IsRational+ ? new[]+ {+ new KernelDiagnostic(+ KernelDiagnosticCode.Unknown,+ KernelDiagnosticSeverity.Info,+ $"Spline surface #{surfaceToDecode.Id} is retained as a rational B-spline because no analytic primitive verified: {recoveryDecision.Reason}",+ SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineRetained"))+ }+ : [];+return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId,- SurfaceGeometry.FromBSplineSurfaceWithKnots(surfaceResult.Value)));+ SurfaceGeometry.FromBSplineSurfaceWithKnots(bSplineSurface)),+ retentionDiagnostics);}return FailureSurfaceBinding($"ADVANCED_FACE surface '{surfaceName}' is unsupported.", SourceFor(surfaceToDecode.Id, "Importer.EntityFamily"));@@ -3407,15 +3449,30 @@ public static class Step242Importercase CurveGeometryKind.BSpline3:var spline = curve.BSpline3!.Value;var splineTrim = edgeBinding.TrimInterval ?? new ParameterInterval(spline.DomainStart, spline.DomainEnd);- var splineMid = splineTrim.Start + ((splineTrim.End - splineTrim.Start) * 0.5d);- points = [spline.Evaluate(splineTrim.Start), spline.Evaluate(splineMid), spline.Evaluate(splineTrim.End)];+ // A start/mid/end polyline cuts corners of any curved B-spline by up to ~1e-2 mm, which is enough to+ // make a hole loop that hugs its outer loop look like it crosses it. Sample densely enough that the+ // classification polygon follows the curve.+ const int splineClassificationSegments = 32;+ points = new List<Point3D>(splineClassificationSegments + 1);+ for (var i = 0; i <= splineClassificationSegments; i++)+ {+ var t = i == splineClassificationSegments+ ? splineTrim.End+ : splineTrim.Start + ((splineTrim.End - splineTrim.Start) * i / splineClassificationSegments);+ points.Add(spline.Evaluate(t));+ }+break;default:points = [];break;}- if (isReversed)+ // Samples above run in curve-parameter order. ORIENTED_EDGE orientation is relative to the edge's vertex+ // order, and EDGE_CURVE same_sense says whether the curve parameter runs with or against that order, so the+ // traversal direction is the XOR of both. Ignoring same_sense=.F. reversed the samples of those edges and+ // produced huge fake gaps between consecutive coedges.+ if (isReversed ^ !edgeBinding.OrientedEdgeSense){points.Reverse();}diff --git a/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs b/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.csindex 1fb78a70..3103180c 100644--- a/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs@@ -54,6 +54,42 @@ internal static class Step242LengthUnitNormalizerreturn 1d;}+ /// <summary>+ /// Resolves the distance accuracy the source file declares for its geometry, in millimetres, or null when it+ /// declares none. This is the exporter's own statement of how exactly its entities agree, which makes it the+ /// right yardstick for deciding whether an approximated entity may be replaced by the primitive it encodes.+ /// The smallest declaration wins, and the value is scaled because unit normalization does not touch it.+ /// </summary>+ public static double? ResolveDistanceAccuracyMillimetres(IReadOnlyList<Step242ParsedEntity> entities, double millimetresPerUnit)+ {+ double? smallest = null;+ foreach (var entity in entities)+ {+ var uncertainty = Step242SubsetDecoder.TryGetConstructor(entity.Instance, "UNCERTAINTY_MEASURE_WITH_UNIT");+ if (uncertainty is null || uncertainty.Arguments.Count == 0)+ {+ continue;+ }++ var measure = uncertainty.Arguments[0] switch+ {+ Step242TypedValue typed when typed.Arguments.Count > 0 && typed.Arguments[0] is Step242NumberValue typedNumber => typedNumber.Value,+ Step242NumberValue number => number.Value,+ _ => double.NaN+ };++ var millimetres = measure * millimetresPerUnit;+ if (!double.IsFinite(millimetres) || millimetres <= 0d)+ {+ continue;+ }++ smallest = smallest is { } current ? double.Min(current, millimetres) : millimetres;+ }++ return smallest;+ }+public static IReadOnlyList<Step242ParsedEntity> Normalize(IReadOnlyList<Step242ParsedEntity> entities, double scale){if (double.Abs(scale - 1d) <= 1e-12d || scale <= 0d || !double.IsFinite(scale))diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.csindex c7b59941..b98587cf 100644--- a/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetDecoder.cs@@ -625,6 +625,42 @@ internal static class Step242SubsetDecoder}}+ /// <summary>Reads the weights_data net of a RATIONAL_B_SPLINE_SURFACE constructor.</summary>+ internal static KernelResult<IReadOnlyList<IReadOnlyList<double>>> ReadRationalBSplineSurfaceWeights(Step242ParsedEntity rationalSurfaceEntity)+ {+ const string context = "RATIONAL_B_SPLINE_SURFACE weights_data";+ const string source = "Importer.Geometry.RationalBSplineSurface";+ if (rationalSurfaceEntity.Arguments.Count < 1 || rationalSurfaceEntity.Arguments[0] is not Step242ListValue rows)+ {+ return Failure<IReadOnlyList<IReadOnlyList<double>>>(KernelDiagnosticCode.InvalidArgument, $"{context}: expected aggregate of aggregates.", source);+ }++ var net = new List<IReadOnlyList<double>>(rows.Items.Count);+ foreach (var rowValue in rows.Items)+ {+ if (rowValue is not Step242ListValue row)+ {+ return Failure<IReadOnlyList<IReadOnlyList<double>>>(KernelDiagnosticCode.InvalidArgument, $"{context}: expected aggregate rows.", source);+ }++ var values = new List<double>(row.Items.Count);+ foreach (var item in row.Items)+ {+ var number = ReadNumberCode(item, context, source);+ if (!number.IsSuccess)+ {+ return KernelResult<IReadOnlyList<IReadOnlyList<double>>>.Failure(number.Diagnostics);+ }++ values.Add(number.Value);+ }++ net.Add(values);+ }++ return KernelResult<IReadOnlyList<IReadOnlyList<double>>>.Success(net);+ }+public static KernelResult<BSplineSurfaceWithKnots> ReadBSplineSurfaceWithKnots(Step242ParsedDocument document, Step242ParsedEntity splineEntity){var degreeUResult = ReadIntArgument(splineEntity, 1, "B_SPLINE_SURFACE_WITH_KNOTS degree_u", "Importer.Geometry.BSplineSurface");diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.csindex 2541a9b1..95ef43dd 100644--- a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs@@ -57,7 +57,8 @@ internal static class Step242SubsetParservar millimetresPerUnit = Step242LengthUnitNormalizer.ResolveMillimetresPerUnit(entities);var normalizedEntities = Step242LengthUnitNormalizer.Normalize(entities, millimetresPerUnit);- return KernelResult<Step242ParsedDocument>.Success(new Step242ParsedDocument(normalizedEntities, millimetresPerUnit));+ var declaredAccuracy = Step242LengthUnitNormalizer.ResolveDistanceAccuracyMillimetres(entities, millimetresPerUnit);+ return KernelResult<Step242ParsedDocument>.Success(new Step242ParsedDocument(normalizedEntities, millimetresPerUnit, declaredAccuracy));}private static KernelResult<Step242ParsedDocument> Failure(string message, string source)@@ -582,10 +583,14 @@ internal sealed class Step242ParsedDocument{private readonly Dictionary<int, Step242ParsedEntity> _entitiesById;- public Step242ParsedDocument(IReadOnlyList<Step242ParsedEntity> entities, double sourceMillimetresPerUnit = 1d)+ public Step242ParsedDocument(+ IReadOnlyList<Step242ParsedEntity> entities,+ double sourceMillimetresPerUnit = 1d,+ double? sourceDistanceAccuracyMillimetres = null){Entities = entities;SourceMillimetresPerUnit = sourceMillimetresPerUnit;+ SourceDistanceAccuracyMillimetres = sourceDistanceAccuracyMillimetres;_entitiesById = entities.ToDictionary(e => e.Id);PlaneAngleToRadiansScale = ResolvePlaneAngleToRadiansScale();}@@ -597,6 +602,9 @@ internal sealed class Step242ParsedDocument/// <summary>Millimetres per length unit declared by the source file; entity lengths have already been multiplied by this.</summary>public double SourceMillimetresPerUnit { get; }+ /// <summary>Distance accuracy the source file declares for its geometry, in millimetres, or null when it declares none.</summary>+ public double? SourceDistanceAccuracyMillimetres { get; }+public KernelResult<Step242ParsedEntity> TryGetEntity(int id, string? expectedName = null){if (!_entitiesById.TryGetValue(id, out var entity))diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.csindex 494b7db7..9221a8e5 100644--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs@@ -292,6 +292,28 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact}}+ [Fact]+ public async Task DisplayPrepare_SurfacesKernelTessellationWarnings_InsteadOfSilentlyDroppingFaces()+ {+ var document = await CreateDocumentAsync("/api/v1/documents");+ var stepText = await File.ReadAllTextAsync(GetRepositoryPath("testdata/step242/generated/v0-expectedfail/cylinder_hole_unsupported.step"));+ var importResponse = await _client.PostAsJsonAsync(+ $"/api/v1/documents/{document.Data!.DocumentId}/import/step",+ new StepImportRequestDto(stepText, "CylinderHole"));+ importResponse.EnsureSuccessStatusCode();+ var imported = await importResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();+ Assert.True(imported!.Success);++ var prepared = await PrepareDisplayAsync(document.Data.DocumentId, imported.Data!.OccurrenceId);++ // The kernel skips the cylinder wall here and reports it only as a warning on an otherwise successful tessellation.+ var skipped = (prepared.Data!.Diagnostics ?? []).Where(d => d.Code.StartsWith("Viewer.Tessellation.", StringComparison.Ordinal)).ToArray();+ Assert.NotEmpty(skipped);+ Assert.All(skipped, d => Assert.NotNull(d.FaceId));+ Assert.All(skipped, d => Assert.DoesNotContain(prepared.Data.Faces ?? [], face => face.FaceId == d.FaceId && face.Status == "Mesh"));+ Assert.NotEqual("Complete", prepared.Data.Status);+ }+[Fact]public async Task DisplayPrepare_SameBodyTwice_IsDeterministic(){diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.csindex f87cd049..39fb2c0e 100644--- a/Aetheris.Server/Api/KernelEndpoints.cs+++ b/Aetheris.Server/Api/KernelEndpoints.cs@@ -336,10 +336,26 @@ public static class KernelEndpoints? completeBoundedMesh.Value: BrepDisplayTessellator.TessellateBoundedPartial(body, options);+ // Kernel tessellation reports skipped or degraded faces as warnings on an otherwise successful+ // result. They used to be dropped here, so a face the kernel gave up on showed up as a silent hole.+ if (completeBoundedMesh.IsSuccess)+ {+ displayDiagnostics.AddRange(completeBoundedMesh.Diagnostics+ .Where(diagnostic => diagnostic.Severity != Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Info)+ .Select(diagnostic => ToKernelWarningDisplayDiagnostic(body, diagnostic)));+ }+tessellationFallback = document.TryGetBodyTransform(bodyId, out var fallbackTransform)? ApiMappings.ToTessellationResponse(boundedMeshResult, fallbackTransform): ApiMappings.ToTessellationResponse(boundedMeshResult);+ // A patch with no triangles is a face the kernel skipped; treat it as absent so the face falls back+ // to wireframe/diagnostic display instead of claiming to be a rendered mesh.+ tessellationFallback = tessellationFallback with+ {+ FacePatches = tessellationFallback.FacePatches.Where(patch => patch.TriangleIndices.Count > 0).ToArray(),+ };+if (!completeBoundedMesh.IsSuccess && boundedMeshResult.FaceDiagnostics is { Count: > 0 }){displayDiagnostics.AddRange(boundedMeshResult.FaceDiagnostics.Select(diagnostic => new DisplayDiagnosticDto(@@ -407,7 +423,7 @@ public static class KernelEndpointsif (boundedMeshResult is not null){- var boundedMeshDiagnostics = boundedMeshResult.FaceDiagnostics?.Count ?? 0;+ var boundedMeshDiagnostics = (boundedMeshResult.FaceDiagnostics?.Count ?? 0) + displayDiagnostics.Count(diagnostic => diagnostic.Phase == "FaceTessellation" && diagnostic.Code.StartsWith("Viewer.Tessellation", StringComparison.Ordinal));var boundedMeshFaceCount = faces.Count(face => face.MaterializationLane == "BoundedMesh" && face.Status == "Mesh");var boundedMeshStatus = boundedMeshDiagnostics > 0 ? (boundedMeshFaceCount > 0 ? "Partial" : "Failed") : "Complete";displayLanes.Add(new DisplayLaneDto(@@ -625,6 +641,30 @@ public static class KernelEndpointsreturn new DisplayEdgeDto(edgeId.Value, points, sourceCurveKind, points.Count, diagnostics);}+ private static DisplayDiagnosticDto ToKernelWarningDisplayDiagnostic(BrepBody body, Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic diagnostic)+ {+ int? faceId = null;+ string? surfaceKind = null;+ var match = System.Text.RegularExpressions.Regex.Match(diagnostic.Message, @"\bFace (\d+)\b");+ if (match.Success && int.TryParse(match.Groups[1].Value, out var parsedFaceId))+ {+ faceId = parsedFaceId;+ var face = body.Topology.Faces.FirstOrDefault(candidate => candidate.Id.Value == parsedFaceId);+ if (face is not null && body.TryGetFaceSurfaceGeometry(face.Id, out var surface) && surface is not null)+ {+ surfaceKind = surface.Kind.ToString();+ }+ }++ return new DisplayDiagnosticDto(+ diagnostic.Source ?? diagnostic.Code.ToString(),+ diagnostic.Message,+ faceId,+ surfaceKind,+ "FaceTessellation",+ "Face was skipped or degraded by kernel tessellation; check the trim loops and surface of this face.");+ }+private static string ResolveDisplayLane(AnalyticDisplayPacket packet){if (packet.AnalyticFaces.Count > 0 && packet.FallbackFaces.Count == 0)diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.jsonindex 1e0a79e7..4570b209 100644--- a/testdata/step242/manifests/nist.v0.report.json+++ b/testdata/step242/manifests/nist.v0.report.json@@ -90,14 +90,14 @@"source": "Audit.None","messagePrefix": "No diagnostics."},- "diagnosticCount": 0,+ "diagnosticCount": 4,"exceptionEscaped": false,"topologyCounts": {"vertices": 239,"edges": 331,"faces": 156},- "canonicalSha256": "677c52bac98905f0a8ca68b5163d641820aa6ee633016181d96a6db0be6912c6"+ "canonicalSha256": "deaddaaefd102199a26aadf3cc6551d4f1337f90f04c2b6103febcf8f499d731"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_06_asme1_ap242-e2",@@ -163,21 +163,21 @@"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e2","path": "testdata/step242/nist/FTC/nist_ftc_08_asme1_ap242-e2.stp","sizeBytes": 4658022,- "status": "importFail",- "firstFailureLayer": "importer-topology",+ "status": "success",+ "firstFailureLayer": "","firstDiagnostic": {- "code": "ValidationFailed",- "source": "Importer.LoopRole.DisconnectedCoedges",- "messagePrefix": "Planar loop contains disconnected consecutive coedges and cannot be normalized safely. innerLoopId=1, outerLoopId=2, out"+ "code": "Unknown",+ "source": "Audit.None",+ "messagePrefix": "No diagnostics."},- "diagnosticCount": 1,+ "diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 0,- "edges": 0,- "faces": 0+ "vertices": 396,+ "edges": 616,+ "faces": 247},- "canonicalSha256": null+ "canonicalSha256": "9c816376544b3555f98e0f1885285d73a27364148e54e4ee2e3d90457f7c1893"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_09_asme1_ap242-e1",@@ -263,21 +263,21 @@"fileId": "testdata_step242_nist_STC_nist_stc_07_asme1_ap242-e3","path": "testdata/step242/nist/STC/nist_stc_07_asme1_ap242-e3.stp","sizeBytes": 1927905,- "status": "importFail",- "firstFailureLayer": "importer-topology",+ "status": "success",+ "firstFailureLayer": "","firstDiagnostic": {- "code": "ValidationFailed",- "source": "Importer.LoopRole.DisconnectedCoedges",- "messagePrefix": "Planar loop contains disconnected consecutive coedges and cannot be normalized safely. innerLoopId=328, outerLoopId=326,"+ "code": "Unknown",+ "source": "Audit.None",+ "messagePrefix": "No diagnostics."},- "diagnosticCount": 1,+ "diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 0,- "edges": 0,- "faces": 0+ "vertices": 588,+ "edges": 871,+ "faces": 306},- "canonicalSha256": null+ "canonicalSha256": "07ebd127a871a8d36ef34b153ee2435cdaf5031463c1eb36ce42fa5d40b5ba6c"},{"fileId": "testdata_step242_nist_STC_nist_stc_08_asme1_ap242-e3",@@ -323,20 +323,20 @@"fileId": "testdata_step242_nist_STC_nist_stc_10_asme1_ap242-e2","path": "testdata/step242/nist/STC/nist_stc_10_asme1_ap242-e2.stp","sizeBytes": 4807322,- "status": "importFail",- "firstFailureLayer": "importer-topology",+ "status": "success",+ "firstFailureLayer": "","firstDiagnostic": {- "code": "ValidationFailed",- "source": "Importer.LoopRole.DisconnectedCoedges",- "messagePrefix": "Planar loop contains disconnected consecutive coedges and cannot be normalized safely. innerLoopId=4, outerLoopId=2, out"+ "code": "Unknown",+ "source": "Audit.None",+ "messagePrefix": "No diagnostics."},"diagnosticCount": 1,"exceptionEscaped": false,"topologyCounts": {- "vertices": 0,- "edges": 0,- "faces": 0+ "vertices": 368,+ "edges": 551,+ "faces": 256},- "canonicalSha256": null+ "canonicalSha256": "0eee08920035167420c527992ee2fcad8b9091fb644f4b21e8438eac5aa1b845"}]