/* sphere.c */

/* sphere functions:
		sphere_init() - initializes a new sphere object;
			calls object_init() to create the object, then
			call list_get_entity() to get the object so that
			the sphere can be attached to it; then load 
			attributes and set polymorphic function pointers
		sphere_load_attributes() - loads the attributes like
			the other load_attribute functions
		sphere_print() - prints a formatted dump of the sphere 
		sphere_hits() - determines if a vector projected from
			location *base in direction *dir hits the sphere; 
			if so, returns the distance from the base to the
			point of contact
*/


#include "ray.h"
#include <math.h>



//=============================================================================
// ******* sphere_init( ) *******
// 
// creates a new sphere and initializes it
//    calls object_init() 
// 	calls list_get_entity to get the	newly created object
//		attach sphere to that object
//		call sphere_load_attributes()
//		set polymorphic function pointers
//=============================================================================
void sphere_init(FILE  *in, model_t  *model, int  attrmax)
{
   sphere_t  *sph;
   object_t *obj;
   int count;
	// vec_t scale = {1, 1, 1};

   /* Call the object_init()function to create the   */
   /* object_t and process the "material" attribute  */
	object_init(in, model);
  

   /* Use list_get_entity() to make obj point to the newly  */
   /* created object_t structure.  Your list_add() function */
   /* MUST have set current to the last element in the list */
   /* for this to work correctly.                           */
	obj = (object_t *) list_get_entity(model->objs);
  

   /* malloc a sphere structure and set the priv pointer   */
   /* in the object_t structure to point to the sphere_t   */
	sph = (sphere_t *) malloc(sizeof(sphere_t));
	obj->priv = sph;
   

   /* Store the word "sphere" in the object_type field of  */
   /* the object_t structure. Use the strcpy() function    */
	strcpy(obj->obj_type, "sphere");
 

   /* Ask sphere_load_attributes to load the attributes */
   /* Attributes are center and radius.                 */
   count = sphere_load_attributes(in, sph, attrmax);
   assert(count == 2);


   /* Setup polymorphic function pointers in object_t   */
	obj->hits = sphere_hits;
	obj->printer = sphere_print;
   

   /* initialize the scale to (1, 1, 1) for spheres      */
	// vec_copy(&scale, &sph->scale);
}


//=============================================================================
// ******* sphere_load_attributes( ) *******
// 
// loads the attributes as in other load_attribute functions
//=============================================================================
int sphere_load_attributes(FILE  *in, sphere_t  *sph, int  attrmax)
{
	char attrib_name[NAME_LEN];
	int count = 0;      // number of items read
	int attrcount = 0;  // total number of attributes


	/* consume the attributes and their values  */

	/* read first attribute name                */
	count = fscanf(in, "%s", attrib_name);
	assert (count == 1);

	while (attrib_name[0] != '}') {
		if (strcmp(attrib_name, "center") == 0) {
			count = fscanf(in, "%lf %lf %lf", 
									  &sph->center.x,
									  &sph->center.y, 
									  &sph->center.z);
			assert (count == 3);
			attrcount += 1;		
		}
		else if (strcmp(attrib_name, "radius") == 0) {
			count = fscanf(in, "%lf", &sph->radius);
			assert (count == 1);
			attrcount += 1;		

		}
		else {
			fprintf(stderr, "Bad sphere attribute: %s \n", attrib_name);
			exit(1);
		}

		/* read next attribute name */
		fscanf(in, "%s", attrib_name);
	}

	return attrcount;
}


//=============================================================================
// ******* sphere_print( ) *******
// 
// prints a formatted version of the sphere structure
// format should be consistent with camera_print() or material_print()   
//=============================================================================
void sphere_print(object_t  *obj, FILE  *out)
{
   sphere_t *sph;

	sph = (sphere_t *) obj->priv;
	object_print(obj, out);

	fprintf(out, "%-12s %5.1lf %5.1lf %5.1lf\n", "center",
			  sph->center.x, sph->center.y, sph->center.z);
  
	fprintf(out, "%-12s %5.1lf\n", "radius", sph->radius);
}


//=============================================================================
// ******* sphere_hits( ) *******
// 
// determine if a vector projected from location *base
//		in direction *dir hits the sphere
//		(*dir is the unit direction vector)
// if so, the return value is the distance from the base
//		to the point of contact
//=============================================================================
double  sphere_hits(object_t  *obj, vec_t  *base, vec_t  *dir)    
{
   sphere_t *sph;

	vec_t V_prime;   /*  V_prime is V-C (center) which is the new    */
						  /*  base (viewpoint) of the ray, at the origin  */

	double a, b, c;  /*  a = D dot D  where D is the unit vector, or dir  */
						  /*  b = 2 (V' dot D)  										 */
						  /*  c = V' dot V' - r*r  									 */
   double disc;     /*  the discriminant = (b*b - 4*a*c)		    			 */
   double dist = 0.0;
	
	vec_t normal, hitpoint;

   assert(obj->cookie == OBJ_COOKIE);

   /* extract sph pointer from object structure */
   sph = (sphere_t *)obj->priv;

   /*  We will use the following notation in the comments below: */
   /*  the dist formula is the following:								  */
   /*     dist = -b - (sqrt(b*b - 4*a*c) ) / 2*a	              */
   /*  which is the same as:												  */
   /*     dist = -b - (sqrt(disc)) / 2*a	                       */

   /*  if (disc < 0) then it's a miss so return a -1				  */
   /*  if (disc == 0) then it's tangent to the sphere, we'll     */
   /*      consider this a miss also									  */
   /*  if (disc > 0) then the ray does hit the sphere and will   */
	/*      pass through it's interior									  */

   /*  dist  = signed distance from base to hitpoint location    */


   /*  Compute V_prime  */
	vec_diff(&sph->center, base, &V_prime);	


   /*  Compute a, b & c  */
   a = vec_dot(dir, dir);
   b = 2.0 * vec_dot(&V_prime, dir);
	c = vec_dot(&V_prime, &V_prime) - (sph->radius * sph->radius);


   /*  Compute the discriminant  */
	disc = (b * b) - (4 * a * c);

   /*  if disc is not > 0, then consider that a miss  */
   if (disc <= 0)	
		return -1.0;


   /* Compute dist = ( -b - (sqrt(disc)) ) / 2 * a     */
	if (a > 0)
   	dist = (-b - sqrt(disc)) / (2 * a);
	
   /* Compute location of hit point by scaling dir by dist */
   /* 	and adding to base                                */
	vec_scale(dist, dir, &hitpoint);
	vec_sum(&hitpoint, base, &hitpoint);		

	
   /* Calculate the normal, which is P - C, the vector from   */
   /* 	the Center to the Point                              */
   /* Copy hitpoint_location to obj->last_hit                 */
   /* 	and  sph->normal to obj->last_normal                 */
	vec_copy(&hitpoint, &obj->last_hit);

	vec_diff(&sph->center, &hitpoint, &normal);
   vec_unit(&normal, &normal);
	vec_copy(&normal, &obj->last_normal);	
	
   return dist;
}


