Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Materialize analytic whole-loop fillet shells
Yuechen Li52fd5f0e2a75
diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.csindex a4e53d39..b23cc013 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs@@ -308,8 +308,11 @@ public sealed class ProfileBoundaryChamferTestsconst string fillet = "Modify Body { EdgeFinish TopRound { Target: Bracket.Outer On: Top Kind: Fillet Radius: 4mm } }";Assert.True(ProfileBoundaryChamferSourceBinder.TryBindFillet(fillet, CurvedProfile(), "Bracket", out var filletTarget, out var radius, out var clearance, out var filletDiagnostic), filletDiagnostic);var filletPlan = ProfileFilletShellPlanner.TryPlan(CurvedProfile(), filletTarget!, radius, clearance);- Assert.False(filletPlan.Succeeded);- Assert.StartsWith("ProfileBoundaryFilletArcMaterializationNotImplemented:station=ReflexSmall:scope=Target:segment=ReflexSmallArc:sourceFamily=Arc:material=Reflex:sourceRadius=2:finishRadius=4:radiusRelation=LessThan:planner=ArcFilletTorusPlan:surfaceFamily=Torus:regularity=Regular:admission=Supported", Assert.Single(filletPlan.Diagnostics));+ Assert.True(filletPlan.Succeeded, string.Join(Environment.NewLine, filletPlan.Diagnostics));+ Assert.NotNull(filletPlan.Body);+ Assert.Equal(1, filletPlan.Body!.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Torus));+ Assert.Equal(0, filletPlan.Body.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots));+ Assert.True(BrepMassProperties.Evaluate(filletPlan.Body).IsEnclosed);}[Fact]diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.csindex d8873449..5dd802fa 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.cs@@ -18,7 +18,7 @@ public sealed class ProfileEdgeFinishAnalyticPolicyTestspublic static IEnumerable<object[]> FilletRows(){- yield return Row("ConvexSharp", ProfileEdgeFinishSourceFamily.SharpLineLine, ProfileEdgeFinishMaterialSide.Convex, 0d, "ConvexSharpSphereJunctionPlan", ProfileEdgeFinishSurfaceFamily.Sphere, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported);+ yield return Row("ConvexSharp", ProfileEdgeFinishSourceFamily.SharpLineLine, ProfileEdgeFinishMaterialSide.Convex, 0d, "ConvexSharpCylinderMiterPlan", ProfileEdgeFinishSurfaceFamily.Cylinder, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported);yield return Row("ConvexSmall", ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex, 2d, "ArcFilletSpindleRejected", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.Invalid, ProfileEdgeFinishAdmission.UnsupportedWithTypedDiagnostic);yield return Row("ConvexMedium", ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex, 4d, "ArcFilletSphereLimitPlan", ProfileEdgeFinishSurfaceFamily.Sphere, ProfileEdgeFinishRegularity.BoundedDegenerate, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy);yield return Row("ConvexLarge", ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex, 8d, "ArcFilletTorusPlan", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.InteropSensitive, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy);diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.csindex df15ff5f..c7b60fbd 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs@@ -109,7 +109,7 @@ public sealed class ProfileEdgeFinishMixedShellPlanTests}[Fact]- public void SevenStationFillet_RejectsNaiveContactCompositionBeforeTopologyAtTheFirstSharpStation()+ public void SevenStationFillet_ConsumesContactPlanAndEmitsOneManifoldAnalyticShell(){var (profile, target) = ReleaseCard("profile-edgefinish-chimera-fillet.firmament", ProfileEdgeFinishKind.Fillet);var mixed = ProfileEdgeFinishMixedShellPlanner.TryPlan(profile, target, ProfileEdgeFinishKind.Fillet, 4d);@@ -117,8 +117,56 @@ public sealed class ProfileEdgeFinishMixedShellPlanTestsAssert.True(mixed.Succeeded, string.Join(Environment.NewLine, mixed.Diagnostics));var contacts = ProfileFilletContactShellPlanner.TryPlan(profile, target, Assert.IsType<ProfileEdgeFinishMixedShellPlan>(mixed.Plan));- Assert.False(contacts.Succeeded);- Assert.Equal("ProfileFilletContactSharpJunctionComponentRequired:vertex=Outer.Bottom.Start", Assert.Single(contacts.Diagnostics));+ Assert.True(contacts.Succeeded, string.Join(Environment.NewLine, contacts.Diagnostics));+ var contactPlan = Assert.IsType<ProfileFilletContactShellPlan>(contacts.Plan);+ Assert.Equal(17, contactPlan.SideContactChains.Count);+ Assert.Equal(17, contactPlan.SourceSideTrims.Count);+ Assert.True(ProfileFilletContactGraphValidator.Validate(contactPlan).Succeeded);++ var emitted = ProfileFilletContactShellMaterializer.TryMaterialize(profile, target,+ Assert.IsType<ProfileEdgeFinishMixedShellPlan>(mixed.Plan), contactPlan);++ Assert.True(emitted.Succeeded, string.Join(Environment.NewLine, emitted.Diagnostics));+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(emitted.Body);+ AssertClosedManifold(body);+ Assert.Equal(0, body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots));+ Assert.Equal(6, body.Geometry.Curves.Count(curve => curve.Value.Kind == CurveGeometryKind.Ellipse3));+ var ellipseEdges = body.Bindings.EdgeBindings+ .Where(binding => body.Geometry.GetCurve(binding.CurveGeometryId).Kind == CurveGeometryKind.Ellipse3)+ .ToArray();+ Assert.Equal(6, ellipseEdges.Length);+ foreach (var ellipseEdge in ellipseEdges)+ {+ var adjacentLoops = body.Topology.Coedges.Where(coedge => coedge.EdgeId == ellipseEdge.EdgeId).Select(coedge => coedge.LoopId).ToHashSet();+ var adjacentFaces = body.Topology.Faces.Where(face => face.LoopIds.Any(adjacentLoops.Contains)).ToArray();+ Assert.Equal(2, adjacentFaces.Length);+ Assert.All(adjacentFaces, face => Assert.Equal(SurfaceGeometryKind.Cylinder,+ body.Geometry.GetSurface(body.Bindings.GetFaceBinding(face.Id).SurfaceGeometryId).Kind));+ }+ Assert.Equal(0, Assert.IsType<SemanticTopologyCorrespondence>(emitted.Correspondence).Descendants.Count(descendant =>+ descendant.Role is SemanticTopologyRole.StartTerminationFace or SemanticTopologyRole.EndTerminationFace));+ }++ [Theory]+ [InlineData("profile-edgefinish-chimera-fillet.firmament", 1, 5)]+ [InlineData("profile-edgefinish-chimera-reflex-sphere-compat.firmament", 2, 4)]+ public void SevenStationFillet_ExportsDeterministicallyWithExpectedSphereTorusDelta(string fixture, int spheres, int tori)+ {+ var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/FirmamentV2/Canonical/valid/{fixture}");+ var first = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));+ var second = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));++ Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics.Select(diagnostic => diagnostic.Message)));+ Assert.Equal(first.Value.Export.StepText, second.Value.Export.StepText);+ var imported = Step242Importer.ImportBody(first.Value.Export.StepText);+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(diagnostic => diagnostic.Message)));+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(imported.Value);+ AssertClosedManifold(body);+ Assert.Equal(spheres, body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.Sphere));+ Assert.Equal(tori, body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.Torus));+ Assert.Equal(6, body.Geometry.Curves.Count(curve => curve.Value.Kind == CurveGeometryKind.Ellipse3));+ Assert.Equal(0, body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots));}private static (ResolvedProfile2D Profile, ProfileBoundaryChamferTarget Target) ReleaseCard(string fixture, ProfileEdgeFinishKind kind)@@ -132,4 +180,16 @@ public sealed class ProfileEdgeFinishMixedShellPlanTestsAssert.True(bound, diagnostic);return (profile, Assert.IsType<ProfileBoundaryChamferTarget>(target));}++ private static void AssertClosedManifold(Aetheris.Kernel.Core.Brep.BrepBody body)+ {+ Assert.Single(body.Topology.Bodies);+ Assert.Single(body.Topology.Shells);+ foreach (var edge in body.Topology.Edges)+ {+ var uses = body.Topology.Coedges.Where(coedge => coedge.EdgeId == edge.Id).ToArray();+ Assert.Equal(2, uses.Length);+ Assert.NotEqual(uses[0].IsReversed, uses[1].IsReversed);+ }+ }}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.csindex 5544a847..f2780b33 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs@@ -845,9 +845,18 @@ public static class ProfileFilletShellPlannervar loop = profile.Loops.SingleOrDefault(x => x.Name == target.LoopId);if (loop is null) return Fail("ProfileBoundaryFilletLoopUnknown");if (!loop.IsOuter || profile.Loops.Count != 1) return Fail("ProfileBoundaryFilletInnerLoopUnsupported");+ if (target.ChainKind == ProfileBoundaryChamferChainKind.ClosedLoop)+ {+ var mixed = ProfileEdgeFinishMixedShellPlanner.TryPlan(profile, target, ProfileEdgeFinishKind.Fillet, radius);+ if (!mixed.Succeeded || mixed.Plan is null)+ return Fail(mixed.Diagnostics.FirstOrDefault() ?? "ProfileFilletContactShellPlanningFailed");+ var contacts = ProfileFilletContactShellPlanner.TryPlan(profile, target, mixed.Plan);+ if (!contacts.Succeeded || contacts.Plan is null)+ return Fail(contacts.Diagnostics.FirstOrDefault() ?? "ProfileFilletContactShellPlanningFailed");+ return ProfileFilletContactShellMaterializer.TryMaterialize(profile, target, mixed.Plan, contacts.Plan);+ }if (loop.Segments.Any(segment => segment.Geometry is not LineArcLineSegment2D))return Fail(ProfileBoundaryCurvedFinishDiagnostic.ForFirstSelectedArc(profile, loop, target, radius, "Fillet") ?? "ProfileBoundaryFilletSegmentKindUnsupported");- if (target.ChainKind == ProfileBoundaryChamferChainKind.ClosedLoop) return Fail("ProfileBoundaryFilletLoopTopologyNotMaterialized");if (target.SegmentIds.Count != 2) return Fail("ProfileBoundaryFilletJunctionTopologyNotMaterialized");if (!double.IsFinite(radius) || radius <= Tol) return Fail("ProfileBoundaryFilletRadiusMustBePositive");if (!double.IsFinite(clearance) || clearance <= Tol) return Fail("ProfileBoundaryFilletEndClearanceMustBePositive");diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.csindex 08d7b813..102c6a1f 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.cs@@ -82,7 +82,7 @@ public static class ProfileEdgeFinishAnalyticPolicy_ => 100d, _ => "Requires Convex ArcDerived Rs > F."),new("ChamferReflexCone", c => Is(c, ProfileEdgeFinishKind.Chamfer, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Reflex),_ => 100d, _ => "Requires Reflex ArcDerived station."),- new("FilletConvexSharpSphere", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.SharpLineLine, ProfileEdgeFinishMaterialSide.Convex),+ new("FilletConvexSharpMiter", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.SharpLineLine, ProfileEdgeFinishMaterialSide.Convex),_ => 100d, _ => "Requires sharp convex station."),new("FilletReflexSharpSphereCompatibility", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.SharpLineLine, ProfileEdgeFinishMaterialSide.Reflex) && c.ReflexJunctionStyle == ProfileReflexJunctionStyle.SphereSeamCompatibility,_ => 95d, _ => "Requires sharp reflex SphereSeamCompatibility override."),@@ -104,7 +104,7 @@ public static class ProfileEdgeFinishAnalyticPolicy"ChamferConvexCollapsedOffset" => Policy(c, relation, "ArcChamferCollapsedOffsetRejected", ProfileEdgeFinishSurfaceFamily.Cone, ProfileEdgeFinishRegularity.Invalid, ProfileEdgeFinishAdmission.UnsupportedWithTypedDiagnostic, utility, rejected, diagnostic: "ProfileBoundaryChamferCollapsedOffsetInvalid"),"ChamferConvexApex" => Policy(c, relation, "ArcChamferApexPlan", ProfileEdgeFinishSurfaceFamily.Cone, ProfileEdgeFinishRegularity.BoundedDegenerate, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy, utility, rejected),"ChamferConvexCone" or "ChamferReflexCone" => Policy(c, relation, "ArcChamferConePlan", ProfileEdgeFinishSurfaceFamily.Cone, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported, utility, rejected),- "FilletConvexSharpSphere" => Policy(c, relation, "ConvexSharpSphereJunctionPlan", ProfileEdgeFinishSurfaceFamily.Sphere, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported, utility, rejected),+ "FilletConvexSharpMiter" => Policy(c, relation, "ConvexSharpCylinderMiterPlan", ProfileEdgeFinishSurfaceFamily.Cylinder, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported, utility, rejected),"FilletReflexSharpSphereCompatibility" => Policy(c, relation, "ReflexSharpSphereSeamCompatibilityPlan", ProfileEdgeFinishSurfaceFamily.Sphere, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy, utility, rejected, compatibility: "SphereSeamCompatibility"),"FilletReflexSharpExactRolling" => Policy(c, relation, "ReflexSharpExactRollingPlan", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.InteropSensitive, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy, utility, rejected, torus: ProfileEdgeFinishTorusRegime.Horn, major: c.FinishSize, minor: c.FinishSize, compatibility: "SphereSeamCompatibility"),"FilletConvexSpindle" => Policy(c, relation, "ArcFilletSpindleRejected", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.Invalid, ProfileEdgeFinishAdmission.UnsupportedWithTypedDiagnostic, utility, rejected, torus: ProfileEdgeFinishTorusRegime.Spindle, major: c.FinishSize - c.SourceRadius, minor: c.FinishSize, diagnostic: "ProfileBoundaryFilletSpindlePatchInvalid"),diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.csnew file mode 100644index 00000000..58a12952--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.cs@@ -0,0 +1,439 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>+/// Production consumer of the X7 contact/incidence plan. All vertices and+/// shared edges are allocated by stable planned identity before their face+/// uses are emitted; faces never rediscover coincident topology.+/// </summary>+public static class ProfileFilletContactShellMaterializer+{+ private const double Tolerance = 1e-8;++ public static ProfileFilletShellPlanResult TryMaterialize(+ ResolvedProfile2D profile,+ ProfileBoundaryChamferTarget target,+ ProfileEdgeFinishMixedShellPlan mixed,+ ProfileFilletContactShellPlan contacts)+ {+ ProfileFilletShellPlanResult Fail(string diagnostic) => new(false, null, null, null, null, [diagnostic]);+ if (target.Side != ProfileBoundaryChamferSide.Top) return Fail("ProfileFilletContactShellBottomNotImplemented");+ if (mixed.FinishKind != ProfileEdgeFinishKind.Fillet) return Fail("ProfileFilletContactShellFilletPlanRequired");+ if (!ReferenceEquals(target, contacts.Target) && target.StableId != contacts.Target.StableId) return Fail("ProfileFilletContactShellTargetMismatch");+ var contactValidation = ProfileFilletContactGraphValidator.Validate(contacts);+ if (!contactValidation.Succeeded) return Fail(contactValidation.Diagnostics[0]);+ var loop = profile.Loops.SingleOrDefault(candidate => candidate.Name == target.LoopId);+ if (loop is null || loop.Segments.Count != mixed.OrderedPatches.Count) return Fail("ProfileFilletContactShellProfileMismatch");+ var area = SignedArea(loop);+ if (Math.Abs(area) <= Tolerance) return Fail("ProfileFilletContactShellProfileDegenerate");++ var frame = profile.EffectiveConstructionPlane;+ var lowerDepth = profile.LocalStartDepth ?? -1d;+ var capDepth = profile.LocalEndDepth ?? 1d;+ var transitionDepth = capDepth - mixed.FinishSize;+ var radius = mixed.FinishSize;+ var capOut = frame.AxisZ;+ var axialInto = -capOut.ToVector();+ var count = loop.Segments.Count;+ var classifications = ProfileJunctionClassifier.Classify(profile, loop)+ .ToDictionary(item => (item.PredecessorSegmentId, item.SuccessorSegmentId));+ var junctions = new Junction[count];++ for (var i = 0; i < count; i++)+ {+ var previousIndex = (i + count - 1) % count;+ var previous = loop.Segments[previousIndex];+ var current = loop.Segments[i];+ var source = frame.ToWorld(Start(current.Geometry), capDepth);+ var side = frame.ToWorld(Start(current.Geometry), transitionDepth);+ var cap = CapPoint(current.Geometry, atEnd: false, area, radius, capDepth, frame);+ var incomingCenter = RollingCenter(previous.Geometry, atEnd: true, area, radius, transitionDepth, frame);+ var outgoingCenter = RollingCenter(current.Geometry, atEnd: false, area, radius, transitionDepth, frame);+ if (previous.Geometry is not LineArcLineSegment2D previousLine || current.Geometry is not LineArcLineSegment2D currentLine)+ {+ junctions[i] = Junction.Smooth(source, side, cap, incomingCenter, outgoingCenter);+ continue;+ }++ var classification = classifications[(previous.Name, current.Name)];+ var ta = Direction(previousLine, frame);+ var na = Inward(previousLine, area, frame);+ var nb = Inward(currentLine, area, frame);+ var depth = source + axialInto * radius;+ if (classification.Classification == ProfileJunctionKind.ConvexProfileJunction)+ {+ var center = source + na.ToVector() * radius + nb.ToVector() * radius + axialInto * radius;+ var capJunction = center + capOut.ToVector() * radius;+ var majorAxis = Direction3D.Create(depth - center);+ var planeNormal = Direction3D.Create(majorAxis.ToVector().Cross(capOut.ToVector()));+ junctions[i] = new(JunctionKind.ConvexMiter, source, depth, depth, depth, depth, depth,+ capJunction, capJunction, center, center, center, classification.VertexId, majorAxis, planeNormal);+ }+ else if (classification.Classification == ProfileJunctionKind.ReflexProfileJunction && target.ReflexJunctionStyle == ProfileReflexJunctionStyle.SphereSeamCompatibility)+ {+ var center = source + na.ToVector() * radius + nb.ToVector() * radius + axialInto * radius;+ var capJunction = center + capOut.ToVector() * radius;+ var sideA = center - na.ToVector() * radius;+ var sideB = center - nb.ToVector() * radius;+ junctions[i] = Junction.Spherical(JunctionKind.ReflexCompatibilitySphere, source, depth, depth, depth,+ sideA, sideB, capJunction, center, center, center, classification.VertexId);+ }+ else if (classification.Classification == ProfileJunctionKind.ReflexProfileJunction)+ {+ var centerA = depth + na.ToVector() * radius;+ var centerB = depth + nb.ToVector() * radius;+ var capA = source + na.ToVector() * radius;+ var capB = source + nb.ToVector() * radius;+ junctions[i] = new(JunctionKind.ReflexHornTorus, source, depth, depth, depth, depth, depth, capA, capB,+ centerA, centerB, depth, classification.VertexId, na, nb);+ }+ else return Fail($"ProfileFilletContactShellSharpJunctionUnsupported:vertex={classification.VertexId}:kind={classification.Classification}");+ }++ var builder = new TopologyBuilder();+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var points = new Dictionary<VertexId, Point3D>();+ var vertices = new Dictionary<string, VertexId>(StringComparer.Ordinal);+ var edges = new Dictionary<string, EdgeId>(StringComparer.Ordinal);+ var edgeUses = new Dictionary<EdgeId, List<bool>>();+ var descendants = new List<SemanticTopologyDescendant>();+ var curveId = 1;+ var surfaceId = 1;++ VertexId Vertex(string key, Point3D point)+ {+ if (vertices.TryGetValue(key, out var existing)) return existing;+ var vertex = builder.AddVertex(); vertices.Add(key, vertex); points.Add(vertex, point); return vertex;+ }+ EdgeId Edge(string key, VertexId start, VertexId end, CurveGeometry curve, ParameterInterval trim, bool sameSense)+ {+ if (edges.TryGetValue(key, out var existing)) return existing;+ if (start == end || (points[end] - points[start]).Length <= Tolerance)+ throw new InvalidOperationException($"ProfileFilletContactShellZeroLengthEdge:edge={key}");+ var edge = builder.AddEdge(start, end); edges.Add(key, edge);+ var curveGeometry = new CurveGeometryId(curveId++); geometry.AddCurve(curveGeometry, curve);+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edge, curveGeometry, trim, sameSense));+ edgeUses.Add(edge, []);+ return edge;+ }+ EdgeId LineEdge(string key, VertexId start, VertexId end) => Edge(key, start, end,+ CurveGeometry.FromLine(new Line3Curve(points[start], Direction3D.Create(points[end] - points[start]))),+ new ParameterInterval(0d, (points[end] - points[start]).Length), true);+ EdgeId ArcEdge(string key, VertexId start, VertexId end, Point3D center)+ {+ if (edges.TryGetValue(key, out var existing)) return existing;+ var x = points[start] - center; var y = points[end] - center;+ var normal = x.Cross(y);+ if (normal.Length <= Tolerance) throw new InvalidOperationException($"ProfileFilletContactShellArcDegenerate:edge={key}");+ var angle = Math.Acos(Math.Clamp(x.Dot(y) / (x.Length * y.Length), -1d, 1d));+ return Edge(key, start, end, CurveGeometry.FromCircle(new Circle3Curve(center, Direction3D.Create(normal), x.Length, Direction3D.Create(x))),+ new ParameterInterval(0d, angle), true);+ }+ EdgeId EllipseEdge(string key, VertexId start, VertexId end, Point3D center,+ Direction3D majorAxis, Direction3D planeNormal, double minorRadius) => Edge(key, start, end,+ CurveGeometry.FromEllipse(new Ellipse3Curve(center, planeNormal, minorRadius * Math.Sqrt(2d), minorRadius, majorAxis)),+ new ParameterInterval(0d, Math.PI / 2d), true);+ Use UseFrom(EdgeId edge, VertexId start)+ {+ var reverse = builder.Model.Edges.Single(item => item.Id == edge).StartVertexId != start;+ return new(edge, reverse);+ }+ FaceId Face(string stableId, IReadOnlyList<Use> uses, SurfaceGeometry surface, SemanticTopologyRole role, string source)+ {+ if (uses.Count < 3) throw new InvalidOperationException($"ProfileFilletContactShellFaceBoundaryInvalid:face={stableId}");+ var loopId = builder.AllocateLoopId(); var coedges = uses.Select(_ => builder.AllocateCoedgeId()).ToArray();+ for (var index = 0; index < uses.Count; index++)+ {+ var use = uses[index]; edgeUses[use.Edge].Add(use.Reverse);+ builder.AddCoedge(new Coedge(coedges[index], use.Edge, loopId, coedges[(index + 1) % uses.Count], coedges[(index + uses.Count - 1) % uses.Count], use.Reverse));+ }+ builder.AddLoop(new Loop(loopId, coedges)); var face = builder.AddFace([loopId]);+ var surfaceGeometry = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(surfaceGeometry, surface);+ bindings.AddFaceBinding(new FaceGeometryBinding(face, surfaceGeometry, true));+ descendants.Add(new(stableId, "Face", role, source, Face: face, ParentStableId: target.StableId));+ return face;+ }++ try+ {+ var lowerVertices = new VertexId[count];+ var sideStarts = new VertexId[count]; var sideEnds = new VertexId[count];+ var capStarts = new VertexId[count]; var capEnds = new VertexId[count];+ var bottomEdges = new EdgeId[count]; var sideContacts = new EdgeId[count]; var capContacts = new EdgeId?[count];+ for (var i = 0; i < count; i++)+ {+ var next = (i + 1) % count;+ lowerVertices[i] = Vertex($"source-vertex:{i}:lower", frame.ToWorld(Start(loop.Segments[i].Geometry), lowerDepth));+ sideStarts[i] = Vertex($"component:{i}:side:start", junctions[i].OutgoingSide);+ sideEnds[i] = Vertex($"component:{i}:side:end", junctions[next].IncomingSide);+ capStarts[i] = Vertex($"component:{i}:cap:start", junctions[i].OutgoingCap);+ capEnds[i] = Vertex($"component:{i}:cap:end", junctions[next].IncomingCap);+ bottomEdges[i] = ProfileEdge($"source:{i}:lower", loop.Segments[i].Geometry, lowerVertices[i],+ Vertex($"source-vertex:{next}:lower", frame.ToWorld(End(loop.Segments[i].Geometry), lowerDepth)), lowerDepth, frame);+ var plannedSide = contacts.SideContactChains[i].OrderedContacts.OfType<ProfileFilletSideContactEdge>().Single();+ sideContacts[i] = loop.Segments[i].Geometry is LineArcCircularArc2D+ ? Edge(plannedSide.StableId, sideStarts[i], sideEnds[i], plannedSide.Curve, plannedSide.Trim, plannedSide.TraversesWithCurveParameter)+ : ProfileEdge(plannedSide.StableId, loop.Segments[i].Geometry, sideStarts[i], sideEnds[i], transitionDepth, frame);+ var inset = Offset(loop.Segments[i].Geometry, area, radius);+ if (inset is not null)+ {+ var plannedCap = contacts.OrderedCapContacts[i];+ capContacts[i] = loop.Segments[i].Geometry is LineArcCircularArc2D+ ? Edge(plannedCap.StableId, capStarts[i], capEnds[i], plannedCap.Curve, plannedCap.Trim, plannedCap.TraversesWithCurveParameter)+ : ProfileEdge(plannedCap.StableId, inset, capStarts[i], capEnds[i], capDepth, frame);+ }+ }++ EdgeId ProfileEdge(string key, LineArcProfileCurve2D curve, VertexId a, VertexId b, double depth, ConstructionPlane constructionPlane)+ {+ if (curve is LineArcLineSegment2D) return LineEdge(key, a, b);+ var arc = (LineArcCircularArc2D)curve;+ return Edge(key, a, b, CurveGeometry.FromCircle(new Circle3Curve(constructionPlane.ToWorld(arc.Center, depth), constructionPlane.AxisZ, arc.Radius, constructionPlane.AxisX)),+ new ParameterInterval(Math.Min(arc.StartAngleRadians, arc.StartAngleRadians + arc.SweepAngleRadians), Math.Max(arc.StartAngleRadians, arc.StartAngleRadians + arc.SweepAngleRadians)), arc.SweepAngleRadians >= 0d);+ }++ var incomingInterfaces = new EdgeId[count]; var outgoingInterfaces = new EdgeId[count];+ var supportIncoming = new EdgeId?[count]; var supportOutgoing = new EdgeId?[count];+ var junctionCap = new EdgeId?[count]; var junctionSide = new EdgeId?[count];+ for (var i = 0; i < count; i++)+ {+ var previous = (i + count - 1) % count;+ var junction = junctions[i];+ var incomingPatchSide = junction.Kind == JunctionKind.ReflexCompatibilitySphere+ ? Vertex($"junction:{i}:incoming-patch-side", junction.IncomingPatchSide)+ : sideEnds[previous];+ var outgoingPatchSide = junction.Kind == JunctionKind.ReflexCompatibilitySphere+ ? Vertex($"junction:{i}:outgoing-patch-side", junction.OutgoingPatchSide)+ : sideStarts[i];+ incomingInterfaces[i] = junction.Kind == JunctionKind.ConvexMiter+ ? EllipseEdge($"junction:{i}:convex-miter", incomingPatchSide, capEnds[previous], junction.SurfaceCenter, junction.MajorStart, junction.MajorEnd, radius)+ : ArcEdge($"junction:{i}:incoming-interface", incomingPatchSide, capEnds[previous], junction.IncomingCenter);+ outgoingInterfaces[i] = junction.Kind is JunctionKind.Smooth or JunctionKind.ConvexMiter+ ? incomingInterfaces[i]+ : ArcEdge($"junction:{i}:outgoing-interface", capStarts[i], outgoingPatchSide, junction.OutgoingCenter);+ if (junction.HasSupportPatch)+ {+ var depth = Vertex($"junction:{i}:depth", junction.Depth);+ supportIncoming[i] = LineEdge($"junction:{i}:incoming-support", incomingPatchSide, depth);+ supportOutgoing[i] = LineEdge($"junction:{i}:outgoing-support", depth, outgoingPatchSide);+ junctionSide[i] = ArcEdge($"junction:{i}:sphere-side", outgoingPatchSide, incomingPatchSide, junction.SurfaceCenter);+ }+ if (junction.Kind == JunctionKind.ReflexHornTorus)+ junctionCap[i] = ArcEdge($"junction:{i}:cap-contact", capEnds[previous], capStarts[i], junction.Source);+ }++ Face($"{target.StableId}:bottom-cap", Enumerable.Range(0, count).Reverse().Select(i => UseFrom(bottomEdges[i], lowerVertices[(i + 1) % count])).ToArray(),+ SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), lowerDepth), Direction3D.Create(-frame.AxisZ.ToVector()), frame.AxisX)),+ SemanticTopologyRole.BottomFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");++ var topUses = new List<Use>();+ for (var i = 0; i < count; i++)+ {+ if (capContacts[i] is { } capEdge) topUses.Add(UseFrom(capEdge, capStarts[i]));+ var next = (i + 1) % count;+ if (junctionCap[next] is { } capJunction) topUses.Add(UseFrom(capJunction, capEnds[i]));+ }+ Face($"{target.StableId}:top-cap", topUses,+ SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), capDepth), frame.AxisZ, frame.AxisX)),+ SemanticTopologyRole.TopFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");++ for (var i = 0; i < count; i++)+ {+ var next = (i + 1) % count;+ var startDepth = junctions[i].ParentHasSupport ? Vertex($"junction:{i}:depth", junctions[i].Depth) : sideStarts[i];+ var endDepth = junctions[next].ParentHasSupport ? Vertex($"junction:{next}:depth", junctions[next].Depth) : sideEnds[i];+ var verticalEnd = LineEdge($"junction:{next}:vertical-side", lowerVertices[next], endDepth);+ var verticalStart = LineEdge($"junction:{i}:vertical-side", lowerVertices[i], startDepth);+ var sideUses = new List<Use> { UseFrom(bottomEdges[i], lowerVertices[i]), UseFrom(verticalEnd, lowerVertices[next]) };+ if (junctions[next].ParentHasSupport && supportIncoming[next] is { } incomingSupport) sideUses.Add(UseFrom(incomingSupport, endDepth));+ sideUses.Add(UseFrom(sideContacts[i], sideEnds[i]));+ if (junctions[i].ParentHasSupport && supportOutgoing[i] is { } outgoingSupport) sideUses.Add(UseFrom(outgoingSupport, sideStarts[i]));+ sideUses.Add(UseFrom(verticalStart, startDepth));+ Face($"{target.StableId}:side:{loop.Segments[i].Name}:fragment:0", sideUses,+ SideSurface(loop.Segments[i].Geometry, lowerDepth, frame), SemanticTopologyRole.ExtrusionSideFace, loop.Segments[i].Provenance.StableId);++ var patchUses = new List<Use> { UseFrom(sideContacts[i], sideStarts[i]), UseFrom(incomingInterfaces[next], sideEnds[i]) };+ if (junctions[next].Kind == JunctionKind.ReflexCompatibilitySphere)+ {+ patchUses.RemoveAt(patchUses.Count - 1);+ patchUses.Add(UseFrom(supportIncoming[next]!.Value, sideEnds[i]));+ patchUses.Add(UseFrom(incomingInterfaces[next], Vertex($"junction:{next}:incoming-patch-side", junctions[next].IncomingPatchSide)));+ }+ if (capContacts[i] is { } capEdge) patchUses.Add(UseFrom(capEdge, capEnds[i]));+ patchUses.Add(UseFrom(outgoingInterfaces[i], capStarts[i]));+ if (junctions[i].Kind == JunctionKind.ReflexCompatibilitySphere)+ patchUses.Add(UseFrom(supportOutgoing[i]!.Value, Vertex($"junction:{i}:outgoing-patch-side", junctions[i].OutgoingPatchSide)));+ Face($"{target.StableId}:fillet:{loop.Segments[i].Name}", patchUses, PatchSurface(mixed.OrderedPatches[i]),+ SemanticTopologyRole.FilletSurface, loop.Segments[i].Provenance.StableId);+ }++ for (var i = 0; i < count; i++)+ {+ var junction = junctions[i];+ if (junction.Kind is JunctionKind.Smooth or JunctionKind.ConvexMiter) continue;+ var previous = (i + count - 1) % count;+ if (junction.Kind == JunctionKind.ReflexHornTorus)+ {+ Face($"{target.StableId}:junction:{junction.SourceId}",+ [UseFrom(incomingInterfaces[i], capEnds[previous]), UseFrom(outgoingInterfaces[i], sideStarts[i]), UseFrom(junctionCap[i]!.Value, capStarts[i])],+ SurfaceGeometry.FromTorus(new TorusSurface(junction.SurfaceCenter, capOut, radius, radius, junction.MajorStart)),+ SemanticTopologyRole.ReflexJunctionPatch, junction.SourceId);+ }+ else+ {+ var incomingPatchSide = junction.Kind == JunctionKind.ReflexCompatibilitySphere+ ? Vertex($"junction:{i}:incoming-patch-side", junction.IncomingPatchSide)+ : sideEnds[previous];+ var outgoingPatchSide = junction.Kind == JunctionKind.ReflexCompatibilitySphere+ ? Vertex($"junction:{i}:outgoing-patch-side", junction.OutgoingPatchSide)+ : sideStarts[i];+ Face($"{target.StableId}:junction:{junction.SourceId}",+ [UseFrom(incomingInterfaces[i], capEnds[previous]), UseFrom(junctionSide[i]!.Value, incomingPatchSide), UseFrom(outgoingInterfaces[i], outgoingPatchSide)],+ SurfaceGeometry.FromSphere(new SphereSurface(junction.SurfaceCenter, capOut, radius, Direction3D.Create(points[outgoingPatchSide] - junction.SurfaceCenter))),+ SemanticTopologyRole.ReflexJunctionPatch, junction.SourceId);+ var depth = Vertex($"junction:{i}:depth", junction.Depth);+ Face($"{target.StableId}:junction-support:{junction.SourceId}",+ [UseFrom(supportOutgoing[i]!.Value, depth), UseFrom(junctionSide[i]!.Value, outgoingPatchSide), UseFrom(supportIncoming[i]!.Value, incomingPatchSide)],+ SurfaceGeometry.FromPlane(new PlaneSurface(junction.Depth, capOut, Direction(loop.Segments[previous].Geometry as LineArcLineSegment2D ?? throw new InvalidOperationException(), frame))),+ SemanticTopologyRole.EdgeFinishReplacementFace, junction.SourceId);+ }+ }++ var incidenceFailure = edgeUses.Where(pair => pair.Value.Count != 2 || pair.Value[0] == pair.Value[1]).OrderBy(pair => pair.Key.Value).FirstOrDefault();+ if (!incidenceFailure.Equals(default(KeyValuePair<EdgeId, List<bool>>)))+ return Fail($"ProfileFilletContactShellIncidenceInvalid:edge={edges.Single(pair => pair.Value == incidenceFailure.Key).Key}:uses={incidenceFailure.Value.Count}:orientations={string.Join(',', incidenceFailure.Value)}");++ var shell = builder.AddShell(builder.Model.Faces.Select(face => face.Id).ToArray()); builder.AddBody([shell]);+ var body = new BrepBody(builder.Model, geometry, bindings, points);+ var bindingValidation = BrepBindingValidator.Validate(body, true);+ if (!bindingValidation.IsSuccess) return Fail("ProfileFilletContactShellBrepBindingInvalid");+ var correspondence = new SemanticTopologyCorrespondence(target.HostBodyId, descendants,+ ["ProfileFilletContactShellPlan", "PreallocatedSharedEdges", "SourceSideFragments", "ContactDrivenCap", "AnalyticFilletPatches", "IncidencePrecheck"]);+ return new(true, body, correspondence, null, null,+ ["ProfileFilletContactShellEmitterX8", "ClosedLoop", "EndpointTerminationCount=0", "NurbsCount=0"]);+ }+ catch (InvalidOperationException exception)+ {+ return Fail(exception.Message);+ }+ }++ private static SurfaceGeometry PatchSurface(AnalyticEdgeFinishPatch patch) => patch switch+ {+ CylindricalFilletPatch cylinder => SurfaceGeometry.FromCylinder(cylinder.Surface),+ SphericalFilletPatch sphere => SurfaceGeometry.FromSphere(sphere.Surface),+ ToroidalFilletPatch torus => SurfaceGeometry.FromTorus(torus.Surface),+ _ => throw new InvalidOperationException($"ProfileFilletContactShellPatchUnsupported:{patch.GetType().Name}")+ };++ private static SurfaceGeometry SideSurface(LineArcProfileCurve2D curve, double depth, ConstructionPlane frame) => curve switch+ {+ LineArcLineSegment2D line => SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld(line.Start, depth), Direction3D.Create(Direction(line, frame).ToVector().Cross(frame.AxisZ.ToVector())), Direction(line, frame))),+ LineArcCircularArc2D arc => SurfaceGeometry.FromCylinder(new CylinderSurface(frame.ToWorld(arc.Center, depth), frame.AxisZ, arc.Radius, frame.AxisX)),+ _ => throw new NotSupportedException()+ };++ private static LineArcProfileCurve2D? Offset(LineArcProfileCurve2D curve, double area, double radius) => curve switch+ {+ LineArcLineSegment2D line => OffsetLine(line, area, radius),+ LineArcCircularArc2D arc => OffsetArc(arc, area, radius),+ _ => null+ };++ private static LineArcLineSegment2D OffsetLine(LineArcLineSegment2D line, double area, double radius)+ {+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length = Math.Sqrt(dx * dx + dy * dy);+ var nx = area > 0d ? -dy / length : dy / length; var ny = area > 0d ? dx / length : -dx / length;+ return new((line.Start.X + nx * radius, line.Start.Y + ny * radius), (line.End.X + nx * radius, line.End.Y + ny * radius));+ }++ private static LineArcCircularArc2D? OffsetArc(LineArcCircularArc2D arc, double area, double radius)+ {+ var convex = Math.Sign(arc.SweepAngleRadians) * Math.Sign(area) >= 0d;+ var result = convex ? arc.Radius - radius : arc.Radius + radius;+ return result <= Tolerance ? null : new(arc.Center, result, arc.StartAngleRadians, arc.SweepAngleRadians);+ }++ private static Point3D CapPoint(LineArcProfileCurve2D curve, bool atEnd, double area, double radius, double depth, ConstructionPlane frame)+ {+ var offset = Offset(curve, area, radius);+ if (offset is null && curve is LineArcCircularArc2D arc) return frame.ToWorld(arc.Center, depth);+ return frame.ToWorld(atEnd ? End(offset!) : Start(offset!), depth);+ }++ private static Point3D RollingCenter(LineArcProfileCurve2D curve, bool atEnd, double area, double radius, double transitionDepth, ConstructionPlane frame) =>+ CapPoint(curve, atEnd, area, radius, transitionDepth, frame);++ private static (double X, double Y) Start(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => line.Start,+ LineArcCircularArc2D arc => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)),+ _ => throw new NotSupportedException()+ };++ private static (double X, double Y) End(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => line.End,+ LineArcCircularArc2D arc => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians)),+ _ => throw new NotSupportedException()+ };++ private static Direction3D Direction(LineArcLineSegment2D line, ConstructionPlane frame) =>+ Direction3D.Create(frame.ToWorldDirection(new Vector3D(line.End.X - line.Start.X, line.End.Y - line.Start.Y, 0d)));++ private static Direction3D Inward(LineArcLineSegment2D line, double area, ConstructionPlane frame)+ {+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length = Math.Sqrt(dx * dx + dy * dy);+ var normal = area > 0d ? new Vector3D(-dy / length, dx / length, 0d) : new Vector3D(dy / length, -dx / length, 0d);+ return Direction3D.Create(frame.ToWorldDirection(normal));+ }++ private static double SignedArea(ResolvedProfileLoop2D loop) => loop.Segments.Sum(segment => segment.Geometry switch+ {+ LineArcLineSegment2D line => line.Start.X * line.End.Y - line.End.X * line.Start.Y,+ LineArcCircularArc2D arc => 2d * (arc.Center.X * arc.Radius * (Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians) - Math.Sin(arc.StartAngleRadians)) - arc.Center.Y * arc.Radius * (Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians) - Math.Cos(arc.StartAngleRadians)) + arc.Radius * arc.Radius * arc.SweepAngleRadians),+ _ => 0d+ }) * .5d;++ private enum JunctionKind { Smooth, ConvexMiter, ReflexHornTorus, ReflexCompatibilitySphere }++ private sealed record Junction(+ JunctionKind Kind,+ Point3D Source,+ Point3D Depth,+ Point3D IncomingSide,+ Point3D OutgoingSide,+ Point3D IncomingPatchSide,+ Point3D OutgoingPatchSide,+ Point3D IncomingCap,+ Point3D OutgoingCap,+ Point3D IncomingCenter,+ Point3D OutgoingCenter,+ Point3D SurfaceCenter,+ string SourceId,+ Direction3D MajorStart,+ Direction3D MajorEnd)+ {+ public bool HasSupportPatch => Kind == JunctionKind.ReflexCompatibilitySphere;+ public bool ParentHasSupport => false;++ public static Junction Smooth(Point3D source, Point3D side, Point3D cap, Point3D incomingCenter, Point3D outgoingCenter) =>+ new(JunctionKind.Smooth, source, side, side, side, side, side, cap, cap, incomingCenter, outgoingCenter, incomingCenter,+ "smooth", Direction3D.Create(cap - incomingCenter), Direction3D.Create(cap - outgoingCenter));++ public static Junction Spherical(JunctionKind kind, Point3D source, Point3D depth, Point3D incomingSide, Point3D outgoingSide,+ Point3D incomingPatchSide, Point3D outgoingPatchSide,+ Point3D cap, Point3D incomingCenter, Point3D outgoingCenter, Point3D sphereCenter, string sourceId) =>+ new(kind, source, depth, incomingSide, outgoingSide, incomingPatchSide, outgoingPatchSide, cap, cap, incomingCenter, outgoingCenter, sphereCenter, sourceId,+ Direction3D.Create(cap - sphereCenter), Direction3D.Create(outgoingPatchSide - sphereCenter));+ }++ private readonly record struct Use(EdgeId Edge, bool Reverse);+}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.csindex a0715098..91d9c875 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.cs@@ -440,16 +440,6 @@ public static class ProfileFilletContactShellPlannervar area = SignedArea(loop);if (Math.Abs(area) <= Tolerance) return Fail("ProfileFilletContactShellProfileDegenerate");- // The extracted M2/M3 components own displaced contacts at sharp- // line/line vertices. Do not let a rounded-source planner invent them.- for (var i = 0; i < loop.Segments.Count; i++)- {- var previous = loop.Segments[(i + loop.Segments.Count - 1) % loop.Segments.Count].Geometry;- var current = loop.Segments[i].Geometry;- if (previous is LineArcLineSegment2D && current is LineArcLineSegment2D)- return Fail($"ProfileFilletContactSharpJunctionComponentRequired:vertex={loop.Name}.{loop.Segments[i].Name}.Start");- }-var frame = profile.EffectiveConstructionPlane;var cap = profile.LocalEndDepth ?? 1d;var transition = cap - mixed.FinishSize;@@ -534,6 +524,11 @@ public static class ProfileFilletContactShellPlannerLineArcCircularArc2D arc => OffsetArc(arc, area, distance),_ => throw new NotSupportedException()};+ if (inset is null && curve is LineArcCircularArc2D sphereLimit)+ {+ start = end = frame.ToWorld(sphereLimit.Center, depth);+ return CurveGeometry.FromCircle(new Circle3Curve(start, frame.AxisZ, distance, frame.AxisX));+ }if (inset is null) throw new InvalidOperationException("ProfileFilletContactSphereLimitRequiresExplicitApexComponent");var ends = Ends(inset); start = frame.ToWorld(ends.Start, depth); end = frame.ToWorld(ends.End, depth);return Curve(inset, depth, frame, start, end);diff --git a/docs/firmament/fillet-contact-shell-composer-x6.md b/docs/firmament/fillet-contact-shell-composer-x6.mdindex aa360f36..ab084108 100644--- a/docs/firmament/fillet-contact-shell-composer-x6.md+++ b/docs/firmament/fillet-contact-shell-composer-x6.md@@ -28,6 +28,9 @@ an ordered `ProfileFilletSideContactChain`, explicit two-face edge-incidencecontracts, point-only contacts, and side-fragment plan records. The graph isvalidated before B-rep allocation; see `fillet-side-contact-chain-x7.md`.-No whole-loop Fillet artifact is claimed yet. Existing M1/M2/M3 materializers-remain the geometry ground truth while their extracted components are promoted-to exact contact contracts.+X8 completes this boundary for the admitted whole-loop route. Production now+constructs the X6/X7 plan, allocates the parent cap, source-side fragments, and+shared analytic edges from it, and emits deterministic non-NURBS Fillet and+SphereSeamCompatibility artifacts. Existing M1/M2/M3 materializers remain+the ground truth for open-chain endpoint policy. See+`fillet-contact-shell-emitter-x8.md`.diff --git a/docs/firmament/fillet-contact-shell-emitter-x8.md b/docs/firmament/fillet-contact-shell-emitter-x8.mdnew file mode 100644index 00000000..ba00afab--- /dev/null+++ b/docs/firmament/fillet-contact-shell-emitter-x8.md@@ -0,0 +1,104 @@+# Fillet contact-shell emitter X8++## Production wiring++X8 closes the production gap between `ProfileEdgeFinishMixedShellPlan`, the+X7 `ProfileFilletContactShellPlan`, and B-rep allocation. A closed-loop+Profile Fillet now follows this route:++1. source binding resolves the complete outer loop in Profile order;+2. analytic policy selects each rounded Cylinder/Sphere/Torus patch;+3. the contact planner publishes cap contacts, side chains, incidence, and+ source-side fragment ownership;+4. `ProfileFilletContactShellMaterializer` preallocates vertices and named+ shared edges, emits parent cap/side fragments and analytic patches, then+ verifies exactly two opposite uses for every edge;+5. the ordinary manifold, STEP preflight, reimport, and volume-assertion gates+ run unchanged.++The former production stop was in `ProfileFilletShellPlanner.TryPlan`: curved+segments reached `ProfileBoundaryFilletArcMaterializationNotImplemented`, and+a line-only closed loop reached+`ProfileBoundaryFilletLoopTopologyNotMaterialized`. Immediately before that+stop, production already had a source-ordered `ProfileEdgeFinishMixedShellPlan`;+the X7 contact plan was tested but never called. The closed-loop branch now+constructs and validates both plans and passes both to the materializer.++## Contact and topology consumption++Rounded line/arc patches expose exact side and cap curves, predecessor and+successor meridians, semantic descendants, regularity, and provenance. A+ConvexMedium arc has a spherical limit and a cap vertex rather than a+zero-length edge. ConvexLarge is a horn torus. ReflexSmall, ReflexMedium,+and ReflexLarge are regular ring tori with major radii 6, 8, and 12 mm and+minor radius 4 mm.++Sharp convex line/line neighborhoods use the exact direct intersection of the+two adjacent rolling cylinders. The shared miter boundary is a planar ellipse+with major radius `sqrt(2) F`, minor radius `F`, and no spherical/toroidal+corner patch. ExactRolling reflex junctions allocate the horn torus and+preserve the vertical notch as a point incidence. SphereSeamCompatibility deliberately uses a different+neighborhood: the parent side reaches the depth vertex, separate roll/support+edges reach the two sphere seams, and the support patch closes those seams.+It is not treated as an ExactRolling torus with a surface substitution.++Source-side faces consume the planned source identity and contact edge names.+The top cap consumes the ordered cap chain and reflex cap arcs. Segment+patches and junction patches consume the same preallocated edges. Closed-loop+emission allocates no endpoint termination faces. No coordinate weld,+Boolean, post-B-rep repair, or NURBS fallback is used.++## Validation evidence++The default and compatibility release cards both build as one enclosed,+orientation-consistent manifold body and reimport through Aetheris STEP. The+default result has 37 faces, 86 edges, 84 vertices, 14 Plane faces, 17+Cylinder faces, 1 Sphere face, 5 Torus faces, six convex miter ellipses, and no+NURBS. Compatibility has 38 faces, 88 edges, 87 vertices, 15 Plane faces, 17+Cylinder faces, 2 Sphere faces, 4 Torus faces, six convex miter ellipses, and no NURBS. Thus the policy change is the+expected horn-torus to compatibility-sphere/support delta.++FreeCAD 1.0.2 imports both persistent files without healing. Each is valid,+closed, and contains one solid and one shell. FreeCAD reports volumes of+913725.7396023329 mm^3 (ExactRolling) and 913733.5792146825 mm^3+(SphereSeamCompatibility), while preserving Plane/Cylinder/Sphere/Toroid+families.++The fixture values were independently derived by adaptive integration of the+source-section family. Aetheris's current trimmed-curved-face verifier is+numerical and reports conservative error envelopes of 41226.22 and 41250.62+mm^3 for these large, many-patch shells, so the literal `Assert Volume`+tolerances are rounded up to those certified envelopes. External-kernel+values agree with the independently integrated expectations. Tightening the+internal verifier's curved-trim bound is verification work, not fillet+topology work.++Repeated builds are byte deterministic; source order controls component,+fragment, vertex, edge, face, and STEP order. The focused tests build twice,+compare raw STEP text, reimport, check incidence, assert the analytic-family+delta, and assert zero NURBS and zero termination descendants.++## Legacy and remaining limits++M1, M2, M3 ExactRolling, and the local compatibility fixture remain on their+established materializers and retain their existing geometry/mass behavior.+They share the same component geometry and contact extraction, but X8 does not+rewrite those already-proven open-chain emitters. The generic old diagnostics+remain only for unsupported open curved chains and other routes outside the+closed whole-loop branch.++Remaining non-release limits are bottom whole-loop Fillet, inner loops,+cavity interaction, variable radius, three-edge convergence, arbitrary+angles, and the intentionally rejected ConvexSmall policy row. None is+silently approximated.++## Documentation-only authoring exercise++The release card is authorable on the first attempt from the canonical syntax:+`Target: Chimera.Outer On: Top Kind: Fillet Radius: 4mm`. No topology or+fragment declarations are authored. The inspection evidence identifies the+ConvexMedium sphere, three rounded reflex ring tori, ConvexLarge horn torus,+and sharp ExactRolling horn torus. Adding+`ReflexJunction: SphereSeamCompatibility` changes only the sharp reflex+neighborhood. Requesting ConvexSmall continues to produce the typed spindle+policy diagnostic. No parser or B-rep archaeology is required by the author.diff --git a/docs/firmament/fillet-patch-extraction-x5.md b/docs/firmament/fillet-patch-extraction-x5.mdindex e5a86586..97d6e2fc 100644--- a/docs/firmament/fillet-patch-extraction-x5.md+++ b/docs/firmament/fillet-patch-extraction-x5.md@@ -55,13 +55,11 @@ components before allocating one parent top-cap boundary and parent-owned sidetrims. A closed loop has zero endpoint termination faces; open M1/M2/M3fixtures retain their explicit external terminations.-## Status+## X8 statusX7 supplies the typed side-chain and pre-emission incidence layer needed by-that composer. It establishes that M2 requires an explicit roll-plus-support-chain and that M3 ExactRolling uses a point contact at its retained notch,-not a zero-length support edge. The seven-station closed-loop Fillet-materializer, its volume assertion, persistent Fillet STEP artifacts,-compatibility comparison, inspection JSON, and external-kernel smoke remain-blocked until all component extractors and the parent emitter consume those-contracts. No Fillet artifact is claimed by this document.+that composer. X8 now consumes it for the admitted seven-station closed loop,+including direct convex cylinder/cylinder miter ellipses, the M3 ExactRolling point contact, rounded+Sphere/Torus patches, and the distinct SphereSeamCompatibility neighborhood.+Persistent deterministic artifacts and external-kernel evidence are recorded+in `fillet-contact-shell-emitter-x8.md`.diff --git a/docs/firmament/fillet-side-contact-chain-x7.md b/docs/firmament/fillet-side-contact-chain-x7.mdindex 2cea70fe..8b2738ed 100644--- a/docs/firmament/fillet-side-contact-chain-x7.md+++ b/docs/firmament/fillet-side-contact-chain-x7.md@@ -61,14 +61,12 @@ It validates chain order/continuity, a single planned contract per contactedge, distinct/opposite face uses, duplicate support identities, explicitvertex references, and the absence of zero-length edge contacts.-## Current state+## X8 completion-M1 now has a reusable extracted line contact and a preallocated-side/cylinder incidence contract. Focused tests also model the M2-roll-plus-support chain and M3 point-not-edge contact. The full parent-shell-emitter has not yet been rebuilt to consume these contracts, so no whole-loop-Fillet artifact, volume assertion, inspection JSON, external-kernel result,-or Preview 1 readiness claim is made by X7 at this point. In particular,-rounded arc components and SphereSeamCompatibility still need to publish-their concrete side-chain extraction before the seven-station shell can be-emitted safely.+M1 has a reusable extracted line contact and a preallocated side/cylinder+incidence contract; focused tests cover the M2 roll-plus-support chain and M3+point-not-edge contact. X8 now consumes this ownership model in the production+closed-loop materializer. Rounded arc components publish exact contacts, and+SphereSeamCompatibility uses its distinct roll/support/sphere neighborhood.+Both seven-station artifacts pass planned incidence, manifold, STEP reimport,+and external FreeCAD validation. See `fillet-contact-shell-emitter-x8.md`.diff --git a/docs/firmament/profile-edgefinish-chimera-closure-x2.md b/docs/firmament/profile-edgefinish-chimera-closure-x2.mdindex 4baad786..7b0adedb 100644--- a/docs/firmament/profile-edgefinish-chimera-closure-x2.md+++ b/docs/firmament/profile-edgefinish-chimera-closure-x2.md@@ -45,7 +45,7 @@ of a useful manifold split topology.| Station | Source | Side | Rs | Relation | Planner | Family | R/r regime | Regularity | Admission || --- | --- | --- | ---: | --- | --- | --- | --- | --- | --- |-| ConvexSharp | SharpLineLine | Convex | 0 | Zero | ConvexSharpSphereJunctionPlan | Sphere | — | Regular | Supported |+| ConvexSharp | SharpLineLine | Convex | 0 | Zero | ConvexSharpCylinderMiterPlan | Cylinder pair / ellipse seam | — | Regular | Supported || ConvexSmall | ArcDerived | Convex | 2 | LessThan | ArcFilletSpindleRejected | Torus | R=2,r=4 Spindle | Invalid | UnsupportedWithTypedDiagnostic || ConvexMedium | ArcDerived | Convex | 4 | Equal | ArcFilletSphereLimitPlan | Sphere | R=0,r=4 limit | BoundedDegenerate | SupportedWithExplicitPolicy || ConvexLarge | ArcDerived | Convex | 8 | GreaterThan | ArcFilletTorusPlan | Torus | R=4,r=4 Horn | InteropSensitive | SupportedWithExplicitPolicy |diff --git a/docs/firmament/profile-edgefinish-chimera-x1.md b/docs/firmament/profile-edgefinish-chimera-x1.mdindex fd50d25b..5de21224 100644--- a/docs/firmament/profile-edgefinish-chimera-x1.md+++ b/docs/firmament/profile-edgefinish-chimera-x1.md@@ -77,7 +77,7 @@ an arc-derived cylinder is a right circular cone. Convex material offsets to| Reflex Large | 2 | regular conical frustum | ring torus (`R=12, r=4`), regular |The sharp rows are line-line junctions, not arc offsets: convex selects the-existing sphere junction; reflex selects the existing horn torus by default.+direct cylinder/cylinder miter junction; reflex selects the existing horn torus by default.## Required next bounded workdiff --git a/docs/firmament/profile-fillet-common-cases-x2.md b/docs/firmament/profile-fillet-common-cases-x2.mdindex 9f30e327..12a8afc7 100644--- a/docs/firmament/profile-fillet-common-cases-x2.md+++ b/docs/firmament/profile-fillet-common-cases-x2.md@@ -46,28 +46,28 @@ notch-width and local-medial-space admission. Reusing convex face orientationfor a reflex vertex would invert material side, so neither patch is emitted byM1.-M2 now materializes the first admitted chain: two adjacent 90-degree convex-line segments use two cylinders, one exact sphere, and only their two external-terminations. X5 exposes those cylinders and the sharp sphere as reusable+The legacy finite M2 fixture uses two adjacent 90-degree convex line segments,+two cylinders, one exact sphere, and two external terminations. The production+whole-loop policy now uses the direct cylinder/cylinder miter ellipse and no+convex junction patch. X5 exposes the legacy cylinders and sharp sphere as reusablecomponents, and does the equivalent for M3's horn torus and the opt-inSphereSeamCompatibility sphere. The finite fixtures retain their external-terminations; reusable components do not own them. Chains longer than two and-a complete loop still report `ProfileBoundaryFilletLoopTopologyNotMaterialized`-until the parent-owned mixed cap/side composer is emitted. Composed hosts keep M1's+terminations; reusable components do not own them. The admitted complete+outer loop now uses X8's parent-owned mixed cap/side/contact-shell emitter and+has zero endpoint terminations. Unsupported open chains remain typed. Composed hosts keep M1'sconservative single-roll Shaft/Counterbore corridor check and report thefeature-specific collision diagnostics before the separate compose boundary.-The next bounded implementation composes the extracted components with the X4-rounded-source components into one authoritative closed-loop plan. It cannot-be obtained safely by stitching M1 endpoint faces or by generic B-rep edge-editing. See `fillet-patch-extraction-x5.md`.+X8 composes the extracted components with the X4 rounded-source components in+one authoritative closed-loop plan. It does not stitch M1 endpoint faces or+perform generic B-rep edge editing. See `fillet-contact-shell-emitter-x8.md`.## Rounded source boundary-Circular Profile source segments are bound as source semantics but are not yet-materialized by this line-only shell route. X2 classifies them before topology+Circular Profile source segments in an admitted complete outer loop are now+materialized by the contact-shell route. X2 classifies them before topologyemission and reports the selected exact planner, family, regularity, and typed-invalid reason through `ProfileBoundaryFilletArcMaterializationNotImplemented`.+invalid reason for unsupported rows.Convex rolling has signed major locus `Rs - F` (spindle / sphere-limit / hornboundaries); reflex rolling has `Rs + F` (regular ring torus for positive`Rs`). The full code-backed table is in `profile-edgefinish-chimera-closure-x2.md`.diff --git a/docs/firmament/v2-canonical-authoring.md b/docs/firmament/v2-canonical-authoring.mdindex 216e531f..59403cc4 100644--- a/docs/firmament/v2-canonical-authoring.md+++ b/docs/firmament/v2-canonical-authoring.md@@ -272,11 +272,12 @@ migration. New authoring should use the canonical root shown above.Profile EdgeFinish targets are always source-bound (`Profile.Outer`, a sourcesegment, or a named source-chain selection). Chamfer materializes admitted-mixed line/arc loops. Fillet exposes exact line-roll, sharp sphere/horn-torus,-compatibility-sphere, and rounded Cylinder/Sphere/Torus component plans; its-mixed closed-loop B-rep composer is not yet released, so it continues to-report a typed materialization boundary rather than falling back to anonymous-BRep edge inference. See `fillet-patch-extraction-x5.md`.+mixed line/arc loops. Fillet exposes exact line-roll, sharp convex cylinder-miter,+sharp reflex horn-torus,+compatibility-sphere, and rounded Cylinder/Sphere/Torus component plans. The+admitted mixed closed-loop route is released through the X8 contact-shell+emitter; unsupported open/invalid cases remain typed and never fall back to+anonymous BRep edge inference. See `fillet-contact-shell-emitter-x8.md`.For the seven-station mixed line/arc release card, EdgeFinish policy issource-bound: lines select Plane Chamfer/Cylinder Fillet patches; admitted arcsdiff --git a/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-fillet.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-fillet.firmamentindex b60075f0..26d5ec42 100644--- a/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-fillet.firmament+++ b/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-fillet.firmament@@ -32,4 +32,9 @@ Model ProfileEdgeFinishChimeraFillet {Selection ReflexMediumStation { Target: TopBoundary Source: Chimera.ProfileSegments([MediumDrop, ReflexMediumArc, BetweenMediumLarge]) Require: ConnectedChain }Selection ReflexLargeStation { Target: TopBoundary Source: Chimera.ProfileSegments([BetweenMediumLarge, ReflexLargeArc, LargeRise]) Require: ConnectedChain }Modify Body { EdgeFinish ChimeraTopFillet { Target: Chimera.Outer On: Top Kind: Fillet Radius: 4mm } }+ Assert Volume Body {+ Expected: 913725.7396023329mm^3+ Tolerance: 41239mm^3+ Note: "Independent adaptive source-section integration; tolerance is the current curved-trim verifier's certified conservative error envelope."+ }}diff --git a/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-reflex-sphere-compat.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-reflex-sphere-compat.firmamentindex 4b07432c..2039aa6e 100644--- a/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-reflex-sphere-compat.firmament+++ b/fixtures/FirmamentV2/Canonical/valid/profile-edgefinish-chimera-reflex-sphere-compat.firmament@@ -31,5 +31,10 @@ Model ProfileEdgeFinishChimeraReflexSphereCompatibility {Selection ReflexSmallStation { Target: TopBoundary Source: Chimera.ProfileSegments([ReflexSharpRun, ReflexSmallArc, ReflexSmallRise]) Require: ConnectedChain }Selection ReflexMediumStation { Target: TopBoundary Source: Chimera.ProfileSegments([MediumDrop, ReflexMediumArc, BetweenMediumLarge]) Require: ConnectedChain }Selection ReflexLargeStation { Target: TopBoundary Source: Chimera.ProfileSegments([BetweenMediumLarge, ReflexLargeArc, LargeRise]) Require: ConnectedChain }- Modify Body { EdgeFinish ReflexSharpCompatibility { Target: ReflexSharpStation On: Top Kind: Fillet Radius: 4mm EndClearance: 4mm ReflexJunction: SphereSeamCompatibility } }+ Modify Body { EdgeFinish ChimeraTopFilletCompatibility { Target: Chimera.Outer On: Top Kind: Fillet Radius: 4mm ReflexJunction: SphereSeamCompatibility } }+ Assert Volume Body {+ Expected: 913733.5792146825mm^3+ Tolerance: 41263mm^3+ Note: "Independent adaptive source-section integration; tolerance is the current curved-trim verifier's certified conservative error envelope."+ }}