From 1a46d9896ff66051f8c5090165141d072bcafbf1 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 2 Nov 2026 07:48:27 -0500 Subject: [PATCH] perf(geometry): speed up labels and shape chaining on many-hole parts The Drawing Library Grid check found seven drawings with 1,000-1,700 holes (90-6138-26/27, Reeves bakery vent pans, 4938 A15) that took 0.5-3.6 s to preview, all of it in the part label point. - PolyLabel skips a hole's containment test outside its bounds and its edge distances when its bounds are farther than the nearest edge so far. Both skips leave the result exactly as before; label points on all seven drawings are unchanged and the search is 4-35x faster. - ShapeBuilder.GetShapes rescanned every remaining entity at each chaining step. An endpoint grid now finds the candidates, tested in list order with the same checks, so chosen entities, reversals and shapes are identical (compared against the old loop on the library drawings and 300 random entity soups). 90-6138: 700 ms -> 40 ms. - The label builds its shapes once: ShapeProfile.FromShapes reuses the ones it already chained instead of chaining them again. Previews of all seven now take 57-166 ms. Co-Authored-By: Claude Opus 5.5 --- OpenNest.Core/Geometry/PolyLabel.cs | 64 +++++++-- OpenNest.Core/Geometry/ShapeBuilder.cs | 172 ++++++++++++++++++++----- OpenNest.Core/Geometry/ShapeProfile.cs | 16 ++- OpenNest/LayoutPart.cs | 2 +- 4 files changed, 205 insertions(+), 49 deletions(-) diff --git a/OpenNest.Core/Geometry/PolyLabel.cs b/OpenNest.Core/Geometry/PolyLabel.cs index 0b625605..4c69da04 100644 --- a/OpenNest.Core/Geometry/PolyLabel.cs +++ b/OpenNest.Core/Geometry/PolyLabel.cs @@ -117,6 +117,7 @@ namespace OpenNest.Geometry } var halfCell = cellSize / 2; + var boxes = HoleBoxes(holes); var initial = new List(); @@ -124,7 +125,7 @@ namespace OpenNest.Geometry { for (var y = minY; y < maxY; y += cellSize) { - initial.Add(new Cell(x + halfCell, y + halfCell, halfCell, outer, holes)); + initial.Add(new Cell(x + halfCell, y + halfCell, halfCell, outer, holes, boxes)); // Far from the origin a step smaller than the coordinate's precision // no longer advances; the grid would never end. if (y + cellSize == y) @@ -136,7 +137,7 @@ namespace OpenNest.Geometry initial.Sort((a, b) => b.MaxDist.CompareTo(a.MaxDist)); - var bestCell = GetCentroidCell(outer, holes); + var bestCell = GetCentroidCell(outer, holes, boxes); evaluatedCells = initial.Count + 1; for (var i = 0; i < initial.Count; i++) @@ -176,10 +177,10 @@ namespace OpenNest.Geometry var newCells = new[] { - new Cell(cell.X - halfCell, cell.Y - halfCell, halfCell, outer, holes), - new Cell(cell.X + halfCell, cell.Y - halfCell, halfCell, outer, holes), - new Cell(cell.X - halfCell, cell.Y + halfCell, halfCell, outer, holes), - new Cell(cell.X + halfCell, cell.Y + halfCell, halfCell, outer, holes), + new Cell(cell.X - halfCell, cell.Y - halfCell, halfCell, outer, holes, boxes), + new Cell(cell.X + halfCell, cell.Y - halfCell, halfCell, outer, holes, boxes), + new Cell(cell.X - halfCell, cell.Y + halfCell, halfCell, outer, holes, boxes), + new Cell(cell.X + halfCell, cell.Y + halfCell, halfCell, outer, holes, boxes), }; evaluatedCells += newCells.Length; @@ -193,7 +194,7 @@ namespace OpenNest.Geometry return new Vector(bestCell.X, bestCell.Y); } - private static Cell GetCentroidCell(Polygon outer, IList holes) + private static Cell GetCentroidCell(Polygon outer, IList holes, Box[] boxes) { var area = 0.0; var cx = 0.0; @@ -213,12 +214,12 @@ namespace OpenNest.Geometry area *= 0.5; if (System.Math.Abs(area) < 1e-10) - return new Cell(verts[0].X, verts[0].Y, 0, outer, holes); + return new Cell(verts[0].X, verts[0].Y, 0, outer, holes, boxes); cx /= (6 * area); cy /= (6 * area); - return new Cell(cx, cy, 0, outer, holes); + return new Cell(cx, cy, 0, outer, holes, boxes); } private static double PointToPolygonDist(double x, double y, Polygon polygon) @@ -267,7 +268,7 @@ namespace OpenNest.Geometry public readonly double Dist; public readonly double MaxDist; - public Cell(double x, double y, double halfSize, Polygon outer, IList holes) + public Cell(double x, double y, double halfSize, Polygon outer, IList holes, Box[] boxes) { X = x; Y = y; @@ -280,7 +281,7 @@ namespace OpenNest.Geometry { for (var i = 0; i < holes.Count; i++) { - if (holes[i].ContainsPoint(pt)) + if (boxes[i].Contains(x, y) && holes[i].ContainsPoint(pt)) { inside = false; break; @@ -288,7 +289,7 @@ namespace OpenNest.Geometry } } - Dist = PointToAllEdgesDist(x, y, outer, holes); + Dist = PointToAllEdgesDist(x, y, outer, holes, boxes); if (!inside) Dist = -Dist; @@ -301,7 +302,8 @@ namespace OpenNest.Geometry double x, double y, Polygon outer, - IList holes + IList holes, + Box[] boxes ) { var minDist = PointToPolygonDist(x, y, outer); @@ -310,6 +312,9 @@ namespace OpenNest.Geometry { for (var i = 0; i < holes.Count; i++) { + // No edge is nearer than its hole's box, so a farther box cannot lower the minimum. + if (boxes[i].Distance(x, y) > minDist) + continue; var d = PointToPolygonDist(x, y, holes[i]); if (d < minDist) minDist = d; @@ -318,5 +323,38 @@ namespace OpenNest.Geometry return minDist; } + + // Each hole's vertex bounds: a cell skips the containment test outside them and the + // edge distances when they are farther than the nearest edge found so far. Both skips + // leave the result exactly as without them; parts with many small holes search far faster. + private static Box[] HoleBoxes(IList holes) + { + if (holes == null) + return null; + + var boxes = new Box[holes.Count]; + for (var i = 0; i < holes.Count; i++) + { + var box = new Box(double.MaxValue, double.MaxValue, double.MinValue, double.MinValue); + foreach (var v in holes[i].Vertices) + box = new Box(System.Math.Min(box.MinX, v.X), System.Math.Min(box.MinY, v.Y), + System.Math.Max(box.MaxX, v.X), System.Math.Max(box.MaxY, v.Y)); + boxes[i] = box; + } + return boxes; + } + + private readonly record struct Box(double MinX, double MinY, double MaxX, double MaxY) + { + // Inclusive, so a point on a hole's edge is still tested. + public bool Contains(double x, double y) => x >= MinX && x <= MaxX && y >= MinY && y <= MaxY; + + public double Distance(double x, double y) + { + var dx = System.Math.Max(System.Math.Max(MinX - x, x - MaxX), 0); + var dy = System.Math.Max(System.Math.Max(MinY - y, y - MaxY), 0); + return System.Math.Sqrt(dx * dx + dy * dy); + } + } } } diff --git a/OpenNest.Core/Geometry/ShapeBuilder.cs b/OpenNest.Core/Geometry/ShapeBuilder.cs index 672352fa..06647e83 100644 --- a/OpenNest.Core/Geometry/ShapeBuilder.cs +++ b/OpenNest.Core/Geometry/ShapeBuilder.cs @@ -64,47 +64,28 @@ namespace OpenNest.Geometry if (weldTolerance.HasValue) WeldEndpoints(entityList, weldTolerance.Value); - while (entityList.Count > 0) + // Chain in list order: each shape starts at the first unused entity and takes the + // first unused entity, in list order, with an end at its current end. An endpoint + // grid finds those candidates without rescanning the whole list at every step. + var index = new EndpointIndex(entityList); + var used = new bool[entityList.Count]; + for (var first = 0; first < entityList.Count; first++) { - var next = entityList[0]; + if (used[first]) + continue; + + var next = entityList[first]; + used[first] = true; var shape = new Shape(); shape.Entities.Add(next); - entityList.RemoveAt(0); - - Vector startPoint = new Vector(); + var startPoint = EndOf(next); Entity connected; - switch (next.Type) - { - case EntityType.Arc: - var arc = (Arc)next; - startPoint = arc.EndPoint(); - break; - - case EntityType.Line: - var line = (Line)next; - startPoint = line.EndPoint; - break; - } - - while ((connected = GetConnected(startPoint, entityList)) != null) + while ((connected = index.TakeConnected(startPoint, entityList, used)) != null) { shape.Entities.Add(connected); - entityList.Remove(connected); - - switch (connected.Type) - { - case EntityType.Arc: - var arc = (Arc)connected; - startPoint = arc.EndPoint(); - break; - - case EntityType.Line: - var line = (Line)connected; - startPoint = line.EndPoint; - break; - } + startPoint = EndOf(connected); } shape.UpdateBounds(); @@ -205,6 +186,131 @@ namespace OpenNest.Geometry } } + private static Vector EndOf(Entity entity) => entity.Type switch + { + EntityType.Arc => ((Arc)entity).EndPoint(), + EntityType.Line => ((Line)entity).EndPoint, + _ => new Vector(), + }; + + // Matches GetConnected entity by entity: true and reversed when only its end matches. + private static bool Connects(Entity entity, Vector pt, double tol) + { + switch (entity.Type) + { + case EntityType.Arc: + var arc = (Arc)entity; + if (arc.StartPoint().DistanceTo(pt) <= tol) + return true; + if (arc.EndPoint().DistanceTo(pt) <= tol) + { + arc.Reverse(); + return true; + } + return false; + + case EntityType.Line: + var line = (Line)entity; + if (line.StartPoint.DistanceTo(pt) <= tol) + return true; + if (line.EndPoint.DistanceTo(pt) <= tol) + { + line.Reverse(); + return true; + } + return false; + + default: + return false; + } + } + + /// + /// Entity positions by the grid cells of their endpoints, cells twice the chain + /// tolerance wide, so every endpoint within tolerance of a point lies in its cell or a + /// neighbor, rounding included. Reversing an entity swaps its endpoints, so the index stays valid. + /// Endpoints too far out or not finite to place are checked on every query. + /// + private sealed class EndpointIndex + { + private const double CellSize = 2 * Tolerance.ChainTolerance; + private const double MaxCell = 1e15; + private readonly Dictionary<(long, long), List> cells = new(); + private readonly List unplaced = new(); + private readonly List candidates = new(); + + public EndpointIndex(List entities) + { + for (var i = 0; i < entities.Count; i++) + { + var (start, end) = GetEndpoints(entities[i]); + if (!Place(i, start) | !Place(i, end)) + unplaced.Add(i); + } + } + + private bool Place(int i, Vector point) + { + if (!TryCell(point, out var cell)) + return false; + if (!cells.TryGetValue(cell, out var list)) + cells[cell] = list = new List(); + if (list.Count == 0 || list[^1] != i) + list.Add(i); + return true; + } + + private static bool TryCell(Vector point, out (long, long) cell) + { + var x = System.Math.Floor(point.X / CellSize); + var y = System.Math.Floor(point.Y / CellSize); + cell = default; + if (!(System.Math.Abs(x) < MaxCell) || !(System.Math.Abs(y) < MaxCell)) + return false; + cell = ((long)x, (long)y); + return true; + } + + /// The first unused entity, in list order, that connects to ; marked used. + public Entity TakeConnected(Vector pt, List entities, bool[] used) + { + candidates.Clear(); + if (TryCell(pt, out var cell)) + { + for (var dx = -1L; dx <= 1; dx++) + { + for (var dy = -1L; dy <= 1; dy++) + { + if (cells.TryGetValue((cell.Item1 + dx, cell.Item2 + dy), out var list)) + candidates.AddRange(list); + } + } + candidates.AddRange(unplaced); + } + else + { + // A point that cannot be placed is compared with every entity, as before. + for (var i = 0; i < entities.Count; i++) + candidates.Add(i); + } + + candidates.Sort(); + var previous = -1; + foreach (var i in candidates) + { + if (i == previous || used[i]) + continue; + previous = i; + if (Connects(entities[i], pt, Tolerance.ChainTolerance)) + { + used[i] = true; + return entities[i]; + } + } + return null; + } + } + internal static Entity GetConnected(Vector pt, IEnumerable geometry) { var tol = Tolerance.ChainTolerance; diff --git a/OpenNest.Core/Geometry/ShapeProfile.cs b/OpenNest.Core/Geometry/ShapeProfile.cs index a6ced1fe..5d951b20 100644 --- a/OpenNest.Core/Geometry/ShapeProfile.cs +++ b/OpenNest.Core/Geometry/ShapeProfile.cs @@ -15,10 +15,22 @@ namespace OpenNest.Geometry Update(entities); } - private void Update(List entities) + private ShapeProfile() { - var shapes = ShapeBuilder.GetShapes(entities); + } + /// A profile of shapes already built, for callers that need them too; at least one. + public static ShapeProfile FromShapes(List shapes) + { + var profile = new ShapeProfile(); + profile.Update(shapes); + return profile; + } + + private void Update(List entities) => Update(ShapeBuilder.GetShapes(entities)); + + private void Update(List shapes) + { Perimeter = shapes[0]; Cutouts = new List(); diff --git a/OpenNest/LayoutPart.cs b/OpenNest/LayoutPart.cs index 5d303b03..36149992 100644 --- a/OpenNest/LayoutPart.cs +++ b/OpenNest/LayoutPart.cs @@ -330,7 +330,7 @@ namespace OpenNest ); } - var profile = new ShapeProfile(nonRapid); + var profile = ShapeProfile.FromShapes(shapes); var outer = profile.Perimeter.ToPolygonWithTolerance(0.1); List holes = null;