#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "../common/objects.h"
#include "../common/vector.h"
#include "./shaders.h"
#include "../render/intersect/intersect.h"
//#include "phong.h"
//#include "tracer.h"
#include "../common/structs.h"
#include "../common/debug.h"
#include "./lighting.h"

extern scene_data* main_scene;
/*
 // {{{ diffuse light
void diffuse_light2(color* c, intersect_data* id, int ln)
{
	vector lightV;  // vector to light from point q
	point *intersectP = &id->intersect;
	double dpLN;
	double atten;
	double distance;

	// light vector
	lightV.x = main_scene->lights[ln]->pos.x - intersectP->x;
	lightV.y = main_scene->lights[ln]->pos.y - intersectP->y;
	lightV.z = main_scene->lights[ln]->pos.z - intersectP->z;
	normalize(&lightV);



	printd(CRAZY, "diffuse lighting\n");
	dpLN = dot_product(&lightV,normalize(&id->normal));

	// directly perpendicular/behind object
	if (dpLN <= 0)
		dpLN = 0;

	// light distance
	distance = sqrt( pow(main_scene->lights[ln]->pos.x-id->obj->pos.x,2) +
			pow(main_scene->lights[ln]->pos.y-id->obj->pos.y,2) +
			pow(main_scene->lights[ln]->pos.z-id->obj->pos.z,2) );

	//atten = 1/(50+2*distance+1.5*pow(distance,2))*80;
	//atten = 1/pow(distance,2)*80;
	atten = 1/distance*20;
	//atten = 5/distance;
	//atten = 1;

	c->r += (id->obj->diff.r * dpLN *
		main_scene->lights[ln]->diff.r * atten);
	c->g += (id->obj->diff.g * dpLN *
		main_scene->lights[ln]->diff.g * atten);
	c->b += (id->obj->diff.b * dpLN *
			main_scene->lights[ln]->diff.b * atten);


}
// }}} 

//{{{ phong 
void diffuse_lighting(intersect_data *id, color *new_color)
{
	vector lightV;  // vector to light from point q
	point tracePt;	//1st object on ray from object to light
	object* ob;
	point *intersectP = &id->intersect;
	vector cameraV;
	vector *norm = &id->normal;
	//vector *projV = &id->proj;

	double shadow = 1;
	double dpLN;
	double dpCR;
	//double distance;
	double atten;
	double gamma = id->obj->spec_alpha;
	//	double lightAngle;
	int i = 0;
	double distance;

	printd(DEBUG, "{phong\n");

	for(i=0; main_scene->lights[i]!=NULL; i++)
	{

		//ambient_light(new_color, id, i);

		// if we are in a shadow, try the next light (ambient is the only
		// lighting needed and it is already done
		shadow = get_shadow(i, id);
		if ( shadow  <= 0)
			continue;

		diffuse_light2(new_color, id, i);

		//specular_light(new_color, id, i);
	}

	printd(CRAZY, "final lighting addition\n");
	// divide final value by the number of lighting calcs * max value
	//     3 * 255 = 765
	new_color->r = new_color->r/765*shadow;
	new_color->g = new_color->g/765*shadow;
	new_color->b = new_color->b/765*shadow;

	printd(DEBUG, "}exiting phong\n");
	//return local;
	return;
} //}}}
*/
