Java examples for 2D Graphics:Polygon
Computes the triangulation of a polygon with ear-clipping algorithm.
/*//from w w w .j av a 2 s. c o m * Flingbox - An OpenSource physics sandbox for Google's Android * Copyright (C) 2009 Jon Ander Pe?alba & Endika Guti?rrez * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; public class Main{ /** * Computes the triangulation of a polygon with ear-clipping * algorithm. * @param Vector2Ds Array of polygon's points * @return Will return n-2 group of 3 points, for n sides polygon * or null if not enough points */ public static short[] triangulatePolygon(final Vector2D[] Vector2Ds) { final int Vector2DsCount = Vector2Ds.length; if (Vector2DsCount < 3) return null; // n-2 group of 3 Vector2Ds, for n sides polygon short[] triangles = new short[3 * (Vector2DsCount - 2)]; boolean[] included = new boolean[Vector2DsCount]; int topVector2DIndex; float topVector2D; for (int trianglesCount = 0; trianglesCount < (Vector2DsCount - 3); ++trianglesCount) { topVector2DIndex = 0; topVector2D = Float.NEGATIVE_INFINITY; // Find top Vector2D to find triangle for (int i = 0; i < Vector2DsCount; i++) { // Find top Vector2D if (!included[i] && (Vector2Ds[i].i > topVector2D)) { topVector2D = Vector2Ds[i].i; topVector2DIndex = i; } } // Exclude Vector2D for next iteration included[topVector2DIndex] = true; // Save triangle int prevVector2D = topVector2DIndex; // Find previous Vector2D do { if (--prevVector2D < 0) prevVector2D = Vector2DsCount - 1; } while (included[prevVector2D]); int nextVector2D = topVector2DIndex; // Find next Vector2D do { if (++nextVector2D >= Vector2DsCount) nextVector2D = 0; } while (included[nextVector2D]); // Store triangle triangles[trianglesCount * 3] = (short) prevVector2D; // Store into array triangles[trianglesCount * 3 + 1] = (short) topVector2DIndex; triangles[trianglesCount * 3 + 2] = (short) nextVector2D; } return triangles; } }