package wonderlab.graphics.renderer;

import wonderlab.graphics.geometry.*;
import wonderlab.graphics.camera.*;
import wonderlab.graphics.world.*;
import java.util.ArrayList;
import java.util.Iterator;

public class Phong {

	Vector3D cameraPos;
	World3D world;
	ArrayList lights;
	
	public Phong(World3D w) {
		world = w;
		lights = world.lights();
	}
	
	public void shade(Vertex v) {
		Vector3D ambient, diffuse, specular, R, curColor, tempColor;
		
		Light curLight = null;
		cameraPos = world.camera().pos();
		Vector3D eye = new Vector3D(cameraPos);
		Vector3D newColor = new Vector3D(4);
		ambient = new Vector3D(v.material().ambientColor());
		newColor.copy(ambient);
		double ndotl, rdote;
// 		Light curLight = (Light)lights.get(0);
// 		ndotl = Math.max(curLight.pos().dot(v.normal()),0);
// //		v.normal().print("Normal");
// 		Vector3D newColor = new Vector3D(v.material().diffuseColor());
// 		//v.material().diffuseColor().print();
// //		curLight.pos().print("Light pos");
// 		//System.out.println(ndotl);
// 		newColor.scaleBy(ndotl);
// 		v.color().copy(newColor);
		
//		eye.subtract(v.pos());
//		eye.print("Normalizing...");
//		eye.normalize();
//		eye.print("Normalized");
		curLight = (Light)lights.get(0);
		
		for (int i = 0; i < lights.size(); i++) {
			curLight = (Light)lights.get(i);
			
			tempColor = new Vector3D(4);
			curColor = new Vector3D(curLight.color());
			diffuse = new Vector3D(v.material().diffuseColor());
			specular = new Vector3D(v.material().specularColor());
			R = new Vector3D(4);
			
			ndotl = Math.max(curLight.pos().dot(v.normal()),0);
			// calculate specular for light source
			// R = 2(N ¥ L)n - L
			R.copy(v.normal());
			R.scaleBy(2*ndotl);
			R.subtract(curLight.pos());
			rdote = Math.max(Math.pow(R.dot(eye),v.material().specularP()),0);		
			specular.scaleBy(rdote);
			diffuse.scaleBy(ndotl);							// calculate diffuse for light source
			// sum diffuse and specular and multiply by light source's inherent color
			tempColor.add(diffuse);
			tempColor.add(specular);	
			curColor.componentMultiply(tempColor);
			newColor.add(curColor);
		}
			v.color().copy(newColor);
 	}
	
}