Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Generalized analytical/non-rational recovery.
Yuechen Lia07bdb344b0a
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.csindex 3aef778a..0b2bbf26 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/NistDisplayCorpusRegressionTests.cs@@ -46,38 +46,74 @@ public sealed class NistDisplayCorpusRegressionTestsAssert.DoesNotContain(display.Value.FacePatches, patch => patch.TriangleIndices.Count == 0);}+ /// <summary>+ /// The weights decide where the surface actually is, so they have to be read even though the reduction means they+ /// do not survive import: the stored non-rational surface must follow the geometry the file stated, not the+ /// different polynomial surface you get by ignoring them.+ /// </summary>[Fact]- public void RationalBSplineSurface_ImportKeepsWeights_SoTheFaceMatchesItsBoundaryEdges()+ public void RationalBSplineSurface_WeightsAreHonoured_EvenThoughTheyDoNotSurviveImport(){- 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 stepText = File.ReadAllText(Path.Combine(FindRepoRoot(), "testdata", "step242", "nist", "CTC", "nist_ctc_05_asme1_ap242-e1.stp"));- 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();+ BSplineSurfaceWithKnots[] asStated;+ using (Step242Importer.PreserveRationalSurfaces())+ {+ var preserved = Step242Importer.ImportBody(stepText);+ Assert.True(preserved.IsSuccess);+ asStated = SplineSurfaces(preserved.Value);+ }++ var stored = SplineSurfaces(Step242Importer.ImportBody(stepText).Value);- Assert.NotEmpty(rational);- Assert.Contains(rational, surface => surface!.IsRational);+ Assert.NotEmpty(asStated);+ Assert.All(asStated, surface => Assert.True(surface.IsRational));+ Assert.All(stored, surface => Assert.False(surface.IsRational));+ Assert.Equal(asStated.Length, stored.Length);++ // One tenth of the 0.0165 mm accuracy this file declares for its own geometry.+ const double budget = 1.655e-3d;+ foreach (var (rational, reduced) in asStated.Zip(stored))+ {+ for (var indexU = 0; indexU <= 8; indexU++)+ {+ var u = rational.DomainStartU + ((rational.DomainEndU - rational.DomainStartU) * indexU / 8d);+ for (var indexV = 0; indexV <= 8; indexV++)+ {+ var v = rational.DomainStartV + ((rational.DomainEndV - rational.DomainStartV) * indexV / 8d);+ Assert.True((rational.Evaluate(u, v) - reduced.Evaluate(u, v)).Length <= budget);+ }+ }+ }}+ /// <summary>The debug path has to stay whole: preserved rationals must export and come back as rationals.</summary>[Fact]- public void RationalBSplineSurface_SurvivesStepRoundTrip()+ public void PreservedRationalSurfaces_SurviveAStepRoundTrip(){- var import = Step242Importer.ImportBody(File.ReadAllText(Path.Combine(FindRepoRoot(), "testdata", "step242", "nist", "CTC", "nist_ctc_05_asme1_ap242-e1.stp")));+ var stepText = File.ReadAllText(Path.Combine(FindRepoRoot(), "testdata", "step242", "nist", "CTC", "nist_ctc_05_asme1_ap242-e1.stp"));++ using var scope = Step242Importer.PreserveRationalSurfaces();+ var import = Step242Importer.ImportBody(stepText);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));+ Assert.Equal(SplineSurfaces(import.Value).Count(surface => surface.IsRational), SplineSurfaces(reimport.Value).Count(surface => surface.IsRational));}+ private static BSplineSurfaceWithKnots[] SplineSurfaces(Aetheris.Kernel.Core.Brep.BrepBody body)+ => body.Geometry.Surfaces+ .OrderBy(surface => surface.Key.Value)+ .Select(surface => surface.Value.BSplineSurfaceWithKnots)+ .Where(surface => surface is not null)+ .Select(surface => surface!)+ .ToArray();+[Fact]public void RationalBSplineSurface_EvaluatesExactCircularArc(){diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.csindex 3667691f..0372ee55 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242BsplineSurfaceRecoveryTests.cs@@ -88,20 +88,21 @@ public sealed class Step242BsplineSurfaceRecoveryTests}/// <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.+ /// CTC-05's rational faces are five-sided vertex blends, not primitives. Import says which primitives it weighed+ /// and on what measurement it rejected each, rather than reporting an unexplained "unsupported"./// </summary>[Fact]- public void NistCtc05VertexBlends_AreRetainedWithAMeasuredReason()+ public void NistCtc05VertexBlends_ReportEveryPrimitiveTheyWereMeasuredAgainst(){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))+ var rejected = import.Diagnostics+ .Where(diagnostic => (diagnostic.Source ?? string.Empty).Contains("RationalBSplineReduced", StringComparison.Ordinal)).ToArray();- Assert.Equal(4, retained.Length);- Assert.All(retained, diagnostic => Assert.Contains("analytic_torus", diagnostic.Message, StringComparison.Ordinal));+ Assert.Equal(4, rejected.Length);+ Assert.All(rejected, diagnostic => Assert.Contains("analytic_torus", diagnostic.Message, StringComparison.Ordinal));+ Assert.All(rejected, diagnostic => Assert.Contains("analytic_cylinder", diagnostic.Message, StringComparison.Ordinal));}[Fact]diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.csnew file mode 100644index 00000000..2f8fff15--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalSurfaceReductionTests.cs@@ -0,0 +1,151 @@+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>+/// Blends that no analytic primitive covers still must not enter the kernel as NURBS. These cover the reduction that+/// replaces them with a non-rational spline inside the accuracy the source file declares, and the debug switch that+/// turns it off when a degenerate legacy surface needs to be looked at as the file stated it.+/// </summary>+public sealed class Step242RationalSurfaceReductionTests+{+ public static TheoryData<string> CorpusFiles => new()+ {+ "testdata/step242/nist/CTC/nist_ctc_02_asme1_ap242-e2.stp",+ "testdata/step242/nist/CTC/nist_ctc_05_asme1_ap242-e1.stp",+ "testdata/step242/nist/FTC/nist_ftc_07_asme1_ap242-e2.stp",+ "testdata/step242/nist/FTC/nist_ftc_10_asme1_ap242-e2.stp",+ "testdata/step242/nist/STC/nist_stc_07_asme1_ap242-e3.stp",+ "testdata/step242/nist/STC/nist_stc_10_asme1_ap242-e2.stp",+ "testdata/step242/OCCT/rod.step",+ "testdata/step242/OCCT/bolt001.step",+ };++ /// <summary>The invariant the whole lane exists to hold: an imported body carries no rational surface.</summary>+ [Theory]+ [MemberData(nameof(CorpusFiles))]+ public void ImportedBody_CarriesNoRationalSurface(string relativePath)+ {+ var import = Step242Importer.ImportBody(ReadFixture(relativePath));++ Assert.True(import.IsSuccess);+ Assert.Equal(0, CountRationalSurfaces(import.Value));+ }++ [Theory]+ [MemberData(nameof(CorpusFiles))]+ public void ExportedFile_ContainsNoRationalSurface(string relativePath)+ {+ var import = Step242Importer.ImportBody(ReadFixture(relativePath));+ Assert.True(import.IsSuccess);++ var exported = Step242Exporter.ExportBody(import.Value);++ Assert.True(exported.IsSuccess);+ Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", exported.Value, StringComparison.Ordinal);+ }++ [Fact]+ public void NistVertexBlends_AreReducedAndSayHowCloselyTheyFollowTheOriginal()+ {+ var import = Step242Importer.ImportBody(ReadFixture("testdata/step242/nist/CTC/nist_ctc_05_asme1_ap242-e1.stp"));++ Assert.True(import.IsSuccess);+ var reduced = import.Diagnostics+ .Where(diagnostic => (diagnostic.Source ?? string.Empty).Contains("RationalBSplineReduced", StringComparison.Ordinal))+ .ToArray();+ Assert.Equal(4, reduced.Length);+ Assert.All(reduced, diagnostic => Assert.Contains("at matched parameters", diagnostic.Message, StringComparison.Ordinal));+ }++ /// <summary>+ /// The debug switch has to give back exactly what the file stated, rationals included, and export has to write+ /// them, or it is no use for diagnosing a surface that the reduction mishandled.+ /// </summary>+ [Fact]+ public void PreserveRationalSurfaces_KeepsTheFileAsStated_AndExportsItRational()+ {+ var stepText = ReadFixture("testdata/step242/nist/CTC/nist_ctc_05_asme1_ap242-e1.stp");++ using (Step242Importer.PreserveRationalSurfaces())+ {+ var preserved = Step242Importer.ImportBody(stepText);+ Assert.True(preserved.IsSuccess);+ Assert.Equal(4, CountRationalSurfaces(preserved.Value));++ var exported = Step242Exporter.ExportBody(preserved.Value);+ Assert.True(exported.IsSuccess);+ Assert.Contains("RATIONAL_B_SPLINE_SURFACE", exported.Value, StringComparison.Ordinal);+ }++ var afterScope = Step242Importer.ImportBody(stepText);+ Assert.True(afterScope.IsSuccess);+ Assert.Equal(0, CountRationalSurfaces(afterScope.Value));+ }++ /// <summary>+ /// Reduction is measured at matched parameters, not closest point, so the parameter map moves no further than the+ /// geometry does and trim intervals keep meaning what they meant.+ /// </summary>+ [Fact]+ public void Reduction_FollowsTheRationalSurfaceAtTheSameParameters_AndKeepsItsDomain()+ {+ var rational = Step242OcctCylinderRecoveryTests.CreateExactRationalCylinder(radius: 5d, height: 10d);+ // Twenty nanometres on a 5 mm radius: two orders below any CAD accuracy, and far inside what the refinement+ // cap can reach for a quadratic section.+ const double tolerance = 1e-4d;++ Assert.True(BSplineSurfaceRationalReduction.TryReduce(rational, tolerance, out var reduced, out var deviation, out _));++ Assert.NotNull(reduced);+ Assert.False(reduced!.IsRational);+ Assert.True(deviation <= tolerance, $"deviation {deviation} exceeded {tolerance}");+ Assert.Equal(rational.DomainStartU, reduced.DomainStartU, 12);+ Assert.Equal(rational.DomainEndU, reduced.DomainEndU, 12);+ Assert.Equal(rational.DomainStartV, reduced.DomainStartV, 12);+ Assert.Equal(rational.DomainEndV, reduced.DomainEndV, 12);++ for (var indexU = 0; indexU <= 20; indexU++)+ {+ var u = rational.DomainStartU + ((rational.DomainEndU - rational.DomainStartU) * indexU / 20d);+ for (var indexV = 0; indexV <= 20; indexV++)+ {+ var v = rational.DomainStartV + ((rational.DomainEndV - rational.DomainStartV) * indexV / 20d);+ Assert.True((rational.Evaluate(u, v) - reduced.Evaluate(u, v)).Length <= tolerance);+ }+ }+ }++ /// <summary>A tighter budget has to buy a closer fit, or the refinement is not doing anything.</summary>+ [Fact]+ public void Reduction_TightensTheFitWhenTheBudgetTightens()+ {+ var rational = Step242OcctCylinderRecoveryTests.CreateExactRationalCylinder(radius: 5d, height: 10d);++ Assert.True(BSplineSurfaceRationalReduction.TryReduce(rational, 1e-3d, out var loose, out var looseDeviation, out _));+ Assert.True(BSplineSurfaceRationalReduction.TryReduce(rational, 1e-5d, out var tight, out var tightDeviation, out _));++ Assert.True(tightDeviation < looseDeviation);+ Assert.True(tight!.ControlPoints[0].Count > loose!.ControlPoints[0].Count);++ // Only the rational direction earns the extra spans; the ruled direction is already exact.+ Assert.Equal(rational.ControlPoints.Count, tight.ControlPoints.Count);+ }++ [Fact]+ public void ReductionBudget_IsOneTenthOfTheAccuracyTheFileDeclares()+ {+ var rational = Step242OcctCylinderRecoveryTests.CreateExactRationalCylinder(radius: 5d, height: 10d);++ Assert.Equal(5e-4d, BSplineSurfaceRationalReduction.ResolveTolerance(rational, 5e-3d), 12);+ }++ private static int CountRationalSurfaces(Aetheris.Kernel.Core.Brep.BrepBody body)+ => body.Geometry.Surfaces.Count(surface => surface.Value.BSplineSurfaceWithKnots is { IsRational: true });++ private static string ReadFixture(string relativePath)+ => File.ReadAllText(Path.Combine(Step242CorpusManifestRunner.RepoRoot(), relativePath.Replace('/', Path.DirectorySeparatorChar)));+}diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.csnew file mode 100644index 00000000..cef1e92b--- /dev/null+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs@@ -0,0 +1,483 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Core.Geometry.Surfaces;++/// <summary>+/// Replaces a rational (NURBS) surface with a non-rational B-spline that follows it within a stated tolerance.+/// <para>+/// Aetheris carries analytic geometry, and a spline face that is really a primitive is recovered as one. What is left+/// over are genuine free-form blends: variable-radius fillets and vertex blends that no primitive describes. Those+/// still must not enter the kernel as NURBS, because a second surface representation costs every later stage a second+/// code path. Since a circular section is not polynomial, the reduction is an approximation by construction, and the+/// only honest way to run it is against a budget the source file itself sets.+/// </para>+/// <para>+/// The reduction refines the knot vectors inside the existing domain and interpolates the rational surface at the+/// refined basis's Greville abscissae. Refinement leaves the domain and the parameter map alone, and interpolating at+/// matched parameters keeps the parameter map to within the same budget as the geometry, so trim intervals and+/// pcurves stay meaningful rather than merely landing somewhere on the new surface.+/// </para>+/// </summary>+internal static class BSplineSurfaceRationalReduction+{+ /// <summary>Fraction of the source file's declared accuracy the reduction is required to stay inside.</summary>+ private const double DeclaredAccuracyFraction = 0.1d;++ /// <summary>Budget relative to the control net when a file declares no accuracy of its own.</summary>+ private const double UndeclaredAccuracyRelativeTolerance = 1e-7d;++ private const double MinimumTolerance = 1e-12d;++ /// <summary>+ /// Knot refinement converges as the span size to the degree plus one, so a handful of doublings is decisive; a+ /// cap keeps a pathological surface from growing an enormous control net instead of failing honestly.+ /// </summary>+ private const int MaximumSpanSubdivision = 32;++ private const int DeviationSamplesPerSpan = 3;+ private const int MinimumDeviationSamples = 24;+ private const int MaximumDeviationSamples = 160;++ /// <summary>The budget this reduction must meet, from the accuracy the source file declares for its geometry.</summary>+ public static double ResolveTolerance(BSplineSurfaceWithKnots surface, double? declaredAccuracyMillimetres)+ {+ if (declaredAccuracyMillimetres is { } declared && double.IsFinite(declared) && declared > 0d)+ {+ return double.Max(declared * DeclaredAccuracyFraction, MinimumTolerance);+ }++ return double.Max(ControlNetDiagonal(surface) * UndeclaredAccuracyRelativeTolerance, MinimumTolerance);+ }++ public static bool TryReduce(+ BSplineSurfaceWithKnots surface,+ double tolerance,+ out BSplineSurfaceWithKnots? reduced,+ out double deviation,+ out string reason)+ {+ reduced = null;+ deviation = double.PositiveInfinity;++ if (!surface.IsRational)+ {+ reason = "surface is already non-rational.";+ return false;+ }++ // Refinement subdivides the spans between declared knots, which only describes the domain when the vector is+ // clamped to it. An unclamped vector is left alone rather than reinterpreted.+ if (!IsClamped(surface.KnotMultiplicitiesU, surface.DegreeU) || !IsClamped(surface.KnotMultiplicitiesV, surface.DegreeV))+ {+ reason = "knot vectors are not clamped to the surface domain, so the spans cannot be refined safely.";+ return false;+ }++ var best = double.PositiveInfinity;++ BSplineSurfaceWithKnots? Attempt(int subdivisionU, int subdivisionV)+ {+ var refinedU = Subdivide(surface.KnotValuesU, surface.KnotMultiplicitiesU, subdivisionU);+ var refinedV = Subdivide(surface.KnotValuesV, surface.KnotMultiplicitiesV, subdivisionV);+ if (!TryInterpolate(surface, refinedU, refinedV, out var attempt) || attempt is null)+ {+ return null;+ }++ var measured = MaximumDeviation(surface, attempt);+ best = double.Min(best, measured);+ return measured <= tolerance ? attempt : null;+ }++ // Refine both directions together until the budget is met, then relax each one on its own. Only the+ // directions that actually carry the rational sections need the extra spans, and a control net refined+ // where it did not need to be costs every later evaluation and every exported point for nothing.+ var uniform = 0;+ for (var subdivision = 1; subdivision <= MaximumSpanSubdivision; subdivision *= 2)+ {+ if (Attempt(subdivision, subdivision) is not null)+ {+ uniform = subdivision;+ break;+ }+ }++ if (uniform == 0)+ {+ deviation = best;+ reason = $"no refinement up to {MaximumSpanSubdivision} spans per knot interval followed the rational surface to {tolerance:G4} mm (closest {best:G4} mm)";+ return false;+ }++ var subdivisionU = uniform;+ var subdivisionV = uniform;+ for (var trial = uniform / 2; trial >= 1; trial /= 2)+ {+ if (Attempt(trial, subdivisionV) is null)+ {+ break;+ }++ subdivisionU = trial;+ }++ for (var trial = uniform / 2; trial >= 1; trial /= 2)+ {+ if (Attempt(subdivisionU, trial) is null)+ {+ break;+ }++ subdivisionV = trial;+ }++ var final = Attempt(subdivisionU, subdivisionV);+ if (final is null)+ {+ deviation = best;+ reason = $"refinement was not reproducible for the relaxed span counts {subdivisionU}x{subdivisionV}";+ return false;+ }++ reduced = final;+ deviation = MaximumDeviation(surface, final);+ reason = $"follows the rational surface to {deviation:G4} mm at matched parameters, within the {tolerance:G4} mm budget, using a {final.ControlPoints.Count}x{final.ControlPoints[0].Count} control net";+ return true;+ }++ private static bool IsClamped(IReadOnlyList<int> multiplicities, int degree)+ => multiplicities.Count >= 2 && multiplicities[0] == degree + 1 && multiplicities[^1] == degree + 1;++ /// <summary>Splits every interval between declared knots into <paramref name="subdivision"/> equal parts.</summary>+ private static (double[] Values, int[] Multiplicities) Subdivide(IReadOnlyList<double> values, IReadOnlyList<int> multiplicities, int subdivision)+ {+ var refinedValues = new List<double>(values.Count * subdivision) { values[0] };+ var refinedMultiplicities = new List<int>(values.Count * subdivision) { multiplicities[0] };++ for (var index = 0; index + 1 < values.Count; index++)+ {+ var start = values[index];+ var end = values[index + 1];+ for (var step = 1; step < subdivision; step++)+ {+ refinedValues.Add(start + ((end - start) * step / subdivision));+ refinedMultiplicities.Add(1);+ }++ refinedValues.Add(end);+ refinedMultiplicities.Add(multiplicities[index + 1]);+ }++ return (refinedValues.ToArray(), refinedMultiplicities.ToArray());+ }++ private static bool TryInterpolate(+ BSplineSurfaceWithKnots surface,+ (double[] Values, int[] Multiplicities) refinedU,+ (double[] Values, int[] Multiplicities) refinedV,+ out BSplineSurfaceWithKnots? candidate)+ {+ candidate = null;+ var knotsU = Expand(refinedU.Values, refinedU.Multiplicities);+ var knotsV = Expand(refinedV.Values, refinedV.Multiplicities);+ var countU = knotsU.Length - surface.DegreeU - 1;+ var countV = knotsV.Length - surface.DegreeV - 1;+ if (countU < surface.DegreeU + 1 || countV < surface.DegreeV + 1)+ {+ return false;+ }++ var sitesU = GrevilleAbscissae(knotsU, surface.DegreeU, countU);+ var sitesV = GrevilleAbscissae(knotsV, surface.DegreeV, countV);+ var collocationU = Collocation(knotsU, surface.DegreeU, countU, sitesU);+ var collocationV = Collocation(knotsV, surface.DegreeV, countV, sitesV);++ var permutationU = new int[countU];+ var permutationV = new int[countV];+ if (!TryFactor(collocationU, permutationU) || !TryFactor(collocationV, permutationV))+ {+ return false;+ }++ // Interpolate along u for every v site, then along v: the tensor-product system separates.+ var intermediate = new Vector3D[countV][];+ var column = new Vector3D[countU];+ for (var siteV = 0; siteV < countV; siteV++)+ {+ for (var siteU = 0; siteU < countU; siteU++)+ {+ column[siteU] = surface.Evaluate(sitesU[siteU], sitesV[siteV]) - Point3D.Origin;+ }++ intermediate[siteV] = Solve(collocationU, permutationU, column);+ }++ var net = new IReadOnlyList<Point3D>[countU];+ var row = new Vector3D[countV];+ for (var indexU = 0; indexU < countU; indexU++)+ {+ for (var siteV = 0; siteV < countV; siteV++)+ {+ row[siteV] = intermediate[siteV][indexU];+ }++ net[indexU] = Solve(collocationV, permutationV, row).Select(vector => Point3D.Origin + vector).ToArray();+ }++ try+ {+ candidate = new BSplineSurfaceWithKnots(+ surface.DegreeU,+ surface.DegreeV,+ net,+ surface.SurfaceForm,+ surface.UClosed,+ surface.VClosed,+ surface.SelfIntersect,+ refinedU.Multiplicities,+ refinedV.Multiplicities,+ refinedU.Values,+ refinedV.Values,+ "UNSPECIFIED");+ return true;+ }+ catch (ArgumentException)+ {+ return false;+ }+ }++ /// <summary>Largest gap between the two surfaces at the same parameters, which also bounds the parameter drift.</summary>+ private static double MaximumDeviation(BSplineSurfaceWithKnots surface, BSplineSurfaceWithKnots candidate)+ {+ var samplesU = SampleCount(candidate.KnotValuesU.Count);+ var samplesV = SampleCount(candidate.KnotValuesV.Count);+ var worst = 0d;+ for (var indexU = 0; indexU < samplesU; indexU++)+ {+ var u = Lerp(surface.DomainStartU, surface.DomainEndU, indexU / (double)(samplesU - 1));+ for (var indexV = 0; indexV < samplesV; indexV++)+ {+ var v = Lerp(surface.DomainStartV, surface.DomainEndV, indexV / (double)(samplesV - 1));+ var gap = (surface.Evaluate(u, v) - candidate.Evaluate(u, v)).Length;+ if (!double.IsFinite(gap))+ {+ return double.PositiveInfinity;+ }++ worst = double.Max(worst, gap);+ }+ }++ return worst;+ }++ private static int SampleCount(int distinctKnotCount)+ => System.Math.Clamp((distinctKnotCount - 1) * DeviationSamplesPerSpan, MinimumDeviationSamples, MaximumDeviationSamples);++ private static double[] Expand(IReadOnlyList<double> values, IReadOnlyList<int> multiplicities)+ {+ var knots = new List<double>();+ for (var index = 0; index < values.Count; index++)+ {+ for (var repeat = 0; repeat < multiplicities[index]; repeat++)+ {+ knots.Add(values[index]);+ }+ }++ return knots.ToArray();+ }++ /// <summary>+ /// Greville abscissae are the natural interpolation sites for a B-spline basis: one per control point, each+ /// inside its own function's support, which is what makes the collocation matrix invertible.+ /// </summary>+ private static double[] GrevilleAbscissae(IReadOnlyList<double> knots, int degree, int count)+ {+ var sites = new double[count];+ for (var index = 0; index < count; index++)+ {+ var sum = 0d;+ for (var offset = 1; offset <= degree; offset++)+ {+ sum += knots[index + offset];+ }++ sites[index] = sum / degree;+ }++ return sites;+ }++ private static double[,] Collocation(IReadOnlyList<double> knots, int degree, int count, IReadOnlyList<double> sites)+ {+ var matrix = new double[count, count];+ for (var siteIndex = 0; siteIndex < count; siteIndex++)+ {+ var span = FindSpan(count, degree, knots, sites[siteIndex]);+ var values = BasisValues(span, sites[siteIndex], degree, knots);+ for (var offset = 0; offset <= degree; offset++)+ {+ matrix[siteIndex, span - degree + offset] = values[offset];+ }+ }++ return matrix;+ }++ private static int FindSpan(int count, int degree, IReadOnlyList<double> knots, double parameter)+ {+ var last = count - 1;+ if (parameter >= knots[last + 1])+ {+ return last;+ }++ if (parameter <= knots[degree])+ {+ return degree;+ }++ var low = degree;+ var high = last + 1;+ var mid = (low + high) / 2;+ while (parameter < knots[mid] || parameter >= knots[mid + 1])+ {+ if (parameter < knots[mid])+ {+ high = mid;+ }+ else+ {+ low = mid;+ }++ mid = (low + high) / 2;+ }++ return mid;+ }++ private static double[] BasisValues(int span, double parameter, int degree, IReadOnlyList<double> knots)+ {+ var values = new double[degree + 1];+ var left = new double[degree + 1];+ var right = new double[degree + 1];+ values[0] = 1d;+ for (var level = 1; level <= degree; level++)+ {+ left[level] = parameter - knots[span + 1 - level];+ right[level] = knots[span + level] - parameter;+ var saved = 0d;+ for (var index = 0; index < level; index++)+ {+ var denominator = right[index + 1] + left[level - index];+ var scaled = denominator == 0d ? 0d : values[index] / denominator;+ values[index] = saved + (right[index + 1] * scaled);+ saved = left[level - index] * scaled;+ }++ values[level] = saved;+ }++ return values;+ }++ private static bool TryFactor(double[,] matrix, int[] permutation)+ {+ var size = permutation.Length;+ for (var index = 0; index < size; index++)+ {+ permutation[index] = index;+ }++ for (var column = 0; column < size; column++)+ {+ var pivotRow = column;+ var best = double.Abs(matrix[column, column]);+ for (var row = column + 1; row < size; row++)+ {+ var magnitude = double.Abs(matrix[row, column]);+ if (magnitude > best)+ {+ best = magnitude;+ pivotRow = row;+ }+ }++ if (!(best > 0d))+ {+ return false;+ }++ if (pivotRow != column)+ {+ for (var index = 0; index < size; index++)+ {+ (matrix[column, index], matrix[pivotRow, index]) = (matrix[pivotRow, index], matrix[column, index]);+ }++ (permutation[column], permutation[pivotRow]) = (permutation[pivotRow], permutation[column]);+ }++ for (var row = column + 1; row < size; row++)+ {+ var factor = matrix[row, column] / matrix[column, column];+ matrix[row, column] = factor;+ for (var index = column + 1; index < size; index++)+ {+ matrix[row, index] -= factor * matrix[column, index];+ }+ }+ }++ return true;+ }++ private static Vector3D[] Solve(double[,] factored, int[] permutation, IReadOnlyList<Vector3D> rightHandSide)+ {+ var size = permutation.Length;+ var forward = new Vector3D[size];+ for (var row = 0; row < size; row++)+ {+ var sum = rightHandSide[permutation[row]];+ for (var column = 0; column < row; column++)+ {+ sum -= factored[row, column] * forward[column];+ }++ forward[row] = sum;+ }++ var solution = new Vector3D[size];+ for (var row = size - 1; row >= 0; row--)+ {+ var sum = forward[row];+ for (var column = row + 1; column < size; column++)+ {+ sum -= factored[row, column] * solution[column];+ }++ solution[row] = sum * (1d / factored[row, row]);+ }++ return solution;+ }++ private static double ControlNetDiagonal(BSplineSurfaceWithKnots surface)+ {+ var points = surface.ControlPoints.SelectMany(row => row).ToArray();+ if (points.Length == 0)+ {+ return 0d;+ }++ 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 double Lerp(double start, double end, double fraction) => start + ((end - start) * fraction);+}diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 36637ab8..12e417e4 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -59,6 +59,23 @@ public static class Step242Importerprivate static readonly AsyncLocal<ICollection<LoopRoleTorusProjectionDiagnostic>?> TorusProjectionDiagnosticsSink = new();private static readonly AsyncLocal<ICollection<PlanarMultiBoundJudgmentDiagnostic>?> PlanarMultiBoundJudgmentDiagnosticsSink = new();+ private static readonly AsyncLocal<bool> PreserveRationalSurfacesFlag = new();++ /// <summary>+ /// Debug escape hatch: keeps rational surfaces exactly as the file stated them, instead of reducing the ones no+ /// analytic primitive covers to the non-rational form the kernel otherwise guarantees. Export writes whatever the+ /// body holds, so this is also what puts RATIONAL_B_SPLINE_SURFACE back into an Aetheris file. It exists to give a+ /// degenerate legacy surface somewhere to land while it is being diagnosed, and is off by default.+ /// </summary>+ public static IDisposable PreserveRationalSurfaces()+ {+ var previous = PreserveRationalSurfacesFlag.Value;+ PreserveRationalSurfacesFlag.Value = true;+ return new PreserveRationalSurfacesScope(previous);+ }++ internal static bool RationalSurfacesArePreserved => PreserveRationalSurfacesFlag.Value;+public static IDisposable CaptureLoopRoleCircularSamplingDiagnostics(ICollection<LoopRoleCircularSamplingDiagnostic> sink){var previous = CircularSamplingDiagnosticsSink.Value;@@ -1238,14 +1255,40 @@ public static class Step242ImporterSourceFor(surfaceToDecode.Id, "Importer.Geometry.BsplineSurfaceRecovery"))]);}+ // What is left is a genuine free-form blend. It still must not enter the kernel as a NURBS, so it is+ // reduced to a non-rational spline that follows it well inside the accuracy the source file declares.+ if (bSplineSurface.IsRational && !RationalSurfacesArePreserved)+ {+ var reductionTolerance = BSplineSurfaceRationalReduction.ResolveTolerance(bSplineSurface, document.SourceDistanceAccuracyMillimetres);+ if (BSplineSurfaceRationalReduction.TryReduce(bSplineSurface, reductionTolerance, out var reducedSurface, out _, out var reductionReason)+ && reducedSurface is not null)+ {+ return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(+ (geometryId, SurfaceGeometry.FromBSplineSurfaceWithKnots(reducedSurface)),+ [new KernelDiagnostic(+ KernelDiagnosticCode.Unknown,+ KernelDiagnosticSeverity.Info,+ $"Spline surface #{surfaceToDecode.Id} is a free-form blend that no analytic primitive covers ({recoveryDecision.Reason}), and was reduced to a non-rational spline that {reductionReason}.",+ SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineReduced"))]);+ }++ return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(+ (geometryId, SurfaceGeometry.FromBSplineSurfaceWithKnots(bSplineSurface)),+ [new KernelDiagnostic(+ KernelDiagnosticCode.Unknown,+ KernelDiagnosticSeverity.Warning,+ $"Spline surface #{surfaceToDecode.Id} stays a rational B-spline: no analytic primitive verified ({recoveryDecision.Reason}), and reduction to a non-rational spline {reductionReason}.",+ SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplineRetained"))]);+ }+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"))+ $"Spline surface #{surfaceToDecode.Id} is retained as a rational B-spline because rational surfaces are preserved for this import: {recoveryDecision.Reason}",+ SourceFor(surfaceToDecode.Id, "Importer.Geometry.RationalBSplinePreserved"))}: [];@@ -3770,6 +3813,14 @@ public static class Step242Importer}}+ private sealed class PreserveRationalSurfacesScope(bool previous) : IDisposable+ {+ public void Dispose()+ {+ PreserveRationalSurfacesFlag.Value = previous;+ }+ }+private static KernelResult<T> LoopRoleFailure<T>(string message, string source) =>KernelResult<T>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source)]);diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.jsonindex 4570b209..834065b1 100644--- a/testdata/step242/manifests/nist.v0.report.json+++ b/testdata/step242/manifests/nist.v0.report.json@@ -97,7 +97,7 @@"edges": 331,"faces": 156},- "canonicalSha256": "deaddaaefd102199a26aadf3cc6551d4f1337f90f04c2b6103febcf8f499d731"+ "canonicalSha256": "863e3de993d60f8dbdd002575807b1326288b55b8a9bebf8228b486f82ef4e8a"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_06_asme1_ap242-e2",@@ -337,6 +337,6 @@"edges": 551,"faces": 256},- "canonicalSha256": "0eee08920035167420c527992ee2fcad8b9091fb644f4b21e8438eac5aa1b845"+ "canonicalSha256": "7117d051431956f4e59f67c2ea95075e87b5bad28f1d0a7136d3a8b74ec135d0"}]