mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-11-25 15:47:40 -05:00
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 <noreply@anthropic.com>
786 lines
31 KiB
C#
786 lines
31 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Runtime.InteropServices;
|
|
using OpenNest.Math;
|
|
|
|
namespace OpenNest.Geometry
|
|
{
|
|
/// <summary>
|
|
/// 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.
|
|
/// <para>
|
|
/// Former GPU-port contract, kept for reference. Per-polygon preparation, done once
|
|
/// per drawing and rotation,
|
|
/// then cached and uploaded: the spacing offset (<see cref="ClipperBridge"/>),
|
|
/// triangulation (<see cref="ConvexDecomposition.Triangulate"/>) 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 (<c>ClipConvex</c>), and
|
|
/// subtraction of hole triangles from the clipped regions (<c>SubtractTriangles</c>).
|
|
/// Inputs are closed, lines-only polygons; winding is normalized by triangulation.
|
|
/// </para>
|
|
/// </summary>
|
|
public static class Collision
|
|
{
|
|
public static CollisionResult Check(
|
|
Polygon a,
|
|
Polygon b,
|
|
List<Polygon> holesA = null,
|
|
List<Polygon> 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<Polygon> holesA = null,
|
|
List<Polygon> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/> with the
|
|
/// per-polygon triangulation supplied by the caller. Triangulations are resolved lazily,
|
|
/// only after the bounding boxes overlap, and must come from <see cref="Triangulate"/> on
|
|
/// the same polygon; the verdict is then identical. The triangles are only read.
|
|
/// </summary>
|
|
internal static bool HasOverlap(
|
|
Polygon a,
|
|
Func<List<Polygon>> trianglesA,
|
|
Polygon b,
|
|
Func<List<Polygon>> trianglesB,
|
|
List<Polygon> holesA = null,
|
|
List<Polygon> holesB = null
|
|
)
|
|
{
|
|
if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox))
|
|
return false;
|
|
|
|
return OverlapRegions(trianglesA(), trianglesB(), holesA, holesB, verdictOnly: true).Count > 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/> with each
|
|
/// polygon's <see cref="TriangulateForClipping"/> supplied by the caller and resolved
|
|
/// lazily, only after the bounding boxes overlap; the verdict is then identical.
|
|
/// </summary>
|
|
internal static bool HasOverlapTriangulated(
|
|
Polygon a,
|
|
Func<List<CollisionTriangle>> trianglesA,
|
|
Polygon b,
|
|
Func<List<CollisionTriangle>> trianglesB
|
|
)
|
|
{
|
|
if (!BoundingBoxesOverlap(a.BoundingBox, b.BoundingBox))
|
|
return false;
|
|
|
|
return OverlapRegions(trianglesA(), trianglesB(), null, null, verdictOnly: true).Count > 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The triangulation <see cref="Check"/> and <see cref="HasOverlap(Polygon, Polygon, List{Polygon}, List{Polygon})"/>
|
|
/// use for <paramref name="polygon"/>: ear-clipped triangles with bounds updated. Callers
|
|
/// that reuse it must not mutate the polygon or the triangles.
|
|
/// </summary>
|
|
internal static List<Polygon> Triangulate(Polygon polygon) => TriangulateWithBounds(polygon);
|
|
|
|
/// <summary>
|
|
/// <see cref="Triangulate"/> 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.
|
|
/// </summary>
|
|
internal static List<CollisionTriangle> TriangulateForClipping(Polygon polygon) =>
|
|
TriangulateForClipping(polygon, new List<CollisionTriangle>(polygon.Vertices.Count));
|
|
|
|
/// <summary>
|
|
/// <see cref="TriangulateForClipping(Polygon)"/> into a list the caller reuses: it is
|
|
/// emptied first and returned holding the same triangles.
|
|
/// </summary>
|
|
internal static List<CollisionTriangle> TriangulateForClipping(
|
|
Polygon polygon,
|
|
List<CollisionTriangle> triangles
|
|
)
|
|
{
|
|
PerfCounters.CountPolygonTriangulation();
|
|
triangles.Clear();
|
|
var sink = new TriangleSink(triangles);
|
|
ConvexDecomposition.Triangulate(polygon, ref sink);
|
|
return sink.Triangles;
|
|
}
|
|
|
|
private readonly struct TriangleSink : ConvexDecomposition.IEarSink
|
|
{
|
|
public TriangleSink(List<CollisionTriangle> triangles) => Triangles = triangles;
|
|
|
|
public List<CollisionTriangle> Triangles { get; }
|
|
|
|
public void Add(Vector prev, Vector curr, Vector next) =>
|
|
Triangles.Add(new CollisionTriangle(prev, curr, next));
|
|
}
|
|
|
|
public static List<CollisionResult> CheckAll(
|
|
List<Polygon> polygons,
|
|
List<List<Polygon>> holes = null
|
|
)
|
|
{
|
|
var results = new List<CollisionResult>();
|
|
|
|
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<Polygon> polygons, List<List<Polygon>> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Positive-area overlap regions left after hole subtraction: the verdict shared by
|
|
/// <see cref="Check"/> and <see cref="HasOverlap"/>. Callers apply the polygon-level
|
|
/// bounding-box pre-filter first.
|
|
/// </summary>
|
|
private static List<Polygon> OverlapRegions(
|
|
Polygon a,
|
|
Polygon b,
|
|
List<Polygon> holesA,
|
|
List<Polygon> holesB,
|
|
bool verdictOnly = false
|
|
) => OverlapRegions(TriangulateForClipping(a), TriangulateForClipping(b), holesA, holesB, verdictOnly);
|
|
|
|
/// <summary>
|
|
/// <see cref="OverlapRegions(List{Polygon}, List{Polygon}, List{Polygon}, List{Polygon}, bool)"/>
|
|
/// over <see cref="TriangulateForClipping"/> triangles: the same pairs clipped in the same
|
|
/// order, so the same regions.
|
|
/// </summary>
|
|
private static List<Polygon> OverlapRegions(
|
|
List<CollisionTriangle> trisA,
|
|
List<CollisionTriangle> trisB,
|
|
List<Polygon> holesA,
|
|
List<Polygon> holesB,
|
|
bool verdictOnly = false
|
|
)
|
|
{
|
|
var regions = new List<Polygon>();
|
|
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<Polygon> OverlapRegions(
|
|
List<Polygon> trisA,
|
|
List<Polygon> trisB,
|
|
List<Polygon> holesA,
|
|
List<Polygon> holesB,
|
|
bool verdictOnly = false
|
|
)
|
|
{
|
|
var regions = new List<Polygon>();
|
|
|
|
// 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static void ClipTrianglePairs(
|
|
List<Polygon> trisA,
|
|
List<Polygon> trisB,
|
|
List<Polygon> 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<Vector>[candidatesB.Count];
|
|
for (var j = 0; j < candidatesB.Count; j++)
|
|
openB[j] = OpenVertices(candidatesB[j]);
|
|
|
|
foreach (var triA in candidatesA)
|
|
{
|
|
List<Vector> 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;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="ClipTrianglePairs(List{Polygon}, List{Polygon}, List{Polygon}, bool)"/> over
|
|
/// <see cref="CollisionTriangle"/>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.
|
|
/// </summary>
|
|
private static void ClipTrianglePairs(
|
|
List<CollisionTriangle> trisA,
|
|
List<CollisionTriangle> trisB,
|
|
List<Polygon> 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<Vector> first = stackalloc Vector[MaxClippedVertices];
|
|
Span<Vector> second = stackalloc Vector[MaxClippedVertices];
|
|
Span<double> 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;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private const int MaxClippedVertices = 3 * 2 * 2 * 2;
|
|
|
|
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
|
|
List<CollisionTriangle> 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);
|
|
}
|
|
|
|
/// <summary>Indices of the triangles the polygon form of this test keeps, in order.</summary>
|
|
private static List<int> TrianglesTouching(
|
|
List<CollisionTriangle> triangles,
|
|
(double Left, double Right, double Bottom, double Top) union
|
|
)
|
|
{
|
|
var result = new List<int>(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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="ClipConvex(List{Vector}, List{Vector})"/> of two triangles' open vertices,
|
|
/// alternating between two caller buffers of <see cref="MaxClippedVertices"/>.
|
|
/// </summary>
|
|
private static Polygon ClipConvex(
|
|
in CollisionTriangle subject,
|
|
in CollisionTriangle clip,
|
|
Span<Vector> first,
|
|
Span<Vector> second,
|
|
Span<double> 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));
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="ClipHalfSpace"/> keeping the inside, written to <paramref name="kept"/>;
|
|
/// returns how many it kept. Each vertex's signed distance is computed once into
|
|
/// <paramref name="distances"/>, the same value ClipHalfSpace computes for it twice.
|
|
/// </summary>
|
|
private static int ClipHalfSpaceInside(
|
|
ReadOnlySpan<Vector> vertices,
|
|
Vector edgeStart,
|
|
Vector edgeEnd,
|
|
Span<Vector> kept,
|
|
Span<double> 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<Vector> vertices, ref int count, Vector point)
|
|
{
|
|
if (count == 0 || !SamePoint(vertices[count - 1], point))
|
|
vertices[count++] = point;
|
|
}
|
|
|
|
private static Polygon PositiveAreaPolygon(ReadOnlySpan<Vector> vertices)
|
|
{
|
|
if (vertices.Length < 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.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.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;
|
|
}
|
|
|
|
private static (double Left, double Right, double Bottom, double Top) UnionBounds(
|
|
List<Polygon> 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The polygons whose boxes pass <see cref="BoundingBoxesOverlap"/> against
|
|
/// <paramref name="union"/>, in order. Same arithmetic as that test, with the union's
|
|
/// sides in place of the other box's.
|
|
/// </summary>
|
|
private static List<Polygon> TrianglesTouching(
|
|
List<Polygon> polygons,
|
|
(double Left, double Right, double Bottom, double Top) union
|
|
)
|
|
{
|
|
var result = new List<Polygon>(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<Vector> FindCrossingPoints(Polygon a, Polygon b)
|
|
{
|
|
PerfCounters.CountCrossingPointScan();
|
|
if (!Intersect.Intersects(a, b, out var rawPts))
|
|
return new List<Vector>();
|
|
|
|
// Filter boundary contacts (vertex touches)
|
|
var vertsA = CollectVertices(a);
|
|
var vertsB = CollectVertices(b);
|
|
var filtered = new List<Vector>();
|
|
|
|
foreach (var pt in rawPts)
|
|
{
|
|
if (IsNearAnyVertex(pt, vertsA) || IsNearAnyVertex(pt, vertsB))
|
|
continue;
|
|
filtered.Add(pt);
|
|
}
|
|
|
|
return filtered;
|
|
}
|
|
|
|
private static List<Vector> CollectVertices(Polygon polygon)
|
|
{
|
|
var verts = new List<Vector>(polygon.Vertices.Count);
|
|
foreach (var v in polygon.Vertices)
|
|
verts.Add(v);
|
|
return verts;
|
|
}
|
|
|
|
private static bool IsNearAnyVertex(Vector pt, List<Vector> vertices)
|
|
{
|
|
foreach (var v in vertices)
|
|
{
|
|
if (pt.X.IsEqualTo(v.X) && pt.Y.IsEqualTo(v.Y))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Triangulates a polygon and ensures each triangle has its bounding box updated.
|
|
/// </summary>
|
|
private static List<Polygon> TriangulateWithBounds(Polygon polygon)
|
|
{
|
|
PerfCounters.CountPolygonTriangulation();
|
|
var tris = ConvexDecomposition.Triangulate(polygon);
|
|
foreach (var tri in tris)
|
|
tri.UpdateBounds();
|
|
return tris;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sutherland-Hodgman polygon clipping. Clips subject against each edge
|
|
/// of clip. Both must be convex. Returns null if no overlap.
|
|
/// </summary>
|
|
private static Polygon ClipConvex(List<Vector> subjectVerts, List<Vector> 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cross product of vectors (edgeStart->edgeEnd) and (edgeStart->point).
|
|
/// Positive = point is left of edge (inside for CCW polygon).
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Subtracts holes from overlap regions.
|
|
/// </summary>
|
|
private static List<Polygon> SubtractHoles(
|
|
List<Polygon> regions,
|
|
List<Polygon> holesA,
|
|
List<Polygon> holesB
|
|
)
|
|
{
|
|
var allHoles = new List<Polygon>();
|
|
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<Polygon>();
|
|
|
|
foreach (var region in regions)
|
|
{
|
|
var pieces = SubtractTriangles(region, holeTris);
|
|
surviving.AddRange(pieces);
|
|
}
|
|
|
|
regions = surviving;
|
|
|
|
if (regions.Count == 0)
|
|
break;
|
|
}
|
|
|
|
return regions;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static List<Polygon> SubtractTriangles(Polygon region, List<Polygon> holeTris)
|
|
{
|
|
var current = new List<Polygon> { region };
|
|
|
|
foreach (var holeTri in holeTris)
|
|
{
|
|
var next = new List<Polygon>();
|
|
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static List<Vector> ClipHalfSpace(
|
|
List<Vector> vertices,
|
|
Vector edgeStart,
|
|
Vector edgeEnd,
|
|
bool inside
|
|
)
|
|
{
|
|
var kept = new List<Vector>();
|
|
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<Vector> vertices, Vector point)
|
|
{
|
|
if (vertices.Count == 0 || !SamePoint(vertices[vertices.Count - 1], point))
|
|
vertices.Add(point);
|
|
}
|
|
|
|
private static List<Vector> OpenVertices(Polygon polygon)
|
|
{
|
|
var vertices = new List<Vector>(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<Vector> vertices) =>
|
|
PositiveAreaPolygon(CollectionsMarshal.AsSpan(vertices));
|
|
}
|
|
}
|