Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Promote canonical face orientation over source same-sense
Yuechen Li6708fc825501
diff --git a/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs b/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.csindex 594b9cf8..66f57f3e 100644--- a/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs+++ b/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs@@ -67,7 +67,7 @@ public sealed class ChamferM6FixturePipelineTestsvar coneBinding = Assert.Single(imported.Value.Bindings.FaceBindings,binding => imported.Value.Geometry.GetSurface(binding.SurfaceGeometryId).Kind == SurfaceGeometryKind.Cone);var cone = imported.Value.Geometry.GetSurface(coneBinding.SurfaceGeometryId).Cone!.Value;- Assert.False(coneBinding.SameSense);+ Assert.False(coneBinding.Orientation.IsAlignedWithSurface);Assert.Equal(transitionZ, cone.PlacementOrigin.Z, 9);Assert.Equal(shaftDiameter / 2d, cone.PlacementRadius, 9);Assert.Equal(1d, cone.Axis.ToVector().Z, 9);diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.csindex c8983175..fa89179c 100644--- a/Aetheris.CLI/StepAnalysisModels.cs+++ b/Aetheris.CLI/StepAnalysisModels.cs@@ -25,7 +25,17 @@ public sealed record AnalyzeSummary(string LengthUnitBasis,IdRangeSummary FaceIds,IdRangeSummary EdgeIds,- IdRangeSummary VertexIds);+ IdRangeSummary VertexIds,+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] FaceOrientationSummary? FaceOrientation = null);++public sealed record FaceOrientationSummary(+ int DerivedFaces,+ int SourceAgreements,+ int SourceMismatches,+ int AmbiguousComponents,+ int GlobalFlips,+ IReadOnlyDictionary<string, int> SourceSameSenseDistribution,+ IReadOnlyDictionary<string, int> Qualifications);public sealed record FaceDetail(int FaceId,diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex 8753bc8e..92b9cf7e 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -1722,7 +1722,17 @@ public sealed record VolumeAnalysisResult("assumed; STEP import length units not yet preserved",BuildIdRange(topology.Faces.Select(f => f.Id.Value)),BuildIdRange(topology.Edges.Select(e => e.Id.Value)),- BuildIdRange(topology.Vertices.Select(v => v.Id.Value)));+ BuildIdRange(topology.Vertices.Select(v => v.Id.Value)),+ body.FaceOrientationReport is not { } orientation ? null : new FaceOrientationSummary(+ orientation.DerivedFaceCount,+ orientation.SourceAgreementCount,+ orientation.SourceMismatchCount,+ orientation.AmbiguousComponentCount,+ orientation.GlobalFlipCount,+ orientation.Faces.GroupBy(face => face.SourceEvidence.StepSameSense switch { true => "true", false => "false", null => "missing" })+ .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal),+ orientation.Faces.GroupBy(face => face.Qualification.ToString())+ .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal)));}private static bool AreOrderedLoopsConnected(BrepBody body, out int disconnectedLoop)@@ -2292,8 +2302,8 @@ public sealed record VolumeAnalysisResult(var outward = facePlane.Normal.ToVector();var hasFaceBinding = body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding);- if (hasFaceBinding && !faceBinding.SameSense) outward = -outward;- return Enumerable.Range(0, ordered.Length / 2).Select(i => OrientForMaterialLeft(RawSectionSegment.Line(ProjectPoint(frame, ordered[i * 2].Point), ProjectPoint(frame, ordered[i * 2 + 1].Point)) with { SourceFace = face.Id.Value, SurfaceFamily = "Plane", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = $"faceSameSense={(hasFaceBinding ? faceBinding.SameSense : null)}" }, frame, outward)).ToArray();+ if (hasFaceBinding && !faceBinding.Orientation.IsAlignedWithSurface) outward = -outward;+ return Enumerable.Range(0, ordered.Length / 2).Select(i => OrientForMaterialLeft(RawSectionSegment.Line(ProjectPoint(frame, ordered[i * 2].Point), ProjectPoint(frame, ordered[i * 2 + 1].Point)) with { SourceFace = face.Id.Value, SurfaceFamily = "Plane", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = $"canonicalFaceAligned={(hasFaceBinding ? faceBinding.Orientation.IsAlignedWithSurface : null)}" }, frame, outward)).ToArray();}private static IReadOnlyList<RawSectionSegment> BuildCylinderFaceSectionSegments(BrepBody body, Face face, CylinderSurface cylinder, SectionFrame frame, double epsilon, ICollection<string> notes)@@ -2356,13 +2366,13 @@ public sealed record VolumeAnalysisResult(var sweep = boundedSweep > Math.PI + 1e-9d ? 2d * Math.PI - minorSweep : minorSweep;var start = new Point2D(center.U + cylinder.Radius * Math.Cos(startAngle), center.V + cylinder.Radius * Math.Sin(startAngle));var end = new Point2D(center.U + cylinder.Radius * Math.Cos(startAngle + sweep), center.V + cylinder.Radius * Math.Sin(startAngle + sweep));- var sameSense = body.Bindings.TryGetFaceBinding(face.Id, out var binding) && binding.SameSense;+ var sameSense = body.Bindings.TryGetFaceBinding(face.Id, out var binding) && binding.Orientation.IsAlignedWithSurface;notes.Add($"section-fragment:cylinder:face={face.Id.Value}:sameSense={sameSense}:center=({center.U:R},{center.V:R}):radius={cylinder.Radius:R}:angles=({angles[0]:R},{angles[1]:R}):sweep={sweep:R}:start=({start.U:R},{start.V:R}):end=({end.U:R},{end.V:R})");var midAngle = startAngle + sweep * .5d;var radial = (center3D - cylinder.Origin) + (frame.UAxis * (cylinder.Radius * Math.Cos(midAngle))) + (frame.VAxis * (cylinder.Radius * Math.Sin(midAngle)));var hasCylinderBinding = body.Bindings.TryGetFaceBinding(face.Id, out var cylinderBinding);- if (hasCylinderBinding && !cylinderBinding.SameSense) radial = -radial;- return [OrientForMaterialLeft(RawSectionSegment.Arc(start, end, center, cylinder.Radius, "ccw", sweep) with { SourceFace = face.Id.Value, SurfaceFamily = "Cylinder", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = $"faceSameSense={(hasCylinderBinding ? cylinderBinding.SameSense : null)}" }, frame, radial)];+ if (hasCylinderBinding && !cylinderBinding.Orientation.IsAlignedWithSurface) radial = -radial;+ return [OrientForMaterialLeft(RawSectionSegment.Arc(start, end, center, cylinder.Radius, "ccw", sweep) with { SourceFace = face.Id.Value, SurfaceFamily = "Cylinder", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = $"canonicalFaceAligned={(hasCylinderBinding ? cylinderBinding.Orientation.IsAlignedWithSurface : null)}" }, frame, radial)];}if (angles.Count > 2) notes.Add($"UnsupportedSectionCurve:cylinder-trim-ambiguous:face={face.Id.Value}:angularVertices={angles.Count}");var fullStart = new Point2D(center.U + cylinder.Radius, center.V);diff --git a/Aetheris.Continuum.Tests/Lattice/ContinuumM4Tests.cs b/Aetheris.Continuum.Tests/Lattice/ContinuumM4Tests.csindex b7a73ef2..2457df4f 100644--- a/Aetheris.Continuum.Tests/Lattice/ContinuumM4Tests.cs+++ b/Aetheris.Continuum.Tests/Lattice/ContinuumM4Tests.cs@@ -62,7 +62,7 @@ public sealed class ContinuumM4Tests{var original=BrepPrimitives.CreateBox(2d,1.5d,1d).Value!; var bindings=new BrepBindingModel();foreach(var edge in original.Bindings.EdgeBindings) bindings.AddEdgeBinding(edge);- foreach(var face in original.Bindings.FaceBindings) bindings.AddFaceBinding(face with { SameSense=!face.SameSense });+ foreach(var face in original.Bindings.FaceBindings) bindings.AddFaceBinding(face with { Orientation=face.Orientation.Reversed() });var reversed=new BrepBody(original.Topology,original.Geometry,bindings,vertexPoints:null,original.SafeBooleanComposition,original.ShellRepresentation);diff --git a/Aetheris.Continuum/Boundaries/ExactBrepBoundaryQuery.cs b/Aetheris.Continuum/Boundaries/ExactBrepBoundaryQuery.csindex 09edbb7e..f2566af7 100644--- a/Aetheris.Continuum/Boundaries/ExactBrepBoundaryQuery.cs+++ b/Aetheris.Continuum/Boundaries/ExactBrepBoundaryQuery.cs@@ -42,7 +42,7 @@ public sealed class ExactBrepBoundaryQueryif (!body.Bindings.TryGetFaceBinding(faceId, out var binding))throw new ArgumentException($"BRep face {faceId.Value} has no geometry binding.", nameof(faceId));- _sameSense = binding.SameSense;+ _sameSense = binding.Orientation.IsAlignedWithSurface;_transform = transform;_inverse = transform.Inverse();}diff --git a/Aetheris.Continuum/Boundaries/WholePartComposition.cs b/Aetheris.Continuum/Boundaries/WholePartComposition.csindex 7768cd67..f733f315 100644--- a/Aetheris.Continuum/Boundaries/WholePartComposition.cs+++ b/Aetheris.Continuum/Boundaries/WholePartComposition.cs@@ -231,11 +231,11 @@ public sealed class WholePartCutCellComposer{if(_region.Classify(point,scale*1e-7d)!=ContinuumPointClassification.Boundary)continue;var normal=ExactSupportBoundaryQuery.ExactSupportNormal(_shell.Body,face.FaceId,point,_shell.Transform);- var evidence=MaterialSideClassifier.ClassifyMaterialSide(face.FaceId,point,normal,_region,scale,face.SameSense);+ var evidence=MaterialSideClassifier.ClassifyMaterialSide(face.FaceId,point,normal,_region,scale,face.IsAlignedWithSurface);if(evidence.Status==MaterialSideStatus.Resolved)return evidence;}var fallback=face.ExactBoundarySamples[0];var fallbackNormal=ExactSupportBoundaryQuery.ExactSupportNormal(_shell.Body,face.FaceId,fallback,_shell.Transform);- return MaterialSideClassifier.ClassifyMaterialSide(face.FaceId,fallback,fallbackNormal,_region,scale,face.SameSense);+ return MaterialSideClassifier.ClassifyMaterialSide(face.FaceId,fallback,fallbackNormal,_region,scale,face.IsAlignedWithSurface);}private CutCellCompositionKind Classify(IReadOnlyList<WholeShellBoundaryCandidate> faces)diff --git a/Aetheris.Continuum/Boundaries/WholeShellBoundaryQuery.cs b/Aetheris.Continuum/Boundaries/WholeShellBoundaryQuery.csindex 7a06028c..cce73ebb 100644--- a/Aetheris.Continuum/Boundaries/WholeShellBoundaryQuery.cs+++ b/Aetheris.Continuum/Boundaries/WholeShellBoundaryQuery.cs@@ -14,7 +14,7 @@ public sealed record WholeShellBoundaryCandidate(IReadOnlyList<VertexId> VertexIds,IReadOnlyList<Point3D> OuterTrimVertices,IReadOnlyList<FaceId> AdjacentFaceIds,- bool SameSense,+ bool IsAlignedWithSurface,string? SemanticIdentity,BoundaryReference Reference);@@ -57,7 +57,7 @@ public sealed class WholeShellBoundaryQuerycandidates.Add(ExactSupportBoundaryQuery.ProjectToSupport(body,face.Id,centroid,transform));for(var i=0;i<points.Length;i+=int.Max(1,points.Length/8))candidates.Add(ExactSupportBoundaryQuery.ProjectToSupport(body,face.Id,new Point3D((points[i].X+centroid.X)*.5d,(points[i].Y+centroid.Y)*.5d,(points[i].Z+centroid.Z)*.5d),transform));- rows.Add(new(face.Id, surface.Kind, bounds, candidates, edges, vertices, trim, adjacent, binding.SameSense, semantic, reference));+ rows.Add(new(face.Id, surface.Kind, bounds, candidates, edges, vertices, trim, adjacent, binding.Orientation.IsAlignedWithSurface, semantic, reference));}_faces = rows;Bounds = BoundsOf(rows.SelectMany(row=>new[]{row.Bounds.Min,row.Bounds.Max}).ToArray());diff --git a/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs b/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.csindex 03d58a40..afb16e71 100644--- a/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs+++ b/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs@@ -235,7 +235,7 @@ public sealed class BrepTorusBoundarySupport : IAnalyticBoundarySupportvar supportNormal = Query.ExactSupportNormal(parameters.U, parameters.V);var scale=double.Max(1d,(_region.Bounds.Max-_region.Bounds.Min).Length);var evidence=MaterialSideClassifier.ClassifyMaterialSide(Query.FaceId,boundaryPoint,supportNormal,_region,scale,- Query.Body.Bindings.GetFaceBinding(Query.FaceId).SameSense);+ Query.Body.Bindings.GetFaceBinding(Query.FaceId).Orientation.IsAlignedWithSurface);if(evidence.MaterialSideNormal is { } material)return material;// Projection to the full analytic torus can put a local-map halo point outside this face's// bounded minor sector. Resolve the orientation at the same major parameter in the interior@@ -243,7 +243,7 @@ public sealed class BrepTorusBoundarySupport : IAnalyticBoundarySupportvar referencePoint=Query.Evaluate(parameters.U,.5d*(_minimumMinorParameter+_maximumMinorParameter));var referenceNormal=Query.ExactSupportNormal(parameters.U,.5d*(_minimumMinorParameter+_maximumMinorParameter));var referenceEvidence=MaterialSideClassifier.ClassifyMaterialSide(Query.FaceId,referencePoint,referenceNormal,_region,scale,- Query.Body.Bindings.GetFaceBinding(Query.FaceId).SameSense);+ Query.Body.Bindings.GetFaceBinding(Query.FaceId).Orientation.IsAlignedWithSurface);if(referenceEvidence.MaterialSideNormal is not { } referenceMaterial)throw new InvalidOperationException($"CIR did not resolve material side for torus face {Query.FaceId.Value}.");return referenceMaterial.Dot(referenceNormal)>=0d?supportNormal:-supportNormal;}diff --git a/Aetheris.Kernel.Core.Tests/Brep/BrepMassPropertiesTests.cs b/Aetheris.Kernel.Core.Tests/Brep/BrepMassPropertiesTests.csindex 78980797..d8c86915 100644--- a/Aetheris.Kernel.Core.Tests/Brep/BrepMassPropertiesTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/BrepMassPropertiesTests.cs@@ -66,8 +66,8 @@ public sealed class BrepMassPropertiesTests.ToArray();Assert.Equal(2, coneFaces.Length);- Assert.True(body.Bindings.GetFaceBinding(coneFaces[0].Id).SameSense);- Assert.False(body.Bindings.GetFaceBinding(coneFaces[1].Id).SameSense);+ Assert.True(body.Bindings.GetFaceBinding(coneFaces[0].Id).Orientation.IsAlignedWithSurface);+ Assert.False(body.Bindings.GetFaceBinding(coneFaces[1].Id).Orientation.IsAlignedWithSurface);foreach (var face in coneFaces){var patch = Assert.Single(first.FacePatches, candidate => candidate.FaceId == face.Id);diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayMeshOrientationCorpusTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayMeshOrientationCorpusTests.csindex a2583101..fbf70e54 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayMeshOrientationCorpusTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/DisplayMeshOrientationCorpusTests.cs@@ -46,6 +46,17 @@ public sealed class DisplayMeshOrientationCorpusTestsvar import = Step242Importer.ImportBody(ReadFixture(relativePath));Assert.True(import.IsSuccess);+ var unresolvedShells = import.Value.FaceOrientationReport?.Shells+ .Where(shell => shell.Qualification == FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown)+ .ToArray() ?? [];+ if (unresolvedShells.Length > 0)+ {+ Assert.All(unresolvedShells, shell => Assert.False(shell.IsClosedManifold));+ Assert.Contains(import.Diagnostics, diagnostic =>+ diagnostic.Source == "Importer.StepOrientation.GlobalOrientationUnknown");+ return;+ }+var (windingVolume, normalVolume) = MeasureVolumes(import.Value);Assert.True(windingVolume > 0d, $"triangle winding encloses a negative volume ({windingVolume:G6}), so the mesh is not outward-oriented");diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.csindex 57357a3a..193ce408 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs@@ -274,7 +274,7 @@ public sealed class SurfaceMeshIrTestsvar offset = centroid - cylinder.Origin;var angle = double.Atan2(offset.Dot(cylinder.YAxis.ToVector()), offset.Dot(cylinder.XAxis.ToVector()));var exactNormal = cylinder.Normal(angle).ToVector();- if (!patch.SameSense) exactNormal = -exactNormal;+ if (!patch.IsAlignedWithSupport) exactNormal = -exactNormal;Assert.True((b - a).Cross(c - a).Dot(exactNormal) > 0d, $"Face {patch.FaceId.Value} contains a reversed trim cell.");});}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.csindex 26d74e0c..d12fec6b 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242CorpusManifestRunner.cs@@ -101,6 +101,15 @@ internal static class Step242CorpusManifestRunnervar displayAudit = includeDisplayAudit? RunDisplayAudit(body): DisplayAuditResult.NotRun;+ // Orientation evidence has its own typed import report and CLI+ // summary. Keep this legacy blocker snapshot focused on parser,+ // topology, binding and export regressions so newly visible+ // non-fatal source disagreements do not masquerade as import+ // failures or rewrite the historical canonical corpus hashes.+ var legacyImportDiagnostics = import.Diagnostics+ .Where(diagnostic => diagnostic.Source is null+ || !diagnostic.Source.StartsWith("Importer.StepOrientation.", StringComparison.Ordinal))+ .ToArray();return new Step242CorpusReportEntry(entry.Id,entry.Path,@@ -108,8 +117,8 @@ internal static class Step242CorpusManifestRunnersizeBytes,Status: "success",FirstFailureLayer: string.Empty,- FirstDiagnostic: FirstDiagnostic(import.Diagnostics),- DiagnosticCount: import.Diagnostics.Count,+ FirstDiagnostic: FirstDiagnostic(legacyImportDiagnostics),+ DiagnosticCount: legacyImportDiagnostics.Length,ExceptionEscaped: false,DisplayStatus: displayAudit.Status,DisplayFirstFailureLayer: displayAudit.FirstFailureLayer,diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242DerivedFaceOrientationTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242DerivedFaceOrientationTests.csnew file mode 100644index 00000000..99a7b84c--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242DerivedFaceOrientationTests.cs@@ -0,0 +1,118 @@+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Boolean;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242DerivedFaceOrientationTests+{+ [Fact]+ public void ClosedBox_OneHostileSameSenseFlag_DerivesIdenticalCanonicalBodyAndReportsMismatch()+ {+ var trusted = Step242Importer.ImportBody(Step242FixtureCorpus.CanonicalBoxGolden);+ var hostileText = FlipAdvancedFaceSameSense(Step242FixtureCorpus.CanonicalBoxGolden, all: false);+ var hostile = Step242Importer.ImportBody(hostileText);++ Assert.True(trusted.IsSuccess);+ Assert.True(hostile.IsSuccess);+ Assert.Equal(CanonicalOrientations(trusted.Value), CanonicalOrientations(hostile.Value));+ Assert.Equal(+ BrepMassProperties.Evaluate(trusted.Value).SignedVolume,+ BrepMassProperties.Evaluate(hostile.Value).SignedVolume,+ precision: 10);+ Assert.Equal(1, hostile.Value.FaceOrientationReport!.SourceMismatchCount);+ Assert.Contains(hostile.Diagnostics, diagnostic => diagnostic.Source == "Importer.StepOrientation.SourceOrientationMismatch");+ }++ [Fact]+ public void ClosedBox_AllHostileSameSenseFlags_DerivesIdenticalCanonicalBody()+ {+ var trusted = Step242Importer.ImportBody(Step242FixtureCorpus.CanonicalBoxGolden);+ var hostile = Step242Importer.ImportBody(FlipAdvancedFaceSameSense(Step242FixtureCorpus.CanonicalBoxGolden, all: true));++ Assert.True(trusted.IsSuccess);+ Assert.True(hostile.IsSuccess);+ Assert.Equal(CanonicalOrientations(trusted.Value), CanonicalOrientations(hostile.Value));+ Assert.Equal(hostile.Value.Topology.Faces.Count(), hostile.Value.FaceOrientationReport!.SourceMismatchCount);+ Assert.All(hostile.Value.FaceOrientationReport.Shells, shell =>+ Assert.Equal(FaceOrientationQualification.DerivedQualified, shell.Qualification));+ }++ [Fact]+ public void OpenShell_ResolvesLocalOrientationButDoesNotClaimGlobalOutwardness()+ {+ var import = Step242Importer.ImportBody(Step242FixtureCorpus.PlanarFaceWithRectangularHole);++ Assert.True(import.IsSuccess);+ var shell = Assert.Single(import.Value.FaceOrientationReport!.Shells);+ Assert.False(shell.IsClosedManifold);+ Assert.Equal(FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown, shell.Qualification);+ Assert.Contains(import.Diagnostics, diagnostic => diagnostic.Source == "Importer.StepOrientation.GlobalOrientationUnknown");+ }++ [Fact]+ public void NonManifoldClosedShell_IsRejectedRatherThanGuessed()+ {+ var duplicatedFace = Regex.Replace(+ Step242FixtureCorpus.CanonicalBoxGolden,+ @"(CLOSED_SHELL\([^;]*\()(#[0-9]+)((?:,#[0-9]+)*)(\)\s*\);)",+ match => $"{match.Groups[1].Value}{match.Groups[2].Value}{match.Groups[3].Value},{match.Groups[2].Value}{match.Groups[4].Value}",+ RegexOptions.CultureInvariant,+ TimeSpan.FromSeconds(1));++ var import = Step242Importer.ImportBody(duplicatedFace);++ Assert.False(import.IsSuccess);+ Assert.Contains(import.Diagnostics, diagnostic => diagnostic.Source == "Importer.StepOrientation.NonManifoldOrientation");+ }++ [Fact]+ public void BrepWithVoid_ProjectsOuterPositiveAndInnerNegativeShellOrientation()+ {+ var outer = BrepPrimitives.CreateBox(20d, 18d, 16d);+ var inner = BrepPrimitives.CreateSphere(3d);+ Assert.True(outer.IsSuccess);+ Assert.True(inner.IsSuccess);+ var cavity = BrepBoolean.Subtract(outer.Value, inner.Value);+ Assert.True(cavity.IsSuccess);+ var export = Step242Exporter.ExportBody(cavity.Value);+ Assert.True(export.IsSuccess);++ var import = Step242Importer.ImportBody(export.Value);++ Assert.True(import.IsSuccess);+ var report = Assert.IsType<FaceOrientationReport>(import.Value.FaceOrientationReport);+ Assert.Equal(2, report.Shells.Count);+ Assert.All(report.Shells, shell => Assert.Equal(FaceOrientationQualification.DerivedQualified, shell.Qualification));+ Assert.True(report.Shells.Single(shell => !shell.IsInnerVoid).SignedVolumeAfterGlobalProjection > 0d);+ var innerShell = report.Shells.Single(shell => shell.IsInnerVoid);+ Assert.NotEqual(0d, innerShell.SignedVolumeBeforeGlobalProjection);+ Assert.True(innerShell.SignedVolumeAfterGlobalProjection < 0d);+ var innerFaces = import.Value.Topology.GetShell(innerShell.ShellId).FaceIds.ToHashSet();+ Assert.All(report.Faces.Where(face => innerFaces.Contains(face.FaceId)), face =>+ Assert.False(face.Orientation.IsAlignedWithSurface));+ }++ private static IReadOnlyList<bool> CanonicalOrientations(BrepBody body)+ => body.Topology.Faces.OrderBy(face => face.Id.Value)+ .Select(face => body.Bindings.GetFaceBinding(face.Id).Orientation.IsAlignedWithSurface)+ .ToArray();++ private static string FlipAdvancedFaceSameSense(string step, bool all)+ {+ var count = 0;+ return Regex.Replace(+ step,+ @"(?m)(ADVANCED_FACE\([^;]*,)(\.T\.|\.F\.)(\)\s*;)",+ match =>+ {+ if (!all && count++ > 0) return match.Value;+ var flipped = match.Groups[2].Value == ".T." ? ".F." : ".T.";+ return $"{match.Groups[1].Value}{flipped}{match.Groups[3].Value}";+ },+ RegexOptions.CultureInvariant,+ TimeSpan.FromSeconds(1));+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.csindex b502b03f..a2f0c7e9 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc06SameSenseRegressionTests.cs@@ -9,7 +9,7 @@ namespace Aetheris.Kernel.Core.Tests.Step242;public sealed class Step242Ftc06SameSenseRegressionTests{[Fact]- public void ExportBody_ImportedCylindricalFaceWithFalseSameSense_PreservesAdvancedFaceSense()+ public void ImportBody_OpenCylindricalFace_DemotesSourceSameSenseToEvidence(){const string cylinderFace = @"ISO-10303-21;HEADER;@@ -55,7 +55,10 @@ END-ISO-10303-21;";var curvedFace = Assert.Single(import.Value.Topology.Faces);Assert.True(import.Value.Bindings.TryGetFaceBinding(curvedFace.Id, out var binding));- Assert.False(binding.SameSense);+ Assert.False(binding.Orientation.IsAlignedWithSurface);+ var orientation = Assert.Single(import.Value.FaceOrientationReport!.Faces);+ Assert.False(orientation.SourceEvidence.StepSameSense);+ Assert.Equal(FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown, orientation.Qualification);var export = Step242Exporter.ExportBody(import.Value);Assert.True(export.IsSuccess);@@ -98,7 +101,7 @@ END-ISO-10303-21;";}[Fact]- public void Step242Ftc06ProblemFace_AdvancedFaceSameSense_Regression()+ public void Step242Ftc06_SourceSameSenseIsCrossCheckedAgainstCanonicalOrientation(){var source = LoadFixture("testdata/step242/nist/FTC/nist_ftc_06_asme1_ap242-e2.stp");var sourceSummary = SummarizeAdvancedFaceSense(source);@@ -111,21 +114,24 @@ END-ISO-10303-21;";var import = Step242Importer.ImportBody(source);Assert.True(import.IsSuccess);- var importedBindingSummary = SummarizeCurvedFaceBindingSense(import.Value);- Assert.Equal(sourceSummary[("CYLINDRICAL_SURFACE", false)], importedBindingSummary[("CYLINDRICAL_SURFACE", false)]);- Assert.Equal(sourceSummary[("TOROIDAL_SURFACE", false)], importedBindingSummary[("TOROIDAL_SURFACE", false)]);- Assert.Equal(sourceSummary[("SPHERICAL_SURFACE", false)], importedBindingSummary[("SPHERICAL_SURFACE", false)]);- Assert.Equal(sourceSummary[("CONICAL_SURFACE", false)], importedBindingSummary[("CONICAL_SURFACE", false)]);+ var report = Assert.IsType<FaceOrientationReport>(import.Value.FaceOrientationReport);+ Assert.All(report.Faces, face => Assert.Equal(FaceOrientationQualification.DerivedQualified, face.Qualification));+ Assert.True(report.SourceMismatchCount > 0);+ Assert.Contains(import.Diagnostics, diagnostic => diagnostic.Source == "Importer.StepOrientation.SourceOrientationMismatch");var export = Step242Exporter.ExportBody(import.Value);Assert.True(export.IsSuccess);var exportSummary = SummarizeAdvancedFaceSense(export.Value);- Assert.Equal(sourceSummary, exportSummary);+ var canonicalCurvedSummary = SummarizeCurvedFaceBindingSense(import.Value);+ Assert.All(canonicalCurvedSummary, pair => Assert.Equal(pair.Value, exportSummary[pair.Key]));+ Assert.Equal(canonicalCurvedSummary.Values.Sum(), exportSummary+ .Where(pair => pair.Key.SurfaceType is "CYLINDRICAL_SURFACE" or "CONICAL_SURFACE" or "SPHERICAL_SURFACE" or "TOROIDAL_SURFACE")+ .Sum(pair => pair.Value));}[Fact]- public void Step242Ftc06_DiagnosticsIdentifyNoKnownInvalidTrimCondition()+ public void Step242Ftc06_RoundTripWritesCanonicalRatherThanSourceOrientation(){var source = LoadFixture("testdata/step242/nist/FTC/nist_ftc_06_asme1_ap242-e2.stp");var import = Step242Importer.ImportBody(source);@@ -134,8 +140,10 @@ END-ISO-10303-21;";var export = Step242Exporter.ExportBody(import.Value);Assert.True(export.IsSuccess);- var mismatches = FindCurvedAdvancedFaceSameSenseLosses(source, export.Value);- Assert.Empty(mismatches);+ var roundTrip = Step242Importer.ImportBody(export.Value);+ Assert.True(roundTrip.IsSuccess);+ Assert.Equal(import.Value.Topology.Faces.Count(), roundTrip.Value.Topology.Faces.Count());+ Assert.Equal(import.Value.FaceOrientationReport!.Faces.Select(face => face.Orientation), roundTrip.Value.FaceOrientationReport!.Faces.Select(face => face.Orientation));}private static Dictionary<(string SurfaceType, bool SameSense), int> SummarizeAdvancedFaceSense(string stepText)@@ -173,7 +181,7 @@ END-ISO-10303-21;";continue;}- var key = (surfaceType, binding.SameSense);+ var key = (surfaceType, binding.Orientation.IsAlignedWithSurface);summary[key] = summary.TryGetValue(key, out var count) ? count + 1 : 1;}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.csindex 6f8eb226..416a840e 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242HoleSemanticsTests.cs@@ -99,7 +99,8 @@ public sealed class Step242HoleSemanticsTestsvar import = Step242Importer.ImportBody(Step242FixtureCorpus.CylindricalFaceWithTwoLoops);Assert.True(import.IsSuccess);- Assert.Empty(import.Diagnostics);+ Assert.Contains(import.Diagnostics, diagnostic =>+ diagnostic.Source == "Importer.StepOrientation.GlobalOrientationUnknown");var body = import.Value;var validation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242OrientationSemanticsTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242OrientationSemanticsTests.csindex 50e449b1..0fc1b9da 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242OrientationSemanticsTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242OrientationSemanticsTests.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Step242;namespace Aetheris.Kernel.Core.Tests.Step242;@@ -34,12 +35,11 @@ public sealed class Step242OrientationSemanticsTests}/// <summary>- /// ADVANCED_FACE.same_sense is carried by the face binding, never folded into the stored support. Folding it in- /// for planes alone made them the one kind a consumer had to special-case, and inverted their normal on every- /// export/import cycle.+ /// ADVANCED_FACE.same_sense is retained as source evidence and never folded into the stored support or exposed as+ /// canonical orientation. An open one-face shell has deterministic local orientation but no global outwardness./// </summary>[Fact]- public void ImportBody_AdvancedFaceSameSenseFalse_KeepsTheStatedPlane_AndRecordsTheSenseOnTheBinding()+ public void ImportBody_AdvancedFaceSameSenseFalse_KeepsTheStatedPlane_AndRecordsSourceEvidenceSeparately(){var forward = Step242Importer.ImportBody(BuildSingleTriangleStep(edgeCurveSameSense: true, faceBoundOrientation: true, advancedFaceSameSense: true));var reversed = Step242Importer.ImportBody(BuildSingleTriangleStep(edgeCurveSameSense: true, faceBoundOrientation: true, advancedFaceSameSense: false));@@ -55,8 +55,12 @@ public sealed class Step242OrientationSemanticsTestsAssert.Equal(1d, forwardSurface!.Plane!.Value.Normal.Z);Assert.Equal(1d, reversedSurface!.Plane!.Value.Normal.Z);- Assert.True(forward.Value.Bindings.GetFaceBinding(forwardFace.Id).SameSense);- Assert.False(reversed.Value.Bindings.GetFaceBinding(reversedFace.Id).SameSense);+ Assert.True(forward.Value.Bindings.GetFaceBinding(forwardFace.Id).Orientation.IsAlignedWithSurface);+ Assert.True(reversed.Value.Bindings.GetFaceBinding(reversedFace.Id).Orientation.IsAlignedWithSurface);+ var evidence = Assert.Single(reversed.Value.FaceOrientationReport!.Faces);+ Assert.False(evidence.SourceEvidence.StepSameSense);+ Assert.Equal(FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown, evidence.Qualification);+ Assert.Equal(SourceFaceOrientationComparison.Disagrees, evidence.SourceComparison);}[Fact]@@ -65,7 +69,7 @@ public sealed class Step242OrientationSemanticsTestsvar result = Step242Importer.ImportBody(BuildSingleEdgeStep(edgeCurveSameSense: false, orientedEdgeOrientation: true, lineDirectionX: -1d));Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => $"{d.Source}:{d.Message}")));- Assert.Empty(result.Diagnostics);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Source == "Importer.StepOrientation.GlobalOrientationUnknown");}[Fact]diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242PeriodicBoundaryOrientationTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242PeriodicBoundaryOrientationTests.csnew file mode 100644index 00000000..3bd0831d--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242PeriodicBoundaryOrientationTests.cs@@ -0,0 +1,105 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242PeriodicBoundaryOrientationTests+{+ public static TheoryData<string> FormerRedCases => new()+ {+ "STC/nist_stc_10_asme1_ap242-e2.stp",+ "FTC/nist_ftc_08_asme1_ap242-e2.stp",+ "FTC/nist_ftc_11_asme1_ap242-e2.stp",+ "CTC/nist_ctc_02_asme1_ap242-e2.stp",+ };++ [Theory]+ [MemberData(nameof(FormerRedCases))]+ public void PeriodicBoundaryOrientation_SurvivesExportImport(string relativePath)+ {+ var imported = Step242Importer.ImportBody(ReadNist(relativePath));+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(diagnostic => diagnostic.Message)));++ var exported = Step242Exporter.ExportBody(imported.Value);+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var reimported = Step242Importer.ImportBody(exported.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(diagnostic => diagnostic.Message)));++ var before = imported.Value.FaceOrientationReport!.Faces.OrderBy(face => face.FaceId.Value)+ .Select(face => (face.FaceId, face.Orientation, face.Qualification)).ToArray();+ var after = reimported.Value.FaceOrientationReport!.Faces.OrderBy(face => face.FaceId.Value)+ .Select(face => (face.FaceId, face.Orientation, face.Qualification)).ToArray();+ Assert.Equal(before, after);+ }++ [Fact]+ public void ImportedBoundaryRoles_SelectExplicitJudgmentCandidate()+ {+ var imported = Step242Importer.ImportBody(ReadNist("FTC/nist_ftc_11_asme1_ap242-e2.stp"));+ Assert.True(imported.IsSuccess);++ foreach (var face in imported.Value.Topology.Faces.Where(face => face.LoopIds.Count > 0))+ {+ var roles = face.LoopIds.Select(loopId => imported.Value.Bindings.GetFaceBoundaryRoleBinding(loopId)).ToArray();+ Assert.Equal(face.LoopIds.Count, roles.Length);+ Assert.Single(roles, role => role.Role == FaceBoundaryRole.Outer);+ var decision = StepFaceBoundaryExportPolicy.Decide(imported.Value, face);+ Assert.NotNull(decision);+ Assert.Equal(StepFaceBoundaryExportPolicy.ExplicitRolesCandidate, decision.Candidate);+ }+ }++ [Fact]+ public void BoundaryPolicy_UsesAuthoredOrderOnlyWhenRoleEvidenceIsAbsent()+ {+ var face = new Face(new FaceId(1), [new LoopId(7), new LoopId(3)]);+ var body = new BrepBody(new TopologyModel(), new BrepGeometryStore(), new BrepBindingModel());++ var decision = StepFaceBoundaryExportPolicy.Decide(body, face);++ Assert.NotNull(decision);+ Assert.Equal(StepFaceBoundaryExportPolicy.AuthoredOrderCandidate, decision.Candidate);+ Assert.Equal(+ [(new LoopId(7), FaceBoundaryRole.Outer), (new LoopId(3), FaceBoundaryRole.Inner)],+ decision.Boundaries);+ }++ [Fact]+ public void BoundaryPolicy_RejectsPartialRoleEvidenceInsteadOfGuessing()+ {+ var faceId = new FaceId(1);+ var firstLoop = new LoopId(7);+ var face = new Face(faceId, [firstLoop, new LoopId(3)]);+ var bindings = new BrepBindingModel();+ bindings.AddFaceBoundaryRoleBinding(new FaceBoundaryRoleBinding(faceId, firstLoop, FaceBoundaryRole.Outer, 101));+ var body = new BrepBody(new TopologyModel(), new BrepGeometryStore(), bindings);++ Assert.Null(StepFaceBoundaryExportPolicy.Decide(body, face));+ }++ [Fact]+ public void PeriodicEquality_IsStableAcrossWholePeriodShifts()+ {+ Assert.True(SurfacePeriodicity.EquivalentModuloPeriod(0.125d, 0.125d + double.Tau, double.Tau, 1e-10d));+ Assert.True(SurfacePeriodicity.EquivalentModuloPeriod(-double.Pi, double.Pi, double.Tau, 1e-10d));+ Assert.False(SurfacePeriodicity.EquivalentModuloPeriod(0.125d, 0.25d, double.Tau, 1e-10d));+ }++ [Fact]+ public void Stc06_RemainsExplicitlyAmbiguous()+ {+ var imported = Step242Importer.ImportBody(ReadNist("STC/nist_stc_06_asme1_ap242-e3.stp"));+ Assert.True(imported.IsSuccess);+ Assert.Contains(imported.Value.FaceOrientationReport!.Shells,+ shell => shell.Qualification == FaceOrientationQualification.Ambiguous);+ }++ private static string ReadNist(string relativePath) => File.ReadAllText(Path.Combine(+ Step242CorpusManifestRunner.RepoRoot(),+ "testdata",+ "step242",+ "nist",+ relativePath.Replace('/', Path.DirectorySeparatorChar)));+}diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.csindex 5f20834b..1fcaa479 100644--- a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs@@ -1175,8 +1175,8 @@ public static class BrepBooleanBoxCylinderHoleBuilder// The analytic cone/cylinder normals point radially away from the hole axis.// For an internal void the solid's outward normal points toward the axis, so// these faces must reverse the support-surface sense in STEP.- bindings.AddFaceBinding(new FaceGeometryBinding(countersinkConeFace, new SurfaceGeometryId(7), SameSense: false));- bindings.AddFaceBinding(new FaceGeometryBinding(continuationCylinderFace, new SurfaceGeometryId(8), SameSense: false));+ bindings.AddFaceBinding(new FaceGeometryBinding(countersinkConeFace, new SurfaceGeometryId(7), IsAlignedWithSurface: false));+ bindings.AddFaceBinding(new FaceGeometryBinding(continuationCylinderFace, new SurfaceGeometryId(8), IsAlignedWithSurface: false));if (deepBottomFace is FaceId deepBottomBinding){bindings.AddFaceBinding(new FaceGeometryBinding(deepBottomBinding, new SurfaceGeometryId(9)));diff --git a/Aetheris.Kernel.Core/Brep/BrepBindingValidator.cs b/Aetheris.Kernel.Core/Brep/BrepBindingValidator.csindex 586a5e2d..cbc015db 100644--- a/Aetheris.Kernel.Core/Brep/BrepBindingValidator.cs+++ b/Aetheris.Kernel.Core/Brep/BrepBindingValidator.cs@@ -53,6 +53,24 @@ public static class BrepBindingValidator}}+ foreach (var boundaryRole in body.Bindings.FaceBoundaryRoleBindings)+ {+ if (!body.Topology.TryGetFace(boundaryRole.FaceId, out var face) || face is null)+ {+ diagnostics.Add(Error($"Face-boundary role references missing face {boundaryRole.FaceId.Value}."));+ continue;+ }++ if (!body.Topology.TryGetLoop(boundaryRole.LoopId, out _))+ {+ diagnostics.Add(Error($"Face-boundary role references missing loop {boundaryRole.LoopId.Value}."));+ }+ else if (!face.LoopIds.Contains(boundaryRole.LoopId))+ {+ diagnostics.Add(Error($"Face-boundary role assigns loop {boundaryRole.LoopId.Value} to face {boundaryRole.FaceId.Value}, but that face does not own the loop."));+ }+ }+if (requireAllEdgeAndFaceBindings){foreach (var edge in body.Topology.Edges)diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.csindex 2a2817e1..ca963a4c 100644--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs@@ -10,11 +10,50 @@ public readonly record struct EdgeGeometryBinding(ParameterInterval? TrimInterval = null,bool OrientedEdgeSense = true);-public readonly record struct FaceGeometryBinding(- FaceId FaceId,- SurfaceGeometryId SurfaceGeometryId,- bool SameSense = true,- int? SourceStepEntityId = null);+/// <summary>+/// Canonical face orientation after topology/material-side resolution. This is+/// intentionally not a STEP <c>same_sense</c> flag: interchange evidence is+/// retained separately on <see cref="BrepBody.FaceOrientationReport"/>.+/// </summary>+public readonly record struct ResolvedFaceOrientation(bool IsAlignedWithSurface)+{+ public static ResolvedFaceOrientation Aligned { get; } = new(true);+ public static ResolvedFaceOrientation Opposed { get; } = new(false);++ public ResolvedFaceOrientation Reversed() => new(!IsAlignedWithSurface);+}++/// <summary>A topology-to-surface binding whose face orientation is already resolved.</summary>+public readonly record struct FaceGeometryBinding+{+ // Keep the historical bool constructor shape for authored kernel geometry,+ // while exposing only the resolved typed value to consumers.+ public FaceGeometryBinding(+ FaceId FaceId,+ SurfaceGeometryId SurfaceGeometryId,+ bool IsAlignedWithSurface = true,+ int? SourceStepEntityId = null)+ : this(FaceId, SurfaceGeometryId, new ResolvedFaceOrientation(IsAlignedWithSurface), SourceStepEntityId)+ {+ }++ public FaceGeometryBinding(+ FaceId FaceId,+ SurfaceGeometryId SurfaceGeometryId,+ ResolvedFaceOrientation Orientation,+ int? SourceStepEntityId = null)+ {+ this.FaceId = FaceId;+ this.SurfaceGeometryId = SurfaceGeometryId;+ this.Orientation = Orientation;+ this.SourceStepEntityId = SourceStepEntityId;+ }++ public FaceId FaceId { get; init; }+ public SurfaceGeometryId SurfaceGeometryId { get; init; }+ public ResolvedFaceOrientation Orientation { get; init; }+ public int? SourceStepEntityId { get; init; }+}public readonly record struct SurfaceParameterPoint(double U, double V);@@ -99,6 +138,18 @@ public readonly record struct CoedgePcurveBinding(PcurveGeometry Pcurve,bool SameSense = true);+public enum FaceBoundaryRole { Outer, Inner }++/// <summary>+/// Semantic role of one loop within one face. The role is use-context evidence:+/// it must not be reconstructed from LoopId ordering during STEP export.+/// </summary>+public readonly record struct FaceBoundaryRoleBinding(+ FaceId FaceId,+ LoopId LoopId,+ FaceBoundaryRole Role,+ int? SourceStepEntityId = null);+/// <summary>/// Explicit topology-to-geometry binding container./// </summary>@@ -107,24 +158,29 @@ public sealed class BrepBindingModelprivate readonly Dictionary<EdgeId, EdgeGeometryBinding> _edgeBindings = [];private readonly Dictionary<FaceId, FaceGeometryBinding> _faceBindings = [];private readonly Dictionary<CoedgeId, CoedgePcurveBinding> _pcurveBindings = [];+ private readonly Dictionary<LoopId, FaceBoundaryRoleBinding> _faceBoundaryRoleBindings = [];public IEnumerable<EdgeGeometryBinding> EdgeBindings => _edgeBindings.Values;public IEnumerable<FaceGeometryBinding> FaceBindings => _faceBindings.Values;public IEnumerable<CoedgePcurveBinding> PcurveBindings => _pcurveBindings.Values;+ public IEnumerable<FaceBoundaryRoleBinding> FaceBoundaryRoleBindings => _faceBoundaryRoleBindings.Values;public void AddEdgeBinding(EdgeGeometryBinding binding) => _edgeBindings.Add(binding.EdgeId, binding);public void AddFaceBinding(FaceGeometryBinding binding) => _faceBindings.Add(binding.FaceId, binding);public void AddPcurveBinding(CoedgePcurveBinding binding) => _pcurveBindings.Add(binding.CoedgeId, binding);+ public void AddFaceBoundaryRoleBinding(FaceBoundaryRoleBinding binding) => _faceBoundaryRoleBindings.Add(binding.LoopId, binding);public bool TryGetEdgeBinding(EdgeId edgeId, out EdgeGeometryBinding binding) => _edgeBindings.TryGetValue(edgeId, out binding);public bool TryGetFaceBinding(FaceId faceId, out FaceGeometryBinding binding) => _faceBindings.TryGetValue(faceId, out binding);public bool TryGetPcurveBinding(CoedgeId coedgeId, out CoedgePcurveBinding binding) => _pcurveBindings.TryGetValue(coedgeId, out binding);+ public bool TryGetFaceBoundaryRoleBinding(LoopId loopId, out FaceBoundaryRoleBinding binding) => _faceBoundaryRoleBindings.TryGetValue(loopId, out binding);public EdgeGeometryBinding GetEdgeBinding(EdgeId edgeId) => _edgeBindings[edgeId];public FaceGeometryBinding GetFaceBinding(FaceId faceId) => _faceBindings[faceId];public CoedgePcurveBinding GetPcurveBinding(CoedgeId coedgeId) => _pcurveBindings[coedgeId];+ public FaceBoundaryRoleBinding GetFaceBoundaryRoleBinding(LoopId loopId) => _faceBoundaryRoleBindings[loopId];}diff --git a/Aetheris.Kernel.Core/Brep/BrepBody.cs b/Aetheris.Kernel.Core/Brep/BrepBody.csindex be9669a9..f68d85ea 100644--- a/Aetheris.Kernel.Core/Brep/BrepBody.cs+++ b/Aetheris.Kernel.Core/Brep/BrepBody.cs@@ -23,7 +23,8 @@ public sealed class BrepBodyBrepBindingModel bindings,IReadOnlyDictionary<VertexId, Point3D>? vertexPoints,SafeBooleanComposition? safeBooleanComposition = null,- BrepBodyShellRepresentation? shellRepresentation = null)+ BrepBodyShellRepresentation? shellRepresentation = null,+ FaceOrientationReport? faceOrientationReport = null){Topology = topology;Geometry = geometry;@@ -31,6 +32,7 @@ public sealed class BrepBody_vertexPoints = vertexPoints ?? new Dictionary<VertexId, Point3D>();SafeBooleanComposition = safeBooleanComposition;ShellRepresentation = shellRepresentation ?? TryCreateLegacySingleShellRepresentation(topology);+ FaceOrientationReport = faceOrientationReport;}public TopologyModel Topology { get; }@@ -43,6 +45,12 @@ public sealed class BrepBodypublic BrepBodyShellRepresentation? ShellRepresentation { get; }+ /// <summary>+ /// Import-boundary provenance and qualification. Null means the body was+ /// authored canonically rather than resolved from interchange evidence.+ /// </summary>+ public FaceOrientationReport? FaceOrientationReport { get; }+public bool TryGetVertexPoint(VertexId vertexId, out Point3D point) => _vertexPoints.TryGetValue(vertexId, out point);public bool TryGetEdgeCurveGeometry(EdgeId edgeId, out CurveGeometry? curve)diff --git a/Aetheris.Kernel.Core/Brep/FaceOrientationReport.cs b/Aetheris.Kernel.Core/Brep/FaceOrientationReport.csnew file mode 100644index 00000000..89f3a4a8--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/FaceOrientationReport.cs@@ -0,0 +1,59 @@+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep;++public enum FaceOrientationQualification+{+ DerivedQualified,+ DerivedLocallyConsistentGlobalUnknown,+ SourceOnly,+ Ambiguous,+ Invalid,+}++public enum SourceFaceOrientationComparison+{+ Agrees,+ Disagrees,+ SourceMissing,+ NotComparable,+}++/// <summary>STEP-authored orientation retained as evidence, never as an instruction.</summary>+public sealed record SourceFaceOrientationEvidence(+ bool? StepSameSense,+ int? SourceEntityId,+ int? SourceSurfaceId);++/// <summary>The resolved face patch visible after the import boundary.</summary>+public sealed record OrientedFacePatch(+ FaceId FaceId,+ ShellId ShellId,+ ResolvedFaceOrientation Orientation,+ FaceOrientationQualification Qualification,+ SourceFaceOrientationEvidence SourceEvidence,+ SourceFaceOrientationComparison SourceComparison,+ string EvidenceSummary);++public sealed record ShellOrientationResolution(+ ShellId ShellId,+ FaceOrientationQualification Qualification,+ bool IsClosedManifold,+ bool IsInnerVoid,+ double? SignedVolumeBeforeGlobalProjection,+ double? SignedVolumeAfterGlobalProjection,+ bool GlobalFlipApplied,+ string EvidenceSummary);++public sealed record FaceOrientationReport(+ IReadOnlyList<OrientedFacePatch> Faces,+ IReadOnlyList<ShellOrientationResolution> Shells)+{+ public int DerivedFaceCount => Faces.Count(face => face.Qualification is+ FaceOrientationQualification.DerivedQualified or+ FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown);+ public int SourceAgreementCount => Faces.Count(face => face.SourceComparison == SourceFaceOrientationComparison.Agrees);+ public int SourceMismatchCount => Faces.Count(face => face.SourceComparison == SourceFaceOrientationComparison.Disagrees);+ public int AmbiguousComponentCount => Shells.Count(shell => shell.Qualification == FaceOrientationQualification.Ambiguous);+ public int GlobalFlipCount => Shells.Count(shell => shell.GlobalFlipApplied);+}diff --git a/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.cs b/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.csindex 01c4f742..409669a8 100644--- a/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.cs@@ -204,7 +204,7 @@ public static class CombinedTopBoundaryChamferThroughHoleBuilder}foreach(var wall in holeFaces){- var sid=new SurfaceGeometryId(surface++);geometry.AddSurface(sid,SurfaceGeometry.FromCylinder(new CylinderSurface(new(wall.Hole.Hole.CenterX,wall.Hole.Hole.CenterY,wall.ZMin),zAxis,wall.Radius,xAxis)));bindings.AddFaceBinding(new(wall.Face,sid,SameSense:false));+ var sid=new SurfaceGeometryId(surface++);geometry.AddSurface(sid,SurfaceGeometry.FromCylinder(new CylinderSurface(new(wall.Hole.Hole.CenterX,wall.Hole.Hole.CenterY,wall.ZMin),zAxis,wall.Radius,xAxis)));bindings.AddFaceBinding(new(wall.Face,sid,IsAlignedWithSurface:false));}foreach(var shoulderBinding in shoulderFaces)BindPlane(shoulderBinding.Face,new(shoulderBinding.Hole.Hole.CenterX,shoulderBinding.Hole.Hole.CenterY,plan.ZMax-shoulderBinding.Hole.Hole.CounterboreDepth!.Value),new Vector3D(1,0,0),new Vector3D(0,1,0));diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.csindex c5cc1130..c420fdbe 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs@@ -260,7 +260,7 @@ public static class BrepDisplayTessellator// a body's display mesh consistently outward-oriented instead of per-face arbitrary.var patch = TessellateFaceSupport(body, faceId, surface, options, executionBudget);return patch.IsSuccess- ? KernelResult<DisplayFaceMeshPatch>.Success(DisplayMeshOrientation.Orient(body, patch.Value), patch.Diagnostics)+ ? KernelResult<DisplayFaceMeshPatch>.Success(DisplayMeshOrientation.ProjectCanonicalOrientation(body, patch.Value), patch.Diagnostics): patch;}diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.csindex 3b0736d5..ed2998d6 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayMeshOrientation.cs@@ -3,14 +3,14 @@ namespace Aetheris.Kernel.Core.Brep.Tessellation;/// <summary>Projects the exact face sense into render normals and front-face triangle winding.</summary>public static class DisplayMeshOrientation{- public static DisplayFaceMeshPatch Orient(BrepBody body, DisplayFaceMeshPatch patch)+ public static DisplayFaceMeshPatch ProjectCanonicalOrientation(BrepBody body, DisplayFaceMeshPatch patch){if (patch.Normals.Count != patch.Positions.Count || patch.TriangleIndices.Count % 3 != 0|| patch.TriangleIndices.Any(i => i < 0 || i >= patch.Positions.Count))throw new InvalidOperationException($"display-mesh-invalid-patch:{patch.FaceId}");if (!body.Bindings.TryGetFaceBinding(patch.FaceId, out var binding))throw new InvalidOperationException($"display-mesh-missing-face-binding:{patch.FaceId}");- var normals = patch.Normals.Select(normal => binding.SameSense ? normal : -normal).ToArray();+ var normals = patch.Normals.Select(normal => binding.Orientation.IsAlignedWithSurface ? normal : -normal).ToArray();var indices = patch.TriangleIndices.ToArray();for (var i = 0; i < indices.Length; i += 3){diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex 9d3dc283..61646cac 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -123,7 +123,7 @@ public sealed record SurfacePatch(SurfaceMeshSupport Support,IReadOnlyList<LoopId> TrimLoops,IReadOnlyList<SurfaceMeshCell> Cells,- bool SameSense,+ bool IsAlignedWithSupport,string? SemanticOwner = null,bool HasPeriodicUSeam = false,bool HasPeriodicVSeam = false,@@ -424,26 +424,26 @@ public static class SurfaceMeshIrTessellatorswitch (surface.Kind){case SurfaceGeometryKind.Plane:- var planePatch = TryBuildPlanePatch(body, face.Id, faceBinding.SameSense, surface.Plane!.Value, byEdge, vertices, ref nextVertexId);+ var planePatch = TryBuildPlanePatch(body, face.Id, faceBinding.Orientation.IsAlignedWithSurface, surface.Plane!.Value, byEdge, vertices, ref nextVertexId);if (planePatch is null) { failure = $"SurfaceMeshIR does not support trim topology on planar face {face.Id.Value}."; return false; }patches.Add(planePatch);break;case SurfaceGeometryKind.Cylinder:- var cylinderPatch = TryBuildCylinderPatch(body, face.Id, faceBinding.SameSense, surface.Cylinder!.Value, byEdge, policy, vertices, ref nextVertexId);+ var cylinderPatch = TryBuildCylinderPatch(body, face.Id, faceBinding.Orientation.IsAlignedWithSurface, surface.Cylinder!.Value, byEdge, policy, vertices, ref nextVertexId);if (cylinderPatch is null) { failure = $"SurfaceMeshIR does not support trim topology on cylindrical face {face.Id.Value}."; return false; }patches.Add(cylinderPatch);break;case SurfaceGeometryKind.Cone:- var conePatch = TryBuildConePatch(body, face.Id, faceBinding.SameSense, surface.Cone!.Value, byEdge, policy, vertices, ref nextVertexId);+ var conePatch = TryBuildConePatch(body, face.Id, faceBinding.Orientation.IsAlignedWithSurface, surface.Cone!.Value, byEdge, policy, vertices, ref nextVertexId);if (conePatch is null) { failure = $"SurfaceMeshIR does not support trim topology on conical face {face.Id.Value}."; return false; }patches.Add(conePatch);break;case SurfaceGeometryKind.Sphere:- if (!TryBuildSphereCharts(body, face.Id, faceBinding.SameSense, surface.Sphere!.Value, vertices, ref nextVertexId, out var spherePatches)) { failure = $"SurfaceMeshIR does not support chart/trim topology on spherical face {face.Id.Value}."; return false; }+ if (!TryBuildSphereCharts(body, face.Id, faceBinding.Orientation.IsAlignedWithSurface, surface.Sphere!.Value, vertices, ref nextVertexId, out var spherePatches)) { failure = $"SurfaceMeshIR does not support chart/trim topology on spherical face {face.Id.Value}."; return false; }patches.AddRange(spherePatches);break;case SurfaceGeometryKind.Torus:- var torusPatch = TryBuildTorusPatch(body, face.Id, faceBinding.SameSense, surface.Torus!.Value, byEdge, policy, vertices, ref nextVertexId);+ var torusPatch = TryBuildTorusPatch(body, face.Id, faceBinding.Orientation.IsAlignedWithSurface, surface.Torus!.Value, byEdge, policy, vertices, ref nextVertexId);if (torusPatch is null) { failure = $"SurfaceMeshIR does not support trim topology on toroidal face {face.Id.Value}."; return false; }patches.Add(torusPatch);break;@@ -1810,13 +1810,13 @@ public static class SurfaceMeshIrTessellator{return patch.Support.Kind switch{- SurfaceMeshSupportKind.Plane when patch.Support.Plane is { } plane => _ => patch.SameSense ? plane.Normal.ToVector() : -plane.Normal.ToVector(),+ SurfaceMeshSupportKind.Plane when patch.Support.Plane is { } plane => _ => patch.IsAlignedWithSupport ? plane.Normal.ToVector() : -plane.Normal.ToVector(),SurfaceMeshSupportKind.Cylinder when patch.Support.Cylinder is { } cylinder => p =>{var offset = p - cylinder.Origin;var angle = double.Atan2(offset.Dot(cylinder.YAxis.ToVector()), offset.Dot(cylinder.XAxis.ToVector()));var exact = cylinder.Normal(angle).ToVector();- return patch.SameSense ? exact : -exact;+ return patch.IsAlignedWithSupport ? exact : -exact;},SurfaceMeshSupportKind.Cone when patch.Support.Cone is { } cone => p =>{@@ -1828,18 +1828,18 @@ public static class SurfaceMeshIrTessellatorvar yAxis = axis.Cross(xAxis);var angle = radial.Length <= Epsilon ? 0d : double.Atan2(radial.Dot(yAxis), radial.Dot(xAxis));var exact = cone.Normal(angle).ToVector();- return patch.SameSense ? exact : -exact;+ return patch.IsAlignedWithSupport ? exact : -exact;},SurfaceMeshSupportKind.Sphere when patch.Support.Sphere is { } sphere => p =>{var exact = Direction3D.Create(p - sphere.Center).ToVector();- return patch.SameSense ? exact : -exact;+ return patch.IsAlignedWithSupport ? exact : -exact;},SurfaceMeshSupportKind.Torus when patch.Support.Torus is { } torus => p =>{var uv = TryProjectPointToTorusUv(torus, p) ?? throw new InvalidOperationException("Torus mesh vertex is not on its exact support.");var exact = torus.Normal(uv.U, uv.V).ToVector();- return patch.SameSense ? exact : -exact;+ return patch.IsAlignedWithSupport ? exact : -exact;},_ => throw new InvalidOperationException($"Patch {patch.FaceId.Value} has no exact support evaluator."),};diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.csindex 74a7d752..cd20939c 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshObjExporter.cs@@ -112,7 +112,7 @@ public static class SurfaceMeshObjExporterSurfaceMeshSupportKind.BoundedParametricPatch when patch.Support.BoundedPatch is { } bounded && bounded.Evaluate(uv.U, uv.V).TryNormal(out var evaluated) => evaluated,_ => throw new InvalidOperationException($"Patch {patch.FaceId.Value} has no exact normal evaluator."),};- return patch.SameSense ? normal : -normal;+ return patch.IsAlignedWithSupport ? normal : -normal;}private static (double U, double V) PolarUv(Vector3D offset, Vector3D axis, Vector3D xAxis, Vector3D yAxis)diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.csindex 265247d3..8a6b7b09 100644--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs@@ -37,7 +37,7 @@ public sealed record BrepMassPropertiesFaceContribution(double SurfaceArea,int TriangleCount,bool FaceSenseAvailable,- bool FaceSameSense,+ bool FaceAlignedWithSurface,bool TriangleOrientationCoherent);public sealed record BrepMassPropertiesTopologyDiagnostics(@@ -275,7 +275,7 @@ public static class BrepMassPropertiesforeach (var face in faces){var kind = body.TryGetFaceSurfaceGeometry(face.Id, out var surface) ? surface?.Kind : null;- contributions.Add(new(face.Id, kind, 0d, 0d, 0, body.Bindings.TryGetFaceBinding(face.Id, out var binding), binding.SameSense, true));+ contributions.Add(new(face.Id, kind, 0d, 0d, 0, body.Bindings.TryGetFaceBinding(face.Id, out var binding), binding.Orientation.IsAlignedWithSurface, true));}var analyticRoundoffBound = System.Math.Max(1e-8d, System.Math.Abs(total) * 1e-14d);result = new BrepMassPropertiesResult(@@ -775,7 +775,7 @@ public static class BrepMassPropertiesarea += faceArea;moment += faceMoment;body.TryGetFaceSurfaceGeometry(patch.FaceId, out var surface);- contributions.Add(new(patch.FaceId, surface?.Kind, faceVolume, faceArea, patch.TriangleIndices.Count / 3, senseAvailable, binding.SameSense, coherent));+ contributions.Add(new(patch.FaceId, surface?.Kind, faceVolume, faceArea, patch.TriangleIndices.Count / 3, senseAvailable, binding.Orientation.IsAlignedWithSurface, coherent));}return new(volume, area, moment, contributions, null);}diff --git a/Aetheris.Kernel.Core/Geometry/SurfacePeriodicity.cs b/Aetheris.Kernel.Core/Geometry/SurfacePeriodicity.csnew file mode 100644index 00000000..a18b3e6f--- /dev/null+++ b/Aetheris.Kernel.Core/Geometry/SurfacePeriodicity.cs@@ -0,0 +1,34 @@+namespace Aetheris.Kernel.Core.Geometry;++/// <summary>+/// Parameter-space periodicity of a support surface. Null means that the axis+/// is not known to be periodic; periods are expressed in native UV units.+/// </summary>+public readonly record struct SurfacePeriodicity(double? UPeriod, double? VPeriod)+{+ public bool IsPeriodic => UPeriod.HasValue || VPeriod.HasValue;++ public static SurfacePeriodicity Of(SurfaceGeometry surface) => surface.Kind switch+ {+ SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone or SurfaceGeometryKind.Sphere+ => new(double.Tau, null),+ SurfaceGeometryKind.Torus => new(double.Tau, double.Tau),+ SurfaceGeometryKind.BSplineSurfaceWithKnots => new(+ surface.BSplineSurfaceWithKnots!.UClosed+ ? surface.BSplineSurfaceWithKnots.DomainEndU - surface.BSplineSurfaceWithKnots.DomainStartU+ : null,+ surface.BSplineSurfaceWithKnots.VClosed+ ? surface.BSplineSurfaceWithKnots.DomainEndV - surface.BSplineSurfaceWithKnots.DomainStartV+ : null),+ _ => default,+ };++ public static bool EquivalentModuloPeriod(double left, double right, double period, double tolerance)+ {+ if (!double.IsFinite(left) || !double.IsFinite(right) || !double.IsFinite(period) || period <= 0d)+ return false;+ var delta = double.Abs(left - right);+ var remainder = delta % period;+ return remainder <= tolerance || period - remainder <= tolerance;+ }+}diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex 8943fc25..5274d0ae 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -218,8 +218,11 @@ public static class Step242Exporter}var loopBoundIds = new List<string>();- foreach (var loopId in face.LoopIds.OrderBy(id => id.Value))+ var boundaryDecision = StepFaceBoundaryExportPolicy.Decide(body, face);+ if (boundaryDecision is null) return null;+ foreach (var boundary in boundaryDecision.Boundaries){+ var loopId = boundary.LoopId;var loop = model.GetLoop(loopId);var oriented = new List<string>();@@ -254,7 +257,7 @@ public static class Step242Exporter}var edgeLoopId = writer.AddEntity("EDGE_LOOP", "$", Step242TextWriter.List(oriented.ToArray()));- var boundEntity = loopBoundIds.Count == 0 ? "FACE_OUTER_BOUND" : "FACE_BOUND";+ var boundEntity = boundary.Role == FaceBoundaryRole.Outer ? "FACE_OUTER_BOUND" : "FACE_BOUND";var boundId = writer.AddEntity(boundEntity, Step242TextWriter.String(string.Empty), Step242TextWriter.Ref(edgeLoopId), Step242TextWriter.BooleanLogical(true));loopBoundIds.Add(boundId);}@@ -264,7 +267,7 @@ public static class Step242ExporterStep242TextWriter.String(string.Empty),Step242TextWriter.List(loopBoundIds.ToArray()),Step242TextWriter.Ref(surfaceEntityId),- Step242TextWriter.BooleanLogical(faceBinding.SameSense));+ Step242TextWriter.BooleanLogical(faceBinding.Orientation.IsAlignedWithSurface));advancedFaceIds[face.Id] = advancedFaceId;faceIds.Add(advancedFaceId);diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 98294f5b..9f43a1b5 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -217,6 +217,9 @@ public static class Step242Importervar nextSurfaceGeometryId = 1;var faceIds = new List<FaceId>();var faceEntityToFaceId = new Dictionary<int, FaceId>();+ var importedFacePatches = new List<ImportedFacePatch>();+ var supportAlignedBoundary = new Dictionary<FaceId, bool>();+ var supportAlignedLoopBoundary = new Dictionary<LoopId, bool>();foreach (var faceEntityId in faceEntityIds){@@ -279,7 +282,7 @@ public static class Step242Importerreturn KernelResult<BrepBody>.Failure(faceSameSenseResult.Diagnostics);}- var bindSurfaceResult = DecodeSurfaceGeometry(document, surfaceEntity, surfaceName, inlineSurfaceArguments, faceSameSenseResult.Value, nextSurfaceGeometryId, faceEntity.Id);+ var bindSurfaceResult = DecodeSurfaceGeometry(document, surfaceEntity, surfaceName, inlineSurfaceArguments, nextSurfaceGeometryId, faceEntity.Id);if (!bindSurfaceResult.IsSuccess){return KernelResult<BrepBody>.Failure(bindSurfaceResult.Diagnostics);@@ -494,7 +497,7 @@ public static class Step242ImporterhasDisconnectedCoedgeGap = true;}- loopData.Add(new LoopBuildData(loopId, loopCoedges, loopSamples, hasDisconnectedCoedgeGap, isDeclaredOuter));+ loopData.Add(new LoopBuildData(loopId, loopCoedges, loopSamples, hasDisconnectedCoedgeGap, isDeclaredOuter, boundEntity.Id));}var classifyResult = ClassifyAndNormalizeFaceLoops(faceEntity.Id, loopData, bindSurfaceResult.Value.SurfaceGeometry);@@ -535,8 +538,27 @@ public static class Step242Importerbindings.AddFaceBinding(new FaceGeometryBinding(faceId,surfaceGeometryId,- faceSameSenseResult.Value,+ ResolvedFaceOrientation.Aligned,SourceStepEntityId: faceEntity.Id));+ var hasDeclaredOuter = classifyResult.Value.Any(loop => loop.IsDeclaredOuter);+ for (var loopIndex = 0; loopIndex < classifyResult.Value.Count; loopIndex++)+ {+ var loop = classifyResult.Value[loopIndex];+ var role = hasDeclaredOuter+ ? loop.IsDeclaredOuter ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner+ : loopIndex == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner;+ bindings.AddFaceBoundaryRoleBinding(new FaceBoundaryRoleBinding(faceId, loop.LoopId, role, loop.SourceBoundEntityId));+ }+ importedFacePatches.Add(new ImportedFacePatch(+ faceId,+ surfaceGeometryId,+ new SourceFaceOrientationEvidence(+ faceSameSenseResult.Value,+ faceEntity.Id,+ surfaceResult.Value.ReferenceId)));+ var loopOrientation = DeriveSupportAlignedBoundaries(classifyResult.Value, surfaceGeometry);+ supportAlignedBoundary[faceId] = loopOrientation.FaceAligned;+ foreach (var pair in loopOrientation.Loops) supportAlignedLoopBoundary[pair.Key] = pair.Value;}foreach (var coedge in coedges)@@ -591,13 +613,28 @@ public static class Step242Importer}var body = new BrepBody(builder.Model, geometry, bindings, vertexMap.Values.ToDictionary(entry => entry.VertexId, entry => entry.Point), shellRepresentation: shellRepresentation);- var validation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);+ var orientation = StepFaceOrientationResolver.Resolve(body, importedFacePatches, supportAlignedBoundary, supportAlignedLoopBoundary);+ if (!orientation.IsSuccess)+ {+ return KernelResult<BrepBody>.Failure(shellRoleDiagnostics+ .Concat(surfaceBindingDiagnostics)+ .Concat(orientation.Diagnostics));+ }++ var validation = BrepBindingValidator.Validate(orientation.Value, requireAllEdgeAndFaceBindings: true);if (!validation.IsSuccess){- return KernelResult<BrepBody>.Failure(validation.Diagnostics);+ return KernelResult<BrepBody>.Failure(validation.Diagnostics+ .Concat(shellRoleDiagnostics)+ .Concat(surfaceBindingDiagnostics)+ .Concat(orientation.Diagnostics));}- return KernelResult<BrepBody>.Success(body, validation.Diagnostics.Concat(shellRoleDiagnostics).Concat(surfaceBindingDiagnostics).ToArray());+ return KernelResult<BrepBody>.Success(orientation.Value, validation.Diagnostics+ .Concat(shellRoleDiagnostics)+ .Concat(surfaceBindingDiagnostics)+ .Concat(orientation.Diagnostics)+ .ToArray());}private static KernelResult<IReadOnlyList<int>> ReadShellFaceIds(Step242ParsedDocument document, int shellEntityId, string role, ICollection<KernelDiagnostic> diagnostics)@@ -1102,7 +1139,6 @@ public static class Step242ImporterStep242ParsedEntity? surfaceEntity,string surfaceName,IReadOnlyList<Step242Value>? inlineSurfaceArguments,- bool faceSameSense,int nextSurfaceGeometryId,int faceEntityId){@@ -1130,8 +1166,8 @@ public static class Step242Importer// made planes the one surface kind whose stored normal already carried the face sense while the binding// recorded it as well - so every consumer that honoured the binding flipped a plane twice, and a plane// face with same_sense=.F. inverted its normal on every export/import cycle. The stored surface is now- // exactly what the file stated for every kind, and FaceGeometryBinding.SameSense is the only carrier of- // face orientation. It cannot be the other way round: a cylinder normal cannot be negated without+ // exactly what the file stated for every kind. The shell solver records source orientation separately+ // and projects one ResolvedFaceOrientation. A cylinder normal cannot be negated without// flipping its axis, which would change the parameterization the trim intervals are written against.return KernelResult<(SurfaceGeometryId SurfaceGeometryId, SurfaceGeometry SurfaceGeometry)>.Success((geometryId, SurfaceGeometry.FromPlane(planeResult.Value)));}@@ -2330,6 +2366,164 @@ public static class Step242Importerreturn KernelResult<IReadOnlyList<LoopBuildData>>.Success(ordered);}+ private static (bool FaceAligned, IReadOnlyDictionary<LoopId, bool> Loops) DeriveSupportAlignedBoundaries(+ IReadOnlyList<LoopBuildData> loops,+ SurfaceGeometry surface)+ {+ if (loops.Count == 0) return (true, new Dictionary<LoopId, bool>());+ var outer = loops.SingleOrDefault(loop => loop.IsDeclaredOuter) ?? loops[0];+ var resolved = new Dictionary<LoopId, bool>();+ foreach (var loop in loops)+ {+ var isOuter = loop.LoopId == outer.LoopId;+ IReadOnlyList<UvPoint>? projected = surface.Kind switch+ {+ SurfaceGeometryKind.Plane => SimplifyClosedPolygon(ProjectLoopToPlane(loop.Samples, surface.Plane!.Value), ContainmentEps),+ SurfaceGeometryKind.Cylinder => ProjectLoopToCylinder(loop.Samples, surface.Cylinder!.Value),+ SurfaceGeometryKind.Cone => ProjectLoopToCone(loop.Samples, surface.Cone!.Value),+ SurfaceGeometryKind.Sphere => ProjectLoopToSphere(loop.Samples, surface.Sphere!.Value),+ SurfaceGeometryKind.Torus => ProjectLoopToTorus(loop.Samples, surface.Torus!.Value),+ _ => null,+ };+ var signedArea = projected is null ? 0d : ComputeSignedArea(projected);+ var periodicity = SurfacePeriodicity.Of(surface);+ var boundaryAligned = surface.Kind == SurfaceGeometryKind.Sphere+ && TryDeriveSupportAlignmentFromBoundaryNormal(loop.Samples, surface, out var sphericalAligned)+ ? sphericalAligned+ : surface.Kind != SurfaceGeometryKind.Sphere+ && projected is not null+ && TryDeriveFullPeriodTraversalAlignment(projected, periodicity, out var periodicAligned)+ ? periodicAligned+ : surface.Kind == SurfaceGeometryKind.Cone+ && TryDeriveSupportAlignmentFromBoundaryNormal(loop.Samples, surface, out var conicalAligned)+ ? conicalAligned+ : projected is not null && double.Abs(signedArea) > ComputeAreaTolerance(projected)+ ? signedArea > 0d+ : TryDeriveSupportAlignmentFromBoundaryNormal(loop.Samples, surface, out var aligned)+ ? aligned+ : isOuter;+ resolved[loop.LoopId] = isOuter ? boundaryAligned : !boundaryAligned;+ }+ return (resolved[outer.LoopId], resolved);+ }++ private static bool TryDeriveFullPeriodTraversalAlignment(+ IReadOnlyList<UvPoint> projected,+ SurfacePeriodicity periodicity,+ out bool aligned)+ {+ aligned = true;+ if (!periodicity.IsPeriodic || projected.Count < 2) return false;++ var endIndex = projected.Count - 1;+ if (SegmentLengthSquared(projected[0], projected[endIndex]) <= ContainmentEps * ContainmentEps)+ endIndex--;+ if (endIndex <= 0) return false;++ var active = projected.Take(endIndex + 1).ToArray();+ var uSpan = active[^1].X - active[0].X;+ var vSpan = active[^1].Y - active[0].Y;+ var uRange = active.Max(point => point.X) - active.Min(point => point.X);+ var vRange = active.Max(point => point.Y) - active.Min(point => point.Y);+ var constantAxisTolerance = ContainmentEps * 8d;++ if (periodicity.UPeriod is { } uPeriod+ && double.Abs(uSpan) >= uPeriod - AngleUnwrapEps+ && SurfacePeriodicity.EquivalentModuloPeriod(active[0].X, active[^1].X, uPeriod, AngleUnwrapEps)+ && vRange <= constantAxisTolerance)+ {+ aligned = uSpan > 0d;+ return true;+ }++ if (periodicity.VPeriod is { } vPeriod+ && double.Abs(vSpan) >= vPeriod - AngleUnwrapEps+ && SurfacePeriodicity.EquivalentModuloPeriod(active[0].Y, active[^1].Y, vPeriod, AngleUnwrapEps)+ && uRange <= constantAxisTolerance)+ {+ aligned = vSpan > 0d;+ return true;+ }++ return false;+ }++ private static bool TryDeriveSupportAlignmentFromBoundaryNormal(+ IReadOnlyList<Point3D> samples,+ SurfaceGeometry surface,+ out bool aligned)+ {+ aligned = true;+ var points = samples+ .Where((point, index) => index == 0 || (point - samples[index - 1]).Length > ContainmentEps)+ .ToArray();+ if (points.Length < 3) return false;+ var boundaryNormal = Vector3D.Zero;+ for (var index = 0; index < points.Length; index++)+ {+ var current = points[index];+ var next = points[(index + 1) % points.Length];+ boundaryNormal += new Vector3D(+ (current.Y - next.Y) * (current.Z + next.Z),+ (current.Z - next.Z) * (current.X + next.X),+ (current.X - next.X) * (current.Y + next.Y));+ }+ if (!boundaryNormal.TryNormalize(out var normalizedBoundary)) return false;+ var center = new Point3D(points.Average(point => point.X), points.Average(point => point.Y), points.Average(point => point.Z));+ Vector3D supportNormal;+ switch (surface.Kind)+ {+ case SurfaceGeometryKind.Plane:+ supportNormal = surface.Plane!.Value.Normal.ToVector();+ break;+ case SurfaceGeometryKind.Cylinder:+ {+ var cylinder = surface.Cylinder!.Value;+ var delta = center - cylinder.Origin;+ supportNormal = delta - (cylinder.Axis.ToVector() * delta.Dot(cylinder.Axis.ToVector()));+ break;+ }+ case SurfaceGeometryKind.Sphere:+ supportNormal = center - surface.Sphere!.Value.Center;+ break;+ case SurfaceGeometryKind.Cone:+ {+ var cone = surface.Cone!.Value;+ var delta = center - cone.Apex;+ var radial = delta - (cone.Axis.ToVector() * delta.Dot(cone.Axis.ToVector()));+ if (!radial.TryNormalize(out var radialDirection)) return false;+ supportNormal = radialDirection - (cone.Axis.ToVector() * double.Tan(cone.SemiAngleRadians));+ break;+ }+ case SurfaceGeometryKind.Torus:+ {+ var torus = surface.Torus!.Value;+ var delta = center - torus.Center;+ var planar = delta - (torus.Axis.ToVector() * delta.Dot(torus.Axis.ToVector()));+ if (!planar.TryNormalize(out var majorDirection)) return false;+ var tubeCenter = torus.Center + (majorDirection * torus.MajorRadius);+ supportNormal = center - tubeCenter;+ break;+ }+ case SurfaceGeometryKind.BSplineSurfaceWithKnots:+ {+ var spline = surface.BSplineSurfaceWithKnots!;+ var u = (spline.DomainStartU + spline.DomainEndU) * 0.5d;+ var v = (spline.DomainStartV + spline.DomainEndV) * 0.5d;+ var du = System.Math.Max((spline.DomainEndU - spline.DomainStartU) * 1e-5d, 1e-8d);+ var dv = System.Math.Max((spline.DomainEndV - spline.DomainStartV) * 1e-5d, 1e-8d);+ supportNormal = (spline.Evaluate(u + du, v) - spline.Evaluate(u - du, v))+ .Cross(spline.Evaluate(u, v + dv) - spline.Evaluate(u, v - dv));+ break;+ }+ default:+ return false;+ }+ if (!supportNormal.TryNormalize(out var normalizedSupport)) return false;+ aligned = normalizedBoundary.Dot(normalizedSupport) > 0d;+ return true;+ }+private static LoopBuildData NormalizeLoopWinding(LoopBuildData loop, double signedArea, bool shouldBePositive){// STEP EDGE_LOOP order is topology, not presentation. Classification@@ -2853,6 +3047,37 @@ public static class Step242Importerreturn uv;}+ private static List<UvPoint> ProjectLoopToSphere(IReadOnlyList<Point3D> samples, SphereSurface sphere)+ {+ var uv = new List<UvPoint>(samples.Count + 1);+ var previousAngle = 0d;+ var revolutions = 0d;+ var hasPrevious = false;+ foreach (var sample in samples)+ {+ var offset = sample - sphere.Center;+ var radial = offset.Length;+ if (!double.IsFinite(radial) || radial <= PointOnSurfaceEps) continue;+ var normalized = offset / radial;+ var angle = double.Atan2(+ normalized.Dot(sphere.YAxis.ToVector()),+ normalized.Dot(sphere.XAxis.ToVector()));+ if (hasPrevious)+ {+ var delta = angle - previousAngle;+ if (delta > double.Pi) revolutions -= 2d * double.Pi;+ else if (delta < -double.Pi) revolutions += 2d * double.Pi;+ }+ var elevation = double.Asin(double.Clamp(normalized.Dot(sphere.Axis.ToVector()), -1d, 1d));+ uv.Add(new UvPoint(angle + revolutions, elevation));+ previousAngle = angle;+ hasPrevious = true;+ }+ if (uv.Count > 0 && SegmentLengthSquared(uv[0], uv[^1]) > ContainmentEps * ContainmentEps)+ uv.Add(uv[0]);+ return uv;+ }+private static List<UvPoint> ProjectLoopToTorus(IReadOnlyList<Point3D> samples, TorusSurface torus){var axis = torus.Axis.ToVector();@@ -3853,7 +4078,13 @@ public static class Step242Importerprivate static string SourceFor(int _entityId, string stableSource) => stableSource;- private sealed record LoopBuildData(LoopId LoopId, IReadOnlyList<Coedge> Coedges, IReadOnlyList<Point3D> Samples, bool HasDisconnectedCoedgeGap = false, bool IsDeclaredOuter = false);+ private sealed record LoopBuildData(+ LoopId LoopId,+ IReadOnlyList<Coedge> Coedges,+ IReadOnlyList<Point3D> Samples,+ bool HasDisconnectedCoedgeGap = false,+ bool IsDeclaredOuter = false,+ int? SourceBoundEntityId = null);private sealed record PlanarLoopInfo(LoopBuildData Loop, IReadOnlyList<UvPoint> ProjectedPoints, double SignedArea);diff --git a/Aetheris.Kernel.Core/Step242/StepFaceBoundaryExportPolicy.cs b/Aetheris.Kernel.Core/Step242/StepFaceBoundaryExportPolicy.csnew file mode 100644index 00000000..72b53809--- /dev/null+++ b/Aetheris.Kernel.Core/Step242/StepFaceBoundaryExportPolicy.cs@@ -0,0 +1,68 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Step242;++internal static class StepFaceBoundaryExportPolicy+{+ internal const string ExplicitRolesCandidate = "explicit-face-boundary-roles";+ internal const string AuthoredOrderCandidate = "authored-loop-order";++ internal sealed record Decision(+ string Candidate,+ IReadOnlyList<(LoopId LoopId, FaceBoundaryRole Role)> Boundaries,+ IReadOnlyList<JudgmentRejection> Rejections);++ private sealed record Context(+ Face Face,+ IReadOnlyList<FaceBoundaryRoleBinding> Roles,+ bool HasCompleteExplicitRoles,+ bool HasExactlyOneOuter);++ private static readonly JudgmentEngine<Context> Engine = new();+ private static readonly IReadOnlyList<JudgmentCandidate<Context>> Candidates =+ [+ new(+ ExplicitRolesCandidate,+ context => context.HasCompleteExplicitRoles && context.HasExactlyOneOuter,+ _ => 1d,+ context => context.Roles.Count == 0+ ? "No explicit face-boundary role evidence is present."+ : "Explicit face-boundary roles are incomplete, cross-face, duplicated, or do not identify exactly one outer loop.",+ TieBreakerPriority: 0),+ new(+ AuthoredOrderCandidate,+ context => context.Roles.Count == 0 && context.Face.LoopIds.Count > 0,+ _ => 0.5d,+ _ => "Authored loop order is only admissible when no explicit role evidence exists.",+ TieBreakerPriority: 1)+ ];++ internal static Decision? Decide(BrepBody body, Face face)+ {+ if (face.LoopIds.Count == 0)+ return new Decision(AuthoredOrderCandidate, [], []);++ var roles = face.LoopIds+ .Where(loopId => body.Bindings.TryGetFaceBoundaryRoleBinding(loopId, out _))+ .Select(loopId => body.Bindings.GetFaceBoundaryRoleBinding(loopId))+ .ToArray();+ var uniqueLoops = roles.Select(role => role.LoopId).Distinct().Count() == roles.Length;+ var sameFace = roles.All(role => role.FaceId == face.Id);+ var complete = roles.Length == face.LoopIds.Count && uniqueLoops && sameFace;+ var exactlyOneOuter = roles.Count(role => role.Role == FaceBoundaryRole.Outer) == 1;+ var context = new Context(face, roles, complete, exactlyOneOuter);+ var judgment = Engine.Evaluate(context, Candidates);+ if (!judgment.IsSuccess) return null;++ var selected = judgment.Selection!.Value.Candidate.Name;+ var boundaries = selected == ExplicitRolesCandidate+ ? roles.OrderBy(role => role.Role == FaceBoundaryRole.Outer ? 0 : 1)+ .Select(role => (role.LoopId, role.Role))+ .ToArray()+ : face.LoopIds.Select((loopId, index) =>+ (loopId, index == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner)).ToArray();+ return new Decision(selected, boundaries, judgment.Rejections);+ }+}diff --git a/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.cs b/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.csnew file mode 100644index 00000000..c91eb2a6--- /dev/null+++ b/Aetheris.Kernel.Core/Step242/StepFaceOrientationResolver.cs@@ -0,0 +1,326 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Step242;++/// <summary>+/// Import-only patch. Its orientation is deliberately absent until the shell+/// graph and material-side solve have completed.+/// </summary>+internal sealed record ImportedFacePatch(+ FaceId FaceId,+ SurfaceGeometryId SurfaceGeometryId,+ SourceFaceOrientationEvidence SourceEvidence);++/// <summary>+/// Resolves STEP face orientation once from shell topology and geometric signed+/// volume. Source same_sense participates only in the final cross-check.+/// </summary>+internal static class StepFaceOrientationResolver+{+ private const double VolumeTolerance = 1e-10d;++ public static KernelResult<BrepBody> Resolve(+ BrepBody unresolvedBody,+ IReadOnlyList<ImportedFacePatch> importedFaces,+ IReadOnlyDictionary<FaceId, bool>? supportAlignedBoundary = null,+ IReadOnlyDictionary<LoopId, bool>? supportAlignedLoopBoundary = null)+ {+ ArgumentNullException.ThrowIfNull(unresolvedBody);+ ArgumentNullException.ThrowIfNull(importedFaces);+ var sourceEvidence = importedFaces.ToDictionary(face => face.FaceId, face => face.SourceEvidence);++ var diagnostics = new List<KernelDiagnostic>();+ var localOrientation = new Dictionary<FaceId, bool>();+ var faceToShell = new Dictionary<FaceId, ShellId>();+ var componentByFace = new Dictionary<FaceId, int>();+ var components = new List<ComponentState>();+ var shellStates = new List<ShellState>();+ var nextComponent = 0;++ foreach (var shell in unresolvedBody.Topology.Shells.OrderBy(shell => shell.Id.Value))+ {+ var faces = shell.FaceIds.OrderBy(face => face.Value).ToArray();+ foreach (var face in faces) faceToShell[face] = shell.Id;+ var edgeUses = CollectEdgeUses(unresolvedBody, faces);+ var nonManifold = edgeUses.Where(pair => pair.Value.Count > 2).OrderBy(pair => pair.Key.Value).ToArray();+ if (nonManifold.Length > 0)+ {+ return KernelResult<BrepBody>.Failure([+ new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"step-orientation-nonmanifold: shell {shell.Id.Value}; edges {string.Join(",", nonManifold.Select(pair => $"{pair.Key.Value}({pair.Value.Count})"))}; canonical orientation was not guessed.",+ "Importer.StepOrientation.NonManifoldOrientation")+ ]);+ }++ var graph = faces.ToDictionary(face => face, _ => new List<Relation>());+ foreach (var uses in edgeUses.Values.Where(uses => uses.Count == 2))+ {+ var left = uses[0];+ var right = uses[1];+ if (left.FaceId == right.FaceId) continue; // periodic seam on one face+ // Relate each raw coedge traversal to its support-space boundary+ // winding. This separates geometric face orientation from both+ // EDGE_CURVE parameter sense and source ADVANCED_FACE evidence.+ var leftBaseline = supportAlignedLoopBoundary?.GetValueOrDefault(+ left.LoopId,+ supportAlignedBoundary?.GetValueOrDefault(left.FaceId) ?? true) ?? true;+ var rightBaseline = supportAlignedLoopBoundary?.GetValueOrDefault(+ right.LoopId,+ supportAlignedBoundary?.GetValueOrDefault(right.FaceId) ?? true) ?? true;+ var mustDiffer = leftBaseline+ ^ rightBaseline+ ^ (left.IsReversed == right.IsReversed);+ var relationEvidence = $"edge={left.EdgeId.Value}; loops={left.LoopId.Value}/{right.LoopId.Value}; loop-baselines={leftBaseline}/{rightBaseline}; coedge-reversed={left.IsReversed}/{right.IsReversed}";+ graph[left.FaceId].Add(new Relation(right.FaceId, mustDiffer, relationEvidence));+ graph[right.FaceId].Add(new Relation(left.FaceId, mustDiffer, relationEvidence));+ }++ foreach (var seed in faces)+ {+ if (localOrientation.ContainsKey(seed)) continue;+ var componentId = nextComponent++;+ var componentFaces = new List<FaceId>();+ var queue = new Queue<FaceId>();+ localOrientation[seed] = supportAlignedBoundary?.GetValueOrDefault(seed) ?? true;+ queue.Enqueue(seed);+ var propagationConflict = false;+ (FaceId Left, FaceId Right)? firstConflict = null;+ string? firstConflictEvidence = null;+ while (queue.Count > 0)+ {+ var current = queue.Dequeue();+ componentFaces.Add(current);+ componentByFace[current] = componentId;+ foreach (var relation in graph[current].OrderBy(relation => relation.FaceId.Value))+ {+ var required = relation.MustDiffer ? !localOrientation[current] : localOrientation[current];+ if (localOrientation.TryGetValue(relation.FaceId, out var existing))+ {+ if (existing != required)+ {+ propagationConflict = true;+ firstConflict ??= (current, relation.FaceId);+ firstConflictEvidence ??= relation.Evidence;+ }+ continue;+ }+ localOrientation[relation.FaceId] = required;+ queue.Enqueue(relation.FaceId);+ }+ }++ if (propagationConflict)+ {+ // Some admitted STEP files reuse topological edges with an+ // ORIENTED_EDGE cycle that cannot be made globally+ // consistent. The independently derived support-space+ // boundary normal is stronger geometric evidence than an+ // arbitrary graph seed, so retain it and make the degraded+ // adjacency evidence explicit.+ foreach (var faceId in componentFaces)+ {+ localOrientation[faceId] = supportAlignedBoundary?.GetValueOrDefault(faceId) ?? true;+ }+ diagnostics.Add(new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Warning,+ $"step-orientation-propagation-conflict: shell {shell.Id.Value}; component seed {seed.Value}; faces {firstConflict?.Left.Value}/{firstConflict?.Right.Value}; {firstConflictEvidence}; contradictory shared-edge requirements; support-space boundary orientation was used.",+ "Importer.StepOrientation.OrientationPropagationConflict"));+ }++ components.Add(new ComponentState(componentId, shell.Id, componentFaces.OrderBy(face => face.Value).ToArray(), propagationConflict));+ }++ var isClosedParametricSurface = edgeUses.Count == 0 && faces.Length > 0+ && faces.All(faceId => unresolvedBody.Topology.GetFace(faceId).LoopIds.Count == 0+ && unresolvedBody.TryGetFaceSurfaceGeometry(faceId, out var surface)+ && surface?.Kind == Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Sphere);+ var isClosed = (edgeUses.Count > 0 && edgeUses.All(pair => pair.Value.Count == 2)) || isClosedParametricSurface;+ var isInnerVoid = unresolvedBody.ShellRepresentation?.InnerShellIds.Contains(shell.Id) == true;+ shellStates.Add(new ShellState(shell.Id, isClosed, isInnerVoid));+ if (!isClosed)+ {+ diagnostics.Add(new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Warning,+ $"step-orientation-global-unknown: shell {shell.Id.Value} is open; local adjacency was resolved but no outward/material-side claim was made.",+ "Importer.StepOrientation.GlobalOrientationUnknown"));+ }+ }++ var localCandidate = CloneWithOrientations(unresolvedBody, localOrientation, faceOrientationReport: null);+ var tessellation = BrepDisplayTessellator.Tessellate(localCandidate);+ var signedVolumeByComponent = new Dictionary<int, double>();+ if (tessellation.IsSuccess)+ {+ foreach (var patch in tessellation.Value.FacePatches)+ {+ if (!componentByFace.TryGetValue(patch.FaceId, out var component)) continue;+ var signed = SignedVolume(patch);+ signedVolumeByComponent[component] = signedVolumeByComponent.GetValueOrDefault(component) + signed;+ }+ }++ var globalFlipByComponent = new Dictionary<int, bool>();+ foreach (var component in components)+ {+ var shell = shellStates.Single(state => state.ShellId == component.ShellId);+ if (!shell.IsClosed || component.HasPropagationConflict)+ {+ globalFlipByComponent[component.Id] = false;+ continue;+ }+ if (!tessellation.IsSuccess || !signedVolumeByComponent.TryGetValue(component.Id, out var signed) || System.Math.Abs(signed) <= VolumeTolerance)+ {+ diagnostics.Add(new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Warning,+ $"step-orientation-shell-ambiguous: shell {shell.ShellId.Value}; component seed {component.Faces[0].Value}; signed volume unavailable or near zero; source evidence was not promoted to authority.",+ "Importer.StepOrientation.ShellOrientationAmbiguous"));+ globalFlipByComponent[component.Id] = false;+ continue;+ }++ var wantsPositive = !shell.IsInnerVoid;+ globalFlipByComponent[component.Id] = wantsPositive ? signed < 0d : signed > 0d;+ }++ var finalOrientation = localOrientation.ToDictionary(+ pair => pair.Key,+ pair => globalFlipByComponent.GetValueOrDefault(componentByFace[pair.Key]) ? !pair.Value : pair.Value);++ var orientedFaces = new List<OrientedFacePatch>();+ foreach (var face in unresolvedBody.Topology.Faces.OrderBy(face => face.Id.Value))+ {+ var evidence = sourceEvidence.TryGetValue(face.Id, out var found)+ ? found+ : new SourceFaceOrientationEvidence(null, null, null);+ var shellId = faceToShell[face.Id];+ var shell = shellStates.Single(state => state.ShellId == shellId);+ var component = components.Single(state => state.Id == componentByFace[face.Id]);+ var hasVolume = signedVolumeByComponent.TryGetValue(component.Id, out var signed) && System.Math.Abs(signed) > VolumeTolerance;+ var qualification = component.HasPropagationConflict+ ? FaceOrientationQualification.Ambiguous+ : !shell.IsClosed+ ? FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown+ : hasVolume+ ? FaceOrientationQualification.DerivedQualified+ : FaceOrientationQualification.Ambiguous;+ var orientation = new ResolvedFaceOrientation(finalOrientation[face.Id]);+ var comparison = evidence.StepSameSense is null+ ? SourceFaceOrientationComparison.SourceMissing+ : qualification == FaceOrientationQualification.Ambiguous+ ? SourceFaceOrientationComparison.NotComparable+ : evidence.StepSameSense.Value == orientation.IsAlignedWithSurface+ ? SourceFaceOrientationComparison.Agrees+ : SourceFaceOrientationComparison.Disagrees;+ var summary = shell.IsClosed+ ? $"local adjacency consistent; candidate signed volume={(hasVolume ? signed.ToString("G17") : "unavailable")}; shell role={(shell.IsInnerVoid ? "inner-void" : "outer")}; global flip={globalFlipByComponent.GetValueOrDefault(component.Id)}"+ : "local adjacency consistent; open shell; global orientation unknown";+ summary += $"; support-boundaries={string.Join(',', face.LoopIds.Select(loopId => $"{loopId.Value}:{supportAlignedLoopBoundary?.GetValueOrDefault(loopId)}"))}";+ orientedFaces.Add(new OrientedFacePatch(face.Id, shellId, orientation, qualification, evidence, comparison, summary));++ if (comparison == SourceFaceOrientationComparison.Disagrees)+ {+ diagnostics.Add(new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Warning,+ $"step-orientation-source-mismatch: face {face.Id.Value}; STEP face #{evidence.SourceEntityId}; source same_sense={evidence.StepSameSense}; derived aligned={orientation.IsAlignedWithSurface}; shell {shellId.Value}; {summary}; action=derived orientation used.",+ "Importer.StepOrientation.SourceOrientationMismatch"));+ }+ }++ var shellResolutions = shellStates.Select(shell =>+ {+ var shellComponents = components.Where(component => component.ShellId == shell.ShellId).ToArray();+ var qualified = shell.IsClosed && shellComponents.All(component => !component.HasPropagationConflict+ && signedVolumeByComponent.TryGetValue(component.Id, out var signed)+ && System.Math.Abs(signed) > VolumeTolerance);+ var qualification = shellComponents.Any(component => component.HasPropagationConflict)+ ? FaceOrientationQualification.Ambiguous+ : !shell.IsClosed+ ? FaceOrientationQualification.DerivedLocallyConsistentGlobalUnknown+ : qualified ? FaceOrientationQualification.DerivedQualified : FaceOrientationQualification.Ambiguous;+ var volume = shellComponents.Sum(component => signedVolumeByComponent.GetValueOrDefault(component.Id));+ return new ShellOrientationResolution(+ shell.ShellId,+ qualification,+ shell.IsClosed,+ shell.IsInnerVoid,+ tessellation.IsSuccess ? volume : null,+ tessellation.IsSuccess+ ? shellComponents.Sum(component => globalFlipByComponent.GetValueOrDefault(component.Id)+ ? -signedVolumeByComponent.GetValueOrDefault(component.Id)+ : signedVolumeByComponent.GetValueOrDefault(component.Id))+ : null,+ shellComponents.Any(component => globalFlipByComponent.GetValueOrDefault(component.Id)),+ $"components={shellComponents.Length}; local adjacency consistent; role={(shell.IsInnerVoid ? "inner-void" : "outer")}");+ }).ToArray();+ var report = new FaceOrientationReport(orientedFaces, shellResolutions);+ var resolved = CloneWithOrientations(unresolvedBody, finalOrientation, report);+ return KernelResult<BrepBody>.Success(resolved, diagnostics);+ }++ private static Dictionary<EdgeId, List<EdgeUse>> CollectEdgeUses(BrepBody body, IReadOnlyCollection<FaceId> faces)+ {+ var result = new Dictionary<EdgeId, List<EdgeUse>>();+ foreach (var faceId in faces)+ foreach (var loopId in body.Topology.GetFace(faceId).LoopIds)+ foreach (var coedgeId in body.GetCoedgeIds(loopId))+ {+ var coedge = body.Topology.GetCoedge(coedgeId);+ if (!result.TryGetValue(coedge.EdgeId, out var uses)) result[coedge.EdgeId] = uses = [];+ uses.Add(new EdgeUse(faceId, loopId, coedge.EdgeId, coedge.IsReversed));+ }+ return result;+ }++ private static BrepBody CloneWithOrientations(+ BrepBody body,+ IReadOnlyDictionary<FaceId, bool> orientations,+ FaceOrientationReport? faceOrientationReport)+ {+ var bindings = new BrepBindingModel();+ foreach (var edge in body.Bindings.EdgeBindings) bindings.AddEdgeBinding(edge);+ foreach (var pcurve in body.Bindings.PcurveBindings) bindings.AddPcurveBinding(pcurve);+ foreach (var role in body.Bindings.FaceBoundaryRoleBindings) bindings.AddFaceBoundaryRoleBinding(role);+ foreach (var face in body.Bindings.FaceBindings)+ {+ var orientation = orientations.TryGetValue(face.FaceId, out var aligned)+ ? new ResolvedFaceOrientation(aligned)+ : face.Orientation;+ bindings.AddFaceBinding(face with { Orientation = orientation });+ }+ var points = body.Topology.Vertices+ .Where(vertex => body.TryGetVertexPoint(vertex.Id, out _))+ .ToDictionary(vertex => vertex.Id, vertex => { body.TryGetVertexPoint(vertex.Id, out var point); return point; });+ return new BrepBody(body.Topology, body.Geometry, bindings, points, body.SafeBooleanComposition, body.ShellRepresentation, faceOrientationReport);+ }++ private static double SignedVolume(DisplayFaceMeshPatch patch)+ {+ var result = 0d;+ for (var i = 0; i < patch.TriangleIndices.Count; i += 3)+ {+ var a = patch.Positions[patch.TriangleIndices[i]];+ var b = patch.Positions[patch.TriangleIndices[i + 1]];+ var c = patch.Positions[patch.TriangleIndices[i + 2]];+ result += (a.X * ((b.Y * c.Z) - (b.Z * c.Y))+ + a.Y * ((b.Z * c.X) - (b.X * c.Z))+ + a.Z * ((b.X * c.Y) - (b.Y * c.X))) / 6d;+ }+ return result;+ }++ private sealed record EdgeUse(FaceId FaceId, LoopId LoopId, EdgeId EdgeId, bool IsReversed);+ private sealed record Relation(FaceId FaceId, bool MustDiffer, string Evidence);+ private sealed record ComponentState(int Id, ShellId ShellId, IReadOnlyList<FaceId> Faces, bool HasPropagationConflict);+ private sealed record ShellState(ShellId ShellId, bool IsClosed, bool IsInnerVoid);+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.csindex ff43a788..1eccf115 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/DifferenceEngineStorageGateTests.cs@@ -1,5 +1,6 @@using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Brep.Verification;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;@@ -104,6 +105,23 @@ public sealed class DifferenceEngineStorageGateTestscapArea += (b - a).Cross(c - a).Z / 2;}Assert.InRange(volume / (capArea * 8), .995, 1.005);++ // Mandatory STEP-ORIENTATION-X1 witness: the Difference Engine drive+ // gear's central bore historically serialized same_sense=false. The+ // import records that source flag as evidence while retaining the+ // independently derived inward-facing cavity wall.+ var step = Step242Exporter.ExportBody(gear);+ Assert.True(step.IsSuccess);+ var imported = Step242Importer.ImportBody(step.Value);+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics.Select(d => d.Message)));+ var boreFace = Assert.Single(imported.Value.Bindings.FaceBindings, binding =>+ imported.Value.Geometry.GetSurface(binding.SurfaceGeometryId).Cylinder is { Radius: > 4.19 and < 4.21 });+ var boreReport = Assert.Single(imported.Value.FaceOrientationReport!.Faces, face => face.FaceId == boreFace.FaceId);+ Assert.False(boreReport.Orientation.IsAlignedWithSurface);+ Assert.False(boreReport.SourceEvidence.StepSameSense);+ var importedMass = BrepMassProperties.Evaluate(imported.Value);+ Assert.True(importedMass.IsEnclosed);+ Assert.True(importedMass.SignedVolume > 0d);}private static AssemblyM1CompilationResult Compile(string name)diff --git a/Aetheris.Kernel.Firmament.Tests/ChamferedEntryHoleVariantAndExecutorTests.cs b/Aetheris.Kernel.Firmament.Tests/ChamferedEntryHoleVariantAndExecutorTests.csindex a0431f95..a60870f9 100644--- a/Aetheris.Kernel.Firmament.Tests/ChamferedEntryHoleVariantAndExecutorTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/ChamferedEntryHoleVariantAndExecutorTests.cs@@ -69,7 +69,7 @@ public sealed class ChamferedEntryHoleVariantAndExecutorTestsAetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Cylinder).ToArray();Assert.Equal(2, inwardFaces.Length);- Assert.All(inwardFaces, binding => Assert.False(binding.SameSense));+ Assert.All(inwardFaces, binding => Assert.False(binding.Orientation.IsAlignedWithSurface));AssertConeBoundaryVerticesLieOnSupport(result.Body!);Assert.Contains(result.Diagnostics, d => d.Contains("cylinder subtract invoked", StringComparison.OrdinalIgnoreCase));Assert.Contains(result.Diagnostics, d => d.Contains("chamfer cone subtract invoked", StringComparison.OrdinalIgnoreCase));diff --git a/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs b/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.csindex 87ab15b9..1eaea3da 100644--- a/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs@@ -271,7 +271,7 @@ public sealed class PrismaticProfileCompositionRoundTripTests.Distinct().ToArray();Assert.Equal(32, holeWalls.Length);- Assert.All(holeWalls, face => Assert.False(body.Bindings.FaceBindings.Single(binding => binding.FaceId == face).SameSense));+ Assert.All(holeWalls, face => Assert.False(body.Bindings.FaceBindings.Single(binding => binding.FaceId == face).Orientation.IsAlignedWithSurface));var m8 = BrepMassProperties.Evaluate(body);Assert.NotEqual(BrepMassPropertiesStatus.Unavailable, m8.Status);diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.csindex dfd8fbf1..69f6c609 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs@@ -46,11 +46,8 @@ public static class AssemblyDisplayMeshExportervar ranges = new List<AssemblyDisplayMeshRange>();foreach (var rawFace in tessellation.Value.FacePatches.OrderBy(p => p.FaceId.Value)){- // Both tessellation paths now emit face-oriented patches: SurfaceMeshIR always did,- // and BrepDisplayTessellator projects the face sense once, for every surface kind, at- // the single place face patches are produced. Re-orienting here flipped every face whose- // binding says same_sense=.F. a second time - one bore cylinder was enough to put this- // gear's enclosed volume 6.25% over its cap-area-times-height value.+ // Both tessellation paths emit canonically oriented patches. Assembly placement transforms+ // positions and normals but never reinterprets interchange orientation evidence.var face = rawFace;if (face.Positions.Count == 0 || face.Normals.Count != face.Positions.Count || face.TriangleIndices.Count == 0|| face.TriangleIndices.Count % 3 != 0 || face.TriangleIndices.Any(i => i < 0 || i >= face.Positions.Count))diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.csindex 018f6198..2b665fb0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.cs@@ -48,7 +48,7 @@ public static class PlateauAuthoringif (baseBody.Body is null) return Fail(baseBody.Diagnostics);var frame = parsed.Profile.EffectiveConstructionPlane;var origin = frame.Origin + frame.AxisZ.ToVector() * (parsed.Profile.LocalEndDepth ?? parsed.Height);- var candidates = baseBody.Body.Bindings.FaceBindings.Where(b => b.SameSense && baseBody.Body.Geometry.GetSurface(b.SurfaceGeometryId).Plane is { } p &&+ var candidates = baseBody.Body.Bindings.FaceBindings.Where(b => b.Orientation.IsAlignedWithSurface && baseBody.Body.Geometry.GetSurface(b.SurfaceGeometryId).Plane is { } p &&(p.Normal.ToVector() - frame.AxisZ.ToVector()).Length < 1e-10 && Math.Abs((p.Origin - origin).Dot(frame.AxisZ.ToVector())) < 1e-8).ToArray();if (candidates.Length != 1) return Fail(["plateau-base-face-unresolved"]);var spans = new List<SectionProfileSpan>();diff --git a/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs b/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.csindex a6fb0786..967749c5 100644--- a/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs+++ b/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs@@ -127,7 +127,7 @@ internal static class SectionStackBlindDrillCavityPlannervar transitionLoop = Loop((transitionArcA, false), (transitionArcB, false));var shaftLoop = Loop((mouthArcA, false), (mouthArcB, false), (shaftSeam, false), (transitionArcB, true), (transitionArcA, true), (shaftSeam, true));var coneLoop = Loop((transitionArcA, false), (transitionArcB, false), (coneSeam, false), (coneSeam, true));- var replacementFace = Face(originalFace!.LoopIds.Concat([mouthLoop]).ToArray(), originalSurface, originalBinding.SameSense);+ var replacementFace = Face(originalFace!.LoopIds.Concat([mouthLoop]).ToArray(), originalSurface, originalBinding.Orientation.IsAlignedWithSurface);var shaftFace = Face([shaftLoop], SurfaceGeometry.FromCylinder(new CylinderSurface(mouth, input.Placement.AxisZ, r, input.Placement.AxisX)), false);var coneFace = Face([coneLoop], SurfaceGeometry.FromCone(new ConeSurface(points[tip], Direction3D.Create(-axis), point!.PointAngleDegrees * Math.PI / 360d, input.Placement.AxisX)), false);@@ -278,7 +278,7 @@ internal static class SectionStackBlindDrillCavityPlannerreturn Loop(uses.ToArray());}var hostLoops = new[] { ReplaceSeam(loops[0], arcForFace[0]), ReplaceSeam(loops[1], arcForFace[1]) };- var replacementFaces = new[] { Face([hostLoops[0]], surfaces[0]!, bindings[0]!.Value.SameSense), Face([hostLoops[1]], surfaces[1]!, bindings[1]!.Value.SameSense) };+ var replacementFaces = new[] { Face([hostLoops[0]], surfaces[0]!, bindings[0]!.Value.Orientation.IsAlignedWithSurface), Face([hostLoops[1]], surfaces[1]!, bindings[1]!.Value.Orientation.IsAlignedWithSurface) };var radial = input.Placement.AxisX.ToVector(); var shaft = input.Corridor.ShaftDepth; var tipLength = input.Corridor.TipLength;var transitionCenter = mouth + axis * shaft; var transitionA = Vertex(transitionCenter + radial * input.Hole.Shaft.Radius); var transitionB = Vertex(transitionCenter - radial * input.Hole.Shaft.Radius); var tip = Vertex(transitionCenter + axis * tipLength);diff --git a/Aetheris.SheetMetal/SheetMetalRecognizer.cs b/Aetheris.SheetMetal/SheetMetalRecognizer.csindex d3a917c9..0dc1b229 100644--- a/Aetheris.SheetMetal/SheetMetalRecognizer.cs+++ b/Aetheris.SheetMetal/SheetMetalRecognizer.cs@@ -321,7 +321,7 @@ public static class SheetMetalRecognizerif(loops.Length==0)continue;var measured=loops.Select(points=>(Points:points,Area:LoopArea(points,surface))).OrderByDescending(x=>x.Area).ToArray();var outer=measured[0].Points;var inner=measured.Skip(1).Select(x=>x.Points).ToArray();- var sameSense=!body.Bindings.TryGetFaceBinding(face.Id,out var binding)||binding.SameSense;+ var sameSense=!body.Bindings.TryGetFaceBinding(face.Id,out var binding)||binding.Orientation.IsAlignedWithSurface;result.Add(new(face.Id,surface,sameSense,outer,inner,measured[0].Area,Centroid(outer),body.GetEdges(face.Id)));}return result;diff --git a/Aetheris.Surfacing/PlanarPlateauMaterializer.cs b/Aetheris.Surfacing/PlanarPlateauMaterializer.csindex 381ce818..4ebfc90b 100644--- a/Aetheris.Surfacing/PlanarPlateauMaterializer.cs+++ b/Aetheris.Surfacing/PlanarPlateauMaterializer.cs@@ -20,7 +20,7 @@ public static class PlanarPlateauMaterializerpublic static PlanarPlateauMaterializationResult Apply(BrepBody source, FaceId supportFace, PlanarPlateauContactPlan plan){PlanarPlateauMaterializationResult Fail(string message) => new(null, null, [], ["plateau-" + message]);- if (!source.Bindings.TryGetFaceBinding(supportFace, out var supportBinding) || !supportBinding.SameSense ||+ if (!source.Bindings.TryGetFaceBinding(supportFace, out var supportBinding) || !supportBinding.Orientation.IsAlignedWithSurface ||source.Geometry.GetSurface(supportBinding.SurfaceGeometryId).Plane is not { } plane ||(plane.Normal.ToVector() - plan.Frame.Normal.ToVector()).Length > 1e-10 ||Math.Abs((plan.Frame.Origin - plane.Origin).Dot(plane.Normal.ToVector())) > 1e-8)diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex 6816df0d..b589ee13 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -335,9 +335,9 @@ internal static class WebMeshBuildervar tessellation = BrepDisplayTessellator.Tessellate(body, new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64));if (!tessellation.IsSuccess) throw new InvalidOperationException(string.Join("; ", tessellation.Diagnostics.Select(item => item.Message)));var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>(); var ranges = new List<object>();- foreach (var raw in tessellation.Value.FacePatches.OrderBy(face => face.FaceId.Value))+ foreach (var face in tessellation.Value.FacePatches.OrderBy(face => face.FaceId.Value)){- var face = DisplayMeshOrientation.Orient(body, raw); var vertexOffset = positions.Count / 3; var triangleStart = indices.Count / 3;+ var vertexOffset = positions.Count / 3; var triangleStart = indices.Count / 3;positions.AddRange(face.Positions.SelectMany(point => new[] { point.X, point.Y, point.Z }));normals.AddRange(face.Normals.SelectMany(normal => new[] { normal.X, normal.Y, normal.Z }));indices.AddRange(face.TriangleIndices.Select(index => index + vertexOffset));diff --git a/docs/development/architecture/face-orientation-authority.md b/docs/development/architecture/face-orientation-authority.mdnew file mode 100644index 00000000..077c7474--- /dev/null+++ b/docs/development/architecture/face-orientation-authority.md@@ -0,0 +1,28 @@+# Face Orientation Authority++STEP `ADVANCED_FACE.same_sense` is source evidence, not Aetheris face-orientation authority.++The exact STEP importer first creates import-only `ImportedFacePatch` values with support geometry, normalized trims, topology, and `SourceFaceOrientationEvidence`. `StepFaceOrientationResolver` then builds deterministic face adjacency from shared edges and propagates a relative orientation from the lowest face ID in each connected component. Nonmanifold adjacency is rejected; contradictory propagation is diagnosed and remains ambiguous rather than guessed. The importer never mutates support-surface parameterization.++For a closed component, the resolver tessellates the locally consistent candidate only as a bounded divergence-theorem oracle. Positive signed volume is required for an outer shell; negative signed volume is required for an inner void shell. A whole component is flipped when its material role requires the opposite sign. Open shells retain local consistency with `DerivedLocallyConsistentGlobalUnknown`; a near-zero or unavailable closed-shell volume is `Ambiguous`. No source flag is promoted to global authority in either case.++The completed boundary is structural:++```text+ImportedFacePatch (no orientation)+ -> StepFaceOrientationResolver+ -> FaceGeometryBinding.Orientation : ResolvedFaceOrientation+ -> OrientedFacePatch report/provenance+```++`FaceGeometryBinding` deliberately has no `SameSense` property. Display tessellation, mass properties, section analysis, Continuum queries, and STEP export consume `ResolvedFaceOrientation`. The raw STEP flag remains only in `BrepBody.FaceOrientationReport` for diagnostics and import reporting. A disagreement produces `Importer.StepOrientation.SourceOrientationMismatch` and records the source entity, derived value, shell, evidence summary, and chosen action.++`BrepDisplayTessellator` projects canonical orientation once when it creates each `DisplayFaceMeshPatch`. Assembly and Web Runtime exporters consume that patch directly and must not invoke another orientation pass. STEP export serializes the canonical resolved orientation; it never copies provenance back as authority.++X1B makes boundary role and periodicity explicit. `FaceBoundaryRoleBinding` records which face-local loop is outer or inner; allocation order is not semantic. `SurfacePeriodicity` records admitted U/V periods and owns modulo-period equality. Full-period constant-coordinate loops derive winding from signed continuous period traversal, while sphere and non-full conical loops prefer support-relative 3D boundary evidence over seam-sensitive planar shoelace area.++STEP export chooses its boundary serialization route through a bounded JudgmentEngine policy: complete explicit roles win, authored order is a fallback only when role evidence is absent, and malformed partial evidence is rejected. The numerical winding calculation itself is deterministic and is not utility-scored.++Current limitation: the topology model can bind a pcurve to each coedge use, but STEP `SURFACE_CURVE`/`SEAM_CURVE` import does not yet populate those bindings, and singular pole/apex `VERTEX_LOOP`s are not yet materialized as explicit loop topology. Therefore X1B does not claim general pcurve or degenerate-boundary acceptance beyond the qualified corpus paths.++This boundary does not alter stable face IDs, source STEP entity provenance, semantic PMI associations, support surfaces, trims, or pcurve parameterization.diff --git a/docs/development/architecture/verification/m8-hole-loop-x1.md b/docs/development/architecture/verification/m8-hole-loop-x1.mdindex 9f213325..d5649054 100644--- a/docs/development/architecture/verification/m8-hole-loop-x1.md+++ b/docs/development/architecture/verification/m8-hole-loop-x1.md@@ -4,7 +4,7 @@**Edge sense is interpreted once. Every later layer consumes the same directed topology contract.**-`Edge.StartVertexId -> Edge.EndVertexId` is the canonical topology direction. A coedge reverses that pair exactly once through `DirectedEdgeUse.Resolve`. `EDGE_CURVE.same_sense` is curve-parameter sense only; it does not alter the topology edge or an `ORIENTED_EDGE` traversal. `ADVANCED_FACE.same_sense` is material-facing surface orientation only and never changes connectivity.+`Edge.StartVertexId -> Edge.EndVertexId` is the canonical topology direction. A coedge reverses that pair exactly once through `DirectedEdgeUse.Resolve`. `EDGE_CURVE.same_sense` is curve-parameter sense only; it does not alter the topology edge or an `ORIENTED_EDGE` traversal. Historical note: this milestone described `ADVANCED_FACE.same_sense` as material-facing authority. STEP-ORIENTATION-X1 supersedes that statement: the flag is retained only as source evidence, while canonical face orientation is derived from topology and geometry.A loop is connected when the end of each resolved use matches the next resolved use, including closing back to the first. Binding-aware gates also admit coincident, distinct vertices at a periodic seam. The currently supported circle forms are a one-edge full circle with coincident endpoints and the existing seam-plus-full-circle wall representation. Split arcs must be explicitly chained; unordered shared incidence is insufficient.diff --git a/docs/development/architecture/verification/profile-compose-inner-loop-x1.md b/docs/development/architecture/verification/profile-compose-inner-loop-x1.mdindex 34ffe79f..9a1d81a5 100644--- a/docs/development/architecture/verification/profile-compose-inner-loop-x1.md+++ b/docs/development/architecture/verification/profile-compose-inner-loop-x1.md@@ -8,7 +8,7 @@ The proven defect was producer-side trim binding. The section-stack emitter assiAfter the repair, the shallow-pocket analytic, in-memory, and reimported volumes agree at `3808 mm³` (floating-point result `3807.9999999999995`). The through-cut reimports at `3639.9999999999995 mm³`, matching `3640 mm³`; the raised pad remains `4319.999999999998 mm³` against analytic `4320 mm³`.-Canonical policy: topology edge start/end and `ORIENTED_EDGE.orientation` determine coedge traversal; `EDGE_CURVE.same_sense` only maps curve parameter direction to topology endpoints; `FACE_OUTER_BOUND`/`FACE_BOUND` carry explicit loop role; `FACE_BOUND.orientation` is retained as STEP source evidence; `ADVANCED_FACE.same_sense` applies once between support surface and face orientation. Import must not mutate `EDGE_LOOP` order to satisfy a local winding preference.+Canonical policy: topology edge start/end and `ORIENTED_EDGE.orientation` determine coedge traversal; `EDGE_CURVE.same_sense` only maps curve parameter direction to topology endpoints; `FACE_OUTER_BOUND`/`FACE_BOUND` carry explicit loop role; `FACE_BOUND.orientation` is retained as STEP source evidence. Historical note: the former statement that `ADVANCED_FACE.same_sense` applies once is superseded by STEP-ORIENTATION-X1; it is now cross-check evidence only, and the importer derives canonical face orientation from topology and geometry. Import must not mutate `EDGE_LOOP` order to satisfy a local winding preference.`Rect2` is available to the profile-authoring and composition source route with `Center` and `Size`. It derives stable `BottomLeft`, `BottomRight`, `TopRight`, `TopLeft`, `Bottom`, `Right`, `Top`, and `Left` guides. Profiles trace the derived sides through normal Profile IR, with provenance such as `concept:Rect2Layout.Base.Bottom`.diff --git a/docs/release/STEP-ORIENTATION-X1.md b/docs/release/STEP-ORIENTATION-X1.mdnew file mode 100644index 00000000..431883be--- /dev/null+++ b/docs/release/STEP-ORIENTATION-X1.md@@ -0,0 +1,92 @@+# STEP-ORIENTATION-X1 — Derived Face Orientation and `same_sense` Demotion++## Executive verdict++**Meaningful progression, not accepted.** The implemented path derives and projects face orientation once at STEP import, retains `same_sense` as cross-check evidence, and prevents downstream face bindings from exposing a raw-or-canonical boolean with ambiguous meaning. Hostile flags, void shells, open shells, nonmanifold rejection, Difference Engine, sheet-metal, PMI/identity, and the isolated NIST display-orientation corpus are qualified. Acceptance remains blocked by pre-existing/now-exposed NIST export-import volume instability on `STC-10`, `FTC-08`, `FTC-11`, and `CTC-02`, plus the intentional canonical-orientation hash changes that still require a reviewed snapshot re-baseline.++## Algorithm++1. Decode support surfaces and trims without applying `ADVANCED_FACE.same_sense`.+2. Preserve the source face ID, source surface ID, and source flag in `SourceFaceOrientationEvidence`.+3. Derive per-loop support-space winding, build deterministic per-shell adjacency through shared edges, and propagate from the smallest face ID. More than two incident faces is rejected as nonmanifold. Contradictory propagation is diagnosed and classified ambiguous; the independently derived support-boundary orientation is retained instead of guessing from the source flag.+4. Tessellate the locally consistent candidate as a bounded signed-volume oracle. Outer shells target positive signed volume. Inner void shells target negative signed volume. A required change flips the whole connected component.+5. Leave open shells locally consistent and globally unknown. Classify near-zero or unavailable closed-shell volume as ambiguous rather than trusting the source flag.+6. Cross-check each derived orientation with source evidence and emit `step-orientation-source-mismatch` warnings without changing the derived result.++The existing exact/qualified occupancy infrastructure remains the independent material-side authority for Continuum and FEA. X1 does not introduce another point-in-solid engine or mutate support parameterizations.++## Type boundary++```text+ImportedFacePatch+ FaceId + SurfaceGeometryId + SourceFaceOrientationEvidence+ (orientation absent)+ |+ v+StepFaceOrientationResolver+ |+ v+FaceGeometryBinding.Orientation : ResolvedFaceOrientation+OrientedFacePatch : qualification + provenance + comparison+```++Downstream canonical consumers are display tessellation, SurfaceMeshIR, mass properties, STEP export, CLI section analysis, Continuum boundary queries, Firmament selection/materialization, SheetMetal recognition, and Surfacing support selection. `FaceGeometryBinding.SameSense` no longer exists.++## Diagnostics and reporting++- `Importer.StepOrientation.SourceOrientationMismatch`+- `Importer.StepOrientation.ShellOrientationAmbiguous`+- `Importer.StepOrientation.NonManifoldOrientation`+- `Importer.StepOrientation.GlobalOrientationUnknown`+- `Importer.StepOrientation.OrientationPropagationConflict`++`aetheris analyze ... --json` now reports derived faces, source true/false/missing distribution, agreements, mismatches, ambiguous components, global flips, and qualification counts.++## Hostile fixtures++The focused suite exports a canonical Aetheris box, flips one `ADVANCED_FACE.same_sense`, and separately flips every face flag without changing topology or geometry. Both hostile imports produce the same canonical face orientations and signed volume as the trusted control. Mismatch diagnostics identify the corrupted evidence. A synthetic duplicated-face shell is rejected rather than guessed.++## Void, open-shell, and round-trip behavior++The `BREP_WITH_VOIDS` witness uses a box with a spherical cavity. The outer shell resolves to positive signed contribution and the inner shell to negative signed contribution. The open planar witness resolves local orientation but reports global orientation unknown. STEP export serializes canonical orientation, and reimport preserves topology and canonical orientation rather than reproducing hostile source flags.++## Cleanup++- Removed the raw `SameSense` property from face bindings.+- Replaced downstream reads with typed `ResolvedFaceOrientation`.+- Kept pcurve and `EDGE_CURVE.same_sense` handling intact; those are parameter/traversal mappings, not face orientation.+- Removed Web Runtime's second display-patch orientation pass.+- Preserved Assembly export's existing single-projection behavior.++## Validation++Qualified on 2026-09-22:++- STEP orientation semantics, hostile flags, void/open/nonmanifold, export projection: 29/29 passed.+- Difference Engine storage gates and line/arc mass witness: 10/10 passed.+- Chamfer CLI fixtures: 7/7 passed.+- Sheet metal: 99/99 passed.+- Firmament inline STEP, canonical construct safety, and advanced grammar/PMI identity: 86/86 passed.+- NIST display orientation corpus in isolation: 16/16 passed. `CTC-04` is structurally open and is now required to report `DerivedLocallyConsistentGlobalUnknown` rather than pretending to have an outward solid orientation.+- Three independent fresh-agent checks passed: one corrupted flag remains canonical with a mismatch diagnostic; an open shell makes no outwardness claim; and no second face-orientation application remains in Assembly/Web/tessellation.++Representative CLI corpus report (`aetheris analyze ... --json`):++| Fixture | Faces | Source true/false | Agree/mismatch | Qualification | Global flips |+| --- | ---: | ---: | ---: | --- | ---: |+| NIST CTC-01 | 117 | 63/54 | 115/2 | 117 derived-qualified | 0 |+| NIST FTC-06 | 187 | 102/85 | 182/5 | 187 derived-qualified | 0 |+| NIST CTC-04 | 484 | 99/385 | 3/481 | 484 local-only/global-unknown (open shell) | 0 |+| NIST STC-06 | 144 | 65/79 | not comparable | 144 ambiguous (one component) | 0 |++The STC-06 row is intentionally reported as unresolved rather than being counted as derived merely because its display path succeeds.++Full Kernel.Core qualification was attempted and stopped after it isolated the remaining blockers:++- `nist_stc_10_asme1_ap242-e2.stp`: export-import volume changed from approximately `197357` to `-52028.4`.+- `nist_ftc_11_asme1_ap242-e2.stp`: export-import volume changed from approximately `3989.48` to `-4389.53`.+- both admitted `FTC-08` variants and `CTC-02` also fail the existing enclosed-volume round-trip gate.+- audit snapshots report unchanged topology/diagnostic counts but changed canonical hashes on files whose emitted face orientations changed. These snapshots are deliberately not auto-approved while the round-trip volume gate is red.+- several display tests exceeded their execution budgets only during the concurrently scheduled full-project run; the dedicated 16-file display-orientation run passed in 1 minute 49 seconds.++The next isolated blocker is periodic/degenerate support-boundary winding through STEP export-import. The resolver reports exact shell/component/edge/loop evidence for propagation conflicts, so the remaining work is bounded and diagnosable; promoting source `same_sense` back to authority would hide rather than solve it.diff --git a/docs/release/STEP-ORIENTATION-X1B.md b/docs/release/STEP-ORIENTATION-X1B.mdnew file mode 100644index 00000000..9ec54207--- /dev/null+++ b/docs/release/STEP-ORIENTATION-X1B.md@@ -0,0 +1,82 @@+# STEP-ORIENTATION-X1B — Periodic and Degenerate Boundary Winding Repair++## Executive verdict++**Meaningful progression.** The four named X1 round-trip regressions now preserve every canonical face orientation across STEP export/re-import without restoring source `same_sense` authority. The complete 17-file NIST round-trip corpus passes. The milestone is not marked Accepted because STEP pcurve ingestion and explicit pole/apex `VERTEX_LOOP` preservation remain incomplete; claiming general seam-side and degenerate-boundary stability would exceed the evidence.++## Authority and policy++X1 remains unchanged:++- `ADVANCED_FACE.same_sense` is provenance and mismatch evidence only.+- `ResolvedFaceOrientation` is Aetheris authority.+- downstream geometry consumes the resolved value once.++JudgmentEngine was evaluated for the requested “multiple input conditions, one correct answer” policy. It is used at the STEP face-boundary export boundary:++1. complete explicit `FaceBoundaryRoleBinding` evidence is admissible and wins;+2. authored loop order is admissible only when no explicit role evidence exists;+3. partial, cross-face, or multiply-outer role evidence has no admissible candidate and export stops.++JudgmentEngine is not used for UV arithmetic. Period equivalence, unwrapping, and winding remain deterministic geometry rather than scored preference.++## Root causes and repairs++### Lost face-bound role++The exporter sorted `Face.LoopIds` and labeled the first result `FACE_OUTER_BOUND`. Imported loop IDs are allocation identity, not boundary role. On multi-loop faces this promoted a hole to the exterior while preserving every edge use, producing severe volume corruption.++`FaceBoundaryRoleBinding` now preserves outer/inner role per face/loop. Import records it, binding validation checks ownership, the orientation resolver preserves it, and the JudgmentEngine-backed exporter serializes the explicit outer bound first without changing loop identity or traversal.++### Full-period zero-area boundaries++FTC-11 cylinder faces contain one-edge full circles. Their continuous UV lift spans `+/-2pi` at constant axial coordinate, so ordinary shoelace area is exactly zero. The former fallback averaged the 3D circle samples to the cylinder axis and attempted to derive a radial support normal there. Tiny serialization noise selected different radial directions before and after round-trip.++`SurfacePeriodicity` now describes U/V periods for analytic and closed B-spline supports and provides `EquivalentModuloPeriod`. A full-period constant-secondary-coordinate boundary uses its signed unwrapped traversal directly. It is never classified from a singular averaged support normal.++### Sphere and cone seam sensitivity++STC-10 and FTC-08 first diverged on spherical loops whose edge topology and support frame were unchanged. Tiny direction components rounded through STEP serialization changed the chosen UV seam lift and reversed shoelace sign. CTC-02 showed the same class at conical apex/seam loops.++Sphere loops now prefer support-relative 3D boundary-normal evidence. Cone loops use signed full-period traversal when applicable and otherwise prefer support-relative boundary-normal evidence before seam-sensitive UV area. These choices are derived from edge-use traversal and support geometry, not file face flags.++## Original failures++| Case | Prior X1 status | First isolated cause | X1B final status |+| --- | --- | --- | --- |+| STC-10 | volume approximately `197357 -> -52028.4` | lost multi-loop role, then seam-sensitive sphere UV area | every face orientation preserved; `202864.773478 -> 202842.039837` |+| FTC-08 | negative/near-zero round-trip volume variants | lost multi-loop role, then seam-sensitive sphere UV area | every face orientation preserved; `505306.986523 -> 505504.056584` |+| FTC-11 | volume approximately `3989.48 -> -4389.53` | full-period cylinder loop had zero UV area and singular centroid-normal fallback | every face orientation preserved; `6861.467338 -> 6861.515022` |+| CTC-02 | enclosed-volume gate failed/open topology | conical seam/apex UV lift changed across serialization | every local face orientation preserved; remains open/global-unknown; `0 -> 0` signed closed-volume claim |+| STC-06 | ambiguous | contradictory/insufficient boundary evidence | remains explicitly `Ambiguous`; not promoted |++The changed absolute starting volumes reflect the corrected X1B derivation on the initial import, not a post-import mass repair. Mass properties continue to expose the resolved topology and do not flip faces.++## Representative traces++FTC-11 face 3 is a cylinder with two single-edge full-circle loops. Before repair, loop 7 changed support baseline `True -> False` even though the support, edge use, vertices, `ORIENTED_EDGE`, circle, and trim were equivalent. The UV trace was a constant-V line with signed U span of one period. X1B classifies that edge-use trace by its signed period traversal, so both imports choose the same baseline.++STC-10 face 193 is a spherical three-edge loop. Its support and topology were byte-equivalent at semantic precision; a source circle normal component of approximately `3.47e-15` serialized as zero, selecting the other UV seam lift. Support-relative 3D boundary evidence is invariant to that harmless rounding and now yields the same orientation.++Imported bodies currently contain zero retained pcurve bindings for these corpus witnesses. This is why the report does not claim pcurve/seam-side acceptance: `SURFACE_CURVE`/`SEAM_CURVE` import still unwraps to the authoritative 3D curve and discards the pcurve list.++## Validation++- X1/X1B focused orientation and boundary-policy suite: 20/20 passed, including explicit-role selection, absent-evidence fallback, partial-evidence rejection, modulo-period equality, and STC-06 ambiguity.+- NIST STEP export/import round-trip corpus: 17/17 passed.+- NIST display-orientation corpus: 16/16 passed.+- Difference Engine, line/arc mass, and selected PMI/stable-identity suites: 96/96 passed.+- Chamfer CLI: 7/7 passed.+- Sheet metal: 99/99 passed.+- Full `Aetheris.slnx` build: succeeded with 0 errors; only existing WebAssembly/analyzer warnings were reported.+- A serialized full-solution test attempt did not complete: it emitted no event after entering `Aetheris.CLI.Tests` for more than five minutes and was stopped. The bounded CLI fixture suite above is the available CLI regression evidence; this report does not represent the aggregate solution test run as passing.+- Ground-truth CLI inspection of FTC-11 succeeds and reports one enclosed manifold with 42 faces, 104 edges, and 72 vertices.+- Fresh-agent periodic diagnosis identified the full-wrap cylinder zero-area/singular-normal failure and rejected `same_sense` repair.+- Fresh-agent degenerate review confirmed that zero 3D length can carry nonzero UV closure and identified the remaining pcurve/`VERTEX_LOOP` loss.+- Fresh-agent code review rejected per-face negative-volume flipping and located support-boundary derivation/export role ownership as the correct layer.++Canonical NIST hashes remain unrebaselined pending full acceptance of pcurve and explicit pole/apex topology preservation.++## Remaining bounded blocker++The topology model already supports per-coedge pcurves, but STEP import does not populate them. Spherical and conical-apex `VERTEX_LOOP`s are still intentionally omitted, and export preflight rejects several explicit zero-length edge representations. Completing those paths requires a separately bounded ingestion/export change with hostile seam-side and pole/apex fixtures; it must not be simulated by source `same_sense`, random face flips, or snapshot updates.diff --git a/tools/Aetheris.Continuum.M4/Program.cs b/tools/Aetheris.Continuum.M4/Program.csindex 2106d512..577ef207 100644--- a/tools/Aetheris.Continuum.M4/Program.cs+++ b/tools/Aetheris.Continuum.M4/Program.cs@@ -60,7 +60,7 @@ RunData Run(string orientation,Transform3D transform,int n,bool fine)object RunAdversarial(){- var source=BrepPrimitives.CreateBox(2,1.5,1).Value!;var bindings=new BrepBindingModel();foreach(var e in source.Bindings.EdgeBindings)bindings.AddEdgeBinding(e);foreach(var f in source.Bindings.FaceBindings)bindings.AddFaceBinding(f with{SameSense=!f.SameSense});+ var source=BrepPrimitives.CreateBox(2,1.5,1).Value!;var bindings=new BrepBindingModel();foreach(var e in source.Bindings.EdgeBindings)bindings.AddEdgeBinding(e);foreach(var f in source.Bindings.FaceBindings)bindings.AddFaceBinding(f with{Orientation=f.Orientation.Reversed()});var body=new BrepBody(source.Topology,source.Geometry,bindings,vertexPoints:null,shellRepresentation:source.ShellRepresentation);var transform=Transform3D.CreateRotationY(.27);var region=new ExactBrepBoxContinuumRegion(new("m4-box"),2,1.5,1,transform);var assoc=new CirBrepAssociation(region.Id,"reversed-face-orientation-box",body.ShellRepresentation!.OuterShellId.Value.ToString());var shell=new WholeShellBoundaryQuery(body,assoc,transform);var composer=new WholePartCutCellComposer(region,shell);var evidence=shell.Faces.Select(f=>composer.Compose(default,Around(Average(f.OuterTrimVertices),1e-3)).Contributors.Single().MaterialSide).ToArray();