

#include <windows.h>
#include <mmsystem.h>
#include <math.h>
#include "rt.h"



//---- DATA ------------------------------------------------------------------//

//---- Render buffer

int *buf;
int w, h;

float bx1, by1, bx2, by2;
float dx, dy, dx4, dy4, dx8, dy8;



//---- Scene

RT_SPHERE *sphere;
int numspheres = 0;

float light_x = 1.0, light_y = 5.0, light_z = 2.0;



//---- Render data

int sw, sh;

RT_PIXEL *spixel;

RT_SPHERE *shadow_list = NULL;

int stamp = 0;



//---- Debug data

int shadow_calc_count = 0;
int shadow_calc_pixels = 0;



//---- FUNCTION PROTOS -------------------------------------------------------//

void rt_pix_sphere(RT_RAY *ray, RT_SPHERE *sphere, RT_PIXEL *pix);
RT_SPHERE *rt_shadow(RT_PIXEL *pix);



//---- SETUP FUNCTIONS -------------------------------------------------------//

//---- rt_startup

void rt_startup(int *buffer, int width, int height)
{
  //- Render buffer

  buf = buffer;
  w = width;
  h = height;

  bx1 = -1.0f*w/h;
  bx2 =  1.0f*w/h;
  dx = 2.0f/h;
  dx4 = dx * 4.0f;
  dx8 = dx * 8.0f;

  by1 =  1.0f;
  by2 = -1.0f;
  dy = -2.0f/h;
  dy4 = dy * 4.0f;
  dy8 = dy * 8.0f;

  //- Allocate scene

  sphere = new RT_SPHERE[128];

  //- Allocate render data

  sw = ((w & -4) >> 2) + 1;
  sh = ((h & -4) >> 2) + 1;

  spixel = new RT_PIXEL[sw*sh];
}



//---- rt_shutdown

void rt_shutdown()
{
  delete[] sphere;

  delete[] spixel;
}



//---- rt_tempSphere

void rt_tempSphere(float x, float y, float z, float rad, int col)
{
  sphere[numspheres].ax = x;
  sphere[numspheres].ay = y;
  sphere[numspheres].az = z;
  
  sphere[numspheres].x = x;
  sphere[numspheres].y = y;
  sphere[numspheres].z = z;

  sphere[numspheres].rad = rad;
  sphere[numspheres].col = col;

  sphere[numspheres].shadow_list = shadow_list;
  shadow_list = &sphere[numspheres];

  numspheres ++;
}

//---- rt_addSphere

void rt_addSphere(float x, float y, float z, float rad, int col)
{
  sphere[numspheres].ax = x;
  sphere[numspheres].ay = y;
  sphere[numspheres].az = z;
  
  sphere[numspheres].x = x;
  sphere[numspheres].y = y;
  sphere[numspheres].z = z;

  sphere[numspheres].rad = rad;
  sphere[numspheres].col = col;

  sphere[numspheres].shadow_list = shadow_list;
  shadow_list = &sphere[numspheres];

  numspheres ++;

/*
  rt_tempSphere(x+rad*1.4, y, z, rad*0.5, col);
  rt_tempSphere(x-rad*1.4, y, z, rad*0.5, col);
  rt_tempSphere(x, y+rad*1.4, z, rad*0.5, col);
  rt_tempSphere(x, y-rad*1.4, z, rad*0.5, col);
  rt_tempSphere(x, y, z+rad*1.4, rad*0.5, col);
  rt_tempSphere(x, y, z-rad*1.4, rad*0.5, col);
*/
}




//---- RAY PRECALC FUNCTIONS -------------------------------------------------//

inline void rt_ray_first_precalc(RT_RAY *ray)
{
  ray->dx2 = ray->dx*ray->dx;
  ray->dy2 = ray->dy*ray->dy;
  ray->dz2 = 1.0f;
	ray->len2 = ray->dx2 + ray->dy2 + 1.0f;
	ray->leno22 = 0.5f / ray->len2;
	ray->len42 = 4.0f * ray->len2;
}



inline void rt_ray_precalc(RT_RAY *ray)
{
  ray->dx2 = ray->dx*ray->dx;
  ray->dy2 = ray->dy*ray->dy;
  ray->dz2 = ray->dz*ray->dz;
	ray->len2 = ray->dx2 + ray->dy2 + ray->dz2;
	ray->leno22 = 0.5f / ray->len2;
	ray->len42 = 4.0f * ray->len2;
}



//---- FIRST HIT RAY FUNCTIONS -----------------------------------------------//



//---- rt_intersect_first_sphere

float rt_intersect_first_sphere(RT_RAY *ray, RT_SPHERE *sphere, RT_PIXEL *pix)
{
  float b = -2.0f*(ray->dx*sphere->x + ray->dy*sphere->y + sphere->z);

  sphere->d = b*b - ray->len42*sphere->c;

  if(sphere->d > 0)
  {
    sphere->d = (float)sqrtf(sphere->d);

    return sphere->d = (-b - sphere->d) * ray->leno22;
  }

  return -1;
}



//---- rt_intersect_first

void rt_intersect_first(RT_RAY *ray, RT_PIXEL *pix)
{
  //- Precalculate ray values

  rt_ray_first_precalc(ray);

  //- Find which sphere this ray intersects

  int i, foundi = -1;
  float dd, d = 9999999;

  for(i=0; i<numspheres; i++)
  {
    if(sphere[i].stamp >= stamp && ray->dx > sphere[i].x1 && ray->dx < sphere[i].x2 && ray->dy > sphere[i].y1 && ray->dy < sphere[i].y2)
    {
    	dd = rt_intersect_first_sphere(ray, &sphere[i], pix);
      if(dd > 0.0001 && dd < d) { d = dd; foundi = i; }
    }
  }

  //- If it doesn't intersect any of them then return blank pixel

  if(foundi < 0)
  {
    pix->sphere = NULL;
    pix->col = 0;
    pix->shadow_sphere = NULL;
  }

  //- If it does then get more info

  else
  {
    rt_pix_sphere(ray, &sphere[foundi], pix);

    pix->sphere = &sphere[foundi];
    pix->shadow_sphere = rt_shadow(pix);
    pix->col = pix->sphere->col;

    if(pix->shadow_sphere)
    {
      pix->col = ((pix->col >> 1) & 0x7F7F7F7F);// + ((pix->shadow_sphere->col >> 2) & 0x3F3F3F3F);
    }
  }

}



//---- GENERAL (NON-FIRST HIT) RAY FUNCTIONS ---------------------------------//



//---- rt_intersect_sphere

float rt_intersect_sphere(RT_RAY *ray, RT_SPHERE *sphere, RT_PIXEL *pix)
{
/*
  sphere->a = ray->dx*ray->dx + ray->dy*ray->dy + ray->dz*ray->dz;
  sphere->b = 2*(ray->dx*(ray->ox-x) + ray->dy*(ray->oy-y) + ray->dz*(ray->oz-z));
  sphere->c = (ray->ox-x)*(ray->ox-x) + (ray->oy-y)*(ray->oy-y) + (ray->oz-z)*(ray->oz-z) - r*r;
  sphere->d = sphere->b*sphere->b - 4*sphere->a*sphere->c;
*/

  float b = -2.0f*(ray->dx*(ray->ox-sphere->x) + ray->dy*(ray->oy-sphere->y) + ray->dz*(ray->oz-sphere->z));

  sphere->d = b*b - ray->len42*sphere->c;

  if(sphere->d > 0)
  {
    sphere->d = sqrtf(sphere->d);

    return sphere->d = (-b - sphere->d) * ray->leno22;
  }

  return -1;
}



//---- rt_intersect

void rt_intersect(RT_RAY *ray, RT_PIXEL *pix)
{
  //- Precalculate ray values

  rt_ray_precalc(ray);

  //- Find which sphere this ray intersects

  int i, foundi = -1;
  float dd, d = 9999999;

  for(i=0; i<numspheres; i++)
  {
  	dd = rt_intersect_sphere(ray, &sphere[i], pix);
    if(dd > 0.0001 && dd < d) { d = dd; foundi = i; }
  }

  //- If it doesn't intersect any of them then return blank pixel

  if(foundi < 0)
  {
    pix->sphere = NULL;
    pix->col = 0;
    pix->shadow_sphere = NULL;
  }

  //- If it does then get more info

  else
  {
    rt_pix_sphere(ray, &sphere[foundi], pix);

    pix->sphere = &sphere[foundi];
    pix->shadow_sphere = rt_shadow(pix);
    pix->col = pix->sphere->col;

    if(pix->shadow_sphere)
    {
      pix->col = ((pix->col >> 1) & 0x7F7F7F7F);// + ((pix->shadow_sphere->col >> 2) & 0x3F3F3F3F);
    }
  }

}



//---- SHADOW & PIXEL FUNCTIONS ----------------------------------------------//

//---- rt_shadow_sphere

bool rt_shadow_sphere(RT_RAY *ray, RT_SPHERE *sphere)
{
  float x = sphere->x;
  float y = sphere->y;
  float z = sphere->z;
//  float r = sphere->rad;

//  float a = ray->dx2 + ray->dy2 + ray->dz2;
  float b = 2.0f*(ray->dx*(ray->ox-sphere->x) + ray->dy*(ray->oy-sphere->y) + ray->dz*(ray->oz-sphere->z));
  float c = (ray->ox-x)*(ray->ox-x) + (ray->oy-y)*(ray->oy-y) + (ray->oz-z)*(ray->oz-z) - sphere->r2;
  float d = b*b - ray->len42*c;

/*
  float b = 2.0f*(ray->dx*(ray->ox-sphere->x) + ray->dy*(ray->oy-sphere->y) + ray->dz*(ray->oz-sphere->z));
  float d = b*b - ray->len42*sphere->c;
*/

  if(d > 0)
  {
  	if(b > 0) b *= b; else b *= -b;
    return d > b;
  }

  return false;
}



//---- rt_shadow

RT_SPHERE *rt_shadow(RT_PIXEL *pix)
{
  //  Calculate shadow ray

  RT_RAY shadow_ray;

  shadow_ray.dx = light_x - pix->x;
  shadow_ray.dy = light_y - pix->y;
  shadow_ray.dz = light_z - pix->z;

  //  Check object normal

  float d = pix->nx * shadow_ray.dx + pix->ny * shadow_ray.dy + pix->nz * shadow_ray.dz;
  if(d < 0) return pix->sphere;

//  return false;

  shadow_ray.ox = pix->x;
  shadow_ray.oy = pix->y;
  shadow_ray.oz = pix->z;

  shadow_ray.dx2 = shadow_ray.dx * shadow_ray.dx;
  shadow_ray.dy2 = shadow_ray.dy * shadow_ray.dy;
  shadow_ray.dz2 = shadow_ray.dz * shadow_ray.dz;

	rt_ray_precalc(&shadow_ray);
  
	//  Test against objects

  int i;

  RT_SPHERE *ls = NULL, *s = shadow_list;

  shadow_calc_pixels ++;

  for(i=0; i<numspheres; i++)
  {
    if(s != pix->sphere)
    {
      shadow_calc_count ++;

  	  if( s->shadow_stamp >= stamp && rt_shadow_sphere(&shadow_ray, s) )
      {
	      if(ls)
        {
          ls->shadow_list = s->shadow_list;
	        s->shadow_list = shadow_list;
	        shadow_list = s;
        }
  	    return s;
      }
    }

  	ls = s;
    s = s->shadow_list;
  }

  return NULL;
}



//---- rt_pix_sphere

void rt_pix_sphere(RT_RAY *ray, RT_SPHERE *sphere, RT_PIXEL *pix)
{
  if(sphere->d > 0)
  {
    pix->t = sphere->d;

    pix->x = ray->ox + pix->t*ray->dx;
    pix->y = ray->oy + pix->t*ray->dy;
    pix->z = ray->oz + pix->t*ray->dz;

    float a = 1.0f/sphere->rad;
    pix->nx = a*(pix->x - sphere->x);
    pix->ny = a*(pix->y - sphere->y);
    pix->nz = a*(pix->z - sphere->z);

    a = - 2.0f * (ray->dx*pix->nx + ray->dy*pix->ny + ray->dz*pix->nz);
    pix->reflx = ray->dx + pix->nx*a;
    pix->refly = ray->dy + pix->ny*a;
    pix->reflz = ray->dz + pix->nz*a;
  }
}



//--------------------------------------------------------------------------




//---- rt_comparePixelObjects

inline bool rt_comparePixelObjects(RT_PIXEL *pix1, RT_PIXEL *pix2)
{
  return pix1->sphere == pix2->sphere;
}



//---- rt_comparePixels

inline bool rt_comparePixels(RT_PIXEL *pix1, RT_PIXEL *pix2)
{
  return pix1->sphere == pix2->sphere &&
         ((bool)pix1->shadow_sphere) == (bool)(pix2->shadow_sphere);
}

//#define rt_comparePixels(a, b) ((a)->sphere == (b)->sphere && (a)->shadow == (b)->shadow)



//---- rt_copyPixel

void rt_copyPixel(RT_PIXEL *dest, RT_PIXEL *src)
{
  dest->col = src->col;
  dest->sphere = src->sphere;
  dest->shadow_sphere = src->shadow_sphere;
}



//---- rt_spix

void rt_spix(RT_PIXEL *spix, int x, int y)
{
  RT_RAY ray;

  ray.ox = 0;
  ray.oy = 0;
  ray.oz = 0;

  ray.dx = bx1 + x*dx;
  ray.dy = by1 + y*dy;
  ray.dz = 1;

  rt_intersect_first(&ray, spix);
}



//---- rt_pixel

void rt_pixel(int x, int y, int col)
{
  if(x >= 0 && x < w && y >= 0 && y < h) buf[y*w+x] = col;
}



//---- rt_dot

void rt_dot(int x, int y, int col)
{
  int i, j, col2;

  if((col&255) + ((col>>8)&255) + ((col>>16)&255) < 384) col2 = 0xFFFFFF; else col2 = 0x000000;

  for(i=-1; i<=1; i++)
  {
    rt_pixel(x-2, y+i, col2);
    rt_pixel(x+2, y+i, col2);
    rt_pixel(x+i, y-2, col2);
    rt_pixel(x+i, y+2, col2);
  }

  for(j=-1; j<=1; j++) for(i=-1; i<=1; i++) rt_pixel(x+i, y+j, col);
}



//---- rt_box

void rt_box(int x1, int y1, int x2, int y2, int col)
{
  int i;

  for(i=x1; i<x2; i++) rt_pixel(i, y1, col);
  for(i=x1; i<x2; i++) rt_pixel(i, y2, col);

  for(i=y1; i<y2; i++) rt_pixel(x1, i, col);
  for(i=y1; i<y2; i++) rt_pixel(x2, i, col);
}



//---- rt_frame

void rt_frame(int x1, int y1, int x2, int y2, int col)
{
  int col2;

  if((col&255) + ((col>>8)&255) + ((col>>16)&255) < 384) col2 = 0xFFFFFF; else col2 = 0x000000;

  rt_box(x1-1, y1-1, x2+1, y2+1, col2);
  rt_box(x1+1, y1+1, x2-1, y2-1, col2);

  rt_box(x1, y1, x2, y2, col);
}



//---- rt_render

void rt_render(float rx, float ry)
{
  int i, j, k, kk, x, y, u, v;

  int offset;

  //- Transform spheres

  float tx, ty, tz, s, c;

  for(i=0; i<numspheres; i++)
  {
    s = (float)sin(3.14159*ry);
    c = (float)cos(3.14159*ry);

    tx = sphere[i].ax * c + sphere[i].az * s;
    tz = sphere[i].az * c - sphere[i].ax * s;
    ty = sphere[i].ay;

    s = (float)sin(3.14159*rx);
    c = (float)cos(3.14159*rx);

    sphere[i].x = tx;
    sphere[i].y = ty * c + tz * s;
    sphere[i].z = 6 + tz * c - ty * s;
  }

  //- Work out screen-space bounding boxes

  for(i=0; i<numspheres; i++)
  {
    float sx = w*0.5 + h*0.5 * sphere[i].x / sphere[i].z;
    float sy = h*0.5 + h*0.5 * sphere[i].y / sphere[i].z;

//    rt_dot(sx, sy, sphere[i].col);

    float radx = sphere[i].rad * h*0.75 / sphere[i].z;
    float rady = sphere[i].rad * h*0.75 / sphere[i].z;

    if(sx-w*0.5-radx < -h*0.5 || sx-w*0.5+radx > h*0.5) radx *= w/h;

//    radx = 20;
//    rady = 20;

    sphere[i].x1 = (sx-radx-w*0.5)/(h*0.5);
    sphere[i].y1 = (sy-rady-h*0.5)/(h*0.5);
    sphere[i].x2 = (sx+radx-w*0.5)/(h*0.5);
    sphere[i].y2 = (sy+rady-h*0.5)/(h*0.5);
  }

  //- Work out per-frame constants

  for(i=0; i<numspheres; i++)
  {
    sphere[i].r2 = sphere[i].rad*sphere[i].rad;
    sphere[i].c = sphere[i].x*sphere[i].x + sphere[i].y*sphere[i].y + sphere[i].z*sphere[i].z - sphere[i].r2;
  }

  //- Mark all objects as active

  stamp = 0;
  for(i=0; i<numspheres; i++) sphere[i].stamp = sphere[i].shadow_stamp = 0;

  //- Reset debug data

  shadow_calc_count = 0;
  shadow_calc_pixels = 0;

  //- Clear (debug)
/*
  for(j=0; j<sh; j++)
  {
    for(i=0; i<sw; i++)
    {
      spixel[ j*sw + i ].col = 0xFF00FF;
      spixel[ j*sw + i ].sphere = NULL;
      spixel[ j*sw + i ].shadow_sphere = NULL;
    }
  }
*/
  //- Render 8x8

  for(j=0; j<sh; j+=2)
  {
    for(i=0; i<sw; i+=2)
    {
      rt_spix(&spixel[ j*sw + i ], i*4, j*4);
    }
  }

  //- Render 4x4

  for(j=0; j<sh-2; j+=2)
  {
    for(i=0; i<sw-2; i+=2)
    {
      offset = j*sw + i;
//      rt_spix(&spixel[ j*sw + i ], i*4, j*4);

      if( rt_comparePixels(&spixel[ offset ], &spixel[ offset + 2]) &&
          rt_comparePixels(&spixel[ offset ], &spixel[ offset + sw*2]) &&
          rt_comparePixels(&spixel[ offset ], &spixel[ offset + sw*2 + 2]) )
      {

//        spixel[ offset ].col = 0xFF00FF;

        //  TODO: Render 8x8 square here!!
        
        rt_copyPixel(&spixel[ offset + 1 ], &spixel[ offset ]);
        rt_copyPixel(&spixel[ offset + sw ], &spixel[ offset ]);
        rt_copyPixel(&spixel[ offset + sw + 1 ], &spixel[ offset ]);
      }
      else
      {
        rt_spix( &spixel[ offset + 1 ], i*4+4, j*4);
        rt_spix( &spixel[ offset + sw ], i*4, j*4+4);
        rt_spix( &spixel[ offset + sw + 1 ], i*4+4, j*4+4);
      }
    }
  }

  //- Display

  int bigoffset = 0;
  int pixoffset = 0;

  int col;

  RT_PIXEL spix;
  RT_RAY ray;
  ray.ox = 0;
  ray.oy = 0;
  ray.oz = 0;
  ray.dz = 1;

  for(j=0; j<sh-1; j++)
  {
    pixoffset = bigoffset;

    for(i=0; i<sw-1; i++)
    {
      offset = j*sw + i;

      if( rt_comparePixels(&spixel[ offset ], &spixel[ offset + 1]) &&
          rt_comparePixels(&spixel[ offset ], &spixel[ offset + sw]) &&
          rt_comparePixels(&spixel[ offset ], &spixel[ offset + sw + 1]) )
      {
        //  All 4 pixels have same object and shadow

        col = spixel[ j*sw+i ].col;// == 0xFF00FF ? 0xFF00FF : 0;

        for(v=0; v<4; v++)
        {
          for(u=0; u<4; u++)
          {
            buf[ pixoffset++ ] = col;
          }
		      pixoffset += w-4;
        }
      }
/*
      else
      if( rt_comparePixelObjects(&spixel[ offset ], &spixel[ offset + 1]) &&
          rt_comparePixelObjects(&spixel[ offset ], &spixel[ offset + sw]) &&
          rt_comparePixelObjects(&spixel[ offset ], &spixel[ offset + sw + 1]) )
      {
        //  Different shadow flag, same object

        for(v=0; v<4; v++)
        {
		      for(u=0; u<4; u++) buf[ pixoffset++ ] = 0;
		      pixoffset += w-4;
        }
      }
*/
      else
      {
        //  Different objects and shadows

        stamp ++;

        if(spixel[ offset ].sphere) spixel[ offset ].sphere->stamp = stamp;
        if(spixel[ offset+1 ].sphere) spixel[ offset+1 ].sphere->stamp = stamp;
        if(spixel[ offset+sw ].sphere) spixel[ offset+sw ].sphere->stamp = stamp;
        if(spixel[ offset+sw+1 ].sphere) spixel[ offset+sw+1 ].sphere->stamp = stamp;

        if(spixel[ offset ].shadow_sphere) spixel[ offset ].shadow_sphere->shadow_stamp = stamp;
        if(spixel[ offset+1 ].shadow_sphere) spixel[ offset+1 ].shadow_sphere->shadow_stamp = stamp;
        if(spixel[ offset+sw ].shadow_sphere) spixel[ offset+sw ].shadow_sphere->shadow_stamp = stamp;
        if(spixel[ offset+sw+1 ].shadow_sphere) spixel[ offset+sw+1 ].shadow_sphere->shadow_stamp = stamp;

        ray.dy = by1 + j*dy4;
        ray.dx = bx1 + i*dx4;

        for(v=0; v<4; v++)
        {
          for(u=0; u<4; u++)
          {
            rt_intersect_first(&ray, &spix);
            buf[ pixoffset++ ] = spix.col;

            ray.dx += dx;
          }

          ray.dx -= dx4;
          ray.dy += dy;
		      pixoffset += w-4;
        }
      }

      pixoffset -= w*4;
      pixoffset += 4;
    }

    bigoffset += w*4;
  }

  //- Testing stuff
/*
  for(i=0; i<numspheres; i++)
  {
    float sx = w*0.5 + h*0.5 * sphere[i].x / sphere[i].z;
    float sy = h*0.5 - h*0.5 * sphere[i].y / sphere[i].z;

    float r = sphere[i].rad;

    rt_dot(sx, sy, sphere[i].col);

    float minx = w, miny = h, maxx = 0, maxy = 0;

    int a, b, c;

    for(a=-1; a<=1; a+=2) for(b=-1; b<=1; b+=2) for(c=-1; c<=1; c+=2)
    {
      float px = w*0.5 + h*0.5 * (sphere[i].x + a*r) / (sphere[i].z + c*r);
      float py = h*0.5 - h*0.5 * (sphere[i].y + b*r) / (sphere[i].z + c*r);

      if(px < minx) minx = px;
      if(py < miny) miny = py;

      if(px > maxx) maxx = px;
      if(py > maxy) maxy = py;
    }

    rt_frame(minx, miny, maxx, maxy, sphere[i].col);
  }

  float sx = w*0.5 + h*0.5 * light_x / light_z;
  float sy = h*0.5 - h*0.5 * light_y / light_z;

  rt_dot(sx, sy, 0x0000FF);
*/
  
  return;
}


