Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support composed profile edge finishes and improve ellipse tessellation

Yuechen Li6efe6401de98
diff --git a/Aetheris.CLI.Tests/FirmamentV2AirChamferStepPipelineTests.cs b/Aetheris.CLI.Tests/FirmamentV2AirChamferStepPipelineTests.cs
index 80adf4b4..24d63e53 100644
--- a/Aetheris.CLI.Tests/FirmamentV2AirChamferStepPipelineTests.cs
+++ b/Aetheris.CLI.Tests/FirmamentV2AirChamferStepPipelineTests.cs
@@ -34,7 +34,7 @@ public sealed class FirmamentV2AirChamferStepPipelineTests
[Theory]
[InlineData(0, "+Z", "Boundary", "air-chamfer-distance-must-be-positive")]
[InlineData(4, "+Z", "Boundary", "air-chamfer-distance-too-large-rejected")]
- [InlineData(1, "-Z", "Boundary", "air-chamfer-unsupported-face-rejected")]
+ [InlineData(4, "-Z", "Boundary", "EdgeFinishFaceBoundaryRejected")]
[InlineData(1, "+Z", "SingleEdge", "air-chamfer-unsupported-selection-rejected")]
public void FirmamentV2_AirChamfer_Rejections_DoNotFallBack(double distance, string face, string target, string expected)
{
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index adf7f8b7..7057cec4 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -732,11 +732,16 @@ public static class BrepDisplayTessellator
.Select(p => double.Min(options.ChordTolerance,
double.Min(p!.RecoveryToleranceMillimetres, p.MeasuredMaxDeviationMillimetres)))
.DefaultIfEmpty(0d).Max();
+ // Intersecting cylindrical fillet rolls terminate on elliptical miter
+ // curves. Their axial extent varies with angle; a rectangular UV
+ // bounding patch protrudes past the retained face at the corners.
+ var ellipticalBoundary = loopIds.Length == 1 && body.GetCoedgeIds(loopIds[0])
+ .Any(id => body.GetEdgeCurve(body.Topology.GetCoedge(id).EdgeId).Kind == CurveGeometryKind.Ellipse3);
// A bounded one-loop face can be a helical strip, a toothed skirt, or a
// narrow rectangular sector. Its bounding cylinder is not the trim.
// Prefer the complete bound parameter trace, retaining legacy dispatch
// for closed-circle/seam families without a polygonal pcurve boundary.
- if (loopIds.Length == 1 && (body.GetCoedgeIds(loopIds[0]).Count >= 3
+ if (loopIds.Length == 1 && (ellipticalBoundary || body.GetCoedgeIds(loopIds[0]).Count >= 3
&& body.GetCoedgeIds(loopIds[0]).Select(id => body.Topology.GetCoedge(id).EdgeId).Distinct().Count() == body.GetCoedgeIds(loopIds[0]).Count
&& body.GetCoedgeIds(loopIds[0]).All(id => body.Bindings.TryGetPcurveBinding(id, out var pc) && pc.FaceId == faceId)
|| body.GetCoedgeIds(loopIds[0]).Any(id =>
@@ -749,9 +754,11 @@ public static class BrepDisplayTessellator
return double.Abs(end.U - start.U) > 1e-8d && double.Abs(end.V - start.V) > 1e-8d;
})))
{
- var uvLoops = TryBuildTrimmedSurfaceUvLoops(body, faceId, loopIds,
- point => TryProjectPointToCylinderUv(cylinder, point, recoveryAllowance), options, executionBudget,
- SurfaceGeometryKind.Cylinder);
+ var uvLoops = ellipticalBoundary
+ ? TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds,
+ point => TryProjectPointToCylinderUv(cylinder, point, recoveryAllowance), options, executionBudget, SurfaceGeometryKind.Cylinder)
+ : TryBuildTrimmedSurfaceUvLoops(body, faceId, loopIds,
+ point => TryProjectPointToCylinderUv(cylinder, point, recoveryAllowance), options, executionBudget, SurfaceGeometryKind.Cylinder);
if (!uvLoops.IsSuccess)
return KernelResult<DisplayFaceMeshPatch>.Failure(uvLoops.Diagnostics);
return TrimmedSurfaceTessellator.Tessellate(faceId, uvLoops.Value,
@@ -3618,7 +3625,7 @@ public static class BrepDisplayTessellator
break;
case CurveGeometryKind.Ellipse3:
- var ellipsePointsResult = SamplePlanarEllipse(body, coedge, isTraversalSwapped, curve.Ellipse3!.Value, segmentStart, segmentEnd, plane, faceId);
+ var ellipsePointsResult = SamplePlanarEllipse(body, coedge, isTraversalSwapped, curve.Ellipse3!.Value, segmentStart, segmentEnd, plane, faceId, options);
if (!ellipsePointsResult.IsSuccess)
{
return KernelResult<IReadOnlyList<Point3D>>.Failure(ellipsePointsResult.Diagnostics);
@@ -3858,7 +3865,8 @@ public static class BrepDisplayTessellator
Point3D start,
Point3D end,
PlaneSurface plane,
- FaceId faceId)
+ FaceId faceId,
+ DisplayTessellationOptions options)
{
const double planeContainmentTolerance = 1e-7d;
var normalAlignment = double.Abs(ellipse.Normal.ToVector().Dot(plane.Normal.ToVector()));
@@ -3877,7 +3885,7 @@ public static class BrepDisplayTessellator
}
var trim = trimResult.Value;
- var segmentCount = ComputeEllipseSegmentCount(trim.Start, trim.End);
+ var segmentCount = ComputeEllipseSegmentCount(ellipse, trim.Start, trim.End, options);
var sampled = SampleEllipseCurve(ellipse, trim, segmentCount).ToArray();
sampled[0] = start;
sampled[^1] = end;
@@ -4153,7 +4161,7 @@ public static class BrepDisplayTessellator
case CurveGeometryKind.Ellipse3:
var ellipse = curve.Ellipse3!.Value;
- var segments = ComputeEllipseSegmentCount(interval.Start, interval.End);
+ var segments = ComputeEllipseSegmentCount(ellipse, interval.Start, interval.End, options);
return KernelResult<DisplayEdgePolyline>.Success(new DisplayEdgePolyline(
edgeId,
SampleEllipseCurve(ellipse, interval, segments),
@@ -4320,12 +4328,14 @@ public static class BrepDisplayTessellator
return points;
}
- private static int ComputeEllipseSegmentCount(double start, double end)
+ private static int ComputeEllipseSegmentCount(Ellipse3Curve ellipse, double start, double end, DisplayTessellationOptions options)
{
- const double maxSegmentAngle = double.Pi / 4d;
- var span = double.Abs(end - start);
- var segmentCount = (int)double.Ceiling(span / maxSegmentAngle);
- return System.Math.Max(2, segmentCount);
+ // An ellipse is an affine image of the unit circle. Its major radius
+ // bounds chord sag; a/b bounds tangent turning per parameter radian.
+ // The old fixed 45-degree step ignored both caller budgets and left
+ // only two chords on a quarter-ellipse fillet miter.
+ return CalculateSegmentCount(double.Abs(end - start), ellipse.MajorRadius,
+ options with { AngularToleranceRadians = options.AngularToleranceRadians * ellipse.MinorRadius / ellipse.MajorRadius });
}
private static KernelResult<IReadOnlyList<Point3D>> SamplePlanarHyperbola(
diff --git a/Aetheris.Kernel.Firmament.Tests/EngineeringRimFinishTests.cs b/Aetheris.Kernel.Firmament.Tests/EngineeringRimFinishTests.cs
new file mode 100644
index 00000000..b97aab7d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/EngineeringRimFinishTests.cs
@@ -0,0 +1,216 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class EngineeringRimFinishTests
+{
+ [Theory]
+ [InlineData("-Z")] [InlineData("+X")] [InlineData("-X")]
+ [InlineData("+Y")] [InlineData("-Y")]
+ public void DisplayFilletRollsRespectTheirEllipticalMiterTrims(string face)
+ {
+ var built = Build($$"""
+ Model Block {
+ units: mm
+ Box Stock { size: [60mm, 40mm, 12mm] }
+ Modify Stock { EdgeFinish<Fillet> Rim { face: {{face}}; target: Boundary; radius: 1mm } }
+ }
+ """);
+ foreach (var body in new[] { built.RuntimeBody!, Step242Importer.ImportBody(built.StepText).Value })
+ {
+ var options = DisplayTessellationOptions.Default with { ChordTolerance = .01 };
+ var display = BrepDisplayTessellator.Tessellate(body, options);
+ Assert.True(display.IsSuccess, string.Join(';', display.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(body.Topology.Faces.Count(), display.Value.FacePatches.Count);
+ foreach (var binding in body.Bindings.EdgeBindings.Where(b => body.GetEdgeCurve(b.EdgeId).Ellipse3.HasValue))
+ {
+ var ellipse = body.GetEdgeCurve(binding.EdgeId).Ellipse3!.Value;
+ var trim = binding.TrimInterval!.Value;
+ var samples = Assert.Single(display.Value.EdgePolylines, e => e.EdgeId == binding.EdgeId).Points;
+ for (var i = 0; i < samples.Count - 1; i++)
+ {
+ var exact = ellipse.Evaluate(trim.Start + (trim.End - trim.Start) * (i + .5) / (samples.Count - 1));
+ var chord = samples[i] + (samples[i + 1] - samples[i]) * .5;
+ Assert.InRange((exact - chord).Length, 0, options.ChordTolerance);
+ }
+ }
+ var cap = face == "+X" ? 30 : face == "-X" ? -30 : face == "+Y" ? 20 : face == "-Y" ? -20 : 0;
+ var points = display.Value.FacePatches.SelectMany(p => p.Positions)
+ .Where(p => Math.Abs((face[1] == 'X' ? p.X : face[1] == 'Y' ? p.Y : p.Z) - cap) < 1e-7).ToArray();
+ Assert.NotEmpty(points);
+ // A rectangular UV bounding patch incorrectly extends each roll to
+ // the sharp stock corner. At the finished cap every axis is inset.
+ Assert.All(points, p => {
+ if (face[1] != 'X') Assert.InRange(p.X, -29.000001, 29.000001);
+ if (face[1] != 'Y') Assert.InRange(p.Y, -19.000001, 19.000001);
+ if (face[1] != 'Z') Assert.InRange(p.Z, .999999, 11.000001);
+ });
+ }
+ }
+
+ [Fact]
+ public void RealHeliosCodexTaskRetainsItsFourHolesAndRim()
+ {
+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/EdgeFinishRobustness/helios-codex-rounded-plate.firmament");
+ var built = Build(source);
+ Assert.Equal(4, built.Features!.Count);
+ Assert.Equal(new[] { (-14d, -9d), (-14d, 9d), (14d, -9d), (14d, 9d) },
+ built.Features.Select(f => (f.LocalU, f.LocalV)).Order().ToArray());
+ Assert.All(built.Features, f => Assert.Equal(4d, f.Diameter));
+ Assert.Contains(built.EngineeringFeatures!, f => f.Kind == "EdgeFinish");
+ Assert.Equal(34, built.RuntimeBody!.Topology.Faces.Count());
+ Assert.Equal(4, built.RuntimeBody.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Torus));
+ Assert.DoesNotContain(built.RuntimeBody.Geometry.Surfaces, s => s.Value.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots);
+ Check(Step242Importer.ImportBody(built.StepText).Value);
+ }
+
+ [Theory]
+ [InlineData("+X", false)] [InlineData("-X", false)]
+ [InlineData("+Y", false)] [InlineData("-Y", false)]
+ [InlineData("+Z", false)] [InlineData("-Z", false)]
+ [InlineData("+X", true)] [InlineData("-X", true)]
+ [InlineData("+Y", true)] [InlineData("-Y", true)]
+ [InlineData("+Z", true)] [InlineData("-Z", true)]
+ public void BoxLoopFinishUsesTheRequestedFace(string face, bool fillet)
+ {
+ var source = $$"""
+ Model Block {
+ units: mm
+ Box Stock { size: [60mm, 40mm, 12mm] }
+ Modify Stock { EdgeFinish<{{(fillet ? "Fillet" : "Chamfer")}}> Rim {
+ face: {{face}}; target: Boundary; {{(fillet ? "radius" : "distance")}}: 1mm
+ } }
+ }
+ """;
+ var built = Build(source);
+ var body = Step242Importer.ImportBody(built.StepText).Value;
+ Check(body);
+ var points = body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).ToArray();
+ Assert.Equal(-30, points.Min(p => p.X), 8); Assert.Equal(30, points.Max(p => p.X), 8);
+ Assert.Equal(-20, points.Min(p => p.Y), 8); Assert.Equal(20, points.Max(p => p.Y), 8);
+ Assert.Equal(0, points.Min(p => p.Z), 8); Assert.Equal(12, points.Max(p => p.Z), 8);
+ var axis = face[1]; var sign = face[0] == '+' ? 1 : -1;
+ double Along(Aetheris.Kernel.Core.Math.Point3D p) => axis == 'X' ? p.X : axis == 'Y' ? p.Y : p.Z;
+ var plane = sign > 0 ? points.Max(Along) : points.Min(Along);
+ var cap = Assert.Single(body.Topology.Faces.Where(f => body.GetFaceSurface(f.Id).Plane is { } p
+ && Math.Abs((axis == 'X' ? p.Normal.ToVector().X : axis == 'Y' ? p.Normal.ToVector().Y : p.Normal.ToVector().Z) - sign) < 1e-8
+ && Math.Abs(Along(p.Origin) - plane) < 1e-8));
+ var capPoints = cap.LoopIds.SelectMany(l => body.Topology.GetLoop(l).CoedgeIds)
+ .Select(c => body.Topology.GetEdge(body.Topology.GetCoedge(c).EdgeId).StartVertexId)
+ .Select(v => { Assert.True(body.TryGetVertexPoint(v, out var p)); return p; }).ToArray();
+ // All four corners of the requested cap are inset; its opposite face
+ // retains the original rectangle. Bounds alone cannot prove orientation.
+ if (axis != 'X') Assert.Equal(58, capPoints.Max(p => p.X) - capPoints.Min(p => p.X), 8);
+ if (axis != 'Y') Assert.Equal(38, capPoints.Max(p => p.Y) - capPoints.Min(p => p.Y), 8);
+ if (axis != 'Z') Assert.Equal(10, capPoints.Max(p => p.Z) - capPoints.Min(p => p.Z), 8);
+ Assert.Contains(built.EngineeringFeatures!, f => f.Kind == "EdgeFinish" && f.Support == face);
+ }
+
+ [Theory]
+ [InlineData(false, false)] [InlineData(false, true)]
+ [InlineData(true, false)] [InlineData(true, true)]
+ public void RoundedRimRetainsAllThroughCavitiesAndExplicitPmi(bool bottom, bool chamfer)
+ {
+ var source = Source;
+ if (bottom) source = source.Replace("target: Boundary; on: +Z", "target: Outline.Outer; on: Bottom");
+ if (chamfer) source = source.Replace("EdgeFinish<Fillet>", "EdgeFinish<Chamfer>").Replace("radius: 1mm", "distance: 1mm");
+ var built = Build(source);
+ var reference = Build(source.Replace(source.Split('\n').Single(l => l.Contains("EdgeFinish<")), ""));
+ var body = built.RuntimeBody!;
+ var imported = Step242Importer.ImportBody(built.StepText);
+ Assert.True(imported.IsSuccess, string.Join(';', imported.Diagnostics.Select(d => d.Message)));
+ Check(body); Check(imported.Value);
+ Assert.Equal(3, built.Features!.Count);
+ var correspondence = built.RuntimeCorrespondence!;
+ Assert.Equal(3, correspondence.Descendants.Count(d => d.Role is SemanticTopologyRole.HoleEntryLoop or SemanticTopologyRole.HoleCounterboreMouthLoop));
+ Assert.Equal(3, correspondence.Descendants.Count(d => d.Role == SemanticTopologyRole.HoleExitLoop));
+ foreach (var role in new[] { SemanticTopologyRole.HoleWallFace, SemanticTopologyRole.HoleCountersinkWallFace,
+ SemanticTopologyRole.HoleCounterboreWallFace, SemanticTopologyRole.HoleCounterboreShaftWallFace,
+ SemanticTopologyRole.HoleEntryLoop, SemanticTopologyRole.HoleCounterboreMouthLoop,
+ SemanticTopologyRole.HoleCounterboreShoulderLoop, SemanticTopologyRole.HoleExitLoop })
+ Assert.Equal(reference.RuntimeCorrespondence!.Descendants.Where(d => d.Role == role).Select(d => d.StableId).Order(),
+ correspondence.Descendants.Where(d => d.Role == role).Select(d => d.StableId).Order());
+ foreach (var wall in reference.RuntimeCorrespondence!.Descendants.Where(d => d.Face.HasValue &&
+ d.Role is SemanticTopologyRole.HoleWallFace or SemanticTopologyRole.HoleCountersinkWallFace
+ or SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCounterboreShaftWallFace))
+ {
+ var retained = Assert.Single(correspondence.Descendants, d => d.StableId == wall.StableId);
+ // Compare exact analytic supports, including cylinder axes, cone
+ // origins, radii and orientation, rather than just face counts.
+ Assert.Equal(reference.RuntimeBody!.GetFaceSurface(wall.Face!.Value), body.GetFaceSurface(retained.Face!.Value));
+ }
+ var sinkCones = imported.Value.Geometry.Surfaces.Where(s => s.Value.Cone is { PlacementOrigin.X: 15 }).ToArray();
+ Assert.Equal(4, sinkCones.Length); // Four qualified quarter patches.
+ Assert.All(sinkCones, c => Assert.Equal(Math.PI / 4, c.Value.Cone!.Value.SemiAngleRadians, 10));
+ var settings = new BrepMassPropertiesOptions(.01, Math.PI / 90, .01, MinimumSegments: 64, MaximumSegments: 256);
+ var mass = BrepMassProperties.Evaluate(imported.Value, settings);
+ var referenceMass = BrepMassProperties.Evaluate(reference.RuntimeBody!, settings);
+ Assert.True(mass.IsEnclosed); Assert.True(referenceMass.IsEnclosed);
+ Assert.True(mass.IsOrientationConsistent);
+ var perimeter = 2 * (60 + 40) - 2 * (4 - Math.PI) * 6;
+ var removed = chamfer ? perimeter / 2 - Math.PI / 3
+ : perimeter * (1 - Math.PI / 4) - Math.PI * (5d / 3 - Math.PI / 2);
+ Assert.InRange(Math.Abs(referenceMass.AbsoluteVolume - mass.AbsoluteVolume - removed), 0, .2);
+ var capZ = bottom ? 0d : 8d;
+ var cap = Assert.Single(body.Topology.Faces, f => body.GetFaceSurface(f.Id).Plane is { } p
+ && Math.Abs(p.Origin.Z - capZ) < 1e-8 && Math.Abs(p.Normal.ToVector().Z) > .99);
+ var capPoints = cap.LoopIds.SelectMany(l => body.Topology.GetLoop(l).CoedgeIds)
+ .Select(c => body.Topology.GetEdge(body.Topology.GetCoedge(c).EdgeId).StartVertexId)
+ .Select(v => { Assert.True(body.TryGetVertexPoint(v, out var p)); return p; }).ToArray();
+ Assert.Equal(58, capPoints.Max(p => p.X) - capPoints.Min(p => p.X), 8);
+ Assert.Equal(38, capPoints.Max(p => p.Y) - capPoints.Min(p => p.Y), 8);
+ var pmi = Step242SemanticPmiInspector.Inspect(built.StepText);
+ Assert.True(pmi.Success); Assert.Equal(1, pmi.DatumCount); Assert.Equal(3, pmi.DimensionCount);
+ Assert.Equal(built.StepText, FirmamentBuildAndExport.CompileSource(source).Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("center: Point2(-15mm, 0mm)", "center: Point2(-15mm, 17mm)", "CavityInterference")]
+ [InlineData("radius: 1mm", "radius: 7mm", "")]
+ [InlineData("target: Boundary; on: +Z", "target: Boundary; on: +X", "FaceNotCap")]
+ [InlineData("radius: 1mm", "raduis: 1mm", "")]
+ public void UnsupportedIntentCannotSilentlyBuildUnfinishedStock(string from, string to, string diagnostic)
+ {
+ var source = Source.Replace(from, to);
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(built.IsSuccess);
+ Assert.Contains(built.Diagnostics, d => d.Message.Contains(diagnostic, StringComparison.Ordinal));
+ if (diagnostic == "CavityInterference")
+ {
+ var shown = built.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "plate.firmament", source));
+ // The presenter resolves the named colliding Hole, which is more
+ // precise than the enclosing EdgeFinish fallback span.
+ Assert.All(shown, d => Assert.Equal(9, d.Line));
+ }
+ Assert.Equal("invalid", FirmamentBuildAdmissionValidation.Admit(
+ FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source)), source).Status);
+ }
+
+ private static string Source => FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/EdgeFinishRobustness/rounded-plate-through-cavities.firmament");
+ private static FirmamentStepExportResult Build(string source)
+ {
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join(';', built.Diagnostics.Select(d => d.Message)));
+ Assert.Equal("valid", FirmamentBuildAdmissionValidation.Admit(
+ FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source)), source).Status);
+ return built.Value;
+ }
+ private static void Check(BrepBody body)
+ {
+ Assert.True(BrepExportPreflight.Validate(body).IsValid);
+ foreach (var edge in body.Topology.Edges)
+ {
+ var uses = body.Topology.Coedges.Where(c => c.EdgeId == edge.Id).ToArray();
+ Assert.Equal(2, uses.Length);
+ }
+ // STEP normalizes face orientation independently from wire direction;
+ // raw coedge flags alone are not a shell-orientation invariant.
+ Assert.True(BrepMassProperties.Evaluate(body).IsEnclosed);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
index 9da2ff5c..dc19be55 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
@@ -397,19 +397,22 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTests
}
[Fact]
- public void ProfileComposePolygonEdgeFinish_ReportsHostAdmissionInsteadOfMissingSemanticSource()
+ public void ProfileComposePolygonEdgeFinish_BindsTheHostBoundaryToTheQualifiedProfilePlanner()
{
- var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Invalid/Geometry/profile-compose-l-bracket-edgefinish-unsupported.firmament"));
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/EdgeFinishRobustness/l-bracket-host-boundary-chamfer.firmament");
var output = Path.Combine(Path.GetTempPath(), "aetheris-l-profile-finish-" + Guid.NewGuid().ToString("N") + ".step");
try
{
var parse = FirmamentV2Parser.Parse(File.ReadAllText(path));
- Assert.False(parse.IsSuccess);
- Assert.Contains(FirmamentV2Parser.EdgeFinishProfileComposeBoundaryUnsupported, parse.Diagnostics);
+ // Non-four-sided stock is not malformed syntax. The materializer
+ // proves that the requested boundary finish is actually admitted.
+ Assert.True(parse.IsSuccess, string.Join(';', parse.Diagnostics));
var build = FirmamentBuildAndExport.Run(path, output);
- Assert.False(build.IsSuccess);
- var diagnostic = Assert.Single(build.Diagnostics.Where(d => d.Message.StartsWith(FirmamentBuildAndExport.EdgeFinishProfileComposeBoundaryUnsupported + ":", StringComparison.Ordinal)));
- Assert.DoesNotContain("SemanticSourceNotFound", diagnostic.Message, StringComparison.Ordinal);
+ Assert.True(build.IsSuccess, string.Join(';', build.Diagnostics.Select(d => d.Message)));
+ var body = Step242Importer.ImportBody(build.Value.Export.StepText).Value;
+ var mass = Aetheris.Kernel.Core.Brep.Verification.BrepMassProperties.Evaluate(body);
+ Assert.True(mass.IsEnclosed);
+ Assert.InRange(Math.Abs(mass.AbsoluteVolume - (28800 - 140 + 4d / 3)), 0, 1e-7);
}
finally
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.FaceBoundary.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.FaceBoundary.cs
new file mode 100644
index 00000000..8b2c3c65
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.FaceBoundary.cs
@@ -0,0 +1,64 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Features;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Firmament.Execution;
+
+namespace Aetheris.Kernel.Firmament;
+
+public static partial class FirmamentBuildAndExport
+{
+ private static KernelResult<FirmamentStepExportResult> ExportV2BoxFaceBoundaryFinish(
+ FirmamentV2Document document, FirmamentV2SolidBinding solid, FirmamentV2EdgeFinishDecl finish, FirmamentV2BoxRecord box)
+ {
+ var x = box.Size[0]; var y = box.Size[1]; var z = box.Size[2];
+ // Proper signed permutations preserve support/curve parameters and shell
+ // orientation. Canonical +Z keeps its established byte-stable route.
+ (double Width, double Depth, double Height, double[]? Matrix) frame = finish.FaceAxis switch
+ {
+ "-Z" => (x, y, z, new double[] { 1,0,0,0, 0,-1,0,0, 0,0,-1,0, 0,0,z,1 }),
+ "+X" => (y, z, x, new double[] { 0,1,0,0, 0,0,1,0, 1,0,0,0, -x/2,0,z/2,1 }),
+ "-X" => (y, z, x, new double[] { 0,-1,0,0, 0,0,1,0, -1,0,0,0, x/2,0,z/2,1 }),
+ "+Y" => (x, z, y, new double[] { -1,0,0,0, 0,0,1,0, 0,1,0,0, 0,-y/2,z/2,1 }),
+ "-Y" => (x, z, y, new double[] { 1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,y/2,z/2,1 }),
+ _ => default
+ };
+ if (frame.Matrix is null)
+ return CombinedFailure($"EdgeFinishFaceUnsupported: '{finish.FaceAxis}' is not a principal Box face.", sourceSpan: finish.SourceSpan);
+ var kind = finish.Kind == "Fillet" ? TopBoundaryEdgeFinishKind.Fillet : TopBoundaryEdgeFinishKind.Chamfer;
+ var plan = new CombinedTopBoundaryEdgeFinishThroughHolePlan(
+ $"edgefinish:{solid.Name}:{finish.Name}", $"stock:{solid.Name}", [finish.Name],
+ frame.Width, frame.Depth, 0, frame.Height, finish.Distance, [], kind);
+ var built = CombinedTopBoundaryEdgeFinishThroughHoleBuilder.Build(plan);
+ if (!built.IsSuccess)
+ return CombinedFailure("EdgeFinishFaceBoundaryRejected: Finish size must fit the selected face and its stock depth.",
+ built.Diagnostics.Select(d => d.Message), finish.SourceSpan);
+ var body = FirmasmAssemblyExecutor.TransformBody(built.Value, Transform3D.FromRowMajor(frame.Matrix));
+ if (!FirmamentManifoldChecker.IsManifold(body))
+ return CombinedFailure("EdgeFinishFaceBoundaryNonManifold", sourceSpan: finish.SourceSpan);
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid)
+ return CombinedFailure("EdgeFinishFaceBoundaryPreflightFailed", preflight.Diagnostics.Select(d => d.Message), finish.SourceSpan);
+ var support = ValidateV2PmiExportSupport(document);
+ if (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);
+ var step = Step242Exporter.ExportBody(body, BuildV2SemanticPmi(document, [], solid.Name, body: body));
+ if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var imported = Step242Importer.ImportBody(step.Value);
+ if (!imported.IsSuccess || !FirmamentManifoldChecker.IsManifold(imported.Value))
+ return CombinedFailure("EdgeFinishFaceBoundaryRoundtripFailed", imported.Diagnostics.Select(d => d.Message), finish.SourceSpan);
+ return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, document.ModelName, 0,
+ "box-face-boundary-finish", "BoxFaceBoundaryFinish")
+ {
+ RuntimeBody = body,
+ MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name),
+ EngineeringFeatures = [new(finish.Name, "EdgeFinish", $"edgefinish:{finish.Name}", solid.Name,
+ finish.FaceAxis, "Boundary", finish.Distance, finish.Kind == "Fillet" ? "Radius" : "Distance", "Remove",
+ PolicySource: finish.Kind, MaterializationRoute: "BoxFaceBoundaryFinish")]
+ });
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
new file mode 100644
index 00000000..1ba3ea00
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.ProfileRim.cs
@@ -0,0 +1,64 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Execution;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament;
+
+public static partial class FirmamentBuildAndExport
+{
+ private static IEnumerable<ResolvedProfile2D> RimSupportProfiles(string source,
+ IReadOnlyDictionary<string, ResolvedProfile2D> profiles, PrismaticSectionStackConstruction stack)
+ {
+ var stock = stack.Feature.Operations.Where(o => o.Intent == PrismaticProfileIntent.Base).ToArray();
+ if (ProfileBoundaryChamferSourceBinder.HasHostBoundaryFinish(source) && stock.Length == 1)
+ return profiles.Where(p => p.Key == stock[0].ProfileReference).Select(p => p.Value);
+ return profiles.Values.OrderBy(p => p.Name, StringComparer.Ordinal);
+ }
+
+ private static KernelResult<FirmamentStepExportResult> ExportComposedProfileRim(string source,
+ PrismaticSectionStackConstruction stack, ResolvedProfile2D profile, ProfileBoundaryChamferTarget target,
+ double amount, bool fillet, double clearance, PrismaticSectionStackEmissionResult emitted, FirmamentV2Document? document)
+ {
+ var declaration = ProfileBoundaryChamferSourceBinder.FinishDeclarations(source)
+ .Single(d => $"edgefinish:{d.Name?.Text}" == target.StableId);
+ KernelResult<FirmamentStepExportResult> Fail(IEnumerable<string> messages) => KernelResult<FirmamentStepExportResult>.Failure(
+ messages.Select(message => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ message, "Firmament.ProfileRimFinish") { SourceSpan = new(declaration.Span.Start, declaration.Span.Length) }).ToArray());
+ var planned = ProfileRimCavityRetention.TryPlan(stack, profile, target, amount, fillet, clearance, emitted);
+ if (!planned.Succeeded || planned.Body is null || planned.Correspondence is null) return Fail(planned.Diagnostics);
+ if (!FirmamentManifoldChecker.IsManifold(planned.Body)) return Fail(["ProfileRimFinishNonManifold"]);
+ var pmi = Array.Empty<Step242SemanticPmi>();
+ if (document is not null)
+ {
+ var support = ValidateV2PmiExportSupport(document);
+ if (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);
+ var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(h => h.Name, h => h.StableId, StringComparer.Ordinal);
+ foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
+ foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
+ pmi = BuildV2SemanticPmi(document, [], stack.Feature.Name, features, planned.Correspondence, planned.Body).ToArray();
+ }
+ var step = Step242Exporter.ExportBody(planned.Body, pmi, new Step242ExportOptions {
+ ProductName = stack.Feature.Name, ApplicationName = "Aetheris.ProfileRimFinish", BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
+ if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var imported = Step242Importer.ImportBody(step.Value);
+ if (!imported.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(imported.Diagnostics);
+ if (!FirmamentManifoldChecker.IsManifold(imported.Value)) return Fail(["ProfileRimFinishRoundtripNonManifold"]);
+ return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, stack.Feature.Name, 0,
+ "profile-rim-cavities", "ProfileRimCavityRetention", Features: CompositionHoleReports(stack.Feature, planned.Body, planned.Correspondence),
+ EngineeringFeatures: EngineeringFeatureReports(stack.Feature).Append(new FirmamentEngineeringFeatureReport(
+ target.StableId["edgefinish:".Length..], "EdgeFinish", target.StableId, target.HostBodyId, target.Side.ToString(),
+ $"{target.ProfileId}.{target.LoopId}", amount, fillet ? "Radius" : "Distance", "Remove", PolicySource: fillet ? "Fillet" : "Chamfer",
+ MaterializationRoute: "ProfileRimCavityRetention")).ToArray())
+ {
+ RuntimeBody = planned.Body, RuntimeCorrespondence = planned.Correspondence, RuntimeBodySourceName = stack.Feature.Name,
+ EdgeFinishPlanning = planned.PlanningEvidence,
+ MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, planned.Correspondence)
+ .Concat(FirmamentFeatureAccounting.ProfileFinish(source, target.StableId["edgefinish:".Length..], target.HostBodyId)).ToArray()
+ });
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index c9074e70..b0fa346c 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -1131,27 +1131,39 @@ public static partial class FirmamentBuildAndExport
string source, PrismaticProfileCompositionParseResult parsed, PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted,
FirmamentV2Document? canonicalDocument)
{
+ var finishSpan = ProfileBoundaryChamferSourceBinder.FinishDeclarations(source).FirstOrDefault()?.Span;
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")]);
+ new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.ComposeSemanticSelection")
+ { SourceSpan = finishSpan is { } span ? new(span.Start, span.Length) : null }]);
if (ProfileBoundaryChamferSourceBinder.SequenceDiagnostic(source) is { } sequenceDiagnostic) return Fail(sequenceDiagnostic);
- if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source))
+ if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)
+ || (ProfileBoundaryChamferSourceBinder.HasHostBoundaryFinish(source)
+ && (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source)
+ || RimSupportProfiles(source, parsed.Profiles, stack).Any(p =>
+ !IsAdmittedPrimitiveBoundary(p.Loops.Single(l => l.IsOuter).Segments.Select(s => s.Geometry).ToArray())))))
{
if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))
{
ProfileBoundaryChamferTarget? filletTarget = null; ResolvedProfile2D? filletProfile = null; double radius = 0d; double clearance = 0d; string? filletDiagnostic = null;
- foreach (var candidate in parsed.Profiles.Values.OrderBy(x => x.Name, StringComparer.Ordinal))
+ foreach (var candidate in RimSupportProfiles(source, parsed.Profiles, stack))
if (ProfileBoundaryChamferSourceBinder.TryBindFillet(source, candidate, stack.Feature.Name, out filletTarget, out radius, out clearance, out filletDiagnostic)) { filletProfile = candidate; break; }
if (filletProfile is null || filletTarget is null) return Fail(filletDiagnostic ?? "ProfileBoundaryFilletProfileUnknown");
- var filletAdmission = ProfileStraightEdgeFilletAdmissionChecker.Check(stack, filletProfile, filletTarget, radius, clearance);
- if (!filletAdmission.Disjoint) return Fail(filletAdmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletCavityInteractionUnsupported");
- return Fail("ProfileBoundaryFilletComposeUnsupported: A composed-body fillet requires an adapter that retains its existing material intervals and cavities. The current profile fillet planner constructs a fresh extrusion; it cannot replace this body without losing authored features. No geometry was emitted.");
+ if (filletTarget.ChainKind != ProfileBoundaryChamferChainKind.ClosedLoop)
+ {
+ var filletAdmission = ProfileStraightEdgeFilletAdmissionChecker.Check(stack, filletProfile, filletTarget, radius, clearance);
+ if (!filletAdmission.Disjoint) return Fail(filletAdmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletCavityInteractionUnsupported");
+ return Fail("ProfileBoundaryFilletComposeUnsupported: An open-chain composed fillet requires an adapter that retains its existing material intervals and cavities and qualifies endpoint termination. No geometry was emitted.");
+ }
+ return ExportComposedProfileRim(source, stack, filletProfile, filletTarget, radius, true, clearance, emitted, canonicalDocument);
}
ProfileBoundaryChamferTarget? target = null; double distance = 0d; string? bindingDiagnostic = null; ResolvedProfile2D? profile = null;
- foreach (var candidate in parsed.Profiles.Values.OrderBy(x => x.Name, StringComparer.Ordinal))
+ foreach (var candidate in RimSupportProfiles(source, parsed.Profiles, stack))
{
if (ProfileBoundaryChamferSourceBinder.TryBind(source, candidate, stack.Feature.Name, out target, out distance, out bindingDiagnostic)) { profile = candidate; break; }
}
if (profile is null || target is null) return Fail(bindingDiagnostic ?? "ProfileBoundaryChamferProfileUnknown");
+ if (target.Side == ProfileBoundaryChamferSide.Bottom || profile.Loops.Any(l => l.Segments.Any(s => s.Geometry is LineArcCircularArc2D)))
+ return ExportComposedProfileRim(source, stack, profile, target, distance, false, distance, emitted, canonicalDocument);
var admission = ComposedProfileBoundaryChamferAdmissionChecker.Check(stack, profile, target, distance);
if (!admission.Admitted) return Fail(admission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferCavityInteractionUnsupported");
var adjusted = ComposedProfileBoundaryChamferStackPlanner.TryApply(stack, profile, target, distance, out var planDiagnostics);
@@ -1243,7 +1255,10 @@ public static partial class FirmamentBuildAndExport
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.HasSemanticProfileBoundaryFinish(source)
+ || (ProfileBoundaryChamferSourceBinder.HasHostBoundaryFinish(source)
+ && (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source)
+ || !IsAdmittedPrimitiveBoundary(profile.Loops.First(l => l.IsOuter).Segments.Select(s => s.Geometry).ToArray()))))
{
if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))
{
@@ -1685,6 +1700,9 @@ public static partial class FirmamentBuildAndExport
if (solid?.Primitive is not FirmamentV2BoxRecord box || box.Size.Count != 3)
return AirChamferFailure("chamfer-unsupported-history:expected-history-known-box-or-right-circular-cylinder");
+ if (finish.Target == "Boundary" && finish.FaceAxis != "+Z" && finish.Kind is "Chamfer" or "Fillet")
+ return ExportV2BoxFaceBoundaryFinish(document, solid, finish, box);
+
// AIR-FILLET-LOCALIZED-M1: semantic support-face selection only; emitted BRep IDs never enter Firmament.
if (string.Equals(finish.Kind, "Fillet", StringComparison.Ordinal))
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePalette.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePalette.cs
index d45109f5..5124c952 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePalette.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePalette.cs
@@ -37,9 +37,9 @@ public static class FirmamentLanguagePaletteService
new("perforation", "Perforation", "Holes", "A field of round vents across the top face.", "feature", "Vents",
"Perforation Vents { On: +Z Diameter: 6mm Layout: Hex Pitch: 9mm Margin: 8mm }"),
- new("chamfer", "Chamfer top edges", "Edges", "Breaks the edges around the top face with a 45° chamfer.", "feature", "TopChamfer",
+ new("chamfer", "Chamfer face rim", "Edges", "Breaks the selected face's boundary with a 45° chamfer. Choose Face; the default is +Z.", "feature", "TopChamfer",
"EdgeFinish TopChamfer { Face: +Z Target: Boundary Kind: Chamfer Distance: 1mm }"),
- new("fillet", "Round top edges", "Edges", "Rounds the edges around the top face.", "feature", "TopRound",
+ new("fillet", "Fillet face rim", "Edges", "Rounds the selected face's boundary. Choose Face; the default is +Z.", "feature", "TopRound",
"EdgeFinish TopRound { Face: +Z Target: Boundary Kind: Fillet Radius: 1mm }"),
];
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 9a9f5c8d..d4fa71db 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1298,13 +1298,8 @@ public static partial class FirmamentV2Parser
};
var (compositionPmi, compositionPmiBlock, compositionBoundPmi) = ParsePmi(
source, compositionSolids, [], [], [], [], diagnostics, (feature.ShaftHoles ?? []).Select(hole => hole.Name).Concat((feature.CounterboreHoles ?? []).Select(hole => hole.Name)).Concat((feature.CountersinkHoles ?? []).Select(hole => hole.Name)));
- if (Regex.IsMatch(body, @"\bEdgeFinish\b", RegexOptions.CultureInvariant)
- && !ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(body)
- && composition.Profiles.Values.Any(profile => profile.Loops.Single().Segments.Count != 4))
- {
- diagnostics.Add($"{EdgeFinishProfileComposeBoundaryUnsupported}:host={feature.Name}:construction=Compose:face=+Z:target=Boundary: EdgeFinish on a Profile-based body is supported on four-sided boundaries; this boundary has curved or extra segments. Use Box stock for a rounded or chamfered rim, or shape the corners in the Profile itself.");
- return CanonicalFailure(diagnostics, EdgeFinishProfileComposeBoundaryUnsupported);
- }
+ // Geometry capability belongs to the source-bound edge-finish planner;
+ // a curved Profile is not a syntax error. Normal validation builds it.
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var document = new FirmamentV2Document(
model.Name!.Text,
@@ -1349,13 +1344,8 @@ public static partial class FirmamentV2Parser
[resolved.Name] = new FirmamentV2SolidBinding(resolved.Name, "Profile", new FirmamentV2AdvancedMaterialRecord("Profile"))
};
var (profilePmi, profilePmiBlock, profileBoundPmi) = ParsePmi(source, profileSolids, [], [], [], [], diagnostics);
- if (Regex.IsMatch(body, @"\bEdgeFinish\b", RegexOptions.CultureInvariant)
- && !ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(body)
- && resolved.Loops.Single().Segments.Count != 4)
- {
- diagnostics.Add($"{EdgeFinishProfileComposeBoundaryUnsupported}:host={resolved.Name}:construction=Profile:face=+Z:target=Boundary: EdgeFinish on a Profile-based body is supported on four-sided boundaries; this boundary has curved or extra segments. Use Box stock for a rounded or chamfered rim, or shape the corners in the Profile itself.");
- return CanonicalFailure(diagnostics, EdgeFinishProfileComposeBoundaryUnsupported);
- }
+ // Geometry capability belongs to the source-bound edge-finish planner;
+ // a curved Profile is not a syntax error. Normal validation builds it.
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var document = new FirmamentV2Document(
model.Name!.Text,
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs
index 27191dc6..0246bcdd 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs
@@ -16,7 +16,7 @@ public static class ProfileSemanticDeclaration { }
public static class ExtrudeSemanticDeclaration { }
[FirmamentConstruct("Compose", "Compose", Context = "Model", Entry = "Compose Plate {\n Base Stock { Profile: Outline; From: 0mm; To: 8mm; Role: Stock }\n}",
- Description = "A Profile-based body built from a Base and optional Boss, Pocket and Hole operations. A later Modify on the Compose name takes Hole, Slot, Pattern and top-rim chamfers on four-sided boundaries; round vertical corners in the Profile (RoundedRect2).")]
+ Description = "A Profile-based body built from a Base and optional Boss, Pocket and Hole operations. A later Modify takes Hole, Slot, Pattern and qualified Profile rim finishes. A constant native-XY Base with disjoint through round holes supports top or bottom fillets/chamfers, including RoundedRect2 corners; other material histories have narrower admission. Round vertical corners in the Profile (RoundedRect2).")]
public static class ComposeSemanticDeclaration { }
[FirmamentConstruct("ComposeBase", "Base", Context = "Compose", Entry = "Base Stock { Profile: Outline; From: 0mm; To: 8mm; Role: Stock }",
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
index 7cb4dfd6..15b4bd5c 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
@@ -73,6 +73,7 @@ public static class PrismaticSectionStackBrepMaterializer
var clone = new BrepBindingModel();
foreach (var binding in source.EdgeBindings.OrderBy(x => x.EdgeId.Value)) clone.AddEdgeBinding(binding);
foreach (var binding in source.FaceBindings.OrderBy(x => x.FaceId.Value)) clone.AddFaceBinding(binding);
+ foreach (var binding in source.FaceBoundaryRoleBindings.OrderBy(x => x.LoopId.Value)) clone.AddFaceBoundaryRoleBinding(binding);
return clone;
}
}
@@ -194,6 +195,7 @@ public static class PrismaticSectionStackEmitter
var builder = new TopologyBuilder(); var points = new Dictionary<VertexId, Point3D>(); var curves = new Dictionary<EdgeId, CurveGeometry>(); var profileCurves = new Dictionary<EdgeId, LineArcProfileCurve2D>();
var vertices = new Dictionary<(long X, long Y, long Z), VertexId>(); var edges = new Dictionary<string, EdgeId>();
var sideFaces = new List<(LoopId Loop, SurfaceGeometry Surface, bool SameSense, string Source, string Construction, double From, double To)>(); var capFaces = new List<(FaceId Face, double Z, bool Up)>();
+ var capLoopRoles = new List<FaceBoundaryRoleBinding>();
var countersinks = stack.Feature.CountersinkHoles ?? [];
PrismaticCountersinkHoleFeature? CountersinkFor(string source) => countersinks.SingleOrDefault(h =>
SourceId(source).StartsWith($"profile:{h.ShaftProfileReference}.Outer.", StringComparison.Ordinal));
@@ -275,8 +277,8 @@ public static class PrismaticSectionStackEmitter
}
foreach (var transition in stack.Transitions)
{
- foreach (var region in transition.UpwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints, AtStation), transition.Level, true));
- foreach (var region in transition.DownwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints, AtStation), transition.Level, false));
+ foreach (var region in transition.UpwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints, AtStation, capLoopRoles), transition.Level, true));
+ foreach (var region in transition.DownwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints, AtStation, capLoopRoles), transition.Level, false));
}
var faces = new List<FaceId>();
foreach (var cap in capFaces) faces.Add(cap.Face);
@@ -292,6 +294,7 @@ public static class PrismaticSectionStackEmitter
curveId++;
}
var surfaceId = 1;
+ foreach (var role in capLoopRoles) bindings.AddFaceBoundaryRoleBinding(role);
foreach (var cap in capFaces) { geometry.AddSurface(new SurfaceGeometryId(surfaceId), SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((0d, 0d), cap.Z), cap.Up ? frame.AxisZ : Direction3D.Create(-frame.AxisZ.ToVector()), frame.AxisX))); bindings.AddFaceBinding(new FaceGeometryBinding(cap.Face, new SurfaceGeometryId(surfaceId++))); }
foreach (var side in sideFaces) { var face = faces[capFaces.Count + sideFaces.IndexOf(side)]; geometry.AddSurface(new SurfaceGeometryId(surfaceId), Transform(side.Surface, frame)); bindings.AddFaceBinding(new FaceGeometryBinding(face, new SurfaceGeometryId(surfaceId++), side.SameSense)); }
foreach (var incidence in builder.Model.Coedges.GroupBy(x => x.EdgeId).Where(x => x.Count() != 2))
@@ -493,16 +496,20 @@ public static class PrismaticSectionStackEmitter
return new(plan, d.Distinct().ToArray(), correspondence);
}
private static FaceId AddCap(TopologyBuilder builder, PrismaticSectionRegion region, double z, Func<LineArcProfileCurve2D, double, (EdgeId Edge, bool Reverse)> edge, IReadOnlyList<(double X, double Y)> splitPoints,
- Func<LineArcProfileCurve2D, double, string, LineArcProfileCurve2D> atStation)
+ Func<LineArcProfileCurve2D, double, string, LineArcProfileCurve2D> atStation, List<FaceBoundaryRoleBinding> roles)
{
var loops = new List<LoopId>();
+ var kinds = new List<FaceBoundaryRole>();
foreach (var item in Loops(region))
{
var segments = item.IsHole ? item.Profile.Loops[0].Segments.Reverse() : item.Profile.Loops[0].Segments;
var curves = segments.SelectMany(s => Split(s.Geometry, splitPoints).Select(curve => atStation(curve, z, s.Provenance.StableId))).ToArray();
loops.Add(AddLoop(builder, curves.Select(curve => { var e = edge(curve, z); return new Use(e.Edge, item.IsHole ? !e.Reverse : e.Reverse); }).ToArray()));
+ kinds.Add(item.IsHole ? FaceBoundaryRole.Inner : FaceBoundaryRole.Outer);
}
- return builder.AddFace(loops);
+ var face = builder.AddFace(loops);
+ for (var i = 0; i < loops.Count; i++) roles.Add(new(face, loops[i], kinds[i]));
+ return face;
}
private static IEnumerable<(ResolvedProfile2D Profile, bool IsHole)> Loops(PrismaticSectionRegion region) { yield return (region.Outer, false); foreach (var h in region.Holes) yield return (h, true); }
private static (double X, double Y)[] Ends(LineArcProfileCurve2D curve) => curve switch { LineArcLineSegment2D l => [l.Start, l.End], LineArcCircularArc2D a => [(a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians)), (a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians + a.SweepAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians + a.SweepAngleRadians))], LineArcCubicBezier2D c => [c.Start, c.End], _ => throw new NotSupportedException($"Unsupported section boundary: {curve.GetType().Name}") };
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs
index afcaa327..74f08fb0 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs
@@ -54,7 +54,6 @@ public sealed record ProfileStraightEdgeFilletPlanResult(
public static class ProfileBoundaryChamferSourceBinder
{
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);
private static readonly Regex Distance = new(@"\bDistance\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);
private static readonly Regex Radius = new(@"\bRadius\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);
@@ -62,15 +61,20 @@ public static class ProfileBoundaryChamferSourceBinder
private static readonly Regex ReflexJunction = new(@"\bReflexJunction\s*:\s*(?<value>\w+)\b", RegexOptions.CultureInvariant);
public static bool HasSemanticProfileBoundaryFinish(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);
+ FinishDeclarations(source).Any(d => SupportWord(d) is "Top" or "Bottom");
- 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"));
+ public static bool HasProfileBoundaryFillet(string source) => FinishDeclarations(source)
+ .Any(d => IsCapWord(SupportWord(d)) && FinishKind(d) == "Fillet");
+
+ internal static bool HasHostBoundaryFinish(string source) => FinishDeclarations(source)
+ .Any(d => Word(d, "Target") == "Boundary" && IsCapWord(SupportWord(d)))
+ && !FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Any(d => d.Type.Name.Text == "Selection" && d.Name?.Text == "Boundary");
+
+ private static string SupportWord(DeclarationSyntax d) => Word(d, "On") is { Length: > 0 } on ? on : Word(d, "Face");
+ private static string FinishKind(DeclarationSyntax d) => Word(d, "Kind") is { Length: > 0 } kind ? kind
+ : d.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(d.Type.Arguments[0].Value) ?? "" : "";
+ private static bool IsCapWord(string value) => value is "Top" or "Bottom" or "+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z";
internal static IEnumerable<DeclarationSyntax> FinishDeclarations(string source)
{
@@ -104,7 +108,7 @@ public static class ProfileBoundaryChamferSourceBinder
target = null; radius = 0d; endClearance = 0d; diagnostic = null;
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");
+ var finish = finishes.FirstOrDefault(d => IsCapWord(SupportWord(d)) && FinishKind(d) == "Fillet");
if (finish?.Body is null) { diagnostic = "ProfileBoundaryFilletBoundaryRequired"; return false; }
var fields = new FinishFields(finish);
fields.Read("Kind", Kind);
@@ -116,13 +120,21 @@ public static class ProfileBoundaryChamferSourceBinder
}
var radiusMatch = fields.Read("Radius", Radius); var clearanceMatch = fields.Read("EndClearance", EndClearance);
if (!radiusMatch.Success || !double.TryParse(radiusMatch.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out radius) || !double.IsFinite(radius) || radius <= 0d) { diagnostic = "ProfileBoundaryFilletRadiusMustBePositive"; return false; }
- var targetMatch = fields.Read("Target", Target); var on = fields.Read("On", On);
- if (!targetMatch.Success || !on.Success) { diagnostic = "ProfileBoundaryFilletDeclarationInvalid"; return false; }
+ var targetMatch = fields.Read("Target", Target);
+ if (!fields.ReadSide(profile, out var side, out diagnostic)) return false;
+ if (!targetMatch.Success) { diagnostic = "ProfileBoundaryFilletDeclarationInvalid"; return false; }
var rawTarget = targetMatch.Groups["value"].Value;
string requestedProfile; string requestedLoop; IReadOnlyList<string> requestedSegments;
ProfileBoundaryChamferChainKind chainKind; string provenance;
var parts = rawTarget.Split('.');
- if (parts.Length is 2 or 3)
+ if (rawTarget == "Boundary" && HasHostBoundaryFinish(source))
+ {
+ var outer = profile.Loops.Where(l => l.IsOuter).ToArray();
+ if (outer.Length != 1) { diagnostic = "ProfileBoundaryEdgeFinishOuterLoopAmbiguous"; return false; }
+ requestedProfile = profile.Name; requestedLoop = outer[0].Name; requestedSegments = [];
+ chainKind = ProfileBoundaryChamferChainKind.ClosedLoop; provenance = "HostCapBoundaryTarget";
+ }
+ else if (parts.Length is 2 or 3)
{
requestedProfile = parts[0]; requestedLoop = parts[1];
requestedSegments = parts.Length == 3 ? [parts[2]] : [];
@@ -166,7 +178,7 @@ public static class ProfileBoundaryChamferSourceBinder
}
if (!fields.Complete(out diagnostic)) return false;
target = new($"edgefinish:{finish.Name?.Text}", hostBodyId, profile.Name, loop.Name,
- orderedSegments.Select(segment => segment.Name).ToArray(), Enum.Parse<ProfileBoundaryChamferSide>(on.Groups["value"].Value),
+ orderedSegments.Select(segment => segment.Name).ToArray(), side,
chainKind, $"offset:{finish.Span.Start}", provenance, reflexJunctionStyle);
return true;
}
@@ -176,12 +188,15 @@ public static class ProfileBoundaryChamferSourceBinder
target = null; distance = 0d; diagnostic = null;
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");
+ var finish = finishes.FirstOrDefault(d => IsCapWord(SupportWord(d)));
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; }
+ var targetMatch = fields.Read("Target", Target);
+ if (!fields.ReadSide(profile, out var side, out diagnostic)) return false;
+ var kind = fields.Read("Kind", Kind);
+ var amount = fields.Read("Distance", Distance);
+ if (!targetMatch.Success || !kind.Success) { diagnostic = "ProfileBoundaryChamferDeclarationInvalid"; return false; }
if (string.Equals(kind.Groups["value"].Value, "Fillet", StringComparison.Ordinal))
{
diagnostic = fields.Read("Radius", Radius).Success ? "ProfileBoundaryFilletNotMaterialized" : "ProfileBoundaryFilletRadiusRequired";
@@ -194,7 +209,14 @@ public static class ProfileBoundaryChamferSourceBinder
var rawTarget = targetMatch.Groups["value"].Value;
string requestedProfile; string loop; IReadOnlyList<string> segments; ProfileBoundaryChamferChainKind chainKind; string provenance;
var parts = rawTarget.Split('.');
- if (parts.Length >= 2)
+ if (rawTarget == "Boundary" && HasHostBoundaryFinish(source))
+ {
+ var outer = profile.Loops.Where(l => l.IsOuter).ToArray();
+ if (outer.Length != 1) { diagnostic = "ProfileBoundaryEdgeFinishOuterLoopAmbiguous"; return false; }
+ requestedProfile = profile.Name; loop = outer[0].Name; segments = [];
+ chainKind = ProfileBoundaryChamferChainKind.ClosedLoop; provenance = "HostCapBoundaryTarget";
+ }
+ else if (parts.Length >= 2)
{
requestedProfile = parts[0]; loop = parts[1];
if (parts.Length == 3) { segments = [parts[2]]; chainKind = ProfileBoundaryChamferChainKind.SingleSegment; }
@@ -224,7 +246,7 @@ public static class ProfileBoundaryChamferSourceBinder
else 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.Span.Start}", provenance);
+ side, chainKind, $"offset:{finish.Span.Start}", provenance);
return true;
}
@@ -232,14 +254,23 @@ public static class ProfileBoundaryChamferSourceBinder
{
private readonly List<string> diagnostics = [];
private readonly FirmamentSyntaxFields fields;
+ private readonly DeclarationSyntax declaration;
internal FinishFields(DeclarationSyntax declaration)
{
+ this.declaration = declaration;
fields = new(declaration, diagnostics);
fields.Take("PatternIdentity"); // Compiler-owned finite expansion receipt.
}
internal Match Read(string name, Regex reader)
{
var value = fields.Take(name);
+ if (name == "Kind" && declaration.Type.Arguments.Count == 1)
+ {
+ var variant = declaration.Type.Arguments[0].Value;
+ if (value is not null && FirmamentSyntaxValues.Reference(value) != FirmamentSyntaxValues.Reference(variant))
+ { diagnostics.Add("ProfileBoundaryEdgeFinishKindMismatch"); return Match.Empty; }
+ value ??= variant;
+ }
if (value is null) return Match.Empty;
var text = name + ": " + FirmamentSyntaxWriter.Expression(value);
var match = reader.Match(text);
@@ -247,6 +278,21 @@ public static class ProfileBoundaryChamferSourceBinder
fields.Invalid(name); // Optional malformed fields must not disappear into defaults.
return Match.Empty;
}
+ internal bool ReadSide(ResolvedProfile2D profile, out ProfileBoundaryChamferSide side, out string? diagnostic)
+ {
+ side = default; diagnostic = null;
+ var on = fields.Take("On"); var face = fields.Take("Face");
+ if (on is not null && face is not null) { diagnostic = "ProfileBoundaryEdgeFinishSupportAmbiguous: Use either on or face, not both."; return false; }
+ var value = FirmamentSyntaxValues.Reference(on ?? face);
+ if (value is "Top" or "Bottom") { side = Enum.Parse<ProfileBoundaryChamferSide>(value); return true; }
+ var axis = value switch { "+X" => new Vector3D(1,0,0), "-X" => new Vector3D(-1,0,0),
+ "+Y" => new Vector3D(0,1,0), "-Y" => new Vector3D(0,-1,0), "+Z" => new Vector3D(0,0,1), "-Z" => new Vector3D(0,0,-1), _ => default };
+ var dot = profile.EffectiveConstructionPlane.AxisZ.ToVector().Dot(axis);
+ if (Math.Abs(dot) < 1d - 1e-8) { diagnostic = $"ProfileBoundaryEdgeFinishFaceNotCap:{value}: Select on: Top or on: Bottom for an extrusion cap; the requested axis is not its normal."; return false; }
+ side = dot > 0 ? ProfileBoundaryChamferSide.Top : ProfileBoundaryChamferSide.Bottom;
+ return true;
+ }
+
internal bool Complete(out string? diagnostic)
{
fields.Complete();
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileRimCavityRetention.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileRimCavityRetention.cs
new file mode 100644
index 00000000..0cf93aa2
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileRimCavityRetention.cs
@@ -0,0 +1,173 @@
+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.Topology;
+
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+/// <summary>Finishes a constant-stock profile rim while retaining its source-planned,
+/// disjoint through cavities. This joins known planar cap loops, not Boolean tools.</summary>
+internal static class ProfileRimCavityRetention
+{
+ private const double Tol = 1e-7;
+ private sealed record Cavity(string Name, string StableId, double CenterX, double CenterY, double Radius, double From, double To);
+ internal static ProfileBoundaryChamferPlanResult TryPlan(PrismaticSectionStackConstruction stack,
+ ResolvedProfile2D profile, ProfileBoundaryChamferTarget target, double amount, bool fillet,
+ double clearance, PrismaticSectionStackEmissionResult original)
+ {
+ ProfileBoundaryChamferPlanResult Fail(string text) => new(false, null, null, target, [text]);
+ var feature = stack.Feature;
+ var stock = feature.Operations.Where(o => o.Intent == PrismaticProfileIntent.Base).ToArray();
+ var holes = (feature.ShaftHoles ?? []).Select(h => new Cavity(h.Name, h.StableId, h.CenterX, h.CenterY, h.Diameter / 2, h.From, h.To))
+ .Concat((feature.CounterboreHoles ?? []).Select(h => new Cavity(h.Name, h.StableId, h.CenterX, h.CenterY, h.CounterboreDiameter / 2, h.From, h.To)))
+ .Concat((feature.CountersinkHoles ?? []).Select(h => new Cavity(h.Name, h.StableId, h.CenterX, h.CenterY, h.CountersinkDiameter / 2, h.From, h.To))).ToArray();
+ var ids = holes.Select(h => h.StableId).ToHashSet(StringComparer.Ordinal);
+ if (stock.Length != 1 || stock[0].ProfileReference != profile.Name || profile.Loops.Count != 1
+ || target.ChainKind != ProfileBoundaryChamferChainKind.ClosedLoop
+ || feature.Operations.Any(o => o.Intent != PrismaticProfileIntent.Base && (o.SemanticFeatureId is null || !ids.Contains(o.SemanticFeatureId)))
+ || (feature.ConstructionPlaneBlindDrills?.Count ?? 0) != 0)
+ return Fail("ProfileRimFinishHistoryUnsupported: This rim plan preserves one constant-stock Base and disjoint through round holes; additional material operations need a qualified adapter.");
+ if (!feature.Placement.TryResolveConstructionPlane(out var frame, out var frameError)) return Fail(frameError!);
+ if (frame is null || (frame.Origin - Point3D.Origin).Length > Tol
+ || (frame.AxisX.ToVector() - new Vector3D(1,0,0)).Length > Tol
+ || (frame.AxisY.ToVector() - new Vector3D(0,1,0)).Length > Tol || frame.AxisZ.ToVector().Z < 1 - Tol)
+ return Fail("ProfileRimFinishFrameUnsupported: The cavity-retaining rim plan currently requires the native XY stock frame.");
+ foreach (var hole in holes)
+ {
+ if (Math.Abs(hole.From - stock[0].From) > Tol || Math.Abs(hole.To - stock[0].To) > Tol)
+ return Fail($"ProfileRimFinishThroughHoleRequired:{hole.Name}");
+ var margin = profile.Loops[0].Segments.Min(s => Distance(s.Geometry, hole.CenterX, hole.CenterY)) - hole.Radius - amount;
+ if (!double.IsFinite(margin) || margin <= Tol) return Fail($"ProfileRimFinishCavityInterference:{hole.Name}: Entry footprint must clear the rim corridor by a positive margin; remaining={margin:R}mm.");
+ }
+ for (var i = 0; i < holes.Length; i++) for (var j = i + 1; j < holes.Length; j++)
+ if (Math.Sqrt(Math.Pow(holes[i].CenterX - holes[j].CenterX, 2) + Math.Pow(holes[i].CenterY - holes[j].CenterY, 2)) <= holes[i].Radius + holes[j].Radius + Tol)
+ return Fail($"ProfileRimFinishCavitiesOverlap:{holes[i].Name}:{holes[j].Name}");
+ profile = profile with { LocalStartDepth = stock[0].From, LocalEndDepth = stock[0].To, ConstructionPlane = frame };
+ ProfileBoundaryChamferPlanResult finished;
+ if (fillet)
+ {
+ var plan = ProfileFilletShellPlanner.TryPlan(profile, target, amount, clearance);
+ finished = new(plan.Succeeded, plan.Body, plan.Correspondence, target, plan.Diagnostics) { PlanningEvidence = plan.PlanningEvidence };
+ }
+ else finished = ProfileBoundaryChamferPlanner.TryPlan(profile, target, amount);
+ if (!finished.Succeeded || finished.Body is null || finished.Correspondence is null || holes.Length == 0) return finished;
+ if (original.Body is null || original.Correspondence is null) return Fail("ProfileRimFinishSourceNotMaterialized");
+ try
+ {
+ var graft = RetainCavities(finished.Body, original.Body, stock[0].From, stock[0].To, holes.Length);
+ var retained = original.Correspondence.Descendants.Where(d =>
+ (!d.Edge.HasValue || graft.Edges.ContainsKey(d.Edge.Value)) && (!d.Vertex.HasValue || graft.Vertices.ContainsKey(d.Vertex.Value))
+ && (!d.Loop.HasValue || graft.Loops.ContainsKey(d.Loop.Value)) && (!d.Face.HasValue || graft.Faces.ContainsKey(d.Face.Value)))
+ .Select(d => d with { Edge = d.Edge is { } e ? graft.Edges[e] : null, Vertex = d.Vertex is { } v ? graft.Vertices[v] : null,
+ Loop = d.Loop is { } l ? graft.Loops[l] : null, Face = d.Face is { } f ? graft.Faces[f] : null });
+ var correspondence = finished.Correspondence with { BodyStableId = feature.Name,
+ Descendants = finished.Correspondence.Descendants.Concat(retained).GroupBy(d => d.StableId, StringComparer.Ordinal).Select(g => g.First()).ToArray(),
+ ProvenanceChain = finished.Correspondence.ProvenanceChain.Concat(original.Correspondence.ProvenanceChain).Append("SourcePlannedCavitiesRetained").ToArray(),
+ SourceSpans = (original.Correspondence.SourceSpans?.AsEnumerable() ?? []).Concat(finished.Correspondence.SourceSpans?.AsEnumerable() ?? [])
+ .GroupBy(p => p.Key, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Value, StringComparer.Ordinal) };
+ return finished with { Body = graft.Body, Correspondence = correspondence };
+ }
+ catch (InvalidOperationException error) { return Fail("ProfileRimFinishCavityRetentionFailed: " + error.Message); }
+ }
+
+ private static double Distance(LineArcProfileCurve2D curve, double x, double y)
+ {
+ if (curve is LineArcLineSegment2D line)
+ {
+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y;
+ var t = Math.Clamp(((x - line.Start.X) * dx + (y - line.Start.Y) * dy) / (dx * dx + dy * dy), 0, 1);
+ return Math.Sqrt(Math.Pow(x - line.Start.X - t * dx, 2) + Math.Pow(y - line.Start.Y - t * dy, 2));
+ }
+ if (curve is not LineArcCircularArc2D arc) return 0; // Unsupported corridors cannot be admitted.
+ var angle = Math.Atan2(y - arc.Center.Y, x - arc.Center.X);
+ var delta = arc.SweepAngleRadians >= 0 ? angle - arc.StartAngleRadians : arc.StartAngleRadians - angle;
+ delta = (delta % Math.Tau + Math.Tau) % Math.Tau;
+ if (delta <= Math.Abs(arc.SweepAngleRadians) + Tol)
+ return Math.Abs(Math.Sqrt(Math.Pow(x - arc.Center.X, 2) + Math.Pow(y - arc.Center.Y, 2)) - arc.Radius);
+ double At(double a) => Math.Sqrt(Math.Pow(x - arc.Center.X - arc.Radius * Math.Cos(a), 2) + Math.Pow(y - arc.Center.Y - arc.Radius * Math.Sin(a), 2));
+ return Math.Min(At(arc.StartAngleRadians), At(arc.StartAngleRadians + arc.SweepAngleRadians));
+ }
+
+ private sealed record Graft(BrepBody Body, Dictionary<VertexId, VertexId> Vertices, Dictionary<EdgeId, EdgeId> Edges,
+ Dictionary<LoopId, LoopId> Loops, Dictionary<FaceId, FaceId> Faces);
+
+ private static Graft RetainCavities(BrepBody skin, BrepBody source, double low, double high, int count)
+ {
+ Face Cap(BrepBody body, double z)
+ {
+ var candidates = body.Topology.Faces.Where(f => body.TryGetFaceSurfaceGeometry(f.Id, out var s)
+ && s?.Plane is { } p && Math.Abs(p.Normal.ToVector().Z) > 1 - Tol && Math.Abs(p.Origin.Z - z) < Tol).ToArray();
+ if (candidates.Length != 1) throw new InvalidOperationException($"Expected one planar stock cap at Z={z:R}mm; found {candidates.Length}.");
+ return candidates[0];
+ }
+ if (skin.Topology.Shells.Count() != 1 || source.Topology.Shells.Count() != 1) throw new InvalidOperationException("One closed shell is required.");
+ var caps = new[] { (Source: Cap(source, low), Target: Cap(skin, low)), (Source: Cap(source, high), Target: Cap(skin, high)) };
+ var capIds = caps.Select(c => c.Source.Id).ToHashSet();
+ var openings = caps.SelectMany(c => c.Source.LoopIds.Where(id => source.Bindings.FaceBoundaryRoleBindings
+ .Any(b => b.FaceId == c.Source.Id && b.LoopId == id && b.Role == FaceBoundaryRole.Inner))).ToHashSet();
+ if (openings.Count != 2 * count) throw new InvalidOperationException("Source cap inner-loop roles do not account for every through hole.");
+ var edgeFaces = source.Topology.Faces.SelectMany(f => f.LoopIds.SelectMany(id => source.Topology.GetLoop(id).CoedgeIds)
+ .Select(id => (source.Topology.GetCoedge(id).EdgeId, f.Id))).GroupBy(p => p.EdgeId).ToDictionary(g => g.Key, g => g.Select(p => p.Id).Distinct().ToArray());
+ var walls = new HashSet<FaceId>(); var pending = new Queue<EdgeId>(openings.SelectMany(id => source.Topology.GetLoop(id).CoedgeIds).Select(id => source.Topology.GetCoedge(id).EdgeId));
+ while (pending.TryDequeue(out var edge)) foreach (var face in edgeFaces[edge])
+ if (!capIds.Contains(face) && walls.Add(face)) foreach (var loop in source.Topology.GetFace(face).LoopIds)
+ foreach (var use in source.Topology.GetLoop(loop).CoedgeIds) pending.Enqueue(source.Topology.GetCoedge(use).EdgeId);
+ var loops = openings.Concat(walls.SelectMany(id => source.Topology.GetFace(id).LoopIds)).ToHashSet();
+ var coedges = loops.SelectMany(id => source.Topology.GetLoop(id).CoedgeIds).ToHashSet();
+ var edges = coedges.Select(id => source.Topology.GetCoedge(id).EdgeId).ToHashSet();
+ var vertices = edges.SelectMany(id => new[] { source.Topology.GetEdge(id).StartVertexId, source.Topology.GetEdge(id).EndVertexId }).ToHashSet();
+ var lastVertex = skin.Topology.Vertices.Max(v => v.Id.Value);
+ var lastEdge = skin.Topology.Edges.Max(e => e.Id.Value);
+ var lastLoop = skin.Topology.Loops.Max(l => l.Id.Value);
+ var lastCoedge = skin.Topology.Coedges.Max(c => c.Id.Value);
+ var lastFace = skin.Topology.Faces.Max(f => f.Id.Value);
+ var vm = vertices.ToDictionary(id => id, id => new VertexId(lastVertex + id.Value));
+ var em = edges.ToDictionary(id => id, id => new EdgeId(lastEdge + id.Value));
+ var lm = loops.ToDictionary(id => id, id => new LoopId(lastLoop + id.Value));
+ var cm = coedges.ToDictionary(id => id, id => new CoedgeId(lastCoedge + id.Value));
+ var fm = walls.ToDictionary(id => id, id => new FaceId(lastFace + id.Value));
+ foreach (var cap in caps) fm[cap.Source.Id] = cap.Target.Id;
+ var sourceCurves = edges.Select(id => { source.Bindings.TryGetEdgeBinding(id, out var b); return b.CurveGeometryId; }).Distinct();
+ var sourceSurfaces = walls.Select(id => { source.Bindings.TryGetFaceBinding(id, out var b); return b.SurfaceGeometryId; }).Distinct();
+ var lastCurve = skin.Geometry.Curves.Max(p => p.Key.Value);
+ var lastSurface = skin.Geometry.Surfaces.Max(p => p.Key.Value);
+ var curves = sourceCurves.ToDictionary(id => id, id => new CurveGeometryId(lastCurve + id.Value));
+ var surfaces = sourceSurfaces.ToDictionary(id => id, id => new SurfaceGeometryId(lastSurface + id.Value));
+ var topology = new TopologyModel(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>();
+ foreach (var v in skin.Topology.Vertices) { topology.AddVertex(v); if (skin.TryGetVertexPoint(v.Id, out var p)) points[v.Id] = p; }
+ foreach (var v in vertices) { topology.AddVertex(new(vm[v])); if (!source.TryGetVertexPoint(v, out var p)) throw new InvalidOperationException("Missing cavity vertex."); points[vm[v]] = p; }
+ foreach (var e in skin.Topology.Edges) topology.AddEdge(e);
+ foreach (var id in edges) { var e = source.Topology.GetEdge(id); topology.AddEdge(e with { Id = em[id], StartVertexId = vm[e.StartVertexId], EndVertexId = vm[e.EndVertexId] }); }
+ foreach (var c in skin.Topology.Coedges) topology.AddCoedge(c);
+ foreach (var id in coedges) { var c = source.Topology.GetCoedge(id); topology.AddCoedge(c with { Id = cm[id], EdgeId = em[c.EdgeId], LoopId = lm[c.LoopId], NextCoedgeId = cm[c.NextCoedgeId], PrevCoedgeId = cm[c.PrevCoedgeId] }); }
+ foreach (var l in skin.Topology.Loops) topology.AddLoop(l);
+ foreach (var id in loops) { var l = source.Topology.GetLoop(id); topology.AddLoop(l with { Id = lm[id], CoedgeIds = l.CoedgeIds.Select(c => cm[c]).ToArray() }); }
+ foreach (var f in skin.Topology.Faces) topology.AddFace(f with { LoopIds = f.LoopIds.Concat(caps.Where(c => c.Target.Id == f.Id).SelectMany(c => c.Source.LoopIds.Where(openings.Contains).Select(l => lm[l]))).ToArray() });
+ foreach (var id in walls) { var f = source.Topology.GetFace(id); topology.AddFace(f with { Id = fm[id], LoopIds = f.LoopIds.Select(l => lm[l]).ToArray() }); }
+ foreach (var shell in skin.Topology.Shells) topology.AddShell(shell with { FaceIds = shell.FaceIds.Concat(walls.Select(id => fm[id])).ToArray() });
+ foreach (var b in skin.Topology.Bodies) topology.AddBody(b);
+ foreach (var p in skin.Geometry.Curves) geometry.AddCurve(p.Key, p.Value);
+ foreach (var p in skin.Geometry.Surfaces) geometry.AddSurface(p.Key, p.Value);
+ foreach (var p in curves) { source.Geometry.TryGetCurve(p.Key, out var c); geometry.AddCurve(p.Value, c!); }
+ foreach (var p in surfaces) { source.Geometry.TryGetSurface(p.Key, out var s); geometry.AddSurface(p.Value, s!); }
+ foreach (var b in skin.Bindings.EdgeBindings) bindings.AddEdgeBinding(b);
+ foreach (var b in source.Bindings.EdgeBindings.Where(b => em.ContainsKey(b.EdgeId))) bindings.AddEdgeBinding(b with { EdgeId = em[b.EdgeId], CurveGeometryId = curves[b.CurveGeometryId] });
+ foreach (var b in skin.Bindings.FaceBindings) bindings.AddFaceBinding(b);
+ foreach (var b in source.Bindings.FaceBindings.Where(b => walls.Contains(b.FaceId))) bindings.AddFaceBinding(b with { FaceId = fm[b.FaceId], SurfaceGeometryId = surfaces[b.SurfaceGeometryId] });
+ foreach (var b in skin.Bindings.FaceBoundaryRoleBindings) bindings.AddFaceBoundaryRoleBinding(b);
+ foreach (var cap in caps)
+ {
+ // The finish planner constructed this cap from one outer Profile and
+ // no cavities. Its sole loop is known outer, not guessed by order.
+ if (cap.Target.LoopIds.Count != 1) throw new InvalidOperationException("Finished cap must have one source-planned outer boundary.");
+ var outer = cap.Target.LoopIds[0];
+ if (!skin.Bindings.FaceBoundaryRoleBindings.Any(b => b.LoopId == outer))
+ bindings.AddFaceBoundaryRoleBinding(new(cap.Target.Id, outer, FaceBoundaryRole.Outer));
+ }
+ foreach (var b in source.Bindings.FaceBoundaryRoleBindings.Where(b => lm.ContainsKey(b.LoopId))) bindings.AddFaceBoundaryRoleBinding(b with { FaceId = fm[b.FaceId], LoopId = lm[b.LoopId] });
+ foreach (var b in skin.Bindings.PcurveBindings) bindings.AddPcurveBinding(b);
+ foreach (var b in skin.Bindings.VertexLoopParameterBindings) bindings.AddVertexLoopParameterBinding(b);
+ return new(new(topology, geometry, bindings, points, shellRepresentation: skin.ShellRepresentation), vm, em, lm, fm);
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/src/concepts.ts b/Aetheris.Web.Runtime/telos/src/concepts.ts
index 4f699281..fa70ef81 100644
--- a/Aetheris.Web.Runtime/telos/src/concepts.ts
+++ b/Aetheris.Web.Runtime/telos/src/concepts.ts
@@ -1,5 +1,12 @@
import { BufferGeometry, Float32BufferAttribute, Group, Line, LineBasicMaterial, Matrix4 } from "three";
import type { DisplayPacket, TelosLine } from "./contracts.js";
+import { fromDisplayMesh } from "./adapters.js";
+
+function gold(line: TelosLine): TelosLine[] {
+ const guide = { ...line, overlay: true, pickable: false, depthMode: "always-on-top" as const,
+ widthPixels: 1.6, color: [1, .68, .12, 1] };
+ return [{ ...guide, id: line.id + ":halo", widthPixels: 7, color: [1, .62, .05, .12] }, guide];
+}
/** Gold construction guides share the material occurrence's local-to-world transform.
* A low-opacity wide stroke is a static halo, not an extra bloom/render pipeline. */
@@ -14,15 +21,30 @@ export function conceptWireframe(packet: DisplayPacket): TelosLine[] {
transform: occurrence.transform, identity: { occurrenceId: occurrence.id, overlayId: `concept:${wire.owner}` },
overlay: true, pickable: false, depthMode: "always-on-top", widthPixels: 1.6, color: [1, .68, .12, 1],
};
- return [{ ...line, id: line.id + ":halo", widthPixels: 7, color: [1, .62, .05, .12] }, line];
+ return gold(line);
}));
}
+/** Compiler-projected BRep boundaries of an operation candidate. These are
+ * presentation guides, not authored Concept declarations or selectable edges. */
+export function operationPreviewWireframe(packet: DisplayPacket): TelosLine[] {
+ return fromDisplayMesh(packet).lines.flatMap(line => gold({ ...line, id: `preview:${line.id}`,
+ identity: { ...line.identity, overlayId: "operation-preview" } }));
+}
+
+export function operationPreviewWireframeGroup(packet: DisplayPacket): Group {
+ return wireframeGroup(operationPreviewWireframe(packet), "Operation preview");
+}
+
/** Transitional WebGL consumes the same projected wires; no independent parsing. */
export function conceptWireframeGroup(packet: DisplayPacket): Group {
+ return wireframeGroup(conceptWireframe(packet), "Concept Structs");
+}
+
+function wireframeGroup(wires: TelosLine[], name: string): Group {
const group = new Group();
- group.name = "Concept Structs";
- for (const wire of conceptWireframe(packet).filter(w => !w.id.endsWith(":halo"))) {
+ group.name = name;
+ for (const wire of wires.filter(w => !w.id.endsWith(":halo"))) {
const geometry = new BufferGeometry().setAttribute("position", new Float32BufferAttribute(Array.from(wire.points), 3));
const material = new LineBasicMaterial({ color: "#ffcb45", depthTest: false, depthWrite: false, toneMapped: false });
const line = new Line(geometry, material);
diff --git a/Aetheris.Web.Runtime/telos/tests/concepts.test.ts b/Aetheris.Web.Runtime/telos/tests/concepts.test.ts
index fbdfc97e..8d0d94ba 100644
--- a/Aetheris.Web.Runtime/telos/tests/concepts.test.ts
+++ b/Aetheris.Web.Runtime/telos/tests/concepts.test.ts
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { Matrix4, Vector3 } from "three";
-import { conceptWireframe, conceptWireframeGroup, disposeConceptWireframe } from "../dist/concepts.js";
+import { conceptWireframe, conceptWireframeGroup, disposeConceptWireframe, operationPreviewWireframe, operationPreviewWireframeGroup } from "../dist/concepts.js";
import { TelosPick } from "../dist/pick.js";
import { TelosCamera } from "../dist/camera.js";
import type { DisplayPacket } from "../dist/contracts.js";
@@ -30,3 +30,24 @@ test("gold guides follow occurrences, remain separate from material and never st
assert.equal(group.children.length, 0);
assert.equal(packet.definitions[0].indices.length, 0);
});
+
+test("operation preview uses retained edge polylines and does not replace material or concepts", () => {
+ const packet: DisplayPacket = {
+ definitions: [{ id: "stock", positions: [0,0,0, 1,0,0, 0,1,0], normals: [], indices: [0,1,2],
+ edges: [{ edgeId: "rim", points: [[0,0,0], [1,0,0], [1,1,0]], closed: true }] }],
+ occurrences: [{ id: "placed", definitionId: "stock", semanticEntityId: "stock", transform: new Matrix4().makeTranslation(10,0,0).elements }],
+ };
+ const before = JSON.stringify(packet);
+ const wires = operationPreviewWireframe(packet);
+ assert.equal(wires.length, 2);
+ assert.deepEqual(wires[1].points, [0,0,0, 1,0,0, 1,1,0, 0,0,0]);
+ assert.ok(wires.every(w => w.overlay && w.pickable === false && w.depthMode === "always-on-top"));
+ assert.equal(wires[1].transform![12], 10);
+ assert.equal(conceptWireframe(packet).length, 0);
+ const group = operationPreviewWireframeGroup(packet);
+ assert.equal(group.children.length, 1);
+ assert.equal(group.children[0].matrix.elements[12], 10);
+ disposeConceptWireframe(group);
+ assert.equal(group.children.length, 0);
+ assert.equal(JSON.stringify(packet), before);
+});
diff --git a/docs/development/reports/2026-10/engineering-edge-finish-robustness.md b/docs/development/reports/2026-10/engineering-edge-finish-robustness.md
new file mode 100644
index 00000000..34f382c1
--- /dev/null
+++ b/docs/development/reports/2026-10/engineering-edge-finish-robustness.md
@@ -0,0 +1,144 @@
+# Engineering edge finishes and Helios previews
+
+2026-10-26. Qualification evidence: `artifacts/local/rim-finish/` in Aetheris;
+`artifacts/local/rim-*` and `artifacts/local/graph-authoring/` in HeliosCAD.
+
+## What changed
+
+- Box whole-face Chamfer/Fillet now admits all six principal faces. Bottom and
+ side plans reuse the qualified +Z construction under proper rigid signed
+ permutations. Existing +Z constructions retain their original path.
+- A native-XY, constant-stock Profile can retain disjoint through shaft,
+ counterbore and countersink cavities while finishing either cap. The adapter
+ retains the source-planned cavity graph and analytic surfaces; it does not
+ Boolean-reconstruct the body or replace it with plain stock. Entry footprints
+ must clear the entire rim corridor. Explicit planar-cap loop roles are emitted
+ by the section-stack owner and retained by its materializer.
+- `Boundary` binds to the unique outer stock Profile, including rounded stock and
+ an L-bracket. It does not override an authored Selection named Boundary.
+ Top/Bottom are local cap names; signed world axes must align with the actual
+ extrusion normal. Generic EdgeFinish spelling and field aliases share binding.
+- Removed two stale parser checks that classified non-four-segment Profiles as
+ syntax failures. Geometry admission stays in the owning planner/materializer.
+ Open-chain collision checks and their existing rejection diagnostics remain.
+- Stable cavity identities, correspondence, original source spans and explicit
+ AP242 PMI survive the retained-cavity operation. The new failure path supplies
+ an enclosing EdgeFinish span; presentation can locate a named colliding Hole
+ more precisely.
+- The shared display tessellator now clips cylindrical rolls at their elliptical
+ miter boundaries, including bodies that do not yet carry pcurves. Previously
+ their rectangular UV envelope produced corner spikes. Periodic UV unwrapping
+ uses the existing trimmed-surface owner. Qualification also exposed a fixed
+ 45-degree ellipse sampler that ignored caller tolerances. Ellipse sampling
+ now honors angular/chord and segment budgets, with major radius bounding sag
+ and axis ratio bounding tangent turning. Existing numerical volume checks
+ retain their thresholds. This changes display tessellation,
+ not exact BRep, STEP supports or authored dimensions.
+- Helios rim previews retain the accepted solid and camera and overlay gold
+ candidate boundary polylines. The guides reuse the Concept wireframe style in
+ WebGPU and WebGL, are not selectable, and disappear on Cancel/Apply. They are
+ projected BRep edges, not fabricated Concept declarations. Other feature
+ previews retain their existing behavior. Palette descriptions now say face
+ rim, and the build timer resets at the beginning of each build.
+
+## Reproduction and regression evidence
+
+Plain rounded Profile top/bottom finishes already worked. The failures were the
+native Boundary selector, composed cavities, and Box face restrictions. These
+were not evidence that a general BRep blend engine already existed.
+
+`EngineeringRimFinishTests` exercises twelve Box face/kind combinations, the four
+cap/kind combinations with all three through-hole families and explicit PMI,
+invalid/interfering requests, and the actual live Codex source. It checks the
+selected cap's inset, bounds, exact retained cavity surfaces, stable semantic
+identities, manifold/preflight admission, orientation, analytic rim-volume loss,
+STEP round-trip and validate/build agreement. Five display witnesses failed
+before the elliptical trim fix and pass afterward, on both runtime and imported
+BReps. They check that display vertices on the finished cap do not extend to the
+old sharp corners; a topology count alone would not detect this defect.
+
+The old invalid L-bracket specimen was preserved verbatim and moved to
+`fixtures/Regression/EdgeFinishRobustness/l-bracket-host-boundary-chamfer.firmament`.
+Its test now proves the admitted chamfer's volume. The old CLI -Z rejection case
+now rejects an oversized finish instead; valid bottom finishes are covered by
+the face matrix. Historical closeout manifests retain their original paths and
+outcomes as historical evidence.
+
+Live desktop dogfood used Helios in Edge and the installed Codex app-server
+connection with its ChatGPT subscription. The real task produced a 40 × 30 × 8 mm
+plate with R3 vertical corners, four Ø4 through holes at (±14, ±9), and an R1 top
+rim. Helios applied it, offered Undo AI changes, and exported STEP. Saved source
+compiled independently through CLI to the identical STEP bytes:
+`724A426FDC653387D72BA436991E62CB3C21BBECC22D010D6D5585EC32CC4570`.
+Inspection found one enclosed shell, 34 faces, bounds [-20,-15,0]–[20,15,8],
+24 cylindrical and four toroidal surfaces, and no spline surfaces. The actual
+agent source is retained as `helios-codex-rounded-plate.firmament` in that same
+regression directory. Undo restored the Box. A second real task was cancelled;
+its candidate was not applied and its Codex child process exited. Ordinary graph
+controls also previewed and applied the bottom fillet without editing source.
+Claude and Antigravity live clients were not qualified in this pass.
+
+## Qualification
+
+Geometry-only qualification passed 6,138 tests with two existing drawing skips.
+After the display fix, final qualification passed **6,143 tests across 21 test
+projects**, with the same two skips and no failures. The fast Core lane passed
+1,127 tests. Build succeeded; existing compiler/analyzer warnings remain.
+
+- Focused finish/countersink qualification: 41 passed, including exact support,
+ volume, trim-containment and ellipse chord-budget checks.
+- Helios: 192 unit tests; eight graph browser workflows; six author transaction
+ browser workflows. The graph witness covers gold preview, unchanged source,
+ Cancel disposal and right-face Apply/STEP export. Author client protocol
+ fixtures are explicitly separate from the real Codex subscription run above.
+- Shared Telos: 20 tests, including non-pickable gold operation guides,
+ occurrence transforms, material/source immutability and disposal.
+- SDK development WASM and Helios frontend builds passed. No production AOT
+ bundle or release publication was performed in this pass.
+
+The final frozen CLI under `candidate-qualified-cli` processed all **380
+canonical sources**, retaining **322 validation acceptances, 297 STEP builds
+and all 297 STEP hashes**, with **zero differences** from the pre-pass corpus.
+Results are under `corpus-qualified`; `qualification.json` consolidates the
+gate totals. Expected standalone/module/domain export refusals count as
+outcomes, not broken parts that were made to appear successful.
+
+The final manual desktop recheck of the updated gold preview could not be
+completed: Computer Use stopped because it could not confidently determine the
+current browser URL. No alternate UI automation was used to bypass that stop.
+The automated gold-preview browser witness and its screenshot remain available.
+Earlier live Codex, export, undo, cancellation and bottom-face graph operations
+were observed successfully before that stop. All owned preview/agent hosts were
+stopped. Concurrent Leviathan source edits were left untouched.
+
+Automatic approval review refused deletion of redundant ignored build snapshots.
+`artifacts/local/rim-finish/cleanup-redundant-snapshots.ps1` is a syntax-checked,
+inspection-by-default script for the user to review and run; it archives summary
+JSON and excludes the final snapshot/corpus and original baseline. It has not
+been executed. No user files outside the workspace were removed.
+
+## Deliberate bounds
+
+This is not general edge blending. Multiple sequential Profile finishes remain
+rejected. The new cavity-retention adapter rejects non-native frames, inner
+profile loops, blind holes, slots and additional material operations. Existing
+qualified Compose top-chamfer histories keep their older, broader interval
+planner; open-chain composed fillets still reject after collision diagnosis.
+Combined primitive Box holes/rims remain +Z-only. These boundaries are documented
+in the public fillet guide; no intent is omitted to get plausible geometry.
+
+No new whole-document parser route, source rewrite, diagnostic allowlist,
+arbitrary Boolean surgery or freeform blend fallback was introduced. Existing
+Judgment-based profile planners still select qualified analytic constructions;
+rigid frame mapping and cavity retention are deterministic adapters, not new
+competing geometry engines.
+
+## Verdict
+
+**Success** for the bounded engineering-finish and gold-preview paths qualified
+above. The motivating rounded plate retains its holes and rim in the real
+Helios/Codex build/export workflow; bottom and side finishes are admitted and
+trimmed correctly in the qualified matrix. Existing canonical STEP geometry is
+unchanged. The final manual desktop recheck is explicitly unverified because of
+the computer-use guard; automated browser coverage and its captured gold-preview
+image are available. This is not release-package or arbitrary-blend qualification.
diff --git a/docs/public/firmament/fillet-profiles.md b/docs/public/firmament/fillet-profiles.md
index 2bbb9315..c8446b73 100644
--- a/docs/public/firmament/fillet-profiles.md
+++ b/docs/public/firmament/fillet-profiles.md
@@ -15,6 +15,27 @@ are complete executable examples. [The angled plate](../../../fixtures/Regressio
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.
+On an unmodified `Box`, `face: +X`, `-X`, `+Y`, `-Y`, `+Z` or `-Z` with
+`target: Boundary` selects that face's entire rim. Both Chamfer and Fillet use
+the selected face's dimensions and the depth perpendicular to it when checking
+the finish size. The same size may fit one face but collapse another.
+
+For a Profile extrusion, `target: Boundary` means the stock Profile's single
+outer loop. `on: Top` and `on: Bottom` are relative to its construction plane;
+a signed world axis is also accepted when it is parallel to the extrusion
+axis. A side axis rejects rather than selecting a different cap.
+
+A constant-stock Profile body may retain disjoint through shaft, counterbore
+and countersink holes while finishing either cap. See the complete
+[rounded mounting plate](../../../fixtures/Regression/EdgeFinishRobustness/rounded-plate-through-cavities.firmament).
+This adapter currently requires the native XY stock frame and one outer loop.
+Each hole's largest entry footprint must clear the entire rim corridor by a
+positive margin, including when finishing the bottom. Overlapping cavities,
+blind holes, slots and additional material operations reject in this adapter;
+they are not discarded or rebuilt as plain stock. Other existing materializer
+routes retain their own qualified combinations, including rectangular top
+chamfers over supported Compose histories.
+
The Profile/Compose materializer currently admits one `EdgeFinish` operation
per compiled construction. Requesting multiple finishes, including separate top
and bottom finishes, rejects with `ProfileBoundaryEdgeFinishSequenceUnsupported`.
diff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.md
index 80a5b27b..1dd84760 100644
--- a/docs/public/reference/language/solids-and-features.md
+++ b/docs/public/reference/language/solids-and-features.md
@@ -140,9 +140,9 @@ What you can select depends on the body:
| Body | Selection |
| --- | --- |
-| A Box | `face: +Z` with `target: Boundary`: the top rim |
-| An extruded Profile | `target: section.Outer` with `on: Top` or `on: Bottom`: the whole rim |
-| A Compose body | `target: profile.Outer` with `on: Top`: that Profile's rim, on its own support |
+| An unmodified Box | `face: +X`, `-X`, `+Y`, `-Y`, `+Z` or `-Z` with `target: Boundary`: that face's rim |
+| An extruded Profile | `target: section.Outer` or `Boundary` with `on: Top` or `on: Bottom`: the whole rim |
+| A Compose body | `target: profile.Outer` with `on: Top` or `on: Bottom`, within the qualified material history below |
| An untouched Box or `Polyhedron<N>` | `target: AllEdges`, fillet only: every edge |
The details that trip people up:
@@ -156,7 +156,11 @@ The details that trip people up:
The fillet keeps sharp vertical corners; it is not whole-box rounding.
- **Compose with holes.** A top-rim chamfer can coexist with pockets and holes as
long as its corridor does not cross a counterbore shoulder or countersink
- transition. Fillets on Compose bodies are rejected.
+ transition. One constant-stock Base with disjoint through round holes also
+ supports either cap's fillet or chamfer, including rounded Profile corners.
+ This cavity-retaining path currently requires native XY stock, a single outer
+ loop and positive clearance between each entry footprint and the rim corridor.
+ Blind holes, slots and additional material operations reject in that path.
- **Whole-stock rounding.** `target: AllEdges` needs one fillet, a radius smaller
than the stock's inradius, and no other edits. It rejects on every other body,
including Ellipsoid, RoundedBox, imported, hollow and already-edited stock, and
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 15bf456a..f366d949 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -8,7 +8,7 @@
| Drawing generation | Bounded | Complete nominal PDF/SVG/editable PPTX for rectangular plates/boxes with disjoint Z-through holes: stock/thickness dimensions, coordinate schedule and grouped limits. Explicit reference-only mode for incomplete PMI views; no process-capability or manufacturing-release claim. Authored Assembly drawings remain available. See [drawings](../drawings.md). |
| Uniform stock fillet | Bounded | `EdgeFinish<Fillet> { target: AllEdges; radius: ... }` on untouched Box or regular Polyhedron stock; all edge/corner patches together. Arbitrary bodies and mixed edits reject. |
| 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). |
+| Box face rim | Bounded | A whole-face Boundary chamfer or fillet on any principal face of unmodified Box stock. One complete +Z rim can also retain disjoint ThroughAll shaft/counterbore/countersink holes. Intersecting holes/finish bands, other combined selectors and general feature chains remain unsupported. Constant native-XY Profile stock with disjoint through round holes supports either cap's rim, including rounded corners. See [fillets and chamfers](../firmament/fillet-profiles.md). |
| 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). |
| Scene spatial composition | Supported / bounded | Metre/mm coordinates; rectangular Room boundaries; Door/Window apertures; independent AssemblyFile and typed Part occurrences; keyed patterns; retained definition reuse; cameras and appearances; USD/GLB. No Scene mechanical relationships, nested Scenes, whole-scene STEP or BIM. See [scenes](../firmament/scenes.md). |
diff --git a/fixtures/Regression/EdgeFinishRobustness/helios-codex-rounded-plate.firmament b/fixtures/Regression/EdgeFinishRobustness/helios-codex-rounded-plate.firmament
new file mode 100644
index 00000000..b8453014
--- /dev/null
+++ b/fixtures/Regression/EdgeFinishRobustness/helios-codex-rounded-plate.firmament
@@ -0,0 +1,28 @@
+Model Untitled {
+ Units: mm
+
+ Profile Outline = RoundedRect2 {
+ Center: [0mm, 0mm]
+ Size: [40mm, 30mm]
+ Radius: 3mm
+ }
+ Extrude Body { Profile: Outline; From: 0mm; To: 8mm }
+
+ Modify Body {
+ Hole<Shaft> MountLeftFront {
+ On: +Z; Center: Point2(-14mm, -9mm); Diameter: 4mm; End: ThroughAll
+ }
+ Hole<Shaft> MountRightFront {
+ On: +Z; Center: Point2(14mm, -9mm); Diameter: 4mm; End: ThroughAll
+ }
+ Hole<Shaft> MountLeftRear {
+ On: +Z; Center: Point2(-14mm, 9mm); Diameter: 4mm; End: ThroughAll
+ }
+ Hole<Shaft> MountRightRear {
+ On: +Z; Center: Point2(14mm, 9mm); Diameter: 4mm; End: ThroughAll
+ }
+ EdgeFinish TopRim {
+ Face: +Z; Target: Boundary; Kind: Fillet; Radius: 1mm
+ }
+ }
+}
diff --git a/fixtures/Invalid/Geometry/profile-compose-l-bracket-edgefinish-unsupported.firmament b/fixtures/Regression/EdgeFinishRobustness/l-bracket-host-boundary-chamfer.firmament
similarity index 100%
rename from fixtures/Invalid/Geometry/profile-compose-l-bracket-edgefinish-unsupported.firmament
rename to fixtures/Regression/EdgeFinishRobustness/l-bracket-host-boundary-chamfer.firmament
diff --git a/fixtures/Regression/EdgeFinishRobustness/rounded-plate-through-cavities.firmament b/fixtures/Regression/EdgeFinishRobustness/rounded-plate-through-cavities.firmament
new file mode 100644
index 00000000..47dc96be
--- /dev/null
+++ b/fixtures/Regression/EdgeFinishRobustness/rounded-plate-through-cavities.firmament
@@ -0,0 +1,20 @@
+Model RoundedMountingPlate {
+ units: mm
+ Concept Struct Layout on XY {
+ RoundedRect2 Stock { center: [0mm, 0mm]; size: [60mm, 40mm]; radius: 6mm }
+ }
+ Profile Outline using Layout { Loop Outer { Stock |> TraceLoop } }
+ Struct Part { Extrude Body { profile: Outline; from: 0mm; to: 8mm } }
+ Modify Body {
+ Hole<Shaft> Plain { on: +Z; center: Point2(-15mm, 0mm); diameter: 4mm; end: ThroughAll }
+ Hole<Counterbore> Bore { on: +Z; center: Point2(0mm, 0mm); diameter: 3mm; counterboreDiameter: 8mm; counterboreDepth: 2mm; end: ThroughAll }
+ Hole<Countersink> Sink { on: +Z; center: Point2(15mm, 0mm); diameter: 4mm; countersinkDiameter: 8mm; countersinkAngle: 90deg; end: ThroughAll }
+ EdgeFinish<Fillet> Rim { target: Boundary; on: +Z; radius: 1mm }
+ }
+ Pmi {
+ Datum A { target: face(+Z) }
+ HoleDiameter PlainDiameter { target: Plain; value: 4mm; tolerance: PlusMinus(0.1mm, 0mm) }
+ HoleDiameter BoreDiameter { target: Bore; value: 3mm; tolerance: PlusMinus(0.1mm, 0mm) }
+ HoleDiameter SinkDiameter { target: Sink; value: 4mm; tolerance: PlusMinus(0.1mm, 0mm) }
+ }
+}