diff --git a/OpenNest.Core/Geometry/Collision.cs b/OpenNest.Core/Geometry/Collision.cs
index fe60a369..f216ff91 100644
--- a/OpenNest.Core/Geometry/Collision.cs
+++ b/OpenNest.Core/Geometry/Collision.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Runtime.InteropServices;
using OpenNest.Math;
namespace OpenNest.Geometry
@@ -82,6 +83,24 @@ namespace OpenNest.Geometry
return OverlapRegions(trianglesA(), trianglesB(), holesA, holesB, verdictOnly: true).Count > 0;
}
+ ///
+ /// with each
+ /// polygon's supplied by the caller and resolved
+ /// lazily, only after the bounding boxes overlap; the verdict is then identical.
+ ///
+ internal static bool HasOverlapTriangulated(
+ Polygon a,
+ Func> trianglesA,
+ Polygon b,
+ Func> trianglesB
+ )
+ {
+ if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox))
+ return false;
+
+ return OverlapRegions(trianglesA(), trianglesB(), null, null, verdictOnly: true).Count > 0;
+ }
+
///
/// The triangulation and
/// use for : ear-clipped triangles with bounds updated. Callers
@@ -89,6 +108,28 @@ namespace OpenNest.Geometry
///
internal static List Triangulate(Polygon polygon) => TriangulateWithBounds(polygon);
+ ///
+ /// 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)
+ {
+ PerfCounters.CountPolygonTriangulation();
+ var sink = new TriangleSink(new List(polygon.Vertices.Count));
+ ConvexDecomposition.Triangulate(polygon, ref sink);
+ return sink.Triangles;
+ }
+
+ private readonly struct TriangleSink : ConvexDecomposition.IEarSink
+ {
+ public TriangleSink(List triangles) => Triangles = triangles;
+
+ public List Triangles { get; }
+
+ public void Add(Vector prev, Vector curr, Vector next) =>
+ Triangles.Add(new CollisionTriangle(prev, curr, next));
+ }
+
public static List CheckAll(
List polygons,
List> holes = null
@@ -140,7 +181,32 @@ namespace OpenNest.Geometry
List holesA,
List holesB,
bool verdictOnly = false
- ) => OverlapRegions(TriangulateWithBounds(a), TriangulateWithBounds(b), holesA, holesB, verdictOnly);
+ ) => OverlapRegions(TriangulateForClipping(a), TriangulateForClipping(b), holesA, holesB, verdictOnly);
+
+ ///
+ ///
+ /// over triangles: the same pairs clipped in the same
+ /// order, so the same regions.
+ ///
+ private static List OverlapRegions(
+ List trisA,
+ List trisB,
+ List holesA,
+ List holesB,
+ bool verdictOnly = false
+ )
+ {
+ var regions = new List();
+ var stopAtFirst = verdictOnly
+ && (holesA == null || holesA.Count == 0)
+ && (holesB == null || holesB.Count == 0);
+ ClipTrianglePairs(trisA, trisB, regions, stopAtFirst);
+
+ if (regions.Count > 0)
+ regions = SubtractHoles(regions, holesA, holesB);
+
+ return regions;
+ }
private static List OverlapRegions(
List trisA,
@@ -219,6 +285,215 @@ namespace OpenNest.Geometry
}
}
+ ///
+ /// over
+ /// s, clipping in two reused buffers: the same pairs in the
+ /// same order with the same arithmetic, and a region polygon built only for a pair that
+ /// overlaps.
+ ///
+ private static void ClipTrianglePairs(
+ List trisA,
+ List trisB,
+ List regions,
+ bool stopAtFirst
+ )
+ {
+ if (trisA.Count == 0 || trisB.Count == 0)
+ return;
+
+ var candidatesA = TrianglesTouching(trisA, UnionBounds(trisB));
+ if (candidatesA.Count == 0)
+ return;
+
+ var candidatesB = TrianglesTouching(trisB, UnionBounds(trisA));
+ if (candidatesB.Count == 0)
+ return;
+
+ Span first = stackalloc Vector[MaxClippedVertices];
+ Span second = stackalloc Vector[MaxClippedVertices];
+ Span distances = stackalloc double[MaxClippedVertices];
+ var spanA = CollectionsMarshal.AsSpan(trisA);
+ var spanB = CollectionsMarshal.AsSpan(trisB);
+
+ foreach (var a in candidatesA)
+ {
+ ref readonly var triA = ref spanA[a];
+
+ foreach (var b in candidatesB)
+ {
+ ref readonly var triB = ref spanB[b];
+ if (!BoundingBoxesOverlap(triA, triB))
+ continue;
+
+ var clipped = ClipConvex(triA, triB, first, second, distances);
+ if (clipped == null)
+ continue;
+
+ regions.Add(clipped);
+ if (stopAtFirst)
+ return;
+ }
+ }
+ }
+
+ ///
+ /// Most vertices clipping a triangle by a triangle's three half-spaces can leave: each
+ /// half-space keeps each vertex and adds at most one crossing after it.
+ ///
+ private const int MaxClippedVertices = 3 * 2 * 2 * 2;
+
+ private static (double Left, double Right, double Bottom, double Top) UnionBounds(
+ List triangles
+ )
+ {
+ var left = double.PositiveInfinity;
+ var right = double.NegativeInfinity;
+ var bottom = double.PositiveInfinity;
+ var top = double.NegativeInfinity;
+
+ foreach (var triangle in triangles)
+ {
+ left = System.Math.Min(left, triangle.Left);
+ right = System.Math.Max(right, triangle.Right);
+ bottom = System.Math.Min(bottom, triangle.Bottom);
+ top = System.Math.Max(top, triangle.Top);
+ }
+
+ return (left, right, bottom, top);
+ }
+
+ /// Indices of the triangles the polygon form of this test keeps, in order.
+ private static List TrianglesTouching(
+ List triangles,
+ (double Left, double Right, double Bottom, double Top) union
+ )
+ {
+ var result = new List(triangles.Count);
+
+ for (var i = 0; i < triangles.Count; i++)
+ {
+ var box = triangles[i];
+ var overlapX = System.Math.Min(box.Right, union.Right) - System.Math.Max(box.Left, union.Left);
+ var overlapY = System.Math.Min(box.Top, union.Top) - System.Math.Max(box.Bottom, union.Bottom);
+
+ if (overlapX > Tolerance.Epsilon && overlapY > Tolerance.Epsilon)
+ result.Add(i);
+ }
+
+ return result;
+ }
+
+ private static bool BoundingBoxesOverlap(in CollisionTriangle a, in CollisionTriangle b)
+ {
+ var overlapX = System.Math.Min(a.Right, b.Right) - System.Math.Max(a.Left, b.Left);
+ var overlapY = System.Math.Min(a.Top, b.Top) - System.Math.Max(a.Bottom, b.Bottom);
+
+ return overlapX > Tolerance.Epsilon && overlapY > Tolerance.Epsilon;
+ }
+
+ ///
+ /// of two triangles' open vertices,
+ /// alternating between two caller buffers of .
+ ///
+ private static Polygon ClipConvex(
+ in CollisionTriangle subject,
+ in CollisionTriangle clip,
+ Span first,
+ Span second,
+ Span distances
+ )
+ {
+ var count = subject.Count;
+ for (var i = 0; i < count; i++)
+ first[i] = subject[i];
+
+ var output = first;
+ var spare = second;
+ for (var i = 0; i < clip.Count && count >= 3; i++)
+ {
+ count = ClipHalfSpaceInside(output.Slice(0, count), clip[i], clip[(i + 1) % clip.Count], spare,
+ distances);
+ var swap = output;
+ output = spare;
+ spare = swap;
+ }
+
+ return PositiveAreaPolygon(output.Slice(0, count));
+ }
+
+ ///
+ /// keeping the inside, written to ;
+ /// returns how many it kept. Each vertex's signed distance is computed once into
+ /// , the same value ClipHalfSpace computes for it twice.
+ ///
+ private static int ClipHalfSpaceInside(
+ ReadOnlySpan vertices,
+ Vector edgeStart,
+ Vector edgeEnd,
+ Span kept,
+ Span distances
+ )
+ {
+ var inside = false;
+ for (var i = 0; i < vertices.Length; i++)
+ {
+ distances[i] = Cross(edgeStart, edgeEnd, vertices[i]);
+ inside |= distances[i] >= 0;
+ }
+
+ // Every vertex strictly outside keeps nothing and crosses nowhere.
+ if (!inside)
+ return 0;
+
+ var count = 0;
+ for (var i = 0; i < vertices.Length; i++)
+ {
+ var current = vertices[i];
+ var nextIndex = i + 1 == vertices.Length ? 0 : i + 1;
+ var next = vertices[nextIndex];
+ var currentDistance = distances[i];
+ var nextDistance = distances[nextIndex];
+ if (currentDistance >= 0)
+ AddDistinct(kept, ref count, current);
+
+ if ((currentDistance < 0 && nextDistance > 0) || (currentDistance > 0 && nextDistance < 0))
+ {
+ var t = currentDistance / (currentDistance - nextDistance);
+ AddDistinct(kept, ref count, new Vector(
+ current.X + t * (next.X - current.X),
+ current.Y + t * (next.Y - current.Y)));
+ }
+ }
+ if (count > 1 && SamePoint(kept[0], kept[count - 1]))
+ count--;
+ return count;
+ }
+
+ private static void AddDistinct(Span vertices, ref int count, Vector point)
+ {
+ if (count == 0 || !SamePoint(vertices[count - 1], point))
+ vertices[count++] = point;
+ }
+
+ private static Polygon PositiveAreaPolygon(ReadOnlySpan vertices)
+ {
+ if (vertices.Length < 3)
+ return null;
+
+ var twiceArea = 0.0;
+ for (var i = 1; i + 1 < vertices.Length; i++)
+ twiceArea += Cross(vertices[0], vertices[i], vertices[i + 1]);
+ if (System.Math.Abs(twiceArea) <= 2 * Tolerance.Epsilon)
+ return null;
+
+ var polygon = new Polygon();
+ foreach (var vertex in vertices)
+ polygon.Vertices.Add(vertex);
+ polygon.Vertices.Add(vertices[0]);
+ polygon.UpdateBounds();
+ return polygon;
+ }
+
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
List polygons
)
diff --git a/OpenNest.Core/Geometry/CollisionTriangle.cs b/OpenNest.Core/Geometry/CollisionTriangle.cs
new file mode 100644
index 00000000..c46b6579
--- /dev/null
+++ b/OpenNest.Core/Geometry/CollisionTriangle.cs
@@ -0,0 +1,67 @@
+namespace OpenNest.Geometry
+{
+ ///
+ /// One ear of as the collision clip loop
+ /// reads its triangle polygon: the open vertices and the bounding-box sides, without building
+ /// the polygon. Every value is bit for bit what the loop reads from the polygon.
+ ///
+ internal readonly struct CollisionTriangle
+ {
+ public CollisionTriangle(Vector prev, Vector curr, Vector next)
+ {
+ // The polygon is [prev, curr, next], closed with prev by Polygon.Close only when prev
+ // and next differ by its fuzzy equality. Its open vertices drop a last vertex exactly
+ // equal to the first: the closing vertex, or next when it was not closed.
+ V0 = prev;
+ V1 = curr;
+ V2 = next;
+ Count = prev != next || !(prev.X == next.X && prev.Y == next.Y) ? 3 : 2;
+
+ // Polygon.UpdateBounds over the same vertices; the closing vertex repeats prev.
+ var minX = prev.X;
+ var maxX = prev.X;
+ var minY = prev.Y;
+ var maxY = prev.Y;
+ Include(curr, ref minX, ref maxX, ref minY, ref maxY);
+ Include(next, ref minX, ref maxX, ref minY, ref maxY);
+
+ // Box sides as Box computes them from its location and size.
+ Left = minX;
+ Bottom = minY;
+ Right = minX + (maxX - minX);
+ Top = minY + (maxY - minY);
+ }
+
+ public Vector V0 { get; }
+ public Vector V1 { get; }
+ public Vector V2 { get; }
+
+ /// Open vertices: 3, or 2 when next is exactly prev.
+ public int Count { get; }
+
+ public double Left { get; }
+ public double Right { get; }
+ public double Bottom { get; }
+ public double Top { get; }
+
+ public Vector this[int index] => index switch
+ {
+ 0 => V0,
+ 1 => V1,
+ _ => V2,
+ };
+
+ private static void Include(Vector vertex, ref double minX, ref double maxX, ref double minY, ref double maxY)
+ {
+ if (vertex.X < minX)
+ minX = vertex.X;
+ else if (vertex.X > maxX)
+ maxX = vertex.X;
+
+ if (vertex.Y < minY)
+ minY = vertex.Y;
+ else if (vertex.Y > maxY)
+ maxY = vertex.Y;
+ }
+ }
+}
diff --git a/OpenNest.Core/Geometry/ConvexDecomposition.cs b/OpenNest.Core/Geometry/ConvexDecomposition.cs
index bfb752e9..b9d7bf79 100644
--- a/OpenNest.Core/Geometry/ConvexDecomposition.cs
+++ b/OpenNest.Core/Geometry/ConvexDecomposition.cs
@@ -15,7 +15,45 @@ namespace OpenNest.Geometry
///
public static List Triangulate(Polygon polygon)
{
- var triangles = new List();
+ var sink = new PolygonSink(new List());
+ Triangulate(polygon, ref sink);
+ return sink.Triangles;
+ }
+
+ ///
+ /// Receives each ear cuts, in order, as the three
+ /// vertices it would build its triangle from (previous, ear, next).
+ ///
+ internal interface IEarSink
+ {
+ void Add(Vector prev, Vector curr, Vector next);
+ }
+
+ private struct PolygonSink : IEarSink
+ {
+ public PolygonSink(List triangles) => Triangles = triangles;
+
+ public List Triangles { get; }
+
+ public void Add(Vector prev, Vector curr, Vector next)
+ {
+ var tri = new Polygon();
+ tri.Vertices.Add(prev);
+ tri.Vertices.Add(curr);
+ tri.Vertices.Add(next);
+ tri.Close();
+ Triangles.Add(tri);
+ }
+ }
+
+ ///
+ /// The ear-clipping of , handing each ear to
+ /// instead of building a triangle polygon for it: the same ears,
+ /// from the same vertices, in the same order.
+ ///
+ internal static void Triangulate(Polygon polygon, ref TSink sink)
+ where TSink : struct, IEarSink
+ {
var verts = new List(polygon.Vertices);
// Remove closing vertex if polygon is closed.
@@ -27,7 +65,7 @@ namespace OpenNest.Geometry
verts.RemoveAt(verts.Count - 1);
if (verts.Count < 3)
- return triangles;
+ return;
// Ensure counter-clockwise winding for ear detection.
if (SignedArea(verts) < 0)
@@ -85,12 +123,7 @@ namespace OpenNest.Geometry
var blocker = failedBlocker[currVertex];
if (!knownNotEar && IsEar(prev, curr, next, verts, nextOf, head, n, out blocker))
{
- var tri = new Polygon();
- tri.Vertices.Add(prev);
- tri.Vertices.Add(curr);
- tri.Vertices.Add(next);
- tri.Close();
- triangles.Add(tri);
+ sink.Add(prev, curr, next);
nextOf[prevVertex] = nextVertex;
prevOf[nextVertex] = prevVertex;
@@ -113,8 +146,6 @@ namespace OpenNest.Geometry
cursor = nextVertex;
}
}
-
- return triangles;
}
///
diff --git a/OpenNest.Core/PartOverlapChecker.cs b/OpenNest.Core/PartOverlapChecker.cs
index 0d721995..c814348f 100644
--- a/OpenNest.Core/PartOverlapChecker.cs
+++ b/OpenNest.Core/PartOverlapChecker.cs
@@ -49,7 +49,7 @@ namespace OpenNest
if (world1.Polygon == null || world2.Polygon == null)
return false;
- return Collision.HasOverlap(
+ return Collision.HasOverlapTriangulated(
world1.Polygon,
world1.Triangles,
world2.Polygon,
@@ -144,7 +144,7 @@ namespace OpenNest
///
private sealed class PreparedPart
{
- private List triangles;
+ private List triangles;
public PreparedPart(Polygon polygon)
{
@@ -154,9 +154,10 @@ namespace OpenNest
public Polygon Polygon { get; }
- public Func> Triangles { get; }
+ public Func> Triangles { get; }
- private List GetTriangles() => triangles ??= Collision.Triangulate(Polygon);
+ private List GetTriangles() =>
+ triangles ??= Collision.TriangulateForClipping(Polygon);
}
private sealed class PreparedProgram
diff --git a/OpenNest.Tests/Fill/PartOverlapCheckerTests.cs b/OpenNest.Tests/Fill/PartOverlapCheckerTests.cs
index ca066f5d..cc7b2d4c 100644
--- a/OpenNest.Tests/Fill/PartOverlapCheckerTests.cs
+++ b/OpenNest.Tests/Fill/PartOverlapCheckerTests.cs
@@ -168,11 +168,12 @@ public class PartOverlapCheckerTests
var actual = WorldPolygon(checker, p);
Assert.Equal(PolygonBits(expected), PolygonBits(actual));
// Cached triangles equal a fresh triangulation of the pre-change world polygon.
+ // The checker keeps them as clip triangles: each polygon's open vertices and box.
var expectedTriangles = Collision.Triangulate(expected);
var actualTriangles = WorldTriangles(checker, p);
Assert.Equal(expectedTriangles.Count, actualTriangles.Count);
for (var t = 0; t < expectedTriangles.Count; t++)
- Assert.Equal(PolygonBits(expectedTriangles[t]), PolygonBits(actualTriangles[t]));
+ Assert.Equal(ClipBits(expectedTriangles[t]), ClipBits(actualTriangles[t]));
}
}
}
@@ -367,8 +368,25 @@ public class PartOverlapCheckerTests
private static Polygon WorldPolygon(PartOverlapChecker checker, Part part) =>
(Polygon)PreparedPartMember(checker, part, "Polygon");
- private static List WorldTriangles(PartOverlapChecker checker, Part part) =>
- ((Func>)PreparedPartMember(checker, part, "Triangles"))();
+ private static List WorldTriangles(PartOverlapChecker checker, Part part) =>
+ ((Func>)PreparedPartMember(checker, part, "Triangles"))();
+
+ /// A triangle polygon as the clip loop reads it: open vertices, then box sides.
+ private static long[] ClipBits(Polygon triangle)
+ {
+ var open = triangle.Vertices.ToList();
+ if (open.Count > 1 && open[0].X == open[^1].X && open[0].Y == open[^1].Y)
+ open.RemoveAt(open.Count - 1);
+ var box = triangle.BoundingBox;
+ return open.SelectMany(v => new[] { v.X, v.Y })
+ .Concat(new[] { box.Left, box.Right, box.Bottom, box.Top })
+ .Select(BitConverter.DoubleToInt64Bits).ToArray();
+ }
+
+ private static long[] ClipBits(CollisionTriangle triangle) =>
+ Enumerable.Range(0, triangle.Count).SelectMany(i => new[] { triangle[i].X, triangle[i].Y })
+ .Concat(new[] { triangle.Left, triangle.Right, triangle.Bottom, triangle.Top })
+ .Select(BitConverter.DoubleToInt64Bits).ToArray();
private static object PreparedPartMember(PartOverlapChecker checker, Part part, string property)
{
diff --git a/OpenNest.Tests/Geometry/CollisionOverlapOnlyTests.cs b/OpenNest.Tests/Geometry/CollisionOverlapOnlyTests.cs
index 22fc4d9b..3abe2d4e 100644
--- a/OpenNest.Tests/Geometry/CollisionOverlapOnlyTests.cs
+++ b/OpenNest.Tests/Geometry/CollisionOverlapOnlyTests.cs
@@ -133,6 +133,103 @@ public class CollisionOverlapOnlyTests
Assert.Equal(new[] { "a", "c" }, resolved);
}
+ ///
+ /// The clip triangles PartOverlapChecker caches give the legacy verdicts, reused across many
+ /// pairs, and read every triangle exactly as the polygon triangulation does.
+ ///
+ [Fact]
+ public void SeededClippingTriangles_ReusedAcrossPairs_MatchLegacyVerdicts()
+ {
+ var random = new Random(17112026);
+ var decisions = 0;
+ var overlaps = 0;
+ var boxOverlapClear = 0;
+ for (var group = 0; group < 40; group++)
+ {
+ var polygons = new List();
+ var shapeA = Make(random, group % 6);
+ var shapeB = Make(random, (group / 6) % 6);
+ for (var sample = 0; sample < 25; sample++)
+ {
+ var (ax, ay, bx, by) = Offsets(random, shapeA, shapeB, sample);
+ var dx = random.NextDouble() * 4 - ax;
+ var dy = random.NextDouble() * 4 - ay;
+ polygons.Add(Move(shapeA, ax + dx, ay + dy));
+ polygons.Add(Move(shapeB, bx + dx, by + dy));
+ }
+ var triangles = polygons.Select(p => new Lazy>(() => Collision.TriangulateForClipping(p)))
+ .ToArray();
+ for (var i = 0; i < polygons.Count; i++)
+ for (var j = i + 1; j < polygons.Count; j++)
+ {
+ var expected = LegacyCollision.HasOverlap(polygons[i], polygons[j]);
+ var ti = triangles[i];
+ var tj = triangles[j];
+ var actual = Collision.HasOverlapTriangulated(polygons[i], () => ti.Value, polygons[j], () => tj.Value);
+ Assert.True(expected == actual, $"group={group} i={i} j={j} expected={expected}");
+ decisions++;
+ if (expected)
+ overlaps++;
+ else if (BoxesOverlap(polygons[i].BoundingBox, polygons[j].BoundingBox))
+ boxOverlapClear++;
+ }
+ for (var i = 0; i < polygons.Count; i++)
+ if (triangles[i].IsValueCreated)
+ Assert.Equal(ClipBits(Collision.Triangulate(polygons[i])), ClipBits(triangles[i].Value));
+ }
+ output.WriteLine($"clip-triangle decisions={decisions}; overlaps={overlaps}; bbox-overlap but clear={boxOverlapClear}");
+ Assert.Equal(40 * 50 * 49 / 2, decisions);
+ Assert.True(overlaps > 10000);
+ Assert.True(boxOverlapClear > 2000);
+ }
+
+ ///
+ /// Ears whose neighbors coincide exactly, or only within the fuzzy equality that closes a
+ /// triangle polygon, keep the polygon's open vertices and bounds.
+ ///
+ [Theory]
+ [InlineData(0.0)]
+ [InlineData(1e-12)]
+ [InlineData(1e-6)]
+ public void TriangulateForClipping_DegenerateEars_MatchTriangulateBitwise(double offset)
+ {
+ var polygons = new[]
+ {
+ // A spike back onto its own vertex, and collinear runs.
+ Ring((0, 0), (4, 0), (4, 2), (2, 2), (2 + offset, 3), (2, 2), (0, 2)),
+ Ring((0, 0), (1, 0), (2, 0), (3, offset), (3, 1), (2, 1), (1, 1 + offset), (0, 1)),
+ Ring((0, 0), (5, 0), (5, 5), (5 + offset, 5), (0, 5)),
+ Move(Make(new Random(3), 4), 123.456, -78.9),
+ };
+ foreach (var polygon in polygons)
+ {
+ var expected = ClipBits(Collision.Triangulate(polygon));
+ Assert.Equal(expected, ClipBits(Collision.TriangulateForClipping(polygon)));
+ }
+ }
+
+ /// Each triangle as the clip loop reads it: open vertices, then box sides.
+ private static long[] ClipBits(List triangles) => triangles
+ .SelectMany(t =>
+ {
+ var open = t.Vertices.ToList();
+ if (open.Count > 1 && open[0].X == open[^1].X && open[0].Y == open[^1].Y)
+ open.RemoveAt(open.Count - 1);
+ var box = t.BoundingBox;
+ return new[] { (long)open.Count }
+ .Concat(open.SelectMany(VectorBits))
+ .Concat(new[] { Bits(box.Left), Bits(box.Right), Bits(box.Bottom), Bits(box.Top) });
+ })
+ .Prepend(triangles.Count)
+ .ToArray();
+
+ private static long[] ClipBits(List triangles) => triangles
+ .SelectMany(t => new[] { (long)t.Count }
+ .Concat(Enumerable.Range(0, t.Count).SelectMany(i => VectorBits(t[i])))
+ .Concat(new[] { Bits(t.Left), Bits(t.Right), Bits(t.Bottom), Bits(t.Top) }))
+ .Prepend(triangles.Count)
+ .ToArray();
+
private static long[] TriangleBits(List triangles) => triangles
.SelectMany(t => new[] { t.BoundingBox.X, t.BoundingBox.Y, t.BoundingBox.Length, t.BoundingBox.Width }
.Concat(t.Vertices.SelectMany(v => new[] { v.X, v.Y })))
diff --git a/docs/performance/fill-verification.md b/docs/performance/fill-verification.md
index e2edb2d0..e1cc381f 100644
--- a/docs/performance/fill-verification.md
+++ b/docs/performance/fill-verification.md
@@ -66,7 +66,7 @@ dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Debug \
--filter 'FullyQualifiedName~DefaultFillComparerWorkTests|FullyQualifiedName~FillHelpersTests|FullyQualifiedName~FillExtentsTests|FullyQualifiedName~StrategyOverlapTests|FullyQualifiedName~FillLinearGeometryReuseTests|FullyQualifiedName~CollisionOverlapOnlyTests|FullyQualifiedName~PartOverlapCheckerTests'
```
-`PerfCounters.FillScoreComputations`, `PartBoundaryPreparations`, `PartBoundsUpdates`, `OffsetPerimeterEntities`, `FeatureBitmaskCells`, `CrossingPointScans`, `OverlapPolygonPreparations`, and `PolygonTriangulations` increments compile away in Release: zero Release counters prove nothing. `OverlapPolygonPreparations` counts overlap-preparation starts (material extraction), not completed polygons: `Part.Intersects` counts both parts on every call, `PartOverlapChecker` counts once per distinct `Program`. `PolygonTriangulations` counts `Collision` triangulations; the checker triangulates a part at most once per check, and only after a bounding-box hit. Serialize counter assertions in `FillCacheCollection` and reset in `finally`. Keep `OpenNest.Tests/Fill/LegacyFillExtents.cs`, `OpenNest.Tests/Fill/LegacyFillLinear.cs`, `OpenNest.Tests/Geometry/LegacyCollision.cs`, and `OpenNest.Tests/Fill/LegacyPartOverlap.cs` frozen for differential tests (never route them through production helpers), not production or before timings; measure the actual baseline production code.
+`PerfCounters.FillScoreComputations`, `PartBoundaryPreparations`, `PartBoundsUpdates`, `OffsetPerimeterEntities`, `FeatureBitmaskCells`, `CrossingPointScans`, `OverlapPolygonPreparations`, and `PolygonTriangulations` increments compile away in Release: zero Release counters prove nothing. `OverlapPolygonPreparations` counts overlap-preparation starts (material extraction), not completed polygons: `Part.Intersects` counts both parts on every call, `PartOverlapChecker` counts once per distinct `Program`. `PolygonTriangulations` counts `Collision` triangulations; the checker triangulates a part at most once per check, and only after a bounding-box hit. `HasOverlap`, `Check` and the checker clip `CollisionTriangle`s (each ear's open vertices and box sides, without a `Polygon` per triangle) in reused buffers with the polygon path's arithmetic; `CollisionOverlapOnlyTests` holds them bitwise to `Collision.Triangulate` and their verdicts to `LegacyCollision`. On a 30-copy fill of an 80-vertex arc-cornered bracket this cut a 15 s Lattice fill to about 4 s with identical poses: per-triangle `Polygon` entities (an interlocked ID each) and per-clip lists dominated. Serialize counter assertions in `FillCacheCollection` and reset in `finally`. Keep `OpenNest.Tests/Fill/LegacyFillExtents.cs`, `OpenNest.Tests/Fill/LegacyFillLinear.cs`, `OpenNest.Tests/Geometry/LegacyCollision.cs`, and `OpenNest.Tests/Fill/LegacyPartOverlap.cs` frozen for differential tests (never route them through production helpers), not production or before timings; measure the actual baseline production code.
Predictor regression checks: `dotnet test OpenNest.Tests/OpenNest.Tests.csproj -c Release --filter "FullyQualifiedName~AngleCandidateBuilderTests|FullyQualifiedName~AnglePredictorTests|FullyQualifiedName~FeatureExtractorTests"` (repeat in Debug for bitmap counters). `IrregularAngles_ReportsWarmNoModelPath` measures the public builder with a missing model and skips when a model is installed; never remove real model files to benchmark. `FeatureExtraction_ReportsFullAndScalarOnly` measures extraction separately.