diff --git a/OpenNest.Core/Geometry/MinimumEnclosingCircle.cs b/OpenNest.Core/Geometry/MinimumEnclosingCircle.cs new file mode 100644 index 00000000..62a43651 --- /dev/null +++ b/OpenNest.Core/Geometry/MinimumEnclosingCircle.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenNest.Geometry +{ + /// + /// Smallest circle containing every point (Welzl's algorithm, expected linear time). Points are + /// visited in a fixed shuffled order, so the result is repeatable. + /// + public static class MinimumEnclosingCircle + { + public static Circle Compute(IEnumerable points) + { + var shuffled = points.ToList(); + + if (shuffled.Count == 0) + throw new ArgumentException("At least one point is required.", nameof(points)); + + var random = new Random(0); + + for (var i = shuffled.Count - 1; i > 0; i--) + { + var j = random.Next(i + 1); + (shuffled[i], shuffled[j]) = (shuffled[j], shuffled[i]); + } + + var center = shuffled[0]; + var radius = 0.0; + + for (var i = 1; i < shuffled.Count; i++) + { + if (Contains(center, radius, shuffled[i])) + continue; + + center = shuffled[i]; + radius = 0; + + for (var j = 0; j < i; j++) + { + if (Contains(center, radius, shuffled[j])) + continue; + + center = (shuffled[i] + shuffled[j]) * 0.5; + radius = center.DistanceTo(shuffled[i]); + + for (var k = 0; k < j; k++) + { + if (Contains(center, radius, shuffled[k])) + continue; + + (center, radius) = Circumcircle(shuffled[i], shuffled[j], shuffled[k]); + } + } + } + + // Rounding can leave a defining point a hair outside; grow to cover every point exactly. + radius = shuffled.Max(p => p.DistanceTo(center)); + + return new Circle(center, radius); + } + + private static bool Contains(Vector center, double radius, Vector point) => + point.DistanceTo(center) <= radius * (1 + 1e-12) + 1e-12; + + private static (Vector Center, double Radius) Circumcircle(Vector a, Vector b, Vector c) + { + var bx = b.X - a.X; + var by = b.Y - a.Y; + var cx = c.X - a.X; + var cy = c.Y - a.Y; + var d = 2 * (bx * cy - by * cx); + + if (System.Math.Abs(d) <= double.Epsilon) + { + // Collinear: the circle on the two farthest-apart points covers the third. + var pairs = new[] { (a, b), (a, c), (b, c) }; + var (p, q) = pairs.OrderByDescending(pair => pair.Item1.DistanceTo(pair.Item2)).First(); + var mid = (p + q) * 0.5; + return (mid, mid.DistanceTo(p)); + } + + var b2 = bx * bx + by * by; + var c2 = cx * cx + cy * cy; + var center = new Vector(a.X + (cy * b2 - by * c2) / d, a.Y + (bx * c2 - cx * b2) / d); + + return (center, center.DistanceTo(a)); + } + } +} diff --git a/OpenNest.Engine.Tests/CirclePacking/ItemCloneTests.cs b/OpenNest.Engine.Tests/CirclePacking/ItemCloneTests.cs index ab63948f..3b27650f 100644 --- a/OpenNest.Engine.Tests/CirclePacking/ItemCloneTests.cs +++ b/OpenNest.Engine.Tests/CirclePacking/ItemCloneTests.cs @@ -53,6 +53,19 @@ public class ItemCloneTests Assert.NotEqual(((Entity)item).Id, ((Entity)clone).Id); } + [Fact] + public void Clone_PreservesPackingGeometry() + { + var item = CreateItem(); + + var clone = Assert.IsType(item.Clone()); + + Assert.Equal(item.FillRatio, clone.FillRatio); + Assert.Equal(item.PartOffset, clone.PartOffset); + Assert.Equal(item.HoleOffset, clone.HoleOffset); + Assert.Equal(item.HoleRadius, clone.HoleRadius); + } + [Fact] public void Clone_PreservesRotation() { @@ -135,6 +148,10 @@ public class ItemCloneTests private static Item CreateItem() => new Item { PackingId = 42, + FillRatio = 0.85, + PartOffset = new Vector(-10, -20), + HoleOffset = new Vector(1, 0), + HoleRadius = 2, Radius = 5, Center = new Vector(10, 20), Rotation = RotationType.CCW, diff --git a/OpenNest.Engine.Tests/CirclePacking/ItemCreateTests.cs b/OpenNest.Engine.Tests/CirclePacking/ItemCreateTests.cs new file mode 100644 index 00000000..15a7706a --- /dev/null +++ b/OpenNest.Engine.Tests/CirclePacking/ItemCreateTests.cs @@ -0,0 +1,181 @@ +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Engine.CirclePacking; +using OpenNest.Engine.Jobs; +using OpenNest.Geometry; +using TestShapes = OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.CirclePacking; + +public class ItemCreateTests +{ + private const double Allowance = Item.FlattenAllowance; + + [Fact] + public void Disc_IsItsOwnCircleWithNoHole() + { + var item = Create(TestShapes.Disc(5)); + + AssertVector(new Vector(0, 0), item.Center, 1e-6); + Assert.InRange(item.Radius, 5 + Allowance, 5 + 2 * Allowance); + Assert.InRange(item.FillRatio, 0.999, 1.0); + Assert.Equal(0, item.HoleRadius); + Assert.Null(item.Hole); + } + + [Fact] + public void Ring_HoleIsConcentric() + { + var item = Create(TestShapes.Ring(10, 6)); + + var hole = Assert.IsType(item.Hole); + AssertVector(item.Center, hole.Center, 1e-6); + Assert.Equal(3 - Allowance, hole.Radius, 6); + } + + [Fact] + public void PartAwayFromOrigin_RecordsTheOffsetBackToItsOrigin() + { + var item = Create(FromEntities(new Circle(50, 20, 4))); + + AssertVector(new Vector(50, 20), item.Center, 1e-6); + AssertVector(new Vector(-50, -20), item.PartOffset, 1e-6); + } + + [Fact] + public void Gear_IsPackedByItsTipCircleAroundItsBore() + { + var entities = Gear(teeth: 20, tipRadius: 10, rootRadius: 9); + entities.Add(new Circle(0, 0, 3)); + + var item = Create(FromEntities(entities.ToArray())); + + AssertVector(new Vector(0, 0), item.Center, 1e-6); + Assert.Equal(10 + Allowance, item.Radius, 6); + Assert.InRange(item.FillRatio, 0.8, 0.95); + Assert.Equal(3 - Allowance, item.HoleRadius, 6); + AssertVector(new Vector(0, 0), item.HoleOffset, 1e-6); + } + + [Theory] + [InlineData(4, 2 / System.Math.PI)] + [InlineData(6, 0.827)] + public void RegularPolygon_FillRatioReflectsTheWastedCorners(int sides, double expected) + { + var item = Create(Polygon(radius: 10, segments: sides)); + + Assert.Equal(expected, item.FillRatio, 2); + } + + [Fact] + public void Obround_IsEnclosedEndToEnd() + { + var item = Create(TestShapes.Obround(20, 10)); + + Assert.InRange(item.Radius, 10 + Allowance, 10 + 2 * Allowance); + Assert.True(item.FillRatio < 0.7); + } + + [Fact] + public void BoltHoleFlange_UsesTheCenterBore() + { + var entities = new List { new Circle(0, 0, 10), new Circle(0, 0, 4) }; + + for (var i = 0; i < 4; i++) + { + var angle = i * System.Math.PI / 2; + entities.Add(new Circle(7 * System.Math.Cos(angle), 7 * System.Math.Sin(angle), 0.5)); + } + + var item = Create(FromEntities(entities.ToArray())); + + AssertVector(new Vector(0, 0), item.HoleOffset, 1e-6); + Assert.Equal(4 - Allowance, item.HoleRadius, 6); + } + + [Fact] + public void OffCenterRoundCutout_IsFoundAboutItsOwnCenter() + { + var item = Create(FromEntities(new Circle(0, 0, 10), new Circle(2, 0, 3))); + + AssertVector(new Vector(2, 0), item.Center + item.HoleOffset, 2e-3); + Assert.InRange(item.HoleRadius, 3 - Allowance - 2e-3, 3 - Allowance); + } + + [Fact] + public void SquareCutout_GivesItsInscribedDisc() + { + var entities = new List + { + new Circle(0, 0, 10), + new Line(-3, -3, 3, -3), new Line(3, -3, 3, 3), new Line(3, 3, -3, 3), new Line(-3, 3, -3, -3), + }; + + var item = Create(FromEntities(entities.ToArray())); + + AssertVector(new Vector(0, 0), item.HoleOffset, 1e-6); + Assert.Equal(3 - Allowance, item.HoleRadius, 6); + } + + [Fact] + public void Radii_BoundTheLayoutChecksFlattenedOutlines() + { + var geometry = JobPartGeometry.Read(PartGeometrySnapshot.FromProgram(TestShapes.Ring(10, 6))); + var item = Item.Create(geometry); + + var outer = geometry.Perimeter.ToPolygonWithTolerance(NestTolerances.ValidationOutline, circumscribe: true); + Assert.All(outer.Vertices, v => Assert.True(v.DistanceTo(item.Center) <= item.Radius)); + + var hole = Assert.IsType(item.Hole); + var inner = geometry.Cutouts[0].ToPolygonWithTolerance(NestTolerances.ValidationOutline); + Assert.All(inner.ToLines(), edge => Assert.True(edge.ClosestPointTo(hole.Center).DistanceTo(hole.Center) >= hole.Radius)); + } + + [Fact] + public void UnreadableSnapshot_GivesNoItem() + { + var open = new Program(); + open.Codes.Add(new RapidMove(0, 0)); + open.Codes.Add(new LinearMove(5, 0)); + + Assert.Null(Item.TryCreate(PartGeometrySnapshot.FromProgram(open))); + } + + private static Item Create(Program program) => + Assert.IsType(Item.TryCreate(PartGeometrySnapshot.FromProgram(program))); + + private static Program FromEntities(params Entity[] entities) => ConvertGeometry.ToProgram(entities.ToList()); + + private static Program Polygon(double radius, int segments) + { + var points = Enumerable.Range(0, segments) + .Select(i => 2 * System.Math.PI * i / segments) + .Select(a => (radius * System.Math.Cos(a), radius * System.Math.Sin(a))) + .ToArray(); + + return TestShapes.Polyline(points); + } + + /// Trapezoid teeth: each pitch rises from the root to a flat tip and back. + private static List Gear(int teeth, double tipRadius, double rootRadius) + { + var pitch = 2 * System.Math.PI / teeth; + var points = new List(); + + for (var k = 0; k < teeth; k++) + { + foreach (var (fraction, radius) in new[] { (0.0, rootRadius), (0.3, tipRadius), (0.5, tipRadius), (0.8, rootRadius) }) + { + var angle = (k + fraction) * pitch; + points.Add(new Vector(radius * System.Math.Cos(angle), radius * System.Math.Sin(angle))); + } + } + + return points.Select((p, i) => (Entity)new Line(p, points[(i + 1) % points.Count])).ToList(); + } + + private static void AssertVector(Vector expected, Vector actual, double tolerance) + { + Assert.True(expected.DistanceTo(actual) <= tolerance, $"Expected {expected}, got {actual}."); + } +} diff --git a/OpenNest.Engine/CirclePacking/Item.cs b/OpenNest.Engine/CirclePacking/Item.cs index a2186f25..29af13e4 100644 --- a/OpenNest.Engine/CirclePacking/Item.cs +++ b/OpenNest.Engine/CirclePacking/Item.cs @@ -1,12 +1,86 @@ +using System.Linq; +using OpenNest.Engine.Jobs; using OpenNest.Geometry; namespace OpenNest.Engine.CirclePacking { + /// + /// A part as the circle packer sees it: its material outline's minimum enclosing circle, and + /// the largest disc inside it that is clear of material. Any shape can be packed this way; a + /// low only means the circle wastes more around the part. Radii are + /// what the layout check sees, so packing is never more lenient than the check: the outline + /// circle covers the check's outward-flattened perimeter, and the hole stays inside its + /// inward-flattened cutouts. + /// internal class Item : Circle { + /// How far the layout check's flattening may move a contour from its arcs. + public const double FlattenAllowance = NestTolerances.ValidationOutline; + // Optional caller-supplied packing identifier; not assigned automatically; preserved by clones. public int PackingId { get; set; } + /// Material outline area divided by the enclosing circle's area: 1 for a disc, + /// about 0.85 for a gear, 2/pi for a square. 0 when unknown. + public double FillRatio { get; set; } + + /// From to the part's local origin, unrotated. + /// The part's location is Center + PartOffset when it is placed without rotation. + public Vector PartOffset { get; set; } + + /// From to the clear disc's center, unrotated. + public Vector HoleOffset { get; set; } + + /// Radius of the largest disc clear of material; 0 for a solid part. + public double HoleRadius { get; set; } + + /// The clear disc where it currently sits, or null for a solid part. + public Circle Hole => HoleRadius > 0 ? new Circle(Center + HoleOffset, HoleRadius) : null; + + public static Item TryCreate(PartGeometrySnapshot snapshot) => + JobPartGeometry.TryRead(snapshot) is { } geometry ? Create(geometry) : null; + + /// Builds the item in the part's unrotated local frame. + public static Item Create(JobPartGeometry geometry) + { + // Every point of the check's outline lies within the allowance of the analytic curve, + // which the circumscribed flattening already contains. + var perimeter = geometry.Perimeter.ToPolygonWithTolerance(FlattenAllowance, circumscribe: true); + var enclosing = MinimumEnclosingCircle.Compute(perimeter.Vertices); + var radius = enclosing.Radius + FlattenAllowance; + var center = enclosing.Center; + + var item = new Item + { + Center = center, + Radius = radius, + FillRatio = System.Math.Abs(geometry.Perimeter.Area()) / (System.Math.PI * radius * radius), + PartOffset = -center, + }; + + foreach (var cutout in geometry.Cutouts) + { + var polygon = cutout.ToPolygonWithTolerance(FlattenAllowance); + var candidates = new[] { PolyLabel.Find(polygon, precision: FlattenAllowance), center }; + + foreach (var candidate in candidates.Where(polygon.ContainsPoint)) + { + // Measured to the analytic boundaries, so it holds however the check flattens + // them; every cutout counts, in case one lies inside another. + var clearance = geometry.Cutouts.Min(c => c.ClosestPointTo(candidate).DistanceTo(candidate)) + - FlattenAllowance; + + if (clearance > item.HoleRadius) + { + item.HoleRadius = clearance; + item.HoleOffset = candidate - center; + } + } + } + + return item; + } + public override Item Clone() { var copy = new Item @@ -15,6 +89,10 @@ namespace OpenNest.Engine.CirclePacking Center = this.Center, Rotation = this.Rotation, PackingId = this.PackingId, + FillRatio = this.FillRatio, + PartOffset = this.PartOffset, + HoleOffset = this.HoleOffset, + HoleRadius = this.HoleRadius, }; CopyBaseTo(copy); return copy; diff --git a/OpenNest.Tests/Geometry/MinimumEnclosingCircleTests.cs b/OpenNest.Tests/Geometry/MinimumEnclosingCircleTests.cs new file mode 100644 index 00000000..f9c34f07 --- /dev/null +++ b/OpenNest.Tests/Geometry/MinimumEnclosingCircleTests.cs @@ -0,0 +1,75 @@ +using OpenNest.Geometry; + +namespace OpenNest.Tests.Geometry; + +public class MinimumEnclosingCircleTests +{ + [Fact] + public void SinglePoint_HasZeroRadius() + { + var circle = MinimumEnclosingCircle.Compute(new[] { new Vector(3, 4) }); + + Assert.Equal(new Vector(3, 4), circle.Center); + Assert.Equal(0, circle.Radius); + } + + [Fact] + public void Square_IsCircumscribed() + { + var circle = MinimumEnclosingCircle.Compute(new[] + { + new Vector(0, 0), new Vector(10, 0), new Vector(10, 10), new Vector(0, 10), new Vector(5, 5), + }); + + Assert.Equal(5, circle.Center.X, 9); + Assert.Equal(5, circle.Center.Y, 9); + Assert.Equal(System.Math.Sqrt(50), circle.Radius, 9); + } + + [Fact] + public void ObtuseTriangle_UsesLongestSideAsDiameter() + { + var circle = MinimumEnclosingCircle.Compute(new[] { new Vector(0, 0), new Vector(10, 0), new Vector(5, 1) }); + + Assert.Equal(5, circle.Center.X, 9); + Assert.Equal(0, circle.Center.Y, 9); + Assert.Equal(5, circle.Radius, 9); + } + + [Fact] + public void CollinearPoints_SpanTheEnds() + { + var circle = MinimumEnclosingCircle.Compute(new[] { new Vector(0, 0), new Vector(4, 4), new Vector(2, 2), new Vector(1, 1) }); + + Assert.Equal(2, circle.Center.X, 9); + Assert.Equal(2, circle.Center.Y, 9); + Assert.Equal(System.Math.Sqrt(8), circle.Radius, 9); + } + + [Fact] + public void RandomPoints_AreAllCoveredByAMinimalCircle() + { + var random = new Random(7); + var points = Enumerable.Range(0, 500) + .Select(_ => new Vector(random.NextDouble() * 100 - 50, random.NextDouble() * 40 - 20)) + .ToList(); + + var circle = MinimumEnclosingCircle.Compute(points); + + Assert.All(points, p => Assert.True(p.DistanceTo(circle.Center) <= circle.Radius)); + // A minimal circle touches at least two points; a larger one could shrink. + Assert.True(points.Count(p => circle.Radius - p.DistanceTo(circle.Center) <= 1e-9) >= 2); + } + + [Fact] + public void Result_IsRepeatable() + { + var points = Enumerable.Range(0, 50).Select(i => new Vector(System.Math.Cos(i * 0.7) * i, System.Math.Sin(i * 1.3) * i)).ToList(); + + var first = MinimumEnclosingCircle.Compute(points); + var second = MinimumEnclosingCircle.Compute(points); + + Assert.Equal(first.Center, second.Center); + Assert.Equal(first.Radius, second.Radius); + } +}