#include "Common.h"
#include "grid.h"
#include "scene.h"

VECTOR                 origin  = {0.0,0.0,0.0};
COLOR                  zerorad = {0.0,0.0,0.0};
DensityEstimationState deState;


// Compute the number of bits sets to one
int countBits(int v)
{
  int c = 0;
  int i = 1;

  while (v != 0)
    {
      if ((i&v)!=0)
	{
	  v ^= i;
	  c++;
	}
      i <<= 1;
    }
  return c;
}


float absMaxComponentColor(COLOR *a)
{
  COLOR c;

  COLORABS(*a,c);
  return COLORMAXCOMPONENT(c);
}


/* Given a unit vector and a coordinate system, this routine computes the spherical 
 * coordinates phi and theta of the vector with respect to the coordinate system */
void vectorToSpherical(VECTOR *C,COORDSYS *coordsys,double *phi,double *theta)
{
  double x, y, z;
  DVECTOR c;

  z = VECTORDOTPRODUCT(*C, coordsys->Z);
  if (z >  1.0) z = 1.0;
  if (z < -1.0)  z = -1.0;
  *theta = acos(z);
	
  VECTORSUMSCALED(*C, -z, coordsys->Z, c);
  VECTORNORMALIZE(c);
  x = VECTORDOTPRODUCT(c, coordsys->X);
  if (x >  1.0) x = 1.0;
  if (x < -1.0)  x = -1.0;
  y = VECTORDOTPRODUCT(c, coordsys->Y);
  *phi = acos(x);
  if (y < 0.) *phi = 2. * M_PI - *phi;
}
  

void RayCastingFunction(PATCH *p,RAY *rin,HITREC& hr)
{
  HITREC *phr;
  float  dist = HUGE;

  // Do not intersect the emissing patch
  PatchDontIntersect(1,  p);
  
  // Do ray casting
  phr = GridIntersect(WorldGrid, rin, 0., &dist, HIT_PATCH|HIT_POINT|HIT_NORMAL|HIT_FRONT|HIT_BACK);
  
  // Save hit record
  if (phr != NULL)
    hr = *phr;
  else
    hr.patch = NULL;
}

void RayCastingFunctionTwo(PATCH *p0,PATCH *p1,RAY *rin,HITREC& hr)
{
  HITREC *phr;
  float  dist = HUGE;

  // Do not intersect the emissing patch
  PatchDontIntersect(2, p0, p1);
  
  // Do ray casting
  phr = GridIntersect(WorldGrid, rin, 0., &dist, HIT_PATCH|HIT_POINT|HIT_NORMAL|HIT_FRONT|HIT_BACK);
  
  // Save hit record
  if (phr != NULL)
    hr = *phr;
  else
    hr.patch = NULL;
}




