public static List<Vertices> ConvexPartition(Vertices vertices)
{
Debug.Assert(vertices.Count > 3);
Debug.Assert(vertices.isCounterClockWise());
int[] polygon = new int[vertices.Count];
for (int v = 0; v < vertices.Count; v++)
polygon[v] = v;
int nv = vertices.Count;
// Remove nv-2 Vertices, creating 1 triangle every time
int count = 2 * nv; /* error detection */
List<Vertices> result = new List<Vertices>();
for (int v = nv - 1; nv > 2; )
{
// If we loop, it is probably a non-simple polygon
if (0 >= (count--))
{
// Triangulate: ERROR - probable bad polygon!
return new List<Vertices>();
}
// Three consecutive vertices in current polygon, <u,v,w>
int u = v;
if (nv <= u)
u = 0; // Previous
v = u + 1;
if (nv <= v)
v = 0; // New v
int w = v + 1;
if (nv <= w)
w = 0; // Next
_tmpA = vertices[polygon[u]];
_tmpB = vertices[polygon[v]];
_tmpC = vertices[polygon[w]];
if (Snip(vertices, u, v, w, nv, polygon))
{
int s, t;
// Output Triangle
Vertices triangle = new Vertices(3);
triangle.Add(_tmpA);
triangle.Add(_tmpB);
triangle.Add(_tmpC);
result.Add(triangle);
// Remove v from remaining polygon
for (s = v, t = v + 1; t < nv; s++, t++)
{
polygon[s] = polygon[t];
}
nv--;
// Reset error detection counter
count = 2 * nv;
}
}
return result;
}