using System; using System.Collections.Generic; using System.Runtime.InteropServices; using OpenNest.Math; namespace OpenNest.Geometry { /// /// Polygon overlap test with hole subtraction, used by engine and validation per-pair /// checks. It was written as the reference for a GPU kernel; that port is on hold in /// favor of Clipper2, starting with the material-overlap diagnostic. Engine callers /// stay on this kernel until a Clipper2 near-contact differential and the layout gate /// pass. /// /// Former GPU-port contract, kept for reference. Per-polygon preparation, done once /// per drawing and rotation, /// then cached and uploaded: the spacing offset (), /// triangulation () of the outline and /// each hole, and the bounding box of every polygon and triangle. Per-pair work, /// kernel-shaped (fixed-size, loop-only, no recursion): the bounding-box rejects, /// Sutherland-Hodgman clipping of convex triangle pairs (ClipConvex), and /// subtraction of hole triangles from the clipped regions (SubtractTriangles). /// Inputs are closed, lines-only polygons; winding is normalized by triangulation. /// /// public static class Collision { public static CollisionResult Check( Polygon a, Polygon b, List holesA = null, List holesB = null ) { // Step 1: Bounding box pre-filter if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox)) return CollisionResult.None; // Step 2: Quick intersection test for crossing points var intersectionPoints = FindCrossingPoints(a, b); // Steps 3-5: Convex decomposition, triangle-pair clipping, hole subtraction var regions = OverlapRegions(a, b, holesA, holesB); // Step 6: Build result return new CollisionResult(regions.Count > 0, regions, intersectionPoints); } public static bool HasOverlap( Polygon a, Polygon b, List holesA = null, List holesB = null ) { if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox)) return false; // Clipping decides the verdict, including containment (one polygon entirely // inside another has zero edge crossings). Crossing points never affect it, // so this overlap-only path skips them. return OverlapRegions(a, b, holesA, holesB, verdictOnly: true).Count > 0; } /// /// with the /// per-polygon triangulation supplied by the caller. Triangulations are resolved lazily, /// only after the bounding boxes overlap, and must come from on /// the same polygon; the verdict is then identical. The triangles are only read. /// internal static bool HasOverlap( Polygon a, Func> trianglesA, Polygon b, Func> trianglesB, List holesA = null, List holesB = null ) { if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox)) return false; 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 /// that reuse it must not mutate the polygon or the triangles. /// 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 ) { var results = new List(); for (var i = 0; i < polygons.Count; i++) { for (var j = i + 1; j < polygons.Count; j++) { var holesA = holes != null && i < holes.Count ? holes[i] : null; var holesB = holes != null && j < holes.Count ? holes[j] : null; var result = Check(polygons[i], polygons[j], holesA, holesB); if (result.Overlaps) results.Add(result); } } return results; } public static bool HasAnyOverlap(List polygons, List> holes = null) { for (var i = 0; i < polygons.Count; i++) { for (var j = i + 1; j < polygons.Count; j++) { var holesA = holes != null && i < holes.Count ? holes[i] : null; var holesB = holes != null && j < holes.Count ? holes[j] : null; if (HasOverlap(polygons[i], polygons[j], holesA, holesB)) return true; } } return false; } /// /// Positive-area overlap regions left after hole subtraction: the verdict shared by /// and . Callers apply the polygon-level /// bounding-box pre-filter first. /// private static List OverlapRegions( Polygon a, Polygon b, List holesA, List holesB, bool verdictOnly = false ) => 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, List trisB, List holesA, List holesB, bool verdictOnly = false ) { var regions = new List(); // Without holes nothing is subtracted, so for a caller that needs only the verdict // the first clipped region decides it. Check returns the regions, so it gets all. 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; } /// /// Clips every triangle pair whose bounding boxes overlap, in (A, B) order, adding the /// positive-area regions. A triangle whose box misses the union of the other list's /// boxes overlaps none of them (min/max are exact and subtraction is monotone, so a /// pair's overlap never exceeds the overlap with the union), so it is dropped before /// the pair loop. The pairs clipped, their order and the regions are those of the /// plain double loop. /// 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; // The clip loop only reads its inputs, so each triangle's open vertices serve // every pair it is in. var openB = new List[candidatesB.Count]; for (var j = 0; j < candidatesB.Count; j++) openB[j] = OpenVertices(candidatesB[j]); foreach (var triA in candidatesA) { List openA = null; for (var j = 0; j < candidatesB.Count; j++) { var triB = candidatesB[j]; if (!BoundingBoxesOverlap(triA.BoundingBox, triB.BoundingBox)) continue; openA ??= OpenVertices(triA); var clipped = ClipConvex(openA, openB[j]); if (clipped == null) continue; regions.Add(clipped); if (stopAtFirst) return; } } } /// /// 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 ) { var left = double.PositiveInfinity; var right = double.NegativeInfinity; var bottom = double.PositiveInfinity; var top = double.NegativeInfinity; foreach (var polygon in polygons) { var box = polygon.BoundingBox; left = System.Math.Min(left, box.Left); right = System.Math.Max(right, box.Right); bottom = System.Math.Min(bottom, box.Bottom); top = System.Math.Max(top, box.Top); } return (left, right, bottom, top); } /// /// The polygons whose boxes pass against /// , in order. Same arithmetic as that test, with the union's /// sides in place of the other box's. /// private static List TrianglesTouching( List polygons, (double Left, double Right, double Bottom, double Top) union ) { var result = new List(polygons.Count); foreach (var polygon in polygons) { var box = polygon.BoundingBox; 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(polygon); } return result; } private static bool BoundingBoxesOverlap(Box a, Box 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; } private static List FindCrossingPoints(Polygon a, Polygon b) { PerfCounters.CountCrossingPointScan(); if (!Intersect.Intersects(a, b, out var rawPts)) return new List(); // Filter boundary contacts (vertex touches) var vertsA = CollectVertices(a); var vertsB = CollectVertices(b); var filtered = new List(); foreach (var pt in rawPts) { if (IsNearAnyVertex(pt, vertsA) || IsNearAnyVertex(pt, vertsB)) continue; filtered.Add(pt); } return filtered; } private static List CollectVertices(Polygon polygon) { var verts = new List(polygon.Vertices.Count); foreach (var v in polygon.Vertices) verts.Add(v); return verts; } private static bool IsNearAnyVertex(Vector pt, List vertices) { foreach (var v in vertices) { if (pt.X.IsEqualTo(v.X) && pt.Y.IsEqualTo(v.Y)) return true; } return false; } /// /// Triangulates a polygon and ensures each triangle has its bounding box updated. /// private static List TriangulateWithBounds(Polygon polygon) { PerfCounters.CountPolygonTriangulation(); var tris = ConvexDecomposition.Triangulate(polygon); foreach (var tri in tris) tri.UpdateBounds(); return tris; } /// /// Sutherland-Hodgman polygon clipping. Clips subject against each edge /// of clip. Both must be convex. Returns null if no overlap. /// private static Polygon ClipConvex(List subjectVerts, List clipVerts) { var output = subjectVerts; for (var i = 0; i < clipVerts.Count && output.Count >= 3; i++) { output = ClipHalfSpace(output, clipVerts[i], clipVerts[(i + 1) % clipVerts.Count], true); } return PositiveAreaPolygon(output); } /// /// Cross product of vectors (edgeStart->edgeEnd) and (edgeStart->point). /// Positive = point is left of edge (inside for CCW polygon). /// private static double Cross(Vector edgeStart, Vector edgeEnd, Vector point) { return (edgeEnd.X - edgeStart.X) * (point.Y - edgeStart.Y) - (edgeEnd.Y - edgeStart.Y) * (point.X - edgeStart.X); } /// /// Subtracts holes from overlap regions. /// private static List SubtractHoles( List regions, List holesA, List holesB ) { var allHoles = new List(); if (holesA != null) allHoles.AddRange(holesA); if (holesB != null) allHoles.AddRange(holesB); if (allHoles.Count == 0) return regions; foreach (var hole in allHoles) { var holeTris = TriangulateWithBounds(hole); var surviving = new List(); foreach (var region in regions) { var pieces = SubtractTriangles(region, holeTris); surviving.AddRange(pieces); } regions = surviving; if (regions.Count == 0) break; } return regions; } /// /// Subtracts hole triangles from a convex region. At each edge, emit the outside /// portion and carry only the inside remainder to the next edge. The emitted /// pieces are disjoint and convex, so no repeated triangulation is needed. /// private static List SubtractTriangles(Polygon region, List holeTris) { var current = new List { region }; foreach (var holeTri in holeTris) { var next = new List(); foreach (var piece in current) { // Subtraction must also remove thin fragments created by clipping. // The pair-level length tolerance would skip some of these even // when their area is large enough to count as an overlap. var a = piece.BoundingBox; var b = holeTri.BoundingBox; if (a.Right <= b.Left || b.Right <= a.Left || a.Top <= b.Bottom || b.Top <= a.Bottom) { next.Add(piece); continue; } var remainder = OpenVertices(piece); var holeVerts = OpenVertices(holeTri); for (var i = 0; i < holeVerts.Count && remainder.Count >= 3; i++) { var start = holeVerts[i]; var end = holeVerts[(i + 1) % holeVerts.Count]; var outside = PositiveAreaPolygon(ClipHalfSpace(remainder, start, end, false)); if (outside != null) next.Add(outside); remainder = ClipHalfSpace(remainder, start, end, true); } } current = next; if (current.Count == 0) break; } return current; } /// /// Clips an open vertex list against one half-space. Classification and /// interpolation use the same signed cross products: intersections always /// lie on the input segment. An epsilon-shifted inside test combined with /// intersections on the unshifted line can extrapolate and create material. /// Apply the area tolerance only to the resulting polygons, not to edge signs. /// private static List ClipHalfSpace( List vertices, Vector edgeStart, Vector edgeEnd, bool inside ) { var kept = new List(); for (var i = 0; i < vertices.Count; i++) { var current = vertices[i]; var next = vertices[(i + 1) % vertices.Count]; var currentDistance = Cross(edgeStart, edgeEnd, current); var nextDistance = Cross(edgeStart, edgeEnd, next); if (inside ? currentDistance >= 0 : currentDistance <= 0) AddDistinct(kept, current); // Only strict opposite signs cross the line. Boundary endpoints // are already kept, and near-parallel crossings need no cutoff. if ((currentDistance < 0 && nextDistance > 0) || (currentDistance > 0 && nextDistance < 0)) { var t = currentDistance / (currentDistance - nextDistance); AddDistinct(kept, new Vector( current.X + t * (next.X - current.X), current.Y + t * (next.Y - current.Y))); } } if (kept.Count > 1 && SamePoint(kept[0], kept[kept.Count - 1])) kept.RemoveAt(kept.Count - 1); return kept; } private static bool SamePoint(Vector a, Vector b) => a.X == b.X && a.Y == b.Y; private static void AddDistinct(List vertices, Vector point) { if (vertices.Count == 0 || !SamePoint(vertices[vertices.Count - 1], point)) vertices.Add(point); } private static List OpenVertices(Polygon polygon) { var vertices = new List(polygon.Vertices); if (vertices.Count > 1 && SamePoint(vertices[0], vertices[vertices.Count - 1])) vertices.RemoveAt(vertices.Count - 1); return vertices; } private static Polygon PositiveAreaPolygon(List vertices) { if (vertices.Count < 3) return null; // Measure relative to a vertex to avoid cancellation of world-coordinate // products when a small clipped fragment is far from the origin. var twiceArea = 0.0; for (var i = 1; i + 1 < vertices.Count; i++) twiceArea += Cross(vertices[0], vertices[i], vertices[i + 1]); if (System.Math.Abs(twiceArea) <= 2 * Tolerance.Epsilon) return null; var polygon = new Polygon(); polygon.Vertices.AddRange(vertices); // Polygon.Close uses fuzzy Vector equality; clipping needs an exact // closing vertex even when the last edge is shorter than Epsilon. polygon.Vertices.Add(vertices[0]); polygon.UpdateBounds(); return polygon; } } }