#include <math.h>
#include <stdio.h>
#include "../../common/objects.h"
#include "../../common/vector.h"
//#include "../render/vector.c"
#include "disc.h"

extern scene_data* main_scene;




double intersect_disc(point* startP, vector* projV, object* plane,
//double intersect_object(point* startP, vector* projV, object* plane, 
	point* pntIntersect)
{
	double normDproj;
	double normDvec;
	double intersectDist;
	vector normV;
	vector planeV;

	// get the plane's normal vector
	normV.x = plane->norm.x;
	normV.y = plane->norm.y;
	normV.z = plane->norm.z;

//	printd(2,"pln: %f, %f, %f\n", plane->norm.x, plane->norm.y, plane->norm.z);
//	printd(2,"srt: %f, %f, %f\n", startP->x, startP->y, startP->z);
//	printd(2,"prj: %f, %f, %f\n", projV->x, projV->y, projV->z);
//	exit(1);

	// normal dot projection
	normDproj = dot_product(&normV, projV);

	// if normDproj is 0, the ray is parallel to the plane, so we stop
	if(normDproj == 0)
		return 0;

	// finish the calc if not parallel
	// get the vector from the plane to the camera
	planeV.x = plane->pos.x - startP->x;
	planeV.y = plane->pos.y - startP->y;
	planeV.z = plane->pos.z - startP->z;

	// normal dot vector to plane
	normDvec = dot_product(&normV, &planeV);

	// if normDvec is negative it's behind the camera
	//if( normDvec < 0)
	//   return 0;

	// intersection is at normDvec / normDproj
	intersectDist = normDvec / normDproj;

	if(intersectDist < 0 )
		return 0;

	//pntIntersect->x = startP->x + projV->x*intersectDist;
	//pntIntersect->y = startP->y + projV->y*intersectDist;
	//pntIntersect->z = startP->z + projV->z*intersectDist;

	//printd(2,"intersected a plane\n");
	//return 1;
	if( distance_between(pntIntersect, &plane->pos) > plane->radius)
		return 0;

	return intersectDist;
}

/*****************************************************
 Calculates the normal vector at a point, on an object
 *****************************************************/
vector* normal_disc(point* q, object* objectHit, vector* n)
{
	n->x = objectHit->norm.x;
	n->y = objectHit->norm.y;
	n->z = objectHit->norm.z;
	return n;
}

