Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Expose edge finish planning and support analytic ellipse and torus tess
Yuechen Li4ab5d032704e
diff --git a/Aetheris.CLI.Tests/EdgeFinishRobustnessCliTests.cs b/Aetheris.CLI.Tests/EdgeFinishRobustnessCliTests.csnew file mode 100644index 00000000..bb008970--- /dev/null+++ b/Aetheris.CLI.Tests/EdgeFinishRobustnessCliTests.cs@@ -0,0 +1,152 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.CLI.Tests;++public sealed class EdgeFinishRobustnessCliTests+{+ [Theory]+ [InlineData("d-profile-fillet", false)]+ [InlineData("d-profile-fillet", true)]+ [InlineData("d-profile-chamfer", false)]+ [InlineData("d-profile-chamfer", true)]+ [InlineData("polygon-rim-fillet", false)]+ [InlineData("polygon-rim-fillet", true)]+ public void ValidateAndBuildAdmitActualFinishedGeometry(string fixture, bool bottom)+ {+ WithSource(fixture, text => bottom ? text.Replace("on: Top", "on: Bottom") : text, (path, output) =>+ {+ var validate = new StringWriter(); var build = new StringWriter(); var error = new StringWriter();+ Assert.True(CliRunner.Run(["validate", path, "--json"], validate, error) == 0, validate + error.ToString());+ Assert.True(CliRunner.Run(["build", path, "--output", output, "--json"], build, error) == 0, build + error.ToString());+ using var json = JsonDocument.Parse(build.ToString());+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());+ var feature = Assert.Single(json.RootElement.GetProperty("engineeringFeatures").EnumerateArray());+ Assert.Equal("edgefinish:Rim", feature.GetProperty("featureId").GetString());+ var imported = Step242Importer.ImportBody(File.ReadAllText(output));+ Assert.True(imported.IsSuccess);+ Assert.Equal(fixture.StartsWith("d-", StringComparison.Ordinal) ? 6 : 10, imported.Value.Topology.Faces.Count());+ if (fixture.StartsWith("d-", StringComparison.Ordinal))+ {+ var planning = json.RootElement.GetProperty("edgeFinishPlanning");+ Assert.Equal("CircularSegmentMiter", planning.GetProperty("decision").GetProperty("strategy").GetString());+ Assert.InRange(planning.GetProperty("maximumCurveDeviationMm").GetDouble(), 0, 1e-6);+ Assert.Equal(2, planning.GetProperty("decision").GetProperty("judgment").GetProperty("candidates").GetArrayLength());+ Assert.False(planning.GetProperty("decision").TryGetProperty("circularSegment", out _)); // Internal tuple packet is not a JSON contract.+ }+ });+ }++ [Theory]+ [InlineData("d-profile-fillet", "radius: 1mm", "radius: 5mm", "ProfileEdgeFinishInsetCollapse")]+ [InlineData("d-profile-chamfer", "distance: 1mm", "distance: 6mm", "ProfileEdgeFinishInsetCollapse")]+ [InlineData("d-profile-fillet", "radius: 1mm", "radius: -1mm", "Radius")]+ [InlineData("d-profile-fillet", "radius: 1mm", "radius: 1mm; endClearance: 1mm", "EndClearanceRequiresOpenChain")]+ [InlineData("d-profile-fillet", "radius: 1mm", "radius: 1mm; raduis: 1mm", "raduis")]+ [InlineData("d-profile-fillet", "radius: 1mm", "radius: 1mm; endClearance: Bogus", "field-value-invalid")]+ [InlineData("d-profile-fillet", "radius: 1mm", "radius: 1mm; reflexJunction: 0", "ReflexJunctionStyleUnsupported")]+ [InlineData("d-profile-fillet", "radius: 1mm }", "radius: 1mm }\n EdgeFinish LowerRim { target: Section.Outer; on: Bottom; kind: Fillet; radius: 1mm }", "ProfileBoundaryEdgeFinishSequenceUnsupported")]+ [InlineData("d-profile-chamfer", "distance: 1mm }", "distance: 1mm }\n EdgeFinish LowerRim { target: Section.Outer; on: Bottom; kind: Chamfer; distance: 1mm }", "ProfileBoundaryEdgeFinishSequenceUnsupported")]+ [InlineData("d-profile-fillet", "radius: 1mm }", "radius: 1mm }\n EdgeFinish LowerRim { target: Section.Outer; on: Bottom; kind: Chamfer; distance: 1mm }", "ProfileBoundaryEdgeFinishSequenceUnsupported")]+ public void RejectedRequestsAgreeAndLeaveNoArtifact(string fixture, string oldText, string replacement, string code)+ {+ WithSource(fixture, text => text.Replace(oldText, replacement), (path, output) =>+ {+ foreach (var command in new[] { "validate", "build" })+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var args = command == "build" ? new[] { command, path, "--output", output, "--json" } : [command, path, "--json"];+ Assert.True(CliRunner.Run(args, stdout, stderr) == 1, stdout + stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString());+ var report = command == "validate" ? json.RootElement.GetProperty("firmamentV2Validation") : json.RootElement;+ Assert.Contains(report.GetProperty("diagnostics").EnumerateArray(), d =>+ d.GetProperty("code").GetString()!.Contains(code, StringComparison.Ordinal) || d.GetProperty("message").GetString()!.Contains(code, StringComparison.Ordinal));+ if (code is "ProfileEdgeFinishInsetCollapse" or "ProfileBoundaryEdgeFinishSequenceUnsupported")+ Assert.Contains(report.GetProperty("diagnostics").EnumerateArray(), d => d.GetProperty("line").GetInt32() > 1);+ }+ Assert.False(File.Exists(output));+ });+ }++ [Theory]+ [InlineData("d-profile-fillet", false)]+ [InlineData("d-profile-fillet", true)]+ [InlineData("d-profile-chamfer", false)]+ [InlineData("d-profile-chamfer", true)]+ [InlineData("polygon-rim-fillet", false)]+ [InlineData("polygon-rim-fillet", true)]+ public void FinishedStepMeshesWithCompleteWatertightOutwardTopology(string fixture, bool bottom)+ {+ WithSource(fixture, text => bottom ? text.Replace("on: Top", "on: Bottom") : text, (path, output) =>+ {+ var error = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["build", path, "--out", output, "--json"], new StringWriter(), error));+ var stdout = new StringWriter();+ Assert.True(CliRunner.Run(["mesh", output, "--format", "obj", "--output", output + ".obj", "--json"], stdout, error) == 0,+ stdout + error.ToString());+ using var json = JsonDocument.Parse(stdout.ToString()); var report = json.RootElement;+ Assert.True(report.GetProperty("watertight").GetBoolean());+ Assert.True(report.GetProperty("outwardOriented").GetBoolean());+ Assert.True(report.GetProperty("connected").GetBoolean());+ Assert.Equal(0, report.GetProperty("crackCount").GetInt32());+ Assert.Equal(0, report.GetProperty("nonManifoldEdgeCount").GetInt32());+ Assert.Equal(fixture.StartsWith("d-", StringComparison.Ordinal) ? 6 : 10, report.GetProperty("patchCount").GetInt32());+ });+ }++ [Fact]+ public void TypedEdgeFinishVariantRetainsTheSameGeometryAndIdentity()+ {+ WithSource("d-profile-fillet", text => text.Replace("EdgeFinish Rim", "EdgeFinish<Fillet> Rim").Replace("kind: Fillet; ", ""), (path, output) =>+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.True(CliRunner.Run(["build", path, "--out", output, "--json"], stdout, stderr) == 0, stdout + stderr.ToString());+ Assert.Contains("edgefinish:Rim", stdout.ToString());+ Assert.Equal(6, Step242Importer.ImportBody(File.ReadAllText(output)).Value.Topology.Faces.Count());+ });+ }++ [Fact]+ public void UncalledFinishRecipeDoesNotBecomeAnotherOperation()+ {+ var fixture = File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament"));+ var expected = Aetheris.Kernel.Firmament.FirmamentBuildAndExport.CompileSource(fixture);+ var recipe = "Feature Unused() -> EdgeFinish { return EdgeFinish { target: Section.Outer; on: Bottom; kind: Fillet; radius: 1mm } }\n";+ var actual = Aetheris.Kernel.Firmament.FirmamentBuildAndExport.CompileSource(fixture.Replace(" Modify", recipe + " Modify"));+ Assert.True(expected.IsSuccess);+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics.Select(d => d.Message)));+ Assert.Equal(expected.Value.StepText, actual.Value.StepText);+ Assert.Single(actual.Value.EngineeringFeatures!);+ }++ [Fact]+ public void NamedClosedSelectionUsesTheSameFinishedGeometry()+ {+ var fixture = File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament"));+ var expected = Aetheris.Kernel.Firmament.FirmamentBuildAndExport.CompileSource(fixture);+ var selection = "Selection Perimeter { source: Section.Outer.[Round, Flat]; require: ClosedLoop }\n";+ var named = fixture.Replace(" Modify", selection + " Modify").Replace("target: Section.Outer", "target: Perimeter");+ var actual = Aetheris.Kernel.Firmament.FirmamentBuildAndExport.CompileSource(named);+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics.Select(d => d.Message)));+ Assert.Equal(expected.Value.StepText, actual.Value.StepText);+ }++ private static void WithSource(string fixture, Func<string, string> transform, Action<string, string> assertion)+ {+ var directory = Path.Combine(Root(), "artifacts/local/tests/edge-finish-robustness", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ try+ {+ var path = Path.Combine(directory, "source.firmament");+ File.WriteAllText(path, transform(File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/EdgeFinishRobustness/" + fixture + ".firmament"))));+ assertion(path, Path.Combine(directory, "body.step"));+ }+ finally { Directory.Delete(directory, true); }+ }+ private static string Root()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory?.FullName ?? throw new DirectoryNotFoundException();+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex ea5f945e..aa873c6a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -572,6 +572,7 @@ public static class CliRunnerassertions = build.Value.Export.Assertions,features = build.Value.Export.Features,engineeringFeatures = build.Value.Export.EngineeringFeatures,+ edgeFinishPlanning = build.Value.Export.EdgeFinishPlanning,patterns = build.Value.Export.Patterns,perforation = build.Value.Export.Perforation,structural = build.Value.Export.Structural,diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex fb0fd3fd..d33338fc 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -250,7 +250,7 @@ public static class SurfaceMeshIrTessellator{var family = body.TryGetEdgeCurveGeometry(edge.Id, out var curve) && curve is not null ? curve.Kind.ToString() : "Unbound";families[family] = families.GetValueOrDefault(family) + 1;- if (family is "Line3" or "Circle3" or "Hyperbola3") continue;+ if (family is "Line3" or "Circle3" or "Ellipse3" or "Hyperbola3") continue;var usedFaces = body.Topology.Faces.Where(face => body.GetLoopIds(face.Id).SelectMany(body.GetCoedgeIds).Any(coedgeId => body.Topology.GetCoedge(coedgeId).EdgeId == edge.Id)).OrderBy(face => face.Id.Value).ToArray();@@ -542,6 +542,24 @@ public static class SurfaceMeshIrTessellatorclosed = false;chordError = ComputePolylineChordDeviation(hyperbola.Evaluate, sampled);break;+ case CurveGeometryKind.Ellipse3 when curve.Ellipse3 is { } ellipse:+ var ellipseSpan = interval.End - interval.Start;+ // An ellipse is a linear image of a unit circle: its major+ // radius bounds chord deviation, and a/b bounds tangent turn.+ var ellipseSegments = int.Max(ResolveCircleSegments(ellipse.MajorRadius, ellipseSpan, policy), forcedSegments ?? 1);+ var tangentSegments = double.Ceiling(double.Abs(ellipseSpan) * ellipse.MajorRadius / ellipse.MinorRadius / policy.TargetNormalErrorRadians);+ if (!double.IsFinite(tangentSegments) || tangentSegments >= policy.MaxBoundarySamples) return false;+ ellipseSegments = int.Max(ellipseSegments, (int)tangentSegments);+ if (ellipseSegments + 1 > policy.MaxBoundarySamples) return false;+ sampled = Enumerable.Range(0, ellipseSegments + 1).Select(i =>+ {+ var parameter = interval.Start + ellipseSpan * i / ellipseSegments;+ return (parameter, ellipse.Evaluate(parameter));+ }).ToList();+ closed = double.Abs(double.Abs(ellipseSpan) - 2 * double.Pi) <= Epsilon;+ chordError = ellipse.MajorRadius * (1 - double.Cos(double.Abs(ellipseSpan) / (2 * ellipseSegments)));+ tangentError = double.Abs(ellipseSpan) * ellipse.MajorRadius / ellipse.MinorRadius / ellipseSegments;+ break;case CurveGeometryKind.BSpline3 when curve.BSpline3 is { } spline:var splineSampling = BSplineTrimSampler.Sample(spline, interval, policy);if (!splineSampling.IsSuccess) return false;@@ -1059,6 +1077,7 @@ public static class SurfaceMeshIrTessellator{SurfaceMeshSupportKind.Cylinder when support.Cylinder is { } supportCylinder => supportCylinder.Evaluate(uv[index].U, uv[index].V),SurfaceMeshSupportKind.Cone when support.Cone is { } cone => cone.Evaluate(uv[index].U, uv[index].V),+ SurfaceMeshSupportKind.Torus when support.Torus is { } torus => torus.Evaluate(uv[index].U, uv[index].V),_ => throw new InvalidOperationException("Sampled boundary triangulation requires an evaluable analytic support.")};if ((reconstructed - vertexById[outerIds[index]].Position).Length > policy.TargetChordalError) return null;@@ -1512,7 +1531,26 @@ public static class SurfaceMeshIrTessellator.ToArray();if (seamPlans.Length != 2){- return null;+ // Bounded CAD miter: two contact circles and two shared spline+ // intersections. Reuse the parameter-space trim owner and its+ // boundary IDs; never turn this into a complete-torus fallback.+ var boundary = body.GetCoedgeIds(body.GetLoopIds(faceId)[0])+ .Select(body.Topology.GetCoedge).Select(c => plans[c.EdgeId]).ToArray();+ if (boundary.Length != 4 ||+ boundary.Count(p => p.CurveKind == CurveGeometryKind.Circle3) != 2 ||+ boundary.Count(p => p.CurveKind == CurveGeometryKind.BSpline3) != 2) return null;+ (double U, double V)? Project(Point3D point)+ {+ var uv = TryProjectPointToTorusUv(torus, point);+ if (uv is not { } value) return null;+ return (value.U, value.V > double.Pi ? value.V - 2 * double.Pi : value.V);+ }+ var projected = boundary.SelectMany(p => p.Samples).Select(s => Project(s.Position)).ToArray();+ if (projected.Any(p => p is null || double.Abs(p.Value.V) > double.Pi / 2 + 1e-8))+ return null; // Only the regular outer half-tube; no pole or periodic V crossing.+ return TryBuildSampledBoundaryBand(body, faceId, sameSense,+ new SurfaceMeshSupport(SurfaceMeshSupportKind.Torus, Torus: torus), plans, policy,+ Project, vertices, ref nextVertexId);}var parameters = seamPlansdiff --git a/Aetheris.Kernel.Firmament.Tests/Integration/CircularSegmentEdgeFinishTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/CircularSegmentEdgeFinishTests.csnew file mode 100644index 00000000..55958c74--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Integration/CircularSegmentEdgeFinishTests.cs@@ -0,0 +1,192 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests.Integration;++public sealed class CircularSegmentEdgeFinishTests+{+ [Theory]+ [InlineData("fillet")]+ [InlineData("chamfer")]+ public void RealSourceCompilesWithFinishRatherThanUnchangedExtrusion(string kind)+ {+ var source = Source(kind);+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics.Select(d => d.Message)));+ var imported = Step242Importer.ImportBody(built.Value.StepText);+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics.Select(d => d.Message)));+ AssertBody(imported.Value);+ Assert.Contains(imported.Value.Geometry.Surfaces, s => s.Value.Kind ==+ (kind == "fillet" ? SurfaceGeometryKind.Torus : SurfaceGeometryKind.Cone));+ Assert.Equal(built.Value.StepText, FirmamentBuildAndExport.CompileSource(source).Value.StepText);+ var plain = source[..source.IndexOf(" Modify", StringComparison.Ordinal)] + "}\n";+ var unmodified = FirmamentBuildAndExport.CompileSource(plain);+ Assert.True(unmodified.IsSuccess);+ Assert.NotEqual(unmodified.Value.StepText, built.Value.StepText);+ Assert.Equal(4, Step242Importer.ImportBody(unmodified.Value.StepText).Value.Topology.Faces.Count());+ }++ [Theory]+ [InlineData(false, false, false, 180d)]+ [InlineData(true, false, false, 180d)]+ [InlineData(false, true, false, 180d)]+ [InlineData(true, true, true, 180d)]+ [InlineData(false, false, true, 120d)]+ [InlineData(true, true, true, 240d)]+ public void BothFinishesRetainSharedIncidenceAndActualSupportCurves(bool clockwise, bool bottom, bool placed, double sweep)+ {+ foreach (var kind in new[] { ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishKind.Chamfer })+ {+ var (profile, target) = Profile(clockwise, bottom, placed, sweep);+ var mixed = ProfileEdgeFinishMixedShellPlanner.TryPlan(profile, target, kind, 1);+ Assert.True(mixed.Succeeded, string.Join("\n", mixed.Diagnostics));+ Assert.Equal("CircularSegmentMiter", mixed.Plan!.JunctionDecision!.Strategy);+ Assert.Single(mixed.Plan.JunctionDecision.Judgment.Candidates, c => c.Admissible);+ if (kind == ProfileEdgeFinishKind.Chamfer)+ {+ var normal = Assert.Single(mixed.Plan.OrderedPatches.OfType<PlanarChamferPatch>()).Surface.Normal;+ var capAxis = profile.EffectiveConstructionPlane.AxisZ.ToVector() * (bottom ? -1 : 1);+ Assert.True(normal.ToVector().Dot(capAxis) > 0); // Outward support, as well as on-surface trims.+ }+ var result = CircularSegmentEdgeFinishMaterializer.TryMaterialize(profile, target, mixed.Plan);+ Assert.True(result.Succeeded, string.Join("\n", result.Diagnostics));+ var body = result.Body!;+ AssertBody(body);+ Assert.Equal(2, result.Correspondence!.Descendants.Count(d => d.Kind == "Edge" && d.GeometryPreview!.Contains("Intersection", StringComparison.Ordinal)));+ Assert.All(body.Topology.Vertices, vertex =>+ {+ Assert.True(body.TryGetVertexPoint(vertex.Id, out var point));+ var local = profile.EffectiveConstructionPlane.ToLocal(point);+ Assert.InRange(local.Z, -1e-7, 8 + 1e-7);+ });+ var step = Step242Exporter.ExportBody(body);+ Assert.True(step.IsSuccess, string.Join("\n", step.Diagnostics.Select(d => d.Message)));+ AssertBody(Step242Importer.ImportBody(step.Value).Value);+ AssertMiterGeometry(profile, result, kind, bottom);+ }+ }++ [Theory]+ [InlineData(5d)]+ [InlineData(6d)]+ [InlineData(8d)]+ public void OversizeFinishesRejectBeforeAllocatingBody(double size)+ {+ var (profile, target) = Profile(false, false, false, 180);+ foreach (var kind in new[] { ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishKind.Chamfer })+ {+ var planned = ProfileEdgeFinishMixedShellPlanner.TryPlan(profile, target, kind, size);+ Assert.False(planned.Succeeded);+ Assert.Null(planned.Plan);+ Assert.Contains(planned.Diagnostics, d => d.Contains(size == 8 ? "Thickness" : "InsetCollapse", StringComparison.Ordinal));+ }+ }++ [Theory]+ [InlineData("fillet")]+ [InlineData("chamfer")]+ public void PreferredAndCompatibilityFieldsProduceIdenticalStep(string kind)+ {+ var source = Source(kind);+ var preferred = FirmamentBuildAndExport.CompileSource(source);+ var compatibility = FirmamentBuildAndExport.CompileSource(FirmamentSourceSpelling.Normalize(source));+ Assert.True(preferred.IsSuccess, string.Join("\n", preferred.Diagnostics.Select(d => d.Message)));+ Assert.True(compatibility.IsSuccess, string.Join("\n", compatibility.Diagnostics.Select(d => d.Message)));+ Assert.Equal(preferred.Value.StepText, compatibility.Value.StepText);+ }++ [Theory]+ [InlineData(-200)]+ [InlineData(200)]+ public void TranslatingTheSketchCannotReverseItsMaterialSide(int y)+ {+ foreach (var kind in new[] { "fillet", "chamfer" })+ {+ var source = Source(kind).Replace("Point2(10mm, 0mm)", $"Point2(10mm, {y}mm)");+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics.Select(d => d.Message)));+ var body = Step242Importer.ImportBody(built.Value.StepText).Value;+ AssertBody(body);+ if (kind == "fillet")+ {+ var torus = Assert.Single(body.Geometry.Surfaces, s => s.Value.Kind == SurfaceGeometryKind.Torus).Value.Torus!.Value;+ Assert.Equal(9, torus.MajorRadius);+ Assert.Equal(y, torus.Center.Y, 7);+ }+ }+ }++ private static void AssertMiterGeometry(ResolvedProfile2D profile, ProfileBoundaryChamferPlanResult result,+ ProfileEdgeFinishKind kind, bool bottom)+ {+ var source = (LineArcCircularArc2D)profile.Loops[0].Segments[0].Geometry;+ var line = (LineArcLineSegment2D)profile.Loops[0].Segments[1].Geometry;+ 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 winding = Math.Sign(source.SweepAngleRadians);+ var nx = -dy / length * winding; var ny = dx / length * winding;+ var k = (line.Start.X - source.Center.X) * nx + (line.Start.Y - source.Center.Y) * ny;+ foreach (var seam in result.Correspondence!.Descendants.Where(d => d.Kind == "Edge"))+ {+ var binding = result.Body!.Bindings.GetEdgeBinding(seam.Edge!.Value);+ var curve = result.Body.Geometry.GetCurve(binding.CurveGeometryId).BSpline3!.Value;+ Assert.Equal(kind == ProfileEdgeFinishKind.Fillet ? 3 : 2, curve.Degree);+ for (var i = 0; i <= 512; i++)+ {+ var p = profile.EffectiveConstructionPlane.ToLocal(curve.Evaluate(curve.DomainStart + (curve.DomainEnd - curve.DomainStart) * i / 512));+ var rise = bottom ? 1 - p.Z : p.Z - 7;+ var inset = kind == ProfileEdgeFinishKind.Fillet ? 1 - Math.Sqrt(Math.Max(0, 1 - rise * rise)) : rise;+ var radial = Math.Sqrt((p.X - source.Center.X) * (p.X - source.Center.X) + (p.Y - source.Center.Y) * (p.Y - source.Center.Y));+ var lineDistance = (p.X - source.Center.X) * nx + (p.Y - source.Center.Y) * ny - k;+ // Comparing implicit support equations avoids the sqrt conditioning+ // at the horizontal cap endpoint of a fillet.+ if (kind == ProfileEdgeFinishKind.Fillet)+ {+ Assert.InRange(Math.Abs((1 - lineDistance) * (1 - lineDistance) + rise * rise - 1), 0, 5e-6);+ Assert.InRange(Math.Abs((radial - 9) * (radial - 9) + rise * rise - 1), 0, 5e-6);+ }+ else+ {+ Assert.InRange(Math.Abs(lineDistance - inset), 0, 1e-9);+ Assert.InRange(Math.Abs(radial - (10 - inset)), 0, 1e-9);+ }+ }+ }+ }++ private static void AssertBody(BrepBody body)+ {+ Assert.Single(body.Topology.Bodies); Assert.Single(body.Topology.Shells);+ Assert.Equal(6, body.Topology.Faces.Count()); Assert.Equal(10, body.Topology.Edges.Count()); Assert.Equal(6, body.Topology.Vertices.Count());+ var preflight = BrepExportPreflight.Validate(body);+ Assert.True(preflight.IsValid, string.Join("\n", preflight.Diagnostics.Select(d => d.Message + ":" + d.MeasuredDeviation)));+ foreach (var edge in body.Topology.Edges)+ {+ var uses = body.Topology.Coedges.Where(c => c.EdgeId == edge.Id).ToArray();+ Assert.Equal(2, uses.Length); Assert.NotEqual(uses[0].IsReversed, uses[1].IsReversed);+ }+ }++ private static (ResolvedProfile2D, ProfileBoundaryChamferTarget) Profile(bool clockwise, bool bottom, bool placed, double sweep)+ {+ var signedSweep = (clockwise ? -1 : 1) * sweep * Math.PI / 180;+ var arc = new LineArcCircularArc2D((0, 0), 10, 0, signedSweep);+ var line = new LineArcLineSegment2D((10 * Math.Cos(signedSweep), 10 * Math.Sin(signedSweep)), (10, 0));+ var frame = placed ? ConstructionPlane.WorldXY with { Origin = new(20, 30, 40),+ AxisY = Direction3D.Create(new(0, 0, 1)), AxisZ = Direction3D.Create(new(0, -1, 0)) } : ConstructionPlane.WorldXY;+ var profile = new ResolvedProfile2D("Section", "XY", [new("Outer", true,+ [new("Round", arc, new("round", "Outline", "fixture", "arc", "XY")),+ new("Flat", line, new("flat", "Outline", "fixture", "chord", "XY"))])], frame, 0, 8);+ var target = new ProfileBoundaryChamferTarget("edgefinish:Rim", "Body", "Section", "Outer", ["Round", "Flat"],+ bottom ? ProfileBoundaryChamferSide.Bottom : ProfileBoundaryChamferSide.Top,+ ProfileBoundaryChamferChainKind.ClosedLoop, "fixture", "SourceOrder");+ return (profile, target);+ }++ private static string Source(string kind) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ $"fixtures/Regression/EdgeFinishRobustness/d-profile-{kind}.firmament"));+}diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/OrdinaryEdgeFinishRobustnessTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/OrdinaryEdgeFinishRobustnessTests.csnew file mode 100644index 00000000..42847a43--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Integration/OrdinaryEdgeFinishRobustnessTests.cs@@ -0,0 +1,95 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests.Integration;++public sealed class OrdinaryEdgeFinishRobustnessTests+{+ [Theory]+ [InlineData(false, false)]+ [InlineData(false, true)]+ [InlineData(true, false)]+ [InlineData(true, true)]+ public void ConvexPolygonRimsAdmitAcuteObtuseAndSubdividedStraightSupports(bool bottom, bool chamfer)+ {+ foreach (var points in new (double, double)[][] {+ [(0, 0), (30, 0), (12, 20)],+ [(0, 0), (30, 0), (38, 20), (0, 20)],+ [(0, 0), (15, 0), (30, 0), (30, 20), (0, 20)] })+ {+ var profile = Polygon(points);+ var target = Target(profile, bottom);+ var result = chamfer ? ProfileBoundaryChamferPlanner.TryPlan(profile, target, 1) : Fillet(profile, target, 1);+ Assert.True(result.Succeeded, string.Join("\n", result.Diagnostics));+ Check(result.Body!);+ var step = Step242Exporter.ExportBody(result.Body!);+ Assert.True(step.IsSuccess, string.Join("\n", step.Diagnostics.Select(d => d.Message)));+ Check(Step242Importer.ImportBody(step.Value).Value);+ }+ }++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public void InvertedInsetIsRejectedInsteadOfEmittingAnInsideOutCap(bool chamfer)+ {+ var profile = Polygon([(0, 0), (30, 0), (30, 4), (0, 4)]);+ var target = Target(profile, false);+ var result = chamfer ? ProfileBoundaryChamferPlanner.TryPlan(profile, target, 3) : Fillet(profile, target, 3);+ Assert.False(result.Succeeded); Assert.Null(result.Body);+ Assert.Contains(result.Diagnostics, d => d.Contains("Inset", StringComparison.Ordinal));+ }++ [Theory]+ [InlineData("profile-edgefinish-chimera-fillet.firmament", false)]+ [InlineData("profile-edgefinish-chimera-chamfer.firmament", true)]+ public void MixedTangentLoopBottomUsesTheSameQualifiedSupports(string fixture, bool chamfer)+ {+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/CanonicalGeometry/" + fixture));+ var profile = ProfileAuthoringParser.Parse(source).Profile!;+ var target = Target(profile, true);+ var result = chamfer ? ProfileBoundaryChamferPlanner.TryPlan(profile, target, 4) : Fillet(profile, target, 4);+ Assert.True(result.Succeeded, string.Join("\n", result.Diagnostics));+ Check(result.Body!);+ var step = Step242Exporter.ExportBody(result.Body!);+ Assert.True(step.IsSuccess, string.Join("\n", step.Diagnostics.Select(d => d.Message)));+ Check(Step242Importer.ImportBody(step.Value).Value);+ }++ private static ProfileBoundaryChamferPlanResult Fillet(ResolvedProfile2D p, ProfileBoundaryChamferTarget t, double radius)+ {+ var result = ProfileFilletShellPlanner.TryPlan(p, t, radius, radius);+ return new(result.Succeeded, result.Body, result.Correspondence, t, result.Diagnostics);+ }+ private static void Check(BrepBody body)+ {+ var preflight = BrepExportPreflight.Validate(body);+ Assert.True(preflight.IsValid, string.Join("\n", preflight.Diagnostics.Select(d => d.Code + ":" + d.Message + ":" + d.MeasuredDeviation)));+ foreach (var edge in body.Topology.Edges)+ {+ var uses = body.Topology.Coedges.Where(c => c.EdgeId == edge.Id).ToArray();+ Assert.Equal(2, uses.Length); Assert.NotEqual(uses[0].IsReversed, uses[1].IsReversed);+ }+ foreach (var loop in body.Topology.Loops)+ {+ for (var i = 0; i < loop.CoedgeIds.Count; i++)+ {+ var use = body.Topology.GetCoedge(loop.CoedgeIds[i]);+ var next = body.Topology.GetCoedge(loop.CoedgeIds[(i + 1) % loop.CoedgeIds.Count]);+ var edge = body.Topology.GetEdge(use.EdgeId); var nextEdge = body.Topology.GetEdge(next.EdgeId);+ Assert.Equal(use.IsReversed ? edge.StartVertexId : edge.EndVertexId,+ next.IsReversed ? nextEdge.EndVertexId : nextEdge.StartVertexId);+ }+ }+ }+ private static ResolvedProfile2D Polygon((double X, double Y)[] points) => new("Section", "XY",+ [new("Outer", true, points.Select((point, i) => new ResolvedProfileSegment2D("Edge" + i,+ new LineArcLineSegment2D(point, points[(i + 1) % points.Length]), new("edge:" + i, "fixture", "fixture", "line", "XY"))).ToArray())],+ LocalStartDepth: 0, LocalEndDepth: 8);+ private static ProfileBoundaryChamferTarget Target(ResolvedProfile2D p, bool bottom) => new("edgefinish:Rim", "Body", p.Name, "Outer",+ p.Loops[0].Segments.Select(s => s.Name).ToArray(), bottom ? ProfileBoundaryChamferSide.Bottom : ProfileBoundaryChamferSide.Top,+ ProfileBoundaryChamferChainKind.ClosedLoop, "fixture", "SourceOrder");+}diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.csindex 8ba0ac11..7d6afb33 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs@@ -295,24 +295,24 @@ public sealed class ProfileBoundaryChamferTests}[Fact]- public void CurvedWholeLoopChamferMaterializesThroughTheMixedPlaneConeShell()+ public void NonTangentCurvedLoopCannotBeReportedValidFromTopologyAlone(){const string chamfer = "Modify Body { EdgeFinish TopBreak { Target: Bracket.Outer On: Top Kind: Chamfer Distance: 4mm } }";Assert.True(ProfileBoundaryChamferSourceBinder.TryBind(chamfer, CurvedProfile(), "Bracket", out var chamferTarget, out var distance, out var chamferDiagnostic), chamferDiagnostic);var chamferPlan = ProfileBoundaryChamferPlanner.TryPlan(CurvedProfile(), chamferTarget!, distance);- Assert.True(chamferPlan.Succeeded, string.Join(Environment.NewLine, chamferPlan.Diagnostics));- Assert.NotNull(chamferPlan.Body);- Assert.Equal(1, chamferPlan.Body!.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Cone));- Assert.True(BrepMassProperties.Evaluate(chamferPlan.Body).IsEnclosed);+ // The unchanged specimen has a 180-degree cusp entering the arc and a+ // sharp unsupported arc/line exit. Its old IsEnclosed assertion proved+ // incidence only, despite the trims missing their analytic supports.+ Assert.False(chamferPlan.Succeeded);+ Assert.Null(chamferPlan.Body);+ Assert.Contains(chamferPlan.Diagnostics, d => d.StartsWith("ProfileEdgeFinishJunctionUnsupported", StringComparison.Ordinal));const 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.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);+ Assert.False(filletPlan.Succeeded);+ Assert.Null(filletPlan.Body);+ Assert.Contains(filletPlan.Diagnostics, d => d.StartsWith("ProfileEdgeFinishJunctionUnsupported", StringComparison.Ordinal));}[Fact]diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.csindex 5dd802fa..186ec548 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishAnalyticPolicyTests.cs@@ -62,6 +62,19 @@ public sealed class ProfileEdgeFinishAnalyticPolicyTestsAssert.Equal("SphereSeamCompatibility", compatibility.CompatibilityOverride);}+ [Theory]+ [InlineData(12d, ProfileEdgeFinishTorusRegime.Ring, ProfileEdgeFinishRegularity.Regular)]+ [InlineData(8d, ProfileEdgeFinishTorusRegime.Horn, ProfileEdgeFinishRegularity.InteropSensitive)]+ [InlineData(6d, ProfileEdgeFinishTorusRegime.Spindle, ProfileEdgeFinishRegularity.InteropSensitive)]+ public void ConvexTorusRegimeUsesBothRadii(double radius, ProfileEdgeFinishTorusRegime regime, ProfileEdgeFinishRegularity regularity)+ {+ var policy = ProfileEdgeFinishAnalyticPolicy.Classify(new("arc", ProfileEdgeFinishKind.Fillet,+ ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex, radius, 4));+ Assert.Equal(regime, policy.TorusRegime);+ Assert.Equal(regularity, policy.Regularity);+ Assert.Equal(radius - 4, policy.TorusMajorRadius);+ }+private static object[] Row(string station, ProfileEdgeFinishSourceFamily source, ProfileEdgeFinishMaterialSide material, double radius, string planner, ProfileEdgeFinishSurfaceFamily surface, ProfileEdgeFinishRegularity regularity, ProfileEdgeFinishAdmission admission)=> [station, source, material, radius, planner, surface, regularity, admission];diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 855dc9b3..f6a33b61 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -19,6 +19,7 @@ using Aetheris.Kernel.Core.Topology;using Aetheris.Kernel.Firmament.Execution;using Aetheris.Kernel.Firmament.Lowering;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Firmament.Materializer;using Aetheris.Kernel.StandardLibrary;using Aetheris.Kernel.Firmament.Structural;@@ -504,7 +505,7 @@ public static class FirmamentBuildAndExportvar emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);if (emitted.Status != LineArcProfileExtrudeStatus.Succeeded || emitted.Body is null) return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());if (materializerSource.Contains("EdgeFinish", StringComparison.Ordinal))- return ExportProfileSemanticTopBoundaryChamfer(materializerSource, parsed.Profile, parsed.Height, emitted);+ return ExportProfileSemanticTopBoundaryChamfer(materializerSource, parsed.Profile, parsed.Height, emitted, v2Parse.DiagnosticSource);var step = Step242Exporter.ExportBody(emitted.Body); if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, parsed.Profile.Name, 0, "profile-extrude", "line-arc-profile"));}@@ -1094,6 +1095,7 @@ public static class FirmamentBuildAndExport{KernelResult<FirmamentStepExportResult> Fail(string code) => KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.ComposeSemanticSelection")]);+ if (ProfileBoundaryChamferSourceBinder.SequenceDiagnostic(source) is { } sequenceDiagnostic) return Fail(sequenceDiagnostic);if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)){if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))@@ -1179,10 +1181,24 @@ public static class FirmamentBuildAndExportstring source,ResolvedProfile2D profile,double height,- LineArcProfileExtrudeResult emitted)+ LineArcProfileExtrudeResult emitted,+ string? diagnosticSource){+ var finishes = ProfileBoundaryChamferSourceBinder.FinishDeclarations(source).ToArray();+ // The legacy materializer transport removes the enclosing Model. Return+ // the corresponding declaration in the frontend's retained source, so+ // the common provenance mapper receives offsets in its own input.+ // A sequence fails at the second requested operation. Recipes are not+ // operations and must not displace a real operation's diagnostic anchor.+ var rejectedFinish = finishes.ElementAtOrDefault(finishes.Length > 1 ? 1 : 0);+ var anchors = diagnosticSource is null ? rejectedFinish is null ? [] : new[] { rejectedFinish }+ : ProfileBoundaryChamferSourceBinder.FinishDeclarations(diagnosticSource)+ .Where(d => rejectedFinish is not null && d.Name?.Text == rejectedFinish.Name?.Text).ToArray();+ var finishSpan = anchors.Length == 1 ? anchors[0].Span : (FirmamentV2SourceSpan?)null;KernelResult<FirmamentStepExportResult> Fail(string code) => KernelResult<FirmamentStepExportResult>.Failure([- new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.SemanticSelection")]);+ new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.SemanticSelection")+ { SourceSpan = finishSpan is { } span ? new(span.Start, span.Length) { LocationNote = "EdgeFinish declaration; the planner reports the enclosing operation." } : null }]);+ if (ProfileBoundaryChamferSourceBinder.SequenceDiagnostic(source) is { } sequenceDiagnostic) return Fail(sequenceDiagnostic);if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)){if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))@@ -1216,7 +1232,14 @@ public static class FirmamentBuildAndExport: fillet.Plan.Junction is ProfileReflexSphereSeamCompatibilityJunctionPlan? "profile-reflex-sphere-seam-compatibility": "profile-convex-fillet-junction";- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(filletStep.Value, filletTarget.StableId, fillet.Correspondence.Descendants.Count, route, "source-grounded-profile-fillet"));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(filletStep.Value, filletTarget.StableId, fillet.Correspondence.Descendants.Count, route, "source-grounded-profile-fillet")+ {+ RuntimeBody = fillet.Body, RuntimeCorrespondence = fillet.Correspondence,+ EdgeFinishPlanning = fillet.PlanningEvidence,+ EngineeringFeatures = [new(filletTarget.StableId["edgefinish:".Length..], "EdgeFinish", filletTarget.StableId,+ filletTarget.HostBodyId, filletTarget.Side.ToString(), $"{profile.Name}.{filletTarget.LoopId}", radius,+ "Radius", "Remove", PolicySource: "Fillet", MaterializationRoute: fillet.PlanningEvidence?.Decision.Strategy ?? route)]+ });}if (!ProfileBoundaryChamferSourceBinder.TryBind(source, profile, profile.Name, out var target, out var distance, out var bindingDiagnostic))return Fail(bindingDiagnostic ?? "ProfileBoundaryChamferBindingFailed");@@ -1234,7 +1257,14 @@ public static class FirmamentBuildAndExportif (!plannedStep.IsSuccess || plannedStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(plannedStep.Diagnostics);var plannedReimport = Step242Importer.ImportBody(plannedStep.Value);if (!plannedReimport.IsSuccess || plannedReimport.Value is null || !FirmamentManifoldChecker.IsManifold(plannedReimport.Value)) return Fail("ProfileBoundaryChamferStepReimportFailed");- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(plannedStep.Value, target.StableId, 0, "profile-boundary-chamfer-section-stack", "source-grounded-profile-boundary-chamfer"));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(plannedStep.Value, target.StableId, 0, "profile-boundary-chamfer-section-stack", "source-grounded-profile-boundary-chamfer")+ {+ RuntimeBody = planned.Body, RuntimeCorrespondence = planned.Correspondence,+ EdgeFinishPlanning = planned.PlanningEvidence,+ EngineeringFeatures = [new(target.StableId["edgefinish:".Length..], "EdgeFinish", target.StableId,+ target.HostBodyId, target.Side.ToString(), $"{profile.Name}.{target.LoopId}", distance,+ "Distance", "Remove", PolicySource: "Chamfer", MaterializationRoute: planned.PlanningEvidence?.Decision.Strategy ?? "ProfileBoundaryChamfer")]+ });}if (emitted.Body is null || emitted.Correspondence is null) return Fail("NoMaterializedDescendants");if (!IsAdmittedPrimitiveBoundary(profile.Loops.Single().Segments.Select(segment => segment.Geometry).ToArray()))diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 8fee46db..093d3aab 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -48,6 +48,7 @@ public sealed record FirmamentStepExportResult([JsonIgnore] internal Aetheris.Kernel.Firmament.FirmamentV2.FirmamentV2Document? RuntimeAdmissionDocument { get; init; }public FirmamentCirRetention? Cir { get; init; }public FirmamentMakerMarkReport? MakerMark { get; init; }+ public ProfileEdgeFinishEvidence? EdgeFinishPlanning { get; init; }}public sealed record FirmamentMakerMarkReport(string Content, double HeightMm, double DepthMm, int CounterCount);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 4f2fa413..8e32cdf0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -261,7 +261,8 @@ public static class FirmamentSourceSpellingAdd("Segment", "Trace From To Sweep");Add("Replace", "On Range Through Derivatives Join StartTangent EndTangent Interpolation SpanNames");Add("Path", "Start Heading");- Add("Line", "Length To");+ Add("Line", "Length To Turn Heading");+ Add("Arc", "Radius Turn");Add("Extrude Base", "Profile From To Role");Add("Boss Pocket", "On Profile Height Depth");Add("Linear", "Source Direction Count Spacing Keys Start Step");diff --git a/Aetheris.Kernel.Firmament/Materializer/CircularSegmentEdgeFinishMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/CircularSegmentEdgeFinishMaterializer.csnew file mode 100644index 00000000..7364cffe--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/CircularSegmentEdgeFinishMaterializer.cs@@ -0,0 +1,233 @@+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.Numerics;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>+/// Ordinary CAD rim finish on a circular segment (arc plus chord). The cap is+/// the intersection of the inset circle and inset half-plane. Adjacent finish+/// supports share their actual intersection, never a guessed tangent meridian.+/// Chamfer seams are exact quadratic parabolas; fillet seams are certified+/// cubic representations of the analytic cylinder/torus intersection.+/// </summary>+public static class CircularSegmentEdgeFinishMaterializer+{+ public static ProfileBoundaryChamferPlanResult TryMaterialize(ResolvedProfile2D profile,+ ProfileBoundaryChamferTarget target, ProfileEdgeFinishMixedShellPlan plan)+ {+ ProfileBoundaryChamferPlanResult Fail(string message) => new(false, null, null, target, [message]);+ if (plan.JunctionDecision is not { Strategy: "CircularSegmentMiter", CircularSegment: { } segment })+ return Fail("ProfileEdgeFinishCircularSegmentPlanRequired");+ if (plan.Target != target || target.ChainKind != ProfileBoundaryChamferChainKind.ClosedLoop)+ return Fail("ProfileEdgeFinishCircularSegmentTargetMismatch");+ if (target.ReflexJunctionStyle != ProfileReflexJunctionStyle.ToroidalRolling)+ return Fail("ProfileBoundaryFilletReflexJunctionStyleRequiresReflexPair");+ var loop = profile.Loops.SingleOrDefault(l => l.Name == target.LoopId);+ if (loop is null || loop.Segments.Count != 2 || !target.SegmentIds.SequenceEqual(loop.Segments.Select(s => s.Name)))+ return Fail("ProfileEdgeFinishCircularSegmentProfileMismatch");+ var frame = profile.EffectiveConstructionPlane;+ var arc = (LineArcCircularArc2D)loop.Segments[segment.ArcIndex].Geometry;+ var size = plan.FinishSize;+ var round = plan.FinishKind == ProfileEdgeFinishKind.Fillet;+ var direction = target.Side == ProfileBoundaryChamferSide.Top ? 1d : -1d;+ var capDepth = direction > 0 ? profile.LocalEndDepth ?? 1 : profile.LocalStartDepth ?? -1;+ var baseDepth = direction > 0 ? profile.LocalStartDepth ?? -1 : profile.LocalEndDepth ?? 1;+ var transition = capDepth - direction * size;+ var capOut = Direction3D.Create(frame.AxisZ.ToVector() * direction);+ var reverseFaces = direction * segment.WindingSign < 0;+ var tangent = Direction3D.Create(frame.ToWorldDirection(new(segment.Tangent.X, segment.Tangent.Y, 0)));+ var inward = Direction3D.Create(frame.ToWorldDirection(new(segment.Inward.X, segment.Inward.Y, 0)));+ var r = segment.Radius; var k = segment.ChordDistance;+ var capX = Math.Sqrt((r - size) * (r - size) - (k + size) * (k + size));+ var builder = new TopologyBuilder();+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var points = new Dictionary<VertexId, Point3D>();+ var descendants = new List<SemanticTopologyDescendant>();+ var nextCurve = 1; var nextSurface = 1;+ var lower = new VertexId[2]; var middle = new VertexId[2]; var upper = new VertexId[2];+ var bottomEdges = new EdgeId[2]; var middleEdges = new EdgeId[2]; var topEdges = new EdgeId[2];+ var verticalEdges = new EdgeId[2]; var seams = new EdgeId[2];+ var capPoints = new (double X, double Y)[2];+ var maxDeviation = 0d;++ VertexId Vertex(Point3D point)+ {+ var vertex = builder.AddVertex(); points.Add(vertex, point); return vertex;+ }+ EdgeId Edge(VertexId a, VertexId b, CurveGeometry curve, ParameterInterval trim, bool sameSense = true)+ {+ var edge = builder.AddEdge(a, b);+ var id = new CurveGeometryId(nextCurve++); geometry.AddCurve(id, curve);+ bindings.AddEdgeBinding(new(edge, id, trim, sameSense)); return edge;+ }+ EdgeId Line(VertexId a, VertexId b) => Edge(a, b,+ CurveGeometry.FromLine(new(points[a], Direction3D.Create(points[b] - points[a]))),+ new(0, (points[b] - points[a]).Length));+ (EdgeId Edge, bool Reverse) Use(EdgeId edge, VertexId start)+ => (edge, builder.Model.Edges.Single(e => e.Id == edge).StartVertexId != start);+ void Face(string name, IReadOnlyList<(EdgeId Edge, bool Reverse)> sourceUses, SurfaceGeometry surface,+ SemanticTopologyRole role, string source)+ {+ // A digon with an arc and a chord is a legitimate face boundary.+ var uses = reverseFaces ? sourceUses.Reverse().Select(u => (u.Edge, Reverse: !u.Reverse)).ToArray() : sourceUses.ToArray();+ var id = builder.AllocateLoopId(); var coedges = uses.Select(_ => builder.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < uses.Length; i++)+ builder.AddCoedge(new(coedges[i], uses[i].Edge, id, coedges[(i + 1) % uses.Length],+ coedges[(i + uses.Length - 1) % uses.Length], uses[i].Reverse));+ builder.AddLoop(new Loop(id, coedges)); var face = builder.AddFace([id]);+ var surfaceId = new SurfaceGeometryId(nextSurface++); geometry.AddSurface(surfaceId, surface);+ bindings.AddFaceBinding(new(face, surfaceId, true));+ descendants.Add(new($"{target.StableId}:{name}", "Face", role, source, Face: face, ParentStableId: target.StableId));+ }+ EdgeId ProfileEdge(int i, double depth, bool inset, VertexId a, VertexId b)+ {+ if (i == segment.LineIndex) return Line(a, b);+ var start = inset ? capPoints[i] : Start(arc);+ var end = inset ? capPoints[1 - i] : End(arc);+ var angleA = Math.Atan2(start.Y - arc.Center.Y, start.X - arc.Center.X);+ var angleB = Math.Atan2(end.Y - arc.Center.Y, end.X - arc.Center.X);+ if (arc.SweepAngleRadians > 0) { while (angleB <= angleA) angleB += 2 * Math.PI; }+ else { while (angleB >= angleA) angleB -= 2 * Math.PI; }+ return Edge(a, b, CurveGeometry.FromCircle(new(frame.ToWorld(arc.Center, depth), frame.AxisZ,+ inset ? r - size : r, frame.AxisX)), new(Math.Min(angleA, angleB), Math.Max(angleA, angleB)), arc.SweepAngleRadians > 0);+ }++ try+ {+ for (var i = 0; i < 2; i++)+ {+ var sourcePoint = Start(loop.Segments[i].Geometry);+ var x = (sourcePoint.X - segment.Center.X) * segment.Tangent.X + (sourcePoint.Y - segment.Center.Y) * segment.Tangent.Y;+ var sign = Math.Sign(x);+ capPoints[i] = (segment.Center.X + sign * capX * segment.Tangent.X + (k + size) * segment.Inward.X,+ segment.Center.Y + sign * capX * segment.Tangent.Y + (k + size) * segment.Inward.Y);+ lower[i] = Vertex(frame.ToWorld(sourcePoint, baseDepth));+ middle[i] = Vertex(frame.ToWorld(sourcePoint, transition));+ upper[i] = Vertex(frame.ToWorld(capPoints[i], capDepth));+ verticalEdges[i] = Line(lower[i], middle[i]);+ var miter = CircularSegmentFinishMiter.Create(segment, frame, transition, direction, size, sign, round);+ maxDeviation = Math.Max(maxDeviation, miter.DeviationBound);+ seams[i] = Edge(middle[i], upper[i], miter.Curve, miter.Trim);+ descendants.Add(new($"{target.StableId}:miter:{loop.Segments[i].Name}.Start", "Edge", SemanticTopologyRole.ComposeTransition,+ $"profile-junction:{loop.Name}.{loop.Segments[i].Name}.Start", Edge: seams[i], ParentStableId: target.StableId,+ GeometryPreview: round ? "CylinderTorusIntersection:CertifiedCubic" : "PlaneConeIntersection:ExactQuadratic"));+ }+ for (var i = 0; i < 2; i++)+ {+ var next = 1 - i;+ bottomEdges[i] = ProfileEdge(i, baseDepth, false, lower[i], lower[next]);+ middleEdges[i] = ProfileEdge(i, transition, false, middle[i], middle[next]);+ topEdges[i] = ProfileEdge(i, capDepth, true, upper[i], upper[next]);+ }+ var loopSource = $"profile:{profile.Name}.{loop.Name}";+ Face("bottom-cap", [Use(bottomEdges[1], lower[0]), Use(bottomEdges[0], lower[1])],+ SurfaceGeometry.FromPlane(new(frame.ToWorld((0d, 0d), baseDepth), Direction3D.Create(-capOut.ToVector()), frame.AxisX)),+ SemanticTopologyRole.BottomFaceBoundaryLoop, loopSource);+ Face("top-cap", [Use(topEdges[0], upper[0]), Use(topEdges[1], upper[1])],+ SurfaceGeometry.FromPlane(new(frame.ToWorld((0d, 0d), capDepth), capOut, frame.AxisX)),+ SemanticTopologyRole.TopFaceBoundaryLoop, loopSource);+ for (var i = 0; i < 2; i++)+ {+ var next = 1 - i;+ var source = loop.Segments[i].Provenance.StableId;+ var side = i == segment.ArcIndex+ ? SurfaceGeometry.FromCylinder(new(frame.ToWorld(segment.Center, baseDepth), frame.AxisZ, r, frame.AxisX))+ : SurfaceGeometry.FromPlane(new(points[lower[i]], Direction3D.Create(-inward.ToVector()), tangent));+ Face($"side:{loop.Segments[i].Name}", [Use(bottomEdges[i], lower[i]), Use(verticalEdges[next], lower[next]),+ Use(middleEdges[i], middle[next]), Use(verticalEdges[i], middle[i])], side, SemanticTopologyRole.ExtrusionSideFace, source);+ var patch = plan.OrderedPatches[i] switch+ {+ CylindricalFilletPatch cylinder => SurfaceGeometry.FromCylinder(cylinder.Surface),+ ToroidalFilletPatch torus => SurfaceGeometry.FromTorus(torus.Surface),+ PlanarChamferPatch plane => SurfaceGeometry.FromPlane(plane.Surface),+ ConicalChamferPatch cone => SurfaceGeometry.FromCone(cone.Surface),+ _ => throw new InvalidOperationException("ProfileEdgeFinishCircularSegmentPatchMismatch")+ };+ Face($"finish:{loop.Segments[i].Name}", [Use(middleEdges[i], middle[i]), Use(seams[next], middle[next]),+ Use(topEdges[i], upper[next]), Use(seams[i], upper[i])], patch,+ round ? SemanticTopologyRole.FilletSurface : SemanticTopologyRole.EdgeFinishReplacementFace, source);+ }+ var shell = builder.AddShell(builder.Model.Faces.Select(f => f.Id).ToArray()); builder.AddBody([shell]);+ var body = new BrepBody(builder.Model, geometry, bindings, points);+ var check = BrepBindingValidator.Validate(body, true);+ if (!check.IsSuccess) return Fail("ProfileEdgeFinishCircularSegmentBindingInvalid");+ var correspondence = new SemanticTopologyCorrespondence(target.HostBodyId, descendants,+ ["ResolvedProfile2D", "CircularSegmentMiter", "SharedIntersectionEdges", "JudgmentBeforeEmission"]);+ return new(true, body, correspondence, target,+ ["ProfileEdgeFinishCircularSegmentMiter", $"MiterDeviationBoundMm={maxDeviation:R}"])+ { PlanningEvidence = new(plan.JunctionDecision, maxDeviation) };+ }+ catch (InvalidOperationException e) { return Fail(e.Message); }+ }++ 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 InvalidOperationException("ProfileEdgeFinishCircularSegmentCurveRequired")+ };+ private static (double X, double Y) 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));+}++internal sealed record CircularSegmentFinishMiter(CurveGeometry Curve, ParameterInterval Trim, double DeviationBound)+{+ internal static CircularSegmentFinishMiter Create(CircularSegmentEdgeFinishPlan segment,+ ConstructionPlane frame, double transition, double direction, double size, double sign, bool round)+ {+ var r = segment.Radius; var k = segment.ChordDistance;+ Point3D Point(double x, double inset, double rise) => frame.ToWorld(+ (segment.Center.X + sign * x * segment.Tangent.X + (k + inset) * segment.Inward.X,+ segment.Center.Y + sign * x * segment.Tangent.Y + (k + inset) * segment.Inward.Y), transition + direction * rise);+ Vector3D Vector(double x, double inset, double rise) => frame.ToWorldDirection(new(+ sign * x * segment.Tangent.X + inset * segment.Inward.X,+ sign * x * segment.Tangent.Y + inset * segment.Inward.Y, direction * rise));+ var a = r * r - k * k - 2 * (r + k) * size;+ var b = 2 * (r + k) * size;+ if (!round)+ {+ // Parameter x is linear; d=(R²-k²-x²)/(2(R+k)) is quadratic.+ // A degree-two Bezier therefore represents the parabola exactly.+ var x0 = Math.Sqrt(r * r - k * k); var x1 = Math.Sqrt(a); var dx = x1 - x0;+ var p0 = Point(x0, 0, 0); var p2 = Point(x1, size, size);+ var derivative = Vector(dx, -x0 * dx / (r + k), -x0 * dx / (r + k));+ var spline = new BSpline3Curve(2, [p0, p0 + derivative * .5, p2], [3, 3], [0, 1], "UNSPECIFIED", false, false, "UNSPECIFIED");+ return new(CurveGeometry.FromBSpline(spline), new(0, 1), 0);+ }+ Point3D Evaluate(double t) => Point(Math.Sqrt(a + b * Math.Cos(t)), size * (1 - Math.Cos(t)), size * Math.Sin(t));+ Vector3D Derivative(double t) => Vector(-b * Math.Sin(t) / (2 * Math.Sqrt(a + b * Math.Cos(t))), size * Math.Sin(t), size * Math.Cos(t));+ // For x=sqrt(g), |g^(n)| <= b and g >= a > 0. Chain rule gives+ // this global fourth-derivative bound. y,z each contribute at most size.+ var fourthX = 15 * Math.Pow(b, 4) / (16 * Math.Pow(a, 3.5))+ + 9 * Math.Pow(b, 3) / (4 * Math.Pow(a, 2.5))+ + 7 * b * b / (4 * Math.Pow(a, 1.5)) + b / (2 * Math.Sqrt(a));+ var fourth = Math.Sqrt(fourthX * fourthX + 2 * size * size);+ var origin = frame.ToWorld(segment.Center, transition);+ var scale = Math.Max(1, Math.Max(Math.Max(Math.Abs(origin.X), Math.Abs(origin.Y)), Math.Max(Math.Abs(origin.Z), r + size)));+ var allowance = 256 * 2.2204460492503131e-16 * scale;+ var budget = ToleranceContext.Default.Linear - allowance;+ if (budget <= 0 || !double.IsFinite(fourth)) throw new InvalidOperationException("ProfileEdgeFinishMiterNumericToleranceExhausted");+ var count = 1;+ double Bound(int n) => fourth * Math.Pow(Math.PI / (2 * n), 4) / 384;+ while (Bound(count) > budget && count < 16384) count *= 2;+ if (Bound(count) > budget) throw new InvalidOperationException("ProfileEdgeFinishMiterRefinementLimit");+ var controls = new List<Point3D>(4 * count); var knots = new List<double>(); var multiplicities = new List<int>();+ knots.Add(0); multiplicities.Add(4);+ for (var i = 0; i < count; i++)+ {+ var start = Math.PI * i / (2 * count); var end = Math.PI * (i + 1) / (2 * count); var h = end - start;+ var p0 = Evaluate(start); var p3 = Evaluate(end);+ controls.Add(p0); controls.Add(p0 + Derivative(start) * (h / 3));+ controls.Add(p3 - Derivative(end) * (h / 3)); controls.Add(p3);+ knots.Add(end); multiplicities.Add(4);+ }+ var curve = new BSpline3Curve(3, controls, multiplicities, knots, "UNSPECIFIED", false, false, "UNSPECIFIED");+ return new(CurveGeometry.FromBSpline(curve), new(0, Math.PI / 2), Bound(count) + allowance);+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.csindex f9353de8..93a02a02 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs@@ -30,7 +30,10 @@ public sealed record ProfileBoundaryChamferTarget(ProfileReflexJunctionStyle ReflexJunctionStyle = ProfileReflexJunctionStyle.ToroidalRolling);public sealed record ProfileBoundaryChamferPlanResult(bool Succeeded, BrepBody? Body, SemanticTopologyCorrespondence? Correspondence,- ProfileBoundaryChamferTarget? Target, IReadOnlyList<string> Diagnostics);+ ProfileBoundaryChamferTarget? Target, IReadOnlyList<string> Diagnostics)+{+ public ProfileEdgeFinishEvidence? PlanningEvidence { get; init; }+}/// <summary>/// M1's source-selected round. It is deliberately a separate, non-generic plan: it@@ -50,7 +53,6 @@ public sealed record ProfileStraightEdgeFilletPlanResult(public static class ProfileBoundaryChamferSourceBinder{- private static readonly Regex EdgeFinishHeader = new(@"\bEdgeFinish\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex Target = new(@"\bTarget\s*:\s*(?<value>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*){0,2})", RegexOptions.CultureInvariant);private static readonly Regex On = new(@"\bOn\s*:\s*(?<value>Top|Bottom)\b", RegexOptions.CultureInvariant);private static readonly Regex Kind = new(@"\bKind\s*:\s*(?<value>\w+)\b", RegexOptions.CultureInvariant);@@ -58,23 +60,38 @@ public static class ProfileBoundaryChamferSourceBinderprivate static readonly Regex Radius = new(@"\bRadius\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);private static readonly Regex EndClearance = new(@"\bEndClearance\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);private static readonly Regex ReflexJunction = new(@"\bReflexJunction\s*:\s*(?<value>\w+)\b", RegexOptions.CultureInvariant);- private static readonly Regex SelectionHeader = new(@"\bSelection\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex CanonicalSelection = new(@"\bSource\s*:\s*(?<profile>\w+)\.(?<loop>\w+)\.\[\s*(?<segments>[\w\s,]+)\s*\]", RegexOptions.CultureInvariant);- private static readonly Regex HistoricalSelection = new(@"\bSource\s*:\s*(?<profile>\w+)\.ProfileSegments\s*\(\s*\[(?<segments>[\w\s,]+)\]\s*\)", RegexOptions.CultureInvariant);- private static readonly Regex Require = new(@"\bRequire\s*:\s*(?<value>ConnectedChain|ClosedLoop)\b", RegexOptions.CultureInvariant);public static bool HasSemanticProfileBoundaryFinish(string source) =>- EdgeFinishHeader.Matches(source).Cast<Match>().Any(header =>- {- var body = Block(source, header.Index + header.Length - 1);- return body is not null && On.IsMatch(body);- });+ FinishDeclarations(source).Any(d => d.Body?.Statements.OfType<FieldSyntax>()+ .Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "On") &&+ FirmamentSyntaxValues.Reference(f.Value) is "Top" or "Bottom") == true);- public static bool HasProfileBoundaryFillet(string source) => EdgeFinishHeader.Matches(source).Cast<Match>().Any(header =>+ public static bool HasProfileBoundaryFillet(string source) => FinishDeclarations(source).Any(d =>+ d.Body?.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "On") &&+ FirmamentSyntaxValues.Reference(f.Value) is "Top" or "Bottom") == true &&+ d.Body.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Kind") &&+ FirmamentSyntaxValues.Reference(f.Value) == "Fillet"));++ internal static IEnumerable<DeclarationSyntax> FinishDeclarations(string source){- var body = Block(source, header.Index + header.Length - 1);- return body is not null && On.IsMatch(body) && string.Equals(Kind.Match(body).Groups["value"].Value, "Fillet", StringComparison.Ordinal);- });+ // Reuse executable construction ownership. A Feature/Template definition+ // describes a recipe; its uncalled body is not another requested finish.+ foreach (var declaration in FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements))+ {+ if (declaration.Type.Name.Text == "EdgeFinish") yield return declaration;+ if (declaration.Type.Name.Text is "Modify" or "Compose")+ foreach (var finish in declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "EdgeFinish") ?? [])+ yield return finish;+ }+ }++ private static string Word(DeclarationSyntax declaration, string field) => declaration.Body?.Statements.OfType<FieldSyntax>()+ .Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, field)).Select(f => FirmamentSyntaxValues.Reference(f.Value)).FirstOrDefault() ?? "";++ internal static string? SequenceDiagnostic(string source) => SequenceDiagnostic(FinishDeclarations(source).ToArray());+ private static string? SequenceDiagnostic(IReadOnlyList<DeclarationSyntax> finishes) => finishes.Count > 1+ ? "ProfileBoundaryEdgeFinishSequenceUnsupported: This Profile materializer admits one EdgeFinish operation; multiple requested finishes cannot be compiled as a first-operation-only result."+ : null;/// <summary>/// Resolves the source-bound fillet target into Profile order. This is shared@@ -85,9 +102,11 @@ public static class ProfileBoundaryChamferSourceBinderpublic static bool TryBindFillet(string source, ResolvedProfile2D profile, string hostBodyId, out ProfileBoundaryChamferTarget? target, out double radius, out double endClearance, out string? diagnostic){target = null; radius = 0d; endClearance = 0d; diagnostic = null;- var finish = EdgeFinishHeader.Matches(source).Cast<Match>().Select(match => (Match: match, Body: Block(source, match.Index + match.Length - 1))).FirstOrDefault(x => x.Body is not null && On.IsMatch(x.Body) && string.Equals(Kind.Match(x.Body).Groups["value"].Value, "Fillet", StringComparison.Ordinal));- if (finish.Body is null) { diagnostic = "ProfileBoundaryFilletBoundaryRequired"; return false; }- var fields = new FinishFields(source, finish.Match.Index, finish.Body);+ var finishes = FinishDeclarations(source).ToArray();+ if (SequenceDiagnostic(finishes) is { } sequenceDiagnostic) { diagnostic = sequenceDiagnostic; return false; }+ var finish = finishes.FirstOrDefault(d => Word(d, "On") is "Top" or "Bottom" && Word(d, "Kind") == "Fillet");+ if (finish?.Body is null) { diagnostic = "ProfileBoundaryFilletBoundaryRequired"; return false; }+ var fields = new FinishFields(finish);fields.Read("Kind", Kind);var profileMode = fields.Read("Profile", new Regex(@"\bProfile\s*:\s*(?<mode>[^\s;}]+)", RegexOptions.CultureInvariant));if (profileMode.Success && profileMode.Groups["mode"].Value != "Circular")@@ -112,18 +131,9 @@ public static class ProfileBoundaryChamferSourceBinder}else{- var selection = SelectionHeader.Matches(source).Cast<Match>()- .Select(match => (Match: match, Body: Block(source, match.Index + match.Length - 1)))- .FirstOrDefault(x => string.Equals(x.Match.Groups["name"].Value, rawTarget, StringComparison.Ordinal));- if (selection.Body is null) { diagnostic = "ProfileBoundaryFilletTargetUnknown"; return false; }- var canonical = CanonicalSelection.Match(selection.Body); var historical = HistoricalSelection.Match(selection.Body);- var selectionSource = canonical.Success ? canonical : historical; var requirement = Require.Match(selection.Body);- if (!selectionSource.Success || !requirement.Success) { diagnostic = "ProfileBoundaryFilletSelectionKindUnsupported"; return false; }- requestedProfile = selectionSource.Groups["profile"].Value;- requestedLoop = canonical.Success ? canonical.Groups["loop"].Value : "Outer";- requestedSegments = selectionSource.Groups["segments"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);- chainKind = string.Equals(requirement.Groups["value"].Value, "ClosedLoop", StringComparison.Ordinal)- ? ProfileBoundaryChamferChainKind.ClosedLoop : ProfileBoundaryChamferChainKind.OpenConnectedChain;+ if (!TrySelection(source, rawTarget, out var selection, out diagnostic)) return false;+ requestedProfile = selection!.Profile; requestedLoop = selection.Loop;+ requestedSegments = selection.Segments; chainKind = selection.Kind;provenance = $"Selection:{rawTarget}";}if (!string.Equals(requestedProfile, profile.Name, StringComparison.Ordinal)) { diagnostic = "ProfileBoundaryFilletProfileUnknown"; return false; }@@ -142,34 +152,39 @@ public static class ProfileBoundaryChamferSourceBinderelse if (ordered.Count == 1) chainKind = ProfileBoundaryChamferChainKind.SingleSegment;var orderedSegments = ordered.Select(index => loop.Segments[index]).ToArray();+ if (closed && clearanceMatch.Success) { diagnostic = "ProfileBoundaryFilletEndClearanceRequiresOpenChain: Closed loops have no endpoint clearance; remove endClearance."; return false; }+endClearance = clearanceMatch.Success && double.TryParse(clearanceMatch.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var explicitClearance) ? explicitClearance : radius;if (!double.IsFinite(endClearance) || endClearance <= 0d) { diagnostic = "ProfileBoundaryFilletEndClearanceMustBePositive"; return false; }var reflexJunctionMatch = fields.Read("ReflexJunction", ReflexJunction);var reflexJunctionStyle = ProfileReflexJunctionStyle.ToroidalRolling;- if (reflexJunctionMatch.Success && !Enum.TryParse(reflexJunctionMatch.Groups["value"].Value, ignoreCase: false, out reflexJunctionStyle))+ if (reflexJunctionMatch.Success && (!Enum.TryParse(reflexJunctionMatch.Groups["value"].Value, ignoreCase: false, out reflexJunctionStyle) ||+ !Enum.IsDefined(reflexJunctionStyle) || reflexJunctionMatch.Groups["value"].Value != reflexJunctionStyle.ToString())){diagnostic = "ProfileBoundaryFilletReflexJunctionStyleUnsupported";return false;}if (!fields.Complete(out diagnostic)) return false;- target = new($"edgefinish:{finish.Match.Groups["name"].Value}", hostBodyId, profile.Name, loop.Name,+ target = new($"edgefinish:{finish.Name?.Text}", hostBodyId, profile.Name, loop.Name,orderedSegments.Select(segment => segment.Name).ToArray(), Enum.Parse<ProfileBoundaryChamferSide>(on.Groups["value"].Value),- chainKind, $"offset:{finish.Match.Index}", provenance, reflexJunctionStyle);+ chainKind, $"offset:{finish.Span.Start}", provenance, reflexJunctionStyle);return true;}public static bool TryBind(string source, ResolvedProfile2D profile, string hostBodyId, out ProfileBoundaryChamferTarget? target, out double distance, out string? diagnostic){target = null; distance = 0d; diagnostic = null;- var finish = EdgeFinishHeader.Matches(source).Cast<Match>().Select(match => (Match: match, Body: Block(source, match.Index + match.Length - 1))).FirstOrDefault(x => x.Body is not null && On.IsMatch(x.Body));- if (finish.Body is null) { diagnostic = "ProfileBoundaryChamferBoundaryRequired"; return false; }- var name = finish.Match.Groups["name"].Value;- var fields = new FinishFields(source, finish.Match.Index, finish.Body);+ var finishes = FinishDeclarations(source).ToArray();+ if (SequenceDiagnostic(finishes) is { } sequenceDiagnostic) { diagnostic = sequenceDiagnostic; return false; }+ var finish = finishes.FirstOrDefault(d => Word(d, "On") is "Top" or "Bottom");+ if (finish?.Body is null) { diagnostic = "ProfileBoundaryChamferBoundaryRequired"; return false; }+ var name = finish.Name?.Text;+ var fields = new FinishFields(finish);var targetMatch = fields.Read("Target", Target); var on = fields.Read("On", On); var kind = fields.Read("Kind", Kind); var amount = fields.Read("Distance", Distance);if (!targetMatch.Success || !on.Success || !kind.Success) { diagnostic = "ProfileBoundaryChamferDeclarationInvalid"; return false; }if (string.Equals(kind.Groups["value"].Value, "Fillet", StringComparison.Ordinal)){- diagnostic = Radius.IsMatch(finish.Body) ? "ProfileBoundaryFilletNotMaterialized" : "ProfileBoundaryFilletRadiusRequired";+ diagnostic = fields.Read("Radius", Radius).Success ? "ProfileBoundaryFilletNotMaterialized" : "ProfileBoundaryFilletRadiusRequired";return false;}if (!amount.Success) { diagnostic = "ProfileBoundaryChamferDeclarationInvalid"; return false; }@@ -188,14 +203,9 @@ public static class ProfileBoundaryChamferSourceBinder}else{- var selection = SelectionHeader.Matches(source).Cast<Match>().Select(match => (Match: match, Body: Block(source, match.Index + match.Length - 1))).FirstOrDefault(x => x.Match.Groups["name"].Value == rawTarget);- if (selection.Body is null) { diagnostic = "ProfileBoundaryChamferTargetUnknown"; return false; }- var canonical = CanonicalSelection.Match(selection.Body); var historical = HistoricalSelection.Match(selection.Body); var sourceMatch = canonical.Success ? canonical : historical;- var require = Require.Match(selection.Body);- if (!sourceMatch.Success || !require.Success) { diagnostic = "ProfileBoundaryChamferSelectionKindUnsupported"; return false; }- requestedProfile = sourceMatch.Groups["profile"].Value; loop = canonical.Success ? canonical.Groups["loop"].Value : "Outer";- segments = sourceMatch.Groups["segments"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);- chainKind = string.Equals(require.Groups["value"].Value, "ClosedLoop", StringComparison.Ordinal) ? ProfileBoundaryChamferChainKind.ClosedLoop : ProfileBoundaryChamferChainKind.OpenConnectedChain;+ if (!TrySelection(source, rawTarget, out var selection, out diagnostic)) return false;+ requestedProfile = selection!.Profile; loop = selection.Loop;+ segments = selection.Segments; chainKind = selection.Kind;provenance = $"Selection:{rawTarget}";}if (!string.Equals(requestedProfile, profile.Name, StringComparison.Ordinal)) { diagnostic = "ProfileBoundaryChamferProfileUnknown"; return false; }@@ -214,35 +224,33 @@ public static class ProfileBoundaryChamferSourceBinderelse if (ordered.Count == 1) chainKind = ProfileBoundaryChamferChainKind.SingleSegment;if (!fields.Complete(out diagnostic)) return false;target = new($"edgefinish:{name}", hostBodyId, profile.Name, loop, ordered.Select(index => resolvedLoop.Segments[index].Name).ToArray(),- Enum.Parse<ProfileBoundaryChamferSide>(on.Groups["value"].Value), chainKind, $"offset:{finish.Match.Index}", provenance);+ Enum.Parse<ProfileBoundaryChamferSide>(on.Groups["value"].Value), chainKind, $"offset:{finish.Span.Start}", provenance);return true;}private sealed class FinishFields{private readonly List<string> diagnostics = [];- private readonly FirmamentSyntaxFields? fields;- private readonly string body;- internal FinishFields(string source, int start, string body)+ private readonly FirmamentSyntaxFields fields;+ internal FinishFields(DeclarationSyntax declaration){- this.body = body;- var declaration = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)- .FirstOrDefault(d => d.Type.Name.Text == "EdgeFinish" && d.Span.Start == start);- if (declaration is not null)- {- fields = new(declaration, diagnostics);- fields.Take("PatternIdentity"); // Compiler-owned finite expansion receipt.- }+ fields = new(declaration, diagnostics);+ fields.Take("PatternIdentity"); // Compiler-owned finite expansion receipt.}internal Match Read(string name, Regex reader){- fields?.Take(name);- return reader.Match(body);+ var value = fields.Take(name);+ if (value is null) return Match.Empty;+ var text = name + ": " + FirmamentSyntaxWriter.Expression(value);+ var match = reader.Match(text);+ if (match.Success && match.Index == 0 && match.Length == text.Length) return match;+ fields.Invalid(name); // Optional malformed fields must not disappear into defaults.+ return Match.Empty;}internal bool Complete(out string? diagnostic){- fields?.Complete();- diagnostic = fields is null ? "ProfileBoundaryEdgeFinishDeclarationInvalid" : diagnostics.FirstOrDefault();+ fields.Complete();+ diagnostic = diagnostics.FirstOrDefault();return diagnostic is null;}}@@ -258,11 +266,31 @@ public static class ProfileBoundaryChamferSourceBinderwhile (selected.Contains(current)) { result.Add(current); current = (current + 1) % count; }return result.Count == selected.Count ? result : null;}- private static string? Block(string text, int open)+ private sealed record BoundarySelection(string Profile, string Loop, IReadOnlyList<string> Segments, ProfileBoundaryChamferChainKind Kind);++ private static bool TrySelection(string source, string name, out BoundarySelection? result, out string? diagnostic){- var depth = 0;- for (var i = open; i < text.Length; i++) { if (text[i] == '{') depth++; else if (text[i] == '}' && --depth == 0) return text[(open + 1)..i]; }- return null;+ result = null; diagnostic = null;+ var declaration = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .FirstOrDefault(d => d.Type.Name.Text == "Selection" && d.Name?.Text == name);+ if (declaration is null) { diagnostic = "ProfileBoundaryEdgeFinishTargetUnknown:" + name; return false; }+ var diagnostics = new List<string>(); var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var selection = fields.Take("Source"); var requirement = fields.Word("Require");+ var target = fields.Word("Target"); // Historical TopBoundary spelling, still admitted.+ var profile = ""; var loop = "Outer"; IReadOnlyList<ArgumentSyntax>? arguments = null;+ if (selection is MemberSetSyntax { Target: MemberSyntax { Target: ReferenceSyntax p } member } set)+ { profile = p.Name.Text; loop = member.Member.Text; arguments = set.Members; }+ else if (selection is CallSyntax { Target: MemberSyntax { Target: ReferenceSyntax p2, Member.Text: "ProfileSegments" }, Arguments.Count: 1 } call &&+ call.Arguments[0].Value is SequenceSyntax { Kind: SequenceKind.List } list)+ { profile = p2.Name.Text; arguments = list.Items; }+ fields.Complete();+ if (diagnostics.Count > 0) { diagnostic = diagnostics[0]; return false; }+ if (arguments is null || arguments.Count == 0 || arguments.Any(a => a.Name is not null || a.Default is not null || a.Value is not ReferenceSyntax) ||+ requirement is not ("ClosedLoop" or "ConnectedChain") || target is not (null or "TopBoundary"))+ { diagnostic = "ProfileBoundaryEdgeFinishSelectionKindUnsupported:" + name; return false; }+ result = new(profile, loop, arguments.Select(a => ((ReferenceSyntax)a.Value).Name.Text).ToArray(),+ requirement == "ClosedLoop" ? ProfileBoundaryChamferChainKind.ClosedLoop : ProfileBoundaryChamferChainKind.OpenConnectedChain);+ return true;}}@@ -281,7 +309,8 @@ public static class ProfileBoundaryChamferPlanner{var mixed = ProfileEdgeFinishMixedShellPlanner.TryPlan(profile, target, ProfileEdgeFinishKind.Chamfer, distance);if (!mixed.Succeeded || mixed.Plan is null)- return Fail(ProfileBoundaryCurvedFinishDiagnostic.ForFirstSelectedArc(profile, loop, target, distance, "Chamfer")+ return Fail((target.ChainKind != ProfileBoundaryChamferChainKind.ClosedLoop+ ? ProfileBoundaryCurvedFinishDiagnostic.ForFirstSelectedArc(profile, loop, target, distance, "Chamfer") : null)?? mixed.Diagnostics.FirstOrDefault()?? "ProfileBoundaryChamferSegmentKindUnsupported");return ProfileEdgeFinishMixedShellMaterializer.TryMaterializeChamfer(profile, target, mixed.Plan);@@ -295,7 +324,7 @@ public static class ProfileBoundaryChamferPlannervar area = SignedArea(lines.Select(x => x.Start).ToArray());if (Math.Abs(area) <= Tol) return Fail("ProfileBoundaryChamferInsetCollapse");var junctions = ProfileJunctionClassifier.Classify(profile, loop);- if (junctions.Any(x => (x.Classification is ProfileJunctionKind.Collinear or ProfileJunctionKind.Degenerate) &&+ if (junctions.Any(x => x.Classification == ProfileJunctionKind.Degenerate &&(selected.Contains(IndexOf(loop, x.PredecessorSegmentId)) || selected.Contains(IndexOf(loop, x.SuccessorSegmentId)))))return Fail("ProfileBoundaryChamferJunctionDegenerate");var inset = BuildInset(lines, selected, area, distance, out var insetDiagnostic);@@ -312,7 +341,7 @@ public static class ProfileBoundaryChamferPlannervar lines = loop.Segments.Select(x => (LineArcLineSegment2D)x.Geometry).ToArray(); var selected = target.SegmentIds.Select(id => Array.FindIndex(loop.Segments.ToArray(), x => x.Name == id)).ToHashSet();if (selected.Count != lines.Length || selected.Any(x => x < 0)) { diagnostic = "ProfileBoundaryChamferComposeWholeLoopRequired"; return false; }var junctions = ProfileJunctionClassifier.Classify(profile, loop);- if (junctions.Any(x => x.Classification is ProfileJunctionKind.Collinear or ProfileJunctionKind.Degenerate)) { diagnostic = "ProfileBoundaryChamferJunctionDegenerate"; return false; }+ if (junctions.Any(x => x.Classification == ProfileJunctionKind.Degenerate)) { diagnostic = "ProfileBoundaryChamferJunctionDegenerate"; return false; }var inset = BuildInset(lines, selected, SignedArea(lines.Select(x => x.Start).ToArray()), distance, out diagnostic);if (inset is null) return false;var segments = lines.Select((_, i) => new ResolvedProfileSegment2D(loop.Segments[i].Name, new LineArcLineSegment2D(inset[i], inset[(i + 1) % inset.Length]), loop.Segments[i].Provenance with { StableId = loop.Segments[i].Provenance.StableId + ":inset", Derivation = "ProfileBoundaryChamferInset" })).ToArray();@@ -343,7 +372,9 @@ public static class ProfileBoundaryChamferPlannerfor (var i = 0; i < count; i++){var line = lines[i]; var a = selected.Contains(i) ? result[i] : line.Start; var b = selected.Contains(i) ? result[(i + 1) % count] : line.End;- if (Distance(a, b) <= Tol) { diagnostic = "ProfileBoundaryChamferInsetCollapse"; return null; }+ if (Distance(a, b) <= Tol || (b.X - a.X) * (line.End.X - line.Start.X) ++ (b.Y - a.Y) * (line.End.Y - line.Start.Y) <= Tol * Distance(line.Start, line.End))+ { diagnostic = "ProfileBoundaryChamferInsetCollapse"; return null; }}if (HasSelfIntersection(result)) { diagnostic = "ProfileBoundaryChamferOffsetSelfIntersection"; return null; }return result;@@ -375,7 +406,11 @@ public static class ProfileBoundaryChamferPlannervar b = (X: second.Start.X + n2x * distance, Y: second.Start.Y + n2y * distance);var r = (X: first.End.X - first.Start.X, Y: first.End.Y - first.Start.Y); var s = (X: second.End.X - second.Start.X, Y: second.End.Y - second.Start.Y);var cross = r.X * s.Y - r.Y * s.X;- if (Math.Abs(cross) <= Tol) { point = default; return false; }+ if (Math.Abs(cross) <= Tol)+ {+ point = b;+ return r.X * s.X + r.Y * s.Y > 0; // Same directed support; preserve the authored subdivision.+ }var q = (X: b.X - a.X, Y: b.Y - a.Y); var t = (q.X * s.Y - q.Y * s.X) / cross;point = (a.X + t * r.X, a.Y + t * r.Y); return double.IsFinite(point.X) && double.IsFinite(point.Y);}@@ -602,17 +637,9 @@ public static class ProfileBoundaryCurvedFinishDiagnosticprivate static double SignedArea(ResolvedProfileLoop2D loop){- var points = loop.Segments.Select(segment => Start(segment.Geometry)).ToArray();- if (points.Any(point => point is null)) return 0d;- return points.Select((point, index) => point!.Value.X * points[(index + 1) % points.Length]!.Value.Y - points[(index + 1) % points.Length]!.Value.X * point.Value.Y).Sum() * .5d;+ return loop.Segments.Sum(segment => ResolvedProfile2DValidator.SignedAreaContribution(segment.Geometry));}- private static (double X, double Y)? Start(LineArcProfileCurve2D geometry) => geometry 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)),- _ => null- };}/// <summary>@@ -869,7 +896,10 @@ public sealed record ProfileReflexFilletJunctionPlan(string VertexId, ProfileJunpublic override Point3D SideBContact { get => VerticalNotchContact; init { } }}public sealed record ProfileFilletShellPlan(ProfileBoundaryChamferTarget Target, double Radius, double EndClearance, IReadOnlyList<ProfileFilletStraightRollPlan> Rolls, ProfileFilletJunctionPlan Junction, string EndpointPolicy = "ExternalEndpointsOnly", IReadOnlyList<ProfileFilletComponent>? Components = null);-public sealed record ProfileFilletShellPlanResult(bool Succeeded, BrepBody? Body, SemanticTopologyCorrespondence? Correspondence, ProfileFilletShellPlan? Plan, ProfileStraightEdgeFilletPlan? SingleSegmentPlan, IReadOnlyList<string> Diagnostics);+public sealed record ProfileFilletShellPlanResult(bool Succeeded, BrepBody? Body, SemanticTopologyCorrespondence? Correspondence, ProfileFilletShellPlan? Plan, ProfileStraightEdgeFilletPlan? SingleSegmentPlan, IReadOnlyList<string> Diagnostics)+{+ public ProfileEdgeFinishEvidence? PlanningEvidence { get; init; }+}public static class ProfileFilletShellPlanner{@@ -892,6 +922,12 @@ public static class ProfileFilletShellPlannervar mixed = ProfileEdgeFinishMixedShellPlanner.TryPlan(profile, target, ProfileEdgeFinishKind.Fillet, radius);if (!mixed.Succeeded || mixed.Plan is null)return Fail(mixed.Diagnostics.FirstOrDefault() ?? "ProfileFilletContactShellPlanningFailed");+ if (mixed.Plan.JunctionDecision?.Strategy == "CircularSegmentMiter")+ {+ var miter = CircularSegmentEdgeFinishMaterializer.TryMaterialize(profile, target, mixed.Plan);+ return new(miter.Succeeded, miter.Body, miter.Correspondence, null, null, miter.Diagnostics)+ { PlanningEvidence = miter.PlanningEvidence };+ }var contacts = ProfileFilletContactShellPlanner.TryPlan(profile, target, mixed.Plan);if (!contacts.Succeeded || contacts.Plan is null)return Fail(contacts.Diagnostics.FirstOrDefault() ?? "ProfileFilletContactShellPlanningFailed");diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.csindex 102c6a1f..935fd457 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishAnalyticPolicy.cs@@ -92,8 +92,12 @@ public static class ProfileEdgeFinishAnalyticPolicy_ => 10d, _ => "Requires Convex ArcDerived Rs < F."),new("FilletConvexSphereLimit", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex) && NearlyEqual(c.SourceRadius, c.FinishSize),_ => 90d, _ => "Requires Convex ArcDerived Rs = F."),- new("FilletConvexHorn", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex) && c.SourceRadius > c.FinishSize + Tolerance,- _ => 80d, _ => "Requires Convex ArcDerived Rs > F."),+ new("FilletConvexRing", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex) && c.SourceRadius > 2 * c.FinishSize + Tolerance,+ _ => 100d, _ => "Requires Convex ArcDerived Rs > 2F."),+ new("FilletConvexHorn", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex) && NearlyEqual(c.SourceRadius, 2 * c.FinishSize),+ _ => 80d, _ => "Requires Convex ArcDerived Rs = 2F."),+ new("FilletConvexSpindleSector", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Convex) && c.SourceRadius > c.FinishSize + Tolerance && c.SourceRadius < 2 * c.FinishSize - Tolerance,+ _ => 80d, _ => "Requires Convex ArcDerived F < Rs < 2F with the existing outer-quarter trim."),new("FilletReflexRing", c => Is(c, ProfileEdgeFinishKind.Fillet, ProfileEdgeFinishSourceFamily.ArcDerived, ProfileEdgeFinishMaterialSide.Reflex),_ => 100d, _ => "Requires Reflex ArcDerived station.")];@@ -110,6 +114,8 @@ public static class ProfileEdgeFinishAnalyticPolicy"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"),"FilletConvexSphereLimit" => Policy(c, relation, "ArcFilletSphereLimitPlan", ProfileEdgeFinishSurfaceFamily.Sphere, ProfileEdgeFinishRegularity.BoundedDegenerate, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy, utility, rejected),"FilletConvexHorn" => Policy(c, relation, "ArcFilletTorusPlan", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.InteropSensitive, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy, utility, rejected, torus: ProfileEdgeFinishTorusRegime.Horn, major: c.SourceRadius - c.FinishSize, minor: c.FinishSize),+ "FilletConvexRing" => Policy(c, relation, "ArcFilletTorusPlan", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported, utility, rejected, torus: ProfileEdgeFinishTorusRegime.Ring, major: c.SourceRadius - c.FinishSize, minor: c.FinishSize),+ "FilletConvexSpindleSector" => Policy(c, relation, "ArcFilletTorusPlan", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.InteropSensitive, ProfileEdgeFinishAdmission.SupportedWithExplicitPolicy, utility, rejected, torus: ProfileEdgeFinishTorusRegime.Spindle, major: c.SourceRadius - c.FinishSize, minor: c.FinishSize),"FilletReflexRing" => Policy(c, relation, "ArcFilletTorusPlan", ProfileEdgeFinishSurfaceFamily.Torus, ProfileEdgeFinishRegularity.Regular, ProfileEdgeFinishAdmission.Supported, utility, rejected, torus: ProfileEdgeFinishTorusRegime.Ring, major: c.SourceRadius + c.FinishSize, minor: c.FinishSize),_ => throw new InvalidOperationException($"Unmapped Profile EdgeFinish policy candidate '{candidate}'.")};diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishJunctionPolicy.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishJunctionPolicy.csnew file mode 100644index 00000000..798f6302--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishJunctionPolicy.cs@@ -0,0 +1,83 @@+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Judgment;+using System.Text.Json.Serialization;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>Source-proven construction choices, before any topology is emitted.+/// Judgment chooses a materializer; it cannot waive a geometric requirement.</summary>+public sealed record ProfileEdgeFinishJunctionDecision(+ JudgmentModelResult<string> Judgment,+ [property: JsonIgnore] CircularSegmentEdgeFinishPlan? CircularSegment)+{+ public string? Strategy => Judgment.Winner?.Value;+}++public sealed record ProfileEdgeFinishEvidence(ProfileEdgeFinishJunctionDecision Decision, double MaximumCurveDeviationMm);++public sealed record CircularSegmentEdgeFinishPlan(+ int ArcIndex, int LineIndex, double Radius, double ChordDistance,+ (double X, double Y) Center, (double X, double Y) Tangent, (double X, double Y) Inward,+ double WindingSign);++public static class ProfileEdgeFinishJunctionPolicy+{+ private sealed record Context(bool OrdinaryContacts, bool CircularSegment, bool RegularMiter, string Reason);++ public static ProfileEdgeFinishJunctionDecision Evaluate(ResolvedProfile2D profile,+ ResolvedProfileLoop2D loop, double size)+ {+ var junctions = ProfileJunctionClassifier.Classify(profile, loop);+ var circular = CircularSegment(loop);+ // Existing line-line junctions retain their established materializers.+ // A curved junction may use a common meridian only when actually tangent.+ var ordinary = junctions.All(j =>+ j.Classification == ProfileJunctionKind.Collinear ||+ loop.Segments.Single(s => s.Name == j.PredecessorSegmentId).Geometry is LineArcLineSegment2D &&+ loop.Segments.Single(s => s.Name == j.SuccessorSegmentId).Geometry is LineArcLineSegment2D);+ var regular = circular is not null && double.IsFinite(size) && size > 0 &&+ size < (circular.Radius - circular.ChordDistance) / 2d - 1e-8;+ var context = new Context(ordinary, circular is not null, regular,+ circular is null ? "Sharp line/arc junction needs a qualified shared intersection curve; the tangent-contact strategy cannot construct it."+ : $"Finish must be smaller than the circular segment inradius {(circular.Radius - circular.ChordDistance) / 2d:R}mm; equality collapses the cap.");+ var model = new JudgmentModel<string, Context>("ProfileEdgeFinish.Junction.v1",+ [new("construction-supported", (strategy, c) => new(+ strategy == "SourceContactShell" ? c.OrdinaryContacts : c.CircularSegment,+ "ProfileEdgeFinishJunctionUnsupported", 0, 0,+ strategy == "SourceContactShell" ? "Requires tangent curved joins or existing sharp line-line joins." : c.Reason)),+ new("noncollapsing-miter", (strategy, c) => new(strategy != "CircularSegmentMiter" || c.RegularMiter,+ "ProfileEdgeFinishInsetCollapse", 0, 0, c.Reason))],+ [new("source-construction-fidelity", 1, (_, _) => new(1, 1, "exact-supports", "Retain authored supports, source order and shared topology."))]);+ return new(model.Evaluate(context, [new("SourceContactShell", "SourceContactShell"),+ new("CircularSegmentMiter", "CircularSegmentMiter")]), circular);+ }++ private static CircularSegmentEdgeFinishPlan? CircularSegment(ResolvedProfileLoop2D loop)+ {+ if (loop.Segments.Count != 2) return null;+ var arcIndex = loop.Segments[0].Geometry is LineArcCircularArc2D ? 0 : 1;+ var lineIndex = 1 - arcIndex;+ if (loop.Segments[arcIndex].Geometry is not LineArcCircularArc2D arc ||+ loop.Segments[lineIndex].Geometry is not LineArcLineSegment2D line) return null;+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y;+ var length = Math.Sqrt(dx * dx + dy * dy);+ if (length <= 1e-8 || !double.IsFinite(arc.Radius) || arc.Radius <= 0) return null;+ var winding = Math.Sign(arc.SweepAngleRadians);+ var tangent = (X: dx / length, Y: dy / length);+ var inward = (X: -tangent.Y * winding, Y: tangent.X * winding);+ var chord = (line.Start.X - arc.Center.X) * inward.X + (line.Start.Y - arc.Center.Y) * inward.Y;+ var angle = arc.StartAngleRadians + arc.SweepAngleRadians / 2d;+ var midDistance = arc.Radius * (Math.Cos(angle) * inward.X + Math.Sin(angle) * inward.Y);+ // The named arc must bound the circle/half-plane intersection, not its complement.+ if (Math.Abs(chord) >= arc.Radius - 1e-8 || midDistance <= chord + 1e-8) return null;+ var start = (X: arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians),+ Y: arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians));+ var end = (X: arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians),+ Y: arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians));+ if (Distance(start, line.End) > 1e-7 || Distance(end, line.Start) > 1e-7) return null;+ return new(arcIndex, lineIndex, arc.Radius, chord, arc.Center, tangent, inward, winding);+ }++ private static double Distance((double X, double Y) a, (double X, double Y) b)+ => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));+}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishMixedShellPlan.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishMixedShellPlan.csindex 1c630b48..2f220855 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishMixedShellPlan.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileEdgeFinishMixedShellPlan.cs@@ -23,7 +23,10 @@ public sealed record ProfileEdgeFinishMixedShellPlan(IReadOnlyList<string> DegenerateVertices,string TopCapPlan,string SideTrimPlan,- IReadOnlyList<string> Provenance);+ IReadOnlyList<string> Provenance)+{+ public ProfileEdgeFinishJunctionDecision? JunctionDecision { get; init; }+}public sealed record ProfileEdgeFinishMixedShellPlanResult(bool Succeeded,@@ -164,6 +167,15 @@ public static class ProfileEdgeFinishMixedShellPlannervar end = profile.LocalEndDepth ?? 1d;if (finishSize >= end - start - Tolerance) return Fail("ProfileEdgeFinishMixedShellFinishExceedsHostThickness");+ var junctionDecision = ProfileEdgeFinishJunctionPolicy.Evaluate(profile, loop, finishSize);+ if (junctionDecision.Strategy is null)+ {+ var rejection = junctionDecision.Judgment.Candidates+ .SelectMany(c => c.Rules).First(r => !r.Result.Passed &&+ (junctionDecision.CircularSegment is null || r.Result.Code == "ProfileEdgeFinishInsetCollapse"));+ return Fail($"{rejection.Result.Code}: {rejection.Result.Evidence}");+ }+var frame = profile.EffectiveConstructionPlane;var signedArea = SignedArea(loop);if (Math.Abs(signedArea) <= Tolerance) return Fail("ProfileEdgeFinishMixedShellProfileDegenerate");@@ -188,6 +200,11 @@ public static class ProfileEdgeFinishMixedShellPlannerif (finishKind == ProfileEdgeFinishKind.Chamfer){var normal = Direction3D.Create(tangent.ToVector().Cross((inward.ToVector() * finishSize) + (capOut.ToVector() * finishSize)));+ // The historical formula assumes CCW traversal and the+ // top cap. Keep that case byte-stable; reverse the plane+ // support sense for a bottom cap or reversed winding.+ var capDirection = target.Side == ProfileBoundaryChamferSide.Top ? 1 : -1;+ if (materialSign * capDirection < 0) normal = Direction3D.Create(-normal.ToVector());patches.Add(new PlanarChamferPatch(stableId, segment.Name,new PlaneSurface(startPoint, normal, tangent), Frame(tangent, inward, capOut), Descendants(segment)));}@@ -257,7 +274,8 @@ public static class ProfileEdgeFinishMixedShellPlannerreturn new(true, new ProfileEdgeFinishMixedShellPlan(target, finishKind, finishSize, patches, seams, degeneracies,finishKind == ProfileEdgeFinishKind.Chamfer ? "MixedInsetLineArcProfile" : "MixedCapContactLineArcProfile",finishKind == ProfileEdgeFinishKind.Chamfer ? "OriginalSideToPlaneConeTrim" : "OriginalSideToCylinderSphereTorusTrim",- ["ResolvedProfile2D", "ProfileEdgeFinishAnalyticPolicy", "ProfileEdgeFinishMixedShellPlan", "SourceOrder", "PreEmissionSeamCorrespondence"]), []);+ ["ResolvedProfile2D", "ProfileEdgeFinishAnalyticPolicy", "ProfileEdgeFinishMixedShellPlan", "SourceOrder", "PreEmissionSeamCorrespondence"])+ { JunctionDecision = junctionDecision }, []);}private static AnalyticEdgeFinishSeam CreateSeam(ProfileEdgeFinishKind kind, string id, AnalyticEdgeFinishPatch predecessor,@@ -314,21 +332,9 @@ public static class ProfileEdgeFinishMixedShellPlannerprivate static string Frame(Direction3D x, Direction3D y, Direction3D z) =>string.Create(CultureInfo.InvariantCulture, $"x=({x.X:R},{x.Y:R},{x.Z:R});y=({y.X:R},{y.Y:R},{y.Z:R});z=({z.X:R},{z.Y:R},{z.Z:R})");- 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 => ArcContribution(arc),- _ => 0d- }) * .5d;+ private static double SignedArea(ResolvedProfileLoop2D loop) =>+ loop.Segments.Sum(segment => ResolvedProfile2DValidator.SignedAreaContribution(segment.Geometry));- private static double ArcContribution(LineArcCircularArc2D arc)- {- var a = arc.StartAngleRadians;- var b = a + arc.SweepAngleRadians;- return 2d * (arc.Center.X * arc.Radius * (Math.Sin(b) - Math.Sin(a))- - arc.Center.Y * arc.Radius * (Math.Cos(b) - Math.Cos(a))- + arc.Radius * arc.Radius * (b - a));- }}/// <summary>@@ -345,14 +351,17 @@ public static class ProfileEdgeFinishMixedShellMaterializer{ProfileBoundaryChamferPlanResult Fail(string code) => new(false, null, null, target, [code]);if (plan.FinishKind != ProfileEdgeFinishKind.Chamfer) return Fail("ProfileEdgeFinishMixedShellChamferPlanRequired");+ if (plan.JunctionDecision?.Strategy == "CircularSegmentMiter")+ return CircularSegmentEdgeFinishMaterializer.TryMaterialize(profile, target, plan);var loop = profile.Loops.SingleOrDefault(x => x.Name == target.LoopId);if (loop is null || loop.Segments.Count != plan.OrderedPatches.Count) return Fail("ProfileEdgeFinishMixedShellPlanProfileMismatch");var frame = profile.EffectiveConstructionPlane;- var start = profile.LocalStartDepth ?? -1d;+ var topSide = target.Side == ProfileBoundaryChamferSide.Top;+ var start = topSide ? profile.LocalStartDepth ?? -1d : profile.LocalEndDepth ?? 1d;var end = profile.LocalEndDepth ?? 1d;- var transition = target.Side == ProfileBoundaryChamferSide.Top ? end - plan.FinishSize : start + plan.FinishSize;- var cap = target.Side == ProfileBoundaryChamferSide.Top ? end : start;- if (target.Side != ProfileBoundaryChamferSide.Top) return Fail("ProfileEdgeFinishMixedShellBottomChamferNotImplemented");+ var transition = topSide ? end - plan.FinishSize : (profile.LocalStartDepth ?? -1d) + plan.FinishSize;+ var cap = topSide ? end : profile.LocalStartDepth ?? -1d;+ var capOut = topSide ? frame.AxisZ : Direction3D.Create(-frame.AxisZ.ToVector());var area = SignedArea(loop);if (Math.Abs(area) <= Tolerance) return Fail("ProfileEdgeFinishMixedShellProfileDegenerate");@@ -442,6 +451,7 @@ public static class ProfileEdgeFinishMixedShellMaterializerUse Use(EdgeId edge, VertexId startVertex) => new(edge, builder.Model.Edges.Single(x => x.Id == edge).StartVertexId != startVertex);FaceId Face(string stableId, IReadOnlyList<Use> uses, SurfaceGeometry surface, SemanticTopologyRole role, string source){+ if (!topSide) uses = uses.Reverse().Select(u => new Use(u.Edge, !u.Reverse)).ToArray();var loopId = builder.AllocateLoopId();var coedges = uses.Select(_ => builder.AllocateCoedgeId()).ToArray();for (var i = 0; i < uses.Count; i++)@@ -465,11 +475,11 @@ public static class ProfileEdgeFinishMixedShellMaterializer// Bottom cap is the source loop reversed; the top cap follows the mixed inset loop.Face($"{target.StableId}:bottom-cap", Enumerable.Range(0, count).Reverse().Select(i => Use(bottom[i], SectionVertex(i, true, start, false))).ToArray(),- SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), start), Direction3D.Create(-frame.AxisZ.ToVector()), frame.AxisX)), SemanticTopologyRole.BottomFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");+ SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), start), Direction3D.Create(-capOut.ToVector()), frame.AxisX)), SemanticTopologyRole.BottomFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");var topUses = new List<Use>();for (var i = 0; i < count; i++)if (top[i] is { } edge) topUses.Add(Use(edge, SectionVertex(i, false, cap, true)));- Face($"{target.StableId}:top-cap", topUses, SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), cap), frame.AxisZ, frame.AxisX)), SemanticTopologyRole.TopFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");+ Face($"{target.StableId}:top-cap", topUses, SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), cap), capOut, frame.AxisX)), SemanticTopologyRole.TopFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");for (var i = 0; i < count; i++){@@ -572,11 +582,7 @@ public static class ProfileEdgeFinishMixedShellMaterializervar t = (qx * sy - qy * sx) / cross;return (first.Start.X + t * rx, first.Start.Y + t * ry);}- private static double SignedArea(ResolvedProfileLoop2D loop) => loop.Segments.Sum(x => x.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 static double SignedArea(ResolvedProfileLoop2D loop) =>+ loop.Segments.Sum(segment => ResolvedProfile2DValidator.SignedAreaContribution(segment.Geometry));private readonly record struct Use(EdgeId Edge, bool Reverse);}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.csindex 58a12952..9ca4dc32 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellMaterializer.cs@@ -23,7 +23,6 @@ public static class ProfileFilletContactShellMaterializerProfileFilletContactShellPlan 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);@@ -34,15 +33,20 @@ public static class ProfileFilletContactShellMaterializerif (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 top = target.Side == ProfileBoundaryChamferSide.Top;+ var lowerDepth = top ? profile.LocalStartDepth ?? -1d : profile.LocalEndDepth ?? 1d;+ var capDepth = top ? profile.LocalEndDepth ?? 1d : profile.LocalStartDepth ?? -1d;+ var transitionDepth = capDepth + (top ? -mixed.FinishSize : mixed.FinishSize);var radius = mixed.FinishSize;- var capOut = frame.AxisZ;+ var capOut = top ? frame.AxisZ : Direction3D.Create(-frame.AxisZ.ToVector());var axialInto = -capOut.ToVector();var count = loop.Segments.Count;var classifications = ProfileJunctionClassifier.Classify(profile, loop).ToDictionary(item => (item.PredecessorSegmentId, item.SuccessorSegmentId));+ if (loop.Segments.All(s => s.Geometry is LineArcLineSegment2D) &&+ classifications.Values.All(j => j.Classification == ProfileJunctionKind.ConvexProfileJunction) &&+ !ProfileBoundaryChamferPlanner.TryCreateInsetOuterProfile(profile, target, radius, out _, out var insetDiagnostic))+ return Fail($"ProfileBoundaryFilletInsetInvalid: {insetDiagnostic}");var junctions = new Junction[count];for (var i = 0; i < count; i++)@@ -68,7 +72,11 @@ public static class ProfileFilletContactShellMaterializervar depth = source + axialInto * radius;if (classification.Classification == ProfileJunctionKind.ConvexProfileJunction){- var center = source + na.ToVector() * radius + nb.ToVector() * radius + axialInto * radius;+ var dot = na.ToVector().Dot(nb.ToVector());+ // Keep established right-angle construction byte-stable. For any+ // other convex angle, intersect the two inset support lines.+ var setback = Math.Abs(dot) <= Tolerance ? radius : radius / (1 + dot);+ var center = source + na.ToVector() * setback + nb.ToVector() * setback + axialInto * radius;var capJunction = center + capOut.ToVector() * radius;var majorAxis = Direction3D.Create(depth - center);var planeNormal = Direction3D.Create(majorAxis.ToVector().Cross(capOut.ToVector()));@@ -77,6 +85,8 @@ public static class ProfileFilletContactShellMaterializer}else if (classification.Classification == ProfileJunctionKind.ReflexProfileJunction && target.ReflexJunctionStyle == ProfileReflexJunctionStyle.SphereSeamCompatibility){+ if (Math.Abs(classification.MaterialInteriorAngleRadians - 3 * Math.PI / 2) > Tolerance)+ return Fail("ProfileBoundaryFilletReflexAngleUnsupported");var center = source + na.ToVector() * radius + nb.ToVector() * radius + axialInto * radius;var capJunction = center + capOut.ToVector() * radius;var sideA = center - na.ToVector() * radius;@@ -86,6 +96,8 @@ public static class ProfileFilletContactShellMaterializer}else if (classification.Classification == ProfileJunctionKind.ReflexProfileJunction){+ if (Math.Abs(classification.MaterialInteriorAngleRadians - 3 * Math.PI / 2) > Tolerance)+ return Fail("ProfileBoundaryFilletReflexAngleUnsupported");var centerA = depth + na.ToVector() * radius;var centerB = depth + nb.ToVector() * radius;var capA = source + na.ToVector() * radius;@@ -93,6 +105,8 @@ public static class ProfileFilletContactShellMaterializerjunctions[i] = new(JunctionKind.ReflexHornTorus, source, depth, depth, depth, depth, depth, capA, capB,centerA, centerB, depth, classification.VertexId, na, nb);}+ else if (classification.Classification == ProfileJunctionKind.Collinear)+ junctions[i] = Junction.Smooth(source, side, cap, incomingCenter, outgoingCenter);else return Fail($"ProfileFilletContactShellSharpJunctionUnsupported:vertex={classification.VertexId}:kind={classification.Classification}");}@@ -137,9 +151,13 @@ public static class ProfileFilletContactShellMaterializernew 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);+ Direction3D majorAxis, Direction3D planeNormal, double minorRadius)+ {+ var majorRadius = (points[start] - center).Length;+ if (Math.Abs(majorRadius - minorRadius * Math.Sqrt(2d)) <= Tolerance) majorRadius = minorRadius * Math.Sqrt(2d);+ return Edge(key, start, end, CurveGeometry.FromEllipse(new Ellipse3Curve(center, planeNormal,+ majorRadius, 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;@@ -147,6 +165,7 @@ public static class ProfileFilletContactShellMaterializer}FaceId Face(string stableId, IReadOnlyList<Use> uses, SurfaceGeometry surface, SemanticTopologyRole role, string source){+ if (!top) uses = uses.Reverse().Select(u => new Use(u.Edge, !u.Reverse)).ToArray();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++)@@ -167,14 +186,33 @@ public static class ProfileFilletContactShellMaterializervar 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];+ string CapVertexKey(int junction, int component, bool start)+ {+ var previous = (junction + count - 1) % count;+ if (mixed.OrderedPatches[junction] is SphericalFilletPatch && mixed.OrderedPatches[previous] is SphericalFilletPatch)+ throw new InvalidOperationException("ProfileFilletContactShellAdjacentSphereLimitsUnsupported");+ // A sphere-limit component has a point cap contact. Both of its+ // interfaces and the adjacent cap edges meet that one authored+ // component apex, rather than two coincident junction vertices.+ var sphere = mixed.OrderedPatches[junction] is SphericalFilletPatch ? junction+ : mixed.OrderedPatches[previous] is SphericalFilletPatch ? previous : -1;+ if (sphere >= 0) return $"sphere-limit:{sphere}:cap";+ return junctions[junction].Kind == JunctionKind.ReflexHornTorus+ ? $"component:{component}:cap:{(start ? "start" : "end")}" : $"junction:{junction}:cap";+ }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);+ // These are junction-owned contacts, shared by the two incident+ // components. Distinct per-component vertex IDs at the same+ // planned point produce geometrically closed, disconnected caps.+ // A reflex torus alone has two distinct cap contacts and an arc+ // joining them; retain those explicit identities.+ sideStarts[i] = Vertex($"junction:{i}:depth", junctions[i].OutgoingSide);+ sideEnds[i] = Vertex($"junction:{next}:depth", junctions[next].IncomingSide);+ capStarts[i] = Vertex(CapVertexKey(i, i, true), junctions[i].OutgoingCap);+ capEnds[i] = Vertex(CapVertexKey(next, i, false), 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();@@ -230,7 +268,7 @@ public static class ProfileFilletContactShellMaterializer}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)),+ SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), lowerDepth), Direction3D.Create(-capOut.ToVector()), frame.AxisX)),SemanticTopologyRole.BottomFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");var topUses = new List<Use>();@@ -241,7 +279,7 @@ public static class ProfileFilletContactShellMaterializerif (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)),+ SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), capDepth), capOut, frame.AxisX)),SemanticTopologyRole.TopFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}");for (var i = 0; i < count; i++)@@ -395,12 +433,8 @@ public static class ProfileFilletContactShellMaterializerreturn 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 static double SignedArea(ResolvedProfileLoop2D loop) =>+ loop.Segments.Sum(segment => ResolvedProfile2DValidator.SignedAreaContribution(segment.Geometry));private enum JunctionKind { Smooth, ConvexMiter, ReflexHornTorus, ReflexCompatibilitySphere }diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.csindex 91d9c875..6c2b2d95 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileFilletContactShellPlan.cs@@ -441,8 +441,9 @@ public static class ProfileFilletContactShellPlannerif (Math.Abs(area) <= Tolerance) return Fail("ProfileFilletContactShellProfileDegenerate");var frame = profile.EffectiveConstructionPlane;- var cap = profile.LocalEndDepth ?? 1d;- var transition = cap - mixed.FinishSize;+ var top = target.Side == ProfileBoundaryChamferSide.Top;+ var cap = top ? profile.LocalEndDepth ?? 1d : profile.LocalStartDepth ?? -1d;+ var transition = cap + (top ? -mixed.FinishSize : mixed.FinishSize);var components = new List<ProfileFilletComponentContactContract>(loop.Segments.Count);var interfaces = new List<ProfileFilletContactBoundary>(loop.Segments.Count);var caps = new List<ProfileFilletContactBoundary>(loop.Segments.Count);@@ -566,10 +567,6 @@ public static class ProfileFilletContactShellPlanner_ => throw new NotSupportedException()};private static bool Oriented(LineArcProfileCurve2D curve) => curve is not LineArcCircularArc2D arc || arc.SweepAngleRadians >= 0d;- private static double SignedArea(ResolvedProfileLoop2D loop) => loop.Segments.Sum(x => x.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 static double SignedArea(ResolvedProfileLoop2D loop) =>+ loop.Segments.Sum(segment => ResolvedProfile2DValidator.SignedAreaContribution(segment.Geometry));}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileJunctionClassification.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileJunctionClassification.csindex 1016298f..9141eb22 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileJunctionClassification.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileJunctionClassification.cs@@ -77,10 +77,9 @@ public static class ProfileJunctionClassifierprivate static double SignedArea(ResolvedProfileLoop2D loop){- var points = loop.Segments.Select(segment => Start(segment.Geometry)).ToArray();- return points.Any(point => point is null)- ? 0d- : points.Select((point, index) => point!.Value.X * points[(index + 1) % points.Length]!.Value.Y - points[(index + 1) % points.Length]!.Value.X * point.Value.Y).Sum() / 2d;+ // Integrate the directed boundary, rather than its endpoint polygon. An+ // arc and chord enclose material even though their two endpoints do not.+ return loop.Segments.Sum(segment => ResolvedProfile2DValidator.SignedAreaContribution(segment.Geometry));}private static bool TryStartTangent(LineArcProfileCurve2D geometry, out (double X, double Y) tangent) =>@@ -106,13 +105,6 @@ public static class ProfileJunctionClassifier}}- private static (double X, double Y)? Start(LineArcProfileCurve2D geometry) => geometry 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)),- _ => null- };-private static bool Normalize(double x, double y, out (double X, double Y) tangent){var length = Math.Sqrt(x * x + y * y);diff --git a/docs/development/FIRMAMENT-EDGE-FINISH-ROBUSTNESS-2026-10-18.md b/docs/development/FIRMAMENT-EDGE-FINISH-ROBUSTNESS-2026-10-18.mdnew file mode 100644index 00000000..fce511ef--- /dev/null+++ b/docs/development/FIRMAMENT-EDGE-FINISH-ROBUSTNESS-2026-10-18.md@@ -0,0 +1,267 @@+# Ordinary CAD fillet/chamfer robustness — 2026-10-18++**Success within the qualified ordinary CAD rim families.** The arc/chord+D-profile now builds a real fillet or chamfer through the source-owned planner,+exports/reimports STEP and produces a complete watertight mesh on either rim.+Judgment selects supported constructions before emission. Existing compatibility+gates pass; unsupported requests reject explicitly.++## Scope and reproduction++Investigated Claude's reported arc-and-line D-profile failure. The exact Claude+source was not supplied in this request, so the durable reproduction is a+minimal semicircle of radius 10 mm, closed by its diameter, extruded 8 mm and+finished with a 1 mm rim radius/distance. It uses ordinary Profile/Struct/Modify+authoring, not BodyState or a general surface blend.++The initial CLI run of the preferred-field specimen rejected with+`concept-path-arc-invalid`, then `EdgeFinishProfileComposeBoundaryUnsupported`+after using the old Arc field casing. The source-owned finish reader was still+testing PascalCase fields with structural regexes before geometry planning.+Its error described an unrelated primitive/Compose limitation. Inspection also+found that the old junction classifier used the polygon of segment endpoints:+two endpoints have zero polygon area even when their arc and chord enclose a+perfectly ordinary part.++Sources are preserved under+[`fixtures/Regression/EdgeFinishRobustness`](../../fixtures/Regression/EdgeFinishRobustness/README.md).+Raw run evidence is ignored under `artifacts/local/edge-finish-robustness/`.+No existing canonical source or geometry golden was rewritten to satisfy this+repair.++## Root causes and repairs++| Finding | Repair |+| --- | --- |+| Preferred Arc `radius`/`turn` and Line `turn`/`heading` missed old spelling projection | Extend the existing scoped spelling owner; preserve symbols and case-only compatibility. |+| Source-bound EdgeFinish/Selection recognition depended on PascalCase regex block discovery | Consume actual AST declarations and existing `FirmamentSyntaxFields`. Reuse source order, member-set selection and the historical ProfileSegments call form. Remaining regexes read bounded serialized field values only; they must consume the whole value. |+| Malformed optional values could disappear into defaults | Mark failed optional field conversions invalid. Numeric enum spellings reject. Closed-loop `endClearance` rejects rather than being ignored. |+| Multiple requested Profile finishes succeeded while emitting only the first | Reject the unsupported sequence before materialization with `ProfileBoundaryEdgeFinishSequenceUnsupported`. Reuse executable AST declaration ownership so uncalled Feature/Template recipes are not counted as operations. |+| Curved profile winding was inferred from endpoint chords; several finish helpers also doubled the arc area contribution | Reuse the existing exact boundary-area owner for classification, contact planning and materialization. Positive/negative sketch translations cannot change material polarity. |+| Every curved join was treated as a tangent rolling meridian | Prove tangency or choose the qualified circular-segment miter through Judgment. Reject other sharp curved junctions before topology allocation. |+| Whole-loop fillets assumed every convex polygon corner was 90 degrees | Compute the actual two-inset-line intersection and exact cylinder/cylinder ellipse for each convex angle. Retain the old support arithmetic at right angles; the separate incidence repair below deliberately changes vertex identity. |+| Collinear authored subdivisions were rejected as corners | Retain the subdivision and common support; do not invent a corner patch. |+| Whole-loop mixed bottom finishes were disabled | Use the selected cap's outward axis, transition depth and reversed loop traversal with the same support contracts. Check outward plane support sense for bottom/reversed-winding chamfers as well as trim containment. |+| Oversized polygon insets could reverse an edge | Reject reversed/collapsed inset edges before emission, using a length-scaled linear tolerance. Convex whole-loop fillets reuse that existing inset proof. |+| Every convex torus with source radius greater than finish radius was labelled Horn | Classify actual major/minor radii: Ring, Horn, or the existing trimmed outer-quarter Spindle support. Geometry is unchanged for existing admitted sectors. |+| Source-owned finish results did not retain their runtime body/correspondence or a feature receipt | Retain the actual emitted geometry, semantic descendants, stable EdgeFinish name and planning evidence. |+| Component-local IDs duplicated the same planned cap/side junction, including a sphere-limit apex | Allocate junction-owned contact vertices and one component-owned sphere-limit apex. This repairs actual loop incidence without coordinate welding. Shared face/edge semantics and boundary geometry remain retained. |+| SurfaceMeshIR rejected existing Ellipse3 curves and bounded torus/spline miter trims | Sample the actual ellipse with bounded chord/tangent error and reuse the existing analytic parameter-space trim owner for a four-sided outer-torus band. Keep shared source edge samples; do not mutate the BRep or synthesize renderer geometry. |++The repair adds no parser dispatch family, source macro system, approximate+polyline solid, general blend fallback, or relaxed export preflight. Existing+Box, hole/finish, bounded internal fillet and low-level sculpting ownership stays+in place. This pass does not resume the separate arbitrary-BodyState editing+adapter work.++## Geometric construction and numerical authority++A circular segment is the intersection of a circle of radius `R` with a+half-plane. In the chord's inward coordinate, the chord lies at `k`. At inset+distance `d`, the finish section is the circle of radius `R-d` clipped by the+line at `k+d`. Their intersections have++```text+x² = R² - k² - 2(R+k)d+```++The finish must stay strictly below `(R-k)/2`, the segment's inradius. Equality+collapses the cap; a larger finish must not emit inverted or unrelated geometry.+The miter construction also requires positive retained stock thickness.++For Chamfer, parameterize `x` linearly. Both inset `d` and axial rise are then+quadratic in that parameter, so one degree-two Bezier represents the shared+plane/cone seam exactly in real arithmetic.++For Fillet, use the rolling meridian `t` in `[0, pi/2]`:++```text+d = f(1-cos(t))+z - transition = f sin(t)+x = sqrt(A+B cos(t))+A = R²-k²-2(R+k)f > 0+B = 2(R+k)f+```++The plane-side rolling cylinder and circular-side torus share this intersection.+Both faces use one edge identity. The implementation constructs piecewise cubic+Hermite spans subordinate to this equation, with a global fourth-derivative+remainder bound plus a separate coordinate-scale floating-point allowance.+Refinement is bounded to 16,384 spans and must meet the default 1e-6 mm linear+tolerance; exhaustion fails explicitly. This is a finite edge representation+on analytic support surfaces, not an assertion that the generic spline is an+exact symbolic curve. STEP retains that finite curve. No sampled polygon is+used as the engineering boundary.++For a 1 mm finish on the 10 mm semicircle, the top chord endpoints move to+`(+/-sqrt(80), 1)` in sketch coordinates. Each cap remains one arc and one line.+The result has six faces, ten shared edges and six vertices. The unmodified+extrusion has four faces. Tests assert this difference, actual support+containment and shared incidence, rather than accepting a plausible unchanged+solid.++## Judgment contract and diagnostics++`ProfileEdgeFinish.Junction.v1` evaluates source-contact and circular-segment+miter candidates before topology emission. Hard rules establish supported+joins and noncollapsing miter geometry; finite source-fidelity utility selects+among admitted constructions with the existing JudgmentEngine adapter. There+is no reject-bypassing generic blend candidate.++`build --json` publishes `edgeFinishPlanning` for the circular-segment path:+candidate rules, admission/rejection evidence, policy version, selected strategy+and maximum curve-deviation bound. Internal construction tuples are deliberately+excluded from this JSON contract. Engineering feature reports retain+`edgefinish:Rim`. A bare-Profile planner failure is anchored at its EdgeFinish+declaration; a rejected sequence identifies the second requested operation.+Expanded provenance follows the existing diagnostic mapping.+The legacy materializer transport removes the enclosing Model, so its local+offsets must first be mapped back to the corresponding declaration in the+frontend's retained source. The initial location test caught this mismatch;+the repair uses retained AST identity, without a new diagnostic-code allowlist.++Oversize, unsupported junction, malformed field and unsupported endpoint-policy+requests reject through validate and build, leaving no artifact. The shared+diagnostic/presentation pipeline remains the compiler authority.++## Qualification and compatibility++The focused matrix covers D-profile fillet/chamfer, both rim sides, placed+frames, materializer winding reversal, minor/major circular segments, acute and+obtuse polygon corners, collinear subdivisions, named selections, typed+EdgeFinish variants, preferred/compatibility fields, shape identity, deterministic+STEP, reimport, curve/support agreement and invalid-size admission. Kernel-level+clockwise tests do not change the language's existing outer-loop winding rules.+Dynamic STEP imports are of newly constructed before/after artifacts, so they+cannot use a static Step242Corpus item.++One pre-existing unit specimen was incorrectly treated as a valid curved loop:+`CurvedProfile()` in `ProfileBoundaryChamferTests` reverses its tangent by 180+degrees entering the arc and has another non-tangent curved exit. Its old+`IsEnclosed` check proved incidence, not that the trims lay on their surfaces.+That exact specimen remains in the test, now asserting explicit rejection with+no body. Legitimate mixed line/arc production cases remain separate regression+tests; no failing source was edited into a different shape.++The first real mesh qualification caught two further ownership gaps that BRep+support containment alone did not detect. D-profile fillets needed bounded+torus/spline trim consumption; polygon fillets exposed duplicate planned vertex+identities at cap corners. Both are now covered through actual CLI STEP-to-OBJ+qualification with all faces, watertight/connected/outward topology and no cracks.+Strict coedge endpoint identity is asserted in addition to geometric closure.++The retained before/after Profile Chimera witness+(`fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-fillet.firmament`)+compares every face support, ordered+loop curve, trim interval, edge/face orientation and endpoint position after+STEP reimport, independently of entity/vertex IDs. Its incidence repair is an+intentional STEP topology correction, not a rebased geometric golden. The+comparison result and counts are included in the final evidence below.++| Chimera STEP-reimport witness | Before | After |+| --- | ---: | ---: |+| Faces / edges | 37 / 86 | 37 / 86 |+| Vertices | 84 | 51 |+| Coedge end/start vertex-identity breaks | 65 | 0 |+| Geometry-only SHA-256 | `8592fd4f6a169f16f81be5b03c431890fbfda3405fe49c3324678664e881f552` | same |++The geometry-only hash excludes entity IDs, but includes the actual support+parameters and ordered trim geometry/sense/positions. The local proof helper+and `incidence-geometry-proof.json` are retained with the ignored run artifacts.++For this repaired whole-loop family, raw STEP hashes and vertex-derived IDs+intentionally change. Source feature names and the face/edge semantic owners+remain retained. This is not a promise of byte compatibility for the formerly+disconnected topology, or of identical display tessellation after enabling the+previously unsupported trim consumers.++| Gate | Result |+| --- | --- |+| Release solution build | 0 errors; 30 existing dependency/WASM warnings |+| Focused Firmament finish matrix | 96 passed |+| Focused CLI admission, identity and mesh matrix | 25 passed |+| Fast Core lane (`Category!=SlowCorpus`) | 1,076 passed |+| Complete solution suite | 5,559 passed, 0 failed, 0 skipped across 20 nonempty test assemblies |+| Historical domain frontend comparison | 37/37 matched: 35 byte-identical STEP artifacts and 2 expected rejections |+| Canonical corpus | 369 records: 296 qualified owner operations, 69 consumed modules, 4 expected external-body boundaries |+| Claude FrontendX4 | 32/32, including Chimera geometry matching its baseline |+| SheetMetalSyntax | 26/26; formed STEP / flat parity true |+| SheetMetalSemantics | 29/29 |+| Actual CLI build → STEP → OBJ | All 6 top/bottom cases fully covered, watertight, connected and outward; 0 cracks, nonmanifold edges or zero-area triangles |++The retained two-rim specimen now rejects through both CLI `validate` and+`build` with `ProfileBoundaryEdgeFinishSequenceUnsupported` at line 13,+column 9 (the second requested finish), and emits no new STEP artifact. The+original first-operation-only success remains preserved as reproduction evidence;+it is not counted as qualification. Separate fillet/fillet, chamfer/chamfer and+fillet/chamfer regressions assert rejection and no output. An uncalled finish+Feature preserves byte-identical STEP and one engineering feature receipt.++The full run includes 1,209 Core tests and 2,905 Firmament tests. FrictionLab+advertises no tests and is not counted as a passed test assembly. Canonical+qualification uses each domain's actual owner operation; an assembly/scene+inspection is not a claim that every such project was independently meshed or+STEP-hash compared. The historical comparison and the explicit Chimera proof+provide the geometry-parity evidence.++An earlier unrestricted-processor full run encountered one existing timed+display failure in `ExternalStepDefinitionsStaySharedWhenPoseChanges`+(`AssemblyKinematicsX0Tests`): Plane face 3 exceeded its execution budget at+6,498 ms. The unchanged test passed in isolation in 372 ms. The complete final+run above passed with two advertised processors; no timeout was increased.+The initial failure and isolated rerun remain in+`full-before-support-sense.log` and `timeout-isolated.log`. This is local+qualification, not a remote CI or desktop UI certification. Frozen Zig suites+were not run because no legacy Zig source or build infrastructure changed.++Reproduce the engineering path from the repository root:++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament --output artifacts/local/d-profile-fillet.step --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll mesh artifacts/local/d-profile-fillet.step --format obj --output artifacts/local/d-profile-fillet.obj --json+```++The regression gates use the installed .NET 10.0.401 SDK and the repository CLI,+with `MSBUILDDISABLENODEREUSE=1`, `-m:1`, `-nr:false` and+`-p:UseSharedCompilation=false` for the Release build. The complete suite uses+`dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1`.+The final full run advertises two processors with process-local+`DOTNET_PROCESSOR_COUNT=2`; this limits oversubscription without removing tests+or changing their deadlines.++## Code-quality review++The source reader now reuses executable AST ownership and the existing field+consumer; no independent field schema, fatal-code allowlist, parser dispatch or+global rewrite was added. Its remaining regular expressions consume one entire+serialized field value. Selection binding retains the existing member-set and+compatibility call forms. The new Judgment policy compares two bounded support+constructions before emission, and cannot admit an unsupported intersection.++Shared topology is allocated from planned source junctions rather than proximity+matching. Circular-segment numerical refinement has an explicit error budget+and finite exhaustion diagnostic. Mesh consumers reuse source boundary IDs and+existing parameter-space triangulation. Public reports omit the internal tuple+packet rather than serializing its coordinates as empty objects. No runtime+host reuse, background service, repository-wide formatting or golden rebasing+was introduced.++## Remaining boundaries and verdict++This is qualification of ordinary source-owned rim families, not a claim that+all CAD fillets now work. Other sharp curved junction graphs, arbitrary imported+edge selection, interacting multi-feature fillets and non-right-angle reflex+junctions need their own shared topology/materialization proof. Existing+unsupported selections remain explicit failures. A general low-level surface+blend is not prescribed as the authoring workaround for a D-shaped CAD part.+The existing Profile/Compose fillet-with-cavity interaction boundary is not+broadened here; Box/hole finishes retain their separate qualified owner.+Profile/Compose still admits one EdgeFinish operation per compiled construction;+top-plus-bottom and mixed-kind sequences now reject rather than losing intent.++Public syntax, construction limits, diagnostics and executable source links+are updated in place. No remaining language-design decision is required for+this bounded repair. The end state is **Success** for the D-profile and qualified+polygon/tangent rim robustness pass, with the explicit boundaries above; this+is not a declaration of universal fillet support or broader X2 closure.diff --git a/docs/public/firmament/fillet-profiles.md b/docs/public/firmament/fillet-profiles.mdindex 991973f1..2bbb9315 100644--- a/docs/public/firmament/fillet-profiles.md+++ b/docs/public/firmament/fillet-profiles.md@@ -1,4 +1,50 @@-# Bounded concave fillet profiles+# Fillets and chamfers++Use `EdgeFinish<Fillet>` with `radius`, or `EdgeFinish<Chamfer>` with `distance`,+for ordinary CAD edge finishing. The existing `kind: Fillet` / `kind: Chamfer`+spelling has the same meaning. Name the engineering boundary and its support;+the planner selects a qualified construction from that source intent. Authors+do not need to replace a simple rim finish with a general sculpting blend.++For an extruded Profile, `target: Section.Outer; on: Top` selects its whole top+rim; `on: Bottom` selects its bottom rim. Qualified cases include straight+polygon rims, tangent line/arc rims, and a circular segment made from one arc+and its closing chord. The [D-profile fillet](../../../fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament)+and [D-profile chamfer](../../../fixtures/Regression/EdgeFinishRobustness/d-profile-chamfer.firmament)+are complete executable examples. [The angled plate](../../../fixtures/Regression/EdgeFinishRobustness/polygon-rim-fillet.firmament)+shows convex corners that are not right angles. These rim finishes preserve+the sharp vertical stock corners; they do not round every edge of the body.++The Profile/Compose materializer currently admits one `EdgeFinish` operation+per compiled construction. Requesting multiple finishes, including separate top+and bottom finishes, rejects with `ProfileBoundaryEdgeFinishSequenceUnsupported`.+It never compiles only the first requested finish. Uncalled Feature/Template+definitions are recipes, not requested operations. Primitive Box finish+combinations retain their separate admission rules.++The circular-segment cap comes from the inset circle and inset chord. Its finish+size must be strictly smaller than the segment's inradius, as well as the stock+thickness. For a semicircle of radius 10 mm, the inradius is 5 mm. A size of 5 mm+collapses the cap and rejects. The two finish surfaces share their real miter+curve: an exact quadratic parabola for Chamfer, and a certified cubic+representation within the kernel's 0.000001 mm linear tolerance for Fillet.+The support surfaces remain analytic planes, cones, cylinders and tori. The+finite edge representation is not an unqualified freeform fallback.++`build --json` exposes `edgeFinishPlanning` for the circular-segment construction:+the selected strategy, candidate admission/rejection traces, policy version and+maximum curve-deviation bound. Judgment chooses among supported constructions;+it cannot relax a failed clearance or support condition. Other sharp line/arc+junction families still reject until their shared intersection is qualified.+Non-right-angle reflex fillets and interacting/collapsing finishes are not+silently approximated. `endClearance` applies to an open chain, and is rejected+on a closed loop, which has no endpoints.++General surface blending remains a low-level sculpting operation with explicit+supports, trims and continuity contracts. It is not a prerequisite for these+ordinary CAD finishes. See [sculpting](sculpting.md) for that separate authority.++## Bounded concave fillet section lawsThe existing concave fillet kernel admits `BoundedFilletProfile.Circular` (default) and `BoundedFilletProfile.CurvatureContinuous`. Both reuse the same trusted-source preflight, selected edges, setback/contact points, source loop, shared edges, and shell construction. The smooth mode replaces the circular quarter-section with a fixed degree-five polynomial and its straight extrusion surface.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex be128f25..2f03b7ab 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -618,6 +618,16 @@ or countersink holes in the same Modify. The hole entry circles must stay strictinset top face. Fillets retain sharp vertical stock corners and join their fourcylindrical blends on exact elliptical seams; this is not a whole-box rounding.A profile-composed finish names its Profile boundary and support instead.+For a bare extruded Profile, `target: Section.Outer; on: Top` or `on: Bottom`+finishes its whole rim. Straight polygon corners need not be right angles;+tangent line/arc rims and an arc closed by a chord also have qualified paths.+The Profile/Compose materializer admits one finish operation per construction;+multiple requested finishes reject explicitly rather than emitting only the+first. Uncalled Feature/Template definitions do not count as operations.+Finish size must leave a noncollapsing cap. Closed loops reject `endClearance`;+that field belongs to open-chain endpoint termination. See+[fillet/chamfer constructions and limits](fillet-profiles.md) for executable+D-profile examples and the planner's Judgment evidence.The generic variant has the same capability checks as `kind`.A bare `Fillet corners { ... }` is not an alternative EdgeFinish declaration.For a combined countersink, its conical relief must end above a positive shaftdiff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.mdindex bbd43465..8a760954 100644--- a/docs/public/reference/diagnostics.md+++ b/docs/public/reference/diagnostics.md@@ -4,6 +4,29 @@ Generic V2 build/validation errors use structured objects with `code`, `severityUnknown canonical statements and Box fields are errors. `profile-layout-placement-unsupported` rejects unsupported Concept Struct layout planes instead of substituting XY. Use a traced Construction Plane for supported oriented profile workflows. `SemanticSourceNotFound` preserves the missing source and the provenance explanation. An accidental through-depth Pocket fails; explicit `end: ThroughAll` selects the admitted through cut. Box top-boundary Fillet with disjoint ThroughAll shaft/counterbore holes is supported; `CombinedFeatureInteractionUnsupported` identifies a hole touching the finish band or another hole. Unsupported combined selectors retain `CombinedFeatureSelectionLost` at the EdgeFinish declaration.+## Profile rim finishes++- `ProfileBoundaryEdgeFinishSequenceUnsupported`: this Profile/Compose owner+ admits one finish operation. Multiple requested finishes cannot be compiled+ as a first-operation-only result. Uncalled recipes do not count as operations.+- `ProfileEdgeFinishInsetCollapse`: the requested circular-segment finish reaches+ or exceeds its inradius. Reduce the radius/distance to retain a cap.+- `ProfileBoundaryFilletInsetInvalid` / `ProfileBoundaryChamferInsetCollapse`:+ an inset polygon edge collapses or reverses; reduce the finish size.+- `ProfileEdgeFinishJunctionUnsupported`: a sharp curved junction lacks a+ qualified shared intersection for this profile family. This does not require+ ordinary CAD authors to supply a general surface blend.+- `ProfileEdgeFinishMixedShellFinishExceedsHostThickness`: the finish consumes+ the full thickness rather than leaving the admitted stock region.+- `ProfileBoundaryFilletEndClearanceRequiresOpenChain`: remove `endClearance`+ from a closed-loop finish, or select the intended open chain.+- `ProfileEdgeFinishMiterNumericToleranceExhausted` / `ProfileEdgeFinishMiterRefinementLimit`:+ the finite miter representation cannot meet its certified tolerance within the+ bounded numerical budget. No artifact is admitted.++When a planner reports one unambiguous EdgeFinish operation, the diagnostic uses+that enclosing declaration's span; expanded provenance is mapped where retained.+## Circular Sweep (X0)- `firmament-sweep-section-invalid`: circular diameter is missing, non-finite, or non-positive.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 50849941..9ddf88ef 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -5,6 +5,7 @@| Area | Status | Preview 3 boundary ||---|---|---|| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |+| Profile rim fillet/chamfer | Bounded ordinary CAD | Top/bottom rims of convex polygons (including non-right-angle corners), admitted tangent line/arc loops, and circular segments formed by one arc and chord. Source-bound Judgment selects qualified construction; shared analytic-support intersections, certified finite fillet miter curves and exact quadratic chamfer miters. Collapsed caps and unqualified sharp curved junction families reject. See [fillets and chamfers](../firmament/fillet-profiles.md). || Box top-boundary finish with holes | Bounded | One complete +Z Boundary Chamfer or constant-radius Fillet with disjoint ThroughAll shaft/counterbore holes; exact cylindrical fillets and elliptical corner seams. Intersecting holes/finish bands, other combined selectors and general feature chains remain unsupported. See [geometry](../firmament/geometry.md#box-top-fillet-with-holes). || Gear Standard Library | Supported / bounded by family | Supported external/internal standard involute spur gears; bounded straight bevel/miter and ratchet/pawl; typed `Interface<Gear>` compatibility and ideal ratios; deterministic manifold AP242. No contact, dynamics, ratings, helical/worm, spiral-bevel, or qualified hub/keyway geometry. See the [gear guide](../firmament/gears.md). || Assembly Interface bundles and Subassemblies | Supported / bounded | Compiler-owned `Fixed`, `Axial`, and `Revolute` expansion; explicit `Custom` atomic bundles; compile-time relative `Include`; reusable nested definitions; private-by-default internals; exposed semantic ports that preserve type, including Gear; stable hierarchical paths and dependency hashes. Include aliases are deferred. See [assemblies](../firmament/assemblies.md). |diff --git a/fixtures/Regression/EdgeFinishRobustness/README.md b/fixtures/Regression/EdgeFinishRobustness/README.mdnew file mode 100644index 00000000..48b45abd--- /dev/null+++ b/fixtures/Regression/EdgeFinishRobustness/README.md@@ -0,0 +1,22 @@+# Ordinary CAD edge-finish robustness++- `d-profile-fillet.firmament`: one semicircular arc and one chord, extruded+ 8 mm, with a 1 mm top-rim fillet.+- `d-profile-chamfer.firmament`: the same stock with a 1 mm chamfer.+- `polygon-rim-fillet.firmament`: a parallelogram with acute/obtuse corners,+ finished without treating every junction as 90 degrees.++Sources use preferred field casing. They are accepted cases, not speculative+syntax or recorded refusals. They must emit the requested finish, not the+unchanged extrusion. D outputs have six faces, ten edges and six vertices;+their two caps are legitimate arc/chord digons.++`CircularSegmentEdgeFinishTests` proves analytic-support containment, shared+incidence, deterministic STEP/reimport, placement frames, both windings,+minor/major circular segments, and rejection of cap collapse. The fillet miter+is a certified finite curve within 1e-6 mm, while the chamfer miter is an exact+quadratic polynomial. `OrdinaryEdgeFinishRobustnessTests` covers polygon angles,+collinear subdivisions, bottom finishes and oversized insets. CLI tests exercise+validate/build agreement, named selections, feature identity and planner evidence.++Generated outputs belong under `artifacts/local/edge-finish-robustness/`.diff --git a/fixtures/Regression/EdgeFinishRobustness/d-profile-chamfer.firmament b/fixtures/Regression/EdgeFinishRobustness/d-profile-chamfer.firmamentnew file mode 100644index 00000000..2927041d--- /dev/null+++ b/fixtures/Regression/EdgeFinishRobustness/d-profile-chamfer.firmament@@ -0,0 +1,14 @@+Model DShape {+ units: mm+ Path Outline {+ start: Point2(10mm, 0mm)+ heading: 90deg+ Arc Round { turn: 180deg; radius: 10mm }+ Close Flat+ }+ Profile Section from Outline+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 8mm } }+ Modify Body {+ EdgeFinish Rim { target: Section.Outer; on: Top; kind: Chamfer; distance: 1mm }+ }+}diff --git a/fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament b/fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmamentnew file mode 100644index 00000000..1c27478e--- /dev/null+++ b/fixtures/Regression/EdgeFinishRobustness/d-profile-fillet.firmament@@ -0,0 +1,14 @@+Model DShape {+ units: mm+ Path Outline {+ start: Point2(10mm, 0mm)+ heading: 90deg+ Arc Round { turn: 180deg; radius: 10mm }+ Close Flat+ }+ Profile Section from Outline+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 8mm } }+ Modify Body {+ EdgeFinish Rim { target: Section.Outer; on: Top; kind: Fillet; radius: 1mm }+ }+}diff --git a/fixtures/Regression/EdgeFinishRobustness/polygon-rim-fillet.firmament b/fixtures/Regression/EdgeFinishRobustness/polygon-rim-fillet.firmamentnew file mode 100644index 00000000..42a51376--- /dev/null+++ b/fixtures/Regression/EdgeFinishRobustness/polygon-rim-fillet.firmament@@ -0,0 +1,16 @@+Model AngledPlate {+ units: mm+ Path Outline {+ start: Point2(0mm, 0mm)+ heading: 0deg+ Line South { length: 30mm }+ Line East { turn: 60deg; length: 20mm }+ Line North { turn: 120deg; length: 30mm }+ Close West+ }+ Profile Section from Outline+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 8mm } }+ Modify Body {+ EdgeFinish Rim { target: Section.Outer; on: Top; kind: Fillet; radius: 1mm }+ }+}