Sorts vertices in a convex polygon - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Sorts vertices in a convex polygon

Demo Code

/***/*ww  w . j av  a 2s  .c o m*/
 * Copyright (C) 2010 Johan Henriksson
 * This code is under the Endrov / BSD license. See www.endrov.net
 * for the full text and how to cite.
 */
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.vecmath.Vector3d;

public class Main{
    /**
     * Sorts vertices in a convex polygon
     */
    public static Vector3d[] sortConvexPolygon(Vector3d[] points) {
        Vector3d center = new Vector3d();
        for (Vector3d v : points)
            center.add(v);
        center.scale(1.0 / points.length);

        //Project points
        List<UnclassifiedPoint> ups = new ArrayList<UnclassifiedPoint>();
        for (int ap = 0; ap < points.length; ap++)
            if (points[ap] != null) {
                UnclassifiedPoint up = new UnclassifiedPoint();
                up.index = ap;
                Vector3d v = new Vector3d(points[ap]);
                v.sub(center);
                up.angle = Math.atan2(v.y, v.x);
                //This *will* explode in some instances. a rotation would solve it.
                ups.add(up);
            }
        Collections.sort(ups);

        for (int ap = 0; ap < points.length; ap++)
            points[ap] = points[ups.get(ap).index];
        return points;
    }
}

Related Tutorials