From af2712e7009d2d05cca65e9199b951f5cdd6c0ed Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Tue, 24 Nov 2026 13:26:51 -0500 Subject: [PATCH] perf(core): triangulate, hull and flatten with the same results and less work Ear clipping walked every remaining vertex from the first after each ear, re-reading a remembered verdict for most of them. It now keeps the set of vertices whose verdict can have changed (an ear's two neighbors and the vertices it blocked) and takes the lowest, which tests the same vertices in the same order. The ear test reads the remaining vertices from packed arrays, several at a time where the hardware allows, with the arithmetic of PointInTriangle per lane. Working arrays are kept per thread. ConvexHull sorts in a per-thread buffer with the position as tie-break, the order the stable two-key LINQ sort gave. Shape flattening adds arc points straight to the polygon; Arc's sweep, segment-count and point arithmetic moved to static helpers so callers can flatten an arc without building one. A 246-vertex triangulation drops from about 410 to 115 microseconds. Triangles, hulls and polygons are bit-identical: the existing frozen ConvexDecomposition oracle tests pass, and new tests compare the hull and the flattening with the earlier code. Co-Authored-By: Claude Fable 5.2 --- OpenNest.Core/Converters/ConvertProgram.cs | 2 +- OpenNest.Core/Geometry/Arc.cs | 60 +++- OpenNest.Core/Geometry/Collision.cs | 15 +- OpenNest.Core/Geometry/ConvexDecomposition.cs | 329 ++++++++++++++---- OpenNest.Core/Geometry/ConvexHull.cs | 49 ++- OpenNest.Core/Geometry/Shape.cs | 14 +- .../Geometry/ConvexHullEquivalenceTests.cs | 227 ++++++++++++ 7 files changed, 599 insertions(+), 97 deletions(-) create mode 100644 OpenNest.Tests/Geometry/ConvexHullEquivalenceTests.cs diff --git a/OpenNest.Core/Converters/ConvertProgram.cs b/OpenNest.Core/Converters/ConvertProgram.cs index 39c7b55e..0c9200bc 100644 --- a/OpenNest.Core/Converters/ConvertProgram.cs +++ b/OpenNest.Core/Converters/ConvertProgram.cs @@ -166,7 +166,7 @@ namespace OpenNest.Converters /// end, which breaks contour chaining. Project the center onto the chord's /// perpendicular bisector so the arc passes through both endpoints exactly. /// - private static Vector FitCenterToEndpoints(Vector center, Vector start, Vector end) + internal static Vector FitCenterToEndpoints(Vector center, Vector start, Vector end) { var startRadius = center.DistanceTo(start); var endRadius = center.DistanceTo(end); diff --git a/OpenNest.Core/Geometry/Arc.cs b/OpenNest.Core/Geometry/Arc.cs index 98fb652c..2e9299d9 100644 --- a/OpenNest.Core/Geometry/Arc.cs +++ b/OpenNest.Core/Geometry/Arc.cs @@ -101,12 +101,15 @@ namespace OpenNest.Geometry /// Angle in radians between start and end angles. /// /// - public double SweepAngle() - { - var startAngle = StartAngle; - var endAngle = EndAngle; + public double SweepAngle() => SweepAngle(StartAngle, EndAngle, IsReversed); - if (IsReversed) + /// + /// of an arc with these angles and direction, for callers + /// that flatten arcs without building them. + /// + internal static double SweepAngle(double startAngle, double endAngle, bool reversed) + { + if (reversed) Generic.Swap(ref startAngle, ref endAngle); if (startAngle > endAngle) @@ -226,15 +229,21 @@ namespace OpenNest.Geometry /// Returns the minimum number of segments needed so that the chord-to-arc /// deviation (sagitta) does not exceed the given tolerance. /// - public int SegmentsForTolerance(double tolerance) + public int SegmentsForTolerance(double tolerance) => + SegmentsForTolerance(Radius, SweepAngle(), tolerance); + + /// + /// of an arc with this radius and sweep. + /// + internal static int SegmentsForTolerance(double radius, double sweepAngle, double tolerance) { - if (tolerance >= Radius) + if (tolerance >= radius) return 1; - var maxAngle = 2.0 * PortableMath.Acos(1.0 - tolerance / Radius); + var maxAngle = 2.0 * PortableMath.Acos(1.0 - tolerance / radius); return System.Math.Max( 1, - (int)System.Math.Ceiling(System.Math.Abs(SweepAngle()) / maxAngle) + (int)System.Math.Ceiling(System.Math.Abs(sweepAngle) / maxAngle) ); } @@ -246,26 +255,43 @@ namespace OpenNest.Geometry public List ToPoints(int segments = 1000, bool circumscribe = false) { var points = new List(); - var stepAngle = reversed ? -SweepAngle() / segments : SweepAngle() / segments; + AppendPoints(points, center, radius, startAngle, SweepAngle(), reversed, segments, circumscribe); + return points; + } + + /// + /// Adds the points gives for an arc with these values to + /// , without building the arc or a list for it. + /// + internal static void AppendPoints( + List points, + Vector center, + double radius, + double startAngle, + double sweepAngle, + bool reversed, + int segments, + bool circumscribe + ) + { + var stepAngle = reversed ? -sweepAngle / segments : sweepAngle / segments; var r = circumscribe && segments > 0 - ? Radius / PortableMath.Cos(System.Math.Abs(stepAngle) / 2.0) - : Radius; + ? radius / PortableMath.Cos(System.Math.Abs(stepAngle) / 2.0) + : radius; for (int i = 0; i <= segments; ++i) { - var angle = stepAngle * i + StartAngle; + var angle = stepAngle * i + startAngle; points.Add( new Vector( - PortableMath.Cos(angle) * r + Center.X, - PortableMath.Sin(angle) * r + Center.Y + PortableMath.Cos(angle) * r + center.X, + PortableMath.Sin(angle) * r + center.Y ) ); } - - return points; } /// diff --git a/OpenNest.Core/Geometry/Collision.cs b/OpenNest.Core/Geometry/Collision.cs index 6480de5f..011cb1b5 100644 --- a/OpenNest.Core/Geometry/Collision.cs +++ b/OpenNest.Core/Geometry/Collision.cs @@ -112,10 +112,21 @@ namespace OpenNest.Geometry /// as the clip loop reads it, without a polygon per triangle: /// the same triangles, vertices and bounds. Callers may reuse it for the same polygon. /// - internal static List TriangulateForClipping(Polygon polygon) + internal static List TriangulateForClipping(Polygon polygon) => + TriangulateForClipping(polygon, new List(polygon.Vertices.Count)); + + /// + /// into a list the caller reuses: it is + /// emptied first and returned holding the same triangles. + /// + internal static List TriangulateForClipping( + Polygon polygon, + List triangles + ) { PerfCounters.CountPolygonTriangulation(); - var sink = new TriangleSink(new List(polygon.Vertices.Count)); + triangles.Clear(); + var sink = new TriangleSink(triangles); ConvexDecomposition.Triangulate(polygon, ref sink); return sink.Triangles; } diff --git a/OpenNest.Core/Geometry/ConvexDecomposition.cs b/OpenNest.Core/Geometry/ConvexDecomposition.cs index b9d7bf79..d49bd3b9 100644 --- a/OpenNest.Core/Geometry/ConvexDecomposition.cs +++ b/OpenNest.Core/Geometry/ConvexDecomposition.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using NumericVector = System.Numerics.Vector; namespace OpenNest.Geometry { @@ -54,112 +55,234 @@ namespace OpenNest.Geometry internal static void Triangulate(Polygon polygon, ref TSink sink) where TSink : struct, IEarSink { - var verts = new List(polygon.Vertices); + var source = polygon.Vertices; + var count = source.Count; // Remove closing vertex if polygon is closed. if ( - verts.Count > 1 - && verts[0].X == verts[verts.Count - 1].X - && verts[0].Y == verts[verts.Count - 1].Y + count > 1 + && source[0].X == source[count - 1].X + && source[0].Y == source[count - 1].Y ) - verts.RemoveAt(verts.Count - 1); + count--; - if (verts.Count < 3) + if (count < 3) return; - // Ensure counter-clockwise winding for ear detection. - if (SignedArea(verts) < 0) - verts.Reverse(); + // The working arrays are kept per thread and reused: a triangulation fills the + // part it needs before reading it, and no sink triangulates in turn. + var scratch = workspace ??= new Workspace(); + scratch.Reserve(count); - // The remaining vertices, in their original order, as a circular linked list: head is - // the first remaining vertex (scan position 0), and cutting an ear unlinks one vertex - // instead of shifting every later index down. - var count = verts.Count; - var nextOf = new int[count]; - var prevOf = new int[count]; + var verts = scratch.Vertices; + for (var i = 0; i < count; i++) + verts[i] = source[i]; + + // Ensure counter-clockwise winding for ear detection. + if (SignedArea(verts, count) < 0) + System.Array.Reverse(verts, 0, count); + + // The remaining vertices, in their original order, as a circular linked list: cutting + // an ear unlinks one vertex instead of shifting every later index down. + var nextOf = scratch.NextOf; + var prevOf = scratch.PrevOf; for (var i = 0; i < count; i++) { nextOf[i] = (i + 1) % count; prevOf[i] = (i + count - 1) % count; } - var head = 0; var n = count; - // The scan restarts at the first remaining vertex after every ear. A vertex that - // failed the ear test keeps failing it while its two neighbors are unchanged and - // the vertex found inside its triangle (or none, when it was not convex) remains, - // since the test depends on nothing else. Remembering why it failed skips repeating - // the O(n) test; the vertices visited, their verdicts and the ears cut are the same. - var removed = new bool[count]; - var failedPrev = new int[count]; - var failedNext = new int[count]; - var failedBlocker = new int[count]; + // The same remaining vertices packed in that order, with each one's original index, + // so the ear test reads them straight through instead of following the links. + var xs = scratch.Xs; + var ys = scratch.Ys; + var ids = scratch.Ids; for (var i = 0; i < count; i++) - failedPrev[i] = -1; - - // Safety counter to avoid infinite loop on degenerate polygons. - var maxIterations = n * n; - var iterations = 0; - var cursor = head; - - while (n > 2 && iterations < maxIterations) { - iterations++; + xs[i] = verts[i].X; + ys[i] = verts[i].Y; + ids[i] = i; + } + + // Ear clipping cuts the first remaining vertex, in order, that is an ear, and after + // every ear looks again from the first remaining vertex. A vertex that failed the + // ear test keeps failing it while its two neighbors are unchanged and the vertex + // found inside its triangle (or none, when it was not convex) remains, since the + // test depends on nothing else. So only the vertices in 'untested' can be ears: all + // of them at first, and after an ear its two neighbors and the vertices it blocked. + // Taking the lowest of those each time tests the same vertices in the same order as + // walking every remaining vertex from the first, and cuts the same ears. + var untested = scratch.Untested; + var words = (count + 63) / 64; + System.Array.Clear(untested, 0, words); + for (var i = 0; i < count; i++) + untested[i >> 6] |= 1UL << i; + + // The failed vertices each vertex blocks, as doubly linked lists threaded through + // the vertices: a vertex waits on at most one blocker. + var firstBlocked = scratch.FirstBlocked; + var blockedBy = scratch.BlockedBy; + var nextBlocked = scratch.NextBlocked; + var prevBlocked = scratch.PrevBlocked; + for (var i = 0; i < count; i++) + { + firstBlocked[i] = -1; + blockedBy[i] = -1; + } + + while (n > 2) + { + var currVertex = LowestSet(untested, words); + + // Every remaining vertex is known not to be an ear: nothing more can be cut. + if (currVertex < 0) + break; + + untested[currVertex >> 6] &= ~(1UL << currVertex); + + // Tested again, so it no longer waits on the vertex that blocked it before. + if (blockedBy[currVertex] >= 0) + Unblock(currVertex, firstBlocked, blockedBy, nextBlocked, prevBlocked); - var currVertex = cursor; var prevVertex = prevOf[currVertex]; var nextVertex = nextOf[currVertex]; - - var knownNotEar = - failedPrev[currVertex] == prevVertex - && failedNext[currVertex] == nextVertex - && (failedBlocker[currVertex] < 0 || !removed[failedBlocker[currVertex]]); - var prev = verts[prevVertex]; var curr = verts[currVertex]; var next = verts[nextVertex]; - var blocker = failedBlocker[currVertex]; - if (!knownNotEar && IsEar(prev, curr, next, verts, nextOf, head, n, out blocker)) + if (IsEar(prev, curr, next, xs, ys, ids, n, out var blocker)) { sink.Add(prev, curr, next); + var packed = System.Array.BinarySearch(ids, 0, n, currVertex); + var after = n - packed - 1; + System.Array.Copy(xs, packed + 1, xs, packed, after); + System.Array.Copy(ys, packed + 1, ys, packed, after); + System.Array.Copy(ids, packed + 1, ids, packed, after); + nextOf[prevVertex] = nextVertex; prevOf[nextVertex] = prevVertex; - removed[currVertex] = true; - if (head == currVertex) - head = nextVertex; n--; - cursor = head; - } - else - { - if (!knownNotEar) + + untested[prevVertex >> 6] |= 1UL << prevVertex; + untested[nextVertex >> 6] |= 1UL << nextVertex; + + for (var waiting = firstBlocked[currVertex]; waiting >= 0; waiting = nextBlocked[waiting]) { - failedPrev[currVertex] = prevVertex; - failedNext[currVertex] = nextVertex; - failedBlocker[currVertex] = blocker; + blockedBy[waiting] = -1; + untested[waiting >> 6] |= 1UL << waiting; } - // The last remaining vertex links back to head, as position n wraps to 0. - cursor = nextVertex; + firstBlocked[currVertex] = -1; + } + else if (blocker >= 0) + { + var first = firstBlocked[blocker]; + blockedBy[currVertex] = blocker; + prevBlocked[currVertex] = -1; + nextBlocked[currVertex] = first; + if (first >= 0) + prevBlocked[first] = currVertex; + firstBlocked[blocker] = currVertex; } } } + [System.ThreadStatic] + private static Workspace workspace; + + /// One thread's working arrays, grown to the largest polygon it has triangulated. + private sealed class Workspace + { + public Vector[] Vertices = System.Array.Empty(); + public double[] Xs; + public double[] Ys; + public int[] Ids; + public int[] NextOf; + public int[] PrevOf; + public int[] FirstBlocked; + public int[] BlockedBy; + public int[] NextBlocked; + public int[] PrevBlocked; + public ulong[] Untested; + + public void Reserve(int count) + { + if (Vertices.Length >= count) + return; + + var size = System.Math.Max(count, Vertices.Length * 2); + Vertices = new Vector[size]; + Xs = new double[size]; + Ys = new double[size]; + Ids = new int[size]; + NextOf = new int[size]; + PrevOf = new int[size]; + FirstBlocked = new int[size]; + BlockedBy = new int[size]; + NextBlocked = new int[size]; + PrevBlocked = new int[size]; + Untested = new ulong[(size + 63) / 64]; + } + } + + /// The lowest set bit's position in the first words, or -1 when none is set. + private static int LowestSet(ulong[] bits, int words) + { + for (var word = 0; word < words; word++) + { + if (bits[word] != 0) + return (word << 6) + System.Numerics.BitOperations.TrailingZeroCount(bits[word]); + } + + return -1; + } + + /// Takes off the list of the vertex that blocks it. + private static void Unblock( + int vertex, + int[] firstBlocked, + int[] blockedBy, + int[] nextBlocked, + int[] prevBlocked + ) + { + var before = prevBlocked[vertex]; + var after = nextBlocked[vertex]; + + if (before >= 0) + nextBlocked[before] = after; + else + firstBlocked[blockedBy[vertex]] = after; + + if (after >= 0) + prevBlocked[after] = before; + + blockedBy[vertex] = -1; + } + /// /// Tests whether the vertex at curr forms an ear (a convex vertex whose /// triangle contains no other polygon vertices). A vertex that fails reports the /// first remaining vertex found inside its triangle, or -1 when it is not convex. + /// The remaining vertices are the first of , + /// and , in scan order. + /// + /// Several vertices are tested at a time where the hardware allows. Each lane does the + /// subtractions, multiplications and comparisons of for + /// its vertex, in the same order and never fused, so it reaches the same verdict; a + /// group with a vertex that may block is then walked one by one to report the first. + /// /// private static bool IsEar( Vector prev, Vector curr, Vector next, - List verts, - int[] nextOf, - int head, + double[] xs, + double[] ys, + int[] ids, int n, out int blocker ) @@ -172,20 +295,71 @@ namespace OpenNest.Geometry return false; // Check that no other vertex lies inside the triangle. - for (int i = 0, index = head; i < n; i++, index = nextOf[index]) + var i = 0; + + if (NumericVector.IsHardwareAccelerated) { - var v = verts[index]; + var width = System.Numerics.Vector.Count; + var zero = System.Numerics.Vector.Zero; + var all = new System.Numerics.Vector(-1); + var prevX = new System.Numerics.Vector(prev.X); + var prevY = new System.Numerics.Vector(prev.Y); + var currX = new System.Numerics.Vector(curr.X); + var currY = new System.Numerics.Vector(curr.Y); + var nextX = new System.Numerics.Vector(next.X); + var nextY = new System.Numerics.Vector(next.Y); - if (v.X == prev.X && v.Y == prev.Y) - continue; - if (v.X == curr.X && v.Y == curr.Y) - continue; - if (v.X == next.X && v.Y == next.Y) - continue; + // The edge vectors Cross forms first: b - a for (prev, curr), (curr, next) + // and (next, prev). + var edge1X = new System.Numerics.Vector(curr.X - prev.X); + var edge1Y = new System.Numerics.Vector(curr.Y - prev.Y); + var edge2X = new System.Numerics.Vector(next.X - curr.X); + var edge2Y = new System.Numerics.Vector(next.Y - curr.Y); + var edge3X = new System.Numerics.Vector(prev.X - next.X); + var edge3Y = new System.Numerics.Vector(prev.Y - next.Y); - if (PointInTriangle(v, prev, curr, next)) + for (; i <= n - width; i += width) { - blocker = index; + var x = new System.Numerics.Vector(xs, i); + var y = new System.Numerics.Vector(ys, i); + + var d1 = edge1X * (y - prevY) - edge1Y * (x - prevX); + var d2 = edge2X * (y - currY) - edge2Y * (x - currX); + var d3 = edge3X * (y - nextY) - edge3Y * (x - nextX); + + var hasNeg = + NumericVector.LessThan(d1, zero) + | NumericVector.LessThan(d2, zero) + | NumericVector.LessThan(d3, zero); + var hasPos = + NumericVector.GreaterThan(d1, zero) + | NumericVector.GreaterThan(d2, zero) + | NumericVector.GreaterThan(d3, zero); + var corner = + (NumericVector.Equals(x, prevX) & NumericVector.Equals(y, prevY)) + | (NumericVector.Equals(x, currX) & NumericVector.Equals(y, currY)) + | (NumericVector.Equals(x, nextX) & NumericVector.Equals(y, nextY)); + + // A lane passes when it is one of the triangle's corners or outside it. + if (NumericVector.EqualsAll((hasNeg & hasPos) | corner, all)) + continue; + + for (var lane = i; lane < i + width; lane++) + { + if (Blocks(new Vector(xs[lane], ys[lane]), prev, curr, next)) + { + blocker = ids[lane]; + return false; + } + } + } + } + + for (; i < n; i++) + { + if (Blocks(new Vector(xs[i], ys[i]), prev, curr, next)) + { + blocker = ids[i]; return false; } } @@ -193,6 +367,19 @@ namespace OpenNest.Geometry return true; } + /// Whether a remaining vertex, not one of the triangle's corners, lies inside it. + private static bool Blocks(Vector v, Vector prev, Vector curr, Vector next) + { + if (v.X == prev.X && v.Y == prev.Y) + return false; + if (v.X == curr.X && v.Y == curr.Y) + return false; + if (v.X == next.X && v.Y == next.Y) + return false; + + return PointInTriangle(v, prev, curr, next); + } + /// /// Returns positive value if A→B→C is a CCW (left) turn. /// @@ -220,13 +407,13 @@ namespace OpenNest.Geometry /// /// Signed area of a polygon. Positive = CCW, negative = CW. /// - private static double SignedArea(List verts) + private static double SignedArea(Vector[] verts, int count) { // World-coordinate products can erase the sign of a small polygon's area // far from the origin, leaving CW outlines/holes untriangulated. Measure // relative to a vertex, just as the clipping kernel measures its fragments. var area = 0.0; - for (var i = 1; i + 1 < verts.Count; i++) + for (var i = 1; i + 1 < count; i++) area += Cross(verts[0], verts[i], verts[i + 1]); return area * 0.5; diff --git a/OpenNest.Core/Geometry/ConvexHull.cs b/OpenNest.Core/Geometry/ConvexHull.cs index d9eeed71..19b71346 100644 --- a/OpenNest.Core/Geometry/ConvexHull.cs +++ b/OpenNest.Core/Geometry/ConvexHull.cs @@ -14,12 +14,26 @@ namespace OpenNest.Geometry return result; } - var sorted = points.OrderBy(p => p.X).ThenBy(p => p.Y).ToList(); + // By X, then Y, equal points in their given order: the order a stable sort on + // those two keys gives. The position breaks ties, so no two entries compare equal + // and the unstable array sort has only one result. The buffer is kept per thread. + var count = points.Count; + var sorted = sortBuffer; + + if (sorted == null || sorted.Length < count) + sortBuffer = sorted = new SortedPoint[System.Math.Max(count, 64)]; + + for (var i = 0; i < count; i++) + sorted[i] = new SortedPoint(points[i], i); + + System.Array.Sort(sorted, 0, count); var lower = new List(); - foreach (var p in sorted) + for (var i = 0; i < count; i++) { + var p = sorted[i].Point; + while ( lower.Count >= 2 && Cross(lower[lower.Count - 2], lower[lower.Count - 1], p) <= 0 @@ -31,9 +45,9 @@ namespace OpenNest.Geometry var upper = new List(); - for (int i = sorted.Count - 1; i >= 0; i--) + for (int i = count - 1; i >= 0; i--) { - var p = sorted[i]; + var p = sorted[i].Point; while ( upper.Count >= 2 @@ -58,6 +72,33 @@ namespace OpenNest.Geometry return hull; } + [System.ThreadStatic] + private static SortedPoint[] sortBuffer; + + private readonly struct SortedPoint : System.IComparable + { + private readonly int position; + + public SortedPoint(Vector point, int position) + { + Point = point; + this.position = position; + } + + public Vector Point { get; } + + public int CompareTo(SortedPoint other) + { + var byX = Point.X.CompareTo(other.Point.X); + + if (byX != 0) + return byX; + + var byY = Point.Y.CompareTo(other.Point.Y); + return byY != 0 ? byY : position.CompareTo(other.position); + } + } + private static double Cross(Vector o, Vector a, Vector b) { return (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X); diff --git a/OpenNest.Core/Geometry/Shape.cs b/OpenNest.Core/Geometry/Shape.cs index ee536383..ec8c95b4 100644 --- a/OpenNest.Core/Geometry/Shape.cs +++ b/OpenNest.Core/Geometry/Shape.cs @@ -314,12 +314,22 @@ namespace OpenNest.Geometry { case EntityType.Arc: var arc = (Arc)entity; - polygon.Vertices.AddRange(arc.ToPoints(arcSegments(arc), circumscribe)); + Arc.AppendPoints( + polygon.Vertices, + arc.Center, + arc.Radius, + arc.StartAngle, + arc.SweepAngle(), + arc.IsReversed, + arcSegments(arc), + circumscribe + ); break; case EntityType.Line: var line = (Line)entity; - polygon.Vertices.AddRange(new[] { line.StartPoint, line.EndPoint }); + polygon.Vertices.Add(line.StartPoint); + polygon.Vertices.Add(line.EndPoint); break; case EntityType.Circle: diff --git a/OpenNest.Tests/Geometry/ConvexHullEquivalenceTests.cs b/OpenNest.Tests/Geometry/ConvexHullEquivalenceTests.cs new file mode 100644 index 00000000..4e1d5adf --- /dev/null +++ b/OpenNest.Tests/Geometry/ConvexHullEquivalenceTests.cs @@ -0,0 +1,227 @@ +using OpenNest.Geometry; +using OpenNest.Math; + +namespace OpenNest.Tests.Geometry; + +/// +/// sorts its points in a reused buffer instead of through a +/// stable two-key LINQ sort, and flattens arcs +/// straight into the polygon. These tests compare both bit for bit with the earlier code, +/// written out here. +/// +public class ConvexHullEquivalenceTests +{ + [Fact] + public void SeededPoints_MatchStableSortHullBitwise() + { + var random = new Random(24112026); + + for (var i = 0; i < 4000; i++) + { + var points = MakePoints(random, i); + + Assert.True( + Bits(LegacyHull(points)).SequenceEqual(Bits(ConvexHull.Compute(points).Vertices)), + $"point set {i} (kind {i % 5}, {points.Count} points)" + ); + } + } + + [Fact] + public void Compute_DoesNotReorderInput() + { + var random = new Random(3); + var points = MakePoints(random, 0); + var before = Bits(points); + + ConvexHull.Compute(points); + + Assert.True(before.SequenceEqual(Bits(points))); + } + + [Fact] + public void FlattenedShape_MatchesPerEntityPointsBitwise() + { + var random = new Random(11); + + for (var i = 0; i < 500; i++) + { + var shape = new Shape(); + var count = 1 + random.Next(6); + + for (var j = 0; j < count; j++) + { + if (random.Next(3) == 0) + { + shape.Entities.Add(new Line(Point(random), Point(random))); + continue; + } + + shape.Entities.Add(new Arc( + Point(random), + 0.0005 + random.NextDouble() * 6, + random.NextDouble() * Angle.TwoPI, + random.NextDouble() * Angle.TwoPI, + random.Next(2) == 0 + )); + } + + foreach (var tolerance in new[] { 0.01, 0.001 }) + { + foreach (var circumscribe in new[] { false, true }) + { + var expected = new Polygon(); + + foreach (var entity in shape.Entities) + { + if (entity is Line line) + expected.Vertices.AddRange(new[] { line.StartPoint, line.EndPoint }); + else if (entity is Arc arc) + expected.Vertices.AddRange(LegacyArcPoints(arc, LegacySegments(arc, tolerance), circumscribe)); + } + + expected.Close(); + expected.Cleanup(); + + var actual = shape.ToPolygonWithTolerance(tolerance, circumscribe); + + Assert.True(Bits(expected.Vertices).SequenceEqual(Bits(actual.Vertices)), $"shape {i}"); + } + } + } + } + + /// The hull as computed before: a stable sort by X then Y, then the monotone chain. + private static List LegacyHull(IList points) + { + if (points.Count < 3) + return points.ToList(); + + var sorted = points.OrderBy(p => p.X).ThenBy(p => p.Y).ToList(); + var lower = new List(); + + foreach (var p in sorted) + { + while (lower.Count >= 2 && Cross(lower[lower.Count - 2], lower[lower.Count - 1], p) <= 0) + lower.RemoveAt(lower.Count - 1); + + lower.Add(p); + } + + var upper = new List(); + + for (var i = sorted.Count - 1; i >= 0; i--) + { + var p = sorted[i]; + + while (upper.Count >= 2 && Cross(upper[upper.Count - 2], upper[upper.Count - 1], p) <= 0) + upper.RemoveAt(upper.Count - 1); + + upper.Add(p); + } + + lower.RemoveAt(lower.Count - 1); + upper.RemoveAt(upper.Count - 1); + lower.AddRange(upper); + + var hull = new Polygon(); + hull.Vertices.AddRange(lower); + hull.Close(); + return hull.Vertices; + } + + private static double Cross(Vector o, Vector a, Vector b) => + (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X); + + /// Arc.SegmentsForTolerance as it was before its arithmetic moved to a shared helper. + private static int LegacySegments(Arc arc, double tolerance) + { + if (tolerance >= arc.Radius) + return 1; + + var maxAngle = 2.0 * PortableMath.Acos(1.0 - tolerance / arc.Radius); + return System.Math.Max(1, (int)System.Math.Ceiling(System.Math.Abs(LegacySweep(arc)) / maxAngle)); + } + + private static double LegacySweep(Arc arc) + { + var startAngle = arc.StartAngle; + var endAngle = arc.EndAngle; + + if (arc.IsReversed) + (startAngle, endAngle) = (endAngle, startAngle); + + if (startAngle > endAngle) + startAngle -= Angle.TwoPI; + + return endAngle - startAngle; + } + + /// Arc.ToPoints as it was before its arithmetic moved to a shared helper. + private static List LegacyArcPoints(Arc arc, int segments, bool circumscribe) + { + var points = new List(); + var stepAngle = arc.IsReversed ? -LegacySweep(arc) / segments : LegacySweep(arc) / segments; + + var r = + circumscribe && segments > 0 + ? arc.Radius / PortableMath.Cos(System.Math.Abs(stepAngle) / 2.0) + : arc.Radius; + + for (var i = 0; i <= segments; ++i) + { + var angle = stepAngle * i + arc.StartAngle; + points.Add(new Vector(PortableMath.Cos(angle) * r + arc.Center.X, PortableMath.Sin(angle) * r + arc.Center.Y)); + } + + return points; + } + + private static List MakePoints(Random random, int index) + { + var count = index % 7 == 0 ? random.Next(4) : 3 + random.Next(300); + var points = new List(count); + + for (var i = 0; i < count; i++) + { + switch (index % 5) + { + // Scattered. + case 0: + points.Add(Point(random)); + break; + + // A coarse grid: many equal X values, equal points and collinear runs. + case 1: + points.Add(new Vector(random.Next(6), random.Next(6))); + break; + + // Two columns, so the sort is decided by Y almost everywhere. + case 2: + points.Add(new Vector(random.Next(2) * 3.5, System.Math.Round(random.NextDouble() * 4, 1))); + break; + + // On a circle, where nearly every point is on the hull. + case 3: + var angle = random.NextDouble() * Angle.TwoPI; + points.Add(new Vector(5 * System.Math.Cos(angle), 5 * System.Math.Sin(angle))); + break; + + // Signed zeros and repeats of one point. + default: + points.Add(random.Next(3) == 0 + ? new Vector(random.Next(2) == 0 ? 0.0 : -0.0, random.Next(2) == 0 ? 0.0 : -0.0) + : new Vector(random.Next(3) - 1, random.Next(3) - 1)); + break; + } + } + + return points; + } + + private static Vector Point(Random random) => + new(random.NextDouble() * 20 - 10, random.NextDouble() * 20 - 10); + + private static long[] Bits(IEnumerable points) => + points.SelectMany(p => new[] { p.X, p.Y }).Select(BitConverter.DoubleToInt64Bits).ToArray(); +}