Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Uniform rounding stage 1: circular edges by the local rolling ball
Claude0ea3e703c615
diff --git a/Aetheris.CLI.Tests/ConvexStockCliTests.cs b/Aetheris.CLI.Tests/ConvexStockCliTests.csindex 2399adb6..d96110f5 100644--- a/Aetheris.CLI.Tests/ConvexStockCliTests.cs+++ b/Aetheris.CLI.Tests/ConvexStockCliTests.cs@@ -10,7 +10,10 @@ public sealed class ConvexStockCliTests{ "box-rounded", 26 }, { "ellipsoid", 8 },{ "polyhedron-4", 4 }, { "polyhedron-6", 6 }, { "polyhedron-8", 8 }, { "polyhedron-12", 12 }, { "polyhedron-20", 20 },{ "polyhedron-4-rounded", 14 }, { "polyhedron-6-rounded", 26 }, { "polyhedron-8-rounded", 26 },- { "polyhedron-12-rounded", 62 }, { "polyhedron-20-rounded", 62 }+ { "polyhedron-12-rounded", 62 }, { "polyhedron-20-rounded", 62 },+ // Every edge of a body built first: rim tori, line strips, sphere corners.+ { "../UniformRounding/cylinder-rounded", 5 }, { "../UniformRounding/frustum-rounded", 5 },+ { "../UniformRounding/box-hole-rounded", 29 }, { "../UniformRounding/d-profile-rounded", 14 }};[Theory]@@ -42,14 +45,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-rounding-circular-edge-unsupported")]+ [InlineData("Cylinder stock { radius: 10mm; height: 20mm }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 12mm }", "uniform-rounding-radius-too-large")][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-rounding-circular-edge-unsupported")]+ [InlineData("Box stock { size: [20mm, 20mm, 20mm] }", "EdgeFinish<Fillet> rounding { target: AllEdges; radius: 1mm } Hole<Shaft> H { on: +Z; center: [5mm, 0mm]; diameter: 6mm; end: ThroughAll }", "uniform-rounding-radius-too-large")]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.csindex 2f4318af..20199dbc 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Blends/UniformRoundingTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Blends/UniformRoundingTests.cs@@ -103,16 +103,76 @@ public sealed class UniformRoundingTestsAssert.Contains("elliptical", message);}+ /// <summary>The local rolling ball on the body's own faces against the opening, where both apply: convex+ /// bodies bounded by planes with three faces at every corner. Same faces, edges, corners and points.</summary>+ [Theory]+ [InlineData("box")]+ [InlineData("tetrahedron")]+ [InlineData("dodecahedron")]+ [InlineData("skew-prism")]+ public void LocalRounding_MatchesTheOpening(string name)+ {+ Point3D[] bottom = [new(0, 0, 0), new(24, 0, 0), new(28, 14, 0), new(6, 17, 0)];+ var body = name switch+ {+ "box" => ConvexStockPrimitives.CreateHull(BoxCorners(40, 30, 20)).Value,+ "tetrahedron" => ConvexStockPrimitives.CreateRegular(4, 30).Value,+ "dodecahedron" => ConvexStockPrimitives.CreateRegular(12, 20).Value,+ _ => ConvexStockPrimitives.CreateHull([.. bottom, .. bottom.Select(p => new Point3D(p.X, p.Y, 10 + 0.25 * p.X + 0.15 * p.Y))]).Value,+ };+ var opening = UniformRounding.RoundAllEdges(body, 1.5);+ var local = LocalRounding.Round(body, 1.5);+ Assert.True(local.Body is not null, local.Refusal?.Message);+ AssertSameSolid(opening.Value, local.Body!, volumeDigits: null);+ var (v0, v1) = (BrepMassProperties.Evaluate(opening.Value).AbsoluteVolume, BrepMassProperties.Evaluate(local.Body!).AbsoluteVolume);+ Assert.True(double.Abs(v1 - v0) <= 1e-4 * v0, $"volume {v1} vs {v0}");+ }++ /// <summary>A cylinder's two rims are circles: each rounds to a torus around the axis (major R - r), the caps+ /// and the side shrink onto the tori's contact circles, and the side's seam runs between them.</summary>+ [Fact]+ public void Cylinder_EachRimATorus()+ {+ var rounded = UniformRounding.RoundAllEdges(BrepPrimitives.CreateCylinder(10, 20).Value, 2);+ Assert.True(rounded.IsSuccess, string.Join("; ", rounded.Diagnostics.Select(d => d.Message)));+ var body = rounded.Value;+ Assert.True(BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true).IsSuccess);+ var tori = body.Topology.Faces.Select(f => body.TryGetFaceSurfaceGeometry(f.Id, out var g) ? g!.Torus : null).Where(t => t is not null).Select(t => t!.Value).ToArray();+ Assert.Equal(2, tori.Length);+ Assert.All(tori, t => { Assert.Equal(8, t.MajorRadius, 9); Assert.Equal(2, t.MinorRadius, 9); Assert.Equal(8, double.Abs(t.Center.Z), 9); });+ Assert.Equal((5, 7), (body.Topology.Faces.Count(), body.Topology.Edges.Count()));+ // The caps keep a disc of radius R - r; the side runs between z = ±(h/2 - r).+ Assert.All(body.Topology.Vertices, v => { body.TryGetVertexPoint(v.Id, out var p); Assert.True(double.Abs(double.Hypot(p.X, p.Y) - 8) < 1e-9 && double.Abs(double.Abs(p.Z) - 10) < 1e-9 || double.Abs(double.Hypot(p.X, p.Y) - 10) < 1e-9 && double.Abs(double.Abs(p.Z) - 8) < 1e-9); });+ AssertRoundTrips(body);+ var strips = BlendRecognition.Recognize(body).Where(r => r.Role == BlendFaceRole.Strip).ToArray();+ Assert.Equal(2, strips.Length);+ Assert.All(strips, s => Assert.Equal(2, s.Blend!.Size, 9));+ }+[Fact]- public void CircularEdges_RefuseByName()+ public void Cylinder_RadiusAsLargeAsTheCylinder_Refuses(){- var refused = UniformRounding.RoundAllEdges(BrepPrimitives.CreateCylinder(10, 20).Value, 1);- Assert.StartsWith("uniform-rounding-circular-edge-unsupported", refused.Diagnostics.Single().Message);+ var refused = UniformRounding.RoundAllEdges(BrepPrimitives.CreateCylinder(10, 40).Value, 12);+ var message = refused.Diagnostics.Single().Message;+ Assert.StartsWith("uniform-rounding-radius-too-large", message);+ var fit = double.Parse(System.Text.RegularExpressions.Regex.Match(message, @"fits is under ([0-9.Ee+-]+) mm").Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);+ Assert.InRange(fit, 4.9, 10);+ Assert.True(UniformRounding.RoundAllEdges(BrepPrimitives.CreateCylinder(10, 40).Value, fit * 0.99).IsSuccess);}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 AssertRoundTrips(BrepBody body)+ {+ var step = Aetheris.Kernel.Core.Step242.Step242Exporter.ExportBody(body);+ Assert.True(step.IsSuccess, string.Join("; ", step.Diagnostics.Select(d => d.Message)));+ var back = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(step.Value);+ Assert.True(back.IsSuccess, string.Join("; ", back.Diagnostics.Select(d => d.Message)));+ Assert.Equal(body.Topology.Faces.Count(), back.Value.Topology.Faces.Count());+ Assert.Equal(Points(body), Points(back.Value));+ }+private static void AssertReadsBack(BrepBody body, int faces, int edges, int vertices, double radius){Assert.True(BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true).IsSuccess);@@ -124,14 +184,14 @@ public sealed class UniformRoundingTestsAssert.Equal(faces, read.Count(r => r.Role == BlendFaceRole.Primary));}- private static void AssertSameSolid(BrepBody expected, BrepBody actual)+ private static void AssertSameSolid(BrepBody expected, BrepBody actual, int? volumeDigits = 6){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);+ if (volumeDigits is { } digits) Assert.Equal(BrepMassProperties.Evaluate(expected).AbsoluteVolume, BrepMassProperties.Evaluate(actual).AbsoluteVolume, digits);}private static string[] Points(BrepBody body) => body.Topology.Verticesdiff --git a/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.cs b/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.csnew file mode 100644index 00000000..fe40bc00--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Blends/LocalRounding.cs@@ -0,0 +1,697 @@+using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Blends;++/// <summary>+/// Every convex edge rounded by a rolling ball of one radius, built locally on the body's own face graph. For a+/// radius small against the body the topology is kept: each face stays on its surface and is trimmed back to where+/// the ball touches it, each edge becomes the tube around the ball centre's path (a cylinder around a line, a torus+/// around a circle) and each three-edge corner a piece of the ball. The ball centre is where the faces moved in by+/// the radius meet, so nothing here is approximated.+///+/// Admits faces on planes, cylinders and cones; line edges between faces that share the line's direction (planes+/// along it, cylinders around it); circle edges between faces that share the circle's axis; corners where three+/// edges meet; seams of periodic faces. Refuses the rest by name, and a radius too large for the body (an edge or a+/// face used up, the ball reaching a face beyond its two) as such.+/// </summary>+internal static class LocalRounding+{+ internal sealed record Refusal(string Code, string Message);++ internal sealed class Outcome+ {+ public BrepBody? Body { get; init; }+ public Refusal? Refusal { get; init; }+ }++ private const double Turn = 2 * double.Pi;++ /// <summary>One face's surface and its outward side, as a distance function.</summary>+ private sealed class Support(FaceId face, SurfaceGeometry surface, double sense)+ {+ public FaceId Face { get; } = face;+ public double Sense { get; } = sense;+ public SurfaceGeometry Surface { get; } = surface;+ public SurfaceGeometryKind Kind => Surface.Kind;++ public Point3D Foot(Point3D x)+ {+ switch (Kind)+ {+ case SurfaceGeometryKind.Plane:+ {+ var p = Surface.Plane!.Value; var n = p.Normal.ToVector();+ return x - n * n.Dot(x - p.Origin);+ }+ case SurfaceGeometryKind.Cylinder:+ {+ var c = Surface.Cylinder!.Value; var a = c.Axis.ToVector(); var q = x - c.Origin; var h = q.Dot(a);+ return c.Origin + a * h + Radial(q, a, c.XAxis.ToVector()) * c.Radius;+ }+ default:+ {+ var k = Surface.Cone!.Value; var a = k.Axis.ToVector(); var q = x - k.Apex; var h = q.Dot(a);+ var (s, co) = (double.Sin(k.SemiAngleRadians), double.Cos(k.SemiAngleRadians));+ var along = double.Max(0, (q - a * h).Length * s + h * co);+ return k.Apex + (Radial(q, a, k.XAxis()) * s + a * co) * along;+ }+ }+ }++ /// <summary>Unit outward normal of the body at the foot of the point.</summary>+ public Vector3D Outward(Point3D x)+ {+ Vector3D n;+ switch (Kind)+ {+ case SurfaceGeometryKind.Plane: n = Surface.Plane!.Value.Normal.ToVector(); break;+ case SurfaceGeometryKind.Cylinder:+ {+ var c = Surface.Cylinder!.Value;+ n = Radial(x - c.Origin, c.Axis.ToVector(), c.XAxis.ToVector()); break;+ }+ default:+ {+ var k = Surface.Cone!.Value; var a = k.Axis.ToVector();+ n = Radial(x - k.Apex, a, k.XAxis()) - a * double.Tan(k.SemiAngleRadians);+ n *= 1 / n.Length; break;+ }+ }+ return n * sense;+ }++ /// <summary>Signed distance to the surface, positive on the material side.</summary>+ public double Inside(Point3D x) { var f = Foot(x); return -Outward(x).Dot(x - f); }++ private static Vector3D Radial(Vector3D q, Vector3D axis, Vector3D fallback)+ {+ var r = q - axis * q.Dot(axis);+ return r.Length > 1e-14 ? r * (1 / r.Length) : fallback;+ }+ }++ /// <summary>An edge's shape from its start to its end: a segment, or an arc about a normal (right-handed).</summary>+ private sealed record Shape(Point3D Start, Point3D End, Point3D? Center, Vector3D Normal, double Sweep)+ {+ public bool Arc => Center is not null;++ public Point3D At(double t) => !Arc ? Start + (End - Start) * t : Rotate(Start, Center!.Value, Normal, Sweep * t);++ public Vector3D Tangent(Point3D p) => !Arc ? Unit(End - Start) : Unit(Normal.Cross(p - Center!.Value));++ public IEnumerable<Point3D> Points(int arcSegments) =>+ Arc ? Enumerable.Range(0, arcSegments + 1).Select(i => At(i / (double)arcSegments)) : [Start, End];+ }++ /// <summary>A sharp edge to round: its two faces (A uses it forward), its shape, and what it is built from.</summary>+ private sealed class Sharp+ {+ public required Edge Edge { get; init; }+ public required Shape Shape { get; init; }+ public required Support F0 { get; init; }+ public required Support F1 { get; init; }+ // Once the faces' loops are oriented: A walks the edge forward, B backward.+ public required Support A { get; init; }+ public required Support B { get; init; }+ public bool Closed => Edge.StartVertexId == Edge.EndVertexId;+ // Closed circles: the ball centre, and where it touches A and B, at the seam's meridian.+ public Point3D Centre { get; set; }+ }++ internal static Outcome Round(BrepBody body, double radius)+ {+ var topology = body.Topology;+ var points = VertexPoints(body);+ if (points.Count != topology.Vertices.Count())+ return Refuse("uniform-rounding-edge-unsupported", "some vertices of the body have no position");+ var extent = points.Values.Max(p => (p - Point3D.Origin).Length);+ var tol = double.Max(1e-9, (extent + 1) * 1e-10) * 1e2;++ // Faces: supports with their outward side.+ var supports = new Dictionary<FaceId, Support>();+ foreach (var face in topology.Faces.OrderBy(f => f.Id.Value))+ {+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var surface) || surface is null || surface.Kind is not (SurfaceGeometryKind.Plane or SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone))+ return Refuse("uniform-rounding-curved-face-unsupported", $"rounding every edge supports faces on planes, cylinders and cones for now; face {face.Id.Value} is {surface?.Kind.ToString() ?? "unbound"}");+ body.Bindings.TryGetFaceBinding(face.Id, out var binding);+ supports.Add(face.Id, new Support(face.Id, surface, binding.Orientation.IsAlignedWithSurface ? 1 : -1));+ }+ var faceOfLoop = topology.Faces.SelectMany(f => f.LoopIds.Select(l => (l, f.Id))).ToDictionary(x => x.l, x => x.Id);+ var uses = topology.Coedges.GroupBy(c => c.EdgeId).ToDictionary(g => g.Key, g => g.ToArray());++ // Edges: shapes, seams, and the sharp convex edges to round.+ var shapes = new Dictionary<EdgeId, Shape>();+ var sharp = new Dictionary<EdgeId, Sharp>();+ var seams = new Dictionary<EdgeId, FaceId>();+ var pairs = new Dictionary<EdgeId, (FaceId F0, FaceId F1)>();+ foreach (var edge in topology.Edges.OrderBy(e => e.Id.Value))+ {+ if (!uses.TryGetValue(edge.Id, out var pair) || pair.Length != 2)+ return Refuse("uniform-rounding-edge-unsupported", $"edge {edge.Id.Value} is not shared by exactly two faces");+ var shape = ShapeOf(body, edge, points);+ if (shape is null)+ return Refuse("uniform-rounding-edge-unsupported", $"edge {edge.Id.Value} has no line or circle geometry this rounding can follow");+ shapes.Add(edge.Id, shape);+ var (f0, f1) = (faceOfLoop[pair[0].LoopId], faceOfLoop[pair[1].LoopId]);+ if (f0 == f1)+ {+ if (shape.Arc || supports[f0].Kind == SurfaceGeometryKind.Plane)+ return Refuse("uniform-rounding-edge-unsupported", $"edge {edge.Id.Value} has face {f0.Value} on both sides and is not the seam of a cylinder or cone");+ seams.Add(edge.Id, f0); continue;+ }+ pairs.Add(edge.Id, (f0, f1));+ }++ // Orientation: each face's outer loop walked counterclockwise about its outward normal, inner loops+ // clockwise, by exact signed area. The input's coedge senses are not relied on.+ var oriented = new Dictionary<FaceId, List<List<(EdgeId Edge, bool Reversed)>>>();+ foreach (var face in topology.Faces.OrderBy(f => f.Id.Value))+ {+ var loops = face.LoopIds.Select(l => topology.GetLoop(l).CoedgeIds.Select(topology.GetCoedge).Select(c => (c.EdgeId, c.IsReversed)).ToList()).ToList();+ var areas = loops.Select(l => SignedArea(supports[face.Id], l, shapes)).ToArray();+ var outer = Array.IndexOf(areas, areas.MaxBy(double.Abs));+ for (var i = 0; i < loops.Count; i++)+ if (areas[i] > 0 != (i == outer)) { loops[i].Reverse(); loops[i] = loops[i].Select(u => (u.EdgeId, !u.IsReversed)).ToList(); }+ oriented.Add(face.Id, loops);+ }++ // Sharp convex edges: A walks the edge forward, B backward; B's interior is left of B's direction about its+ // outward normal, and across a convex edge it lies behind A's tangent plane.+ foreach (var (edgeId, (f0, f1)) in pairs)+ {+ var edge = topology.GetEdge(edgeId); var shape = shapes[edgeId];+ var on0 = oriented[f0].SelectMany(l => l).Where(u => u.Edge == edgeId).ToArray();+ var on1 = oriented[f1].SelectMany(l => l).Where(u => u.Edge == edgeId).ToArray();+ if (on0.Length != 1 || on1.Length != 1 || on0[0].Reversed == on1[0].Reversed)+ return Refuse("uniform-rounding-edge-unsupported", $"faces {f0.Value} and {f1.Value} do not walk edge {edgeId.Value} in opposite directions once oriented");+ var (a, b) = on0[0].Reversed ? (supports[f1], supports[f0]) : (supports[f0], supports[f1]);+ var p = shape.At(0.5);+ var (na, nb) = (a.Outward(p), b.Outward(p));+ if (na.Cross(nb).Length < 1e-7 && na.Dot(nb) > 0)+ return Refuse("uniform-rounding-tangent-edge-unsupported", $"rounding every edge does not support edges where faces meet tangentially yet: edge {edgeId.Value} between faces {a.Face.Value} and {b.Face.Value} is smooth");+ var intoB = nb.Cross(shape.Tangent(p) * -1);+ if (na.Dot(intoB) > -1e-9)+ return Refuse("uniform-rounding-concave-unsupported", $"rounding every edge supports convex edges only for now: edge {edgeId.Value} between faces {a.Face.Value} and {b.Face.Value} is a concave edge (closing concave edges with the ball is not built yet)");+ if (!Shares(a, shape, tol) || !Shares(b, shape, tol))+ return Refuse("uniform-rounding-edge-unsupported", $"rounding every edge needs each edge's faces to run along its line or around its circle's axis: edge {edgeId.Value} {(shape.Arc ? "is a circle" : "is a line")} between a {Article(a.Kind)} and a {Article(b.Kind)} face that do not, so the ball's path along it is not a line or a circle");+ sharp.Add(edgeId, new Sharp { Edge = edge, Shape = shape, F0 = a, F1 = b, A = a, B = b });+ }++ // Corners: every vertex on an open sharp edge joins exactly three sharp edges and three faces.+ var corners = new Dictionary<VertexId, (Point3D Centre, EdgeId[] Edges, FaceId[] Faces)>();+ foreach (var vertex in topology.Vertices.OrderBy(v => v.Id.Value))+ {+ var incident = topology.Edges.Where(e => e.StartVertexId == vertex.Id || e.EndVertexId == vertex.Id).ToArray();+ var open = incident.Where(e => e.StartVertexId != e.EndVertexId).ToArray();+ if (open.Length == 0) continue;+ if (open.Any(e => seams.ContainsKey(e.Id)) && open.All(e => seams.ContainsKey(e.Id))) continue; // seam ends+ if (open.Length != 3 || open.Any(e => !sharp.ContainsKey(e.Id)))+ return Refuse("uniform-rounding-vertex-unsupported", $"vertex {vertex.Id.Value} joins {open.Length} edges; rounding every edge on a body with curved faces needs three sharp edges at each corner for now");+ var faces = open.SelectMany(e => new[] { sharp[e.Id].F0.Face, sharp[e.Id].F1.Face }).Distinct().ToArray();+ if (faces.Length != 3)+ return Refuse("uniform-rounding-vertex-unsupported", $"vertex {vertex.Id.Value} joins {faces.Length} faces with three edges; rounding needs three faces at each corner");+ var centre = Centre(faces.Select(f => supports[f]).ToArray(), points[vertex.Id], radius, tol);+ if (centre is null || (centre.Value - points[vertex.Id]).Length > 50 * radius)+ return TooLarge(radius, $"the ball does not fit in the corner at vertex {vertex.Id.Value}");+ corners.Add(vertex.Id, (centre.Value, open.Select(e => e.Id).ToArray(), faces));+ }++ // Closed circles: the ball centre at the seam's meridian (or the circle's own start).+ foreach (var s in sharp.Values.Where(s => s.Closed))+ {+ var seam = seams.Where(x => x.Value == s.F0.Face || x.Value == s.F1.Face).Select(x => shapes[x.Key].Start).ToArray();+ var c = s.Shape.Center!.Value; var nu = s.Shape.Normal;+ var x0 = Unit(s.Shape.Start - c);+ if (seam.Length > 0)+ {+ var meridian = Unit((seam[0] - c) - nu * (seam[0] - c).Dot(nu));+ if (seam.Skip(1).Any(q => Unit((q - c) - nu * (q - c).Dot(nu)).Dot(meridian) < 1 - 1e-9))+ return Refuse("uniform-rounding-edge-unsupported", $"the faces around circle edge {s.Edge.Id.Value} have seams at different angles");+ x0 = meridian;+ }+ var centre = Meridian(s.F0, s.F1, c, nu, x0, s.Shape.Start, radius, tol, (s.Shape.Start - c).Length);+ if (centre is null) return TooLarge(radius, $"the ball does not fit along circle edge {s.Edge.Id.Value}");+ s.Centre = centre.Value;+ }++ return Build(body, radius, tol, supports, oriented, shapes, sharp, seams, corners);+ }++ private static Outcome Build(BrepBody body, double radius, double tol, Dictionary<FaceId, Support> supports, Dictionary<FaceId, List<List<(EdgeId Edge, bool Reversed)>>> oriented,+ Dictionary<EdgeId, Shape> shapes, Dictionary<EdgeId, Sharp> sharp, Dictionary<EdgeId, FaceId> seams,+ Dictionary<VertexId, (Point3D Centre, EdgeId[] Edges, FaceId[] Faces)> corners)+ {+ var topology = body.Topology;+ var builder = new TopologyBuilder();+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var positions = new Dictionary<VertexId, Point3D>();+ var built = new Dictionary<EdgeId, Shape>();+ var resultFaces = new List<FaceId>();++ VertexId NewVertex(Point3D p) { var id = builder.AddVertex(); positions[id] = p; return id; }+ EdgeId NewEdge(VertexId a, VertexId b, Shape shape)+ {+ var edge = builder.AddEdge(a, b); var id = new CurveGeometryId(geometry.Curves.Count() + 1);+ if (shape.Arc)+ {+ var c = shape.Center!.Value;+ geometry.AddCurve(id, CurveGeometry.FromCircle(new Circle3Curve(c, Direction3D.Create(shape.Normal), (shape.Start - c).Length, Direction3D.Create(shape.Start - c))));+ bindings.AddEdgeBinding(new(edge, id, new(0, shape.Sweep)));+ }+ else+ {+ geometry.AddCurve(id, CurveGeometry.FromLine(new Line3Curve(shape.Start, Direction3D.Create(shape.End - shape.Start))));+ bindings.AddEdgeBinding(new(edge, id, new(0, (shape.End - shape.Start).Length)));+ }+ built.Add(edge, shape); return edge;+ }+ void NewFace(IReadOnlyList<IReadOnlyList<(EdgeId Edge, bool Reversed)>> loops, SurfaceGeometry surface, bool aligned)+ {+ var loopIds = new List<LoopId>();+ foreach (var loop in loops)+ {+ var id = builder.AllocateLoopId(); var ids = loop.Select(_ => builder.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < ids.Length; i++)+ builder.AddCoedge(new(ids[i], loop[i].Edge, id, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], loop[i].Reversed));+ builder.AddLoop(new Loop(id, ids)); loopIds.Add(id);+ }+ var face = builder.AddFace(loopIds); resultFaces.Add(face);+ var sid = new SurfaceGeometryId(geometry.Surfaces.Count() + 1); geometry.AddSurface(sid, surface);+ bindings.AddFaceBinding(new FaceGeometryBinding(face, sid, aligned));+ }++ // Contact vertices: where the ball at a corner touches each of its faces; for closed circles, where the ball+ // at the meridian touches each side.+ var contact = new Dictionary<(VertexId Vertex, FaceId Face), VertexId>();+ foreach (var (vertex, corner) in corners)+ foreach (var face in corner.Faces)+ contact.Add((vertex, face), NewVertex(supports[face].Foot(corner.Centre)));+ var ring = new Dictionary<(EdgeId Edge, FaceId Face), VertexId>();+ foreach (var s in sharp.Values.Where(s => s.Closed))+ {+ ring.Add((s.Edge.Id, s.A.Face), NewVertex(s.A.Foot(s.Centre)));+ ring.Add((s.Edge.Id, s.B.Face), NewVertex(s.B.Foot(s.Centre)));+ }++ // Contact edges along each sharp edge, on each of its faces; the ball's cross-section arcs at its ends.+ var along = new Dictionary<(EdgeId Edge, FaceId Face), EdgeId>();+ var section = new Dictionary<(EdgeId Edge, VertexId Vertex), EdgeId>();+ var strips = new List<(Sharp Sharp, SurfaceGeometry Surface)>();+ foreach (var s in sharp.Values.OrderBy(s => s.Edge.Id.Value))+ {+ var shape = s.Shape;+ if (s.Closed)+ {+ var c = shape.Center!.Value; var nu = shape.Normal;+ foreach (var face in new[] { s.A, s.B })+ {+ var v = ring[(s.Edge.Id, face.Face)]; var p = positions[v]; var centre = c + nu * (p - c).Dot(nu);+ if ((p - centre).Length <= tol) return TooLarge(radius, $"the contact with face {face.Face.Value} along circle edge {s.Edge.Id.Value} shrinks to a point");+ along.Add((s.Edge.Id, face.Face), NewEdge(v, v, new Shape(p, p, centre, nu, Turn)));+ }+ var (a, b) = (ring[(s.Edge.Id, s.A.Face)], ring[(s.Edge.Id, s.B.Face)]);+ var tangent = Unit(nu.Cross(s.Centre - c));+ section.Add((s.Edge.Id, s.Edge.StartVertexId), NewEdge(a, b, Cross(positions[a], positions[b], s.Centre, tangent)));+ var axisCentre = c + nu * (s.Centre - c).Dot(nu); var major = (s.Centre - axisCentre).Length;+ if (major <= radius + tol) return TooLarge(radius, $"the ball along circle edge {s.Edge.Id.Value} reaches the circle's axis");+ strips.Add((s, SurfaceGeometry.FromTorus(new TorusSurface(axisCentre, Direction3D.Create(nu), major, radius, Direction3D.Create(s.Centre - axisCentre)))));+ continue;+ }++ var (start, end) = (s.Edge.StartVertexId, s.Edge.EndVertexId);+ var (c0, c1) = (corners[start].Centre, corners[end].Centre);+ foreach (var face in new[] { s.A, s.B })+ {+ var (v0, v1) = (contact[(start, face.Face)], contact[(end, face.Face)]);+ var (p0, p1) = (positions[v0], positions[v1]);+ Shape? path = null;+ if (!shape.Arc)+ {+ if ((p1 - p0).Dot(shape.End - shape.Start) <= tol * (shape.End - shape.Start).Length)+ return TooLarge(radius, $"the rounding uses up edge {s.Edge.Id.Value} on face {face.Face.Value}");+ path = new Shape(p0, p1, null, Vector3D.Zero, 0);+ }+ else+ {+ var c = shape.Center!.Value; var nu = shape.Normal; var centre = c + nu * (p0 - c).Dot(nu);+ var sweep = Angle(p0 - centre, p1 - centre, nu);+ if ((p0 - centre).Length <= tol || double.Abs(sweep - shape.Sweep) >= double.Pi / 2 || sweep <= 1e-9)+ return TooLarge(radius, $"the rounding uses up edge {s.Edge.Id.Value} on face {face.Face.Value}");+ path = new Shape(p0, p1, centre, nu, sweep);+ }+ along.Add((s.Edge.Id, face.Face), NewEdge(v0, v1, path));+ }+ foreach (var (vertex, centre) in new[] { (start, c0), (end, c1) })+ {+ var (a, b) = (contact[(vertex, s.A.Face)], contact[(vertex, s.B.Face)]);+ section.Add((s.Edge.Id, vertex), NewEdge(a, b, Cross(positions[a], positions[b], centre, shape.Tangent(shape.Arc ? Project(centre, shape) : centre))));+ }+ if (!shape.Arc)+ {+ if ((c1 - c0).Dot(shape.End - shape.Start) <= tol || Unit(c1 - c0).Cross(Unit(shape.End - shape.Start)).Length > 1e-7)+ return TooLarge(radius, $"the ball's path along edge {s.Edge.Id.Value} folds back");+ strips.Add((s, SurfaceGeometry.FromCylinder(new CylinderSurface(c0, Direction3D.Create(c1 - c0), radius, Direction3D.Create(positions[contact[(start, s.A.Face)]] - c0)))));+ }+ else+ {+ var c = shape.Center!.Value; var nu = shape.Normal; var axisCentre = c + nu * (c0 - c).Dot(nu); var major = (c0 - axisCentre).Length;+ if (major <= radius + tol) return TooLarge(radius, $"the ball along circle edge {s.Edge.Id.Value} reaches the circle's axis");+ strips.Add((s, SurfaceGeometry.FromTorus(new TorusSurface(axisCentre, Direction3D.Create(nu), major, radius, Direction3D.Create(c0 - axisCentre)))));+ }+ }++ // Seams: the generator between the contacts at either end of the periodic face.+ var seam = new Dictionary<EdgeId, EdgeId>();+ foreach (var (edge, face) in seams)+ {+ var shape = shapes[edge];+ VertexId? Nearest(Point3D p) => sharp.Values.Where(s => s.Closed && (s.A.Face == face || s.B.Face == face))+ .OrderBy(s => double.Abs((p - s.Shape.Center!.Value).Dot(s.Shape.Normal))).Select(s => (VertexId?)ring[(s.Edge.Id, face)]).FirstOrDefault();+ if (Nearest(shape.Start) is not { } v0 || Nearest(shape.End) is not { } v1 || v0 == v1)+ return Refuse("uniform-rounding-edge-unsupported", $"seam edge {edge.Value} on face {face.Value} does not run between two circle edges");+ if ((positions[v1] - positions[v0]).Dot(shape.End - shape.Start) <= tol)+ return TooLarge(radius, $"the rounding uses up face {face.Value} along its seam");+ seam.Add(edge, NewEdge(v0, v1, new Shape(positions[v0], positions[v1], null, Vector3D.Zero, 0)));+ }++ // Original faces, trimmed: each coedge replaced by its contact edge (or rebuilt seam), same direction.+ var originalLoops = new Dictionary<FaceId, List<List<(EdgeId Edge, bool Reversed)>>>();+ foreach (var face in topology.Faces.OrderBy(f => f.Id.Value))+ {+ var loops = oriented[face.Id].Select(loop => loop.Select(u => (seam.TryGetValue(u.Edge, out var rebuilt) ? rebuilt : along[(u.Edge, face.Id)], u.Reversed)).ToList()).ToList();+ originalLoops.Add(face.Id, loops);+ body.Bindings.TryGetFaceBinding(face.Id, out var binding);+ NewFace(loops.Select(l => (IReadOnlyList<(EdgeId, bool)>)l).ToList(), supports[face.Id].Surface, binding.Orientation.IsAlignedWithSurface);+ }++ // Strips: the contact on A against A's direction, the section at the start, the contact on B, the section+ // at the end back. A uses the edge forward, so every shared edge is used once each way.+ foreach (var (s, surface) in strips)+ {+ var a = along[(s.Edge.Id, s.A.Face)]; var b = along[(s.Edge.Id, s.B.Face)];+ var first = section[(s.Edge.Id, s.Edge.StartVertexId)];+ var last = s.Closed ? first : section[(s.Edge.Id, s.Edge.EndVertexId)];+ NewFace([[(a, true), (first, false), (b, false), (last, true)]], surface, true);+ }++ // Corners: the three sections, each against the direction its strip uses it.+ foreach (var (vertex, corner) in corners.OrderBy(c => c.Key.Value))+ {+ var arcs = corner.Edges.Select(e => (Edge: section[(e, vertex)], Reversed: sharp[e].Edge.StartVertexId == vertex)).ToList();+ var ordered = new List<(EdgeId, bool)> { arcs[0] }; arcs.RemoveAt(0);+ while (arcs.Count > 0)+ {+ var (last, reversed) = ordered[^1]; var e = builder.Model.GetEdge(last); var end = reversed ? e.StartVertexId : e.EndVertexId;+ var next = arcs.FindIndex(x => (x.Reversed ? builder.Model.GetEdge(x.Edge).EndVertexId : builder.Model.GetEdge(x.Edge).StartVertexId) == end);+ if (next < 0) return Refuse("uniform-rounding-vertex-unsupported", $"the corner at vertex {vertex.Value} does not close");+ ordered.Add(arcs[next]); arcs.RemoveAt(next);+ }+ var axis = Unit(corner.Faces.Aggregate(Vector3D.Zero, (n, f) => n + supports[f].Outward(corner.Centre)));+ NewFace([ordered], SurfaceGeometry.FromSphere(new SphereSurface(corner.Centre, Direction3D.Create(axis), radius, Direction3D.Create(Perpendicular(axis)))), true);+ }++ // Fit: the ball touches nothing beyond its own faces, and planar faces keep their loops simple.+ var refusal = Clearance(body, radius, tol, supports, sharp, corners) ?? Planar(radius, tol, oriented, supports, shapes, built, originalLoops);+ if (refusal is not null) return new Outcome { Refusal = refusal };++ builder.AddBody([builder.AddShell(resultFaces)]);+ var result = new BrepBody(builder.Model, geometry, bindings, positions);+ var validation = BrepBindingValidator.Validate(result, requireAllEdgeAndFaceBindings: true);+ return validation.IsSuccess ? new Outcome { Body = result }+ : Refuse("uniform-rounding-build-failed", string.Join("; ", validation.Diagnostics.Select(d => d.Message)));+ }++ /// <summary>The ball centre at inward distance r from three faces, by Newton on their distance functions+ /// (whose gradients are the inward normals); exact in one step on planes.</summary>+ private static Point3D? Centre(Support[] faces, Point3D vertex, double radius, double tol)+ {+ var x = vertex - Unit(faces.Aggregate(Vector3D.Zero, (n, f) => n + f.Outward(vertex))) * radius;+ for (var i = 0; i < 60; i++)+ {+ var rows = faces.Select(f => f.Outward(x) * -1).ToArray();+ var residual = faces.Select(f => f.Inside(x) - radius).ToArray();+ if (residual.All(r => double.Abs(r) <= tol * 1e-3)) return x;+ var det = rows[0].Dot(rows[1].Cross(rows[2]));+ if (double.Abs(det) < 1e-12) return null;+ var step = (rows[1].Cross(rows[2]) * -residual[0] + rows[2].Cross(rows[0]) * -residual[1] + rows[0].Cross(rows[1]) * -residual[2]) * (1 / det);+ x += step;+ }+ return faces.All(f => double.Abs(f.Inside(x) - radius) <= tol) ? x : null;+ }++ /// <summary>The ball centre at inward distance r from two coaxial faces, in the half-plane at the meridian.</summary>+ private static Point3D? Meridian(Support a, Support b, Point3D centre, Vector3D axis, Vector3D meridian, Point3D onEdge, double radius, double tol, double rho0)+ {+ var start = centre + meridian * rho0;+ var (rho, z) = (rho0, 0d);+ var guess = start - Unit(a.Outward(start) + b.Outward(start)) * radius;+ (rho, z) = ((guess - centre).Dot(meridian), (guess - centre).Dot(axis));+ for (var i = 0; i < 60; i++)+ {+ var x = centre + meridian * rho + axis * z;+ var (ra, rb) = (a.Inside(x) - radius, b.Inside(x) - radius);+ if (double.Abs(ra) <= tol * 1e-3 && double.Abs(rb) <= tol * 1e-3) return x;+ var (ga, gb) = (a.Outward(x) * -1, b.Outward(x) * -1);+ var (j00, j01, j10, j11) = (ga.Dot(meridian), ga.Dot(axis), gb.Dot(meridian), gb.Dot(axis));+ var det = j00 * j11 - j01 * j10;+ if (double.Abs(det) < 1e-12) return null;+ rho -= (ra * j11 - rb * j01) / det; z -= (rb * j00 - ra * j10) / det;+ }+ return null;+ }++ /// <summary>Sampled ball centres along every strip and at every corner stay further than r from each face that+ /// is not one of their own, wherever that face actually is.</summary>+ private static Refusal? Clearance(BrepBody body, double radius, double tol, Dictionary<FaceId, Support> supports,+ Dictionary<EdgeId, Sharp> sharp, Dictionary<VertexId, (Point3D Centre, EdgeId[] Edges, FaceId[] Faces)> corners)+ {+ IEnumerable<(Point3D Centre, FaceId[] Own, string Where)> Samples()+ {+ foreach (var s in sharp.Values)+ {+ var own = new[] { s.A.Face, s.B.Face };+ if (s.Closed)+ {+ var c = s.Shape.Center!.Value;+ for (var i = 0; i < 24; i++) yield return (Rotate(s.Centre, c, s.Shape.Normal, Turn * i / 24), own, $"along edge {s.Edge.Id.Value}");+ continue;+ }+ var (c0, c1) = (corners[s.Edge.StartVertexId].Centre, corners[s.Edge.EndVertexId].Centre);+ for (var i = 1; i < 8; i++)+ {+ var t = i / 8d;+ yield return (!s.Shape.Arc ? c0 + (c1 - c0) * t : Rotate(c0, s.Shape.Center!.Value, s.Shape.Normal, Angle(c0 - Axial(c0, s.Shape), c1 - Axial(c0, s.Shape), s.Shape.Normal) * t), own, $"along edge {s.Edge.Id.Value}");+ }+ }+ foreach (var (vertex, corner) in corners) yield return (corner.Centre, corner.Faces, $"at vertex {vertex.Value}");+ }+ foreach (var (centre, own, where) in Samples())+ foreach (var (face, support) in supports)+ {+ if (own.Contains(face)) continue;+ var foot = support.Foot(centre);+ // Touching counts: a ball that touches a third face leaves a face pinched to nothing there.+ if ((foot - centre).Length > radius + tol) continue;+ var on = FaceDomainQuery.TryClassifyPointOnFace(body, face, foot);+ if (on.Classification is FaceDomainClassification.Inside or FaceDomainClassification.OnBoundary)+ return TooLarge(radius, $"the ball {where} reaches face {face.Value}").Refusal;+ }+ return null;+ }++ /// <summary>Each planar face's new loops keep their winding and do not cross one another.</summary>+ private static Refusal? Planar(double radius, double tol, Dictionary<FaceId, List<List<(EdgeId Edge, bool Reversed)>>> oriented, Dictionary<FaceId, Support> supports,+ Dictionary<EdgeId, Shape> shapes, Dictionary<EdgeId, Shape> built, Dictionary<FaceId, List<List<(EdgeId Edge, bool Reversed)>>> loops)+ {+ foreach (var (face, newLoops) in loops)+ {+ if (supports[face].Kind != SurfaceGeometryKind.Plane) continue;+ var plane = supports[face].Surface.Plane!.Value;+ var (u, v, n) = (plane.UAxis.ToVector(), plane.VAxis.ToVector(), plane.Normal.ToVector());+ (double X, double Y) Flat(Point3D p) => ((p - plane.Origin).Dot(u), (p - plane.Origin).Dot(v));+ List<(double X, double Y)> Polyline(IEnumerable<(Shape Shape, bool Reversed)> edges) =>+ edges.SelectMany(e => { var pts = e.Shape.Points(24).ToList(); if (e.Reversed) pts.Reverse(); return pts.Take(pts.Count - 1); }).Select(Flat).ToList();+ var original = oriented[face].Select(l => Polyline(l.Select(u => (shapes[u.Edge], u.Reversed)))).ToList();+ var segments = new List<((double X, double Y) P, (double X, double Y) Q, EdgeId Edge)>();+ for (var i = 0; i < newLoops.Count; i++)+ {+ var polyline = Polyline(newLoops[i].Select(e => (built[e.Edge], e.Reversed)));+ if (double.Sign(Area(polyline)) != double.Sign(Area(original[i])) || double.Abs(Area(polyline)) <= tol * tol)+ return TooLarge(radius, $"the rounding turns a boundary of face {face.Value} inside out").Refusal;+ foreach (var (edge, reversed) in newLoops[i])+ {+ var pts = built[edge].Points(24).Select(Flat).ToList();+ for (var k = 0; k + 1 < pts.Count; k++) segments.Add((pts[k], pts[k + 1], edge));+ }+ }+ for (var i = 0; i < segments.Count; i++)+ for (var j = i + 1; j < segments.Count; j++)+ if (segments[i].Edge != segments[j].Edge && Crosses(segments[i].P, segments[i].Q, segments[j].P, segments[j].Q, tol))+ return TooLarge(radius, $"the rounding makes the boundaries of face {face.Value} cross").Refusal;+ }+ return null;+ }++ /// <summary>A loop's signed area about the face's outward normal: in the plane, by the shoelace over its+ /// vertices plus each arc's circular segment; on a cylinder or cone, in the (angle, height) chart, where its+ /// circles and generators are straight and counterclockwise is the surface normal.</summary>+ private static double SignedArea(Support face, List<(EdgeId Edge, bool Reversed)> loop, Dictionary<EdgeId, Shape> shapes)+ {+ var sense = face.Sense;+ var area = 0d;+ if (face.Kind == SurfaceGeometryKind.Plane)+ {+ var plane = face.Surface.Plane!.Value; var n = plane.Normal.ToVector();+ var (u, v) = (plane.UAxis.ToVector(), plane.VAxis.ToVector());+ var corners = loop.Select(x => StartOf(shapes[x.Edge], x.Reversed)).Select(q => ((q - plane.Origin).Dot(u), (q - plane.Origin).Dot(v))).ToList();+ for (var i = 0; i < corners.Count; i++) { var (a, b) = (corners[i], corners[(i + 1) % corners.Count]); area += (a.Item1 * b.Item2 - b.Item1 * a.Item2) / 2; }+ foreach (var (edge, reversed) in loop)+ {+ var shape = shapes[edge]; if (!shape.Arc) continue;+ var r = (shape.Start - shape.Center!.Value).Length; var turn = (reversed ? shape.Normal * -1 : shape.Normal).Dot(n) > 0 ? 1 : -1;+ area += turn * r * r / 2 * (shape.Sweep - double.Sin(shape.Sweep));+ }+ return sense * area;+ }+ var (origin, axis, x0) = face.Kind == SurfaceGeometryKind.Cylinder+ ? (face.Surface.Cylinder!.Value.Origin, face.Surface.Cylinder!.Value.Axis.ToVector(), face.Surface.Cylinder!.Value.XAxis.ToVector())+ : (face.Surface.Cone!.Value.Apex, face.Surface.Cone!.Value.Axis.ToVector(), face.Surface.Cone!.Value.XAxis());+ var theta = double.Atan2((StartOf(shapes[loop[0].Edge], loop[0].Reversed) - origin).Dot(axis.Cross(x0)), (StartOf(shapes[loop[0].Edge], loop[0].Reversed) - origin).Dot(x0));+ var chart = new List<(double T, double H)>();+ foreach (var (edge, reversed) in loop)+ {+ var shape = shapes[edge];+ chart.Add((theta, (StartOf(shape, reversed) - origin).Dot(axis)));+ if (shape.Arc) theta += shape.Sweep * ((reversed ? shape.Normal * -1 : shape.Normal).Dot(axis) > 0 ? 1 : -1);+ }+ for (var i = 0; i < chart.Count; i++) { var (a, b) = (chart[i], chart[(i + 1) % chart.Count]); area += (a.T * b.H - b.T * a.H) / 2; }+ return sense * area;+ }++ private static Point3D StartOf(Shape shape, bool reversed) => reversed ? shape.End : shape.Start;++ /// <summary>Vertex positions, falling back to the curve's ends where a body leaves a vertex unplaced.</summary>+ private static Dictionary<VertexId, Point3D> VertexPoints(BrepBody body)+ {+ var points = new Dictionary<VertexId, Point3D>();+ foreach (var vertex in body.Topology.Vertices) if (body.TryGetVertexPoint(vertex.Id, out var p)) points[vertex.Id] = p;+ foreach (var edge in body.Topology.Edges)+ {+ if (points.ContainsKey(edge.StartVertexId) && points.ContainsKey(edge.EndVertexId)) continue;+ if (!body.Bindings.TryGetEdgeBinding(edge.Id, out var b) || b.TrimInterval is not { } t || !body.Geometry.TryGetCurve(b.CurveGeometryId, out var curve) || curve is null) continue;+ Point3D? At(double s) => curve.Kind switch { CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(s), CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(s), _ => null };+ var (first, last) = b.OrientedEdgeSense ? (t.Start, t.End) : (t.End, t.Start);+ if (!points.ContainsKey(edge.StartVertexId) && At(first) is { } a) points[edge.StartVertexId] = a;+ if (!points.ContainsKey(edge.EndVertexId) && At(last) is { } z) points[edge.EndVertexId] = z;+ }+ return points;+ }++ private static Shape? ShapeOf(BrepBody body, Edge edge, Dictionary<VertexId, Point3D> points)+ {+ if (!body.Bindings.TryGetEdgeBinding(edge.Id, out var binding) || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) || curve is null) return null;+ var (start, end) = (points[edge.StartVertexId], points[edge.EndVertexId]);+ switch (curve.Kind)+ {+ case CurveGeometryKind.Line3:+ return (end - start).Length > 0 ? new Shape(start, end, null, Vector3D.Zero, 0) : null;+ case CurveGeometryKind.Circle3:+ {+ var circle = curve.Circle3!.Value; var c = circle.Center; var n = circle.Normal.ToVector();+ var span = binding.TrimInterval is { } t ? double.Abs(t.End - t.Start) : Turn;+ if (edge.StartVertexId == edge.EndVertexId)+ return new Shape(start, start, c, binding.OrientedEdgeSense ? n : n * -1, Turn);+ var forward = Angle(start - c, end - c, n);+ if (double.Abs(forward - span) < 1e-6) return new Shape(start, end, c, n, forward);+ if (double.Abs(Turn - forward - span) < 1e-6) return new Shape(start, end, c, n * -1, Turn - forward);+ return null;+ }+ default: return null;+ }+ }++ /// <summary>The face runs along the edge: a plane containing its line, a cylinder around a parallel axis; or+ /// around the circle's axis: a plane across it, a cylinder or cone on it.</summary>+ private static bool Shares(Support face, Shape shape, double tol)+ {+ var s = face.Surface;+ if (!shape.Arc)+ {+ var d = Unit(shape.End - shape.Start);+ return face.Kind switch+ {+ SurfaceGeometryKind.Plane => double.Abs(s.Plane!.Value.Normal.ToVector().Dot(d)) < 1e-9,+ SurfaceGeometryKind.Cylinder => s.Cylinder!.Value.Axis.ToVector().Cross(d).Length < 1e-9,+ _ => false,+ };+ }+ var (c, n) = (shape.Center!.Value, shape.Normal);+ bool OnAxis(Point3D origin, Vector3D axis) => axis.Cross(n).Length < 1e-9 && ((c - origin) - axis * (c - origin).Dot(axis)).Length <= tol;+ return face.Kind switch+ {+ SurfaceGeometryKind.Plane => s.Plane!.Value.Normal.ToVector().Cross(n).Length < 1e-9,+ SurfaceGeometryKind.Cylinder => OnAxis(s.Cylinder!.Value.Origin, s.Cylinder!.Value.Axis.ToVector()),+ _ => OnAxis(s.Cone!.Value.Apex, s.Cone!.Value.Axis.ToVector()),+ };+ }++ /// <summary>The ball's cross-section at a centre: the arc from one contact to the other the short way round.</summary>+ private static Shape Cross(Point3D a, Point3D b, Point3D centre, Vector3D tangent)+ {+ var sweep = Angle(a - centre, b - centre, tangent);+ return sweep <= double.Pi ? new Shape(a, b, centre, tangent, sweep) : new Shape(a, b, centre, tangent * -1, Turn - sweep);+ }++ private static Point3D Project(Point3D p, Shape arc) => arc.Center!.Value + Unit(Flatten(p - arc.Center!.Value, arc.Normal)) * (arc.Start - arc.Center!.Value).Length;++ private static Point3D Axial(Point3D p, Shape arc) => arc.Center!.Value + arc.Normal * (p - arc.Center!.Value).Dot(arc.Normal);++ private static Vector3D Flatten(Vector3D v, Vector3D n) => v - n * v.Dot(n);++ /// <summary>Angle from a to b about n, in [0, 2π).</summary>+ private static double Angle(Vector3D a, Vector3D b, Vector3D n)+ {+ var (fa, fb) = (Flatten(a, n), Flatten(b, n));+ var angle = double.Atan2(n.Dot(fa.Cross(fb)), fa.Dot(fb));+ return angle < -1e-12 ? angle + Turn : double.Max(angle, 0);+ }++ private static Point3D Rotate(Point3D p, Point3D centre, Vector3D n, double angle)+ {+ var axial = centre + n * (p - centre).Dot(n); var r = p - axial; var y = n.Cross(r);+ return axial + r * double.Cos(angle) + y * double.Sin(angle);+ }++ private static double Area(List<(double X, double Y)> p)+ {+ var area = 0d;+ for (var i = 0; i < p.Count; i++) { var (a, b) = (p[i], p[(i + 1) % p.Count]); area += a.X * b.Y - b.X * a.Y; }+ return area / 2;+ }++ private static bool Crosses((double X, double Y) p, (double X, double Y) q, (double X, double Y) r, (double X, double Y) s, double tol)+ {+ double Cross2((double X, double Y) o, (double X, double Y) a, (double X, double Y) b) => (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X);+ var (d1, d2, d3, d4) = (Cross2(r, s, p), Cross2(r, s, q), Cross2(p, q, r), Cross2(p, q, s));+ var eps = tol * tol;+ return (d1 > eps && d2 < -eps || d1 < -eps && d2 > eps) && (d3 > eps && d4 < -eps || d3 < -eps && d4 > eps);+ }++ private static Vector3D Unit(Vector3D v) => v * (1 / v.Length);++ private static Vector3D Perpendicular(Vector3D n) => Unit(double.Abs(n.X) < 0.9 ? n.Cross(new Vector3D(1, 0, 0)) : n.Cross(new Vector3D(0, 1, 0)));++ private static string Article(SurfaceGeometryKind kind) => kind.ToString().ToLowerInvariant();++ private static Vector3D XAxis(this ConeSurface cone) => cone.Evaluate(0, 1) - (cone.Apex + cone.Axis.ToVector()) is var r && r.Length > 0 ? r * (1 / r.Length) : Perpendicular(cone.Axis.ToVector());++ private static Outcome Refuse(string code, string message) => new() { Refusal = new(code, message) };++ private static Outcome TooLarge(double radius, string why) => Refuse(UniformRounding.TooLargeCode, $"radius {radius:G6} mm does not fit: {why}");+}diff --git a/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs b/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.csindex 424d84e4..bfa516cc 100644--- a/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs+++ b/Aetheris.Kernel.Core/Brep/Blends/UniformRounding.cs@@ -8,23 +8,39 @@ 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.+/// a morphological opening (erode by the radius, then sweep the ball over what is left). Convex bodies bounded by+/// planes are built exactly that way, from the erosion, by <see cref="ConvexStockPrimitives"/>' ball sweep, which+/// also opens corners of any valence. Other bodies of plane, cylinder and cone faces with convex edges are built by+/// the local rolling ball on their own faces (<see cref="LocalRounding"/>): cylinders along lines, tori around+/// circles, spheres at three-edge corners. 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";+ internal const string TooLargeCode = "uniform-rounding-radius-too-large";++ /// <summary>The local route, with a radius that does not fit refused alongside the largest that does (by+ /// bisection: every check that refuses a radius also refuses every larger one).</summary>+ private static KernelResult<BrepBody> Local(BrepBody body, double radius)+ {+ var outcome = LocalRounding.Round(body, radius);+ if (outcome.Body is not null) return KernelResult<BrepBody>.Success(outcome.Body);+ var refusal = outcome.Refusal!;+ if (refusal.Code != TooLargeCode) return Failure(refusal.Code, refusal.Message);+ var (lo, hi) = (0d, radius);+ for (var i = 0; i < 40; i++) { var mid = 0.5 * (lo + hi); if (LocalRounding.Round(body, mid).Body is not null) lo = mid; else hi = mid; }+ return Failure(refusal.Code, $"{refusal.Message}; the largest that fits is under {hi:G6} mm");+ }+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.+ // Edges first, so the message names what the body is made of, not only that a face is curved: spline and+ // elliptical edges 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();@@ -40,34 +56,37 @@ public static class UniformRounding"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");+ if (curved.Any(x => x.Kind != CurveGeometryKind.Circle3))+ {+ var other = curved.First(x => x.Kind != CurveGeometryKind.Circle3);+ return Failure("uniform-rounding-curved-edge-unsupported", $"rounding every edge does not support {other.Kind} edges (edge {other.Edge.Value}); lines and circles only for now");+ }++ // Convex and bounded by planes: the opening, erode then sweep, which also opens corners where four or more+ // faces meet unevenly. Anything else: the local rolling ball on the body's own faces.+ var planar = curved.Length == 0 && body.Topology.Faces.All(f => body.TryGetFaceSurfaceGeometry(f.Id, out var g) && g?.Plane is not null);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 points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : (Point3D?)null).Where(p => p is not null).Select(p => p!.Value).ToArray();+ if (points.Length == 0) return Local(body, radius);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)+ if (planar){- 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 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))+ {+ body.TryGetFaceSurfaceGeometry(face.Id, out var surface);+ var plane = surface!.Plane!.Value; 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)));+ }+ planar = planes.All(q => points.All(p => q.Normal.Dot(p - Point3D.Origin) <= q.Offset + tolerance));}+ if (!planar) return Local(body, radius);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)");+ return Failure(TooLargeCode, $"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)diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex 2064b56a..1c70ae7d 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -1392,7 +1392,8 @@ public static class SurfaceMeshIrTessellatorprivate static SurfacePatch? BuildFourSidedPatch(FaceId faceId, bool sameSense, SurfaceMeshSupport support, IReadOnlyList<LoopId> loops, FourSidedBoundary boundary,- Func<Point3D, (double U, double V)?> project, Func<double, double, Point3D> evaluate, List<SurfaceMeshVertex> vertices, ref int nextVertexId, bool hasPeriodicUSeam)+ Func<Point3D, (double U, double V)?> project, Func<double, double, Point3D> evaluate, List<SurfaceMeshVertex> vertices, ref int nextVertexId, bool hasPeriodicUSeam,+ bool periodicV = false){var columns = boundary.Top.Count;var rows = boundary.Left.Count;@@ -1409,7 +1410,8 @@ public static class SurfaceMeshIrTessellator{var top = topUv[column]!.Value; var bottom = bottomUv[column]!.Value;var u = InterpolateAngle(top.U, bottom.U, t);- var v = top.V + ((bottom.V - top.V) * t);+ // A torus's V is its minor angle: across a tube that crosses V = 0 the short way round is the patch.+ var v = periodicV ? InterpolateAngle(top.V, bottom.V, t) : top.V + ((bottom.V - top.V) * t);var point = evaluate(u, v);grid[row, column] = new SurfaceMeshVertex(nextVertexId++, point, u, v);vertices.Add(grid[row, column]);@@ -1577,8 +1579,9 @@ public static class SurfaceMeshIrTessellatorList<SurfaceMeshVertex> vertices,ref int nextVertexId){- // A swept bend has two closed minor rings and one bounded major arc- // used twice as a seam. Those rings do not imply a complete torus.+ // Two closed rings and one bounded arc used twice as a seam: a swept+ // bend (minor rings, major seam) or a rounded rim (major rings, minor+ // seam). Those rings do not imply a complete torus.for (var offset = 0; offset < 4; offset++){if (!TryGetFourSidedBoundary(body, faceId, plans, out var band, offset, allowClosed: true)@@ -1590,10 +1593,23 @@ public static class SurfaceMeshIrTessellatorvar ring = band.Top.Select(sample => TryProjectPointToTorusUv(torus, sample.Position)).ToArray();var seam = band.Left.Select(sample => TryProjectPointToTorusUv(torus, sample.Position)).ToArray();if (ring.Any(uv => uv is null) || seam.Any(uv => uv is null)) return null;- // Validate ring correspondence before adding any vertices.- for (var column = 0; column < ring.Length; column++)- if ((torus.Evaluate(seam[^1]!.Value.U, ring[column]!.Value.V) - band.Bottom[column].Position).Length > 1e-7d)- return null;+ // The rings are minor circles and the seam a major arc (a swept bend), or the rings are major circles+ // around the axis and the seam a minor arc (a rim rounded all the way round). Each grid point is the+ // ring's parameter along it and the seam's across.+ (double U, double V) At(int row, int column, bool majorRings) =>+ majorRings ? (ring[column]!.Value.U, seam[row]!.Value.V) : (seam[row]!.Value.U, ring[column]!.Value.V);+ bool? layout = null;+ foreach (var majorRings in new[] { false, true })+ {+ var matches = true;+ for (var column = 0; column < ring.Length && matches; column++)+ {+ var (u, v) = At(seam.Length - 1, column, majorRings);+ matches = (torus.Evaluate(u, v) - band.Bottom[column].Position).Length <= 1e-7d;+ }+ if (matches) { layout = majorRings; break; }+ }+ if (layout is not { } majorRingLayout) return null;var bandGrid = new int[seam.Length, ring.Length];for (var row = 0; row < seam.Length; row++)for (var column = 0; column < ring.Length; column++)@@ -1604,7 +1620,7 @@ public static class SurfaceMeshIrTessellatorelse if (column == ring.Length - 1) bandGrid[row, column] = band.Right[row].Id;else{- var u = seam[row]!.Value.U; var v = ring[column]!.Value.V;+ var (u, v) = At(row, column, majorRingLayout);bandGrid[row, column] = nextVertexId++;vertices.Add(new SurfaceMeshVertex(bandGrid[row, column], torus.Evaluate(u, v), u, v));}@@ -1614,13 +1630,12 @@ public static class SurfaceMeshIrTessellatorfor (var column = 0; column < ring.Length - 1; column++){int[] ids = [bandGrid[row,column],bandGrid[row,column+1],bandGrid[row+1,column+1],bandGrid[row+1,column]];- // Columns follow minor V and rows major U. Their traversal- // can oppose the analytic support orientation; resolve the- // chart winding before applying the authoritative face sign.- var u = seam[row]!.Value.U; var v = ring[column]!.Value.V;+ // The traversal can oppose the analytic support orientation; resolve the chart winding before+ // applying the authoritative face sign.+ var (u, v) = At(row, column, majorRingLayout);var p = torus.Evaluate(u, v);- var cross = (torus.Evaluate(u, ring[column+1]!.Value.V) - p)- .Cross(torus.Evaluate(seam[row+1]!.Value.U, v) - p);+ var along = At(row, column + 1, majorRingLayout); var across = At(row + 1, column, majorRingLayout);+ var cross = (torus.Evaluate(along.U, along.V) - p).Cross(torus.Evaluate(across.U, across.V) - p);if (cross.Dot(torus.Normal(u, v).ToVector()) < 0) Array.Reverse(ids);bandCells.Add(new QuadCell(Orient(ids, sameSense)));}@@ -1636,7 +1651,7 @@ public static class SurfaceMeshIrTessellator{return BuildFourSidedPatch(faceId, sameSense, new SurfaceMeshSupport(SurfaceMeshSupportKind.Torus, Torus: torus), body.GetLoopIds(faceId), bounded,point => TryProjectPointToTorusUv(torus, point), (u, v) => torus.Evaluate(u, v), vertices, ref nextVertexId,- hasPeriodicUSeam: false);+ hasPeriodicUSeam: false, periodicV: true);}if (body.GetLoopIds(faceId).Count != 1){diff --git a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.csindex 308435dd..657c2c1e 100644--- a/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Experiments/BlendNetworkRemovalTests.cs@@ -160,6 +160,39 @@ public sealed class BlendNetworkRemovalTests(ITestOutputHelper output)Assert.Equal(Points(plain), Points(body));}+ /// <summary>Bodies with circular edges rounded whole, then every strip and corner removed: the body again.+ /// The original walls are kept (they are faces the body was built with, not blends).</summary>+ [Theory]+ [InlineData("cylinder-rounded")]+ [InlineData("frustum-rounded")]+ [InlineData("box-hole-rounded")]+ [InlineData("d-profile-rounded")]+ public void RemovingWholeBodyRounding_ReturnsTheBody(string name)+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/UniformRounding", name + ".firmament"));+ var finished = Import(source);+ var plain = Import(Regex.Replace(source, @"EdgeFinish<Fillet>[^{}]*\{[^{}]*\}", ""));+ var walls = plain.Topology.Faces.Select(f => plain.TryGetFaceSurfaceGeometry(f.Id, out var g) ? g : null).Where(g => g is { Kind: not Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Plane }).ToArray();+ var keep = finished.Topology.Faces.Select(f => f.Id).Where(f => finished.TryGetFaceSurfaceGeometry(f, out var g) && walls.Any(w => w!.Kind == g!.Kind && Same(w, g))).ToHashSet();+ var probe = BlendRegionProbe.Run(name, finished, new BlendRegionProbe.Options(Keep: keep));+ var blends = probe.Regions.SelectMany(r => r.Faces).Select(f => new FaceId(f)).ToHashSet();+ Assert.Equal(finished.Topology.Faces.Count() - plain.Topology.Faces.Count(), 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.Faces.Count(), body.Topology.Faces.Count());+ Assert.Equal(plain.Topology.Edges.Count(), body.Topology.Edges.Count());+ output.WriteLine($"{name}: removed {blends.Count} faces; plain {Kinds(plain)}; body {Kinds(body)}");+ }++ private static bool Same(Aetheris.Kernel.Core.Geometry.SurfaceGeometry? a, Aetheris.Kernel.Core.Geometry.SurfaceGeometry? b) => (a, b) switch+ {+ ({ Cylinder: { } x }, { Cylinder: { } y }) => Math.Abs(x.Radius - y.Radius) < 1e-9 && x.Axis.ToVector().Cross(y.Axis.ToVector()).Length < 1e-9,+ ({ Cone: { } x }, { Cone: { } y }) => Math.Abs(x.SemiAngleRadians - y.SemiAngleRadians) < 1e-9,+ _ => false,+ };+/// <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.csindex 9ec9fa1b..c38dcc88 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/UniformRoundingRouteTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/UniformRoundingRouteTests.cs@@ -96,11 +96,43 @@ public sealed class UniformRoundingRouteTestsAssert.Contains("concave edge", message);}+ /// <summary>Bodies with circular edges: every rim a torus, every line edge a cylinder, every three-edge corner a+ /// sphere, read back by the rolling-ball certificate at the radius, exported and imported again.</summary>+ [Theory]+ [InlineData("cylinder-rounded", 2, 2, 1, 2, 0, 0, 2)]+ [InlineData("frustum-rounded", 1.5, 2, 0, 2, 0, 1, 2)]+ [InlineData("box-hole-rounded", 1, 6, 13, 2, 8, 0, 14)]+ [InlineData("d-profile-rounded", 1, 3, 5, 2, 4, 0, 6)]+ public void CircularEdges_RoundToTori(string name, double radius, int planes, int cylinders, int tori, int spheres, int cones, int edges)+ {+ var built = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/UniformRounding", name + ".firmament")));+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics.Select(d => d.Message)));+ var body = Step242Importer.ImportBody(built.Value.StepText).Value;+ 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((planes, cylinders, tori, spheres, cones),+ (Count(SurfaceGeometryKind.Plane), Count(SurfaceGeometryKind.Cylinder), Count(SurfaceGeometryKind.Torus), Count(SurfaceGeometryKind.Sphere), Count(SurfaceGeometryKind.Cone)));+ var read = BlendRecognition.Recognize(body);+ var strips = read.Where(r => r.Role == BlendFaceRole.Strip).ToArray();+ Assert.Equal(edges, strips.Length); // one per edge of the body before rounding+ Assert.All(strips, s => Assert.Equal(radius, s.Blend!.Size, 9));+ Assert.Equal(spheres, read.Count(r => r.Role == BlendFaceRole.Joiner));+ Assert.True(BrepMassProperties.Evaluate(body).AbsoluteVolume > 0);+ }++ /// <summary>A bore 2 mm from a wall: the bore's rim torus and the wall's edge strip meet at a 1 mm radius, so+ /// 1 mm is refused (it would pinch the top face to nothing) and the reported fit is under 1 mm.</summary>[Fact]- public void CircularEdges_RefuseByName()+ public void BoreNearAWall_RefusesTheRadiusThatPinchesTheTop(){- 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);+ string Source(double r) => $"Model Near {{ units: mm\n Box stock {{ size: [20mm, 20mm, 20mm] }}\n Modify stock {{ Hole<Shaft> Bore {{ on: +Z; center: [5mm, 0mm]; diameter: 6mm; end: ThroughAll }} EdgeFinish<Fillet> Round {{ target: AllEdges; radius: {r}mm }} }} }}";+ var message = Assert.Single(FirmamentBuildAndExport.CompileSource(Source(1)).Diagnostics).Message;+ Assert.Contains("uniform-rounding-radius-too-large", message);+ Assert.Contains("reaches face", message);+ Assert.Matches(@"largest that fits is under (1|0\.99\d*) mm", message);+ var fits = FirmamentBuildAndExport.CompileSource(Source(0.9));+ Assert.True(fits.IsSuccess, string.Join("\n", fits.Diagnostics.Select(d => d.Message)));+ Assert.True(BrepMassProperties.Evaluate(Step242Importer.ImportBody(fits.Value.StepText).Value).AbsoluteVolume > 0);}/// <summary>The diagnostic an LLM or a person feeds back: the body has splines, how many, and which.</summary>diff --git a/docs/development/reports/2026-11/UNIFORM-ROUNDING.md b/docs/development/reports/2026-11/UNIFORM-ROUNDING.mdindex fbed6321..ad24ff5b 100644--- a/docs/development/reports/2026-11/UNIFORM-ROUNDING.md+++ b/docs/development/reports/2026-11/UNIFORM-ROUNDING.md@@ -55,3 +55,45 @@ Chamfer-all and several AllEdges finishes keep the old refusal.- 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.++## Stage 1: circular edges (local rolling ball)++`LocalRounding` builds the rounding on the body's own face graph for small r:+faces keep their surfaces and are re-trimmed; each convex edge's strip is the+tube around the ball centre's path (cylinder around a line, torus around a+circle); each three-edge corner a sphere. Ball centres: 3×3 Newton on the faces'+distance functions at corners (exact in one step on planes), 2×2 in the meridian+for closed circles, at the seam's angle so rebuilt seams stay generators.+Convex planar bodies still go to the opening (it handles uneven high-valence+corners); `LocalRounding_MatchesTheOpening` checks the two agree (counts,+points, volume to 1e-4) on box, tetrahedron, dodecahedron and a skew prism.++Found on the way:++- Input loops are not oriented: STEP-imported and primitive bodies walk shared+ edges the same way on both faces, and point containment answers Boundary even+ at a tetrahedron's centre (primitives only). Orientation and convexity are+ therefore computed, not read: each loop's exact signed area (shoelace plus+ circular segments in the plane; the (angle, height) chart on cylinders and+ cones, where circles and generators are straight) sets outer loops CCW about+ the outward normal, and convexity follows from the oriented coedges. Output is+ consistently oriented (every edge used once each way), STEP round trip too.+- `BrepPrimitives.CreateCylinder` leaves seam vertices unplaced; positions come+ from the curves' ends.+- A ball that only touches a third face pinches a face to nothing (a bore 2 mm+ from a wall at r = 1 built with zero volume); touching is now refused.+- SurfaceMeshIR: a rim rounded all the way round is a torus band whose closed+ rings run around the major direction (the swept-bend case had only minor+ rings); and the four-sided torus patch interpolated V (the minor angle)+ linearly, folding any strip whose tube crosses V = 0 (the bottom rim of an+ extruded arc). Both fixed; the four fixtures mesh watertight and outward.++Results: `fixtures/Regression/UniformRounding` — cylinder (2 tori), frustum (2+tori on a cone), block with a through bore (12 cylinder strips, 2 tori, 8+spheres), D-profile (4 cylinder strips, 2 tori, 4 spheres). Each validates and+builds through the CLI, round-trips STEP, meshes watertight, reads back by the+certificate at r, and Remove(Round(x)) restores x's faces and edges. Fit sizes+are exact where checkable: a Ø6 bore in a 20 mm block refuses r = 4 "under+3.5 mm" (10 − r − 3 = r); a bore 2 mm from a wall refuses r = 1 "under 1 mm".++Next: concave edges (stage 2), mixed vertices and tangent junctions (stage 3).diff --git a/docs/public/firmament/geometry.md b/docs/public/firmament/geometry.mdindex ec7c18a9..47f9d583 100644--- a/docs/public/firmament/geometry.md+++ b/docs/public/firmament/geometry.md@@ -3,10 +3,12 @@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` 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.+stock, and of other bodies whose faces are planes, cylinders and cones and whose+edges are all convex: extruded polygons and line-and-arc profiles, cylinders,+frustums, blocks with through holes. The body is built without the finish and+then rounded whole. Spline and elliptical edges, concave edges, tangent+junctions and corners where more than three edges meet on a curved body are+refused at the finish with what was found.Ellipsoid BRep export uses exact rational quadratic patches and reimports them asnative 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.mdindex b85b96e9..2b6c7310 100644--- a/docs/public/reference/diagnostics.md+++ b/docs/public/reference/diagnostics.md@@ -130,7 +130,7 @@ Common recovery patterns:| `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. 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. |+| `firmament-uniform-rounding` | Rounding every edge of the built body was refused; the message names why. `uniform-rounding-spline-edge-unsupported` / `-elliptical-edge-unsupported`: the body has those edges (count and ids given); use a local `EdgeFinish` on the edges you need. `-concave-unsupported`: the named edge is concave. `-tangent-edge-unsupported`: the named faces meet tangentially. `-curved-face-unsupported`: a face is not a plane, cylinder or cone. `-edge-unsupported` / `-vertex-unsupported`: the named edge's faces do not share its line or axis, or the named corner joins other than three edges. `-radius-too-large` / `-radius-consumes-faces`: the message says what the radius used up or where the ball reached another face; 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.mdindex 77657224..2ee8f45c 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>`, or any convex body bounded by planes | `target: AllEdges`, fillet only: every edge |+| An untouched Box or `Polyhedron<N>`, or any body of plane, cylinder and cone faces with convex edges | `target: AllEdges`, fillet only: every edge |The details that trip people up:@@ -167,14 +167,18 @@ The details that trip people up:- **Whole-body rounding.** `target: AllEdges` needs one fillet. On Box andPolyhedron stock the radius must be below the stock's inradius. On any otherbody, 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.+ rounded: each straight edge becomes a cylinder strip, each circular edge (a+ cylinder's rim, a hole's rim, an arc in an extruded profile) a torus, and each+ corner a sphere. Faces may be planes, cylinders and cones; every edge must be+ convex. On convex bodies bounded by planes, corners where four or more faces+ meet unevenly open into short strips, as a rolled ball would leave them; on+ curved bodies each corner must join three edges. Not supported yet: spline or+ elliptical edges (common on imported parts and on planes cut at an angle+ through cylinders), concave edges, and faces meeting tangentially; each is+ refused at the finish, naming the edges found. A radius that does not fit,+ for instance one whose ball would reach a nearby hole, 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 cornersneed not be right angles; tangent line/arc rims and arcs closed by a chord alsowork. `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.mdindex 59f6252e..07086108 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 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. |+| Uniform fillet (all edges) | Bounded | `EdgeFinish<Fillet> { target: AllEdges; radius: ... }` on untouched Box or regular Polyhedron stock, and on any other body of plane, cylinder and cone faces with convex edges: line edges become cylinder strips, circular edges tori, corners spheres, exact. Spline and elliptical edges, concave and tangent edges 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.mdindex 1bb09ff6..5e6852c3 100644--- a/fixtures/Regression/ConvexStock/README.md+++ b/fixtures/Regression/ConvexStock/README.md@@ -9,5 +9,5 @@ reimport, full face display, mesh closure/orientation, and validate/build agreemInvalid mutations are tested separately without rewriting these accepted sources.`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+other bodies are rounded after they are built (see `../UniformRounding` and the FirmamentUniformRoundingRoute tests). It never silently ignores other operations.diff --git a/fixtures/Regression/UniformRounding/README.md b/fixtures/Regression/UniformRounding/README.mdnew file mode 100644index 00000000..a253b501--- /dev/null+++ b/fixtures/Regression/UniformRounding/README.md@@ -0,0 +1,11 @@+# Rounding every edge of bodies with circular edges++Each source fillets every edge of a body that is not Box or Polyhedron stock, so+the body is built first and then rounded whole: `cylinder-rounded` (two rim tori),+`frustum-rounded` (rim tori on a cone), `box-hole-rounded` (a through bore whose+rims round to tori next to the block's cylinder strips and sphere corners) and+`d-profile-rounded` (an extruded line-and-arc profile: tori along the arc, a+cylinder down each line-to-arc edge, spheres at the four corners).++The Firmament UniformRoundingRoute tests build them; the BlendNetworkRemoval+experiments remove the rounding again.diff --git a/fixtures/Regression/UniformRounding/box-hole-rounded.firmament b/fixtures/Regression/UniformRounding/box-hole-rounded.firmamentnew file mode 100644index 00000000..6a12e6ec--- /dev/null+++ b/fixtures/Regression/UniformRounding/box-hole-rounded.firmament@@ -0,0 +1,8 @@+Model RoundedBlock {+ units: mm+ Box stock { size: [20mm, 20mm, 20mm] }+ Modify stock {+ Hole<Shaft> Bore { on: +Z; center: [0mm, 0mm]; diameter: 6mm; end: ThroughAll }+ EdgeFinish<Fillet> Round { target: AllEdges; radius: 1mm }+ }+}diff --git a/fixtures/Regression/UniformRounding/cylinder-rounded.firmament b/fixtures/Regression/UniformRounding/cylinder-rounded.firmamentnew file mode 100644index 00000000..a3b3951f--- /dev/null+++ b/fixtures/Regression/UniformRounding/cylinder-rounded.firmament@@ -0,0 +1,5 @@+Model RoundedCan {+ units: mm+ Cylinder stock { radius: 10mm; height: 20mm }+ Modify stock { EdgeFinish<Fillet> Round { target: AllEdges; radius: 2mm } }+}diff --git a/fixtures/Regression/UniformRounding/d-profile-rounded.firmament b/fixtures/Regression/UniformRounding/d-profile-rounded.firmamentnew file mode 100644index 00000000..be871364--- /dev/null+++ b/fixtures/Regression/UniformRounding/d-profile-rounded.firmament@@ -0,0 +1,12 @@+Model RoundedD {+ units: mm+ Path Outline {+ start: Point2(10mm, 0mm)+ heading: 90deg+ Arc Round { turn: 180deg; radius: 10mm }+ Close Flat+ }+ Profile Section from Outline+ Struct Body { Extrude Stock { profile: Section; from: 0mm; to: 8mm } }+ Modify Body { EdgeFinish<Fillet> Edges { target: AllEdges; radius: 1mm } }+}diff --git a/fixtures/Regression/UniformRounding/frustum-rounded.firmament b/fixtures/Regression/UniformRounding/frustum-rounded.firmamentnew file mode 100644index 00000000..93cde38f--- /dev/null+++ b/fixtures/Regression/UniformRounding/frustum-rounded.firmament@@ -0,0 +1,5 @@+Model RoundedFrustum {+ units: mm+ Frustum stock { bottomRadius: 12mm; topRadius: 6mm; height: 15mm }+ Modify stock { EdgeFinish<Fillet> Round { target: AllEdges; radius: 1.5mm } }+}