package net.beadsproject.touch.examples;
import java.util.ArrayList;

import math.geom2d.Point2D;
import megamu.mesh.MPolygon;
import megamu.mesh.Voronoi;
import processing.core.PApplet;


/**
 * Performs a hierarchical layout of a performtree. 
 * Basic algorithm:
 * - Define POLY = Rect(0,0,width,height)
 * - Layout children of root using particle repulsion (stopping after particles have achieved rest)
 * - Generate Voronoi regions 
 * - For each child, layout its children use RPM and confine to its v region
 * - Recurse in this manner until all children are laid out
 * 
 * @author ben
 */
public class VoronoiTest extends PApplet {		
	Voronoi voronoi;
	ArrayList<Point2D> p;
	
	public void setup()
	{
		size(900,900);
		
		ellipseMode(PApplet.CENTER);
		smooth();		
		
		//frameRate(25);
		noLoop();
		p = new ArrayList<Point2D>();
		for(int i=0;i<100;i++)
		{
			p.add(new Point2D(Math.random()*width,Math.random()*height));
		}
		buildVoronoi(p);
		
	}		
	
	public void draw()
	{		
		background(255);		
		
		for(MPolygon mp: voronoi.getRegions())
		{
			fill((int)(Math.random()*255));
			mp.draw(this);
		}
		
		for(Point2D pt: p)
		{
			fill(0);
			noStroke();
			ellipse((float)pt.x,(float)pt.y,2,2);
		}
		
	}	
	
	public void buildVoronoi(ArrayList<Point2D> ps)
	{
		float[][] pts = new float[ps.size()][2];
		int index = 0;
		
		//System.err.printf("voronoi: ");
		for(Point2D p: ps)
		{
			pts[ps.size()-1-index][0] = (float) p.x;
			pts[ps.size()-1-index][1] = (float) p.y;
			index++;				
		}		
		voronoi = new Voronoi(pts);			
	}	
}
