Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

rational spline recovery

Yuechen Liac627fb36864
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.cs
index f7e33abe..50d7fffd 100644
--- a/Aetheris.CLI.Tests/CliBaselineTests.cs
+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs
@@ -252,7 +252,7 @@ public sealed class CliBaselineTests
Assert.Equal(0, summary.GetProperty("surfaceFamilies").GetProperty("bspline").GetInt32());
Assert.Equal("mm", summary.GetProperty("lengthUnit").GetString());
- Assert.Contains("assumed", summary.GetProperty("lengthUnitBasis").GetString(), StringComparison.OrdinalIgnoreCase);
+ Assert.Contains("normalized", summary.GetProperty("lengthUnitBasis").GetString(), StringComparison.OrdinalIgnoreCase);
var faceIds = summary.GetProperty("faceIds");
Assert.Equal(1, faceIds.GetProperty("min").GetInt32());
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 8ab1dffd..2db180ba 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -714,12 +714,15 @@ public static class CliRunner
}
PcurveBuildResult? recoveredPcurves = null;
if (!imported.Value.Bindings.PcurveBindings.Any())
- recoveredPcurves = BoundedPcurveBuilder.Populate(imported.Value.Topology, imported.Value.Geometry, imported.Value.Bindings);
- var importedPcurveEvidence = recoveredPcurves is null ? BrepPcurveValidator.Validate(imported.Value) : null;
+ recoveredPcurves = BoundedPcurveBuilder.Populate(imported.Value.Topology, imported.Value.Geometry, imported.Value.Bindings, tolerance: 1e-3d);
+ var importedPcurveEvidence = recoveredPcurves is null && imported.Value.PcurveRecoveryReport is null
+ ? BrepPcurveValidator.Validate(imported.Value) : null;
var rendered = BrepWireframeSvgRenderer.Render(imported.Value, new(view, density, samples));
Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, rendered.Svg);
var report = new { command = "wireframe", success = true, input, output, rendered.Evidence,
- pcurveRecovery = recoveredPcurves is null
+ pcurveRecovery = imported.Value.PcurveRecoveryReport is { } importRecovery
+ ? (object)new { importRecovery.IsSuccess, importRecovery.Count, importRecovery.MaximumResidual, importRecovery.Diagnostics }
+ : recoveredPcurves is null
? (object)new { IsSuccess = importedPcurveEvidence!.IsValid, Count = importedPcurveEvidence.PcurveCount, MaximumResidual = importedPcurveEvidence.MaximumReconstructionDeviation, Diagnostics = importedPcurveEvidence.Diagnostics }
: new { recoveredPcurves.IsSuccess, recoveredPcurves.Count, recoveredPcurves.MaximumResidual, recoveredPcurves.Diagnostics } };
if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.cs
index af29af06..3ced652b 100644
--- a/Aetheris.CLI/StepAnalysisModels.cs
+++ b/Aetheris.CLI/StepAnalysisModels.cs
@@ -27,7 +27,29 @@ public sealed record AnalyzeSummary(
IdRangeSummary EdgeIds,
IdRangeSummary VertexIds,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] FaceOrientationSummary? FaceOrientation = null,
- [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] BoundaryTopologySummary? BoundaryTopology = null);
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] BoundaryTopologySummary? BoundaryTopology = null,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SplineRecoverySummary? SplineRecovery = null,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PcurveQualificationSummary? PcurveQualification = null);
+
+public sealed record PcurveQualificationSummary(
+ string Status,
+ int TotalFaceEdgeBindings,
+ int SourcePcurves,
+ int RecoveredPcurves,
+ int FailedBindings,
+ double? WorstLiftDeviationMillimetres,
+ double BaseToleranceMillimetres,
+ IReadOnlyDictionary<string, int> SurfaceFamilies);
+
+public sealed record SplineRecoverySummary(
+ int AnalyticEntities,
+ int ExactSplineEntities,
+ int RecoveredSplineEntities,
+ int UnsupportedEntities,
+ int RecoveredCurves,
+ int RecoveredSurfaces,
+ double? WorstMeasuredDeviationMillimetres,
+ double? RecoveryToleranceMillimetres);
public sealed record BoundaryTopologySummary(
int EdgeLoopCount,
diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.cs
index aa237ffd..79b85d77 100644
--- a/Aetheris.CLI/StepAnalyzer.cs
+++ b/Aetheris.CLI/StepAnalyzer.cs
@@ -1650,10 +1650,17 @@ public sealed record VolumeAnalysisResult(
["bspline"] = 0,
["unsupported"] = 0
};
+ var analyticEntities = 0;
+ var exactSplineEntities = 0;
+ var recoveredCurves = 0;
+ var recoveredSurfaces = 0;
+ var unsupportedEntities = 0;
+ var worstDeviation = 0d;
+ double? recoveryTolerance = null;
foreach (var edge in topology.Edges)
{
- if (!body.TryGetEdgeCurveGeometry(edge.Id, out var curve) || curve is null) { curveFamilies["unsupported"]++; continue; }
+ if (!body.TryGetEdgeCurveGeometry(edge.Id, out var curve) || curve is null) { curveFamilies["unsupported"]++; unsupportedEntities++; continue; }
var key = curve.Kind switch
{
CurveGeometryKind.Line3 => "line",
@@ -1664,6 +1671,15 @@ public sealed record VolumeAnalysisResult(
_ => "unsupported"
};
curveFamilies[key]++;
+ if (curve.RecoveryProvenance is { } curveRecovery)
+ {
+ recoveredCurves++;
+ worstDeviation = double.Max(worstDeviation, curveRecovery.MeasuredMaxDeviationMillimetres);
+ recoveryTolerance = curveRecovery.RecoveryToleranceMillimetres;
+ }
+ else if (curve.Kind == CurveGeometryKind.BSpline3) exactSplineEntities++;
+ else if (curve.Kind == CurveGeometryKind.Unsupported) unsupportedEntities++;
+ else analyticEntities++;
}
foreach (var face in topology.Faces)
@@ -1671,9 +1687,19 @@ public sealed record VolumeAnalysisResult(
if (!body.TryGetFaceSurface(face.Id, out var surface) || surface is null)
{
surfaceFamilies["other"]++;
+ unsupportedEntities++;
continue;
}
+ if (surface.RecoveryProvenance is { } surfaceRecovery)
+ {
+ recoveredSurfaces++;
+ worstDeviation = double.Max(worstDeviation, surfaceRecovery.MeasuredMaxDeviationMillimetres);
+ recoveryTolerance = surfaceRecovery.RecoveryToleranceMillimetres;
+ }
+ else if (surface.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots) exactSplineEntities++;
+ else analyticEntities++;
+
switch (surface.Kind)
{
case SurfaceGeometryKind.Plane: IncrementSurfaceFamily(surfaceFamilies, "plane"); break;
@@ -1719,7 +1745,7 @@ public sealed record VolumeAnalysisResult(
curveFamilies,
basis,
"mm",
- "assumed; STEP import length units not yet preserved",
+ "STEP source lengths normalized to millimetres during import",
BuildIdRange(topology.Faces.Select(f => f.Id.Value)),
BuildIdRange(topology.Edges.Select(e => e.Id.Value)),
BuildIdRange(topology.Vertices.Select(v => v.Id.Value)),
@@ -1741,7 +1767,31 @@ public sealed record VolumeAnalysisResult(
.GroupBy(binding => (topology.GetCoedge(binding.CoedgeId).EdgeId, binding.SurfaceGeometryId))
.Count(group => group.Count() > 1),
body.Bindings.PcurveBindings.GroupBy(binding => binding.SourceCurveType ?? binding.Pcurve.Kind.ToString())
- .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal)));
+ .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal)),
+ new SplineRecoverySummary(analyticEntities, exactSplineEntities, recoveredCurves + recoveredSurfaces,
+ unsupportedEntities, recoveredCurves, recoveredSurfaces,
+ recoveredCurves + recoveredSurfaces == 0 ? null : worstDeviation, recoveryTolerance),
+ BuildPcurveQualificationSummary(body));
+ }
+
+ private static PcurveQualificationSummary BuildPcurveQualificationSummary(BrepBody body)
+ {
+ var bindings = body.Bindings.PcurveBindings.ToArray();
+ var total = body.Topology.Coedges.Count();
+ var evidence = BrepPcurveValidator.Validate(body, 1e-3d, requireEveryCoedge: true);
+ var recovered = bindings.Count(binding => binding.Qualification is { Origin: not PcurveBindingOrigin.SourceValidated });
+ var source = bindings.Count(binding => binding.SourceStepPcurveEntityId is not null
+ || binding.Qualification?.Origin == PcurveBindingOrigin.SourceValidated);
+ var failures = System.Math.Max(total - bindings.Length,
+ System.Math.Max(body.PcurveRecoveryReport?.Diagnostics.Count ?? 0, evidence.Diagnostics.Count));
+ var worst = bindings.Where(binding => binding.Qualification is not null)
+ .Select(binding => binding.Qualification!.MaximumLiftDeviationMillimetres).DefaultIfEmpty().Max();
+ var status = failures > 0 || !evidence.IsValid ? "inspectable-unqualified"
+ : total == bindings.Length ? "qualified" : "not-assessed";
+ return new PcurveQualificationSummary(status, total, source, recovered, failures,
+ bindings.Length == 0 ? null : double.Max(worst, evidence.MaximumReconstructionDeviation), 1e-3d,
+ bindings.GroupBy(binding => body.Geometry.Surfaces.Single(pair => pair.Key == binding.SurfaceGeometryId).Value.Kind.ToString())
+ .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal));
}
private static bool AreOrderedLoopsConnected(BrepBody body, out int disconnectedLoop)
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs
index 416a840e..68175fe7 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs
@@ -139,7 +139,7 @@ public sealed class Step242HoleSemanticsTests
}
[Fact]
- public void ImportBody_OcctNutExtractPlanarMultiBound_UsesJudgmentEngineRecoveryCandidate()
+ public void ImportBody_OcctNutExtractUsesWeightedCurveGeometryWithoutPlanarCrossingRepair()
{
var diagnostics = new List<Step242Importer.PlanarMultiBoundJudgmentDiagnostic>();
using var scope = Step242Importer.CapturePlanarMultiBoundJudgmentDiagnostics(diagnostics);
@@ -147,9 +147,10 @@ public sealed class Step242HoleSemanticsTests
var import = Step242Importer.ImportBody(ReadNutExtractStepText());
Assert.True(import.IsSuccess, string.Join(Environment.NewLine, import.Diagnostics.Select(d => d.Message)));
- var selected = diagnostics.Where(d => d.SelectedCandidate == "planar_crossing_inside_recover_as_inner").ToList();
- Assert.NotEmpty(selected);
- Assert.All(selected, diagnostic => Assert.Equal(diagnostic.VertexCount, diagnostic.ContainedVertexCount));
+ // The source's weighted curves are now evaluated and recovered as geometry. The previous
+ // planar-crossing judgment was needed only when these weights were silently discarded.
+ Assert.DoesNotContain(diagnostics, d => d.SelectedCandidate == "planar_crossing_inside_recover_as_inner");
+ Assert.Contains(import.Value.Geometry.Curves, pair => pair.Value.RecoveryProvenance is not null);
}
private static string ReadNutExtractStepText()
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242LocalRationalWitnessTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242LocalRationalWitnessTests.cs
new file mode 100644
index 00000000..511a5517
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242LocalRationalWitnessTests.cs
@@ -0,0 +1,65 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242LocalRationalWitnessTests
+{
+ [Fact]
+ public void McMasterThreadedBoltImportsTessellatesAndRoundTripsWhenSupplied()
+ {
+ var path = Environment.GetEnvironmentVariable("AETHERIS_STEP_NURBS_WITNESS");
+ if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return;
+
+ var imported = Step242Importer.ImportBody(File.ReadAllText(path));
+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics.Select(d => d.Message)));
+ var body = imported.Value;
+ Assert.Equal(147, body.Topology.Faces.Count());
+ Assert.Equal(405, body.Topology.Edges.Count());
+ var recoveredCurves = body.Geometry.Curves.Count(pair => pair.Value.RecoveryProvenance is not null);
+ var recoveredSurfaces = body.Geometry.Surfaces.Count(pair => pair.Value.RecoveryProvenance is not null);
+ Assert.True(recoveredCurves > 0);
+ Assert.True(recoveredSurfaces > 0);
+ Assert.NotNull(body.PcurveRecoveryReport);
+ Assert.True(body.PcurveRecoveryReport.IsSuccess, string.Join("\n", body.PcurveRecoveryReport.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(body.Topology.Coedges.Count(), body.Bindings.PcurveBindings.Count());
+ Assert.Equal(810, body.Bindings.PcurveBindings.Count());
+ Assert.All(body.Bindings.PcurveBindings, binding => Assert.NotNull(binding.Qualification));
+ var pcurveEvidence = BrepPcurveValidator.Validate(body, 1e-3d, requireEveryCoedge: true);
+ Assert.True(pcurveEvidence.IsValid,
+ $"worst={pcurveEvidence.MaximumReconstructionDeviation:R}; closure={pcurveEvidence.MaximumUvLoopClosure:R}; "
+ + string.Join("\n", pcurveEvidence.Diagnostics.Take(12)));
+ Assert.All(body.Geometry.Curves.Where(pair => pair.Value.RecoveryProvenance is not null),
+ pair => Assert.InRange(pair.Value.RecoveryProvenance!.MeasuredMaxDeviationMillimetres, 0d, 0.1d));
+
+ var tessellation = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(tessellation.IsSuccess, string.Join("\n", tessellation.Diagnostics.Select(d => d.Message)));
+ Assert.NotEmpty(tessellation.Value.FacePatches);
+
+ var exported = Step242Exporter.ExportBody(body);
+ Assert.True(exported.IsSuccess, string.Join("\n", exported.Diagnostics.Select(d => d.Message)));
+ var reimported = Step242Importer.ImportBody(exported.Value);
+ Assert.True(reimported.IsSuccess, string.Join("\n", reimported.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(body.Topology.Faces.Count(), reimported.Value.Topology.Faces.Count());
+ Assert.Equal(body.Topology.Edges.Count(), reimported.Value.Topology.Edges.Count());
+ Assert.Equal(body.Bindings.PcurveBindings.Count(), reimported.Value.Bindings.PcurveBindings.Count());
+ var worstRoundTripCurveDeviation = 0d;
+ foreach (var edge in body.Topology.Edges)
+ {
+ Assert.True(body.TryGetEdgeCurveGeometry(edge.Id, out var originalCurve));
+ Assert.True(reimported.Value.TryGetEdgeCurveGeometry(edge.Id, out var roundTripCurve));
+ if (originalCurve?.BSpline3 is not { } originalSpline || roundTripCurve?.BSpline3 is not { } roundTripSpline)
+ continue;
+ for (var sample = 0; sample <= 16; sample++)
+ {
+ var parameter = originalSpline.DomainStart +
+ (originalSpline.DomainEnd - originalSpline.DomainStart) * sample / 16d;
+ worstRoundTripCurveDeviation = double.Max(worstRoundTripCurveDeviation,
+ (originalSpline.Evaluate(parameter) - roundTripSpline.Evaluate(parameter)).Length);
+ }
+ }
+ Assert.InRange(worstRoundTripCurveDeviation, 0d, 0.01d);
+ }
+}
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs
index 175919d5..b18da45d 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242RationalBSplineCurveRecoveryTests.cs
@@ -65,6 +65,29 @@ public sealed class Step242RationalBSplineCurveRecoveryTests
Assert.Contains("step242-rational-bspline-circle", decision.Reason, StringComparison.OrdinalIgnoreCase);
}
+ [Fact]
+ public void GenericRationalCurveRecoversWithinConfigurableEngineeringTolerance()
+ {
+ var source = new BSpline3Curve(2,
+ [new Point3D(0d, 0d, 0d), new Point3D(0.3d, 0.9d, 0.2d),
+ new Point3D(1d, 0d, 0d), new Point3D(1.5d, 0.4d, 0.6d)],
+ [3, 1, 3], [0d, 0.5d, 1d], "UNSPECIFIED", false, false, "UNSPECIFIED");
+ double[] weights = [1d, 0.8d, 1.2d, 1d];
+
+ Assert.True(BSplineCurveRationalReduction.TryReduce(source, weights, 0.1d,
+ out var coarse, out var coarseDeviation, out _));
+ Assert.True(BSplineCurveRationalReduction.TryReduce(source, weights, 0.001d,
+ out var fine, out var fineDeviation, out _));
+ Assert.InRange(coarseDeviation, 0d, 0.1d);
+ Assert.InRange(fineDeviation, 0d, 0.001d);
+ Assert.True(fine.ControlPoints.Count >= coarse.ControlPoints.Count);
+ for (var i = 0; i <= 100; i++)
+ {
+ var u = i / 100d;
+ Assert.InRange((source.EvaluateRational(weights, u)!.Value - fine.Evaluate(u)).Length, 0d, 0.001d);
+ }
+ }
+
[Fact]
public void LeavesNonRationalBSplineUnchanged()
{
diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
index 13b1db3e..4e45ec17 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
@@ -187,7 +187,19 @@ public readonly record struct CoedgePcurveBinding(
int? SourceStepPcurveEntityId = null,
int? SourceStepCurveEntityId = null,
string? SourceCurveType = null,
- int? SourceStepSurfaceEntityId = null);
+ int? SourceStepSurfaceEntityId = null,
+ PcurveQualification? Qualification = null);
+
+public enum PcurveBindingOrigin { SourceValidated, RecoveredAnalytic, RecoveredSpline }
+
+/// <summary>Measured edge-to-surface-lift evidence for one face-local trim.</summary>
+public sealed record PcurveQualification(
+ PcurveBindingOrigin Origin,
+ double MaximumLiftDeviationMillimetres,
+ double QualificationToleranceMillimetres,
+ int LiftSamples,
+ string RecoveryMethod,
+ string SurfaceFamily);
public enum FaceBoundaryRole { Outer, Inner }
diff --git a/Aetheris.Kernel.Core/Brep/BrepBody.cs b/Aetheris.Kernel.Core/Brep/BrepBody.cs
index f68d85ea..af2bb687 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBody.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBody.cs
@@ -51,6 +51,9 @@ public sealed class BrepBody
/// </summary>
public FaceOrientationReport? FaceOrientationReport { get; }
+ /// <summary>Present when an interchange body required reconstructed trim bindings.</summary>
+ public BrepPcurveRecoveryResult? PcurveRecoveryReport { get; internal set; }
+
public bool TryGetVertexPoint(VertexId vertexId, out Point3D point) => _vertexPoints.TryGetValue(vertexId, out point);
public bool TryGetEdgeCurveGeometry(EdgeId edgeId, out CurveGeometry? curve)
diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
new file mode 100644
index 00000000..3a3b5273
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
@@ -0,0 +1,402 @@
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep;
+
+public sealed record BrepPcurveRecoveryResult(bool IsSuccess, int Count, double MaximumResidual, IReadOnlyList<BrepPcurveRecoveryDiagnostic> Diagnostics);
+public sealed record BrepPcurveRecoveryDiagnostic(string Code, string Message, string? Entity = null);
+
+/// <summary>Builds deterministic face-local pcurves from edge and support geometry.</summary>
+public static class BrepPcurveRecovery
+{
+ public static BrepPcurveRecoveryResult Populate(TopologyModel topology, BrepGeometryStore geometry, BrepBindingModel bindings,
+ double tolerance = 1e-5, int sampleCount = 129)
+ {
+ var diagnostics = new List<BrepPcurveRecoveryDiagnostic>();
+ var count = 0;
+ var maximum = 0d;
+ foreach (var face in topology.Faces.OrderBy(item => item.Id.Value))
+ {
+ if (!bindings.TryGetFaceBinding(face.Id, out var faceBinding) || !geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface is null)
+ continue;
+ foreach (var coedge in face.LoopIds.Select(topology.GetLoop).SelectMany(loop => loop.CoedgeIds.Select(topology.GetCoedge)))
+ {
+ if (!bindings.TryGetEdgeBinding(coedge.EdgeId, out var edgeBinding) || !geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null
+ || edgeBinding.TrimInterval is not { } interval)
+ {
+ diagnostics.Add(new("surf-pcurve-invalid", $"Coedge {coedge.Id.Value} has no bounded 3D edge curve.", coedge.Id.Value.ToString()));
+ continue;
+ }
+ var qualificationTolerance = ResolveQualificationTolerance(surface, curve, tolerance);
+ if (bindings.TryGetPcurveBinding(coedge.Id, out var retained))
+ {
+ var residual = MaximumResidual(surface, curve, retained.Pcurve, interval, sampleCount);
+ if (retained.FaceId != face.Id || retained.SurfaceGeometryId != faceBinding.SurfaceGeometryId || residual > qualificationTolerance)
+ diagnostics.Add(new("surf-pcurve-invalid", "Retained pcurve has inconsistent ownership or geometry.", coedge.Id.Value.ToString()));
+ maximum = double.Max(maximum, residual); count++; continue;
+ }
+ (PcurveGeometry? Pcurve, double MaximumResidual, string? Diagnostic) built;
+ try { built = Build(surface, curve, interval, qualificationTolerance, sampleCount); }
+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NotSupportedException)
+ {
+ diagnostics.Add(new("surf-pcurve-invalid",
+ $"Face {face.Id.Value}, edge {coedge.EdgeId.Value}, {surface.Kind}: {exception.Message}",
+ coedge.Id.Value.ToString()));
+ continue;
+ }
+ if (built.Pcurve is null)
+ {
+ diagnostics.Add(new("surf-pcurve-invalid", built.Diagnostic ?? "Pcurve construction failed.", coedge.Id.Value.ToString()));
+ continue;
+ }
+ var liftSamples = surface.BSplineSurfaceWithKnots is null ? 1025 : 8193;
+ var liftResidual = MaximumResidual(surface, curve, built.Pcurve, interval, liftSamples);
+ if (!double.IsFinite(liftResidual) || liftResidual > qualificationTolerance)
+ {
+ diagnostics.Add(new("surf-pcurve-invalid",
+ $"Face {face.Id.Value}, edge {coedge.EdgeId.Value}, {surface.Kind}: lifted pcurve residual {liftResidual:R} mm exceeds {qualificationTolerance:R} mm over {liftSamples} samples.",
+ coedge.Id.Value.ToString()));
+ continue;
+ }
+ var origin = surface.BSplineSurfaceWithKnots is null
+ ? PcurveBindingOrigin.RecoveredAnalytic : PcurveBindingOrigin.RecoveredSpline;
+ bindings.AddPcurveBinding(new(coedge.Id, face.Id, faceBinding.SurfaceGeometryId, built.Pcurve,
+ Qualification: new(origin, liftResidual, qualificationTolerance, liftSamples,
+ built.Pcurve.Kind.ToString(), surface.Kind.ToString())));
+ maximum = double.Max(maximum, liftResidual);
+ count++;
+ }
+ }
+ return new(diagnostics.Count == 0, count, maximum, diagnostics);
+ }
+
+ private static double ResolveQualificationTolerance(SurfaceGeometry surface, CurveGeometry curve, double baseTolerance)
+ {
+ var curveRecovery = curve.RecoveryProvenance;
+ var surfaceRecovery = surface.RecoveryProvenance;
+ if (curveRecovery is null && surfaceRecovery is null) return baseTolerance;
+ var budget = double.Min(curveRecovery?.RecoveryToleranceMillimetres ?? double.PositiveInfinity,
+ surfaceRecovery?.RecoveryToleranceMillimetres ?? double.PositiveInfinity);
+ var observed = (curveRecovery?.MeasuredMaxDeviationMillimetres ?? 0d)
+ + (surfaceRecovery?.MeasuredMaxDeviationMillimetres ?? 0d);
+ return double.Min(budget, double.Max(baseTolerance, baseTolerance + observed * 1.25d));
+ }
+
+ private static (PcurveGeometry? Pcurve, double MaximumResidual, string? Diagnostic) Build(
+ SurfaceGeometry surface, CurveGeometry curve, ParameterInterval interval, double tolerance, int samples)
+ {
+ if (surface.Plane is { } plane)
+ {
+ var start = PlaneUv(plane, EvaluateCurve(curve, interval.Start));
+ var end = PlaneUv(plane, EvaluateCurve(curve, interval.End));
+ if (curve.Kind == CurveGeometryKind.Line3) return (PcurveGeometry.Line(interval, start, end), 0d, null);
+ if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)
+ {
+ var center = PlaneUv(plane, circle.Center);
+ var cosinePoint = PlaneUv(plane, circle.Evaluate(0d));
+ var sinePoint = PlaneUv(plane, circle.Evaluate(double.Pi / 2d));
+ return (PcurveGeometry.Ellipse(interval, center,
+ new(cosinePoint.U - center.U, cosinePoint.V - center.V),
+ new(sinePoint.U - center.U, sinePoint.V - center.V)), 0d, null);
+ }
+ if (curve.BSpline3 is { } polynomial)
+ {
+ // Affine projection commutes with B-spline evaluation. The hull bound
+ // certifies the whole 3D curve lies on this support, without fitting.
+ var bound = polynomial.ControlPoints.Max(p => double.Abs((p - plane.Origin).Dot(plane.Normal.ToVector())));
+ if (bound > tolerance) return (null, bound, "Polynomial edge control hull is not on the planar support.");
+ var controls = polynomial.ControlPoints.Select(p => { var uv = PlaneUv(plane, p); return new Point3D(uv.U, uv.V, 0); }).ToArray();
+ var uvCurve = new BSpline3Curve(polynomial.Degree, controls, polynomial.KnotMultiplicities, polynomial.KnotValues,
+ polynomial.CurveForm, polynomial.ClosedCurve, polynomial.SelfIntersect, polynomial.KnotSpec);
+ return (PcurveGeometry.Polynomial(interval, uvCurve), bound, null);
+ }
+ var lineCandidate = PcurveGeometry.Line(interval, start, end);
+ var lineResidual = MaximumResidual(surface, curve, lineCandidate, interval, 67);
+ if (lineResidual <= tolerance) return (lineCandidate, lineResidual, null);
+ const int denseSamples = 4097;
+ return (PcurveGeometry.Polyline(interval, Sample(interval, denseSamples, t => PlaneUv(plane, EvaluateCurve(curve, t)))), 0d, null);
+ }
+ if (surface.Cylinder is { } cylinder)
+ return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => CylinderUv(cylinder, point));
+ if (surface.Cone is { } cone)
+ return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => ConeUv(cone, point));
+ if (surface.Sphere is { } sphere)
+ return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => SphereUv(sphere, point));
+ if (surface.Torus is { } torus)
+ return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => TorusUv(torus, point), unwrapV: true);
+ if (surface.BSplineSurfaceWithKnots is not { } spline)
+ return (null, double.PositiveInfinity, $"Surface family {surface.Kind} is outside the qualified pcurve matrix.");
+
+ var startInverse = Invert(spline, EvaluateCurve(curve, interval.Start), null, tolerance);
+ var endInverse = Invert(spline, EvaluateCurve(curve, interval.End), startInverse.Success ? startInverse.Uv : null, tolerance);
+ if (startInverse.Success && endInverse.Success)
+ {
+ var lineCandidate = PcurveGeometry.Line(interval, startInverse.Uv, endInverse.Uv);
+ var lineResidual = MaximumResidual(surface, curve, lineCandidate, interval, 67);
+ if (lineResidual <= tolerance) return (lineCandidate, lineResidual, null);
+ }
+
+ var bestResidual = double.PositiveInfinity;
+ for (var inverseSamples = 129; inverseSamples <= 4097; inverseSamples = (inverseSamples - 1) * 2 + 1)
+ {
+ var uv = new List<SurfaceParameterPoint>(inverseSamples);
+ SurfaceParameterPoint? seed = null;
+ var inversionFailed = false;
+ for (var index = 0; index < inverseSamples; index++)
+ {
+ var t = interval.Start + ((interval.End - interval.Start) * index / (inverseSamples - 1d));
+ var inverse = Invert(spline, EvaluateCurve(curve, t), seed, tolerance);
+ if (!inverse.Success)
+ {
+ bestResidual = double.Min(bestResidual, inverse.Residual);
+ inversionFailed = true;
+ break;
+ }
+ seed = inverse.Uv;
+ uv.Add(inverse.Uv);
+ }
+ if (inversionFailed) continue;
+ var candidate = PcurveGeometry.Polyline(interval, uv);
+ var residual = MaximumResidual(surface, curve, candidate, interval, (inverseSamples - 1) * 2 + 1);
+ bestResidual = double.Min(bestResidual, residual);
+ if (residual <= tolerance) return (candidate, residual, null);
+ }
+ return (null, bestResidual,
+ $"Spline pcurve inversion/refinement exceeded 4097 samples; best lifted residual={bestResidual:R} mm, tolerance={tolerance:R} mm.");
+ }
+
+ private static (bool Success, SurfaceParameterPoint Uv, double Residual) Invert(BSplineSurfaceWithKnots spline, Point3D target, SurfaceParameterPoint? prior, double tolerance)
+ {
+ // Intersection traces are parameter-continuous, so the preceding inverse is
+ // the deterministic seed after the first sample. Avoiding a fresh global grid
+ // search at every dense qualification point keeps high-accuracy pcurves bounded.
+ var best = prior ?? GridSeed(spline, target);
+ for (var iteration = 0; iteration < 32; iteration++)
+ {
+ var point = spline.Evaluate(best.U, best.V);
+ var residual = point - target;
+ if (residual.Length <= 1e-8d) return (true, best, residual.Length);
+ var hu = double.Max((spline.DomainEndU - spline.DomainStartU) * 1e-4d, 1e-7d);
+ var hv = double.Max((spline.DomainEndV - spline.DomainStartV) * 1e-4d, 1e-7d);
+ var du = (spline.Evaluate(double.Min(best.U + hu, spline.DomainEndU), best.V) - spline.Evaluate(double.Max(best.U - hu, spline.DomainStartU), best.V))
+ / (double.Min(best.U + hu, spline.DomainEndU) - double.Max(best.U - hu, spline.DomainStartU));
+ var dv = (spline.Evaluate(best.U, double.Min(best.V + hv, spline.DomainEndV)) - spline.Evaluate(best.U, double.Max(best.V - hv, spline.DomainStartV)))
+ / (double.Min(best.V + hv, spline.DomainEndV) - double.Max(best.V - hv, spline.DomainStartV));
+ var a = du.Dot(du); var b = du.Dot(dv); var c = dv.Dot(dv);
+ var r1 = du.Dot(residual); var r2 = dv.Dot(residual);
+ var determinant = (a * c) - (b * b);
+ if (double.Abs(determinant) <= 1e-18d) break;
+ var deltaU = ((c * r1) - (b * r2)) / determinant;
+ var deltaV = ((a * r2) - (b * r1)) / determinant;
+ var accepted = false;
+ for (var damping = 1d; damping >= 1d / 64d; damping *= .5d)
+ {
+ var candidate = new SurfaceParameterPoint(
+ System.Math.Clamp(best.U - (deltaU * damping), spline.DomainStartU, spline.DomainEndU),
+ System.Math.Clamp(best.V - (deltaV * damping), spline.DomainStartV, spline.DomainEndV));
+ if ((spline.Evaluate(candidate.U, candidate.V) - target).LengthSquared >= residual.LengthSquared) continue;
+ best = candidate; accepted = true; break;
+ }
+ if (!accepted) break;
+ }
+ // Deterministic bounded pattern refinement handles domain-boundary minima where
+ // the two-column normal equation can become poorly conditioned.
+ var stepU = (spline.DomainEndU - spline.DomainStartU) / 32d;
+ var stepV = (spline.DomainEndV - spline.DomainStartV) / 32d;
+ var bestDistance = (spline.Evaluate(best.U, best.V) - target).LengthSquared;
+ for (var iteration = 0; iteration < 64 && (stepU > 1e-13d || stepV > 1e-13d); iteration++)
+ {
+ var improved = false;
+ foreach (var offsetU in new[] { -stepU, 0d, stepU }) foreach (var offsetV in new[] { -stepV, 0d, stepV })
+ {
+ if (offsetU == 0d && offsetV == 0d) continue;
+ var candidate = new SurfaceParameterPoint(
+ System.Math.Clamp(best.U + offsetU, spline.DomainStartU, spline.DomainEndU),
+ System.Math.Clamp(best.V + offsetV, spline.DomainStartV, spline.DomainEndV));
+ var distance = (spline.Evaluate(candidate.U, candidate.V) - target).LengthSquared;
+ if (distance >= bestDistance) continue;
+ best = candidate; bestDistance = distance; improved = true;
+ }
+ if (!improved) { stepU *= .5d; stepV *= .5d; }
+ }
+ var finalResidual = (spline.Evaluate(best.U, best.V) - target).Length;
+ return (finalResidual <= tolerance, best, finalResidual);
+ }
+
+ private static SurfaceParameterPoint GridSeed(BSplineSurfaceWithKnots spline, Point3D target)
+ {
+ var best = new SurfaceParameterPoint(spline.DomainStartU, spline.DomainStartV);
+ var distance = double.PositiveInfinity;
+ const int divisions = 32;
+ for (var i = 0; i <= divisions; i++) for (var j = 0; j <= divisions; j++)
+ {
+ var u = spline.DomainStartU + ((spline.DomainEndU - spline.DomainStartU) * i / divisions);
+ var v = spline.DomainStartV + ((spline.DomainEndV - spline.DomainStartV) * j / divisions);
+ var d = (spline.Evaluate(u, v) - target).LengthSquared;
+ if (d < distance) { distance = d; best = new(u, v); }
+ }
+ // Trim endpoints commonly lie on a support-domain boundary. A narrow patch can
+ // be missed by a two-dimensional grid even when its boundary is easy to sample.
+ const int boundaryDivisions = 2048;
+ for (var i = 0; i <= boundaryDivisions; i++)
+ {
+ var u = spline.DomainStartU + (spline.DomainEndU - spline.DomainStartU) * i / boundaryDivisions;
+ var v = spline.DomainStartV + (spline.DomainEndV - spline.DomainStartV) * i / boundaryDivisions;
+ Check(u, spline.DomainStartV);
+ Check(u, spline.DomainEndV);
+ Check(spline.DomainStartU, v);
+ Check(spline.DomainEndU, v);
+ }
+ return best;
+
+ void Check(double u, double v)
+ {
+ var d = (spline.Evaluate(u, v) - target).LengthSquared;
+ if (d < distance) { distance = d; best = new(u, v); }
+ }
+ }
+
+ private static Point3D EvaluateCurve(CurveGeometry curve, double parameter) => curve.Kind switch
+ {
+ CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(parameter),
+ CurveGeometryKind.BSpline3 => curve.BSpline3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Ellipse3 => curve.Ellipse3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Hyperbola3 => curve.Hyperbola3!.Value.Evaluate(parameter),
+ _ => throw new NotSupportedException($"Curve family {curve.Kind} is outside the qualified pcurve matrix.")
+ };
+ private static SurfaceParameterPoint PlaneUv(PlaneSurface plane, Point3D point)
+ {
+ var d = point - plane.Origin;
+ return new(d.Dot(plane.UAxis.ToVector()), d.Dot(plane.VAxis.ToVector()));
+ }
+ private static SurfaceParameterPoint CylinderUv(CylinderSurface cylinder, Point3D point)
+ {
+ var d = point - cylinder.Origin;
+ return new(double.Atan2(d.Dot(cylinder.YAxis.ToVector()), d.Dot(cylinder.XAxis.ToVector())), d.Dot(cylinder.Axis.ToVector()));
+ }
+ private static SurfaceParameterPoint ConeUv(ConeSurface cone, Point3D point)
+ {
+ var fromApex = point - cone.Apex;
+ var axial = fromApex.Dot(cone.Axis.ToVector());
+ var originRadial = cone.Evaluate(0d, 1d) - cone.Apex - cone.Axis.ToVector();
+ var xAxis = Direction3D.Create(originRadial);
+ var yAxis = Direction3D.Create(cone.Axis.ToVector().Cross(xAxis.ToVector()));
+ return new(double.Atan2(fromApex.Dot(yAxis.ToVector()), fromApex.Dot(xAxis.ToVector())), axial);
+ }
+ private static SurfaceParameterPoint SphereUv(SphereSurface sphere, Point3D point)
+ {
+ var d = point - sphere.Center;
+ var axial = d.Dot(sphere.Axis.ToVector());
+ return new(double.Atan2(d.Dot(sphere.YAxis.ToVector()), d.Dot(sphere.XAxis.ToVector())),
+ double.Atan2(axial, double.Sqrt(double.Max(0d, d.LengthSquared - axial * axial))));
+ }
+ private static SurfaceParameterPoint TorusUv(TorusSurface torus, Point3D point)
+ {
+ var d = point - torus.Center;
+ var x = d.Dot(torus.XAxis.ToVector());
+ var y = d.Dot(torus.YAxis.ToVector());
+ var axial = d.Dot(torus.Axis.ToVector());
+ return new(double.Atan2(y, x), double.Atan2(axial, double.Sqrt(x * x + y * y) - torus.MajorRadius));
+ }
+ private static (PcurveGeometry? Pcurve, double MaximumResidual, string? Diagnostic) BuildPeriodicAnalytic(
+ SurfaceGeometry surface, CurveGeometry curve, ParameterInterval interval, double tolerance,
+ Func<Point3D, SurfaceParameterPoint> inverse, bool unwrapV = false)
+ {
+ var best = double.PositiveInfinity;
+ for (var count = 17; count <= 513; count = (count - 1) * 2 + 1)
+ {
+ var uv = Sample(interval, count, t => inverse(EvaluateCurve(curve, t))).ToArray();
+ UnwrapAngles(uv, unwrapV);
+ var controls = new List<Point3D>((count - 1) * 3 + 1);
+ var knots = new List<double>(count);
+ var multiplicities = new List<int>(count);
+ for (var index = 0; index < count - 1; index++)
+ {
+ var start = interval.Start + (interval.End - interval.Start) * index / (count - 1d);
+ var end = interval.Start + (interval.End - interval.Start) * (index + 1) / (count - 1d);
+ var delta = (end - start) * 1e-4d;
+ var nearStart = inverse(EvaluateCurve(curve, start + delta));
+ var nearEnd = inverse(EvaluateCurve(curve, end - delta));
+ var p0 = uv[index];
+ var p3 = uv[index + 1];
+ nearStart = nearStart with { U = UnwrapNear(nearStart.U, p0.U) };
+ nearEnd = nearEnd with { U = UnwrapNear(nearEnd.U, p3.U) };
+ if (unwrapV)
+ {
+ nearStart = nearStart with { V = UnwrapNear(nearStart.V, p0.V) };
+ nearEnd = nearEnd with { V = UnwrapNear(nearEnd.V, p3.V) };
+ }
+ var scale = (end - start) / (3d * delta);
+ var p1 = new SurfaceParameterPoint(p0.U + (nearStart.U - p0.U) * scale,
+ p0.V + (nearStart.V - p0.V) * scale);
+ var p2 = new SurfaceParameterPoint(p3.U - (p3.U - nearEnd.U) * scale,
+ p3.V - (p3.V - nearEnd.V) * scale);
+ if (index == 0)
+ {
+ controls.Add(new Point3D(p0.U, p0.V, 0d));
+ knots.Add(start);
+ multiplicities.Add(4);
+ }
+ controls.Add(new Point3D(p1.U, p1.V, 0d));
+ controls.Add(new Point3D(p2.U, p2.V, 0d));
+ controls.Add(new Point3D(p3.U, p3.V, 0d));
+ knots.Add(end);
+ multiplicities.Add(index == count - 2 ? 4 : 3);
+ }
+ var polynomial = new BSpline3Curve(3, controls, multiplicities, knots,
+ "UNSPECIFIED", false, false, "UNSPECIFIED");
+ var candidate = PcurveGeometry.Polynomial(interval, polynomial);
+ var residual = MaximumResidual(surface, curve, candidate, interval, (count - 1) * 4 + 1);
+ best = double.Min(best, residual);
+ if (residual <= tolerance) return (candidate, residual, null);
+ }
+ return (null, best, $"{surface.Kind} pcurve refinement could not meet {tolerance:R} mm (best sampled lift residual {best:R} mm).");
+ }
+
+ private static double UnwrapNear(double value, double reference)
+ {
+ while (value - reference > double.Pi) value -= 2d * double.Pi;
+ while (value - reference < -double.Pi) value += 2d * double.Pi;
+ return value;
+ }
+ private static void UnwrapAngles(SurfaceParameterPoint[] points, bool unwrapV)
+ {
+ for (var index = 1; index < points.Length; index++)
+ {
+ var u = points[index].U;
+ while (u - points[index - 1].U > double.Pi) u -= 2d * double.Pi;
+ while (u - points[index - 1].U < -double.Pi) u += 2d * double.Pi;
+ points[index] = points[index] with { U = u,
+ V = unwrapV ? UnwrapNear(points[index].V, points[index - 1].V) : points[index].V };
+ }
+ }
+ private static IReadOnlyList<SurfaceParameterPoint> Sample(ParameterInterval interval, int count, Func<double, SurfaceParameterPoint> evaluator)
+ => Enumerable.Range(0, count).Select(index => evaluator(interval.Start + ((interval.End - interval.Start) * index / (count - 1d)))).ToArray();
+
+ private static double MaximumResidual(SurfaceGeometry surface, CurveGeometry curve, PcurveGeometry pcurve, ParameterInterval interval, int count)
+ {
+ var maximum = 0d;
+ for (var index = 0; index < count; index++)
+ {
+ var parameter = interval.Start + ((interval.End - interval.Start) * index / (count - 1d));
+ var uv = pcurve.Evaluate(parameter);
+ var onSurface = surface.Kind switch
+ {
+ SurfaceGeometryKind.Plane => surface.Plane!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.Cylinder => surface.Cylinder!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.Cone => surface.Cone!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.Sphere => surface.Sphere!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.Torus => surface.Torus!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.BSplineSurfaceWithKnots => surface.BSplineSurfaceWithKnots!.Evaluate(uv.U, uv.V),
+ _ => throw new InvalidOperationException()
+ };
+ maximum = double.Max(maximum, (onSurface - EvaluateCurve(curve, parameter)).Length);
+ }
+ return maximum;
+ }
+}
+
diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
index 484153fb..c70da9ca 100644
--- a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
@@ -42,6 +42,7 @@ public static class BrepPcurveValidator
if (requireEveryCoedge) diagnostics.Add($"surf-pcurve-missing:coedge={coedge.Id.Value}");
continue;
}
+ var bindingTolerance = binding.Qualification?.QualificationToleranceMillimetres ?? tolerance;
var face = body.Topology.Faces.SingleOrDefault(candidate => candidate.LoopIds.Contains(coedge.LoopId));
if (face is null || face.Id != binding.FaceId)
{
@@ -69,7 +70,7 @@ public static class BrepPcurveValidator
var parameter = interval.Start + ((interval.End - interval.Start) * fraction);
var curveParameter = binding.SameSense ? parameter : interval.End - ((parameter - interval.Start));
var uv = binding.Pcurve.Evaluate(curveParameter);
- if (!WithinSurfaceDomain(surface, uv, tolerance))
+ if (!WithinSurfaceDomain(surface, uv, bindingTolerance))
{
domainValid = false;
diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:surface-domain:u={uv.U:R}:v={uv.V:R}");
@@ -87,15 +88,15 @@ public static class BrepPcurveValidator
residualSamples++;
}
maximum = double.Max(maximum, coedgeMaximum);
- if (coedgeMaximum > tolerance)
- diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:face={face.Id.Value}:surface={surface.Kind}:curve={curve.Kind}:pcurve={binding.Pcurve.Kind}:deviation={coedgeMaximum:R}:tolerance={tolerance:R}");
+ if (coedgeMaximum > bindingTolerance)
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:face={face.Id.Value}:surface={surface.Kind}:curve={curve.Kind}:pcurve={binding.Pcurve.Kind}:deviation={coedgeMaximum:R}:tolerance={bindingTolerance:R}");
if (body.TryGetVertexPoint(coedge.IsReversed ? body.Topology.GetEdge(coedge.EdgeId).EndVertexId : body.Topology.GetEdge(coedge.EdgeId).StartVertexId, out var start))
{
var parameter = coedge.IsReversed ? interval.End : interval.Start;
var uv = binding.Pcurve.Evaluate(binding.SameSense ? parameter : interval.End - (parameter - interval.Start));
var reconstructed = Evaluate(surface, uv);
- if (reconstructed is null || (reconstructed.Value - start).Length > tolerance)
+ if (reconstructed is null || (reconstructed.Value - start).Length > bindingTolerance)
{
orientationValid = false;
diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:orientation");
@@ -109,7 +110,7 @@ public static class BrepPcurveValidator
var parameter = coedge.IsReversed ? interval.Start : interval.End;
var uv = binding.Pcurve.Evaluate(binding.SameSense ? parameter : interval.End - (parameter - interval.Start));
var reconstructed = Evaluate(surface, uv);
- if (reconstructed is null || (reconstructed.Value - endPoint).Length > tolerance)
+ if (reconstructed is null || (reconstructed.Value - endPoint).Length > bindingTolerance)
{
orientationValid = false;
diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:end-orientation");
@@ -127,16 +128,18 @@ public static class BrepPcurveValidator
var nextUv = nextBinding.Pcurve.Evaluate(nextBinding.SameSense ? nextLoopParameter : nextInterval.End - (nextLoopParameter - nextInterval.Start));
var closure = UvDistance(surface, currentUv, nextUv);
maximumUvClosure = double.Max(maximumUvClosure, closure);
- if (closure > tolerance)
+ var closureTolerance = double.Max(bindingTolerance,
+ nextBinding.Qualification?.QualificationToleranceMillimetres ?? tolerance);
+ if (closure > closureTolerance)
{
loopClosureValid = false;
- diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:uv-loop-closure={closure:R}:tolerance={tolerance:R}");
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:uv-loop-closure={closure:R}:tolerance={closureTolerance:R}");
}
}
}
var count = body.Bindings.PcurveBindings.Count();
- var valid = diagnostics.Count == 0 && maximum <= tolerance && domainValid && orientationValid && loopClosureValid;
+ var valid = diagnostics.Count == 0 && domainValid && orientationValid && loopClosureValid;
return new(valid, body.Topology.Edges.Count(), count, maximum, domainValid, orientationValid, diagnostics)
{
LoopClosureValid = loopClosureValid,
diff --git a/Aetheris.Kernel.Core/Geometry/CurveGeometry.cs b/Aetheris.Kernel.Core/Geometry/CurveGeometry.cs
index 355e110e..066d8089 100644
--- a/Aetheris.Kernel.Core/Geometry/CurveGeometry.cs
+++ b/Aetheris.Kernel.Core/Geometry/CurveGeometry.cs
@@ -42,6 +42,9 @@ public sealed record CurveGeometry
public string? UnsupportedKind { get; }
+ /// <summary>Present only when import has promoted a measured generic recovery to geometric authority.</summary>
+ public SplineRecoveryProvenance? RecoveryProvenance { get; private init; }
+
/// <summary>
/// Exact parent-cylinder intersection and certified realization when this B-spline
/// is only a finite representation of an analytic surface-intersection edge.
@@ -54,6 +57,12 @@ public sealed record CurveGeometry
public static CurveGeometry FromBSpline(BSpline3Curve curve) => new(CurveGeometryKind.BSpline3, null, null, curve, null, null, null);
+ public static CurveGeometry FromRecoveredBSpline(BSpline3Curve curve, SplineRecoveryProvenance provenance)
+ {
+ ArgumentNullException.ThrowIfNull(provenance);
+ return FromBSpline(curve) with { RecoveryProvenance = provenance };
+ }
+
public static CurveGeometry FromCertifiedIntersection(QualifiedCylinderIntersectionRepresentation representation)
{
ArgumentNullException.ThrowIfNull(representation);
diff --git a/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs b/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs
index 0a1285e9..fe2e2906 100644
--- a/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs
+++ b/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs
@@ -121,6 +121,41 @@ public readonly record struct BSpline3Curve
return d[p];
}
+ /// <summary>Evaluates source rational evidence without promoting weights to authored curve authority.</summary>
+ public Point3D? EvaluateRational(IReadOnlyList<double> weights, double parameter)
+ {
+ if (weights.Count != ControlPoints.Count || !double.IsFinite(parameter)) return null;
+ var u = ClampToDomain(parameter);
+ var span = FindSpan(u);
+ var points = new (double X, double Y, double Z, double W)[Degree + 1];
+ for (var j = 0; j <= Degree; j++)
+ {
+ var index = span - Degree + j;
+ var weight = weights[index];
+ if (!double.IsFinite(weight) || weight <= 0d) return null;
+ var control = ControlPoints[index];
+ points[j] = (control.X * weight, control.Y * weight, control.Z * weight, weight);
+ }
+ for (var r = 1; r <= Degree; r++)
+ {
+ for (var j = Degree; j >= r; j--)
+ {
+ var left = FullKnots[span - Degree + j];
+ var right = FullKnots[span + 1 + j - r];
+ var denominator = right - left;
+ var alpha = double.Abs(denominator) <= 1e-15d ? 0d : (u - left) / denominator;
+ var a = points[j - 1];
+ var b = points[j];
+ points[j] = (a.X + (b.X - a.X) * alpha, a.Y + (b.Y - a.Y) * alpha,
+ a.Z + (b.Z - a.Z) * alpha, a.W + (b.W - a.W) * alpha);
+ }
+ }
+ var result = points[Degree];
+ if (!double.IsFinite(result.W) || result.W <= 0d) return null;
+ var point = new Point3D(result.X / result.W, result.Y / result.W, result.Z / result.W);
+ return double.IsFinite(point.X) && double.IsFinite(point.Y) && double.IsFinite(point.Z) ? point : null;
+ }
+
/// <summary>Evaluates the exact polynomial derivative of this non-rational B-spline.</summary>
public Vector3D EvaluateTangent(double parameter)
{
diff --git a/Aetheris.Kernel.Core/Geometry/Curves/BSplineCurveRationalReduction.cs b/Aetheris.Kernel.Core/Geometry/Curves/BSplineCurveRationalReduction.cs
new file mode 100644
index 00000000..0bd1fc15
--- /dev/null
+++ b/Aetheris.Kernel.Core/Geometry/Curves/BSplineCurveRationalReduction.cs
@@ -0,0 +1,130 @@
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Kernel.Core.Geometry.Curves;
+
+/// <summary>Adaptive, parameter-preserving cubic approximation of a rational STEP edge.</summary>
+public static class BSplineCurveRationalReduction
+{
+ private const int MaximumSegments = 2048;
+ private const int MaximumDepth = 14;
+
+ public static bool TryReduce(
+ BSpline3Curve source,
+ IReadOnlyList<double> weights,
+ double toleranceMillimetres,
+ out BSpline3Curve reduced,
+ out double measuredMaxDeviationMillimetres,
+ out string reason)
+ {
+ reduced = default;
+ measuredMaxDeviationMillimetres = double.PositiveInfinity;
+ if (!double.IsFinite(toleranceMillimetres) || toleranceMillimetres <= 0d
+ || weights.Count != source.ControlPoints.Count
+ || weights.Any(weight => !double.IsFinite(weight) || weight <= 0d))
+ {
+ reason = "Recovery tolerance and all rational weights must be positive and finite, with one weight per control point.";
+ return false;
+ }
+
+ var intervals = source.GetNonZeroKnotSpans(new ParameterInterval(source.DomainStart, source.DomainEnd));
+ if (intervals.Count == 0)
+ {
+ reason = "The rational source has no nonzero knot span.";
+ return false;
+ }
+
+ var accepted = new List<Segment>();
+ var measured = 0d;
+ foreach (var interval in intervals)
+ {
+ if (!Refine(interval.Start, interval.End, 0))
+ {
+ reason = $"Adaptive cubic refinement could not meet {toleranceMillimetres:G6} mm within {MaximumSegments} segments (last accepted span deviation {measured:G6} mm).";
+ measuredMaxDeviationMillimetres = double.PositiveInfinity;
+ return false;
+ }
+ }
+
+ var controls = new List<Point3D>(accepted.Count * 3 + 1);
+ var knots = new List<double>(accepted.Count + 1);
+ var multiplicities = new List<int>(accepted.Count + 1);
+ for (var index = 0; index < accepted.Count; index++)
+ {
+ var segment = accepted[index];
+ if (index == 0)
+ {
+ knots.Add(segment.Start);
+ multiplicities.Add(4);
+ controls.Add(segment.P0);
+ }
+ controls.Add(segment.P1);
+ controls.Add(segment.P2);
+ controls.Add(segment.P3);
+ knots.Add(segment.End);
+ multiplicities.Add(index == accepted.Count - 1 ? 4 : 3);
+ }
+
+ try
+ {
+ reduced = new BSpline3Curve(3, controls, multiplicities, knots,
+ source.CurveForm, source.ClosedCurve, source.SelfIntersect, "UNSPECIFIED");
+ }
+ catch (ArgumentException ex)
+ {
+ reason = $"Recovered spline construction failed: {ex.Message}";
+ return false;
+ }
+
+ measuredMaxDeviationMillimetres = measured;
+ reason = $"adaptive cubic recovery used {accepted.Count} spans; maximum sampled deviation {measured:G6} mm within {toleranceMillimetres:G6} mm.";
+ return true;
+
+ bool Refine(double start, double end, int depth)
+ {
+ if (accepted.Count >= MaximumSegments) return false;
+ if (!TryEvaluate(start, out var p0) || !TryEvaluate(end, out var p3)) return false;
+ var h = end - start;
+ // Interior secants avoid evaluating a derivative across repeated source knots.
+ var delta = h * 1e-4d;
+ if (!TryEvaluate(start + delta, out var nearStart) || !TryEvaluate(end - delta, out var nearEnd)) return false;
+ var p1 = p0 + ((nearStart - p0) * (h / (3d * delta)));
+ var p2 = p3 - ((p3 - nearEnd) * (h / (3d * delta)));
+ var candidate = new Segment(start, end, p0, p1, p2, p3);
+ var error = 0d;
+ foreach (var fraction in new[] { 0.125d, 0.25d, 0.375d, 0.5d, 0.625d, 0.75d, 0.875d })
+ {
+ if (!TryEvaluate(start + h * fraction, out var actual)) return false;
+ error = double.Max(error, (actual - candidate.Evaluate(fraction)).Length);
+ }
+ if (error <= toleranceMillimetres)
+ {
+ accepted.Add(candidate);
+ measured = double.Max(measured, error);
+ return true;
+ }
+ if (depth >= MaximumDepth || accepted.Count + 2 > MaximumSegments) return false;
+ var middle = start + h * 0.5d;
+ return Refine(start, middle, depth + 1) && Refine(middle, end, depth + 1);
+ }
+
+ bool TryEvaluate(double parameter, out Point3D point)
+ {
+ var evaluated = source.EvaluateRational(weights, parameter);
+ point = evaluated ?? default;
+ return evaluated.HasValue;
+ }
+ }
+
+ private readonly record struct Segment(double Start, double End, Point3D P0, Point3D P1, Point3D P2, Point3D P3)
+ {
+ public Point3D Evaluate(double fraction)
+ {
+ var opposite = 1d - fraction;
+ return Point3D.Origin
+ + ((P0 - Point3D.Origin) * (opposite * opposite * opposite))
+ + ((P1 - Point3D.Origin) * (3d * opposite * opposite * fraction))
+ + ((P2 - Point3D.Origin) * (3d * opposite * fraction * fraction))
+ + ((P3 - Point3D.Origin) * (fraction * fraction * fraction));
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.cs b/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.cs
new file mode 100644
index 00000000..75a39362
--- /dev/null
+++ b/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.cs
@@ -0,0 +1,11 @@
+namespace Aetheris.Kernel.Core.Geometry;
+
+/// <summary>Measured import evidence, in normalized model millimetres, for a non-analytic spline.</summary>
+public sealed record SplineRecoveryProvenance(
+ string SourceGeometryKind,
+ string RecoveryMethod,
+ double RecoveryToleranceMillimetres,
+ double MeasuredMaxDeviationMillimetres,
+ bool AnalyticRecognitionAttempted,
+ string AnalyticRecognitionResult,
+ bool RationalSourceRetained = false);
diff --git a/Aetheris.Kernel.Core/Geometry/SurfaceGeometry.cs b/Aetheris.Kernel.Core/Geometry/SurfaceGeometry.cs
index 185134bc..8c32b71c 100644
--- a/Aetheris.Kernel.Core/Geometry/SurfaceGeometry.cs
+++ b/Aetheris.Kernel.Core/Geometry/SurfaceGeometry.cs
@@ -59,6 +59,8 @@ public sealed record SurfaceGeometry
public BSplineSurfaceWithKnots? BSplineSurfaceWithKnots { get; }
+ public SplineRecoveryProvenance? RecoveryProvenance { get; private init; }
+
public static SurfaceGeometry FromPlane(PlaneSurface plane) => new(SurfaceGeometryKind.Plane, plane, null, null, null, null, null, null, null);
public static SurfaceGeometry FromCylinder(CylinderSurface cylinder) => new(SurfaceGeometryKind.Cylinder, null, cylinder, null, null, null, null, null, null);
@@ -74,4 +76,10 @@ public sealed record SurfaceGeometry
public static SurfaceGeometry FromSurfaceOfRevolution(SurfaceOfRevolutionSurface surface) => new(SurfaceGeometryKind.SurfaceOfRevolution, null, null, null, null, null, null, surface, null);
public static SurfaceGeometry FromBSplineSurfaceWithKnots(BSplineSurfaceWithKnots surface) => new(SurfaceGeometryKind.BSplineSurfaceWithKnots, null, null, null, null, null, null, null, surface);
+
+ public static SurfaceGeometry FromRecoveredBSplineSurfaceWithKnots(BSplineSurfaceWithKnots surface, SplineRecoveryProvenance provenance)
+ {
+ ArgumentNullException.ThrowIfNull(provenance);
+ return FromBSplineSurfaceWithKnots(surface) with { RecoveryProvenance = provenance };
+ }
}
diff --git a/Aetheris.Kernel.Core/Import/ImportContracts.cs b/Aetheris.Kernel.Core/Import/ImportContracts.cs
index c7f9405d..94ac7992 100644
--- a/Aetheris.Kernel.Core/Import/ImportContracts.cs
+++ b/Aetheris.Kernel.Core/Import/ImportContracts.cs
@@ -24,7 +24,10 @@ public enum ImportRepresentationTruthKind
public sealed record ImportRequest(string SourceText, ImportPolicy? Policy = null);
-public sealed record ImportPolicy(ImportLaneKind PreferredLane = ImportLaneKind.Auto);
+public sealed record ImportPolicy(
+ ImportLaneKind PreferredLane = ImportLaneKind.Auto,
+ double RecoveryToleranceMillimetres = 0.1d,
+ double PcurveQualificationToleranceMillimetres = 1e-3d);
public sealed record ImportResult(
KernelResult<BrepBody> BodyResult,
diff --git a/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs b/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs
index f71b2246..caaf8db3 100644
--- a/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242BsplineCurveRecoveryLane.cs
@@ -100,35 +100,7 @@ internal static class Step242BsplineCurveRecoveryLane
}
internal static Point3D? EvaluateRational(BSpline3Curve curve, IReadOnlyList<double> weights, double parameter)
- {
- var p = curve.Degree;
- var u = double.Min(double.Max(parameter, curve.DomainStart), curve.DomainEnd);
- if (double.Abs(u - curve.DomainEnd) <= 1e-12d) return curve.ControlPoints[^1];
- var span = FindSpan(curve, u);
- var points = new (double X, double Y, double Z, double W)[p + 1];
- for (var j = 0; j <= p; j++)
- {
- var index = span - p + j;
- var w = weights[index];
- var cp = curve.ControlPoints[index];
- points[j] = (cp.X * w, cp.Y * w, cp.Z * w, w);
- }
-
- for (var r = 1; r <= p; r++)
- {
- for (var j = p; j >= r; j--)
- {
- var leftKnot = curve.FullKnots[span - p + j];
- var rightKnot = curve.FullKnots[span + 1 + j - r];
- var denominator = rightKnot - leftKnot;
- var alpha = double.Abs(denominator) <= 1e-15d ? 0d : (u - leftKnot) / denominator;
- points[j] = Lerp(points[j - 1], points[j], alpha);
- }
- }
-
- if (double.Abs(points[p].W) <= DegenerateTolerance) return null;
- return new Point3D(points[p].X / points[p].W, points[p].Y / points[p].W, points[p].Z / points[p].W);
- }
+ => curve.EvaluateRational(weights, parameter);
private static bool TryFitCircle(IReadOnlyList<Point3D> samples, out Circle3Curve circle, out string reason)
{
@@ -172,24 +144,6 @@ internal static class Step242BsplineCurveRecoveryLane
return true;
}
- private static int FindSpan(BSpline3Curve curve, double u)
- {
- var n = curve.ControlPoints.Count - 1;
- if (u >= curve.FullKnots[n + 1]) return n;
- var low = curve.Degree;
- var high = n + 1;
- var mid = (low + high) / 2;
- while (u < curve.FullKnots[mid] || u >= curve.FullKnots[mid + 1])
- {
- if (u < curve.FullKnots[mid]) high = mid; else low = mid;
- mid = (low + high) / 2;
- }
- return mid;
- }
-
- private static (double X, double Y, double Z, double W) Lerp((double X, double Y, double Z, double W) a, (double X, double Y, double Z, double W) b, double t) =>
- (a.X + ((b.X - a.X) * t), a.Y + ((b.Y - a.Y) * t), a.Z + ((b.Z - a.Z) * t), a.W + ((b.W - a.W) * t));
-
private readonly record struct RecoveryContext(bool IsRationalLike, CircleProbe CircleProbe);
private readonly record struct CircleProbe(Circle3Curve? Circle, string Reason);
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 6f70582c..81d1005f 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -85,7 +85,10 @@ public static class Step242Exporter
var hyperbolaIds = new Dictionary<EdgeId, string>();
var surfaceIds = new Dictionary<SurfaceGeometryId, string>();
var advancedFaceIds = new Dictionary<FaceId, string>();
- var pcurveContextId = body.Bindings.PcurveBindings.Any()
+ // Keep source pcurves, but do not publish a partial recovered trim set.
+ var pcurveContextId = body.Bindings.PcurveBindings.Any(binding =>
+ body.PcurveRecoveryReport is not { IsSuccess: false }
+ || binding.SourceStepPcurveEntityId is not null)
? writer.AddEntity("REPRESENTATION_CONTEXT", Step242TextWriter.String("2D"), Step242TextWriter.String("parameter space"))
: null;
@@ -1090,14 +1093,19 @@ public static class Step242Exporter
var edgePcurveBindings = pcurveContextId is null
? []
: body.Bindings.PcurveBindings
- .Where(binding => model.GetCoedge(binding.CoedgeId).EdgeId == edgeId)
+ .Where(binding => model.GetCoedge(binding.CoedgeId).EdgeId == edgeId
+ && (body.PcurveRecoveryReport is not { IsSuccess: false }
+ || binding.SourceStepPcurveEntityId is not null))
.OrderBy(binding => binding.FaceId.Value)
.ThenBy(binding => binding.CoedgeId.Value)
.ToArray();
var pcurveIds = pcurveContextId is null
? []
: edgePcurveBindings
- .Select(binding => BuildStepPcurve(writer, binding, surfaceIds, pcurveContextId))
+ .Select(binding => BuildStepPcurve(writer, binding, surfaceIds, pcurveContextId,
+ curve.Kind == CurveGeometryKind.Line3 && binding.Qualification is
+ { Origin: PcurveBindingOrigin.RecoveredAnalytic or PcurveBindingOrigin.RecoveredSpline }
+ ? new ParameterInterval(0d, (endPoint - startPoint).Length) : null))
.Where(id => id is not null)
.Select(id => id!)
.ToArray();
@@ -1122,9 +1130,32 @@ public static class Step242Exporter
Step242TextWriter writer,
CoedgePcurveBinding binding,
IReadOnlyDictionary<SurfaceGeometryId, string> surfaceIds,
- string contextId)
+ string contextId,
+ ParameterInterval? reparameterizedLineDomain)
{
if (!surfaceIds.TryGetValue(binding.SurfaceGeometryId, out var surfaceId)) return null;
+ var representationName = binding.Qualification is { } qualification
+ ? $"aetheris-qualified-pcurve:{Step242TextWriter.Number(qualification.QualificationToleranceMillimetres)}"
+ : "pcurve";
+ if (reparameterizedLineDomain is { } lineDomain)
+ {
+ var sourceDomain = binding.Pcurve.Domain;
+ if (binding.Pcurve.PolynomialCurve is { } sourcePolynomial)
+ {
+ var span = sourceDomain.End - sourceDomain.Start;
+ var knots = sourcePolynomial.KnotValues.Select(value => lineDomain.Start
+ + (value - sourceDomain.Start) * (lineDomain.End - lineDomain.Start) / span).ToArray();
+ var remapped = new BSpline3Curve(sourcePolynomial.Degree, sourcePolynomial.ControlPoints,
+ sourcePolynomial.KnotMultiplicities, knots, sourcePolynomial.CurveForm,
+ sourcePolynomial.ClosedCurve, sourcePolynomial.SelfIntersect, sourcePolynomial.KnotSpec);
+ binding = binding with { Pcurve = PcurveGeometry.Polynomial(lineDomain, remapped) };
+ }
+ else if (binding.Pcurve.Kind == PcurveGeometryKind.Line)
+ binding = binding with { Pcurve = PcurveGeometry.Line(lineDomain,
+ binding.Pcurve.Points[0], binding.Pcurve.Points[1]) };
+ else if (binding.Pcurve.Kind == PcurveGeometryKind.Polyline)
+ binding = binding with { Pcurve = PcurveGeometry.Polyline(lineDomain, binding.Pcurve.Points) };
+ }
if (binding.Pcurve.PolynomialCurve is { } polynomial)
{
var controls = polynomial.ControlPoints.Select(p => writer.AddEntity("CARTESIAN_POINT", "$",
@@ -1137,7 +1168,7 @@ public static class Step242Exporter
Step242TextWriter.BooleanLogical(polynomial.ClosedCurve), Step242TextWriter.BooleanLogical(polynomial.SelfIntersect),
Step242TextWriter.List(polynomial.KnotMultiplicities.Select(n => n.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray()),
Step242TextWriter.List(polynomial.KnotValues.Select(Step242TextWriter.Number).ToArray()), Step242TextWriter.Enum(polynomial.KnotSpec));
- var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(curve), Step242TextWriter.Ref(contextId));
+ var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(curve), Step242TextWriter.Ref(contextId));
return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));
}
if (binding.Pcurve.Kind == PcurveGeometryKind.Line)
@@ -1155,7 +1186,7 @@ public static class Step242Exporter
var directionId = writer.AddEntity("DIRECTION", "$", Step242TextWriter.List(Step242TextWriter.Number(du / magnitude), Step242TextWriter.Number(dv / magnitude)));
var vectorId = writer.AddEntity("VECTOR", "$", Step242TextWriter.Ref(directionId), Step242TextWriter.Number(magnitude));
var lineId = writer.AddEntity("LINE", "$", Step242TextWriter.Ref(originId), Step242TextWriter.Ref(vectorId));
- var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(lineId), Step242TextWriter.Ref(contextId));
+ var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(lineId), Step242TextWriter.Ref(contextId));
return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));
}
if (binding.Pcurve.Kind is PcurveGeometryKind.Circle or PcurveGeometryKind.Ellipse)
@@ -1202,7 +1233,7 @@ public static class Step242Exporter
Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(binding.Pcurve.Domain.Start)})"),
Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(binding.Pcurve.Domain.End)})"),
Step242TextWriter.BooleanLogical(false), Step242TextWriter.Enum("PARAMETER"));
- var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(conicId), Step242TextWriter.Ref(contextId));
+ var representation = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(conicId), Step242TextWriter.Ref(contextId));
return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representation));
}
var samples = binding.Pcurve.Kind switch
@@ -1218,7 +1249,7 @@ public static class Step242Exporter
}).Select(point => writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(point.U), Step242TextWriter.Number(point.V))))
.ToArray();
var curve2dId = writer.AddEntity("POLYLINE", "$", Step242TextWriter.List(points));
- var representationId = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(curve2dId), Step242TextWriter.Ref(contextId));
+ var representationId = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String(representationName), Step242TextWriter.List(curve2dId), Step242TextWriter.Ref(contextId));
return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representationId));
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index 5ce9c8d3..51b4ee8e 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -111,10 +111,10 @@ public static class Step242Importer
return new PlanarMultiBoundJudgmentDiagnosticsScope(previous);
}
- public static KernelResult<BrepBody> ImportBody(string stepText)
+ public static KernelResult<BrepBody> ImportBody(string stepText, ImportPolicy? policy = null)
{
var orchestrator = ImportOrchestrator.CreateDefault();
- var result = orchestrator.Import(new ImportRequest(stepText));
+ var result = orchestrator.Import(new ImportRequest(stepText, policy));
return result.BodyResult;
}
@@ -678,6 +678,22 @@ public static class Step242Importer
}
}
+ if (orientation.Value.Geometry.Curves.Any(curve => curve.Value.RecoveryProvenance is not null)
+ || orientation.Value.Geometry.Surfaces.Any(surface => surface.Value.RecoveryProvenance is not null))
+ {
+ var recovery = BrepPcurveRecovery.Populate(
+ orientation.Value.Topology, orientation.Value.Geometry, orientation.Value.Bindings,
+ tolerance: document.PcurveQualificationToleranceMillimetres);
+ var pcurveEvidence = BrepPcurveValidator.Validate(orientation.Value,
+ document.PcurveQualificationToleranceMillimetres, requireEveryCoedge: true);
+ orientation.Value.PcurveRecoveryReport = pcurveEvidence.IsValid ? recovery : recovery with
+ {
+ IsSuccess = false,
+ Diagnostics = recovery.Diagnostics.Concat(pcurveEvidence.Diagnostics.Select(message =>
+ new BrepPcurveRecoveryDiagnostic("surf-pcurve-invalid", message))).ToArray()
+ };
+ }
+
var validation = BrepBindingValidator.Validate(orientation.Value, requireAllEdgeAndFaceBindings: true);
if (!validation.IsSuccess)
{
@@ -1074,15 +1090,22 @@ public static class Step242Importer
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(weightsResult.Diagnostics);
}
- var hasMaterialRationalWeights = weightsResult.Value.Any(w => double.IsFinite(w) && double.Abs(w - 1d) > 1e-12d);
- if (splineResult.Value.Degree != 2 || !hasMaterialRationalWeights)
+ var weights = weightsResult.Value;
+ if (weights.Count != splineResult.Value.ControlPoints.Count
+ || weights.Any(w => !double.IsFinite(w) || w <= 0d))
+ return FailureCurveBinding($"RATIONAL_B_SPLINE_CURVE #{curveEntity.Id} has invalid weights: expected one positive finite weight per control point.",
+ SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineCurve"));
+
+ // Uniform weights cancel in the rational quotient, even when their common value is not one.
+ var hasMaterialRationalWeights = weights.Any(w => double.Abs(w / weights[0] - 1d) > 1e-12d);
+ if (!hasMaterialRationalWeights)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
CurveGeometry.FromBSpline(splineResult.Value),
- new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd)));
+ explicitTrim ?? new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd)));
}
- var recoveryDecision = Step242BsplineCurveRecoveryLane.Decide(curveEntity, splineResult.Value, weightsResult.Value);
+ var recoveryDecision = Step242BsplineCurveRecoveryLane.Decide(curveEntity, splineResult.Value, weights);
if (recoveryDecision.RecoveredCurve is CurveGeometry recoveredCurve)
{
var trimResult = recoveredCurve.Kind == CurveGeometryKind.Circle3 && recoveredCurve.Circle3 is Circle3Curve recoveredCircle
@@ -1096,8 +1119,21 @@ public static class Step242Importer
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((recoveredCurve, trimResult.Value));
}
+ if (BSplineCurveRationalReduction.TryReduce(splineResult.Value, weights,
+ document.RecoveryToleranceMillimetres, out var reduced, out var deviation, out var reductionReason))
+ {
+ var provenance = new SplineRecoveryProvenance("RATIONAL_B_SPLINE_CURVE", "AdaptiveCubic",
+ document.RecoveryToleranceMillimetres, deviation, true, recoveryDecision.Reason);
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((
+ CurveGeometry.FromRecoveredBSpline(reduced, provenance),
+ explicitTrim ?? new ParameterInterval(reduced.DomainStart, reduced.DomainEnd)),
+ [new KernelDiagnostic(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info,
+ $"Rational curve #{curveEntity.Id}: analytic recognition failed; generic spline recovered. {reductionReason}",
+ SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineRecovered"))]);
+ }
+
return FailureCurveBinding(
- $"RATIONAL_B_SPLINE_CURVE #{curveEntity.Id} cannot be imported exactly: the curve is not a qualified analytic circle, and CurveGeometry has no weighted B-spline curve representation. Do not discard its weights or substitute the polynomial control polygon. {recoveryDecision.Reason}",
+ $"RATIONAL_B_SPLINE_CURVE #{curveEntity.Id}: analytic recognition failed ({recoveryDecision.Reason}); generic recovery failed: {reductionReason}",
SourceFor(curveEntity.Id, "Importer.Geometry.RationalBSplineCurve"));
}
@@ -1346,12 +1382,21 @@ public static class Step242Importer
// 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)
+ var sourceReductionTolerance = BSplineSurfaceRationalReduction.ResolveTolerance(
+ bSplineSurface, document.SourceDistanceAccuracyMillimetres);
+ // Source accuracies that would drive this approximate interchange conversion below
+ // 10 nm can require pathological control-net growth. Keep established source-accuracy
+ // behavior for ordinary files, and use the caller's engineering budget for that case.
+ var reductionTolerance = sourceReductionTolerance < 1e-5d
+ ? document.RecoveryToleranceMillimetres
+ : double.Min(document.RecoveryToleranceMillimetres, sourceReductionTolerance);
+ if (BSplineSurfaceRationalReduction.TryReduce(bSplineSurface, reductionTolerance, out var reducedSurface, out var deviation, out var reductionReason)
&& reducedSurface is not null)
{
+ var provenance = new SplineRecoveryProvenance("RATIONAL_B_SPLINE_SURFACE", "AdaptiveGreville",
+ document.RecoveryToleranceMillimetres, deviation, true, recoveryDecision.Reason);
return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success(
- (geometryId, SurfaceGeometry.FromBSplineSurfaceWithKnots(reducedSurface)),
+ (geometryId, SurfaceGeometry.FromRecoveredBSplineSurfaceWithKnots(reducedSurface, provenance)),
[new KernelDiagnostic(
KernelDiagnosticCode.Unknown,
KernelDiagnosticSeverity.Info,
@@ -3150,7 +3195,10 @@ public static class Step242Importer
candidate.PcurveEntityId,
candidate.CurveEntityId,
candidate.CurveType,
- candidate.SurfaceEntityId));
+ candidate.SurfaceEntityId,
+ candidate.DeclaredQualificationToleranceMillimetres is double declaredTolerance
+ ? new PcurveQualification(PcurveBindingOrigin.SourceValidated, 0d, declaredTolerance,
+ 67, "source-qualified", surface.Kind.ToString()) : null));
}
return KernelResult<IReadOnlyList<CoedgePcurveBinding>>.Success(result);
diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
index 95ef43dd..e41f31d1 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
@@ -605,6 +605,12 @@ internal sealed class Step242ParsedDocument
/// <summary>Distance accuracy the source file declares for its geometry, in millimetres, or null when it declares none.</summary>
public double? SourceDistanceAccuracyMillimetres { get; }
+ /// <summary>Engineering budget for recovered geometry after source lengths have been normalized to millimetres.</summary>
+ public double RecoveryToleranceMillimetres { get; set; } = 0.1d;
+
+ /// <summary>Base edge-to-lift budget, separately configurable from geometry recovery.</summary>
+ public double PcurveQualificationToleranceMillimetres { get; set; } = 1e-3d;
+
public KernelResult<Step242ParsedEntity> TryGetEntity(int id, string? expectedName = null)
{
if (!_entitiesById.TryGetValue(id, out var entity))
diff --git a/Aetheris.Kernel.Core/Step242/StepImportConnectorAndLanes.cs b/Aetheris.Kernel.Core/Step242/StepImportConnectorAndLanes.cs
index b6d2cb4d..3ed893fd 100644
--- a/Aetheris.Kernel.Core/Step242/StepImportConnectorAndLanes.cs
+++ b/Aetheris.Kernel.Core/Step242/StepImportConnectorAndLanes.cs
@@ -46,6 +46,16 @@ internal sealed class StepSourceConnector : ISourceConnector
return KernelResult<IParsedSourceDocument>.Failure(parseResult.Diagnostics);
}
+ var tolerance = request.Policy?.RecoveryToleranceMillimetres ?? 0.1d;
+ if (!double.IsFinite(tolerance) || tolerance <= 0d)
+ return Step242ImportSharedUtilities.NotImplementedFailure<IParsedSourceDocument>(
+ "RecoveryToleranceMillimetres must be a positive finite distance.", "Importer.RecoveryTolerance");
+ parseResult.Value.RecoveryToleranceMillimetres = tolerance;
+ var pcurveTolerance = request.Policy?.PcurveQualificationToleranceMillimetres ?? 1e-3d;
+ if (!double.IsFinite(pcurveTolerance) || pcurveTolerance <= 0d)
+ return Step242ImportSharedUtilities.NotImplementedFailure<IParsedSourceDocument>(
+ "PcurveQualificationToleranceMillimetres must be a positive finite distance.", "Importer.PcurveQualificationTolerance");
+ parseResult.Value.PcurveQualificationToleranceMillimetres = double.Min(pcurveTolerance, tolerance);
return KernelResult<IParsedSourceDocument>.Success(new StepParsedSourceDocument(parseResult.Value));
}
}
diff --git a/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.cs b/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.cs
index 599fc1d0..3712ccca 100644
--- a/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.cs
+++ b/Aetheris.Kernel.Core/Step242/StepPcurveDecoder.cs
@@ -12,7 +12,8 @@ internal sealed record ImportedStepPcurve(
int PcurveEntityId,
int CurveEntityId,
string CurveType,
- int SurfaceEntityId);
+ int SurfaceEntityId,
+ double? DeclaredQualificationToleranceMillimetres);
internal static class StepPcurveDecoder
{
@@ -51,8 +52,17 @@ internal static class StepPcurveDecoder
if (!curveResult.IsSuccess) return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Failure(curveResult.Diagnostics);
var geometryResult = DecodeGeometry(document, curveResult.Value, edgeDomain);
if (!geometryResult.IsSuccess) return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Failure(geometryResult.Diagnostics);
+ const string qualifier = "aetheris-qualified-pcurve:";
+ var name = (representationResult.Value.Arguments.ElementAtOrDefault(0) as Step242StringValue)?.Value;
+ double? declaredTolerance = null;
+ if (name?.StartsWith(qualifier, StringComparison.Ordinal) == true
+ && double.TryParse(name[qualifier.Length..], System.Globalization.NumberStyles.Float,
+ System.Globalization.CultureInfo.InvariantCulture, out var parsedTolerance)
+ && double.IsFinite(parsedTolerance) && parsedTolerance is > 0d and <= 0.1d)
+ declaredTolerance = parsedTolerance;
result.Add(new ImportedStepPcurve(geometryResult.Value.Geometry, geometryResult.Value.SameSense,
- pcurve.Id, curveResult.Value.Id, DescribeCurveType(curveResult.Value), supportReference.TargetId));
+ pcurve.Id, curveResult.Value.Id, DescribeCurveType(curveResult.Value), supportReference.TargetId,
+ declaredTolerance));
}
return KernelResult<IReadOnlyList<ImportedStepPcurve>>.Success(result);
}
@@ -123,10 +133,15 @@ internal static class StepPcurveDecoder
{
var spline = Step242SubsetDecoder.ReadBSplineCurveWithKnots(document, splineEntity, allowTwoDimensionalControlPoints: true);
if (!spline.IsSuccess) return KernelResult<DecodedPcurveGeometry>.Failure(spline.Diagnostics);
- var splineDomain = new ParameterInterval(
- System.Math.Max(domain.Start, spline.Value.DomainStart),
- System.Math.Min(domain.End, spline.Value.DomainEnd));
- if (fallbackDomain.Equals(domain)) splineDomain = new ParameterInterval(spline.Value.DomainStart, spline.Value.DomainEnd);
+ var splineStart = fallbackDomain.Equals(domain) ? spline.Value.DomainStart
+ : System.Math.Max(domain.Start, spline.Value.DomainStart);
+ var splineEnd = fallbackDomain.Equals(domain) ? spline.Value.DomainEnd
+ : System.Math.Min(domain.End, spline.Value.DomainEnd);
+ if (splineEnd < splineStart)
+ return Failure<DecodedPcurveGeometry>(
+ $"Pcurve parameter interval [{domain.Start:R}, {domain.End:R}] does not overlap its spline domain [{spline.Value.DomainStart:R}, {spline.Value.DomainEnd:R}].",
+ "Importer.Pcurve.SplineDomain");
+ var splineDomain = new ParameterInterval(splineStart, splineEnd);
var rational = Step242SubsetDecoder.TryGetConstructor(source.Instance, "RATIONAL_B_SPLINE_CURVE");
if (rational is null)
return Success(PcurveGeometry.Polynomial(splineDomain, spline.Value));
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 9221a8e5..e2bc828f 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -194,7 +194,7 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
var importResponse = await _client.PostAsJsonAsync(
$"/api/v1/documents/{document.Data!.DocumentId}/import/step",
new StepImportRequestDto(unsupportedStepText, "Unsupported"));
- importResponse.EnsureSuccessStatusCode();
+ Assert.True(importResponse.IsSuccessStatusCode, await importResponse.Content.ReadAsStringAsync());
var imported = await importResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();
Assert.NotNull(imported);
Assert.True(imported!.Success);
@@ -338,7 +338,7 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
var importResponse = await _client.PostAsJsonAsync(
$"/api/v1/documents/{document.Data!.DocumentId}/import/step",
new StepImportRequestDto(unsupportedStepText, "Unsupported"));
- importResponse.EnsureSuccessStatusCode();
+ Assert.True(importResponse.IsSuccessStatusCode, await importResponse.Content.ReadAsStringAsync());
var imported = await importResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();
var displayPrepared = await PrepareDisplayAsync(document.Data.DocumentId, imported!.Data!.OccurrenceId);
diff --git a/Aetheris.Surfacing/BoundedPcurveBuilder.cs b/Aetheris.Surfacing/BoundedPcurveBuilder.cs
index 3e433345..063138fc 100644
--- a/Aetheris.Surfacing/BoundedPcurveBuilder.cs
+++ b/Aetheris.Surfacing/BoundedPcurveBuilder.cs
@@ -1,246 +1,19 @@
-using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Geometry;
-using Aetheris.Kernel.Core.Geometry.Surfaces;
-using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Topology;
namespace Aetheris.Surfacing;
public sealed record PcurveBuildResult(bool IsSuccess, int Count, double MaximumResidual, IReadOnlyList<SculptDiagnostic> Diagnostics);
-/// <summary>Builds deterministic face-local pcurves for the qualified Plane/Cylinder/non-rational B-spline matrix.</summary>
+/// <summary>Compatibility facade for the shared kernel pcurve recovery path.</summary>
public static class BoundedPcurveBuilder
{
public static PcurveBuildResult Populate(TopologyModel topology, BrepGeometryStore geometry, BrepBindingModel bindings,
double tolerance = 1e-5, int sampleCount = 129)
{
- var diagnostics = new List<SculptDiagnostic>();
- var count = 0;
- var maximum = 0d;
- foreach (var face in topology.Faces.OrderBy(item => item.Id.Value))
- {
- if (!bindings.TryGetFaceBinding(face.Id, out var faceBinding) || !geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface is null)
- continue;
- foreach (var coedge in face.LoopIds.Select(topology.GetLoop).SelectMany(loop => loop.CoedgeIds.Select(topology.GetCoedge)))
- {
- if (!bindings.TryGetEdgeBinding(coedge.EdgeId, out var edgeBinding) || !geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null
- || edgeBinding.TrimInterval is not { } interval)
- {
- diagnostics.Add(new("surf-pcurve-invalid", $"Coedge {coedge.Id.Value} has no bounded 3D edge curve.", coedge.Id.Value.ToString()));
- continue;
- }
- if (bindings.TryGetPcurveBinding(coedge.Id, out var retained))
- {
- var residual = MaximumResidual(surface, curve, retained.Pcurve, interval, sampleCount);
- if (retained.FaceId != face.Id || retained.SurfaceGeometryId != faceBinding.SurfaceGeometryId || residual > tolerance)
- diagnostics.Add(new("surf-pcurve-invalid", "Retained pcurve has inconsistent ownership or geometry.", coedge.Id.Value.ToString()));
- maximum = double.Max(maximum, residual); count++; continue;
- }
- var built = Build(surface, curve, interval, tolerance, sampleCount);
- if (built.Pcurve is null)
- {
- diagnostics.Add(new("surf-pcurve-invalid", built.Diagnostic ?? "Pcurve construction failed.", coedge.Id.Value.ToString()));
- continue;
- }
- bindings.AddPcurveBinding(new(coedge.Id, face.Id, faceBinding.SurfaceGeometryId, built.Pcurve));
- maximum = double.Max(maximum, built.MaximumResidual);
- count++;
- }
- }
- return new(diagnostics.Count == 0 && maximum <= tolerance, count, maximum, diagnostics);
- }
-
- private static (PcurveGeometry? Pcurve, double MaximumResidual, string? Diagnostic) Build(
- SurfaceGeometry surface, CurveGeometry curve, ParameterInterval interval, double tolerance, int samples)
- {
- if (surface.Plane is { } plane)
- {
- var start = PlaneUv(plane, EvaluateCurve(curve, interval.Start));
- var end = PlaneUv(plane, EvaluateCurve(curve, interval.End));
- if (curve.Kind == CurveGeometryKind.Line3) return (PcurveGeometry.Line(interval, start, end), 0d, null);
- if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)
- {
- var center = PlaneUv(plane, circle.Center);
- var cosinePoint = PlaneUv(plane, circle.Evaluate(0d));
- var sinePoint = PlaneUv(plane, circle.Evaluate(double.Pi / 2d));
- return (PcurveGeometry.Ellipse(interval, center,
- new(cosinePoint.U - center.U, cosinePoint.V - center.V),
- new(sinePoint.U - center.U, sinePoint.V - center.V)), 0d, null);
- }
- if (curve.BSpline3 is { } polynomial)
- {
- // Affine projection commutes with B-spline evaluation. The hull bound
- // certifies the whole 3D curve lies on this support, without fitting.
- var bound = polynomial.ControlPoints.Max(p => double.Abs((p - plane.Origin).Dot(plane.Normal.ToVector())));
- if (bound > tolerance) return (null, bound, "Polynomial edge control hull is not on the planar support.");
- var controls = polynomial.ControlPoints.Select(p => { var uv = PlaneUv(plane, p); return new Point3D(uv.U, uv.V, 0); }).ToArray();
- var uvCurve = new BSpline3Curve(polynomial.Degree, controls, polynomial.KnotMultiplicities, polynomial.KnotValues,
- polynomial.CurveForm, polynomial.ClosedCurve, polynomial.SelfIntersect, polynomial.KnotSpec);
- return (PcurveGeometry.Polynomial(interval, uvCurve), bound, null);
- }
- var lineCandidate = PcurveGeometry.Line(interval, start, end);
- var lineResidual = MaximumResidual(surface, curve, lineCandidate, interval, 67);
- if (lineResidual <= tolerance) return (lineCandidate, lineResidual, null);
- const int denseSamples = 4097;
- return (PcurveGeometry.Polyline(interval, Sample(interval, denseSamples, t => PlaneUv(plane, EvaluateCurve(curve, t)))), 0d, null);
- }
- if (surface.Cylinder is { } cylinder)
- {
- var points = Sample(interval, samples, t => CylinderUv(cylinder, EvaluateCurve(curve, t))).ToArray();
- UnwrapAngles(points);
- return (PcurveGeometry.Polyline(interval, points), 0d, null);
- }
- if (surface.BSplineSurfaceWithKnots is not { } spline)
- return (null, double.PositiveInfinity, $"Surface family {surface.Kind} is outside the qualified pcurve matrix.");
-
- var startInverse = Invert(spline, EvaluateCurve(curve, interval.Start), null);
- var endInverse = Invert(spline, EvaluateCurve(curve, interval.End), startInverse.Success ? startInverse.Uv : null);
- if (startInverse.Success && endInverse.Success)
- {
- var lineCandidate = PcurveGeometry.Line(interval, startInverse.Uv, endInverse.Uv);
- var lineResidual = MaximumResidual(surface, curve, lineCandidate, interval, 67);
- if (lineResidual <= tolerance) return (lineCandidate, lineResidual, null);
- }
-
- const int inverseSamples = 4097;
- var uv = new List<SurfaceParameterPoint>(inverseSamples);
- SurfaceParameterPoint? seed = null;
- var maximum = 0d;
- for (var index = 0; index < inverseSamples; index++)
- {
- var t = interval.Start + ((interval.End - interval.Start) * index / (inverseSamples - 1d));
- var point = EvaluateCurve(curve, t);
- var inverse = Invert(spline, point, seed);
- if (!inverse.Success || inverse.Residual > tolerance)
- return (null, inverse.Residual, $"Non-rational B-spline inverse failed at sample {index}; residual={inverse.Residual:R}, tolerance={tolerance:R}.");
- seed = inverse.Uv;
- uv.Add(inverse.Uv);
- maximum = double.Max(maximum, inverse.Residual);
- }
- return (PcurveGeometry.Polyline(interval, uv), maximum, null);
- }
-
- private static (bool Success, SurfaceParameterPoint Uv, double Residual) Invert(BSplineSurfaceWithKnots spline, Point3D target, SurfaceParameterPoint? prior)
- {
- // Intersection traces are parameter-continuous, so the preceding inverse is
- // the deterministic seed after the first sample. Avoiding a fresh global grid
- // search at every dense qualification point keeps high-accuracy pcurves bounded.
- var best = prior ?? GridSeed(spline, target);
- for (var iteration = 0; iteration < 32; iteration++)
- {
- var point = spline.Evaluate(best.U, best.V);
- var residual = point - target;
- if (residual.Length <= 1e-8d) return (true, best, residual.Length);
- var hu = double.Max((spline.DomainEndU - spline.DomainStartU) * 1e-4d, 1e-7d);
- var hv = double.Max((spline.DomainEndV - spline.DomainStartV) * 1e-4d, 1e-7d);
- var du = (spline.Evaluate(double.Min(best.U + hu, spline.DomainEndU), best.V) - spline.Evaluate(double.Max(best.U - hu, spline.DomainStartU), best.V))
- / (double.Min(best.U + hu, spline.DomainEndU) - double.Max(best.U - hu, spline.DomainStartU));
- var dv = (spline.Evaluate(best.U, double.Min(best.V + hv, spline.DomainEndV)) - spline.Evaluate(best.U, double.Max(best.V - hv, spline.DomainStartV)))
- / (double.Min(best.V + hv, spline.DomainEndV) - double.Max(best.V - hv, spline.DomainStartV));
- var a = du.Dot(du); var b = du.Dot(dv); var c = dv.Dot(dv);
- var r1 = du.Dot(residual); var r2 = dv.Dot(residual);
- var determinant = (a * c) - (b * b);
- if (double.Abs(determinant) <= 1e-18d) break;
- var deltaU = ((c * r1) - (b * r2)) / determinant;
- var deltaV = ((a * r2) - (b * r1)) / determinant;
- var accepted = false;
- for (var damping = 1d; damping >= 1d / 64d; damping *= .5d)
- {
- var candidate = new SurfaceParameterPoint(
- System.Math.Clamp(best.U - (deltaU * damping), spline.DomainStartU, spline.DomainEndU),
- System.Math.Clamp(best.V - (deltaV * damping), spline.DomainStartV, spline.DomainEndV));
- if ((spline.Evaluate(candidate.U, candidate.V) - target).LengthSquared >= residual.LengthSquared) continue;
- best = candidate; accepted = true; break;
- }
- if (!accepted) break;
- }
- // Deterministic bounded pattern refinement handles domain-boundary minima where
- // the two-column normal equation can become poorly conditioned.
- var stepU = (spline.DomainEndU - spline.DomainStartU) / 32d;
- var stepV = (spline.DomainEndV - spline.DomainStartV) / 32d;
- var bestDistance = (spline.Evaluate(best.U, best.V) - target).LengthSquared;
- for (var iteration = 0; iteration < 64 && (stepU > 1e-13d || stepV > 1e-13d); iteration++)
- {
- var improved = false;
- foreach (var offsetU in new[] { -stepU, 0d, stepU }) foreach (var offsetV in new[] { -stepV, 0d, stepV })
- {
- if (offsetU == 0d && offsetV == 0d) continue;
- var candidate = new SurfaceParameterPoint(
- System.Math.Clamp(best.U + offsetU, spline.DomainStartU, spline.DomainEndU),
- System.Math.Clamp(best.V + offsetV, spline.DomainStartV, spline.DomainEndV));
- var distance = (spline.Evaluate(candidate.U, candidate.V) - target).LengthSquared;
- if (distance >= bestDistance) continue;
- best = candidate; bestDistance = distance; improved = true;
- }
- if (!improved) { stepU *= .5d; stepV *= .5d; }
- }
- var finalResidual = (spline.Evaluate(best.U, best.V) - target).Length;
- return (finalResidual <= 1e-5d, best, finalResidual);
- }
-
- private static SurfaceParameterPoint GridSeed(BSplineSurfaceWithKnots spline, Point3D target)
- {
- var best = new SurfaceParameterPoint(spline.DomainStartU, spline.DomainStartV);
- var distance = double.PositiveInfinity;
- const int divisions = 32;
- for (var i = 0; i <= divisions; i++) for (var j = 0; j <= divisions; j++)
- {
- var u = spline.DomainStartU + ((spline.DomainEndU - spline.DomainStartU) * i / divisions);
- var v = spline.DomainStartV + ((spline.DomainEndV - spline.DomainStartV) * j / divisions);
- var d = (spline.Evaluate(u, v) - target).LengthSquared;
- if (d < distance) { distance = d; best = new(u, v); }
- }
- return best;
- }
-
- private static Point3D EvaluateCurve(CurveGeometry curve, double parameter) => curve.Kind switch
- {
- CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(parameter),
- CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(parameter),
- CurveGeometryKind.BSpline3 => curve.BSpline3!.Value.Evaluate(parameter),
- CurveGeometryKind.Ellipse3 => curve.Ellipse3!.Value.Evaluate(parameter),
- CurveGeometryKind.Hyperbola3 => curve.Hyperbola3!.Value.Evaluate(parameter),
- _ => throw new NotSupportedException($"Curve family {curve.Kind} is outside the qualified pcurve matrix.")
- };
- private static SurfaceParameterPoint PlaneUv(PlaneSurface plane, Point3D point)
- {
- var d = point - plane.Origin;
- return new(d.Dot(plane.UAxis.ToVector()), d.Dot(plane.VAxis.ToVector()));
- }
- private static SurfaceParameterPoint CylinderUv(CylinderSurface cylinder, Point3D point)
- {
- var d = point - cylinder.Origin;
- return new(double.Atan2(d.Dot(cylinder.YAxis.ToVector()), d.Dot(cylinder.XAxis.ToVector())), d.Dot(cylinder.Axis.ToVector()));
- }
- private static void UnwrapAngles(SurfaceParameterPoint[] points)
- {
- for (var index = 1; index < points.Length; index++)
- {
- var u = points[index].U;
- while (u - points[index - 1].U > double.Pi) u -= 2d * double.Pi;
- while (u - points[index - 1].U < -double.Pi) u += 2d * double.Pi;
- points[index] = points[index] with { U = u };
- }
- }
- private static IReadOnlyList<SurfaceParameterPoint> Sample(ParameterInterval interval, int count, Func<double, SurfaceParameterPoint> evaluator)
- => Enumerable.Range(0, count).Select(index => evaluator(interval.Start + ((interval.End - interval.Start) * index / (count - 1d)))).ToArray();
-
- private static double MaximumResidual(SurfaceGeometry surface, CurveGeometry curve, PcurveGeometry pcurve, ParameterInterval interval, int count)
- {
- var maximum = 0d;
- for (var index = 0; index < count; index++)
- {
- var parameter = interval.Start + ((interval.End - interval.Start) * index / (count - 1d));
- var uv = pcurve.Evaluate(parameter);
- var onSurface = surface.Kind switch
- {
- SurfaceGeometryKind.Plane => surface.Plane!.Value.Evaluate(uv.U, uv.V),
- SurfaceGeometryKind.BSplineSurfaceWithKnots => surface.BSplineSurfaceWithKnots!.Evaluate(uv.U, uv.V),
- _ => throw new InvalidOperationException()
- };
- maximum = double.Max(maximum, (onSurface - EvaluateCurve(curve, parameter)).Length);
- }
- return maximum;
+ var result = BrepPcurveRecovery.Populate(topology, geometry, bindings, tolerance, sampleCount);
+ return new PcurveBuildResult(result.IsSuccess, result.Count, result.MaximumResidual,
+ result.Diagnostics.Select(d => new SculptDiagnostic(d.Code, d.Message, d.Entity)).ToArray());
}
}
diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.md
index 20b7d02a..727906c6 100644
--- a/docs/public/firmament/step-import.md
+++ b/docs/public/firmament/step-import.md
@@ -2,6 +2,10 @@
Use `aetheris analyze part.step --json` to inspect STEP topology, analytic surface families, bounds, manifold assessment, and semantic PMI. When a part is easiest to understand by its manufacturing section, inspect it first with `aetheris analyze section part.step --xy|--xz|--yz --offset value --json`; use `--origin x,y,z --normal x,y,z` for an arbitrary construction plane and `--out section.svg` for deterministic visual evidence. This section-first path preserves analytic line/arc trims and reports closed-loop nesting instead of asking a tessellated view to carry design intent. Use `aetheris sheetmetal recognize` for bounded Sheet Metal recognition rather than treating generic topology analysis as manufacturing intent.
+`analyze --json` also reports `splineRecovery`: counts of analytic, exact spline, recovered spline, and unsupported edge/face geometry; the worst measured recovery deviation; and the requested engineering tolerance. The default `ImportPolicy.RecoveryToleranceMillimetres` is 0.1 mm after STEP unit normalization. Rational curves and surfaces are recognized as analytic geometry where qualified; otherwise the importer attempts bounded generic spline recovery and records provenance on recovered geometry. The maximum deviation is sampled evidence.
+
+For recovered geometry, `pcurveQualification` reports the face-edge use count, source and reconstructed pcurves, failed uses, worst sampled 3D lift deviation, and surface-family counts. `qualified` means every coedge is bound and the independent pcurve validator accepts edge/surface agreement, endpoint sense, and loop closure. `inspectable-unqualified` means the body can still be inspected, but its recovered pcurves do not form a complete qualified trim set; STEP export then omits that partial set while retaining valid source pcurves. `ImportPolicy.PcurveQualificationToleranceMillimetres` defaults to 0.001 mm. A recovered curve or support can use a larger local allowance based on its measured geometry-recovery deviations, capped by the separate 0.1 mm geometry recovery budget. The CLI reports the observed lift deviation separately from geometry recovery deviation.
+
Firmament `inlineSTEP` consumes Aetheris-canonical AP242 on the bounded production path. Imported faces are selected by source entity identity, for example `body.face(#170)`, and recognized regions may supply stable semantic aliases. [`inline-step-cantilever.firmament`](../../../fixtures/Canonical/FEA/inline-step-cantilever.firmament) demonstrates FEA on a checked-in canonical STEP resource.
The single-body importer does not promise arbitrary containment, multi-root assemblies, or every AP242 surface family as one native body. `aetheris analyze compound part.step --json` is the exact inspection path for disconnected rigid roots: it reports each root independently and never silently selects or merges one. Multiple geometric roots alone do **not** establish product structure, occurrence transforms, mates, or interfaces. Use assembly import when the STEP product graph carries that semantics, and use Firmament assembly authoring when the intended component relationships must be stated explicitly. Unsupported containment in FEA reports `firmament-analysis-inline-step-containment-unsupported`; missing files and unresolved face identities are fatal diagnostics.
diff --git a/docs/release/STEP-NURBS-RECOVERY-X0.md b/docs/release/STEP-NURBS-RECOVERY-X0.md
new file mode 100644
index 00000000..edc1c8be
--- /dev/null
+++ b/docs/release/STEP-NURBS-RECOVERY-X0.md
@@ -0,0 +1,34 @@
+# STEP NURBS recovery X0
+
+**X0 verdict: Meaningful progression.** Aetheris now imports the supplied McMaster threaded bolt through its exact BRep path, including weighted curve `#2175`, and preserves its source topology. Generic weighted curves that do not recognize as circles are adaptively approximated as polynomial cubic B-splines. The supplied body tessellates and exports/reimports through STEP. At the X0 checkpoint, full pcurve qualification remained open; see `STEP-RECOVERED-PCURVE-X1.md` for the subsequent trim-binding result.
+
+## Policy and units
+
+The importer tries analytic recognition first, preserves directly supported non-rational splines exactly, then attempts bounded generic recovery. `ImportPolicy.RecoveryToleranceMillimetres` defaults to **0.1 mm**. STEP source lengths are normalized to millimetres before recovery. This engineering budget is distinct from kernel topology tolerances and the much stricter analytic recognition gates. Imported generic curves and surfaces carry `SplineRecoveryProvenance` with source kind, method, requested budget, maximum observed deviation, and analytic recognition result. The reported deviation is a sampled measurement, not a certified supremum.
+
+For rational 3D curves, the shared `BSpline3Curve.EvaluateRational` evaluates the source with its original control points, knots, and weights. `BSplineCurveRationalReduction` refines individual nonzero knot spans and stops once a seven-point interior check per candidate span meets the requested budget, with explicit depth and segment caps. Uniform weights cancel and preserve the polynomial spline exactly. A failed bounded fit produces a diagnostic instead of discarding weights. Rational surfaces use the existing `BSplineSurfaceRationalReduction` at the engineering budget; source rational surfaces remain the fallback when reduction fails, as supported by the legacy interchange route.
+
+## Mandatory local witness
+
+The supplied `91280A546_Medium-Strength Class 8.8 Steel Hex Head Screw.STEP` is kept outside the repository. With the new importer, `aetheris analyze <file> --json` reports one body, one shell, **147 faces, 405 edges, 268 vertices**, an enclosed-manifold structural assessment, **160 recovered curves**, **3 recovered surfaces**, and **0 unsupported entities**. The worst sampled recovery deviation is **0.023580323 mm**, below the 0.1 mm default. The normalized bounding box is approximately `13.0 × 15.011107 × 56.432813 mm`. These counts describe imported topology, not feature history or semantic thread recognition.
+
+The local opt-in test uses `AETHERIS_STEP_NURBS_WITNESS=<path>` and asserts import, topology, tessellation, STEP export/reimport, and less than 0.01 mm sampled corresponding-spline-edge drift after roundtrip. Missing local witness data skips the qualification work. A deterministic diagnostic [isometric wireframe](../../artifacts/local/step-nurbs-recovery-x0/mcmaster-bolt.svg) was generated from the imported body; it covers all 405 boundary edges and 131 of 147 faces with trimmed isolines. No SolidWorks/Fusion reference image was supplied in this task, so a visual match is not claimed.
+
+The first attempted witness import, still using the older source-accuracy surface reduction budget, ran more than two minutes and was stopped. With the explicit 0.1 mm surface budget, the CLI analysis completed in about two seconds on this machine. This is a measured before/after bound, not a controlled benchmark. The existing 3DM recovery inspection contributes the same-net candidate idea, while the rational evaluator now lives on the shared kernel spline type; a full 3DM BRep importer is outside this milestone.
+
+## Remaining boundary
+
+The supplied source has no imported pcurve bindings. The diagnostic `wireframe` path attempted pcurve recovery and produced **579** bindings with a small residual for those recovered, but its result is not fully qualified. Its diagnostics include **54** cone-family exclusions and **177** non-rational B-spline inverse failures. Some inverse residuals are several millimetres, well outside the engineering budget. Accordingly, `pcurve/3D` agreement for every recovered trim is not yet established, and this milestone is not accepted as complete. The BRep tessellation and STEP roundtrip checks establish downstream usability of this witness; they do not substitute for all-trim pcurve qualification.
+
+## Validation
+
+The full solution builds with zero errors and existing Web.Runtime WASM warnings. The kernel fast lane passes **1,002/1,002** tests; the full kernel lane, including the NIST corpus, passes **1,135/1,135**. The serial solution test gate has one failure in an unchanged OBJ hex-bolt assertion (`MeshObj_HexBolt_ExportsStructuredPolygonsDirectlyFromSurfaceMeshIr`, expected 905 polygons, actual 908). The local McMaster witness test and the corrected CLI analyze baseline test pass. `git diff --check` passes.
+
+## Reproduction
+
+```powershell
+$env:AETHERIS_STEP_NURBS_WITNESS = '<local McMaster STEP path>'
+dotnet test Aetheris.Kernel.Core.Tests -c Release --filter FullyQualifiedName~Step242LocalRationalWitnessTests
+dotnet run --project Aetheris.CLI -c Release -- analyze $env:AETHERIS_STEP_NURBS_WITNESS --json
+dotnet run --project Aetheris.CLI -c Release -- wireframe $env:AETHERIS_STEP_NURBS_WITNESS --out artifacts/local/step-nurbs-recovery-x0/mcmaster-bolt.svg --view iso --density 8 --json
+```
diff --git a/docs/release/STEP-RECOVERED-PCURVE-X1.md b/docs/release/STEP-RECOVERED-PCURVE-X1.md
new file mode 100644
index 00000000..d5fd0ccb
--- /dev/null
+++ b/docs/release/STEP-RECOVERED-PCURVE-X1.md
@@ -0,0 +1,36 @@
+# STEP recovered pcurve X1
+
+**Verdict: Meaningful progression, with the mandatory McMaster witness qualified.** The normal exact-BRep import path now constructs and qualifies a face-local pcurve for every one of its 810 coedge uses. The source supplies none. The body remains one enclosed manifold with 147 faces, 405 edges, and 268 vertices; its X0 geometry recovery remains 160 curves, 3 surfaces, and 0.023580323 mm worst sampled geometry deviation. A separate NIST part still has a partial recovered trim set, so the broader corpus qualification target remains open.
+
+## Binding and tolerance
+
+The importer retains and validates source pcurves first. When geometry recovery was needed, it reconstructs missing coedge pcurves from each edge curve and supporting face. Planes use affine projection, cylinders and cones use analytic inverse frames, and sphere and torus inverses use their existing analytic parameterizations. Periodic angles are unwrapped along each trim. Cone trims that were previously excluded now use a bounded cubic UV curve; each candidate is accepted only after its lift back to the support is sampled against the unchanged 3D edge. Spline supports use a bounded grid and dense domain-boundary initialization at the first point, then neighboring UV seeds with damped Gauss–Newton and bounded pattern refinement. Polyline sampling doubles from 129 up to 4097 only as required by measured 3D lift error.
+
+`ImportPolicy.PcurveQualificationToleranceMillimetres` defaults to **0.001 mm**, distinct from kernel topology tolerances and the **0.1 mm** default geometry recovery budget. For a recovered edge or support, the local allowance includes 1.25 times the sum of their measured X0 deviations and never exceeds the geometry budget. Each recovered binding records origin, method, surface family, local tolerance, lift sample count, and maximum sampled edge-to-lift deviation; source STEP identity remains on imported bindings. The importer also runs the independent pcurve validator over every coedge, including endpoints, sense, periodic UV loop closure, and surface domains. A body with incomplete bindings remains inspectable but reports `inspectable-unqualified`; export suppresses its partial recovered pcurve set and retains valid source pcurves.
+
+## McMaster evidence
+
+The local witness is `91280A546_Medium-Strength Class 8.8 Steel Hex Head Screw.STEP`, supplied outside the repository. Before X1, diagnostic reconstruction produced 579 bindings and left 54 cone and 177 spline inverse failures. The completed import produces **810/810 bindings, zero failed bindings**, including **54 cone**, **317 cylinder**, **134 plane**, and **305 spline-support** uses. The worst sampled pcurve lift deviation is **0.031310873 mm** under its local qualification allowance; this is separate from the **0.023580323 mm** geometry recovery deviation. A coarse first-sample spline grid missed a narrow boundary solution on face 143 / edge 255; bounded boundary search resolves that initialization failure. The witness remains tessellatable and exports to STEP with pcurve associations. Reimport validates all 810 source pcurves, preserves face and edge counts, and passes the existing sampled corresponding-spline-edge drift bound of 0.01 mm.
+
+The `analyze --json` `pcurveQualification` object reports `qualified`, total/source/recovered/failed binding counts, worst sampled lift deviation, base tolerance, and surface-family counts. A measured CLI wireframe run took **4.26 seconds** on this machine, including import, pcurve qualification, and SVG output; the X0 analyze path had taken about two seconds, but these are different commands, not a controlled before/after timing comparison. The local wireframe output and raw JSON live under ignored `artifacts/local/step-recovered-pcurve-x1/`; they are diagnostic artifacts, not committed fixtures.
+
+## Export parameterization
+
+STEP export rewrites 3D lines from their start vertices, so recovered UV pcurves on those lines must receive the same affine parameter change. The exporter maps their spline knots or line/polyline domains before writing `PCURVE`. It also names recovered pcurve representations with their bounded local qualification tolerance. Reimport treats that name as a tolerance claim and independently checks the lifted curve and loop; ordinary source pcurves continue to use source accuracy. A source pcurve with a disjoint spline domain receives a specific diagnostic instead of an interval-constructor exception.
+
+## Scope and limits
+
+Measured deviations are sampled bounds, not mathematical suprema. Sphere and torus analytic inverse paths exist, but the supplied bolt exercises only plane, cylinder, cone, and spline supports. A NIST CTC part with four recovered surfaces currently reports a partial trim set (`inspectable-unqualified`); its STEP export intentionally omits those partial recovered pcurves. This does not change that part's pre-X1 interchange result. The source McMaster STEP file remains uncommitted.
+
+## Validation
+
+The local McMaster witness test passes import, all-binding qualification, independent pcurve validation, tessellation, bound STEP export/reimport, and sampled spline drift. The fast kernel lane passes **1,002/1,002**; the serial full kernel corpus passes **1,135/1,135**. The full serial solution gate has one pre-existing unrelated failure: `MeshObj_HexBolt_ExportsStructuredPolygonsDirectlyFromSurfaceMeshIr` expects 905 OBJ polygons and sees 908. The other test projects, including Server, pass. The full solution builds with zero errors and seven Web.Runtime warnings. `git diff --check` passes.
+
+## Reproduction
+
+```powershell
+$env:AETHERIS_STEP_NURBS_WITNESS = '<local McMaster STEP path>'
+dotnet test Aetheris.Kernel.Core.Tests -c Release --filter FullyQualifiedName~Step242LocalRationalWitnessTests
+dotnet run --project Aetheris.CLI -c Release -- analyze $env:AETHERIS_STEP_NURBS_WITNESS --json
+dotnet run --project Aetheris.CLI -c Release -- wireframe $env:AETHERIS_STEP_NURBS_WITNESS --out artifacts/local/step-recovered-pcurve-x1/mcmaster-bolt.svg --view iso --density 8 --json
+```