/* * Triangulates a polygon using simple O(N^2) ear-clipping algorithm * Returns a Triangle array unless the polygon can't be triangulated, * in which case null is returned. This should only happen if the * polygon self-intersects, though it will not _always_ return null * for a bad polygon - it is the caller's responsibility to check for * self-intersection, and if it doesn't, it should at least check * that the return value is non-null before using. You're warned! */ Triangle[] triangulatePolygon(float[] xv, float[] yv, int vNum){ if (vNum < 3) return null; Triangle[] buffer = new Triangle[vNum]; int bufferSize = 0; float[] xrem = new float[vNum]; float[] yrem = new float[vNum]; for (int i=0; i 3){ //Find an ear int earIndex = -1; for (int i=0; i= xv.length || i < 0 || xv.length < 3){ return false; } int upper = i+1; int lower = i-1; if (i == 0){ dx0 = xv[0] - xv[xv.length-1]; dy0 = yv[0] - yv[yv.length-1]; dx1 = xv[1] - xv[0]; dy1 = yv[1] - yv[0]; lower = xv.length-1; } else if (i == xv.length-1){ dx0 = xv[i] - xv[i-1]; dy0 = yv[i] - yv[i-1]; dx1 = xv[0] - xv[i]; dy1 = yv[0] - yv[i]; upper = 0; } else{ dx0 = xv[i] - xv[i-1]; dy0 = yv[i] - yv[i-1]; dx1 = xv[i+1] - xv[i]; dy1 = yv[i+1] - yv[i]; } float cross = dx0*dy1-dx1*dy0; if (cross > 0) return false; Triangle myTri = new Triangle(xv[i],yv[i],xv[upper],yv[upper],xv[lower],yv[lower]); for (int j=0; j