Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add configurable 3DM recovery and STEP BRep binding
Yuechen Lic0491e87a716
diff --git a/Aetheris.CLI.Tests/ThreeDmBrepBindLocalTests.cs b/Aetheris.CLI.Tests/ThreeDmBrepBindLocalTests.csnew file mode 100644index 00000000..b1f810a3--- /dev/null+++ b/Aetheris.CLI.Tests/ThreeDmBrepBindLocalTests.cs@@ -0,0 +1,87 @@+using System.Security.Cryptography;+using Aetheris.ThreeDm;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.CLI.Tests;++public sealed class ThreeDmBrepBindLocalTests+{+ [LocalThreeDmFact]+ public void ProductDesignExportsEverySourceBrepAndCombinedReference()+ {+ var root = RepositoryRoot();+ var source = Path.Combine(root, "testdata", "3DM", "cartesian-product-metres.3dm");+ var output = Path.Combine(root, "artifacts", "local", "3dm-bind-x0-tests", "product");+ var report = ThreeDmStepRecovery.Run(source, output, emitCombinedStep: true);++ Assert.Equal(27, report.Bodies.Count);+ Assert.Equal(27, report.QualifiedBodyCount);+ Assert.Equal(0, report.PartialBodyCount);+ Assert.Equal(185, report.BoundFaceCount);+ Assert.Equal(742, report.BoundTrimCount);+ Assert.True(report.CombinedStepReimported, string.Join("; ", report.CombinedDiagnostics));+ Assert.Equal(28, report.CombinedSolidCount);+ Assert.Equal(24, report.Bodies.Count(body => body.Status == ThreeDmStepImportStatus.Qualified));+ Assert.Equal(new[] { 5, 21, 26 }, report.Bodies+ .Where(body => body.Status == ThreeDmStepImportStatus.InspectableRecovered)+ .Select(body => body.ObjectIndex).ToArray());+ Assert.InRange(report.CombinedBoundingBoxDriftMillimetres!.Value, 0, 0.1);+ Assert.True(File.Exists(report.CombinedStepPath));+ Assert.All(report.Bodies.Where(body => body.StepReimported), body =>+ {+ Assert.True(body.BoundIsEnclosed);+ Assert.True(body.BoundOrientationConsistent);+ Assert.Equal(body.SourceFaces, body.BoundFaces);+ Assert.Equal(body.SourceTrims, body.BoundTrims);+ Assert.InRange(body.WorstPcurveResidualMillimetres, 0, 0.1);+ Assert.InRange(body.MaximumBoundingBoxDriftMillimetres!.Value, 0, 0.1);+ Assert.True(File.Exists(body.StepPath));+ });+ Assert.Contains(report.Bodies, body => body.ObjectIndex == 3 && body.StepReimported+ && body.SourcePcurves > 0 && body.RecoveredPcurves > 0);+ Assert.Contains(report.Bodies, body => body.ObjectIndex == 5 && body.StepReimported+ && body.Adjustments.Any(adjustment => adjustment.Kind == "RhinoSingularTrimCollapsedToVertex"+ && adjustment.BeforeMillimetres > 0.4 && adjustment.BeforeMillimetres < adjustment.AllowedMillimetres));+ Assert.Contains(report.Bodies, body => body.ObjectIndex == 21 && body.StepReimported+ && body.Adjustments.Any(adjustment => adjustment.Kind == "SourceVertexToCoincidentEdgeEndpoints"+ && adjustment.BeforeMillimetres is > 0.059 and < 0.061 && adjustment.AfterMillimetres < 1e-6));+ Assert.Contains(report.Bodies, body => body.ObjectIndex == 22 && body.StepReimported+ && body.ComponentCount == 2 && body.StepPaths.Count == 2);+ Assert.Contains(report.Bodies, body => body.ObjectIndex == 26 && body.StepReimported+ && body.Adjustments.Count(adjustment => adjustment.Kind == "RhinoSingularTrimCollapsedToVertex") == 2);++ var nearCoincident = report.Bodies.Single(body => body.ObjectIndex == 21);+ var step = File.ReadAllText(nearCoincident.StepPath!);+ Assert.False(Step242Importer.ImportBody(step).IsSuccess);+ Assert.True(Step242Importer.ImportBody(step,+ new ImportPolicy(AllowBoundedNearCoincidentInnerLoop: true)).IsSuccess);+ }++ [LocalThreeDmFact]+ public void RecoveredProductBodyStepIsDeterministicAndFurnitureBodyReimports()+ {+ var root = RepositoryRoot();+ var directory = Path.Combine(root, "artifacts", "local", "3dm-bind-x0-tests", "focused");+ var product = Path.Combine(root, "testdata", "3DM", "cartesian-product-metres.3dm");+ var first = ThreeDmStepRecovery.Run(product, directory, selectedObjectIndex: 3).Bodies.Single();+ Assert.True(first.StepReimported, string.Join("; ", first.Diagnostics));+ var firstHash = SHA256.HashData(File.ReadAllBytes(first.StepPath!));+ var second = ThreeDmStepRecovery.Run(product, directory, selectedObjectIndex: 3).Bodies.Single();+ Assert.True(second.StepReimported, string.Join("; ", second.Diagnostics));+ Assert.Equal(firstHash, SHA256.HashData(File.ReadAllBytes(second.StepPath!)));++ var furniture = Path.Combine(root, "testdata", "3DM", "cartesian-furniture-metres.3dm");+ var furnitureBody = ThreeDmStepRecovery.Run(furniture, directory, selectedObjectIndex: 1).Bodies.Single();+ Assert.True(furnitureBody.StepReimported, string.Join("; ", furnitureBody.Diagnostics));+ Assert.Equal((6, 24), (furnitureBody.BoundFaces, furnitureBody.BoundTrims));+ }++ private static string RepositoryRoot()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx")))+ directory = directory.Parent;+ return directory?.FullName ?? throw new DirectoryNotFoundException("Aetheris repository root not found.");+ }+}diff --git a/Aetheris.CLI.Tests/ThreeDmRecoveryLocalTests.cs b/Aetheris.CLI.Tests/ThreeDmRecoveryLocalTests.csindex 32a0bc87..892545f4 100644--- a/Aetheris.CLI.Tests/ThreeDmRecoveryLocalTests.cs+++ b/Aetheris.CLI.Tests/ThreeDmRecoveryLocalTests.cs@@ -5,6 +5,64 @@ namespace Aetheris.CLI.Tests;public sealed class ThreeDmRecoveryLocalTests{+ [LocalThreeDmFact]+ public void ProductRationalSupportsRecoverAtConfigurableEngineeringTolerance()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx")))+ directory = directory.Parent;+ Assert.NotNull(directory);+ var path = Path.Combine(directory.FullName, "testdata", "3DM", "cartesian-product-metres.3dm");++ var ordinary = ThreeDmRecovery.Analyze(path, 0.1);+ var tighter = ThreeDmRecovery.Analyze(path, 0.05);+ Assert.Equal((53, 83), (ordinary.RecoveredCurveCount, ordinary.RecoveredSurfaceCount));+ Assert.Equal((53, 83), (tighter.RecoveredCurveCount, tighter.RecoveredSurfaceCount));+ Assert.Equal(0.1, ordinary.RecoveryToleranceMillimetres);+ Assert.Equal(0.05, tighter.RecoveryToleranceMillimetres);++ var ordinaryCandidates = ordinary.Bodies.SelectMany(body =>+ body.Edges.Select(edge => edge.GenericRecovery).Concat(body.Faces.Select(face => face.GenericRecovery)))+ .Where(candidate => candidate is not null).ToArray();+ var tighterCandidates = tighter.Bodies.SelectMany(body =>+ body.Edges.Select(edge => edge.GenericRecovery).Concat(body.Faces.Select(face => face.GenericRecovery)))+ .Where(candidate => candidate is not null).ToArray();+ Assert.All(ordinaryCandidates, candidate =>+ {+ Assert.Equal(RecoveryQualification.WithinRecoveryTolerance, candidate!.Qualification);+ Assert.InRange(candidate.Residual.MaxMillimetres, 0, 0.1);+ Assert.True(candidate.Residual.SampleCount >= 65);+ });+ Assert.All(tighterCandidates, candidate =>+ {+ Assert.Equal(RecoveryQualification.WithinRecoveryTolerance, candidate!.Qualification);+ Assert.InRange(candidate.Residual.MaxMillimetres, 0, 0.05);+ });+ Assert.True(tighterCandidates.Sum(candidate => candidate!.Parameters["controlPointsU"] *+ double.Max(1, candidate.Parameters["controlPointsV"])) >=+ ordinaryCandidates.Sum(candidate => candidate!.Parameters["controlPointsU"] *+ double.Max(1, candidate.Parameters["controlPointsV"])));+ Assert.StartsWith("No canonical BRep", ordinary.ProductionStatus);+ }++ [LocalThreeDmFact]+ public void TightUnsupportedSupportsDoNotEraseOtherSourceBodies()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx")))+ directory = directory.Parent;+ Assert.NotNull(directory);+ var report = ThreeDmRecovery.Analyze(Path.Combine(directory.FullName,+ "testdata", "3DM", "cartesian-product-metres.3dm"), 0.00001);++ Assert.Equal(27, report.Bodies.Count);+ Assert.True(report.RecoveredSurfaceCount > 0);+ Assert.True(report.UnrecoveredSurfaceCount > 0);+ Assert.Contains(report.Bodies, body => body.Faces.Any(face =>+ face.GenericRecovery?.Qualification == RecoveryQualification.Unresolved &&+ face.GenericRecovery.Limitation.Length > 0));+ }+[LocalThreeDmFact]public void ProductRecoveryStudyIsDeterministicAndLeavesTopologyProvisional(){diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 2db180ba..4f4be9b4 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -4824,7 +4824,7 @@ Model CanonicalPanel {stdout.WriteLine(" view Build/open a model in Cadmata.");stdout.WriteLine(" inspect Inspect Firmament semantics or STEP topology.");stdout.WriteLine(" inspect-3dm Inventory local Rhino 3DM geometry and import blockers.");- stdout.WriteLine(" recover-3dm Measure analytic recovery candidates from Rhino 3DM geometry.");+ stdout.WriteLine(" recover-3dm Measure Rhino recovery candidates or bind qualified BReps to STEP.");stdout.WriteLine(" analyze Analyze STEP topology and analytic surfaces.");stdout.WriteLine(" fea Compile and solve a Firmament linear-elastic analysis and export Abaqus verification input.");stdout.WriteLine(" drawing Compile production drawings or inspect/highlight PDFs with source-linked Drawing Notes.");diff --git a/Aetheris.CLI/ThreeDmCli.cs b/Aetheris.CLI/ThreeDmCli.csindex 80c7748e..e1c2f5f2 100644--- a/Aetheris.CLI/ThreeDmCli.cs+++ b/Aetheris.CLI/ThreeDmCli.cs@@ -9,19 +9,39 @@ internal static class ThreeDmCli{if (args.Length == 1 && args[0] is "--help" or "-h"){- stdout.WriteLine("Usage: aetheris recover-3dm <file.3dm> [--body <index> [--edge <index>|--face <index>]] [--json]");+ stdout.WriteLine("Usage: aetheris recover-3dm <file.3dm> [--recovery-tolerance-mm <positive-mm>] [--body <index> [--edge <index>|--face <index>]] [--bind-step --out-dir <local-directory> [--combined-step]] [--json]");return 0;}if (args.Length < 1){- stderr.WriteLine("Usage: aetheris recover-3dm <file.3dm> [--body <index> [--edge <index>|--face <index>]] [--json]");+ stderr.WriteLine("Usage: aetheris recover-3dm <file.3dm> [--recovery-tolerance-mm <positive-mm>] [--body <index> [--edge <index>|--face <index>]] [--bind-step --out-dir <local-directory> [--combined-step]] [--json]");return 1;}var json = false;+ var bindStep = false;+ var combinedStep = false;+ string? outputDirectory = null;+ var recoveryTolerance = 0.1d;int? bodyIndex = null, edgeIndex = null, faceIndex = null;for (var i = 1; i < args.Length; i++){if (args[i] == "--json") { json = true; continue; }+ if (args[i] == "--bind-step") { bindStep = true; continue; }+ if (args[i] == "--combined-step") { combinedStep = true; continue; }+ if (args[i] == "--out-dir" && i + 1 < args.Length)+ {+ outputDirectory = args[++i];+ continue;+ }+ if (args[i] == "--recovery-tolerance-mm" && i + 1 < args.Length &&+ double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float,+ System.Globalization.CultureInfo.InvariantCulture, out var parsedTolerance) &&+ double.IsFinite(parsedTolerance) && parsedTolerance > 0d)+ {+ recoveryTolerance = parsedTolerance;+ i++;+ continue;+ }if (args[i] is "--body" or "--edge" or "--face" && i + 1 < args.Length &&int.TryParse(args[i + 1], out var index) && index >= 0){@@ -42,7 +62,31 @@ internal static class ThreeDmClistderr.WriteLine("--edge or --face requires --body; choose only one focused entity.");return 1;}- var report = ThreeDmRecovery.Analyze(args[0]);+ if (bindStep)+ {+ if (edgeIndex.HasValue || faceIndex.HasValue || string.IsNullOrWhiteSpace(outputDirectory) || combinedStep && bodyIndex.HasValue)+ {+ stderr.WriteLine("--bind-step requires --out-dir; --combined-step requires the whole file and cannot be combined with --body, --edge, or --face.");+ return 1;+ }+ var bound = ThreeDmStepRecovery.Run(args[0], outputDirectory, recoveryTolerance, bodyIndex, combinedStep);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(bound, jsonOptions));+ else+ {+ stdout.WriteLine($"Bound {bound.QualifiedBodyCount}/{bound.Bodies.Count} source BReps to STEP and reimported them; {bound.PartialBodyCount} partial; faces {bound.BoundFaceCount}/{bound.Bodies.Sum(body => body.SourceFaces)}, trims {bound.BoundTrimCount}/{bound.Bodies.Sum(body => body.SourceTrims)}; {bound.TotalMilliseconds:F0} ms total.");+ foreach (var body in bound.Bodies)+ stdout.WriteLine($"Object {body.ObjectIndex}: status={body.Status}, components={body.ComponentCount}, faces {body.BoundFaces}/{body.SourceFaces}, trims {body.BoundTrims}/{body.SourceTrims}, pcurves {body.SourcePcurves} source/{body.RecoveredPcurves} recovered, enclosed={body.BoundIsEnclosed}, STEP={body.StepExported}, reimport={body.StepReimported}, path={body.StepPath ?? "none"}, diagnostic={body.Diagnostics.FirstOrDefault() ?? "none"}");+ if (combinedStep)+ stdout.WriteLine($"Combined STEP: reimport={bound.CombinedStepReimported}, solids={bound.CombinedSolidCount}, drift={bound.CombinedBoundingBoxDriftMillimetres:G6} mm, path={bound.CombinedStepPath ?? "none"}, diagnostic={bound.CombinedDiagnostics.FirstOrDefault() ?? "none"}");+ }+ return combinedStep ? bound.CombinedStepReimported ? 0 : 2 : bound.QualifiedBodyCount > 0 ? 0 : 2;+ }+ if (outputDirectory is not null || combinedStep)+ {+ stderr.WriteLine("--out-dir and --combined-step require --bind-step.");+ return 1;+ }+ var report = ThreeDmRecovery.Analyze(args[0], recoveryTolerance);if (bodyIndex is int selectedBody){var body = report.Bodies.FirstOrDefault(b => b.ObjectIndex == selectedBody);@@ -64,6 +108,7 @@ internal static class ThreeDmClistdout.WriteLine($"Source: {report.Bodies.Count} BReps, {report.SourceRationalEdgeCount} rational edges, {report.SourceRationalSurfaceCount} rational surfaces");stdout.WriteLine($"Rational edges: {report.NativeAnalyticRationalEdgeCount} native analytic supports; {report.StudiedRationalEdgeCount} previously unclassified; {report.QualifiedRecoveredRationalEdgeCount} of those have support candidates within source tolerance; {report.UnresolvedRationalEdgeCount} unresolved supports");stdout.WriteLine($"Rational surface study: {report.QualifiedAnalyticRationalSurfaceCount} analytic support candidates within source tolerance; {report.UnresolvedRationalSurfaceCount} unresolved");+ stdout.WriteLine($"Generic spline supports at {report.RecoveryToleranceMillimetres:G6} mm: {report.RecoveredCurveCount} curves, {report.RecoveredSurfaceCount} surfaces; {report.UnrecoveredCurveCount} curves and {report.UnrecoveredSurfaceCount} surfaces exceed/failed budget; trim/topology qualification pending");stdout.WriteLine(report.ProductionStatus);}return 0;diff --git a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.csindex 1c3b033d..c080b100 100644--- a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs+++ b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs@@ -59,9 +59,14 @@ public static class BrepExportPreflight{private static readonly ToleranceContext Tolerances = ToleranceContext.Default;- public static BrepExportPreflightResult Validate(BrepBody body)+ public static BrepExportPreflightResult Validate(BrepBody body, double? importedRecoveryToleranceMillimetres = null,+ IReadOnlyDictionary<VertexId, double>? importedSourceVertexTolerancesMillimetres = null){ArgumentNullException.ThrowIfNull(body);+ if (importedRecoveryToleranceMillimetres is double importedTolerance &&+ (!double.IsFinite(importedTolerance) || importedTolerance <= 0d || importedTolerance > 1d))+ throw new ArgumentOutOfRangeException(nameof(importedRecoveryToleranceMillimetres));+ var geometricTolerance = importedRecoveryToleranceMillimetres ?? Tolerances.Linear;var diagnostics = new List<BrepExportPreflightDiagnostic>();var model = body.Topology;int? bodyId = model.Bodies.Count() == 1 ? model.Bodies.Single().Id.Value : null;@@ -191,7 +196,11 @@ public static class BrepExportPreflightAddError("brep-preflight-missing-curve", "edge", "Edge is missing a bound curve or trim interval.", edgeId: edge.Id.Value);return;}- if (edge.StartVertexId == edge.EndVertexId && curve.Kind is not CurveGeometryKind.Circle3 and not CurveGeometryKind.Ellipse3)+ var isClosedSpline = curve.BSpline3 is { } closedSpline && closedSpline.ClosedCurve &&+ (closedSpline.Evaluate(binding.TrimInterval.Value.Start) -+ closedSpline.Evaluate(binding.TrimInterval.Value.End)).Length <= Tolerances.Linear;+ if (edge.StartVertexId == edge.EndVertexId &&+ curve.Kind is not CurveGeometryKind.Circle3 and not CurveGeometryKind.Ellipse3 && !isClosedSpline)AddError("brep-preflight-edge-degenerate", "edge", "Non-periodic edge uses the same topology vertex at both endpoints.", edgeId: edge.Id.Value);var a = Evaluate(curve, binding.TrimInterval.Value.Start);var b = Evaluate(curve, binding.TrimInterval.Value.End);@@ -205,13 +214,26 @@ public static class BrepExportPreflightvar expectedEnd = binding.OrientedEdgeSense ? endPoint : startPoint;var startDeviation = Distance(a.Value, expectedStart);var endDeviation = Distance(b.Value, expectedEnd);- if (startDeviation > Tolerances.Linear || endDeviation > Tolerances.Linear)- AddError("brep-preflight-edge-curve-endpoint-mismatch", "edge", "Edge curve trim endpoints do not match the topology edge endpoints.", edgeId: edge.Id.Value, deviation: double.Max(startDeviation, endDeviation));+ var startAllowed = EndpointTolerance(edge.StartVertexId);+ var endAllowed = EndpointTolerance(edge.EndVertexId);+ if (startDeviation > startAllowed || endDeviation > endAllowed)+ AddError("brep-preflight-edge-curve-endpoint-mismatch", "edge", "Edge curve trim endpoints do not match the topology edge endpoints.", edgeId: edge.Id.Value,+ deviation: double.Max(startDeviation, endDeviation), allowedTolerance: double.Max(startAllowed, endAllowed));}if (a is not null && b is not null && curve.Kind is CurveGeometryKind.Line3 && Distance(a.Value, b.Value) <= Tolerances.Linear)AddError("brep-preflight-edge-degenerate", "edge", "Line edge has zero geometric length.", edgeId: edge.Id.Value, deviation: Distance(a.Value, b.Value));}+ double EndpointTolerance(VertexId vertexId)+ {+ if (importedSourceVertexTolerancesMillimetres is null ||+ !importedSourceVertexTolerancesMillimetres.TryGetValue(vertexId, out var sourceTolerance))+ return geometricTolerance;+ if (!double.IsFinite(sourceTolerance) || sourceTolerance < 0d || sourceTolerance > 1d)+ throw new ArgumentOutOfRangeException(nameof(importedSourceVertexTolerancesMillimetres));+ return double.Max(geometricTolerance, sourceTolerance);+ }+void ValidateTrimOnSurface(FaceId faceId, LoopId loopId, EdgeId edgeId, Edge edge, SurfaceGeometry surface){if (!body.Bindings.TryGetEdgeBinding(edgeId, out var binding) || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) || curve is null || binding.TrimInterval is null) return;@@ -226,13 +248,13 @@ public static class BrepExportPreflightAddWarning("brep-preflight-check-unsupported", "trim-surface", $"Containment check is not implemented for {surface.Kind}.", faceId.Value, loopId.Value, edgeId: edgeId.Value, surface: surface.Kind.ToString());return;}- if (deviation > Tolerances.Linear)- AddError("brep-preflight-trim-off-surface", "trim-surface", $"Trim point does not lie on {surface.Kind}; deviation {deviation:G6} exceeds tolerance {Tolerances.Linear:G6}.", faceId.Value, loopId.Value, edgeId: edgeId.Value, surface: surface.Kind.ToString(), deviation: deviation);+ if (deviation > geometricTolerance)+ AddError("brep-preflight-trim-off-surface", "trim-surface", $"Trim point does not lie on {surface.Kind}; deviation {deviation:G6} exceeds tolerance {geometricTolerance:G6}.", faceId.Value, loopId.Value, edgeId: edgeId.Value, surface: surface.Kind.ToString(), deviation: deviation, allowedTolerance: geometricTolerance);}}- void AddError(string code, string stage, string message, int? faceId = null, int? loopId = null, int? coedgeIndex = null, int? edgeId = null, string? surface = null, double? deviation = null) =>- diagnostics.Add(new(code, BrepExportPreflightSeverity.Error, stage, message, bodyId, faceId, loopId, coedgeIndex, edgeId, surface, deviation, deviation is null ? null : Tolerances.Linear, ClassificationFor(code, stage)));+ void AddError(string code, string stage, string message, int? faceId = null, int? loopId = null, int? coedgeIndex = null, int? edgeId = null, string? surface = null, double? deviation = null, double? allowedTolerance = null) =>+ diagnostics.Add(new(code, BrepExportPreflightSeverity.Error, stage, message, bodyId, faceId, loopId, coedgeIndex, edgeId, surface, deviation, deviation is null ? null : allowedTolerance ?? Tolerances.Linear, ClassificationFor(code, stage)));void AddWarning(string code, string stage, string message, int? faceId = null, int? loopId = null, int? coedgeIndex = null, int? edgeId = null, string? surface = null, double? deviation = null) =>diagnostics.Add(new(code, BrepExportPreflightSeverity.Warning, stage, message, bodyId, faceId, loopId, coedgeIndex, edgeId, surface, deviation, deviation is null ? null : Tolerances.Linear, ClassificationFor(code, stage)));}diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.csindex 3a3b5273..a1f0ecf3 100644--- a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs@@ -181,10 +181,15 @@ public static class BrepPcurveRecoveryif (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 uLow = double.Max(best.U - hu, spline.DomainStartU);+ var uHigh = double.Min(best.U + hu, spline.DomainEndU);+ var vLow = double.Max(best.V - hv, spline.DomainStartV);+ var vHigh = double.Min(best.V + hv, spline.DomainEndV);+ // These are parameter spans, not model-space distances. Avoid the+ // Vector3D division operator's world-space near-zero threshold.+ if (uHigh - uLow <= 1e-15d || vHigh - vLow <= 1e-15d) break;+ var du = (spline.Evaluate(uHigh, best.V) - spline.Evaluate(uLow, best.V)) * (1d / (uHigh - uLow));+ var dv = (spline.Evaluate(best.U, vHigh) - spline.Evaluate(best.U, vLow)) * (1d / (vHigh - vLow));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);diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.csindex c70da9ca..323aef55 100644--- a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs@@ -1,5 +1,6 @@using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;namespace Aetheris.Kernel.Core.Brep;@@ -17,10 +18,16 @@ public sealed record BrepPcurveEvidence(public double RootMeanSquareReconstructionDeviation { get; init; }}+/// <summary>Source-local topology evidence for collapsed trim vertices; omitted by authored callers.</summary>+public sealed record BrepPcurveTopologyEvidence(+ IReadOnlyDictionary<VertexId, double> VertexTolerancesMillimetres,+ IReadOnlySet<(CoedgeId Current, CoedgeId Next)> CollapsedSingularTransitions);+/// <summary>Independently samples face-local pcurves against their shared 3D edge geometry.</summary>public static class BrepPcurveValidator{- public static BrepPcurveEvidence Validate(BrepBody body, double tolerance = 1e-6, bool requireEveryCoedge = false, int samples = 67)+ public static BrepPcurveEvidence Validate(BrepBody body, double tolerance = 1e-6, bool requireEveryCoedge = false, int samples = 67,+ BrepPcurveTopologyEvidence? sourceTopology = null){ArgumentNullException.ThrowIfNull(body);if (!double.IsFinite(tolerance) || tolerance <= 0d) throw new ArgumentOutOfRangeException(nameof(tolerance));@@ -91,12 +98,14 @@ public static class BrepPcurveValidatorif (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 startVertexId = coedge.IsReversed ? body.Topology.GetEdge(coedge.EdgeId).EndVertexId : body.Topology.GetEdge(coedge.EdgeId).StartVertexId;+ if (body.TryGetVertexPoint(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 > bindingTolerance)+ var vertexTolerance = sourceTopology?.VertexTolerancesMillimetres.GetValueOrDefault(startVertexId) ?? 0d;+ if (reconstructed is null || (reconstructed.Value - start).Length > double.Max(bindingTolerance, vertexTolerance)){orientationValid = false;diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:orientation");@@ -110,7 +119,8 @@ public static class BrepPcurveValidatorvar 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 > bindingTolerance)+ var vertexTolerance = sourceTopology?.VertexTolerancesMillimetres.GetValueOrDefault(endVertex) ?? 0d;+ if (reconstructed is null || (reconstructed.Value - endPoint).Length > double.Max(bindingTolerance, vertexTolerance)){orientationValid = false;diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:end-orientation");@@ -130,7 +140,23 @@ public static class BrepPcurveValidatormaximumUvClosure = double.Max(maximumUvClosure, closure);var closureTolerance = double.Max(bindingTolerance,nextBinding.Qualification?.QualificationToleranceMillimetres ?? tolerance);- if (closure > closureTolerance)+ if (sourceTopology?.CollapsedSingularTransitions.Contains((coedge.Id, next.Id)) == true)+ {+ // The omitted Rhino singular trim crosses UV while lifting to one vertex.+ // Check its two lifted endpoints in model space against that source vertex.+ var currentLift = Evaluate(surface, currentUv);+ var nextLift = Evaluate(surface, nextUv);+ var vertex = coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId;+ var sourceLimit = sourceTopology.VertexTolerancesMillimetres.GetValueOrDefault(vertex);+ if (currentLift is null || nextLift is null || !body.TryGetVertexPoint(vertex, out var vertexPoint)+ || (currentLift.Value - vertexPoint).Length > double.Max(closureTolerance, sourceLimit)+ || (nextLift.Value - vertexPoint).Length > double.Max(closureTolerance, sourceLimit))+ {+ loopClosureValid = false;+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:collapsed-singular-lift");+ }+ }+ else if (closure > closureTolerance){loopClosureValid = false;diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:uv-loop-closure={closure:R}:tolerance={closureTolerance:R}");diff --git a/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.cs b/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.csindex 75a39362..fd7460ae 100644--- a/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.cs+++ b/Aetheris.Kernel.Core/Geometry/SplineRecoveryProvenance.cs@@ -8,4 +8,5 @@ public sealed record SplineRecoveryProvenance(double MeasuredMaxDeviationMillimetres,bool AnalyticRecognitionAttempted,string AnalyticRecognitionResult,- bool RationalSourceRetained = false);+ bool RationalSourceRetained = false,+ string? SourceEntityIdentity = null);diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.csindex cef1e92b..d91b78df 100644--- a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceRationalReduction.cs@@ -18,7 +18,7 @@ namespace Aetheris.Kernel.Core.Geometry.Surfaces;/// pcurves stay meaningful rather than merely landing somewhere on the new surface./// </para>/// </summary>-internal static class BSplineSurfaceRationalReduction+public static class BSplineSurfaceRationalReduction{/// <summary>Fraction of the source file's declared accuracy the reduction is required to stay inside.</summary>private const double DeclaredAccuracyFraction = 0.1d;@@ -33,6 +33,8 @@ internal static class BSplineSurfaceRationalReduction/// cap keeps a pathological surface from growing an enormous control net instead of failing honestly./// </summary>private const int MaximumSpanSubdivision = 32;+ private const int MaximumControlPointsPerAxis = 256;+ private const int MaximumControlPoints = 8192;private const int DeviationSamplesPerSpan = 3;private const int MinimumDeviationSamples = 24;@@ -74,11 +76,20 @@ internal static class BSplineSurfaceRationalReduction}var best = double.PositiveInfinity;+ var controlLimitReached = false;BSplineSurfaceWithKnots? Attempt(int subdivisionU, int subdivisionV){var refinedU = Subdivide(surface.KnotValuesU, surface.KnotMultiplicitiesU, subdivisionU);var refinedV = Subdivide(surface.KnotValuesV, surface.KnotMultiplicitiesV, subdivisionV);+ var countU = refinedU.Multiplicities.Sum() - surface.DegreeU - 1;+ var countV = refinedV.Multiplicities.Sum() - surface.DegreeV - 1;+ if (countU > MaximumControlPointsPerAxis || countV > MaximumControlPointsPerAxis ||+ (long)countU * countV > MaximumControlPoints)+ {+ controlLimitReached = true;+ return null;+ }if (!TryInterpolate(surface, refinedU, refinedV, out var attempt) || attempt is null){return null;@@ -105,7 +116,8 @@ internal static class BSplineSurfaceRationalReductionif (uniform == 0){deviation = best;- reason = $"no refinement up to {MaximumSpanSubdivision} spans per knot interval followed the rational surface to {tolerance:G4} mm (closest {best:G4} mm)";+ reason = $"no refinement up to {MaximumSpanSubdivision} spans per knot interval followed the rational surface to {tolerance:G4} mm (closest {best:G4} mm)" ++ (controlLimitReached ? $"; control-net cap {MaximumControlPointsPerAxis} per axis/{MaximumControlPoints} total reached" : string.Empty);return false;}@@ -182,7 +194,9 @@ internal static class BSplineSurfaceRationalReductionvar knotsV = Expand(refinedV.Values, refinedV.Multiplicities);var countU = knotsU.Length - surface.DegreeU - 1;var countV = knotsV.Length - surface.DegreeV - 1;- if (countU < surface.DegreeU + 1 || countV < surface.DegreeV + 1)+ if (countU < surface.DegreeU + 1 || countV < surface.DegreeV + 1 ||+ countU > MaximumControlPointsPerAxis || countV > MaximumControlPointsPerAxis ||+ (long)countU * countV > MaximumControlPoints){return false;}diff --git a/Aetheris.Kernel.Core/Import/ImportContracts.cs b/Aetheris.Kernel.Core/Import/ImportContracts.csindex 94ac7992..a6f4c035 100644--- a/Aetheris.Kernel.Core/Import/ImportContracts.cs+++ b/Aetheris.Kernel.Core/Import/ImportContracts.cs@@ -27,7 +27,8 @@ public sealed record ImportRequest(string SourceText, ImportPolicy? Policy = nulpublic sealed record ImportPolicy(ImportLaneKind PreferredLane = ImportLaneKind.Auto,double RecoveryToleranceMillimetres = 0.1d,- double PcurveQualificationToleranceMillimetres = 1e-3d);+ double PcurveQualificationToleranceMillimetres = 1e-3d,+ bool AllowBoundedNearCoincidentInnerLoop = false);public sealed record ImportResult(KernelResult<BrepBody> BodyResult,diff --git a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.csindex 78ec6496..e689b30e 100644--- a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs+++ b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs@@ -3,6 +3,7 @@ using System.Security.Cryptography;using System.Text;using System.Text.RegularExpressions;using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Import;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Results;@@ -189,11 +190,20 @@ public static class Step242AssemblyExporterpublic static class Step242AssemblyImporter{- public static KernelResult<Step242ProductStructure> Import(string stepText)+ public static KernelResult<Step242ProductStructure> Import(string stepText, ImportPolicy? policy = null){var parsed = Step242SubsetParser.Parse(stepText);if (!parsed.IsSuccess) return KernelResult<Step242ProductStructure>.Failure(parsed.Diagnostics);var document = parsed.Value;+ if (policy is not null)+ {+ if (!double.IsFinite(policy.RecoveryToleranceMillimetres) || policy.RecoveryToleranceMillimetres <= 0d)+ throw new ArgumentOutOfRangeException(nameof(policy));+ document.RecoveryToleranceMillimetres = policy.RecoveryToleranceMillimetres;+ document.PcurveQualificationToleranceMillimetres = double.Min(policy.PcurveQualificationToleranceMillimetres,+ policy.RecoveryToleranceMillimetres);+ document.AllowBoundedNearCoincidentInnerLoop = policy.AllowBoundedNearCoincidentInnerLoop;+ }var products = document.Entities.Where(entity => entity.Name == "PRODUCT").ToDictionary(entity => entity.Id);var formations = document.Entities.Where(entity => entity.Name == "PRODUCT_DEFINITION_FORMATION").ToDictionary(entity => entity.Id);var definitionsByEntity = document.Entities.Where(entity => entity.Name == "PRODUCT_DEFINITION").ToDictionary(entity => entity.Id);diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.csindex fa7714e4..a2600950 100644--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs@@ -1,5 +1,7 @@namespace Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;+/// <summary>Controls whether export preflight findings are only reported or block serialization.</summary>public enum BrepExportPreflightMode{@@ -41,9 +43,18 @@ public sealed class Step242ExportOptions/// </summary>public BrepExportPreflightPolicy BrepExportPreflightPolicy { get; init; } = BrepExportPreflightPolicy.LegacyRoute;+ /// <summary>Explicit import-only geometric consistency budget; authored export uses kernel tolerance.</summary>+ public double? ImportedRecoveryToleranceMillimetres { get; init; }++ /// <summary>Source-declared vertex tolerances for an imported topology, capped by its binder.</summary>+ public IReadOnlyDictionary<VertexId, double>? ImportedSourceVertexTolerancesMillimetres { get; init; }+/// <summary>Preserve a full circular edge's declared parameter interval as TRIMMED_CURVE.</summary>public bool EmitFullCircleTrimmedCurves { get; init; }+ /// <summary>Emit qualified coedge pcurves; false leaves STEP trim binding to the importer.</summary>+ public bool EmitQualifiedPcurves { get; init; } = true;+public static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata){static string Coalesce(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value!;diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex 81d1005f..f29308b8 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -41,7 +41,8 @@ public static class Step242Exportervar preflight = options.BrepExportPreflightMode == BrepExportPreflightMode.Disabled? null- : BrepExportPreflight.Validate(body);+ : BrepExportPreflight.Validate(body, options.ImportedRecoveryToleranceMillimetres,+ options.ImportedSourceVertexTolerancesMillimetres);if (preflight is { IsValid: false } && options.BrepExportPreflightMode == BrepExportPreflightMode.Enforce){return KernelResult<string>.Failure(ToKernelDiagnostics(preflight, errorsAsWarnings: false));@@ -86,7 +87,7 @@ public static class Step242Exportervar surfaceIds = new Dictionary<SurfaceGeometryId, string>();var advancedFaceIds = new Dictionary<FaceId, string>();// Keep source pcurves, but do not publish a partial recovered trim set.- var pcurveContextId = body.Bindings.PcurveBindings.Any(binding =>+ var pcurveContextId = options.EmitQualifiedPcurves && 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"))diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 51b4ee8e..d244f48f 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -52,6 +52,7 @@ public static class Step242Importerprivate const double AngleUnwrapEps = 1e-8d;private const double ContainmentEps = 1e-8d;private const string PlanarCrossingInsideRecoveryCandidate = "planar_crossing_inside_recover_as_inner";+ private const string PlanarNearCoincidentRecoveryCandidate = "planar_near_coincident_declared_inner";private const string PlanarCrossingInsideRejectCandidate = "planar_crossing_inside_reject";private static readonly AsyncLocal<ICollection<LoopRoleCircularSamplingDiagnostic>?> CircularSamplingDiagnosticsSink = new();private static readonly AsyncLocal<ICollection<LoopRoleCoedgeGapDiagnostic>?> CoedgeGapDiagnosticsSink = new();@@ -517,7 +518,8 @@ public static class Step242ImporterloopData.Add(new LoopBuildData(loopId, loopCoedges, loopSamples, hasDisconnectedCoedgeGap, isDeclaredOuter, boundEntity.Id, loopPcurveCandidates));}- var classifyResult = ClassifyAndNormalizeFaceLoops(faceEntity.Id, loopData, bindSurfaceResult.Value.SurfaceGeometry);+ var classifyResult = ClassifyAndNormalizeFaceLoops(faceEntity.Id, loopData, bindSurfaceResult.Value.SurfaceGeometry,+ document.AllowBoundedNearCoincidentInnerLoop ? document.RecoveryToleranceMillimetres : 0d);if (!classifyResult.IsSuccess){return KernelResult<BrepBody>.Failure(classifyResult.Diagnostics);@@ -1944,7 +1946,8 @@ public static class Step242Importerprivate static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizeFaceLoops(int faceEntityId,IReadOnlyList<LoopBuildData> loops,- SurfaceGeometry surface)+ SurfaceGeometry surface,+ double nearCoincidentTolerance){if (loops.Count <= 1){@@ -1977,7 +1980,7 @@ public static class Step242Importer// import must not silently reorder or reverse STEP evidence.var validation = surface.Kind switch{- SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value),+ SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value, nearCoincidentTolerance),SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),@@ -2003,7 +2006,7 @@ public static class Step242Importerreturn surface.Kind switch{- SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value),+ SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value, nearCoincidentTolerance),SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),@@ -2018,7 +2021,8 @@ public static class Step242Importerprivate static KernelResult<IReadOnlyList<LoopBuildData>> ClassifyAndNormalizePlanarLoops(IReadOnlyList<LoopBuildData> loops,- PlaneSurface plane)+ PlaneSurface plane,+ double nearCoincidentTolerance){var infos = new List<PlanarLoopInfo>(loops.Count);foreach (var loop in loops)@@ -2098,8 +2102,8 @@ public static class Step242Importer}if (intersectsOuter- && containment.OutsideCount == 0- && TryRecoverPlanarCrossingInnerWithJudgmentEngine(candidate.Info, outer.Info, containment, intersectionCount, containmentTolerance, loops.Count, declaredOuterCount))+ && TryRecoverPlanarCrossingInnerWithJudgmentEngine(candidate.Info, outer.Info, containment, intersectionCount,+ containmentTolerance, loops.Count, declaredOuterCount, nearCoincidentTolerance)){containedInners.Add(candidate.Info);continue;@@ -2725,7 +2729,7 @@ public static class Step242Importervar message = source == "Importer.LoopRole.DisconnectedCoedges"? $"Planar loop contains disconnected consecutive coedges and cannot be normalized safely. innerLoopId={inner.Loop.LoopId.Value}, outerLoopId={outer.Loop.LoopId.Value}, outsideVertices={containment.OutsideCount}/{containment.VertexCount}, nearestOuterDistance={containment.MinDistanceToOuter:E6}, areaRatio={areaRatio:E6}, intersections={intersectionCount}."- : $"Inner loop could not be normalized: {reason}. innerLoopId={inner.Loop.LoopId.Value}, outerLoopId={outer.Loop.LoopId.Value}, outsideVertices={containment.OutsideCount}/{containment.VertexCount}, nearestOuterDistance={containment.MinDistanceToOuter:E6}, areaRatio={areaRatio:E6}, intersections={intersectionCount}.";+ : $"Inner loop could not be normalized: {reason}. innerLoopId={inner.Loop.LoopId.Value}, outerLoopId={outer.Loop.LoopId.Value}, outsideVertices={containment.OutsideCount}/{containment.VertexCount}, nearestOuterDistance={containment.MinDistanceToOuter:E6}, maximumOutsideDistance={containment.MaxOutsideDistanceToOuter:E6}, areaRatio={areaRatio:E6}, intersections={intersectionCount}.";return new ContainmentFailure(message, source);}@@ -2736,9 +2740,11 @@ public static class Step242Importerint intersectionCount,double containmentTolerance,int loopCount,- int declaredOuterCount)+ int declaredOuterCount,+ double nearCoincidentTolerance){- var context = BuildPlanarCrossingInsideRecoveryContext(inner, outer, containment, intersectionCount, containmentTolerance, loopCount, declaredOuterCount);+ var context = BuildPlanarCrossingInsideRecoveryContext(inner, outer, containment, intersectionCount,+ containmentTolerance, loopCount, declaredOuterCount, nearCoincidentTolerance);var engine = new JudgmentEngine<PlanarCrossingInsideRecoveryContext>();var result = engine.Evaluate(context, BuildPlanarCrossingInsideRecoveryCandidates());var selected = result.Selection?.Candidate.Name ?? PlanarCrossingInsideRejectCandidate;@@ -2758,7 +2764,7 @@ public static class Step242ImporterSelectedCandidate: selected,CandidateRejections: string.Join(" | ", result.Rejections.Select(rejection => $"{rejection.CandidateName}:{rejection.Reason}"))));- return string.Equals(selected, PlanarCrossingInsideRecoveryCandidate, StringComparison.Ordinal);+ return selected is PlanarCrossingInsideRecoveryCandidate or PlanarNearCoincidentRecoveryCandidate;}private static PlanarCrossingInsideRecoveryContext BuildPlanarCrossingInsideRecoveryContext(@@ -2768,7 +2774,8 @@ public static class Step242Importerint intersectionCount,double containmentTolerance,int loopCount,- int declaredOuterCount)+ int declaredOuterCount,+ double nearCoincidentTolerance){var outerArea = double.Abs(outer.SignedArea);var innerArea = double.Abs(inner.SignedArea);@@ -2787,7 +2794,9 @@ public static class Step242ImporterMinDistanceToOuter: containment.MinDistanceToOuter,HasDisconnectedCoedgeGap: hasDisconnectedCoedgeGap,HasSingleDeclaredOuterLoop: declaredOuterCount == 1,- IsNearBoundaryContact: containment.MinDistanceToOuter <= containmentTolerance * 8d);+ IsNearBoundaryContact: containment.MinDistanceToOuter <= containmentTolerance * 8d,+ MaximumOutsideDistance: containment.MaxOutsideDistanceToOuter,+ NearCoincidentTolerance: nearCoincidentTolerance);}private static IReadOnlyList<JudgmentCandidate<PlanarCrossingInsideRecoveryContext>> BuildPlanarCrossingInsideRecoveryCandidates()@@ -2807,12 +2816,25 @@ public static class Step242ImporterRejectionReason: context =>$"requires bounded planar crossing-all-inside recovery facts (loopCount={context.LoopCount}, intersections={context.IntersectionCount}, contained={context.ContainedVertexCount}/{context.VertexCount}, disconnected={context.HasDisconnectedCoedgeGap}, areaRatio={context.AreaRatio:E6}, nearBoundary={context.IsNearBoundaryContact}, singleDeclaredOuter={context.HasSingleDeclaredOuterLoop})",TieBreakerPriority: 0),+ new JudgmentCandidate<PlanarCrossingInsideRecoveryContext>(+ Name: PlanarNearCoincidentRecoveryCandidate,+ IsAdmissible: When.All<PlanarCrossingInsideRecoveryContext>(+ context => context.NearCoincidentTolerance > 0d,+ context => context.LoopCount == 2 && context.IntersectionCount > 0,+ context => context.ContainedVertexCount < context.VertexCount,+ context => context.HasSingleDeclaredOuterLoop && !context.HasDisconnectedCoedgeGap,+ context => context.AreaRatio > 0d && context.AreaRatio < 1d,+ context => context.MaximumOutsideDistance <= context.NearCoincidentTolerance),+ Score: context => 50d - context.MaximumOutsideDistance / context.NearCoincidentTolerance,+ RejectionReason: context =>+ $"requires explicit bounded near-coincident inner-loop policy (outside={context.MaximumOutsideDistance:E6}, limit={context.NearCoincidentTolerance:E6}, areaRatio={context.AreaRatio:E6}, intersections={context.IntersectionCount})",+ TieBreakerPriority: 1),new JudgmentCandidate<PlanarCrossingInsideRecoveryContext>(Name: PlanarCrossingInsideRejectCandidate,IsAdmissible: _ => true,Score: _ => -1d,RejectionReason: _ => "bounded planar crossing-all-inside recovery candidate is not admissible",- TieBreakerPriority: 1)+ TieBreakerPriority: 2)];}@@ -2824,6 +2846,7 @@ public static class Step242Importervar outsideCount = 0;var vertexCount = 0;var minDistanceToOuter = double.MaxValue;+ var maxOutsideDistanceToOuter = 0d;for (var i = 0; i < inner.Count - 1; i++){@@ -2833,6 +2856,7 @@ public static class Step242Importerif (!IsPointInPolygon(point, outer, containmentTolerance)){outsideCount++;+ maxOutsideDistanceToOuter = double.Max(maxOutsideDistanceToOuter, DistancePointToPolygon(point, outer));}}@@ -2841,7 +2865,7 @@ public static class Step242ImporterminDistanceToOuter = 0d;}- return new ContainmentEvaluation(outsideCount, vertexCount, minDistanceToOuter);+ return new ContainmentEvaluation(outsideCount, vertexCount, minDistanceToOuter, maxOutsideDistanceToOuter);}private static bool IsLoopContainedByOuter(@@ -4333,7 +4357,8 @@ public static class Step242Importerprivate sealed record CylindricalLoopInfo(LoopBuildData Loop, IReadOnlyList<UvPoint> ProjectedPoints, double SignedArea, UvPoint Centroid);- private sealed record ContainmentEvaluation(int OutsideCount, int VertexCount, double MinDistanceToOuter);+ private sealed record ContainmentEvaluation(int OutsideCount, int VertexCount, double MinDistanceToOuter,+ double MaxOutsideDistanceToOuter);private sealed record ContainmentFailure(string Message, string Source);@@ -4350,7 +4375,9 @@ public static class Step242Importerdouble MinDistanceToOuter,bool HasDisconnectedCoedgeGap,bool HasSingleDeclaredOuterLoop,- bool IsNearBoundaryContact);+ bool IsNearBoundaryContact,+ double MaximumOutsideDistance,+ double NearCoincidentTolerance);private readonly record struct UvPoint(double X, double Y){diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.csindex e41f31d1..9b9243e0 100644--- a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs@@ -611,6 +611,9 @@ internal sealed class Step242ParsedDocument/// <summary>Base edge-to-lift budget, separately configurable from geometry recovery.</summary>public double PcurveQualificationToleranceMillimetres { get; set; } = 1e-3d;+ /// <summary>Explicit compatibility policy for bounded crossings of a declared planar inner loop.</summary>+ public bool AllowBoundedNearCoincidentInnerLoop { get; set; }+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.csindex 3ed893fd..dbcad89c 100644--- a/Aetheris.Kernel.Core/Step242/StepImportConnectorAndLanes.cs+++ b/Aetheris.Kernel.Core/Step242/StepImportConnectorAndLanes.cs@@ -56,6 +56,7 @@ internal sealed class StepSourceConnector : ISourceConnectorreturn Step242ImportSharedUtilities.NotImplementedFailure<IParsedSourceDocument>("PcurveQualificationToleranceMillimetres must be a positive finite distance.", "Importer.PcurveQualificationTolerance");parseResult.Value.PcurveQualificationToleranceMillimetres = double.Min(pcurveTolerance, tolerance);+ parseResult.Value.AllowBoundedNearCoincidentInnerLoop = request.Policy?.AllowBoundedNearCoincidentInnerLoop == true;return KernelResult<IParsedSourceDocument>.Success(new StepParsedSourceDocument(parseResult.Value));}}diff --git a/Aetheris.ThreeDm/ThreeDmBrepBinder.cs b/Aetheris.ThreeDm/ThreeDmBrepBinder.csnew file mode 100644index 00000000..e1781f46--- /dev/null+++ b/Aetheris.ThreeDm/ThreeDmBrepBinder.cs@@ -0,0 +1,377 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;+using Rhino.Geometry;+using KernelPoint = Aetheris.Kernel.Core.Math.Point3D;++namespace Aetheris.ThreeDm;++public sealed record ThreeDmBoundBody(+ int ObjectIndex, Guid SourceId, BrepBody? Body, int SourceFaces, int SourceTrims,+ int BoundFaces, int BoundTrims, int SourcePcurves, int RecoveredPcurves,+ double WorstPcurveResidualMillimetres, IReadOnlyList<string> Diagnostics)+{+ public bool IsQualified => Body is not null && Diagnostics.Count == 0;+ public IReadOnlyList<ThreeDmTopologyAdjustment> Adjustments { get; init; } = [];+ public IReadOnlyDictionary<VertexId, double> SourceVertexTolerancesMillimetres { get; init; } =+ new Dictionary<VertexId, double>();+}++public sealed record ThreeDmTopologyAdjustment(+ string Kind, int SourceIndex, double BeforeMillimetres, double AfterMillimetres,+ double AllowedMillimetres, string Explanation);++/// <summary>Import-only topology bridge. Source edge and trim indices remain in diagnostics.</summary>+public static class ThreeDmBrepBinder+{+ public static ThreeDmBoundBody Bind(Brep source, int objectIndex, Guid sourceId,+ double millimetresPerUnit, double recoveryToleranceMillimetres)+ {+ var diagnostics = new List<string>();+ var builder = new TopologyBuilder();+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var vertexPoints = new Dictionary<VertexId, KernelPoint>();+ var vertices = new Dictionary<int, VertexId>();+ var edges = new Dictionary<int, EdgeId>();+ var faces = new List<FaceId>();+ var boundTrims = 0;+ var sourcePcurves = 0;+ var adjustments = new List<ThreeDmTopologyAdjustment>();+ var endpointCandidates = new Dictionary<int, List<KernelPoint>>();+ var vertexTolerances = new Dictionary<VertexId, double>();+ var singularTransitions = new HashSet<(CoedgeId Current, CoedgeId Next)>();++ try+ {+ foreach (var vertex in source.Vertices)+ {+ var id = builder.AddVertex();+ vertices.Add(vertex.VertexIndex, id);+ vertexPoints.Add(id, ToPoint(vertex.Location, millimetresPerUnit));+ vertexTolerances.Add(id, double.IsFinite(vertex.Tolerance)+ ? double.Min(1d, double.Max(0d, vertex.Tolerance * millimetresPerUnit)) : 0d);+ }+ foreach (var edge in source.Edges)+ {+ if (edge.StartVertex is null || edge.EndVertex is null)+ return Failed($"object:{objectIndex}/edge:{edge.EdgeIndex}: endpoint vertex missing.");+ var id = builder.AddEdge(vertices[edge.StartVertex.VertexIndex], vertices[edge.EndVertex.VertexIndex]);+ edges.Add(edge.EdgeIndex, id);+ var curve = BindCurve(edge, sourceId, millimetresPerUnit, recoveryToleranceMillimetres,+ out var interval, out var reason);+ if (curve is null) return Failed($"object:{objectIndex}/edge:{edge.EdgeIndex}: {reason}");+ var geometryId = new CurveGeometryId(edge.EdgeIndex + 1);+ geometry.AddCurve(geometryId, curve);+ bindings.AddEdgeBinding(new(id, geometryId, interval));+ AddEndpoint(edge.StartVertex.VertexIndex, EvaluateCurve(curve, interval.Start));+ AddEndpoint(edge.EndVertex.VertexIndex, EvaluateCurve(curve, interval.End));+ }+ foreach (var vertex in source.Vertices)+ {+ if (!endpointCandidates.TryGetValue(vertex.VertexIndex, out var candidates) || candidates.Count == 0) continue;+ var id = vertices[vertex.VertexIndex];+ var original = vertexPoints[id];+ var before = candidates.Max(point => (point - original).Length);+ if (before <= 1e-6d) continue;+ var anchor = candidates[0];+ var after = candidates.Max(point => (point - anchor).Length);+ var sourceLimit = double.IsFinite(vertex.Tolerance) && vertex.Tolerance > 0+ ? vertex.Tolerance * millimetresPerUnit : recoveryToleranceMillimetres;+ // Source vertex tolerance is topology evidence, distinct from spline recovery error.+ // Cap it locally; never change the kernel or authored tolerance.+ var allowed = double.Max(recoveryToleranceMillimetres, double.Min(1d, sourceLimit));+ if (before > allowed || after > 1e-6d) continue;+ vertexPoints[id] = anchor;+ adjustments.Add(new("SourceVertexToCoincidentEdgeEndpoints", vertex.VertexIndex,+ before, after, allowed, "All incident bound edge endpoints agree; source vertex is within its declared tolerance."));+ }++ foreach (var face in source.Faces)+ {+ var surface = BindSurface(source.Surfaces[face.SurfaceIndex], sourceId, face.FaceIndex, millimetresPerUnit,+ recoveryToleranceMillimetres, out var reason);+ if (surface is null) return Failed($"object:{objectIndex}/face:{face.FaceIndex}: {reason}");+ var loops = new List<LoopId>();+ var pendingPcurves = new List<(CoedgeId Id, BrepTrim Trim)>();+ foreach (var loop in face.Loops)+ {+ if (loop.Trims.Count == 0) return Failed($"object:{objectIndex}/face:{face.FaceIndex}/loop:{loop.LoopIndex}: empty loop.");+ foreach (var trim in loop.Trims.Where(trim => trim.Edge is null))+ {+ if (trim.TrimType != BrepTrimType.Singular || trim.StartVertex is null ||+ trim.StartVertex.VertexIndex != trim.EndVertex?.VertexIndex || trim.TrimCurve is null)+ return Failed($"object:{objectIndex}/face:{face.FaceIndex}/loop:{loop.LoopIndex}/trim:{trim.TrimIndex}: edgeless trim is not a qualified singular vertex use.");+ var vertex = trim.StartVertex;+ var original = ToPoint(vertex.Location, millimetresPerUnit);+ var domain = trim.Domain;+ var worst = 0d;+ for (var sample = 0; sample <= 32; sample++)+ {+ var uv = trim.PointAt(domain.T0 + (domain.T1 - domain.T0) * sample / 32d);+ var lifted = ToPoint(source.Surfaces[face.SurfaceIndex].PointAt(uv.X, uv.Y), millimetresPerUnit);+ worst = double.Max(worst, (lifted - original).Length);+ }+ // Rhino's declared vertex tolerance is source topology evidence, capped locally.+ var allowed = double.Max(recoveryToleranceMillimetres,+ double.Min(1d, double.IsFinite(vertex.Tolerance) ? double.Max(0d, vertex.Tolerance * millimetresPerUnit) : 0d));+ if (!double.IsFinite(worst) || worst > allowed)+ return Failed($"object:{objectIndex}/face:{face.FaceIndex}/loop:{loop.LoopIndex}/trim:{trim.TrimIndex}: singular lift {worst:G9} mm exceeds source-local bound {allowed:G9} mm.");+ adjustments.Add(new("RhinoSingularTrimCollapsedToVertex", trim.TrimIndex, worst, 0d,+ allowed, $"Face {face.FaceIndex}, loop {loop.LoopIndex}, source vertex {vertex.VertexIndex}; no 3D edge exists."));+ }+ var edgeTrims = loop.Trims.Where(trim => trim.Edge is not null).ToArray();+ if (edgeTrims.Length == 0)+ return Failed($"object:{objectIndex}/face:{face.FaceIndex}/loop:{loop.LoopIndex}: standalone singular vertex loop requires a supported collapsed analytic surface.");+ for (var i = 0; i < edgeTrims.Length; i++)+ {+ var previous = edgeTrims[i];+ var next = edgeTrims[(i + 1) % edgeTrims.Length];+ if (previous.EndVertex?.VertexIndex != next.StartVertex?.VertexIndex)+ return Failed($"object:{objectIndex}/face:{face.FaceIndex}/loop:{loop.LoopIndex}/trim:{previous.TrimIndex}: chain ends at vertex {previous.EndVertex?.VertexIndex}, next trim {next.TrimIndex} starts at {next.StartVertex?.VertexIndex}.");+ }+ var loopId = builder.AllocateLoopId();+ var coedges = edgeTrims.Select(_ => builder.AllocateCoedgeId()).ToArray();+ var edgePositions = Enumerable.Range(0, loop.Trims.Count).Where(index => loop.Trims[index].Edge is not null).ToArray();+ for (var i = 0; i < edgePositions.Length; i++)+ if ((edgePositions[(i + 1) % edgePositions.Length] - edgePositions[i] + loop.Trims.Count) % loop.Trims.Count != 1)+ singularTransitions.Add((coedges[i], coedges[(i + 1) % coedges.Length]));+ for (var i = 0; i < coedges.Length; i++)+ {+ var trim = edgeTrims[i];+ builder.AddCoedge(new Coedge(coedges[i], edges[trim.Edge!.EdgeIndex], loopId,+ coedges[(i + 1) % coedges.Length], coedges[(i + coedges.Length - 1) % coedges.Length],+ trim.IsReversed()));+ pendingPcurves.Add((coedges[i], trim));+ boundTrims++;+ }+ boundTrims += loop.Trims.Count - edgeTrims.Length;+ builder.AddLoop(new Loop(loopId, coedges));+ loops.Add(loopId);+ }+ var faceId = builder.AddFace(loops);+ faces.Add(faceId);+ var surfaceId = new SurfaceGeometryId(face.FaceIndex + 1);+ geometry.AddSurface(surfaceId, surface);+ bindings.AddFaceBinding(new FaceGeometryBinding(faceId, surfaceId, !face.OrientationIsReversed));+ for (var i = 0; i < loops.Count; i++)+ {+ var role = face.Loops[i].LoopType == BrepLoopType.Inner ? FaceBoundaryRole.Inner : FaceBoundaryRole.Outer;+ bindings.AddFaceBoundaryRoleBinding(new(faceId, loops[i], role));+ }+ foreach (var (coedgeId, trim) in pendingPcurves)+ {+ if (surface.BSplineSurfaceWithKnots is null || trim.TrimCurve is null || trim.Edge is null)+ continue;+ var edgeBinding = bindings.GetEdgeBinding(edges[trim.Edge.EdgeIndex]);+ if (edgeBinding.TrimInterval is not { } interval) continue;+ var retained = TrySourcePcurve(trim, geometry.GetCurve(edgeBinding.CurveGeometryId),+ surface.BSplineSurfaceWithKnots, interval, millimetresPerUnit,+ recoveryToleranceMillimetres, out var residual);+ if (retained is null) continue;+ bindings.AddPcurveBinding(new(coedgeId, faceId, surfaceId, retained,+ Qualification: new(PcurveBindingOrigin.SourceValidated, residual,+ recoveryToleranceMillimetres, 1025, "RhinoTrimSamples", surface.Kind.ToString())));+ sourcePcurves++;+ }+ }+ var shell = builder.AddShell(faces);+ builder.AddBody([shell]);+ var body = new BrepBody(builder.Model, geometry, bindings, vertexPoints);+ var graph = BrepBindingValidator.Validate(body);+ if (!graph.IsSuccess)+ return Failed($"object:{objectIndex}: {string.Join("; ", graph.Diagnostics.Select(item => item.Message))}");+ var recovered = BrepPcurveRecovery.Populate(builder.Model, geometry, bindings,+ tolerance: recoveryToleranceMillimetres);+ var pcurveEvidence = BrepPcurveValidator.Validate(body, recoveryToleranceMillimetres, requireEveryCoedge: true,+ sourceTopology: new(vertexTolerances, singularTransitions));+ if (!recovered.IsSuccess || !pcurveEvidence.IsValid)+ return Failed($"object:{objectIndex}: pcurve binding: {string.Join("; ", recovered.Diagnostics.Select(item => item.Message).Concat(pcurveEvidence.Diagnostics))}",+ body, recovered.Count - sourcePcurves, recovered.MaximumResidual);+ return new(objectIndex, sourceId, body, source.Faces.Count, source.Trims.Count,+ faces.Count, boundTrims, sourcePcurves, recovered.Count - sourcePcurves,+ recovered.MaximumResidual, diagnostics)+ { Adjustments = adjustments, SourceVertexTolerancesMillimetres = vertexTolerances };+ }+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NotSupportedException or KeyNotFoundException)+ {+ return Failed($"object:{objectIndex}: {exception.GetType().Name}: {exception.Message}");+ }++ ThreeDmBoundBody Failed(string reason, BrepBody? body = null, int recoveredPcurves = 0, double worstResidual = 0)+ {+ diagnostics.Add(reason);+ return new(objectIndex, sourceId, body, source.Faces.Count, source.Trims.Count,+ faces.Count, boundTrims, sourcePcurves, recoveredPcurves, worstResidual, diagnostics)+ { Adjustments = adjustments, SourceVertexTolerancesMillimetres = vertexTolerances };+ }+ void AddEndpoint(int vertexIndex, KernelPoint point)+ {+ if (!endpointCandidates.TryGetValue(vertexIndex, out var points)) endpointCandidates[vertexIndex] = points = [];+ points.Add(point);+ }+ }++ private static KernelPoint 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),+ _ => throw new NotSupportedException($"3DM bound curve {curve.Kind} has no endpoint evaluator.")+ };++ private static CurveGeometry? BindCurve(BrepEdge edge, Guid sourceId, double scale, double tolerance,+ out ParameterInterval interval, out string reason)+ {+ var domain = edge.Domain;+ interval = new(domain.T0, domain.T1);+ reason = string.Empty;+ if (edge.EdgeCurve.IsLinear())+ {+ var start = ToPoint(edge.PointAt(domain.T0), scale);+ var end = ToPoint(edge.PointAt(domain.T1), scale);+ if (!Direction3D.TryCreate(end - start, out var direction))+ { reason = "linear edge has coincident endpoints."; return null; }+ interval = new(0, (end - start).Length);+ return CurveGeometry.FromLine(new Line3Curve(start, direction));+ }+ if (edge.EdgeCurve.TryGetCircle(out var circle) || edge.EdgeCurve.TryGetArc(out var arc) && (circle = new Circle(arc.Plane, arc.Radius)).IsValid)+ {+ var start = edge.PointAt(domain.T0);+ var normal = circle.Normal;+ var radial = start - circle.Center;+ radial.Unitize();+ var tangent = Vector3d.CrossProduct(normal, radial);+ if (tangent * edge.TangentAt(domain.T0) < 0) normal = -normal;+ var geometry = new Circle3Curve(ToPoint(circle.Center, scale), ToDirection(normal),+ circle.Radius * scale, ToDirection(radial));+ var sweep = 2d * double.Pi;+ if (edge.StartVertex?.VertexIndex != edge.EndVertex?.VertexIndex)+ {+ var endRadial = edge.PointAt(domain.T1) - circle.Center;+ var midRadial = edge.PointAt((domain.T0 + domain.T1) * 0.5d) - circle.Center;+ var yAxis = Vector3d.CrossProduct(normal, radial);+ static double PositiveAngle(Vector3d x, Vector3d y, Vector3d vector)+ {+ var angle = double.Atan2(vector * y, vector * x);+ return angle < 0 ? angle + 2d * double.Pi : angle;+ }+ sweep = PositiveAngle(radial, yAxis, endRadial);+ if (PositiveAngle(radial, yAxis, midRadial) > sweep + 1e-8d) sweep += 2d * double.Pi;+ }+ interval = new(0, sweep);+ return CurveGeometry.FromCircle(geometry);+ }+ var source = edge.EdgeCurve.ToNurbsCurve();+ var polynomial = ThreeDmSplineRecovery.SourceCurve(source, scale);+ if (!source.IsRational) return CurveGeometry.FromBSpline(polynomial);+ var weights = Enumerable.Range(0, source.Points.Count).Select(i => source.Points[i].Weight).ToArray();+ if (!BSplineCurveRationalReduction.TryReduce(polynomial, weights, tolerance,+ out var reduced, out var deviation, out reason)) return null;+ interval = new(reduced.DomainStart, reduced.DomainEnd);+ return CurveGeometry.FromRecoveredBSpline(reduced,+ new SplineRecoveryProvenance("3DM_RATIONAL_EDGE", "AdaptiveCubic", tolerance,+ deviation, true, "Rhino analytic probes did not qualify.",+ SourceEntityIdentity: $"3dm:{sourceId}/edge:{edge.EdgeIndex}"));+ }++ private static SurfaceGeometry? BindSurface(Surface source, Guid sourceId, int faceIndex,+ double scale, double tolerance, out string reason)+ {+ reason = string.Empty;+ if (source.TryGetPlane(out var plane))+ return SurfaceGeometry.FromPlane(new Aetheris.Kernel.Core.Geometry.Surfaces.PlaneSurface(ToPoint(plane.Origin, scale),+ ToDirection(plane.Normal), ToDirection(plane.XAxis)));+ if (source.TryGetCylinder(out var cylinder))+ return SurfaceGeometry.FromCylinder(new CylinderSurface(ToPoint(cylinder.Center, scale),+ ToDirection(cylinder.Axis), cylinder.Radius * scale, ToDirection(cylinder.BasePlane.XAxis)));+ if (source.TryGetCone(out var cone) && double.Abs(cone.Height) > 1e-12d)+ return SurfaceGeometry.FromCone(new ConeSurface(ToPoint(cone.ApexPoint, scale),+ ToDirection(cone.Axis), double.Atan(double.Abs(cone.Radius / cone.Height)),+ ToDirection(cone.Plane.XAxis)));+ if (source.TryGetSphere(out var sphere))+ return SurfaceGeometry.FromSphere(new SphereSurface(ToPoint(sphere.Center, scale),+ ToDirection(sphere.EquatorialPlane.Normal), sphere.Radius * scale,+ ToDirection(sphere.EquatorialPlane.XAxis)));+ if (source.TryGetTorus(out var torus))+ return SurfaceGeometry.FromTorus(new TorusSurface(ToPoint(torus.Plane.Origin, scale),+ ToDirection(torus.Plane.Normal), torus.MajorRadius * scale,+ torus.MinorRadius * scale, ToDirection(torus.Plane.XAxis)));+ var nurbs = source.ToNurbsSurface();+ var spline = ThreeDmSplineRecovery.SourceSurface(nurbs, scale);+ if (!spline.IsRational) return SurfaceGeometry.FromBSplineSurfaceWithKnots(spline);+ if (!BSplineSurfaceRationalReduction.TryReduce(spline, tolerance,+ out var reduced, out var deviation, out reason) || reduced is null) return null;+ return SurfaceGeometry.FromRecoveredBSplineSurfaceWithKnots(reduced,+ new SplineRecoveryProvenance("3DM_RATIONAL_FACE", "AdaptiveGreville", tolerance,+ deviation, true, "Rhino analytic probes did not qualify.",+ SourceEntityIdentity: $"3dm:{sourceId}/face:{faceIndex}"));+ }++ private static PcurveGeometry? TrySourcePcurve(BrepTrim trim, CurveGeometry boundCurve,+ BSplineSurfaceWithKnots recovered, ParameterInterval interval, double scale,+ double tolerance, out double maximum)+ {+ maximum = 0;+ var uv = new SurfaceParameterPoint[1025];+ var domain = trim.Domain;+ for (var i = 0; i < uv.Length; i++)+ {+ var fraction = i / 1024d;+ var edge = trim.Edge!;+ var edgeDomain = edge.Domain;+ var edgeFraction = fraction;+ if (boundCurve.Circle3 is { } circle)+ {+ var angle = interval.Start + (interval.End - interval.Start) * fraction;+ var target = circle.Evaluate(angle);+ var targetSource = new Point3d(target.X / scale, target.Y / scale, target.Z / scale);+ edgeFraction = fraction == 1d ? 1d : ClosestParameterFraction(edge, targetSource);+ }+ var sourceFraction = trim.IsReversed() ? 1d - edgeFraction : edgeFraction;+ var point = trim.PointAt(domain.T0 + (domain.T1 - domain.T0) * sourceFraction);+ uv[i] = new(point.X, point.Y);+ var edgePoint = boundCurve.Circle3 is { } boundCircle+ ? boundCircle.Evaluate(interval.Start + (interval.End - interval.Start) * fraction)+ : ToPoint(edge.PointAt(edgeDomain.T0 + (edgeDomain.T1 - edgeDomain.T0) * fraction), scale);+ var lifted = recovered.Evaluate(point.X, point.Y);+ var residual = (lifted - edgePoint).Length;+ maximum = double.Max(maximum, residual);+ if (!double.IsFinite(maximum) || maximum > tolerance) return null;+ }+ return PcurveGeometry.Polyline(interval, uv);+ }++ private static KernelPoint ToPoint(Point3d source, double scale) =>+ new(source.X * scale, source.Y * scale, source.Z * scale);++ private static double ClosestParameterFraction(BrepEdge edge, Point3d target)+ {+ var domain = edge.Domain;+ var bestIndex = 0;+ var best = double.PositiveInfinity;+ for (var i = 0; i <= 64; i++)+ {+ var parameter = domain.T0 + (domain.T1 - domain.T0) * i / 64d;+ var distance = edge.PointAt(parameter).DistanceToSquared(target);+ if (distance < best) { best = distance; bestIndex = i; }+ }+ var lower = double.Max(0, bestIndex - 1) / 64d;+ var upper = double.Min(64, bestIndex + 1) / 64d;+ for (var i = 0; i < 24; i++)+ {+ var left = lower + (upper - lower) / 3d;+ var right = upper - (upper - lower) / 3d;+ var leftPoint = edge.PointAt(domain.T0 + (domain.T1 - domain.T0) * left);+ var rightPoint = edge.PointAt(domain.T0 + (domain.T1 - domain.T0) * right);+ if (leftPoint.DistanceToSquared(target) < rightPoint.DistanceToSquared(target)) upper = right;+ else lower = left;+ }+ return (lower + upper) / 2d;+ }+ private static Direction3D ToDirection(Vector3d source) =>+ Direction3D.Create(new Vector3D(source.X, source.Y, source.Z));+}diff --git a/Aetheris.ThreeDm/ThreeDmRecovery.cs b/Aetheris.ThreeDm/ThreeDmRecovery.csindex c2d7d6b3..a12e9930 100644--- a/Aetheris.ThreeDm/ThreeDmRecovery.cs+++ b/Aetheris.ThreeDm/ThreeDmRecovery.cs@@ -6,7 +6,7 @@ using KernelPoint = Aetheris.Kernel.Core.Math.Point3D;namespace Aetheris.ThreeDm;-public enum RecoveryQualification { WithinSourceTolerance, Approximate, Unresolved }+public enum RecoveryQualification { WithinSourceTolerance, Approximate, Unresolved, WithinRecoveryTolerance }public sealed record RecoveryResidual(double RmsMillimetres, double P95Millimetres, double MaxMillimetres,@@ -20,13 +20,19 @@ public sealed record RecoveryEdge(int EdgeIndex, bool SourceIsRational, int Degree, int ControlPointCount, int KnotCount,double MinimumWeight, double MaximumWeight, double RelativeWeightSpread,string NativeClassification, IReadOnlyList<RecoveryCandidate> Candidates,- string? PreferredCandidate, string Status, string TopologyStatus);+ string? PreferredCandidate, string Status, string TopologyStatus)+{+ public RecoveryCandidate? GenericRecovery { get; init; }+}public sealed record RecoveryFace(int FaceIndex, int SurfaceIndex, bool SourceIsRational, int DegreeU, int DegreeV,int ControlPointCountU, int ControlPointCountV, int KnotCountU, int KnotCountV,int LoopCount, int TrimCount, string NativeClassification, RecoveryCandidate? Candidate,- string Status, string TopologyStatus);+ string Status, string TopologyStatus)+{+ public RecoveryCandidate? GenericRecovery { get; init; }+}public sealed record RecoveryBody(int ObjectIndex, Guid SourceId, int LayerIndex, bool SourceIsSolid, bool SourceIsManifold,@@ -47,7 +53,18 @@ public sealed record ThreeDmRecoveryReport(int SourceRationalSurfaceCount, int QualifiedAnalyticRationalSurfaceCount,int UnresolvedRationalSurfaceCount,IReadOnlyList<RecoveryDimensionHypothesis> RepeatedDimensions,- string ProductionStatus, IReadOnlyList<string> Diagnostics);+ string ProductionStatus, IReadOnlyList<string> Diagnostics)+{+ public double RecoveryToleranceMillimetres { get; init; }+ public int RecoveredCurveCount => Bodies.Sum(body => body.Edges.Count(edge =>+ edge.GenericRecovery?.Qualification == RecoveryQualification.WithinRecoveryTolerance));+ public int RecoveredSurfaceCount => Bodies.Sum(body => body.Faces.Count(face =>+ face.GenericRecovery?.Qualification == RecoveryQualification.WithinRecoveryTolerance));+ public int UnrecoveredCurveCount => Bodies.Sum(body => body.Edges.Count(edge =>+ edge.GenericRecovery is { Qualification: RecoveryQualification.Unresolved }));+ public int UnrecoveredSurfaceCount => Bodies.Sum(body => body.Faces.Count(face =>+ face.GenericRecovery is { Qualification: RecoveryQualification.Unresolved }));+}/// <summary>/// Deterministic, read-only geometry recovery evidence. Candidates are support-geometry@@ -55,9 +72,11 @@ public sealed record ThreeDmRecoveryReport(/// </summary>public static class ThreeDmRecovery{- public static ThreeDmRecoveryReport Analyze(string path)+ public static ThreeDmRecoveryReport Analyze(string path, double recoveryToleranceMillimetres = 0.1d){ArgumentException.ThrowIfNullOrWhiteSpace(path);+ if (!double.IsFinite(recoveryToleranceMillimetres) || recoveryToleranceMillimetres <= 0d)+ throw new ArgumentOutOfRangeException(nameof(recoveryToleranceMillimetres), "Recovery tolerance must be positive and finite.");using var file = File3dm.Read(Path.GetFullPath(path)) ?? throw new InvalidDataException("OpenNURBS could not read the 3DM file.");var unit = file.Settings.ModelUnitSystem.ToString();var factor = unit switch@@ -84,10 +103,10 @@ public static class ThreeDmRecovery}var edges = new List<RecoveryEdge>(brep.Edges.Count);foreach (var edge in brep.Edges)- edges.Add(RecoverEdge(edge, factor, tolerance, angleToleranceDegrees));+ edges.Add(RecoverEdge(edge, factor, tolerance, angleToleranceDegrees, recoveryToleranceMillimetres));var faces = new List<RecoveryFace>(brep.Faces.Count);foreach (var face in brep.Faces)- faces.Add(RecoverFace(face, brep.Surfaces[face.SurfaceIndex], factor, tolerance, angleToleranceDegrees));+ faces.Add(RecoverFace(face, brep.Surfaces[face.SurfaceIndex], factor, tolerance, angleToleranceDegrees, recoveryToleranceMillimetres));var box = ThreeDmBoundsSampler.Sample(brep);bodies.Add(new RecoveryBody(objectIndex, item.Attributes.ObjectId, item.Attributes.LayerIndex,brep.IsSolid, brep.IsManifold, brep.Faces.Count, brep.Loops.Count, brep.Trims.Count,@@ -116,10 +135,11 @@ public static class ThreeDmRecoveryallFaces.Count(f => f.SourceIsRational && f.Status == "Qualified support candidate; topology pending"),allFaces.Count(f => f.SourceIsRational && f.Status == "Unresolved"),RepeatedDimensions(bodies, tolerance),- "No canonical BRep or production STEP is emitted. All candidates require trim/topology qualification.", diagnostics);+ "No canonical BRep or production STEP is emitted. All candidates require trim/topology qualification.", diagnostics)+ { RecoveryToleranceMillimetres = recoveryToleranceMillimetres };}- private static RecoveryEdge RecoverEdge(BrepEdge edge, double factor, double toleranceMm, double angleToleranceDegrees)+ private static RecoveryEdge RecoverEdge(BrepEdge edge, double factor, double toleranceMm, double angleToleranceDegrees, double recoveryToleranceMm){var source = edge.EdgeCurve;var nurbs = source.ToNurbsCurve();@@ -206,10 +226,11 @@ public static class ThreeDmRecoveryreturn new RecoveryEdge(edge.EdgeIndex, true, nurbs.Degree, nurbs.Points.Count, nurbs.Knots.Count,minimumWeight, maximumWeight, relativeWeightSpread, "Unclassified", candidates, preferred,preferred is null ? "Unresolved" : "Qualified support candidate; topology pending",- "Original edge and trims retained as source evidence; no canonical edge built.");+ "Original edge and trims retained as source evidence; no canonical edge built.")+ { GenericRecovery = ThreeDmSplineRecovery.RecoverCurve(nurbs, factor, recoveryToleranceMm) };}- private static RecoveryFace RecoverFace(BrepFace face, Surface surface, double factor, double toleranceMm, double angleToleranceDegrees)+ private static RecoveryFace RecoverFace(BrepFace face, Surface surface, double factor, double toleranceMm, double angleToleranceDegrees, double recoveryToleranceMm){var nurbs = surface.ToNurbsSurface();var kind = "Unclassified";@@ -312,7 +333,9 @@ public static class ThreeDmRecoverynurbs.KnotsU.Count, nurbs.KnotsV.Count, face.Loops.Count,face.Loops.Sum(loop => loop.Trims.Count), kind, candidate,qualified ? "Qualified support candidate; topology pending" : "Unresolved",- "Source loops/trims are inventory only; no canonical face or pcurve built.");+ "Source loops/trims are inventory only; no canonical face or pcurve built.")+ { GenericRecovery = nurbs.IsRational && !qualified+ ? ThreeDmSplineRecovery.RecoverSurface(nurbs, factor, recoveryToleranceMm) : null };}private static IReadOnlyList<Point3d> SampleEdge(BrepEdge edge, int count)diff --git a/Aetheris.ThreeDm/ThreeDmSplineRecovery.cs b/Aetheris.ThreeDm/ThreeDmSplineRecovery.csnew file mode 100644index 00000000..a5d9ca06--- /dev/null+++ b/Aetheris.ThreeDm/ThreeDmSplineRecovery.cs@@ -0,0 +1,146 @@+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Rhino.Geometry;+using KernelPoint = Aetheris.Kernel.Core.Math.Point3D;++namespace Aetheris.ThreeDm;++/// <summary>Import-only bridge from OpenNURBS source nets to the shared STEP spline reducers.</summary>+internal static class ThreeDmSplineRecovery+{+ internal static BSpline3Curve SourceCurve(NurbsCurve source, double scale)+ {+ var controls = Enumerable.Range(0, source.Points.Count)+ .Select(i => source.Points[i].Location)+ .Select(p => new KernelPoint(p.X * scale, p.Y * scale, p.Z * scale)).ToArray();+ var (values, multiplicities) = Knots(Enumerable.Range(0, source.Knots.Count)+ .Select(i => source.Knots[i]).ToArray());+ return new BSpline3Curve(source.Degree, controls, multiplicities, values,+ "UNSPECIFIED", source.IsClosed, false, "UNSPECIFIED");+ }++ internal static BSplineSurfaceWithKnots SourceSurface(NurbsSurface source, double scale)+ {+ var controls = new IReadOnlyList<KernelPoint>[source.Points.CountU];+ var weights = new IReadOnlyList<double>[source.Points.CountU];+ for (var u = 0; u < source.Points.CountU; u++)+ {+ var row = new KernelPoint[source.Points.CountV];+ var weightRow = new double[source.Points.CountV];+ for (var v = 0; v < source.Points.CountV; v++)+ {+ var point = source.Points.GetControlPoint(u, v);+ row[v] = new KernelPoint(point.Location.X * scale, point.Location.Y * scale, point.Location.Z * scale);+ weightRow[v] = point.Weight;+ }+ controls[u] = row;+ weights[u] = weightRow;+ }+ var (valuesU, multiplicitiesU) = Knots(Enumerable.Range(0, source.KnotsU.Count)+ .Select(i => source.KnotsU[i]).ToArray());+ var (valuesV, multiplicitiesV) = Knots(Enumerable.Range(0, source.KnotsV.Count)+ .Select(i => source.KnotsV[i]).ToArray());+ return new BSplineSurfaceWithKnots(source.OrderU - 1, source.OrderV - 1,+ controls, "UNSPECIFIED", source.IsClosed(0), source.IsClosed(1), false,+ multiplicitiesU, multiplicitiesV, valuesU, valuesV, "UNSPECIFIED", weights);+ }++ internal static RecoveryCandidate RecoverCurve(NurbsCurve source, double scale, double tolerance)+ {+ try+ {+ var weights = Enumerable.Range(0, source.Points.Count).Select(i => source.Points[i].Weight).ToArray();+ var curve = SourceCurve(source, scale);+ if (BSplineCurveRationalReduction.TryReduce(curve, weights, tolerance,+ out var reduced, out var deviation, out var reason))+ {+ var sourceDomain = source.Domain;+ var distances = Enumerable.Range(0, 65).Select(i =>+ {+ var parameter = sourceDomain.T0 + (sourceDomain.T1 - sourceDomain.T0) * i / 64d;+ var actual = source.PointAt(parameter);+ var candidate = reduced.Evaluate(parameter);+ return Distance(actual, candidate, scale);+ }).ToArray();+ return Candidate("RecoveredSpline", "AdaptiveCubic", tolerance,+ double.Max(deviation, distances.Max()), reduced.ControlPoints.Count, 0, reason, distances);+ }+ return Candidate("RecoveredSpline", "AdaptiveCubic", tolerance, deviation, 0, 0, reason);+ }+ catch (ArgumentException ex)+ {+ return Candidate("RecoveredSpline", "AdaptiveCubic", tolerance, double.PositiveInfinity, 0, 0, ex.Message);+ }+ }++ internal static RecoveryCandidate RecoverSurface(NurbsSurface source, double scale, double tolerance)+ {+ try+ {+ var surface = SourceSurface(source, scale);+ RecoveryCandidate? last = null;+ for (var attempt = 0; attempt < 3; attempt++)+ {+ var workingTolerance = tolerance / (1 << attempt);+ if (!BSplineSurfaceRationalReduction.TryReduce(surface, workingTolerance,+ out var reduced, out var deviation, out var reason) || reduced is null)+ return last ?? Candidate("RecoveredSpline", "AdaptiveGreville", tolerance, deviation, 0, 0, reason);+ var domainU = source.Domain(0);+ var domainV = source.Domain(1);+ var distances = new double[17 * 17];+ for (var u = 0; u < 17; u++)+ for (var v = 0; v < 17; v++)+ {+ var parameterU = domainU.T0 + (domainU.T1 - domainU.T0) * u / 16d;+ var parameterV = domainV.T0 + (domainV.T1 - domainV.T0) * v / 16d;+ distances[u * 17 + v] = Distance(source.PointAt(parameterU, parameterV),+ reduced.Evaluate(parameterU, parameterV), scale);+ }+ var measured = double.Max(deviation, distances.Max());+ last = Candidate("RecoveredSpline", "AdaptiveGreville", tolerance,+ measured, reduced.ControlPoints.Count, reduced.ControlPoints[0].Count,+ $"{reason} Independent Rhino maximum {distances.Max():G6} mm; refinement attempt {attempt + 1}/3.", distances);+ if (measured <= tolerance) return last;+ }+ return last!;+ }+ catch (ArgumentException ex)+ {+ return Candidate("RecoveredSpline", "AdaptiveGreville", tolerance, double.PositiveInfinity, 0, 0, ex.Message);+ }+ }++ // OpenNURBS stores the interior/full knot vector without one knot at either end.+ private static (double[] Values, int[] Multiplicities) Knots(IReadOnlyList<double> source)+ {+ if (source.Count == 0) throw new ArgumentException("Source knot vector is empty.");+ var values = new List<double>();+ var multiplicities = new List<int>();+ for (var i = -1; i <= source.Count; i++)+ {+ var knot = source[int.Clamp(i, 0, source.Count - 1)];+ if (values.Count > 0 && knot == values[^1]) multiplicities[^1]++;+ else { values.Add(knot); multiplicities.Add(1); }+ }+ return (values.ToArray(), multiplicities.ToArray());+ }++ private static double Distance(Point3d source, KernelPoint recovered, double scale) =>+ double.Sqrt(double.Pow(source.X * scale - recovered.X, 2) ++ double.Pow(source.Y * scale - recovered.Y, 2) ++ double.Pow(source.Z * scale - recovered.Z, 2));++ private static RecoveryCandidate Candidate(string kind, string method, double tolerance,+ double deviation, int controlsU, int controlsV, string reason, double[]? independentDistances = null) =>+ new(kind, method,+ new RecoveryResidual(+ independentDistances is null ? 0 : double.Sqrt(independentDistances.Average(d => d * d)),+ independentDistances is null ? 0 : independentDistances.OrderBy(d => d).ElementAt(+ (int)double.Ceiling(0.95 * independentDistances.Length) - 1),+ deviation, 0, null, independentDistances?.Length ?? 0),+ double.IsFinite(deviation) && deviation <= tolerance+ ? RecoveryQualification.WithinRecoveryTolerance : RecoveryQualification.Unresolved,+ new Dictionary<string, double> { ["controlPointsU"] = controlsU, ["controlPointsV"] = controlsV,+ ["recoveryToleranceMillimetres"] = tolerance },+ $"{reason} Max includes shared reducer validation and independent Rhino evaluation; RMS/p95 use independent samples. Support geometry only; edge/trim/loop binding and topology remain unqualified.");+}diff --git a/Aetheris.ThreeDm/ThreeDmStepRecovery.cs b/Aetheris.ThreeDm/ThreeDmStepRecovery.csnew file mode 100644index 00000000..5a2eab1a--- /dev/null+++ b/Aetheris.ThreeDm/ThreeDmStepRecovery.cs@@ -0,0 +1,354 @@+using System.Diagnostics;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Step242;+using Rhino.FileIO;+using Rhino.Geometry;++namespace Aetheris.ThreeDm;++public enum ThreeDmStepImportStatus { Qualified, InspectableRecovered, Partial, Unsupported }++public sealed record ThreeDmStepBodyResult(+ int ObjectIndex, Guid SourceId, int SourceFaces, int BoundFaces,+ int SourceTrims, int BoundTrims, int SourcePcurves, int RecoveredPcurves,+ double WorstPcurveResidualMillimetres, bool SourceIsManifold,+ bool BoundIsEnclosed, bool BoundOrientationConsistent,+ bool StepExported, bool StepReimported, string? StepPath,+ double BindingMilliseconds, double ExportMilliseconds,+ IReadOnlyList<string> Diagnostics)+{+ public ThreeDmStepImportStatus Status => !StepReimported+ ? BoundFaces > 0 ? ThreeDmStepImportStatus.Partial : ThreeDmStepImportStatus.Unsupported+ : Adjustments.Count > 0 ? ThreeDmStepImportStatus.InspectableRecovered : ThreeDmStepImportStatus.Qualified;+ public double? MaximumBoundingBoxDriftMillimetres { get; init; }+ public IReadOnlyList<string> StepPaths { get; init; } = [];+ public int ComponentCount { get; init; } = 1;+ public IReadOnlyList<ThreeDmTopologyAdjustment> Adjustments { get; init; } = [];+}++public sealed record ThreeDmStepRecoveryReport(+ string SourcePath, double RecoveryToleranceMillimetres,+ IReadOnlyList<ThreeDmStepBodyResult> Bodies, double SourceReadMilliseconds,+ double SupportStudyMilliseconds, double TotalMilliseconds)+{+ public int QualifiedBodyCount => Bodies.Count(body => body.StepExported && body.StepReimported);+ public int PartialBodyCount => Bodies.Count - QualifiedBodyCount;+ public int BoundFaceCount => Bodies.Sum(body => body.BoundFaces);+ public int BoundTrimCount => Bodies.Sum(body => body.BoundTrims);+ public string? CombinedStepPath { get; init; }+ public bool CombinedStepReimported { get; init; }+ public int CombinedSolidCount { get; init; }+ public double? CombinedBoundingBoxDriftMillimetres { get; init; }+ public IReadOnlyList<string> CombinedDiagnostics { get; init; } = [];+}++/// <summary>Local 3DM-to-STEP qualification route; each source BRep fails independently.</summary>+public static class ThreeDmStepRecovery+{+ public static ThreeDmStepRecoveryReport Run(string path, string outputDirectory,+ double recoveryToleranceMillimetres = 0.1d, int? selectedObjectIndex = null,+ bool emitCombinedStep = false)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(path);+ ArgumentException.ThrowIfNullOrWhiteSpace(outputDirectory);+ if (!double.IsFinite(recoveryToleranceMillimetres) || recoveryToleranceMillimetres <= 0)+ throw new ArgumentOutOfRangeException(nameof(recoveryToleranceMillimetres));+ if (emitCombinedStep && selectedObjectIndex.HasValue)+ throw new ArgumentException("Combined STEP requires the complete source file.", nameof(selectedObjectIndex));+ var total = Stopwatch.StartNew();+ var study = Stopwatch.StartNew();+ var support = ThreeDmRecovery.Analyze(path, recoveryToleranceMillimetres);+ study.Stop();+ var read = Stopwatch.StartNew();+ using var file = File3dm.Read(Path.GetFullPath(path))+ ?? throw new InvalidDataException("OpenNURBS could not read the 3DM file.");+ read.Stop();+ Directory.CreateDirectory(outputDirectory);+ var results = new List<ThreeDmStepBodyResult>();+ var objectIndex = 0;+ foreach (var item in file.Objects)+ {+ if (selectedObjectIndex.HasValue && objectIndex != selectedObjectIndex.Value)+ { objectIndex++; continue; }+ if (item.Geometry is not Brep source) { objectIndex++; continue; }+ var components = ConnectedFaceComponents(source);+ Brep[] parts = components.Count == 1+ ? [source]+ : components.Select(faces => source.DuplicateSubBrep(faces)).ToArray();+ var partResults = parts.Select((part, index) => RecoverPart(part, objectIndex,+ item.Attributes.ObjectId, components.Count == 1 ? null : index, outputDirectory,+ support.MillimetresPerSourceUnit, recoveryToleranceMillimetres)).ToArray();+ var paths = partResults.Select(result => result.StepPath).OfType<string>().ToArray();+ results.Add(new(objectIndex, item.Attributes.ObjectId, source.Faces.Count,+ partResults.Sum(result => result.BoundFaces), source.Trims.Count,+ partResults.Sum(result => result.BoundTrims), partResults.Sum(result => result.SourcePcurves),+ partResults.Sum(result => result.RecoveredPcurves),+ partResults.Max(result => result.WorstPcurveResidualMillimetres), source.IsManifold,+ partResults.All(result => result.BoundIsEnclosed),+ partResults.All(result => result.BoundOrientationConsistent),+ partResults.All(result => result.StepExported),+ partResults.All(result => result.StepReimported), paths.FirstOrDefault(),+ partResults.Sum(result => result.BindingMilliseconds),+ partResults.Sum(result => result.ExportMilliseconds),+ partResults.SelectMany(result => result.Diagnostics).ToArray())+ {+ StepPaths = paths,+ ComponentCount = parts.Length,+ Adjustments = partResults.SelectMany(result => result.Adjustments).ToArray(),+ MaximumBoundingBoxDriftMillimetres = partResults.All(result => result.MaximumBoundingBoxDriftMillimetres.HasValue)+ ? partResults.Max(result => result.MaximumBoundingBoxDriftMillimetres!.Value) : null+ });+ objectIndex++;+ }+ CombinedArtifact? combined = null;+ if (emitCombinedStep)+ combined = BuildCombinedArtifact(file, results, outputDirectory,+ support.MillimetresPerSourceUnit, recoveryToleranceMillimetres);+ total.Stop();+ return new(Path.GetFullPath(path), recoveryToleranceMillimetres, results,+ read.Elapsed.TotalMilliseconds, study.Elapsed.TotalMilliseconds, total.Elapsed.TotalMilliseconds)+ {+ CombinedStepPath = combined?.Path,+ CombinedStepReimported = combined?.Reimported ?? false,+ CombinedSolidCount = combined?.SolidCount ?? 0,+ CombinedBoundingBoxDriftMillimetres = combined?.BoundingBoxDriftMillimetres,+ CombinedDiagnostics = combined?.Diagnostics ?? []+ };+ }++ private sealed record CombinedArtifact(string? Path, bool Reimported, int SolidCount,+ double? BoundingBoxDriftMillimetres, IReadOnlyList<string> Diagnostics);++ private static CombinedArtifact BuildCombinedArtifact(File3dm source, IReadOnlyList<ThreeDmStepBodyResult> results,+ string outputDirectory, double scale, double tolerance)+ {+ if (results.Count == 0 || results.Any(result => !result.StepReimported))+ return new(null, false, 0, null, ["Combined STEP requires every selected source BRep to reimport successfully."]);+ var paths = results.SelectMany(result => result.StepPaths).ToArray();+ var importPolicy = new ImportPolicy(RecoveryToleranceMillimetres: tolerance,+ AllowBoundedNearCoincidentInnerLoop: true);+ var identity = new double[] { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };+ var definitions = new List<Step242AssemblyDefinition>(paths.Length);+ var occurrences = new List<Step242AssemblyOccurrence>(paths.Length + 1)+ { new("root", "Recovered 3DM reference", null, null, identity) };+ foreach (var path in paths)+ {+ var name = Path.GetFileNameWithoutExtension(path);+ var body = Step242Importer.ImportBody(File.ReadAllText(path), importPolicy);+ if (!body.IsSuccess)+ return new(null, false, definitions.Count, null,+ [$"Combined STEP input {name}: {string.Join("; ", body.Diagnostics.Select(diagnostic => diagnostic.Message))}"]);+ definitions.Add(new($"def:{name}", name, body.Value));+ occurrences.Add(new(name, name, "root", $"def:{name}", identity));+ }+ var step = Step242AssemblyExporter.Export(new("Recovered 3DM reference", "root", definitions, occurrences));+ if (!step.IsSuccess)+ return new(null, false, 0, null,+ [$"Combined STEP export: {string.Join("; ", step.Diagnostics.Select(diagnostic => diagnostic.Message))}"]);+ var combinedPath = Path.GetFullPath(Path.Combine(outputDirectory, "recovered-assembly.step"));+ File.WriteAllText(combinedPath, step.Value);+ var reimported = Step242AssemblyImporter.Import(step.Value, importPolicy);+ if (!reimported.IsSuccess)+ return new(combinedPath, false, 0, null,+ [$"Combined STEP reimport: {string.Join("; ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message))}"]);+ var solids = reimported.Value.Definitions.Where(definition => definition.Geometry is not null).ToArray();+ if (solids.Length != paths.Length || reimported.Value.Occurrences.Count != paths.Length ||+ solids.Any(solid =>+ {+ var mass = BrepMassProperties.Evaluate(solid.Geometry!);+ return !mass.IsEnclosed || !mass.IsOrientationConsistent;+ }))+ return new(combinedPath, false, solids.Length, null,+ ["Combined STEP reimport changed the solid/occurrence count or enclosure/orientation."]);+ var drift = CombinedBoundingBoxDrift(source, solids.Select(solid => solid.Geometry!).ToArray(), scale);+ if (!double.IsFinite(drift) || drift > tolerance)+ return new(combinedPath, false, solids.Length, drift,+ [$"Combined STEP bounding-box drift {drift:G9} mm exceeds {tolerance:G9} mm."]);+ return new(combinedPath, true, solids.Length, drift, []);+ }++ private static double CombinedBoundingBoxDrift(File3dm source, IReadOnlyList<BrepBody> solids, double scale)+ {+ var sourcePoints = source.Objects.Select(item => item.Geometry).OfType<Brep>()+ .SelectMany(brep => brep.Edges).SelectMany(edge => Enumerable.Range(0, 129).Select(i =>+ {+ var domain = edge.Domain;+ var point = edge.PointAt(domain.T0 + (domain.T1 - domain.T0) * i / 128d);+ return (X: point.X * scale, Y: point.Y * scale, Z: point.Z * scale);+ })).ToArray();+ var targetPoints = solids.SelectMany(solid => solid.Topology.Edges.SelectMany(edge =>+ {+ var binding = solid.Bindings.GetEdgeBinding(edge.Id);+ var curve = solid.Geometry.GetCurve(binding.CurveGeometryId);+ var interval = binding.TrimInterval!.Value;+ return Enumerable.Range(0, 129).Select(i =>+ {+ var parameter = interval.Start + (interval.End - interval.Start) * i / 128d;+ var point = 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($"Assembly bounding-box sampling cannot evaluate {curve.Kind}.")+ };+ return (point.X, point.Y, point.Z);+ });+ })).ToArray();+ static double[] Bounds((double X, double Y, double Z)[] points) =>+ [points.Min(point => point.X), points.Max(point => point.X),+ points.Min(point => point.Y), points.Max(point => point.Y),+ points.Min(point => point.Z), points.Max(point => point.Z)];+ return Bounds(sourcePoints).Zip(Bounds(targetPoints), (a, b) => double.Abs(a - b)).Max();+ }++ private static ThreeDmStepBodyResult RecoverPart(Brep source, int objectIndex, Guid sourceId,+ int? componentIndex, string outputDirectory, double millimetresPerUnit, double recoveryToleranceMillimetres)+ {+ var label = componentIndex is int index ? $"object:{objectIndex}/component:{index}" : $"object:{objectIndex}";+ var bindingTimer = Stopwatch.StartNew();+ var bound = ThreeDmBrepBinder.Bind(source, objectIndex, sourceId,+ millimetresPerUnit, recoveryToleranceMillimetres);+ bindingTimer.Stop();+ var errors = bound.Diagnostics.ToList();+ var enclosed = false;+ var oriented = false;+ var exported = false;+ var reimported = false;+ double? boundingBoxDrift = null;+ string? stepPath = null;+ var exportTimer = new Stopwatch();+ if (bound.IsQualified && bound.Body is { } body)+ {+ var mass = BrepMassProperties.Evaluate(body);+ enclosed = mass.IsEnclosed;+ oriented = mass.IsOrientationConsistent;+ if (!enclosed || !oriented)+ errors.Add($"{label}: bound shell failed enclosure/orientation: {string.Join("; ", mass.Topology.Messages)}");+ else+ {+ exportTimer.Start();+ // STEP EDGE_LOOP has no mixed singular-trim use. Keep the qualified UV+ // bindings in the import body, but let STEP consumers rebind those loops.+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions+ {+ ProductName = componentIndex is int component ? $"3dm-object-{objectIndex:D3}-component-{component:D2}" : $"3dm-object-{objectIndex:D3}",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,+ ImportedRecoveryToleranceMillimetres = recoveryToleranceMillimetres,+ ImportedSourceVertexTolerancesMillimetres = bound.SourceVertexTolerancesMillimetres,+ EmitQualifiedPcurves = !bound.Adjustments.Any(adjustment => adjustment.Kind == "RhinoSingularTrimCollapsedToVertex")+ });+ if (step.IsSuccess)+ {+ exported = true;+ var name = componentIndex is int partIndex ? $"object-{objectIndex:D3}-component-{partIndex:D2}.step" : $"object-{objectIndex:D3}.step";+ stepPath = Path.GetFullPath(Path.Combine(outputDirectory, name));+ File.WriteAllText(stepPath, step.Value);+ var imported = Step242Importer.ImportBody(step.Value, new ImportPolicy(+ RecoveryToleranceMillimetres: recoveryToleranceMillimetres,+ AllowBoundedNearCoincidentInnerLoop: true));+ reimported = imported.IsSuccess;+ if (!reimported)+ errors.Add($"{label}: STEP reimport: {string.Join("; ", imported.Diagnostics.Select(d => d.Message))}");+ else+ {+ var reimportMass = BrepMassProperties.Evaluate(imported.Value);+ if (!reimportMass.IsEnclosed || !reimportMass.IsOrientationConsistent)+ {+ reimported = false;+ errors.Add($"{label}: STEP reimport shell is not enclosed/oriented: {string.Join("; ", reimportMass.Topology.Messages)}");+ }+ else+ {+ boundingBoxDrift = MaximumBoundingBoxDrift(source, imported.Value,+ millimetresPerUnit);+ if (!double.IsFinite(boundingBoxDrift.Value) ||+ boundingBoxDrift.Value > recoveryToleranceMillimetres)+ {+ reimported = false;+ errors.Add($"{label}: source/STEP sampled bounding-box drift {boundingBoxDrift.Value:G6} mm exceeds {recoveryToleranceMillimetres:G6} mm.");+ }+ }+ }+ }+ else errors.Add($"{label}: STEP export: {string.Join("; ", step.Diagnostics.Select(d => d.Message))}");+ exportTimer.Stop();+ }+ }+ return new(objectIndex, sourceId, source.Faces.Count, bound.BoundFaces,+ source.Trims.Count, bound.BoundTrims, bound.SourcePcurves, bound.RecoveredPcurves,+ bound.WorstPcurveResidualMillimetres, source.IsManifold,+ enclosed, oriented, exported, reimported, stepPath,+ bindingTimer.Elapsed.TotalMilliseconds, exportTimer.Elapsed.TotalMilliseconds, errors)+ { MaximumBoundingBoxDriftMillimetres = boundingBoxDrift,+ StepPaths = stepPath is null ? [] : [stepPath], Adjustments = bound.Adjustments };+ }++ private static IReadOnlyList<int[]> ConnectedFaceComponents(Brep source)+ {+ var neighbors = Enumerable.Range(0, source.Faces.Count).ToDictionary(index => index, _ => new HashSet<int>());+ foreach (var group in source.Trims.Where(trim => trim.Edge is not null && trim.Face is not null)+ .GroupBy(trim => trim.Edge!.EdgeIndex))+ {+ var incident = group.Select(trim => trim.Face!.FaceIndex).Distinct().ToArray();+ foreach (var a in incident) foreach (var b in incident)+ if (a != b) neighbors[a].Add(b);+ }+ var unvisited = neighbors.Keys.ToHashSet();+ var components = new List<int[]>();+ while (unvisited.Count > 0)+ {+ var queue = new Queue<int>(); queue.Enqueue(unvisited.Min());+ var component = new List<int>();+ while (queue.Count > 0)+ {+ var face = queue.Dequeue();+ if (!unvisited.Remove(face)) continue;+ component.Add(face);+ foreach (var neighbor in neighbors[face].Order()) if (unvisited.Contains(neighbor)) queue.Enqueue(neighbor);+ }+ components.Add(component.Order().ToArray());+ }+ return components;+ }++ private static double MaximumBoundingBoxDrift(Brep source, BrepBody reimported, double scale)+ {+ var sourcePoints = source.Edges.SelectMany(edge => Enumerable.Range(0, 129).Select(i =>+ {+ var domain = edge.Domain;+ var point = edge.PointAt(domain.T0 + (domain.T1 - domain.T0) * i / 128d);+ return (X: point.X * scale, Y: point.Y * scale, Z: point.Z * scale);+ })).ToArray();+ var targetPoints = reimported.Topology.Edges.SelectMany(edge =>+ {+ var binding = reimported.Bindings.GetEdgeBinding(edge.Id);+ var curve = reimported.Geometry.GetCurve(binding.CurveGeometryId);+ var interval = binding.TrimInterval!.Value;+ return Enumerable.Range(0, 129).Select(i =>+ {+ var parameter = interval.Start + (interval.End - interval.Start) * i / 128d;+ var point = 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($"Bounding-box sampling cannot evaluate {curve.Kind}.")+ };+ return (point.X, point.Y, point.Z);+ });+ }).ToArray();+ static double[] Bounds((double X, double Y, double Z)[] points) =>+ [points.Min(point => point.X), points.Max(point => point.X),+ points.Min(point => point.Y), points.Max(point => point.Y),+ points.Min(point => point.Z), points.Max(point => point.Z)];+ return Bounds(sourcePoints).Zip(Bounds(targetPoints), (a, b) => double.Abs(a - b)).Max();+ }+}diff --git a/docs/public/reference/3dm-recovery.md b/docs/public/reference/3dm-recovery.mdindex a1cf7bca..5c2e6ebb 100644--- a/docs/public/reference/3dm-recovery.md+++ b/docs/public/reference/3dm-recovery.md@@ -1,8 +1,12 @@# 3DM geometry recovery evidence-`aetheris inspect-3dm model.3dm --json` reads Rhino/OpenNURBS file metadata and BRep inventory. `aetheris recover-3dm model.3dm --json` measures bounded analytic and non-rational recovery candidates. Use `--body N --edge N` or `--body N --face N` with `recover-3dm` to inspect one source entity. The file's unit metadata determines conversion to Aetheris millimetres.+`aetheris inspect-3dm model.3dm --json` reads Rhino/OpenNURBS file metadata and BRep inventory. `aetheris recover-3dm model.3dm --json` measures bounded analytic and non-rational recovery candidates. Use `--body N --edge N` or `--body N --face N` with `recover-3dm` to inspect one source entity. `--recovery-tolerance-mm N` sets the generic spline budget (default 0.1 mm). The file's unit metadata determines conversion to Aetheris millimetres.-The recovery report is a **review aid**. It lists source object UUIDs, body/face/edge indices, degree and control-net sizes, candidate dimensions, RMS/p95/max deviations, angular deviations, rejected alternatives, and topology status. It also groups repeated radii as hypotheses. The command does not rebuild trims, create a canonical Aetheris BRep, infer Firmament authoring history, or export STEP.+The recovery report is a **review aid**. It lists source object UUIDs, body/face/edge indices, degree and control-net sizes, candidate dimensions, RMS/p95/max deviations, angular deviations, rejected alternatives, and topology status. It also groups repeated radii as hypotheses. For unrecognized rational supports, `genericRecovery` reports the bounded non-rational candidate, its method, control-net complexity, and deviation against both the shared reducer and independent Rhino evaluation. The analysis mode does not build a BRep or STEP.++`aetheris recover-3dm model.3dm --bind-step --out-dir artifacts/local/3dm-bind --json` runs the separate topology-binding path. It preserves Rhino edge reuse, vertices, loops, and trim direction, retains source UV pcurves when qualified, and asks the shared recovered-pcurve binder for the rest. It exports only bodies that pass shell, pcurve, trusted STEP preflight, reimport, and sampled bounding-box checks. STEP files and the JSON report should stay under ignored `artifacts/local/` for private source models. Add `--body N` to bind just one source BRep.++Add `--combined-step` for a whole-file AP242 assembly when every source BRep qualifies. This emits `recovered-assembly.step` alongside deterministic per-object files; a source BRep with disconnected closed components contributes one STEP solid per component. Singular Rhino trims remain vertex semantics in the bound BRep. On mixed singular loops, the reference STEP omits pcurve associations that cannot yet roundtrip reliably, while preserving the 3D edges, faces, and source binding evidence. Explicit source vertex tolerances are capped locally at 1 mm and reported separately from the default 0.1 mm spline recovery budget. A near-coincident planar inner loop can be reimported under the explicit `AllowBoundedNearCoincidentInnerLoop` import policy; the default strict STEP importer continues to reject crossings.Reported BRep bounds use 129 deterministic samples on each trimmed edge. Rhino's BRep bounding box can include the untrimmed support surfaces and substantially overstate a part's envelope. Edge-sampled bounds are useful for navigating this file but are not certified face-interior extrema.diff --git a/docs/release/3DM-BREP-BIND-X0.md b/docs/release/3DM-BREP-BIND-X0.mdnew file mode 100644index 00000000..0d51baa7--- /dev/null+++ b/docs/release/3DM-BREP-BIND-X0.md@@ -0,0 +1,59 @@+# 3DM-BREP-BIND-X0 qualification++**Verdict: Meaningful progression.** Aetheris now turns 22 of 27 local Cartesian/Formas Product Design BReps into enclosed, oriented Aetheris bodies, trusted non-rational/analytic STEP files, and successful STEP reimports. Five bodies remain partial, so the complete Product Design model is not yet available as one usable artifact.++## Binding path++`Aetheris.ThreeDm.ThreeDmBrepBinder` maps source vertices and shared edge indices once, then reconstructs trim order, coedge sense, outer/inner loop roles, face sense, and a shell. Rhino analytic planes, cylinders, cones, spheres, and tori become native supports when Rhino recognizes them. Unknown rational surfaces and curves reuse the X2 shared reducers and carry `SplineRecoveryProvenance` with source object UUID and face/edge index. Exact non-rational spline supports stay spline-backed. Authored Firmament geometry is unchanged.++The binder reuses Rhino UV trims where they lift onto the recovered support within 0.1 mm; otherwise it calls `BrepPcurveRecovery.Populate` and `BrepPcurveValidator`. It makes no unrestricted topology repairs or endpoint snaps. The shared pcurve inverter now treats its finite-difference denominators as parameter spans, avoiding a false world-tolerance divide-by-zero on narrow domains. A genuinely closed polynomial spline edge is admitted by STEP preflight when its declared trim endpoints coincide. These changes preserve the authored geometry invariants.++Run locally:++```text+aetheris recover-3dm testdata/3DM/cartesian-product-metres.3dm --bind-step --out-dir artifacts/local/3dm-bind-x0/product --json+```++The exporter is the trusted production route with enforced preflight. Every emitted body is reimported and checked for enclosure, orientation, and sampled bounding-box drift. Output is deterministic per source object (`object-NNN.step`). All derived files remain ignored and local; no Cartesian/Formas source asset is redistributed.++## Product Design witness at 0.1 mm++| Metric | Result |+| --- | ---: |+| Source BReps / faces / trims | 27 / 185 / 742 |+| Bodies exported and reimported | 22 |+| Bodies partial | 5 |+| Faces / trims bound across all attempts | 130 / 443 |+| Faces / trims in qualified bodies | 99 / 302 |+| Recognized analytic / exact non-rational spline / recovered rational spline faces in qualified bodies | 64 / 4 / 31 |+| Retained Rhino UV pcurves / recovered pcurves in qualified bodies | 82 / 220 |+| Qualified enclosed, orientation-consistent shells | 22 |+| Worst qualified pcurve lift residual | 0.09907974 mm |+| Worst sampled source-to-STEP bounding-box coordinate drift | 0.00189385 mm |+| Total warm CLI time | 9.33 s |++Source read took 4.89 ms; the X2 support study took 1.39 s; per-body binding totaled 3.07 s; export, reimport, and their checks totaled 3.17 s. These timings do not isolate face construction from trim binding within each body.++Object 3 is a compact recovered-surface witness: 3 faces and 6 trims bound, 2 Rhino pcurves retained, 4 pcurves recovered, 0.01095 mm worst pcurve residual, enclosed and oriented, STEP reimport successful. Its sampled bounding-box coordinate drift is 0.0002455 mm. Object 8 is a larger 9-face, 42-trim witness. Source-edge and STEP-reimport wireframes show the same ring/block outline, with no obvious missing face or exploded trim. The local source, STEP, and render references are `artifacts/local/3dm-probe/body-3-source.png`, `artifacts/local/3dm-probe/body-3.png`, `artifacts/local/3dm-probe/body-8-source.png`, and `artifacts/local/3dm-bind-x0/product/object-008.png`.++## Partial bodies and next boundary++| Source object | First decisive finding |+| ---: | --- |+| 1 | Trusted STEP preflight finds a cylinder trim 0.000012966 mm off support, above its 0.000001 mm kernel gate. The source recovery budget is 0.1 mm; no global kernel tolerance was relaxed. |+| 5 | Face 1, loop 1 has a singular Rhino trim without a 3D edge. |+| 21 | Trusted STEP preflight finds edge-curve endpoint mismatches. |+| 22 | The bound shell has disconnected face components. |+| 26 | Face 1, loop 1 has a singular Rhino trim without a 3D edge. |++The per-body JSON under `artifacts/local/3dm-bind-x0-product.json` preserves detailed diagnostics and STEP paths. Successful bodies remain available when a different body fails. No snap, trim-closure adjustment, seam split, or healing operation was applied.++Furniture source object 1 (6 faces, 24 trims) also binds, exports, and reimports; it retains 16 Rhino pcurves, recovers 8, and has 0.00907 mm worst lift residual. Furniture object 0 remains partial because two spline pcurves could not be inverted within 0.1 mm.++The complete lamp/Product Design model is still missing five BReps. The next bounded work is singular-trim representation and measured resolution of the three remaining preflight/shell cases. Structure and Interior were not processed in this milestone.++**Downstream X1 closeout (2026-09-29):** All five former partials have bounded resolutions. All 27 source BReps now bind/export/reimport, and one local AP242 assembly contains 28 closed solids because source object 22 has two disconnected components. The X0 verdict and metrics above describe the original X0 run; see [3DM-BREP-BIND-X1.md](3DM-BREP-BIND-X1.md) for the later result and its source-topology limits.++## Validation++Release solution build passed with 0 errors. The fast kernel lane passed 1,002 tests; the full serial solution lane passed, including 452 CLI tests, 1,135 kernel tests, and 1,692 Firmament tests. Local Product Design and Furniture STEP roundtrip tests are included in the CLI lane when their ignored source files are present. The `Aetheris.FrictionLab.Tests` assembly reports no discoverable tests.diff --git a/docs/release/3DM-BREP-BIND-X1.md b/docs/release/3DM-BREP-BIND-X1.mdnew file mode 100644index 00000000..f4d3d6c0--- /dev/null+++ b/docs/release/3DM-BREP-BIND-X1.md@@ -0,0 +1,52 @@+# 3DM-BREP-BIND-X1 — complete Product Design reference STEP++**Verdict: Accepted for the recovered reference artifact.** The local Cartesian/Formas Product Design 3DM now binds all 27 source BReps (185 faces, 742 trims), exports 28 closed solids, and reimports one 28-occurrence AP242 assembly. Rhino object 22 contains two disconnected closed components, so it contributes two solids. This is interoperability geometry for inspection and semantic redraw, not Rhino feature-history recovery or an authored Firmament representation.++## Run and artifact++```text+aetheris recover-3dm testdata/3DM/cartesian-product-metres.3dm --bind-step --combined-step --out-dir artifacts/local/3dm-bind-x1/product --json+```++The ignored local assembly is `artifacts/local/3dm-bind-x1/product/recovered-assembly.step` (10.33 MB). The same directory holds deterministic `object-NNN.step` files and `object-022-component-00/01.step`; `artifacts/local/3dm-bind-x1-product.json` is the qualification report. The combined STEP uses the existing AP242 assembly exporter. Its product-structure importer returns 28 solid definitions and 28 identity-transform occurrences. Every imported solid is enclosed and orientation-consistent. Source assets and source-derived STEP/images remain local and uncommitted.++| Result at 0.1 mm | Value |+| --- | ---: |+| Source BReps / fully bound / partial | 27 / 27 / 0 |+| Source and bound faces / trims | 185 / 185; 742 / 742 |+| Exported and reimported solids | 28 / 28 |+| Worst X2 support deviation | 0.09908 mm |+| Worst bound pcurve lift residual | 0.09908 mm |+| Worst per-solid sampled source-to-STEP bounding-box drift | 0.00224445 mm |+| Combined assembly sampled bounding-box coordinate drift | 0.00000862 mm |+| Warm CLI runtime including assembly export/reimport | 16.67 s |++Per-source-object status is explicit in the JSON report: **Qualified** for objects 0–4, 6–20, 22–25; **InspectableRecovered** for 5, 21, 26; **Partial/Unsupported** for none. Every object exports and reimports. `InspectableRecovered` records the singular or near-coincident source-topology qualification described below; it is not an exact-topology claim.++The original support fitting and 0.1 mm budget are unchanged. The separate Rhino vertex tolerances below are *source topology evidence*, not a change to the recovery or kernel tolerance. No unbounded sew/heal operation or mesh geometry authority was introduced.++## Five former partials++| Object | X0 failure | X1 resolution | Measured bound | Final status |+| ---: | --- | --- | --- | --- |+| 1 | Cylinder trim failed strict 0.000001 mm preflight. | Import-only preflight uses the explicit 0.1 mm recovered-geometry consistency budget for edge/support checks; authored export retains the kernel gate. | 0.000012966 mm support residual, below 0.1 mm. | Qualified; STEP reimported. |+| 5 | 48 Rhino singular trim uses have no 3D edge. | Verify each collapsed trim against its source vertex, retain the vertex and ordinary shared edges, and remove only zero-dimensional trim segments from mixed edge loops. The bound BRep retains qualified pcurves; STEP omits those associations on singular mixed loops so its importer can bind the 3D topology. | Maximum source singular lift 0.424267 mm; opposite incident edge endpoints at one Rhino vertex can differ by 0.848533 mm, within Rhino's local 0.864441 mm vertex tolerance. This inherited topology discrepancy exceeds the 0.1 mm *support* budget and is reported separately. | Inspectable recovered; enclosed/oriented STEP reimported. |+| 21 | Two edge endpoints missed their source vertex. | Move source vertex 8 to the coincident incident edge endpoints; retain the 3D curves. Explicit recovered-STEP import policy admits a declared planar inner loop whose sampled crossing stays inside 0.1 mm. Default strict STEP import still rejects this crossing. | Vertex move 0.06000174 mm, allowed source vertex tolerance 0.198568 mm, final endpoint spread 1.7e-13 mm. Inner-loop maximum sampled outside distance 0.00563952 mm. | Inspectable recovered; STEP reimported with explicit bounded import policy. |+| 22 | One shell was disconnected. | Rhino source graph has two independent six-face closed components. Duplicate those source components and bind/export each without stitching. | Two 6-face, 24-trim manifold solids; worst component bbox drift 0.00007149 mm. | Qualified as two solids; both reimported. |+| 26 | Two Rhino singular trims have no 3D edge. | Preserve their collapsed vertex semantics and shared seam edges; omit ambiguous STEP pcurve associations on this mixed singular loop. | Source singular lift below 1.2e-13 mm; component bbox drift 0.00007507 mm. | Inspectable recovered; enclosed/oriented STEP reimported. |++`ThreeDmBoundBody.Adjustments` and the JSON report record each accepted singular collapse or vertex reconciliation with before/after residual and allowed source-local limit. No seam split, arbitrary edge weld, or unrestricted closure repair was made. Bodies without singular topology continue to export qualified pcurves. The X1 STEP artifact is intended for dimensional/visual reference; readers demanding exact pcurve identity for objects 5 and 26 or strict planar containment for object 21 need the retained 3DM provenance and report.++## Visual comparison and semantic handoff++The local `artifacts/local/3dm-bind-x1/lamp-source-step-semantic.png` shows all source 3DM edges, the combined STEP reimport, and the existing semantic Firmament assembly in the same isometric projection and scale. Separate panels are `rhino-source-3dm.png`, `recovered-step-reimport.png`, and `semantic-firmament-lamp.png` in that directory. The source and recovered STEP visibly agree on the base, pole, upper hardware, and shade, including the source's loose cable. The semantic model captures the intended base, pole, joint, head, and shade with simpler upper hardware and no loose cable. No Firmament source was modified.++## Architecture and limits++The source topology bridge remains in `Aetheris.ThreeDm`. Recovered polynomial supports retain `SplineRecoveryProvenance`; source object identity and face/edge index remain available for later replacement with exact supports. The binder uses the shared pcurve recovery and validator. Singular trim and source-vertex tolerance evidence are passed as explicit import-local inputs; default authored STEP preflight and default strict STEP loop classification remain unchanged. The combined assembly is a reference artifact, not the semantic lamp authority.++STEP reimport of object 21 and of the combined assembly requires `ImportPolicy(AllowBoundedNearCoincidentInnerLoop: true, RecoveryToleranceMillimetres: 0.1)`. Its guarded JudgmentEngine candidate requires one declared outer loop, two planar loops, a smaller declared inner area, no disconnected coedge chain, and sampled outside distance within the supplied budget. The default importer still rejects the crossing. Independent third-party CAD opening has not been verified; the local wireframe and Aetheris reimport establish the current visual and topological result.++## Validation++The local Product Design regression asserts 27/27 source objects, 28/28 combined solid roundtrips, unchanged face/trim totals, measured reconciliation, bounded crossing policy, and combined bbox drift. It also retains a deterministic per-body STEP check and the Furniture representative-body regression. The Release solution build passed. The fast kernel lane passed 1,002/1,002 tests, and the full serial solution gate passed, including 452/452 CLI, 1,135/1,135 Core, and 1,692/1,692 Firmament tests. The FrictionLab assembly currently has no discoverable tests.diff --git a/docs/release/3DM-RECOVERY-X2.md b/docs/release/3DM-RECOVERY-X2.mdnew file mode 100644index 00000000..6e2c54cb--- /dev/null+++ b/docs/release/3DM-RECOVERY-X2.md@@ -0,0 +1,35 @@+# 3DM-RECOVERY-X2 qualification++**Verdict: Meaningful progression.** Real Rhino rational edge and surface support geometry now passes through the shared bounded non-rational STEP recovery algorithms. The 3DM path still has no trim/topology binding or STEP export, so this is not an accepted 3DM-to-STEP milestone.++## Boundary and tolerance++`Aetheris.ThreeDm` converts OpenNURBS control nets, weights, and knot vectors to the existing core spline representation. It attempts Rhino analytic recognition first. Unrecognized rational curves use `BSplineCurveRationalReduction` (adaptive cubic segments); unrecognized rational surfaces use `BSplineSurfaceRationalReduction` (adaptive Greville refinement). The generic result is attached to a source edge or face as `GenericRecovery`, separate from the analytic candidate. It records method, configured budget, maximum sampled deviation, independent Rhino sample statistics, and recovered control counts. The parent BRep report carries the source object UUID and entity indices.++The default recovery budget is **0.1 mm**, configurable with `recover-3dm --recovery-tolerance-mm`. Source tolerance remains separate and governs the older analytic candidate study. Kernel tolerance is not altered. A surface reducer cap of 256 controls per axis and 8,192 controls total prevents unbounded collocation allocation. The shared reducers stop when the requested tolerance is met; the 3DM bridge also checks the result independently against Rhino at matched parameters. These are sampled bounds, not continuous error proofs.++Recovered support geometry belongs to import/interoperability. The authored Firmament materializer and analytic geometry types are untouched. A future exact recognition pass can replace a `GenericRecovery` candidate for the same source edge or face before BRep binding. No recovered spline is promoted to a plane, cylinder, or other analytic authority by this fallback.++## Local witness measurements++All files below are ignored local Cartesian/Formas assets under `testdata/3DM`; none is copied into tracked output. Timings are warm CLI analysis passes on this host and cover source read, recognition, and support reduction together. They do not include topology construction or STEP export.++| Witness | Source BReps | Faces | Edges | Recovered rational curves | Recovered rational surfaces | Worst measured deviation | Manifold / STEP | Time |+| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | ---: |+| Product Design, 0.1 mm | 27 | 185 | 346 | 53 | 83 | 0.09908 mm | Source 27/27 / unavailable | 2.04 s |+| Product Design, 0.05 mm | 27 | 185 | 346 | 53 | 83 | 0.04497 mm | Source 27/27 / unavailable | 2.06 s |+| Furniture, 0.05 mm | 67 | 402 | 804 | 0 | 0 | N/A | Source 67/67 / unavailable | 1.03 s |+| Structure, 0.05 mm | 316 | 2,010 | 4,433 | 0 | 0 | N/A | Source 316/316 / unavailable | 1.35 s |+| Interior, 0.05 mm | 539 | 31,997 | 49,705 | 0 | 0 | N/A | Source 539/539 / unavailable | 6.58 s |++The Product Design source has 143 Rhino-recognized rational analytic edge supports and 21 qualified rational analytic surface supports in the existing study. Its 53 unclassified rational edges and 83 unresolved rational surfaces all produced generic supports at both settings. Aggregate generic control count increased from 3,227 to 3,776 at the tighter setting. At an intentionally extreme 0.00001 mm budget, 53 curves and 37 surfaces qualify while 46 surfaces report failure; all 27 source BRep records remain visible. The other three witnesses have no unresolved rational supports in this study; this does not mean their bodies are imported.++## Blocking work for accepted X2++The current `ThreeDmRecovery.Analyze` returns source topology inventory and support candidates, not `BrepBody`. It does not map Rhino vertices, edge uses, loops, trims, face orientation, and shell enclosure into Aetheris topology. In particular, source pcurves have not been bound or qualified against recovered supports. `BrepPcurveRecovery.Populate` is the existing shared pcurve path to reuse after topology and geometry bindings exist. Without that work, no honest manifold, volume, STEP, or STEP reimport result can be reported. Failed per-body conversion and partial preservation likewise require an actual conversion path.++The next pass should build one complete source BRep through the existing topology/binding model, reuse the shared pcurve binder, validate enclosure and orientation, then run production STEP export and reimport. It should preserve per-object diagnostics so one bad body does not suppress good bodies. This boundary keeps generic source recovery out of authored Firmament geometry.++## Downstream status++The later [3DM-BREP-BIND-X0](3DM-BREP-BIND-X0.md) pass binds and reimports 22 of the 27 Product Design BReps through production STEP. The five remaining bodies have explicit trim, preflight, or enclosure diagnostics. This does not change the X2 support-only verdict above.