package vgp.tutor.subdivision;

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 subdivision algorithms.
 * Work in progress...
 * 
 * @see			jv.viewer.PvViewer
 * @author		Konrad Polthier
 * @version		15.01.00, 1.00 revised (kp) <br>
 *					15.01.00, 1.00 created (kp)
 */
public class PjSubdivision extends PjProject {
	protected	PgPolygonSet	m_geom;
	protected	int				m_numULines = 10;
	protected	int				m_numVLines = m_numULines;

	public PjSubdivision() {
		super("Torus as Subdivision");
		m_geom = new PgPolygonSet(3);				// create a new geometry
		m_geom.setName("Torus as Subdivision");
		if (getClass() == PjSubdivision.class)
			init();
	}
	public void init() {
		m_geom.setGlobalVertexColor(Color.yellow);
		m_geom.setGlobalVertexSize(2.);
		m_geom.setGlobalVertexNormalColor(Color.red);
		m_geom.setGlobalPolygonColor(new Color(25, 20, 200));
		m_geom.setGlobalPolygonSize(2.);
		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++) {
			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++;
			}
		}
	}
}

