

#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;



//---- Debug data

int shadow_calc_count = 0;
int shadow_calc_pixels = 0;



//---- CODE ------------------------------------------------------------------//

//---- 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[64];

  //- 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_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_intersect_sphere

float rt_intersect_sphere(RT_RAY *ray, RT_SPHERE *sphere, RT_PIXEL *pix)
{
  float x = sphere->x;
  float y = sphere->y;
  float z = sphere->z;
  float r = sphere->rad;

/*
  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 a = ray->dx*ray->dx + ray->dy*ray->dy + ray->dz*ray->dz;
  float b = 2*(ray->dx*(ray->ox-x) + ray->dy*(ray->oy-y) + ray->dz*(ray->oz-z));
  float c = (ray->ox-x)*(ray->ox-x) + (ray->oy-y)*(ray->oy-y) + (ray->oz-z)*(ray->oz-z) - r*r;

/*
  float a = ray->dx*ray->dx + ray->dy*ray->dy + 1.0f;
  float b = -2.0f*(ray->dx*x + ray->dy*y + ray->dz*z);
  float c = x*x + y*y + z*z - r*r;
*/

  sphere->d = b*b - 4*a*c;

  if(sphere->d > 0)
  {
    sphere->d = (float)sqrt(sphere->d);

    return sphere->d = (-b - sphere->d) / (a+a);
  }

  return -1;
}



//---- 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;

  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;

  if(sphere->d > 0)
  {
  	if(sphere->b > 0) sphere->b *= sphere->b;
	               else sphere->b *= -sphere->b;

    return sphere->d > sphere->b;
  }

  return false;
}



//---- rt_pix_sphere

void rt_pix_sphere(RT_RAY *ray, RT_SPHERE *sphere, RT_PIXEL *pix)
{
  float x = sphere->x;
  float y = sphere->y;
  float z = sphere->z;
  float r = sphere->rad;

  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/r;
    pix->nx = a*(pix->x - x);
    pix->ny = a*(pix->y - y);
    pix->nz = a*(pix->z - z);

    a = - (ray->dx*pix->nx + ray->dy*pix->ny + ray->dz*pix->nz);
    pix->reflx = ray->dx + 2*pix->nx*a;
    pix->refly = ray->dy + 2*pix->ny*a;
    pix->reflz = ray->dz + 2*pix->nz*a;
  }
}



//---- rt_shadow

bool 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 false;

  shadow_ray.ox = pix->x;
  shadow_ray.oy = pix->y;
  shadow_ray.oz = pix->z;

  //  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( rt_shadow_sphere(&shadow_ray, s) )
      {
	      if(ls)
        {
          ls->shadow_list = s->shadow_list;
	        s->shadow_list = shadow_list;
	        shadow_list = s;
        }
  	    return true;
      }
    }

  	ls = s;
	  s = s->shadow_list;
  }

  return false;
}



//--------------------------------------------------------------------------




//---- rt_intersect

void rt_intersect(RT_RAY *ray, RT_PIXEL *pix)
{
  //- Find which sphere this ray intersects

  int i, foundi = -1;
  float dd, d = 9999999;

  for(i=0; i<numspheres; i++)
  {
    if(ray->dx > sphere[i].x1 && ray->dx < sphere[i].x2 && ray->dy > sphere[i].y1 && ray->dy < sphere[i].y2)
    {
    	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 = false;
  }

  //- If it does then get more info

  else
  {
    rt_pix_sphere(ray, &sphere[foundi], pix);

    pix->sphere = &sphere[foundi];
    pix->shadow = rt_shadow(pix);
    pix->col = pix->sphere->col;

    if(pix->shadow)
    {
      pix->col = ((pix->col >> 1) & 0x7F7F7F7F);
    }
  }

}



//---- rt_comparePixelObjects

inline bool rt_comparePixelObjects(RT_PIXEL *pix1, RT_PIXEL *pix2)
{
  return pix1->sphere == pix2->sphere;
}



//---- rt_comparePixels

bool rt_comparePixels(RT_PIXEL *pix1, RT_PIXEL *pix2)
{
  if(pix1->sphere != pix2->sphere) return false;
  if(pix1->shadow != pix2->shadow) return false;

  return true;
}

//#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 = src->shadow;
}



//---- 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(&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);
  }

  //- 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 = false;
    }
  }

  //- Render 16x16

  for(j=0; j<sh; j+=4)
  {
    for(i=0; i<sw; i+=4)
    {
      rt_spix(&spixel[ j*sw + i ], i*4, j*4);
    }
  }

  for(j=0; j<sh-4; j+=4)
  {
    for(i=0; i<sw-4; i+=4)
    {
      offset = j*sw + i;

      if( rt_comparePixels(&spixel[ offset ], &spixel[ offset + 4]) &&
          rt_comparePixels(&spixel[ offset ], &spixel[ offset + sw*4]) &&
          rt_comparePixels(&spixel[ offset ], &spixel[ offset + sw*4 + 4]) )
      {
//        spixel[ offset ].col = 0xCC00CC;

        rt_copyPixel(&spixel[ offset + 2 ], &spixel[ offset ]);
        rt_copyPixel(&spixel[ offset + sw*2 ], &spixel[ offset ]);
        rt_copyPixel(&spixel[ offset + sw*2 + 2 ], &spixel[ offset ]);
      }
      else
      {
        rt_spix( &spixel[ offset + 2 ], i*4+8, j*4);
        rt_spix( &spixel[ offset + sw*2 ], i*4, j*4+8);
        rt_spix( &spixel[ offset + sw*2 + 2 ], i*4+8, j*4+8);
      }
    }
  }

  //- 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]) )
      {

//        if(spixel[ offset ].col != 0xCC00CC) spixel[ offset ].col = 0xFF00FF;

        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;

        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

        ray.dy = by1 + j*dy4;
        ray.dx = bx1 + i*dx4;

        for(v=0; v<4; v++)
        {
          for(u=0; u<4; u++)
          {
            rt_intersect(&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;

    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)
    {

    }

    rt_frame(minx, miny, maxx, maxy, sphere[i].col);
  }
*/
  return;
}


