package vgp.tutor.polygonSet;

import java.awt.Color;

import jv.geom.PgPolygonSet;
import jv.object.PsDebug;
import jv.project.PjProject;
import jv.vecmath.PdVector;
import jv.vecmath.PiVector;

/**
 * Tutorial on usage of PgPolygonSet class.
 * 
 * @see			jv.viewer.PvViewer
 * @author		Konrad Polthier
 * @version		28.11.99, 1.00 revised (kp) <br>
 *					28.11.99, 1.00 created (kp)
 */
public class PjPolygonSet extends PjProject {
	protected	PgPolygonSet	m_geom;
	protected	int				m_numULines = 10;
	protected	int				m_numVLines = m_numULines;

	public PjPolygonSet() {
		super("Torus as PolygonSet");
		m_geom = new PgPolygonSet(3);				// create a new geometry
		m_geom.setName("Torus as PolygonSet");
		if (getClass() == PjPolygonSet.class) {
			init();
		}
	}
	public void init() {
		m_geom.setGlobalVertexColor(Color.yellow);
		m_geom.setGlobalVertexSize(4.);
		m_geom.setGlobalVertexNormalColor(Color.red);
		m_geom.setGlobalPolygonColor(new Color(25, 20, 200));
		m_geom.setGlobalPolygonSize(4.);
		// Enable usage of individual polygon colors
		m_geom.showPolygonColors(true);
		// Assure that polygon colors are allocated, needs to be called only once.
		m_geom.assurePolygonColors();
		// Show arrow at end of each polygon
		m_geom.showPolygonEndArrow(true);
		computeLines();
	}
	public void start() {
		if (PsDebug.NOTIFY) PsDebug.notify("computing torus as element set");
		addGeometry(m_geom);
		selectGeometry(m_geom);
		super.start();
	}
	public void computeLines() {
		m_geom.setNumVertices(m_numULines*(m_numULines+1)/2);
		m_geom.setNumPolygons(m_numULines);
		m_geom.assureVertexNormals();

		double thick = 1.;
		double radius = 2.;
		double uFac=0, vFac=0;
		if (m_numULines > 1)
			uFac = 2.*Math.PI/(-1.+m_numULines);
		if (m_numVLines > 1)
			vFac = 2.*Math.PI/(-1.+m_numVLines);
		// generate vertices and vertex normals
		PdVector [] vertex			= m_geom.getVertices();
		PdVector [] vertexNormal	= m_geom.getVertexNormals();
		int ind = 0;
		for (int i=0; i<m_numULines; i++) {
			// Set a sample coloring for each polygon
			int val = (int)(i*255/(m_numULines-1.f));
			m_geom.setPolygonColor(i, new Color(val, 255-val, 0));
			// Compute coordinates of polygon vertices
			double u = uFac*i;
			PiVector line = m_geom.getPolygon(i);
			line.setSize(m_numULines-i);
			for (int j=0; j<m_numULines-i; j++) {
				double v = Math.PI+vFac*j;
				vertex[ind].m_data[0] = Math.cos(u)*(thick*Math.cos(v)+radius);
				vertex[ind].m_data[1] = Math.sin(u)*(thick*Math.cos(v)+radius);
				vertex[ind].m_data[2] = thick*Math.sin(v);

				vertexNormal[ind].m_data[0] = Math.cos(u)*Math.cos(v);
				vertexNormal[ind].m_data[1] = Math.sin(u)*Math.cos(v);
				vertexNormal[ind].m_data[2] = Math.sin(v);
				
				line.m_data[j] = ind;
				ind++;
			}
		}
	}
}

