Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Uniform rounding: fillet every edge of a convex planar body, routed from AllEdges

Claude8169beb6442e
diff --git a/Aetheris.CLI.Tests/ConvexStockCliTests.cs b/Aetheris.CLI.Tests/ConvexStockCliTests.cs
index cbc8f5bc..2399adb6 100644
--- a/Aetheris.CLI.Tests/ConvexStockCliTests.cs
+++ b/Aetheris.CLI.Tests/ConvexStockCliTests.cs
@@ -42,14 +42,14 @@ public sealed class ConvexStockCliTests
[InlineData("Polyhedron<10> stock { edgeLength: 20mm }", "", "polyhedron-face-count-unsupported")]
[InlineData("Polyhedron<6> stock { edgeLength: 20 }", "", "field-value-invalid")]
[InlineData("Ellipsoid stock { radii: [18mm, 0mm, 25mm] }", "", "ellipsoid-radii-invalid")]
- [InlineData("Cylinder stock { radius: 10mm; height: 20mm }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm }", "uniform-stock-fillet-unsupported")]
- [InlineData("Ellipsoid stock { radii: [18mm, 12mm, 25mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm }", "uniform-stock-fillet-unsupported")]
+ [InlineData("Cylinder stock { radius: 10mm; height: 20mm }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm }", "uniform-rounding-circular-edge-unsupported")]
+ [InlineData("Ellipsoid stock { radii: [18mm, 12mm, 25mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm }", "uniform-rounding-elliptical-edge-unsupported")]
[InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 10mm }", "UniformFilletRadiusTooLarge")]
[InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; face: [1, 2]; radius: 1mm }", "field-value-invalid")]
[InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; kind: 9; radius: 1mm }", "field-value-invalid")]
[InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; distance: 1mm }", "field-value-invalid")]
[InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Chamfer> rounding { target: AllEdges; distance: 1mm }", "uniform-stock-fillet-unsupported")]
- [InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm } Hole<Shaft> H { on: +Z; center: [0mm, 0mm]; diameter: 2mm; end: ThroughAll }", "uniform-stock-fillet-unsupported")]
+ [InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm } Hole<Shaft> H { on: +Z; center: [0mm, 0mm]; diameter: 2mm; end: ThroughAll }", "uniform-rounding-circular-edge-unsupported")]
public void UnsupportedAndInvalidIntentCannotProduceAnArtifact(string stock, string operation, string code)
{
var source = "Model Rejected {\n units: mm\n " + stock + "\n" + (operation.Length == 0 ? "" : " Modify stock {\n " + operation + "\n }\n") + "}";
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Blends/UniformRoundingTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Blends/UniformRoundingTests.cs
new file mode 100644
index 00000000..2f4318af
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/Blends/UniformRoundingTests.cs
@@ -0,0 +1,140 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Blends;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Tests.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.Blends;
+
+/// <summary>"Fillet everything" as an opening: erode by the radius, sweep the ball back. Checked against the
+/// dedicated regular-stock builder, and read back by the rolling-ball certificate.</summary>
+public sealed class UniformRoundingTests
+{
+ [Theory]
+ [InlineData(4)]
+ [InlineData(6)]
+ [InlineData(8)]
+ [InlineData(12)]
+ [InlineData(20)]
+ public void RegularSolids_MatchTheDedicatedBuilder(int faces)
+ {
+ const double radius = 2;
+ var rounded = UniformRounding.RoundAllEdges(ConvexStockPrimitives.CreateRegular(faces, 30).Value, radius);
+ Assert.True(rounded.IsSuccess, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));
+ var expected = ConvexStockPrimitives.CreateRegular(faces, 30, radius).Value;
+ AssertSameSolid(expected, rounded.Value);
+ }
+
+ [Fact]
+ public void Box_MatchesTheRoundedBox()
+ {
+ var rounded = UniformRounding.RoundAllEdges(ConvexStockPrimitives.CreateHull(BoxCorners(40, 30, 20)).Value, 3);
+ Assert.True(rounded.IsSuccess, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));
+ AssertSameSolid(ConvexStockPrimitives.CreateRoundedBox(40, 30, 20, 3).Value, rounded.Value);
+ }
+
+ /// <summary>A square pyramid's apex has four faces: the eroded planes meet there only by the pyramid's symmetry
+ /// in general, so the erosion is the half-spaces' intersection, not three planes per vertex. The rounded result
+ /// reads back, by the certificate alone, as one strip per edge at the radius and one corner per vertex.</summary>
+ [Fact]
+ public void SquarePyramid_EveryEdgeAStripEveryVertexACorner()
+ {
+ var pyramid = ConvexStockPrimitives.CreateHull([new(-10, -10, 0), new(10, -10, 0), new(10, 10, 0), new(-10, 10, 0), new(0, 0, 12)]).Value;
+ Assert.Equal(5, pyramid.Topology.Faces.Count());
+ var rounded = UniformRounding.RoundAllEdges(pyramid, 1.5);
+ Assert.True(rounded.IsSuccess, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));
+ AssertReadsBack(rounded.Value, faces: 5, edges: 8, vertices: 5, radius: 1.5);
+ Assert.True(BrepMassProperties.Evaluate(rounded.Value).AbsoluteVolume < BrepMassProperties.Evaluate(pyramid).AbsoluteVolume);
+ }
+
+ /// <summary>A prism cut by a skewed plane: no symmetry, unequal dihedral angles, three faces at every vertex, so
+ /// the erosion keeps the body's structure and the rounding has one strip per edge and one corner per vertex.</summary>
+ [Fact]
+ public void SkewCutPrism_EveryEdgeAStripEveryVertexACorner()
+ {
+ Point3D[] bottom = [new(0, 0, 0), new(24, 0, 0), new(28, 14, 0), new(6, 17, 0)];
+ double Top(Point3D p) => 10 + 0.25 * p.X + 0.15 * p.Y;
+ var hull = ConvexStockPrimitives.CreateHull([.. bottom, .. bottom.Select(p => new Point3D(p.X, p.Y, Top(p)))]).Value;
+ var plain = hull.Topology;
+ Assert.All(plain.Vertices, v => Assert.Equal(3, plain.Edges.Count(e => e.StartVertexId == v.Id || e.EndVertexId == v.Id)));
+ var rounded = UniformRounding.RoundAllEdges(hull, 1);
+ Assert.True(rounded.IsSuccess, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));
+ AssertReadsBack(rounded.Value, plain.Faces.Count(), plain.Edges.Count(), plain.Vertices.Count(), 1);
+ }
+
+ /// <summary>Where four or more faces meet without symmetry, the faces moved in by the radius do not meet at one
+ /// point: the vertex opens into short edges, each its own strip. That is what a ball rolled over the body does.</summary>
+ [Fact]
+ public void IrregularHighValenceVertices_OpenIntoShortStrips()
+ {
+ var hull = ConvexStockPrimitives.CreateHull([new(0, 0, 0), new(30, 0, 0), new(26, 18, 0), new(3, 15, 0), new(4, 3, 9), new(22, 2, 11), new(19, 13, 8)]).Value;
+ Assert.Contains(hull.Topology.Vertices, v => hull.Topology.Edges.Count(e => e.StartVertexId == v.Id || e.EndVertexId == v.Id) > 3);
+ var rounded = UniformRounding.RoundAllEdges(hull, 1);
+ Assert.True(rounded.IsSuccess, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));
+ var body = rounded.Value;
+ int Count(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind kind) => body.Topology.Faces.Count(f => body.TryGetFaceSurfaceGeometry(f.Id, out var g) && g!.Kind == kind);
+ Assert.True(Count(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Cylinder) > hull.Topology.Edges.Count());
+ AssertReadsBack(body, hull.Topology.Faces.Count(), Count(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Cylinder), Count(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Sphere), 1);
+ }
+
+ [Fact]
+ public void RadiusTooLarge_RefusesNamingTheLargestThatKeepsEveryFace()
+ {
+ var pyramid = ConvexStockPrimitives.CreateHull([new(-10, -10, 0), new(10, -10, 0), new(10, 10, 0), new(-10, 10, 0), new(0, 0, 12)]).Value;
+ var refused = UniformRounding.RoundAllEdges(pyramid, 50);
+ Assert.False(refused.IsSuccess);
+ var message = refused.Diagnostics.Single().Message;
+ var fit = double.Parse(System.Text.RegularExpressions.Regex.Match(message, @"(?:keeps every face is|fits is under) ([0-9.Ee+-]+) mm").Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
+ Assert.True(fit > 0 && fit < 12, message);
+ Assert.True(UniformRounding.RoundAllEdges(pyramid, fit * 0.99).IsSuccess, $"{fit * 0.99} should fit: {message}");
+ Assert.False(UniformRounding.RoundAllEdges(pyramid, fit * 1.01).IsSuccess);
+ }
+
+ [Fact]
+ public void SplineAndEllipticalEdges_RefuseByName()
+ {
+ // Fusion's SO-101 export has both.
+ var refused = UniformRounding.RoundAllEdges(Step242Corpus.Body("testdata/step242/community/so101/Under_arm_SO101.step"), 1);
+ Assert.False(refused.IsSuccess);
+ var message = refused.Diagnostics.Single().Message;
+ Assert.StartsWith("uniform-rounding-spline-edge-unsupported", message);
+ Assert.Contains("does not support spline or elliptical edges", message);
+ Assert.Contains("spline", message);
+ Assert.Contains("elliptical", message);
+ }
+
+ [Fact]
+ public void CircularEdges_RefuseByName()
+ {
+ var refused = UniformRounding.RoundAllEdges(BrepPrimitives.CreateCylinder(10, 20).Value, 1);
+ Assert.StartsWith("uniform-rounding-circular-edge-unsupported", refused.Diagnostics.Single().Message);
+ }
+
+ private static Point3D[] BoxCorners(double x, double y, double z) =>
+ [.. from a in new[] { -1, 1 } from b in new[] { -1, 1 } from c in new[] { -1, 1 } select new Point3D(a * x / 2, b * y / 2, c * z / 2)];
+
+ private static void AssertReadsBack(BrepBody body, int faces, int edges, int vertices, double radius)
+ {
+ Assert.True(BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true).IsSuccess);
+ var read = BlendRecognition.Recognize(body);
+ var strips = read.Where(r => r.Role == BlendFaceRole.Strip).ToArray();
+ Assert.Equal(edges, strips.Length);
+ Assert.All(strips, s => { Assert.Equal(radius, s.Blend!.Size, 9); Assert.True(s.Blend.Hypothesis.Convex); });
+ Assert.Equal(vertices, read.Count(r => r.Role == BlendFaceRole.Joiner));
+ Assert.Equal(faces, read.Count(r => r.Role == BlendFaceRole.Primary));
+ }
+
+ private static void AssertSameSolid(BrepBody expected, BrepBody actual)
+ {
+ Assert.True(BrepBindingValidator.Validate(actual, requireAllEdgeAndFaceBindings: true).IsSuccess);
+ Assert.Equal(expected.Topology.Faces.Count(), actual.Topology.Faces.Count());
+ Assert.Equal(expected.Topology.Edges.Count(), actual.Topology.Edges.Count());
+ Assert.Equal(expected.Topology.Vertices.Count(), actual.Topology.Vertices.Count());
+ Assert.Equal(Points(expected), Points(actual));
+ Assert.Equal(BrepMassProperties.Evaluate(expected).AbsoluteVolume, BrepMassProperties.Evaluate(actual).AbsoluteVolume, 6);
+ }
+
+ private static string[] Points(BrepBody body) => body.Topology.Vertices
+ .Select(v => { body.TryGetVertexPoint(v.Id, out var p); return $"{double.Round(p.X, 6) + 0.0:F6},{double.Round(p.Y, 6) + 0.0:F6},{double.Round(p.Z, 6) + 0.0:F6}"; })
+ .Order(StringComparer.Ordinal).ToArray();
+}
diff --git a/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs b/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs
new file mode 100644
index 00000000..424d84e4
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs
@@ -0,0 +1,144 @@
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep.Blends;
+
+/// <summary>
+/// "Fillet everything": one constant radius on every edge of a body. Rounding a convex body's edges with a ball is
+/// a morphological opening (erode by the radius, then sweep the ball over what is left), so it has one answer,
+/// with no corner cases to choose: corners come out as sphere patches by construction, whatever their valence.
+/// Built exactly from the erosion (the faces' planes moved in by the radius) by
+/// <see cref="ConvexStockPrimitives"/>' ball sweep. Admits convex bodies bounded by planes; everything else is
+/// refused with what it found and where, and a radius that does not fit is refused with the largest that does.
+/// </summary>
+public static class UniformRounding
+{
+ public const string Source = "UniformRounding";
+
+ public static KernelResult<BrepBody> RoundAllEdges(BrepBody body, double radius)
+ {
+ ArgumentNullException.ThrowIfNull(body);
+ if (!double.IsFinite(radius) || radius <= 0) return Failure("uniform-rounding-radius-invalid", "radius must be finite and positive");
+
+ // Edges first, so the message names what the body is made of, not only that a face is curved. Spline and
+ // elliptical edges are named before circles: they are the ones this construction has no plan for yet.
+ var curved = body.Topology.Edges.OrderBy(e => e.Id.Value)
+ .Select(e => (Edge: e.Id, Kind: body.Bindings.TryGetEdgeBinding(e.Id, out var b) && body.Geometry.TryGetCurve(b.CurveGeometryId, out var c) && c is not null ? c.Kind : (CurveGeometryKind?)null))
+ .Where(x => x.Kind is not null && x.Kind != CurveGeometryKind.Line3).ToArray();
+ string Some(CurveGeometryKind kind, string adjective)
+ {
+ var ids = curved.Where(x => x.Kind == kind).Select(x => x.Edge.Value).ToArray();
+ return $"{ids.Length} {adjective} edge{(ids.Length == 1 ? "" : "s")} ({string.Join(", ", ids.Take(5))}{(ids.Length > 5 ? ", ..." : "")})";
+ }
+ var splines = curved.Any(x => x.Kind == CurveGeometryKind.BSpline3);
+ var ellipses = curved.Any(x => x.Kind == CurveGeometryKind.Ellipse3);
+ if (splines || ellipses)
+ return Failure(splines ? "uniform-rounding-spline-edge-unsupported" : "uniform-rounding-elliptical-edge-unsupported",
+ "rounding every edge does not support spline or elliptical edges yet: this body has "
+ + string.Join(" and ", new[] { splines ? Some(CurveGeometryKind.BSpline3, "spline") : null, ellipses ? Some(CurveGeometryKind.Ellipse3, "elliptical") : null }.Where(x => x is not null))
+ + ". Round a body bounded by planes, or finish those edges with a local EdgeFinish");
+ if (curved.Any(x => x.Kind == CurveGeometryKind.Circle3))
+ return Failure("uniform-rounding-circular-edge-unsupported", $"rounding every edge does not support circular edges yet: this body has {Some(CurveGeometryKind.Circle3, "circular")}. Bodies bounded by planes only for now");
+ if (curved.Length > 0)
+ return Failure("uniform-rounding-curved-edge-unsupported", $"rounding every edge does not support {curved[0].Kind} edges (edge {curved[0].Edge.Value}); bodies bounded by planes only for now");
+ var planes = new List<(FaceId Face, Vector3D Normal, double Offset)>();
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : throw new InvalidOperationException($"vertex {v.Id.Value} has no point")).ToArray();
+ var extent = points.Max(p => (p - Point3D.Origin).Length);
+ var tolerance = double.Max(1e-9, (extent + 1) * 1e-10) * 1e3;
+ var centroid = Point3D.Origin + points.Aggregate(Vector3D.Zero, (s, p) => s + (p - Point3D.Origin)) * (1d / points.Length);
+ foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value))
+ {
+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var surface) || surface?.Plane is not { } plane)
+ return Failure("uniform-rounding-curved-face-unsupported", $"rounding every edge needs a body bounded by planes for now; face {face.Id.Value} is {surface?.Kind.ToString() ?? "unbound"}");
+ var n = plane.Normal.ToVector();
+ if (n.Dot(plane.Origin - centroid) < 0) n = n * -1;
+ planes.Add((face.Id, n, n.Dot(plane.Origin - Point3D.Origin)));
+ }
+ // Convex: every vertex on the inner side of every face. A vertex outside names a concave edge's region.
+ foreach (var (face, n, d) in planes)
+ {
+ var outside = points.Select((p, i) => (Point: p, Index: i)).Where(x => n.Dot(x.Point - Point3D.Origin) > d + tolerance).ToArray();
+ if (outside.Length > 0)
+ return Failure("uniform-rounding-concave-unsupported", $"rounding every edge supports convex bodies only for now: the body reaches {outside.Max(x => n.Dot(x.Point - Point3D.Origin) - d):G4} mm beyond face {face.Value}'s plane, so it has a concave edge (closing concave edges with the ball is not built yet)");
+ }
+
+ var eroded = Erode(planes, radius, tolerance);
+ if (eroded is null || !FullDimensional(eroded, tolerance))
+ return Failure("uniform-rounding-radius-too-large", $"radius {radius:G6} mm leaves nothing of the body to round (the largest that fits is under {Largest(planes, tolerance, keepEveryFace: false, radius):G6} mm)");
+ var kept = KeptFaces(planes, eroded, radius, tolerance);
+ var distinct = Distinct(planes).Length;
+ if (kept < distinct)
+ return Failure("uniform-rounding-radius-consumes-faces", $"radius {radius:G6} mm consumes {distinct - kept} face(s) of the body whole; the largest radius that keeps every face is {Largest(planes, tolerance, keepEveryFace: true, radius):G6} mm");
+ var swept = ConvexStockPrimitives.Dilate(eroded, radius);
+ return swept.IsSuccess ? swept : KernelResult<BrepBody>.Failure(swept.Diagnostics);
+ }
+
+ /// <summary>The vertices of the faces' planes moved in by the radius: their half-spaces' intersection.</summary>
+ private static Point3D[]? Erode(IReadOnlyList<(FaceId Face, Vector3D Normal, double Offset)> planes, double radius, double tolerance)
+ {
+ var found = new List<Point3D>();
+ for (var i = 0; i < planes.Count; i++)
+ for (var j = i + 1; j < planes.Count; j++)
+ for (var k = j + 1; k < planes.Count; k++)
+ {
+ var (a, b, c) = (planes[i], planes[j], planes[k]);
+ var det = a.Normal.Dot(b.Normal.Cross(c.Normal));
+ if (double.Abs(det) < 1e-12) continue;
+ var p = Point3D.Origin + (b.Normal.Cross(c.Normal) * (a.Offset - radius) + c.Normal.Cross(a.Normal) * (b.Offset - radius) + a.Normal.Cross(b.Normal) * (c.Offset - radius)) * (1 / det);
+ if (planes.All(q => q.Normal.Dot(p - Point3D.Origin) <= q.Offset - radius + tolerance) && found.All(f => (f - p).Length > tolerance))
+ found.Add(p);
+ }
+ return found.Count == 0 ? null : found.ToArray();
+ }
+
+ private static bool FullDimensional(Point3D[] points, double tolerance)
+ {
+ if (points.Length < 4) return false;
+ var o = points[0];
+ var far = points.MaxBy(p => (p - o).Length);
+ var line = far - o;
+ if (line.Length <= tolerance) return false;
+ var off = points.MaxBy(p => line.Cross(p - o).Length);
+ var normal = line.Cross(off - o);
+ if (normal.Length <= tolerance * line.Length) return false;
+ return points.Any(p => double.Abs(normal.Dot(p - o)) / normal.Length > tolerance);
+ }
+
+ /// <summary>How many distinct planes still bound the eroded body with an area (three non-collinear of its
+ /// vertices on the plane moved in by the radius).</summary>
+ private static int KeptFaces(IReadOnlyList<(FaceId Face, Vector3D Normal, double Offset)> planes, Point3D[] eroded, double radius, double tolerance) =>
+ Distinct(planes).Count(p => FaceHasArea(eroded.Where(x => double.Abs(p.Normal.Dot(x - Point3D.Origin) - (p.Offset - radius)) <= tolerance).ToArray(), tolerance));
+
+ private static (FaceId Face, Vector3D Normal, double Offset)[] Distinct(IReadOnlyList<(FaceId Face, Vector3D Normal, double Offset)> planes) =>
+ planes.GroupBy(p => (double.Round(p.Normal.X, 9), double.Round(p.Normal.Y, 9), double.Round(p.Normal.Z, 9), double.Round(p.Offset, 6))).Select(g => g.First()).ToArray();
+
+ private static bool FaceHasArea(Point3D[] onFace, double tolerance)
+ {
+ if (onFace.Length < 3) return false;
+ var o = onFace[0];
+ var far = onFace.MaxBy(p => (p - o).Length);
+ return onFace.Any(p => (far - o).Cross(p - o).Length > tolerance * double.Max(1, (far - o).Length));
+ }
+
+ /// <summary>The largest radius that leaves the body something to round (or keeps every face), by bisection:
+ /// erosion only shrinks as the radius grows, so both conditions are monotone.</summary>
+ private static double Largest(IReadOnlyList<(FaceId Face, Vector3D Normal, double Offset)> planes, double tolerance, bool keepEveryFace, double above)
+ {
+ var faces = Distinct(planes).Length;
+ bool Fits(double r)
+ {
+ var e = Erode(planes, r, tolerance);
+ if (e is null || !FullDimensional(e, tolerance)) return false;
+ return !keepEveryFace || KeptFaces(planes, e, r, tolerance) >= faces;
+ }
+ var (lo, hi) = (0d, above);
+ for (var i = 0; i < 60; i++) { var mid = 0.5 * (lo + hi); if (Fits(mid)) lo = mid; else hi = mid; }
+ return lo;
+ }
+
+ private static KernelResult<BrepBody> Failure(string code, string message) => KernelResult<BrepBody>.Failure([
+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, $"{code}: {message}", Source)]);
+}
diff --git a/Aetheris.Kernel.Core/Brep/ConvexStockPrimitives.cs b/Aetheris.Kernel.Core/Brep/ConvexStockPrimitives.cs
index 179c6662..44163fc7 100644
--- a/Aetheris.Kernel.Core/Brep/ConvexStockPrimitives.cs
+++ b/Aetheris.Kernel.Core/Brep/ConvexStockPrimitives.cs
@@ -48,6 +48,21 @@ public static class ConvexStockPrimitives
return Build(vertices.Select(p => new Point3D(p.X * scale, p.Y * scale, p.Z * scale)).ToArray(), filletRadius, faceCount);
}
+ /// <summary>The convex hull of the points as a solid bounded by planes (coplanar points share one face).</summary>
+ public static KernelResult<BrepBody> CreateHull(IReadOnlyList<Point3D> points)
+ {
+ ArgumentNullException.ThrowIfNull(points);
+ if (points.Count < 4) return Failure("ConvexHullInvalid: a solid hull needs at least four points.");
+ var extent = points.Max(p => (p - Point3D.Origin).Length);
+ var tolerance = System.Math.Max(1e-9, extent * 1e-10);
+ var local = points.ToArray();
+ var faces = Hull(local, tolerance);
+ if (faces.Count < 4) return Failure("ConvexHullInvalid: the points do not span a solid.");
+ var used = faces.SelectMany(f => f.Vertices).Distinct().Order().ToArray();
+ if (used.Length != local.Length) return Failure("ConvexHullInvalid: some points are inside the hull; give its corners only.");
+ return Sweep(faces, local, 0);
+ }
+
/// <summary>Kernel-centered Box; Firmament applies its existing bottom-on-XY stock frame.</summary>
public static KernelResult<BrepBody> CreateRoundedBox(double x, double y, double z, double radius)
{
@@ -75,6 +90,30 @@ public static class ConvexStockPrimitives
return Failure(FormattableString.Invariant($"UniformFilletRadiusTooLarge: radius {radius:R}mm must be smaller than the stock inradius {limit:R}mm, leaving positive planar faces and edge spans."));
if (radius > 0 && radius <= tolerance) return Failure("UniformFilletRadiusInvalid: radius is below the stock construction tolerance.");
+ var incident = Enumerable.Range(0, points.Count).Select(v => Enumerable.Range(0, faces.Count).Where(f => faces[f].Vertices.Contains(v)).ToArray()).ToArray();
+ var inner = radius == 0 ? points.ToArray() : Enumerable.Range(0, points.Count).Select(v => OffsetVertex(incident[v], faces, radius)).ToArray();
+ if (inner.Any(p => !double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z)))
+ return Failure("ConvexStockOffsetInvalid: the stock's incident planes do not have a finite common inward offset.");
+ return Sweep(faces, inner, radius);
+ }
+
+ /// <summary>
+ /// The ball swept over an eroded convex hull, as a BRep: every hull face carried out by the radius (a plane),
+ /// every hull edge a cylinder, every hull vertex a sphere patch with one side per incident face. Exact, with
+ /// no surface intersection. <paramref name="eroded"/> is the hull already moved in by the radius.
+ /// </summary>
+ internal static KernelResult<BrepBody> Dilate(IReadOnlyList<Point3D> eroded, double radius)
+ {
+ if (!Positive(radius)) return Failure("UniformFilletRadiusInvalid: radius must be finite and positive.");
+ var extent = eroded.Max(p => (p - Point3D.Origin).Length);
+ var tolerance = System.Math.Max(1e-9, extent * 1e-10);
+ var faces = Hull(eroded, tolerance);
+ if (faces.Count < 4) return Failure("ConvexStockHullInvalid: the eroded stock has no volume.");
+ return Sweep(faces, eroded.ToArray(), radius);
+ }
+
+ private static KernelResult<BrepBody> Sweep(List<StockFace> faces, Point3D[] inner, double radius)
+ {
var builder = new TopologyBuilder();
var geometry = new BrepGeometryStore();
var bindings = new BrepBindingModel();
@@ -83,10 +122,7 @@ public static class ConvexStockPrimitives
var contact = new Dictionary<(int Vertex, int Face), VertexId>();
var lines = new Dictionary<(int A, int B, int Face), EdgeId>();
var arcs = new Dictionary<(int Vertex, int A, int B), EdgeId>();
- var incident = Enumerable.Range(0, points.Count).Select(v => Enumerable.Range(0, faces.Count).Where(f => faces[f].Vertices.Contains(v)).ToArray()).ToArray();
- var inner = radius == 0 ? points.ToArray() : Enumerable.Range(0, points.Count).Select(v => OffsetVertex(incident[v], faces, radius)).ToArray();
- if (inner.Any(p => !double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z)))
- return Failure("ConvexStockOffsetInvalid: the stock's incident planes do not have a finite common inward offset.");
+ var incident = Enumerable.Range(0, inner.Length).Select(v => Enumerable.Range(0, faces.Count).Where(f => faces[f].Vertices.Contains(v)).ToArray()).ToArray();
VertexId Vertex(int v, int f)
{
@@ -140,9 +176,9 @@ public static class ConvexStockPrimitives
}
for (var f = 0; f < faces.Count; f++)
{
- var face = faces[f]; var n = Direction3D.Create(face.Normal); var x = Direction3D.Create(points[face.Vertices[1]] - points[face.Vertices[0]]);
+ var face = faces[f]; var n = Direction3D.Create(face.Normal); var x = Direction3D.Create(inner[face.Vertices[1]] - inner[face.Vertices[0]]);
Face(face.Vertices.Select((v, i) => Line(v, face.Vertices[(i + 1) % face.Vertices.Length], f)).ToArray(),
- SurfaceGeometry.FromPlane(new(points[face.Vertices[0]], n, x)), face.Normal);
+ SurfaceGeometry.FromPlane(new(inner[face.Vertices[0]] + face.Normal * radius, n, x)), face.Normal);
}
if (radius > 0)
{
@@ -157,8 +193,9 @@ public static class ConvexStockPrimitives
Face([Line(edge.A, edge.B, a), Arc(edge.B, a, b), Line(edge.B, edge.A, b), Arc(edge.A, b, a)],
SurfaceGeometry.FromCylinder(new(inner[edge.A], Direction3D.Create(inner[edge.B] - inner[edge.A]), radius, Direction3D.Create(faces[a].Normal))), normal);
}
- for (var v = 0; v < points.Count; v++)
+ for (var v = 0; v < inner.Length; v++)
{
+ if (incident[v].Length == 0) continue;
var normal = incident[v].Aggregate(Vector3D.Zero, (n, f) => n + faces[f].Normal);
var axis = Direction3D.Create(normal); var x = Tangent(axis.ToVector()); var y = axis.ToVector().Cross(x);
var ordered = incident[v].OrderBy(f => double.Atan2(faces[f].Normal.Dot(y), faces[f].Normal.Dot(x))).ToArray();
@@ -180,12 +217,15 @@ public static class ConvexStockPrimitives
var cross = (points[b] - points[a]).Cross(points[c] - points[a]);
if (cross.Length <= tolerance * tolerance) continue;
var normal = cross * (1 / cross.Length); var d = normal.Dot(points[a] - Point3D.Origin);
- if (d < 0) { normal *= -1; d *= -1; }
- if (d <= tolerance || points.Any(p => normal.Dot(p - Point3D.Origin) > d + tolerance)) continue;
+ // Outward: every point on the inner side. Independent of where the origin is.
+ if (points.Any(p => normal.Dot(p - Point3D.Origin) > d + tolerance)) { normal *= -1; d *= -1; }
+ if (points.Any(p => normal.Dot(p - Point3D.Origin) > d + tolerance)) continue;
var coplanar = Enumerable.Range(0, points.Count).Where(i => double.Abs(normal.Dot(points[i] - Point3D.Origin) - d) <= tolerance).ToArray();
var key = string.Join(',', coplanar); if (found.ContainsKey(key)) continue;
var x = Tangent(normal); var y = normal.Cross(x);
- var ordered = coplanar.OrderBy(i => double.Atan2((points[i] - Point3D.Origin).Dot(y), (points[i] - Point3D.Origin).Dot(x))).ToArray();
+ // Around the face's own centre: the origin's projection need not be inside the face.
+ var centre = coplanar.Aggregate(Vector3D.Zero, (sum, i) => sum + (points[i] - Point3D.Origin)) * (1d / coplanar.Length);
+ var ordered = coplanar.OrderBy(i => double.Atan2((points[i] - Point3D.Origin - centre).Dot(y), (points[i] - Point3D.Origin - centre).Dot(x))).ToArray();
found.Add(key, new(ordered, normal, d));
}
return found.OrderBy(k => k.Key, StringComparer.Ordinal).Select(k => k.Value).ToList();
diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs
index 34e9994a..308435dd 100644
--- a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs
@@ -140,6 +140,26 @@ public sealed class BlendNetworkRemovalTests(ITestOutputHelper output)
Assert.Equal(Points(plain), Points(reimported.Value));
}
+ /// <summary>The two toolboxes undo each other: an extruded prism rounded whole through Firmament, then every
+ /// strip and corner removed, is the prism again.</summary>
+ [Fact]
+ public void RemovingWholeBodyRounding_ReturnsThePrism()
+ {
+ var source = Integration.UniformRoundingRouteTests.Prism(2);
+ var finished = Import(source);
+ var plain = Import(Regex.Replace(source, @"Modify Body \{\s*EdgeFinish[^{}]*\{[^{}]*\}\s*\}", ""));
+ Assert.Equal((5, 20), (plain.Topology.Faces.Count(), finished.Topology.Faces.Count()));
+ var probe = BlendRegionProbe.Run("rounded-prism", finished);
+ var blends = probe.Regions.SelectMany(r => r.Faces).Select(f => new FaceId(f)).ToHashSet();
+ Assert.Equal(15, blends.Count);
+ var removed = BlendNetworkRemoval.Remove(finished, blends, Anchors(probe));
+ Assert.True(removed.Body is not null, removed.Refusal);
+ var body = removed.Body!;
+ Assert.True(BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true).IsSuccess);
+ Assert.Equal(plain.Topology.Edges.Count(), body.Topology.Edges.Count());
+ Assert.Equal(Points(plain), Points(body));
+ }
+
/// <summary>E3: rounded convex solids lose every fillet and corner patch (3- to 5-valent corners).</summary>
[Theory]
[InlineData("box-rounded", "")]
diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/UniformRoundingRouteTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/UniformRoundingRouteTests.cs
new file mode 100644
index 00000000..9ec9fa1b
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Integration/UniformRoundingRouteTests.cs
@@ -0,0 +1,147 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Blends;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests.Integration;
+
+/// <summary><c>EdgeFinish&lt;Fillet&gt; { target: AllEdges }</c> on a body the Box/Polyhedron stock route does not
+/// admit: the body is built without the finish and every edge of the result is rounded, or the finish is refused
+/// with what the rounding found.</summary>
+public sealed class UniformRoundingRouteTests
+{
+ internal static string Prism(double radius, string extra = "") => $$"""
+ Model Prism {
+ units: mm
+ Path Outline {
+ start: Point2(0mm, 0mm)
+ heading: 0deg
+ Line South { length: 40mm }
+ Line East { turn: 120deg; length: 40mm }
+ Close West
+ }
+ Profile Section from Outline
+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 12mm } }
+ Modify Body { EdgeFinish<Fillet> Round { target: AllEdges; radius: {{radius}}mm } }
+ {{extra}}}
+ """;
+
+ [Fact]
+ public void ExtrudedPrism_EveryEdgeAStripEveryVertexACorner()
+ {
+ var built = FirmamentBuildAndExport.CompileSource(Prism(2));
+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics.Select(d => d.Message)));
+ var body = built.Value.RuntimeBody!;
+ Assert.True(BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true).IsSuccess);
+ int Count(SurfaceGeometryKind kind) => body.Topology.Faces.Count(f => body.TryGetFaceSurfaceGeometry(f.Id, out var g) && g!.Kind == kind);
+ Assert.Equal((5, 9, 6), (Count(SurfaceGeometryKind.Plane), Count(SurfaceGeometryKind.Cylinder), Count(SurfaceGeometryKind.Sphere)));
+ var read = BlendRecognition.Recognize(body);
+ Assert.All(read.Where(r => r.Role == BlendFaceRole.Strip), s => Assert.Equal(2, s.Blend!.Size, 9));
+ Assert.Contains(built.Value.MaterializedFeatures!, r => r is { Host: "Body", Kind: "EdgeFinish", Name: "Round" });
+ Assert.Equal("Prism", built.Value.DocumentName);
+
+ // The exported STEP is the rounded body.
+ var imported = Step242Importer.ImportBody(built.Value.StepText);
+ Assert.True(imported.IsSuccess);
+ Assert.Equal(20, imported.Value.Topology.Faces.Count());
+ Assert.Equal(built.Value.StepText, FirmamentBuildAndExport.CompileSource(Prism(2)).Value.StepText);
+ }
+
+ [Fact]
+ public void Assertions_AreCheckedOnTheRoundedBody()
+ {
+ var held = FirmamentBuildAndExport.CompileSource(Prism(2, " Assert Topology Body { faces: 20; edges: 36; vertices: 18; shells: 1 }\n"));
+ Assert.True(held.IsSuccess, string.Join("\n", held.Diagnostics.Select(d => d.Message)));
+ var sharp = FirmamentBuildAndExport.CompileSource(Prism(2, " Assert Topology Body { faces: 5; edges: 9; vertices: 6; shells: 1 }\n"));
+ Assert.False(sharp.IsSuccess, "sharp counts held on the rounded body");
+ Assert.Contains(sharp.Diagnostics, d => d.Message.StartsWith("firmament-v2-assert-topology-failed", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void RadiusTooLarge_NamesTheLargestThatFits()
+ {
+ var refused = FirmamentBuildAndExport.CompileSource(Prism(30));
+ var message = Assert.Single(refused.Diagnostics).Message;
+ Assert.StartsWith(UniformRoundingRoute.Code + ": target: AllEdges (fillet every edge) on 'Round'", message);
+ Assert.Contains("uniform-rounding-radius-too-large", message);
+ Assert.Matches(@"largest that fits is under 6(\.0+)? mm|largest that fits is under 5\.99", message);
+ Assert.NotNull(refused.Diagnostics.Single().SourceSpan);
+ }
+
+ [Fact]
+ public void ConcaveBody_RefusesAsConcave()
+ {
+ const string source = """
+ Model Ell {
+ units: mm
+ Path Outline {
+ start: Point2(0mm, 0mm)
+ heading: 0deg
+ Line A { length: 40mm }
+ Line B { turn: 90deg; length: 15mm }
+ Line C { turn: 90deg; length: 25mm }
+ Line D { turn: -90deg; length: 15mm }
+ Line E { turn: 90deg; length: 15mm }
+ Close F
+ }
+ Profile Section from Outline
+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 10mm } }
+ Modify Body { EdgeFinish<Fillet> Round { target: AllEdges; radius: 1mm } }
+ }
+ """;
+ var message = Assert.Single(FirmamentBuildAndExport.CompileSource(source).Diagnostics).Message;
+ Assert.Contains("uniform-rounding-concave-unsupported", message);
+ Assert.Contains("concave edge", message);
+ }
+
+ [Fact]
+ public void CircularEdges_RefuseByName()
+ {
+ var refused = FirmamentBuildAndExport.CompileSource("Model Can { units: mm; Cylinder stock { radius: 10mm; height: 20mm } Modify stock { EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm } } }");
+ Assert.Contains("uniform-rounding-circular-edge-unsupported", Assert.Single(refused.Diagnostics).Message);
+ }
+
+ /// <summary>The diagnostic an LLM or a person feeds back: the body has splines, how many, and which.</summary>
+ [Fact]
+ public void SplineEdges_RefuseByNameWithCountsAndIds()
+ {
+ const string source = """
+ Model NistRound {
+ units: mm
+ InlineStep Source {
+ path: "../../../../testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp"
+ textSha256: "daad981598736d2ee6a104a7213b8d7813deaaabd7f683bc8cf8bbbf401a579a"
+ geometryOnly: true
+ }
+ Modify Source { EdgeFinish<Fillet> Round { target: AllEdges; radius: 1mm } }
+ }
+ """;
+ var refused = FirmamentBuildAndExport.CompileSource(source, Path.Combine(Root(), "fixtures/Regression/InlineStep/production"));
+ var message = Assert.Single(refused.Diagnostics).Message;
+ Assert.Contains("uniform-rounding-spline-edge-unsupported", message);
+ Assert.Contains("does not support spline or elliptical edges yet", message);
+ Assert.Matches(@"\d+ spline edges \(\d+(, \d+)*(, \.\.\.)?\)", message);
+ }
+
+ [Fact]
+ public void Validate_AgreesWithBuild()
+ {
+ var parse = FirmamentV2Parser.Parse(Prism(2));
+ var report = FirmamentV2ValidationReportBuilder.Build(parse, "prism.firmament", null, null, Prism(2));
+ Assert.Equal("invalid", report.Status);
+ var admitted = FirmamentBuildAdmissionValidation.Admit(report, Prism(2));
+ Assert.Equal(("valid", "Built"), (admitted.Status, admitted.ValidationLevel));
+ var refused = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(Prism(30)), "p.firmament", null, null, Prism(30)), Prism(30));
+ Assert.Equal("invalid", refused.Status);
+ Assert.Contains(refused.Diagnostics, d => d.Code == UniformRoundingRoute.Code && d.Message.Contains("radius-too-large", StringComparison.Ordinal));
+ }
+
+ private static string Root()
+ {
+ var dir = new DirectoryInfo(AppContext.BaseDirectory);
+ while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Aetheris.slnx"))) dir = dir.Parent;
+ return dir?.FullName ?? throw new InvalidOperationException("Could not find repo root.");
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index c297f151..ddd22cab 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -292,6 +292,18 @@ public static partial class FirmamentBuildAndExport
var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();
var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema, resources);
canonicalParseWatch.Stop();
+ // Fillet every edge on a body the dedicated Box/Polyhedron route does not take: build the body without the
+ // finish, then round it whole (or refuse with the rounding's reason, at the finish).
+ if (!v2Parse.IsSuccess && v2Parse.SyntaxDiagnostics.Any(d => d.Code == UniformStockFilletAdmission.Code)
+ && UniformRoundingRoute.Find(sourceText) is { } rounding)
+ {
+ // The source as written does not parse (the stock route refuses the finish), so the admitted document
+ // (bodies, assertions) is the one without it; assertions then measure the rounded body.
+ var rounded = UniformRoundingRoute.Export(rounding, stripped => ExportSource(stripped, sourceDirectory, allowV1Compatibility, explicitSchema, resources));
+ return rounded.IsSuccess && rounded.Value.RuntimeAdmissionDocument is null && ParseSemanticSource(rounding.Stripped, sourceDirectory).Document is { } admitted
+ ? KernelResult<FirmamentStepExportResult>.Success(rounded.Value with { RuntimeAdmissionDocument = admitted }, rounded.Diagnostics)
+ : rounded;
+ }
var built = ExportAdmittedSource(sourceText, sourceDirectory, allowV1Compatibility, explicitSchema, resources, v2Parse, canonicalParseWatch);
if (!built.IsSuccess) return built;
var accounting = FirmamentFeatureAccounting.Verify(v2Parse, authoredSource, built.Value);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
index b74b5814..87fc800a 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
@@ -9,6 +9,9 @@ public static class FirmamentBuildAdmissionValidation
public static FirmamentV2ValidationReport Admit(
FirmamentV2ValidationReport report, string source, string? sourceDirectory = null)
{
+ if (report.Status == "invalid" && report.Diagnostics.Any(d => d.Code == UniformStockFilletAdmission.Code)
+ && UniformRoundingRoute.Find(source) is not null)
+ return Rounded(report, source, sourceDirectory);
if (report.Status == "invalid") return report;
var compilation = FirmamentBuildAndExport.CompileSource(source, sourceDirectory);
var diagnostics = report.Diagnostics.Concat(compilation.Diagnostics.Select(diagnostic =>
@@ -27,6 +30,24 @@ public static class FirmamentBuildAdmissionValidation
};
}
+ /// <summary>An AllEdges fillet the stock route does not admit is validated the way build answers it: by building
+ /// the body and rounding it. The stock route's refusal and the generic parse failure give way to that answer.</summary>
+ private static FirmamentV2ValidationReport Rounded(FirmamentV2ValidationReport report, string source, string? sourceDirectory)
+ {
+ var built = FirmamentBuildAndExport.CompileSource(source, sourceDirectory);
+ var diagnostics = report.Diagnostics.Where(d => d.Code is not (UniformStockFilletAdmission.Code or "firmament-v2-parse-failed"))
+ .Concat(built.Diagnostics.Select(d => Present(d, report.Source, source))).Distinct().ToArray();
+ var fatal = diagnostics.Count(d => d.Severity is "fatal" or "error");
+ return report with
+ {
+ Status = built.IsSuccess && fatal == 0 ? "valid" : "invalid",
+ ValidationLevel = built.IsSuccess ? "Built" : "BuildRejected",
+ ParserRoute = UniformRoundingRoute.Code,
+ Diagnostics = diagnostics,
+ Summary = report.Summary with { FatalDiagnosticCount = fatal, WarningDiagnosticCount = diagnostics.Count(d => d.Severity == "warning") },
+ };
+ }
+
public static FirmamentV2ValidationDiagnostic Present(KernelDiagnostic diagnostic, string sourceFile, string? source = null)
{
var separator = diagnostic.Message.IndexOf(':');
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/UniformRoundingRoute.cs b/Aetheris.Kernel.Firmament/FirmamentV2/UniformRoundingRoute.cs
new file mode 100644
index 00000000..4ecc80e8
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/UniformRoundingRoute.cs
@@ -0,0 +1,77 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Blends;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// <c>EdgeFinish&lt;Fillet&gt; { target: AllEdges }</c> on a body the dedicated Box/Polyhedron route does not admit:
+/// build the body without that finish through the ordinary pipeline, then round every edge of the result
+/// (<see cref="UniformRounding"/>: an opening by the ball, exact on convex bodies bounded by planes). Anything the
+/// rounding cannot do yet (curved, spline or elliptical edges, concave bodies, a radius that does not fit) is
+/// refused at the finish with the rounding's own reason.
+/// </summary>
+internal static class UniformRoundingRoute
+{
+ internal const string Code = "firmament-uniform-rounding";
+
+ internal sealed record Request(string Stripped, double Radius, string FinishName, FirmamentV2SourceSpan Span, string? Model, string? Host);
+
+ /// <summary>The one AllEdges fillet in the source and the source without it; null when there is none (or more than one,
+ /// or it is a chamfer: those keep their existing diagnostics).</summary>
+ internal static Request? Find(string source)
+ {
+ var document = FirmamentSyntaxParser.Parse(source).Document;
+ var declarations = FirmamentSyntaxTraversal.Declarations(document).ToArray();
+ var finishes = declarations.Where(d => d.Type.Name.Text == "EdgeFinish" && Field(d, "Target") is { } t && FirmamentSyntaxValues.Reference(t) == "AllEdges").ToArray();
+ if (finishes.Length != 1) return null;
+ var finish = finishes[0];
+ var generic = finish.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(finish.Type.Arguments[0].Value) : null;
+ var kind = generic ?? FirmamentSyntaxValues.Reference(Field(finish, "Kind"));
+ if (kind != "Fillet" || !FirmamentSyntaxValues.TryMeasure(Field(finish, "Radius"), "mm", out var radius)) return null;
+ // Remove the finish; a Modify left empty goes with it.
+ var owner = declarations.FirstOrDefault(d => d.Type.Name.Text == "Modify" && d.Body?.Statements.Contains(finish) == true);
+ var span = owner is not null && owner.Body!.Statements.Count == 1 ? owner.Span : finish.Span;
+ var stripped = source.Remove(span.Start, span.Length);
+ var model = declarations.FirstOrDefault(d => d.Type.Name.Text == "Model")?.Name?.Text;
+ return new(stripped, radius, finish.Name?.Text ?? "AllEdges", finish.Span, model, owner?.Name?.Text);
+ }
+
+ internal static KernelResult<FirmamentStepExportResult> Export(Request request, Func<string, KernelResult<FirmamentStepExportResult>> build)
+ {
+ var unfinished = build(request.Stripped);
+ if (!unfinished.IsSuccess) return unfinished;
+ var body = unfinished.Value.RuntimeBody;
+ if (body is null)
+ {
+ var imported = Step242Importer.ImportBody(unfinished.Value.StepText);
+ if (!imported.IsSuccess) return Refuse(request, "the body before rounding could not be read back: " + string.Join("; ", imported.Diagnostics.Select(d => d.Message)));
+ body = imported.Value;
+ }
+ var rounded = UniformRounding.RoundAllEdges(body, request.Radius);
+ if (!rounded.IsSuccess) return Refuse(request, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));
+ var step = Step242Exporter.ExportBody(rounded.Value, new Step242ExportOptions { ProductName = unfinished.Value.ExportedFeatureId });
+ if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ return KernelResult<FirmamentStepExportResult>.Success(unfinished.Value with
+ {
+ StepText = step.Value,
+ RuntimeBody = rounded.Value,
+ // Correspondence and retained CIR described the body before rounding; they no longer hold.
+ RuntimeCorrespondence = null,
+ Cir = null,
+ DocumentName = request.Model ?? unfinished.Value.DocumentName,
+ MaterializedFeatures = [.. unfinished.Value.MaterializedFeatures ?? [], new FirmamentFeatureReceipt(request.Host ?? unfinished.Value.ExportedFeatureId, "EdgeFinish", request.FinishName)],
+ }, unfinished.Diagnostics);
+ }
+
+ private static KernelResult<FirmamentStepExportResult> Refuse(Request request, string reason) => KernelResult<FirmamentStepExportResult>.Failure([
+ new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ $"{Code}: target: AllEdges (fillet every edge) on '{request.FinishName}': {reason}", "Firmament.UniformRounding")
+ { SourceSpan = new(request.Span.Start, request.Span.Length) }]);
+
+ private static ExpressionSyntax? Field(DeclarationSyntax d, string name) =>
+ d.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, name))?.Value;
+}
diff --git a/docs/development/reports/2026-11/UNIFORM-ROUNDING.md b/docs/development/reports/2026-11/UNIFORM-ROUNDING.md
new file mode 100644
index 00000000..fbed6321
--- /dev/null
+++ b/docs/development/reports/2026-11/UNIFORM-ROUNDING.md
@@ -0,0 +1,57 @@
+# Uniform rounding: "fillet everything" on convex planar bodies
+
+## Method
+
+Rounding every convex edge of a body with a ball of radius r is a morphological
+opening: erode by r, then dilate by the ball. On a convex body bounded by planes
+the erosion is the intersection of the face half-spaces moved in by r (vertices
+by triple-plane enumeration), and the dilation is the existing exact ball sweep
+(`ConvexStockPrimitives`: planes back out by r, cylinders on edges, spheres on
+vertices). There is no corner policy to choose: a vertex where four or more faces
+meet unevenly opens into short edges, each its own strip, which is what a rolled
+ball does. `UniformRounding.RoundAllEdges` in Core.
+
+Refusals, in order, each naming what was found:
+
+- spline / elliptical edges (`uniform-rounding-spline-edge-unsupported`,
+ `-elliptical-edge-unsupported`): counts and the first edge ids of each;
+- circular, other curved edges, curved faces;
+- concave (a vertex beyond a face plane, by how much);
+- radius too large / consuming a face whole: with the largest radius that fits,
+ by bisection (both predicates are monotone in r).
+
+`ConvexStockPrimitives.Hull` no longer assumes the origin is inside (orientation
+and coplanar ordering use the centroid); `CreateHull` is public.
+
+## Firmament
+
+`EdgeFinish<Fillet> { target: AllEdges }` that the Box/Polyhedron stock route
+refuses (`firmament-v2-uniform-stock-fillet-unsupported`) is routed: the finish
+(and a Modify it leaves empty) is removed from the source, the rest is built
+through the ordinary pipeline, and the result is rounded and re-exported with an
+EdgeFinish receipt. Rounding refusals surface as `firmament-uniform-rounding` at
+the finish. `validate` (not `--parse-only`) answers the same way as build. The
+admitted document is the stripped one, so assertions measure the rounded body —
+first wiring silently skipped them (the full source does not parse), caught by a
+test asserting the sharp counts must fail.
+
+Chamfer-all and several AllEdges finishes keep the old refusal.
+
+## Results
+
+- Core: regular solids 4/6/8/12/20 and the box equal the dedicated builders
+ (counts, vertex points, volume); square pyramid, skew-cut prism and an
+ irregular high-valence hull round and read back by the rolling-ball
+ certificate (one strip per edge at r, one joiner per corner); fit size is
+ sharp (0.99·fit builds, 1.01·fit refuses); SO-101 names splines and ellipses.
+- Firmament: extruded triangle prism r 2 → 5 planes, 9 cylinders, 6 spheres,
+ deterministic STEP; L-profile refuses as concave; r 30 refuses with "under
+ 6 mm"; Cylinder, Box+Hole refuse as circular; Ellipsoid as elliptical; FTC-09
+ via InlineStep as "N spline edges (ids…)".
+- Round trip: Remove(Round(prism)) is the prism (points and edge count).
+
+## Open
+
+- Circular edges (cylinders, holes): the erosion is no longer polyhedral.
+- Concave edges: closing by the ball (the dual operation) is not built.
+- Spline / elliptical edges: no plan yet; the message says so to be fed back.
diff --git a/docs/public/firmament/geometry.md b/docs/public/firmament/geometry.md
index 499db4cb..ec7c18a9 100644
--- a/docs/public/firmament/geometry.md
+++ b/docs/public/firmament/geometry.md
@@ -2,8 +2,11 @@
For exact regular solids, ellipsoids and the bounded whole-stock fillet, see
[regular polyhedra and ellipsoids in the syntax guide](../reference/language/solids-and-features.md#primitives).
-`target: AllEdges` currently applies only to untouched size-based Box and regular
-Polyhedron stock. It does not admit rounding all edges of an arbitrary body.
+`target: AllEdges` rounds every edge of untouched Box and regular Polyhedron
+stock, and of any other convex body bounded by planes (an extruded polygon, a
+cut prism): the body is built without the finish and then rounded whole. Bodies
+with curved, spline or elliptical edges, and concave bodies, are refused at the
+finish with what was found.
Ellipsoid BRep export uses exact rational quadratic patches and reimports them as
native exact quadrics. STEP also defines an [`ELLIPSOID` CSG primitive](https://www.steptools.com/docs/stp_aim/html/t_ellipsoid.html);
diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.md
index 5eb87529..b85b96e9 100644
--- a/docs/public/reference/diagnostics.md
+++ b/docs/public/reference/diagnostics.md
@@ -129,7 +129,8 @@ Common recovery patterns:
| unit mismatch | use the required dimension (`mm`, `deg`, `N`) rather than a bare/wrong-dimension value |
| `firmament-v2-polyhedron-face-count-unsupported` | `Polyhedron<N>` requires a compile-time regular convex face count: 4, 6, 8, 12 or 20; N is not the side count of a prism. |
| `firmament-v2-ellipsoid-radii-invalid` | Supply three finite positive X/Y/Z semiaxes with length units in `radii`. |
-| `firmament-v2-uniform-stock-fillet-unsupported` | Use one `EdgeFinish<Fillet>` with `target: AllEdges`, positive `radius` and no face selector on untouched direct Box or regular Polyhedron stock. Arbitrary bodies, hollow stock, other edits and construction adapters are outside this capability. |
+| `firmament-v2-uniform-stock-fillet-unsupported` | Use one `EdgeFinish<Fillet>` with `target: AllEdges`, positive `radius` and no face selector. A body that is not Box or Polyhedron stock is built first and rounded whole, which reports `firmament-uniform-rounding` instead; this code remains for chamfers, several AllEdges finishes and `validate --parse-only`. |
+| `firmament-uniform-rounding` | Rounding every edge of the built body was refused; the message names why. `uniform-rounding-spline-edge-unsupported` / `-elliptical-edge-unsupported` / `-circular-edge-unsupported`: the body has those edges (count and ids given); round a body bounded by planes, or use a local `EdgeFinish`. `-concave-unsupported`: the body has a concave edge. `-radius-too-large` / `-radius-consumes-faces`: use a radius below the one reported. |
| `UniformFilletRadiusTooLarge` | Reduce the radius below the reported stock inradius; this construction requires positive remaining planar faces and edge spans. |
| `drawing-pmi-target-unlocated` | The PMI needs a geometric face association. Automatic generation refuses a model-center leader. |
| `drawing-pmi-value-unavailable` | Supply an admitted finite PMI nominal/depth; a missing measure is not interpreted as zero. |
diff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.md
index f8a4e11f..77657224 100644
--- a/docs/public/reference/language/solids-and-features.md
+++ b/docs/public/reference/language/solids-and-features.md
@@ -146,7 +146,7 @@ What you can select depends on the body:
| 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 |
+| An untouched Box or `Polyhedron<N>`, or any convex body bounded by planes | `target: AllEdges`, fillet only: every edge |
The details that trip people up:
@@ -164,10 +164,17 @@ The details that trip people up:
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
- it rejects an all-edge chamfer.
+- **Whole-body rounding.** `target: AllEdges` needs one fillet. On Box and
+ Polyhedron stock the radius must be below the stock's inradius. On any other
+ body, the body is built without the finish and every edge of the result is
+ rounded: each edge becomes a cylinder strip and each vertex a sphere corner,
+ and where four or more faces meet unevenly the corner opens into short strips,
+ as a rolled ball would leave it. This works on convex bodies bounded by planes.
+ It does not support spline or elliptical edges yet (common on imported parts
+ and on planes cut at an angle through cylinders), nor circular edges or concave
+ bodies; each is refused at the finish, naming the edges found. A radius that
+ does not fit is refused with the largest that does. Assertions measure the
+ rounded body. An all-edge chamfer is refused.
- **Size.** A finish must leave a non-collapsing cap. Straight polygon corners
need not be right angles; tangent line/arc rims and arcs closed by a chord also
work. `endClearance` is for open chains and rejects on closed loops.
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index f366d949..59f6252e 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -6,7 +6,7 @@
|---|---|---|
| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox, exact Ellipsoid, regular Polyhedron<4/6/8/12/20>, and admitted line/arc profile construction/composition |
| 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. |
+| Uniform fillet (all edges) | Bounded | `EdgeFinish<Fillet> { target: AllEdges; radius: ... }` on untouched Box or regular Polyhedron stock, and on any convex body bounded by planes: every edge a cylinder strip and every vertex a sphere corner, exact. Curved, spline and elliptical edges and concave bodies reject by name; a radius that does not fit rejects with the largest that does. |
| 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 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). |
diff --git a/fixtures/Regression/ConvexStock/README.md b/fixtures/Regression/ConvexStock/README.md
index ca2c03ff..1bb09ff6 100644
--- a/fixtures/Regression/ConvexStock/README.md
+++ b/fixtures/Regression/ConvexStock/README.md
@@ -8,5 +8,6 @@ The Core and CLI ConvexStock tests cover actual topology, exact STEP export and
reimport, full face display, mesh closure/orientation, and validate/build agreement.
Invalid mutations are tested separately without rewriting these accepted sources.
-`AllEdges` applies only to untouched Box and the five regular Polyhedron stocks.
-It does not admit arbitrary-body blending or silently ignore other operations.
+`AllEdges` on Box and the five regular Polyhedron stocks uses the dedicated builder;
+other convex planar bodies are rounded after they are built (see the Firmament
+UniformRoundingRoute tests). It never silently ignores other operations.