From 6067d0c89e134c6a1fbc41b1997fa6d2280319e9 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Tue, 24 Nov 2026 13:26:52 -0500 Subject: [PATCH] perf(bestfit): evaluate pair candidates without rebuilding the parts PairEvaluator built two parts for every candidate and converted and chained each one's program twice, about 140 KB of garbage per candidate. Under the workstation GC that allocation, not the arithmetic, set the pace. It now builds the first part once and the second once per rotation, and applies each candidate's offset to their hull vertices and bounds. The overlap polygons are flattened straight from the perimeter program's codes: turned, converted, chained, moved and flattened with the operands and order of the long way, using the conversion's and Arc's own helpers. The chain ShapeBuilder finds is recorded once and replayed, which is only done when every pair of entity ends is clearly together or clearly apart; otherwise, and for full circles, incremental moves and sub-programs, the perimeter is built as before. On 51 drawings from four production nests (68,521 candidates) the evaluator goes from 5.9 s to 0.93 s and FindCandidates from 7.9 s to 3.3 s; allocation falls from 9.6 GB to 1.6 GB. Results, their order and the overlap polygons are bit-identical to the previous evaluator, which the tests keep as a frozen oracle. Co-Authored-By: Claude Fable 5.2 --- OpenNest.Engine/BestFit/PairEvaluator.cs | 764 ++++++++++++++++-- OpenNest.Tests/BestFit/LegacyPairEvaluator.cs | 200 +++++ .../BestFit/PairEvaluatorEquivalenceTests.cs | 246 ++++++ 3 files changed, 1152 insertions(+), 58 deletions(-) create mode 100644 OpenNest.Tests/BestFit/LegacyPairEvaluator.cs create mode 100644 OpenNest.Tests/BestFit/PairEvaluatorEquivalenceTests.cs diff --git a/OpenNest.Engine/BestFit/PairEvaluator.cs b/OpenNest.Engine/BestFit/PairEvaluator.cs index 8aa1b6b4..72243b75 100644 --- a/OpenNest.Engine/BestFit/PairEvaluator.cs +++ b/OpenNest.Engine/BestFit/PairEvaluator.cs @@ -1,6 +1,8 @@ +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using OpenNest.CNC; using OpenNest.Converters; using OpenNest.Engine.Fill; using OpenNest.Geometry; @@ -26,9 +28,10 @@ namespace OpenNest.Engine.BestFit if (candidates.Count == 0) return new List(); - // Build a perimeter-only drawing once — all candidates share the same drawing. - // This avoids cloning the full program (with all cutouts) for every candidate. - var perimeterDrawing = CreatePerimeterDrawing(candidates[0].Drawing); + // Build the perimeter-only geometry once: all candidates share the same drawing. + // This avoids cloning the full program (with all cutouts) for every candidate, and + // rebuilding the parts' geometry for every candidate. + var geometry = new PairGeometry(CreatePerimeterDrawing(candidates[0].Drawing)); // Results keep candidate order: callers sort stably, so ties must not depend on // which worker finished first. @@ -39,7 +42,7 @@ namespace OpenNest.Engine.BestFit candidates.Count, i => { - results[i] = Evaluate(candidates[i], perimeterDrawing); + results[i] = Evaluate(candidates[i], geometry, out _, out _); } ); @@ -48,21 +51,66 @@ namespace OpenNest.Engine.BestFit public BestFitResult Evaluate(PairCandidate candidate) { - var perimeterDrawing = CreatePerimeterDrawing(candidate.Drawing); - return Evaluate(candidate, perimeterDrawing); + return Evaluate( + candidate, + new PairGeometry(CreatePerimeterDrawing(candidate.Drawing)), + out _, + out _ + ); } - private BestFitResult Evaluate(PairCandidate candidate, Drawing perimeterDrawing) + /// + /// The two polygons the overlap check reads for , either + /// null when the drawing has no perimeter. For tests, which compare them with the + /// polygons of two parts built, placed and turned the long way. + /// + internal (Polygon First, Polygon Second) OverlapPolygons(PairCandidate candidate) { - var part1 = Part.CreateAtOrigin(perimeterDrawing); + Evaluate( + candidate, + new PairGeometry(CreatePerimeterDrawing(candidate.Drawing)), + out var first, + out var second + ); + return (first, second); + } - var part2 = Part.CreateAtOrigin(perimeterDrawing, candidate.Part2Rotation); - part2.Location = candidate.Part2Offset; - part2.UpdateBounds(); + /// + /// Evaluates one candidate as if both parts were built from the perimeter drawing with + /// , placed and turned for it alone. Whatever depends + /// only on a rotation comes from ; whatever depends on the + /// candidate's offset is applied with the arithmetic such a part would use, in the same + /// order, so the result is the same to the last bit. + /// + private static BestFitResult Evaluate( + PairCandidate candidate, + PairGeometry geometry, + out Polygon polygon1, + out Polygon polygon2 + ) + { + var part1 = geometry.Part1; + var part2 = geometry.Turned(candidate.Part2Rotation); + var location1 = part1.Location; + var location2 = candidate.Part2Offset; + + var box1 = part1.Bounds; + var box2 = new Box( + part2.ProgramBounds.X, + part2.ProgramBounds.Y, + part2.ProgramBounds.Length, + part2.ProgramBounds.Width + ); + box2.Offset(location2); // Convex hull vertices from perimeter polygons only - var allPoints = GetPartVertices(part1); - allPoints.AddRange(GetPartVertices(part2)); + var vertices1 = part1.PlacedVertices; + var vertices2 = part2.Vertices; + var allPoints = new Vector[vertices1.Length + vertices2.Length]; + vertices1.CopyTo(allPoints, 0); + + for (var i = 0; i < vertices2.Length; i++) + allPoints[vertices1.Length + i] = vertices2[i].Offset(location2); // Find optimal bounding rectangle via rotating calipers double bestArea, @@ -71,7 +119,7 @@ namespace OpenNest.Engine.BestFit bestRotation; List hullAngles = null; - if (allPoints.Count >= 3) + if (allPoints.Length >= 3) { var hull = ConvexHull.Compute(allPoints); var result = RotatingCalipers.MinimumBoundingRectangle(hull); @@ -83,9 +131,7 @@ namespace OpenNest.Engine.BestFit } else { - var combinedBox = ( - (IEnumerable)new IBoundable[] { part1, part2 } - ).GetBoundingBox(); + var combinedBox = PairBounds(box1, box2); bestArea = combinedBox.Area(); bestWidth = combinedBox.Width; bestHeight = combinedBox.Length; @@ -110,28 +156,21 @@ namespace OpenNest.Engine.BestFit // uses downstream. Uses Collision.HasOverlap (full polygon clip) rather than // Shape.Intersects (edge-crossing only), which misses containment-style overlaps // where one perimeter's boundary never crosses the other's. Checking pre-rotation - // geometry here (rather than rotating part1/part2 first, matching BuildParts) would + // geometry here (rather than turning both parts first, matching BuildParts) would // tessellate arcs at a different orientation than the geometry actually gets placed // with, letting tangent-corner slivers slip through in one frame but not the other. - if (!bestRotation.IsEqualTo(0)) + var turned = !bestRotation.IsEqualTo(0); + + if (turned) { - var pairBounds = ( - (IEnumerable)new IBoundable[] { part1, part2 } - ).GetBoundingBox(); - var center = pairBounds.Center; - part1.Rotate(-bestRotation, center); - part2.Rotate(-bestRotation, center); + var center = PairBounds(box1, box2).Center; + location1 = location1.Rotate(-bestRotation, center); + location2 = location2.Rotate(-bestRotation, center); } - var shape1 = GetPerimeterShape(part1); - var shape2 = GetPerimeterShape(part2); - var overlaps = - shape1 != null - && shape2 != null - && Collision.HasOverlap( - shape1.ToPolygonWithTolerance(OverlapChordTolerance), - shape2.ToPolygonWithTolerance(OverlapChordTolerance) - ); + polygon1 = part1.OverlapPolygon(turned, -bestRotation, location1); + polygon2 = part2.OverlapPolygon(turned, -bestRotation, location2); + var overlaps = Overlap(polygon1, polygon2); return new BestFitResult { @@ -147,6 +186,79 @@ namespace OpenNest.Engine.BestFit }; } + /// The box around both parts, as GetBoundingBox gives it for the pair. + private static Box PairBounds(Box first, Box second) + { + var left = first.Left; + var bottom = first.Bottom; + var right = first.Right; + var top = first.Top; + + if (second.Left < left) + left = second.Left; + if (second.Right > right) + right = second.Right; + if (second.Bottom < bottom) + bottom = second.Bottom; + if (second.Top > top) + top = second.Top; + + return new Box(left, bottom, right - left, top - bottom); + } + + [System.ThreadStatic] + private static List firstTriangles; + + [System.ThreadStatic] + private static List secondTriangles; + + /// + /// of + /// two overlap polygons, false when either part has no perimeter. The triangles go into + /// lists this thread reuses. + /// + private static bool Overlap(Polygon first, Polygon second) + { + if (first == null || second == null) + return false; + + return Collision.HasOverlapTriangulated( + first, + () => Collision.TriangulateForClipping(first, firstTriangles ??= new List()), + second, + () => Collision.TriangulateForClipping(second, secondTriangles ??= new List()) + ); + } + + /// + /// The overlap polygon of a perimeter this candidate owns, moved to + /// . The perimeter is moved before it is flattened, as a + /// placed part's is: flattening first and moving the points afterwards rounds + /// differently. + /// + private static Polygon PlacedPolygon(Shape perimeter, Vector location) + { + if (perimeter == null) + return null; + + perimeter.Offset(location); + return perimeter.ToPolygonWithTolerance(OverlapChordTolerance); + } + + /// A copy of a shared perimeter for one candidate to move, or null for none. + private static Shape Copy(Shape perimeter) + { + if (perimeter == null) + return null; + + var copy = new Shape(); + + foreach (var entity in perimeter.Entities) + copy.Entities.Add(entity.Clone()); + + return copy; + } + private static Drawing CreatePerimeterDrawing(Drawing source) { var entities = ConvertProgram @@ -158,36 +270,572 @@ namespace OpenNest.Engine.BestFit return new Drawing(source.Name, program); } - private static Shape GetPerimeterShape(Part part) + /// + /// The perimeter drawing's geometry for one evaluation run: the first part, and the + /// second part at each rotation the candidates use. Entries are built on first use and + /// only read afterwards, so the workers share them. + /// + private sealed class PairGeometry { - var entities = ConvertProgram - .ToGeometry(part.Program) - .Where(e => SpecialLayers.IsMaterial(e.Layer)) - .ToList(); - var shapes = ShapeBuilder.GetShapes(entities); - if (shapes.Count == 0) - return null; - shapes[0].Offset(part.Location); - return shapes[0]; - } + private readonly Drawing perimeterDrawing; + private readonly ConcurrentDictionary turned = new(); - private static List GetPartVertices(Part part) - { - var entities = ConvertProgram - .ToGeometry(part.Program) - .Where(e => SpecialLayers.IsMaterial(e.Layer)) - .ToList(); - var shapes = ShapeBuilder.GetShapes(entities); - var points = new List(); + private readonly PerimeterChain chain; - foreach (var shape in shapes) + public PairGeometry(Drawing perimeterDrawing) { - var polygon = shape.ToPolygonWithTolerance(ChordTolerance); - polygon.Offset(part.Location); - points.AddRange(polygon.Vertices); + this.perimeterDrawing = perimeterDrawing; + chain = PerimeterChain.Record(perimeterDrawing.Program); + Part1 = new TurnedPart(perimeterDrawing, 0, chain); } - return points; + public TurnedPart Part1 { get; } + + /// The second part at , keyed by its exact value. + public TurnedPart Turned(double rotation) => + turned.GetOrAdd( + System.BitConverter.DoubleToInt64Bits(rotation), + static (_, state) => + new TurnedPart(state.perimeterDrawing, state.rotation, state.chain), + (perimeterDrawing, rotation, chain) + ); } + + /// + /// How chains the perimeter program's entities into + /// its first shape: which entities, in which order, and which it reverses. Chaining + /// asks only whether two entity ends lie within , + /// and turning the program moves every end rigidly, apart from rounding and an arc's + /// start, which may sit up to off the previous move's + /// end depending on whether the conversion refits its center. A record is therefore + /// kept only when every pair of ends is clearly together or clearly apart, by more + /// than those shifts can add up to; the chain is then the same at every rotation and is + /// replayed instead of searched for. Otherwise there is no record and every perimeter + /// is chained by itself. + /// + private sealed class PerimeterChain + { + /// Ends this close stay within the chain tolerance at any rotation. + private const double Together = 2 * Tolerance.Epsilon; + + /// Ends this far apart stay outside the chain tolerance at any rotation. + private const double Apart = 2 * Tolerance.ChainTolerance; + + private readonly EntityType[] types; + private readonly int[] order; + private readonly bool[] reversed; + + private PerimeterChain(EntityType[] types, int[] order, bool[] reversed) + { + this.types = types; + this.order = order; + this.reversed = reversed; + } + + /// The chain of 's perimeter, or null when it is ambiguous. + public static PerimeterChain Record(Program program) + { + var entities = MaterialEntities(program); + var types = new EntityType[entities.Count]; + var starts = new Vector[entities.Count]; + var ends = new List(entities.Count * 2); + + for (var i = 0; i < entities.Count; i++) + { + types[i] = entities[i].Type; + + switch (entities[i]) + { + case Line line: + starts[i] = line.StartPoint; + ends.Add(line.StartPoint); + ends.Add(line.EndPoint); + break; + + case Arc arc: + starts[i] = arc.StartPoint(); + ends.Add(starts[i]); + ends.Add(arc.EndPoint()); + break; + + case Circle: + break; + + default: + return null; + } + } + + if (!ClearlySeparated(ends)) + return null; + + var positions = new Dictionary(ReferenceEqualityComparer.Instance); + + for (var i = 0; i < entities.Count; i++) + positions[entities[i]] = i; + + var shapes = ShapeBuilder.GetShapes(entities); + + if (shapes.Count == 0) + return new PerimeterChain(types, System.Array.Empty(), System.Array.Empty()); + + var chained = shapes[0].Entities; + var order = new int[chained.Count]; + var reversed = new bool[chained.Count]; + + for (var i = 0; i < chained.Count; i++) + { + if (!positions.TryGetValue(chained[i], out var position)) + return null; + + // Chaining reverses an entity in place, which swaps its ends. + var start = chained[i] switch + { + Line line => line.StartPoint, + Arc arc => arc.StartPoint(), + _ => starts[position], + }; + + order[i] = position; + reversed[i] = start.X != starts[position].X || start.Y != starts[position].Y; + } + + return new PerimeterChain(types, order, reversed); + } + + /// How many material entities the program has. + public int EntityCount => types.Length; + + /// How many entities the perimeter chains, none when there is no perimeter. + public int Length => order.Length; + + /// The kind of the material entity at . + public EntityType TypeOf(int index) => types[index]; + + /// The material entity the perimeter takes at . + public int EntityAt(int step) => order[step]; + + /// Whether chaining reverses the entity taken at . + public bool ReversedAt(int step) => reversed[step]; + + /// + /// Chains , the material entities of the same program at + /// another rotation, as recorded. False, with nothing changed, when they are not the + /// same kinds of entity: an arc can become a full circle, or the reverse, when its + /// end angles round together. + /// + public bool TryReplay(List entities, out Shape perimeter) + { + perimeter = null; + + if (entities.Count != types.Length) + return false; + + for (var i = 0; i < types.Length; i++) + { + if (entities[i].Type != types[i]) + return false; + } + + if (order.Length == 0) + return true; + + perimeter = new Shape(); + + for (var i = 0; i < order.Length; i++) + { + var entity = entities[order[i]]; + + if (reversed[i]) + entity.Reverse(); + + perimeter.Entities.Add(entity); + } + + return true; + } + + /// + /// Whether every two ends are either within or at least + /// from each other, and all are finite. + /// + private static bool ClearlySeparated(List ends) + { + foreach (var end in ends) + { + if (!double.IsFinite(end.X) || !double.IsFinite(end.Y)) + return false; + } + + ends.Sort((a, b) => a.X.CompareTo(b.X)); + + for (var i = 0; i < ends.Count; i++) + { + for (var j = i + 1; j < ends.Count && ends[j].X - ends[i].X < Apart; j++) + { + var distance = ends[i].DistanceTo(ends[j]); + + if (distance > Together && distance < Apart) + return false; + } + } + + return true; + } + } + + /// + /// One part of the pair as builds it at a rotation, + /// before the candidate's offset: its bounds, hull vertices and perimeter, and the + /// perimeter after a further turn into each bounding-rectangle orientation. + /// + private sealed class TurnedPart + { + private readonly Program program; + private readonly PerimeterChain chain; + private readonly PerimeterCodes codes; + + public TurnedPart(Drawing perimeterDrawing, double rotation, PerimeterChain chain) + { + var part = Part.CreateAtOrigin(perimeterDrawing, rotation); + + this.chain = chain; + program = part.Program; + codes = PerimeterCodes.Read(program, chain); + Location = part.Location; + Bounds = part.BoundingBox; + ProgramBounds = program.BoundingBox(); + + var shapes = ShapeBuilder.GetShapes(MaterialEntities(program)); + var points = new List(); + + foreach (var shape in shapes) + points.AddRange(shape.ToPolygonWithTolerance(ChordTolerance).Vertices); + + Perimeter = shapes.Count == 0 ? null : shapes[0]; + Vertices = points.ToArray(); + PlacedVertices = new Vector[Vertices.Length]; + + for (var i = 0; i < Vertices.Length; i++) + PlacedVertices[i] = Vertices[i].Offset(Location); + } + + /// Where leaves the part. + public Vector Location { get; } + + /// The part's bounds at . Read only. + public Box Bounds { get; } + + /// The program's bounds, before any location is added. Read only. + public Box ProgramBounds { get; } + + /// Hull vertices of the program, before any location is added. + public Vector[] Vertices { get; } + + /// moved to . + public Vector[] PlacedVertices { get; } + + /// The program's perimeter, or null when it has none. Read only. + public Shape Perimeter { get; } + + /// + /// The polygon the overlap check reads for this part at , + /// after the program turns by when + /// ; null when the part has no perimeter. It is flattened + /// straight from the program's codes where they allow it, and otherwise from the + /// perimeter shape a part would build. + /// + public Polygon OverlapPolygon(bool turned, double angle, Vector location) + { + if (codes != null && codes.TryFlatten(turned, angle, location, out var polygon)) + return polygon; + + return PlacedPolygon(turned ? PerimeterTurned(angle) : Copy(Perimeter), location); + } + + /// + /// The perimeter after the program turns by , or null when + /// it has none. Bounding-rectangle angles rarely repeat between candidates, so this + /// is built per call, and the caller owns the result. + /// + private Shape PerimeterTurned(double angle) + { + var copy = (Program)program.Clone(); + copy.Rotate(angle); + var entities = MaterialEntities(copy); + + if (chain != null && chain.TryReplay(entities, out var perimeter)) + return perimeter; + + var shapes = ShapeBuilder.GetShapes(entities); + return shapes.Count == 0 ? null : shapes[0]; + } + } + + /// + /// A perimeter program's moves, read once, from which a candidate's overlap polygon is + /// flattened without copying the program or building its entities. Each step is the one + /// the long way takes, with the same operands in the same order: turning the codes + /// (), converting them + /// (), chaining and reversing them (the + /// ), moving them to the part's location and flattening + /// them (). Arcs are fitted and flattened by + /// the conversion's and 's own helpers. + /// + private sealed class PerimeterCodes + { + private readonly PerimeterChain chain; + private readonly bool[] isArc; + private readonly bool[] clockwise; + private readonly Vector[] ends; + private readonly Vector[] centers; + + /// Each move's place among the material entities, or -1 when it is not material. + private readonly int[] slots; + + private int vertexCount = 64; + + [System.ThreadStatic] + private static Piece[] pieceBuffer; + + private PerimeterCodes( + PerimeterChain chain, + bool[] isArc, + bool[] clockwise, + Vector[] ends, + Vector[] centers, + int[] slots + ) + { + this.chain = chain; + this.isArc = isArc; + this.clockwise = clockwise; + this.ends = ends; + this.centers = centers; + this.slots = slots; + } + + /// + /// The moves of , or null when it must go the long way: + /// no recorded chain, no perimeter, incremental moves, sub-programs, a full circle, + /// or moves that do not match the chain's entities one for one. + /// + public static PerimeterCodes Read(Program program, PerimeterChain chain) + { + if (chain == null || chain.Length == 0 || program.Mode != Mode.Absolute) + return null; + + var isArc = new List(); + var clockwise = new List(); + var ends = new List(); + var centers = new List(); + + for (var i = 0; i < program.Length; i++) + { + var code = program[i]; + + switch (code.Type) + { + case CodeType.ArcMove: + var arc = (ArcMove)code; + isArc.Add(true); + clockwise.Add(arc.Rotation == RotationType.CW); + ends.Add(arc.EndPoint); + centers.Add(arc.CenterPoint); + break; + + case CodeType.LinearMove: + case CodeType.RapidMove: + isArc.Add(false); + clockwise.Add(false); + ends.Add(((Motion)code).EndPoint); + centers.Add(new Vector()); + break; + + case CodeType.SubProgramCall: + return null; + } + } + + // The conversion gives one entity per move, in order: its layers say which are + // material, and so which entity of the chain each move is. + var entities = ConvertProgram.ToGeometry(program); + + if (entities.Count != isArc.Count) + return null; + + var slots = new int[entities.Count]; + var material = 0; + + for (var i = 0; i < entities.Count; i++) + { + if (!SpecialLayers.IsMaterial(entities[i].Layer)) + { + slots[i] = -1; + continue; + } + + if (material >= chain.EntityCount) + return null; + + if (chain.TypeOf(material) != (isArc[i] ? EntityType.Arc : EntityType.Line)) + return null; + + slots[i] = material++; + } + + if (material != chain.EntityCount) + return null; + + return new PerimeterCodes( + chain, + isArc.ToArray(), + clockwise.ToArray(), + ends.ToArray(), + centers.ToArray(), + slots + ); + } + + /// + /// Flattens the perimeter at , after the program turns by + /// when . False when an arc comes + /// out as a full circle at this angle, which the chain did not record. + /// + public bool TryFlatten(bool turned, double angle, Vector location, out Polygon polygon) + { + polygon = null; + + var pieces = pieceBuffer; + + if (pieces == null || pieces.Length < chain.EntityCount) + pieceBuffer = pieces = new Piece[chain.EntityCount]; + + // Program.Rotate turns every move about the origin; Vector.Rotate takes the + // cosine and sine of the same angle for each point. + var origin = new Vector(0, 0); + var cos = turned ? PortableMath.Cos(angle) : 0; + var sin = turned ? PortableMath.Sin(angle) : 0; + + // ConvertProgram.ToGeometry: each move runs from where the last one ended. + var current = new Vector(); + + for (var i = 0; i < ends.Length; i++) + { + var end = turned ? Turn(ends[i], cos, sin, origin) : ends[i]; + var slot = slots[i]; + + if (!isArc[i]) + { + if (slot >= 0) + pieces[slot] = new Piece { Start = current, End = end }; + } + else + { + var center = turned ? Turn(centers[i], cos, sin, origin) : centers[i]; + center = ConvertProgram.FitCenterToEndpoints(center, current, end); + + var startAngle = center.AngleTo(current); + var endAngle = center.AngleTo(end); + + var dx = end.X - center.X; + var dy = end.Y - center.Y; + var radius = System.Math.Sqrt(dx * dx + dy * dy); + + if (startAngle.IsEqualTo(endAngle)) + return false; + + if (slot >= 0) + { + pieces[slot] = new Piece + { + IsArc = true, + Start = center, + Radius = radius, + StartAngle = startAngle, + EndAngle = endAngle, + Reversed = clockwise[i], + }; + } + } + + current = end; + } + + polygon = new Polygon(); + var vertices = polygon.Vertices; + vertices.Capacity = vertexCount; + + for (var step = 0; step < chain.Length; step++) + { + ref readonly var piece = ref pieces[chain.EntityAt(step)]; + var reverse = chain.ReversedAt(step); + + if (!piece.IsArc) + { + // Line.Reverse swaps the ends; Line.Offset adds the location to each. + vertices.Add((reverse ? piece.End : piece.Start) + location); + vertices.Add((reverse ? piece.Start : piece.End) + location); + continue; + } + + // Arc.Reverse swaps the angles and flips the direction; Arc.Offset adds + // the location to the center. + var startAngle = reverse ? piece.EndAngle : piece.StartAngle; + var endAngle = reverse ? piece.StartAngle : piece.EndAngle; + var reversed = piece.Reversed != reverse; + var sweep = Arc.SweepAngle(startAngle, endAngle, reversed); + + Arc.AppendPoints( + vertices, + piece.Start + location, + piece.Radius, + startAngle, + sweep, + reversed, + Arc.SegmentsForTolerance(piece.Radius, sweep, OverlapChordTolerance), + circumscribe: false + ); + } + + // Sized for the next candidate: the count barely changes with the angle. + if (vertices.Count + 16 > vertexCount) + vertexCount = vertices.Count + 16; + + polygon.Close(); + polygon.Cleanup(); + polygon.UpdateBounds(); + return true; + } + + /// with the angle's cosine and sine given. + private static Vector Turn(Vector point, double cos, double sin, Vector origin) + { + var pt = point - origin; + + return new Vector( + pt.X * cos - pt.Y * sin + origin.X, + pt.X * sin + pt.Y * cos + origin.Y + ); + } + + /// One material entity: a line from Start to End, or an arc centered on Start. + private struct Piece + { + public bool IsArc; + public Vector Start; + public Vector End; + public double Radius; + public double StartAngle; + public double EndAngle; + public bool Reversed; + } + } + + private static List MaterialEntities(Program program) => + ConvertProgram + .ToGeometry(program) + .Where(e => SpecialLayers.IsMaterial(e.Layer)) + .ToList(); } } diff --git a/OpenNest.Tests/BestFit/LegacyPairEvaluator.cs b/OpenNest.Tests/BestFit/LegacyPairEvaluator.cs new file mode 100644 index 00000000..fcf19aec --- /dev/null +++ b/OpenNest.Tests/BestFit/LegacyPairEvaluator.cs @@ -0,0 +1,200 @@ +#nullable disable +// Frozen, test-only copy of OpenNest.Engine/BestFit/PairEvaluator.cs at commit 24f70fc3 +// (before it stopped rebuilding both parts and their geometry for every candidate). +// Only #nullable disable, the namespace, type name, visibility and the Polygons seam, which +// hands out the two polygons the overlap check reads, differ from the original. +// Do not edit: differential tests use it as the independent pre-change oracle. +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using OpenNest.Converters; +using OpenNest.Engine.BestFit; +using OpenNest.Engine.Fill; +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Tests.BestFit +{ + internal class LegacyPairEvaluator : IPairEvaluator + { + private const double ChordTolerance = 0.01; + + /// + /// Tighter chord tolerance for the overlap check only. Rounded-corner arcs + /// polygonized at the coarser can "cut the corner" + /// enough to hide a genuine but tiny sliver overlap between two candidates — + /// this needs to match the precision Part.Intersects uses elsewhere so BestFit's + /// Keep decision agrees with the same overlap check callers rely on downstream. + /// + private const double OverlapChordTolerance = 0.001; + + /// Test seam: receives each candidate and the two polygons its overlap check read. + public System.Action Polygons; + + public List EvaluateAll(List candidates) + { + if (candidates.Count == 0) + return new List(); + + // Build a perimeter-only drawing once — all candidates share the same drawing. + // This avoids cloning the full program (with all cutouts) for every candidate. + var perimeterDrawing = CreatePerimeterDrawing(candidates[0].Drawing); + + // Results keep candidate order: callers sort stably, so ties must not depend on + // which worker finished first. + var results = new BestFitResult[candidates.Count]; + + Parallel.For( + 0, + candidates.Count, + i => + { + results[i] = Evaluate(candidates[i], perimeterDrawing); + } + ); + + return results.ToList(); + } + + public BestFitResult Evaluate(PairCandidate candidate) + { + var perimeterDrawing = CreatePerimeterDrawing(candidate.Drawing); + return Evaluate(candidate, perimeterDrawing); + } + + private BestFitResult Evaluate(PairCandidate candidate, Drawing perimeterDrawing) + { + var part1 = Part.CreateAtOrigin(perimeterDrawing); + + var part2 = Part.CreateAtOrigin(perimeterDrawing, candidate.Part2Rotation); + part2.Location = candidate.Part2Offset; + part2.UpdateBounds(); + + // Convex hull vertices from perimeter polygons only + var allPoints = GetPartVertices(part1); + allPoints.AddRange(GetPartVertices(part2)); + + // Find optimal bounding rectangle via rotating calipers + double bestArea, + bestWidth, + bestHeight, + bestRotation; + List hullAngles = null; + + if (allPoints.Count >= 3) + { + var hull = ConvexHull.Compute(allPoints); + var result = RotatingCalipers.MinimumBoundingRectangle(hull); + bestArea = result.Area; + bestWidth = result.Width; + bestHeight = result.Height; + bestRotation = result.Angle; + hullAngles = RotationAnalysis.GetHullEdgeAngles(hull); + } + else + { + var combinedBox = ( + (IEnumerable)new IBoundable[] { part1, part2 } + ).GetBoundingBox(); + bestArea = combinedBox.Area(); + bestWidth = combinedBox.Width; + bestHeight = combinedBox.Length; + bestRotation = 0; + hullAngles = new List { 0 }; + } + + var trueArea = candidate.Drawing.Area * 2; + + // Normalize to landscape (width >= height) for consistent display. Do this before + // the overlap check so bestRotation already matches the final OptimalRotation that + // BuildParts will apply. + if (bestHeight > bestWidth) + { + var tmp = bestWidth; + bestWidth = bestHeight; + bestHeight = tmp; + bestRotation += Angle.HalfPI; + } + + // Overlap check — perimeter vs perimeter, in the same final orientation BuildParts + // uses downstream. Uses Collision.HasOverlap (full polygon clip) rather than + // Shape.Intersects (edge-crossing only), which misses containment-style overlaps + // where one perimeter's boundary never crosses the other's. Checking pre-rotation + // geometry here (rather than rotating part1/part2 first, matching BuildParts) would + // tessellate arcs at a different orientation than the geometry actually gets placed + // with, letting tangent-corner slivers slip through in one frame but not the other. + if (!bestRotation.IsEqualTo(0)) + { + var pairBounds = ( + (IEnumerable)new IBoundable[] { part1, part2 } + ).GetBoundingBox(); + var center = pairBounds.Center; + part1.Rotate(-bestRotation, center); + part2.Rotate(-bestRotation, center); + } + + var shape1 = GetPerimeterShape(part1); + var shape2 = GetPerimeterShape(part2); + var polygon1 = shape1?.ToPolygonWithTolerance(OverlapChordTolerance); + var polygon2 = shape2?.ToPolygonWithTolerance(OverlapChordTolerance); + Polygons?.Invoke(candidate, polygon1, polygon2); + var overlaps = shape1 != null && shape2 != null && Collision.HasOverlap(polygon1, polygon2); + + return new BestFitResult + { + Candidate = candidate, + RotatedArea = bestArea, + BoundingWidth = bestWidth, + BoundingHeight = bestHeight, + OptimalRotation = bestRotation, + TrueArea = trueArea, + HullAngles = hullAngles, + Keep = !overlaps, + Reason = overlaps ? "Overlap detected" : "Valid", + }; + } + + private static Drawing CreatePerimeterDrawing(Drawing source) + { + var entities = ConvertProgram + .ToGeometry(source.Program) + .Where(e => SpecialLayers.IsMaterial(e.Layer)) + .ToList(); + var profile = new ShapeProfile(entities); + var program = ConvertGeometry.ToProgram(profile.Perimeter); + return new Drawing(source.Name, program); + } + + private static Shape GetPerimeterShape(Part part) + { + var entities = ConvertProgram + .ToGeometry(part.Program) + .Where(e => SpecialLayers.IsMaterial(e.Layer)) + .ToList(); + var shapes = ShapeBuilder.GetShapes(entities); + if (shapes.Count == 0) + return null; + shapes[0].Offset(part.Location); + return shapes[0]; + } + + private static List GetPartVertices(Part part) + { + var entities = ConvertProgram + .ToGeometry(part.Program) + .Where(e => SpecialLayers.IsMaterial(e.Layer)) + .ToList(); + var shapes = ShapeBuilder.GetShapes(entities); + var points = new List(); + + foreach (var shape in shapes) + { + var polygon = shape.ToPolygonWithTolerance(ChordTolerance); + polygon.Offset(part.Location); + points.AddRange(polygon.Vertices); + } + + return points; + } + } +} diff --git a/OpenNest.Tests/BestFit/PairEvaluatorEquivalenceTests.cs b/OpenNest.Tests/BestFit/PairEvaluatorEquivalenceTests.cs new file mode 100644 index 00000000..721c5390 --- /dev/null +++ b/OpenNest.Tests/BestFit/PairEvaluatorEquivalenceTests.cs @@ -0,0 +1,246 @@ +using System.Collections.Concurrent; +using OpenNest.CNC; +using OpenNest.Converters; +using OpenNest.Engine; +using OpenNest.Engine.BestFit; +using OpenNest.Geometry; +using OpenNest.Math; +using OpenNest.Shapes; + +namespace OpenNest.Tests.BestFit; + +/// +/// no longer builds two parts and their geometry for every +/// candidate. These tests compare it bit for bit against the frozen pre-change +/// (commit 24f70fc3): the same results in the same order, +/// read from the same overlap polygons. +/// +public class PairEvaluatorEquivalenceTests +{ + public static IEnumerable Shapes => Drawings.Keys.Select(name => new object[] { name }); + + private static readonly Dictionary> Drawings = new() + { + // Arcs at every corner. + ["rounded rectangle"] = () => new RoundedRectangleShape { Length = 6, Width = 3.5, Radius = 0.75 }.GetDrawing(), + + // Concave outlines whose pairs interlock. + ["tee"] = () => new TShape { Width = 10, Height = 8 }.GetDrawing(), + ["ell"] = () => new LShape { Width = 7, Height = 9, LegWidth = 2, LegHeight = 2.5 }.GetDrawing(), + ["notched arcs"] = NotchedArcs, + + // Holes, which the perimeter leaves out. + ["ring"] = () => new RingShape { OuterDiameter = 6, InnerDiameter = 3 }.GetDrawing(), + ["flange"] = () => new PipeFlangeShape + { + OD = 8, + HoleDiameter = 0.75, + HolePatternDiameter = 6, + HoleCount = 6, + PipeClearance = 3, + }.GetDrawing(), + + // A full circle and a bolt-circle outline: tangent contacts at every angle. + ["disc"] = () => new CircleShape { Diameter = 5 }.GetDrawing(), + ["hexagon"] = () => new NgonShape { Sides = 6, Width = 4 }.GetDrawing(), + + // Segments shorter than the chain tolerance, where chaining is ambiguous. + ["tiny segments"] = TinySegments, + + // An outline that is not axis aligned and starts away from the origin. + ["turned tee"] = () => + { + var drawing = new TShape { Width = 10, Height = 8 }.GetDrawing(); + drawing.Program.Rotate(Angle.ToRadians(23), new Vector(4, 1)); + drawing.ProgramChanged(); + return drawing; + }, + + // An incremental source program: the perimeter is rebuilt from its geometry. + ["incremental"] = () => + { + var drawing = NotchedArcs(); + drawing.Program.Mode = Mode.Incremental; + drawing.ProgramChanged(); + return drawing; + }, + }; + + [Theory] + [MemberData(nameof(Shapes))] + public void EvaluateAll_MatchesLegacyBitwise(string shape) + { + var drawing = CanonicalFrame.AsCanonicalCopy(Drawings[shape]()); + var candidates = Candidates(drawing); + + var polygons = new ConcurrentDictionary(); + var legacy = new LegacyPairEvaluator + { + Polygons = (candidate, first, second) => polygons[candidate] = (first, second), + }; + + var expected = legacy.EvaluateAll(candidates); + var evaluator = new PairEvaluator(); + var actual = evaluator.EvaluateAll(candidates); + + Assert.Equal(expected.Count, actual.Count); + + for (var i = 0; i < expected.Count; i++) + { + Assert.Same(candidates[i], actual[i].Candidate); + Assert.True(ResultBits(expected[i]).SequenceEqual(ResultBits(actual[i])), $"{shape}: result {i}"); + Assert.Equal(expected[i].Reason, actual[i].Reason); + + var (first, second) = evaluator.OverlapPolygons(candidates[i]); + Assert.True(PolygonBits(polygons[candidates[i]].First).SequenceEqual(PolygonBits(first)), $"{shape}: first polygon {i}"); + Assert.True(PolygonBits(polygons[candidates[i]].Second).SequenceEqual(PolygonBits(second)), $"{shape}: second polygon {i}"); + + // The single-candidate entry point takes the same path. + if (i % 7 == 0) + Assert.True(ResultBits(expected[i]).SequenceEqual(ResultBits(evaluator.Evaluate(candidates[i]))), $"{shape}: single {i}"); + } + + // The comparison is only worth something when it sees both verdicts and both the + // turned and the unturned overlap check. + Assert.Contains(expected, r => r.Keep); + Assert.Contains(expected, r => !r.Keep); + Assert.Contains(expected, r => r.OptimalRotation.IsEqualTo(0)); + Assert.Contains(expected, r => !r.OptimalRotation.IsEqualTo(0)); + } + + [Fact] + public void EvaluateAll_NoCandidates_IsEmpty() + { + Assert.Empty(new PairEvaluator().EvaluateAll(new List())); + } + + /// + /// The candidates the best-fit search slides into contact, touching (no spacing) and + /// spaced, plus pairs it would never propose: coincident, barely overlapping, exactly + /// tangent along a straight side, and far apart. + /// + private static List Candidates(Drawing drawing) + { + var candidates = new List(); + var index = 1; + + foreach (var spacing in new[] { 0.0, 0.25 }) + { + foreach (var degrees in new[] { 0.0, 90, 180, 270, 37, 211.5 }) + { + var strategy = new RotationSlideStrategy( + Angle.ToRadians(degrees), + index++, + string.Empty, + new CpuDistanceComputer() + ); + candidates.AddRange(strategy.GenerateCandidates(drawing, spacing, 0.5)); + } + } + + var box = Part.CreateAtOrigin(drawing).BoundingBox; + var offsets = new[] + { + new Vector(0, 0), + new Vector(box.Length * 0.5, box.Width * 0.25), + new Vector(box.Length - 1e-4, 0), + new Vector(box.Length, 0), + new Vector(0, box.Width), + new Vector(box.Length + 1e-7, 0.125), + new Vector(box.Length * 3, box.Width * 2), + new Vector(-box.Length * 0.25, box.Width * 0.9), + }; + + foreach (var rotation in new[] { 0, System.Math.PI, Angle.HalfPI, Angle.ToRadians(12.5) }) + { + foreach (var offset in offsets) + { + candidates.Add(new PairCandidate + { + Drawing = drawing, + Part1Rotation = 0, + Part2Rotation = rotation, + Part2Offset = offset, + StrategyIndex = index, + Spacing = 0, + }); + } + + index++; + } + + return candidates; + } + + /// A plate with a square notch, a round notch cut clockwise and two rounded corners. + private static Drawing NotchedArcs() + { + var program = new Program(); + program.MoveTo(0, 0); + program.LineTo(3, 0); + program.LineTo(3, 1.5); + program.LineTo(4.25, 1.5); + program.LineTo(4.25, 0); + program.LineTo(8, 0); + program.LineTo(8, 4); + program.ArcTo(7, 5, 7, 4, RotationType.CCW); + program.LineTo(5.5, 5); + program.ArcTo(3.5, 5, 4.5, 5, RotationType.CW); + program.LineTo(1, 5); + program.ArcTo(0, 4, 1, 4, RotationType.CCW); + program.LineTo(0, 0); + return new Drawing("notched arcs", program); + } + + /// + /// A rectangle whose top edge is a run of segments shorter than the chain tolerance, as a + /// curve exported as a dense polyline has. + /// + private static Drawing TinySegments() + { + var program = new Program(); + program.MoveTo(0, 0); + program.LineTo(4, 0); + program.LineTo(4, 2); + + for (var i = 1; i <= 40; i++) + program.LineTo(4 - i * 0.00004, 2 + System.Math.Sin(i * 0.3) * 0.00002); + + program.LineTo(0, 2); + program.LineTo(0, 0); + return new Drawing("tiny segments", program); + } + + private static long[] ResultBits(BestFitResult result) + { + var values = new List + { + result.RotatedArea, + result.BoundingWidth, + result.BoundingHeight, + result.OptimalRotation, + result.TrueArea, + result.Keep ? 1 : 0, + result.HullAngles == null ? -1 : result.HullAngles.Count, + }; + + if (result.HullAngles != null) + values.AddRange(result.HullAngles); + + return values.Select(BitConverter.DoubleToInt64Bits).ToArray(); + } + + private static long[] PolygonBits(Polygon polygon) + { + if (polygon == null) + return new long[] { -1 }; + + var box = polygon.BoundingBox; + + return polygon.Vertices + .SelectMany(v => new[] { v.X, v.Y }) + .Concat(new[] { box.X, box.Y, box.Length, box.Width }) + .Select(BitConverter.DoubleToInt64Bits) + .ToArray(); + } +}