#include <stdio.h>
#include <math.h>
#include <stdlib.h>


#include "SDL.h"
#include "SDL_image.h"

#define SCREEN_WIDTH	320
#define SCREEN_HEIGHT	240
#define SCREEN_DEPTH	32

#define CAM_HORI_ANG	(90	* 2 * PI / 360)

#define PI	3.141592

void uvToXYZ(float u, float v, float phi, float th, float *x, float *y, float *z);
void xyzToThPhi(float *phi, float *th, float x, float y, float z);
void thPhiRToXYZ(float r, float phi, float th, float *x, float *y, float *z);

Uint32 getpixel(SDL_Surface *surface, int x, int y);
void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel);

int main(int argc, char **argv)
{
	/* Variables declaration */
	
	SDL_Surface *screen = NULL, *map=NULL, *temp;
	int i,j;
	int quit = 0;
	SDL_Event event;
	
	float phi = 0, th = PI/2;
	float u,v, dx, dy, dz, cx, cy, cz, cr;
	float tempphi, tempth;
	Uint32 pixel;
	
	/* Program starting */
	
	printf("---------------\nWelcome to Our Sky Sphere !\n");
	
	if (argc < 2)
	{
		printf("Usage : 360 mapfile\n");
		exit(EXIT_FAILURE);
	}
	
	
	/* SDL initialization */
	
	if ( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0 )
	{
		fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}
	
	printf("SDL initialized.\n");
	
	screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH, \
								SDL_SWSURFACE|SDL_DOUBLEBUF);
	
	if (screen == NULL)
	{
		fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(1);
	}
	
	map = IMG_Load(argv[1]);
	temp = SDL_DisplayFormat(map);
	SDL_FreeSurface(map);
	map = temp;
	
	cr = SCREEN_WIDTH / (2 *atan(CAM_HORI_ANG/2) ) ;
	
	/* And let's rock'n'roll... */
		
	while(!quit)
	{
		
		while ( SDL_PollEvent(&event) )
		{
			if (event.type == SDL_QUIT)
			{
				printf("Ok, exiting...\n");
				quit = 1;
			}
			if (event.type == SDL_KEYDOWN)
			{
				switch(event.key.keysym.sym)
				{
					case SDLK_UP :
						th -= 5*2*PI/360;
						break;
					case SDLK_DOWN :
						th += 5*2*PI/360;
						break;
					case SDLK_LEFT :
						phi += 5*2*PI/360;
						break;
					case SDLK_RIGHT :
						phi -= 5*2*PI/360;
						break;
					default :
						break;
				}
			}
		}
		
		thPhiRToXYZ(cr, phi, th, &cx, &cy, &cz);
		
		
		SDL_LockSurface(screen);
		SDL_LockSurface(map);
		
		for( i=0 ; i<SCREEN_WIDTH ; i++)
		{
			for( j=0 ; j<SCREEN_HEIGHT ; j++) 
			{
				/* Find coordinates on the rotated plane */
				
				u = (-i + SCREEN_WIDTH/2 );
				v = (j - SCREEN_HEIGHT/2 );
				
				/* Convert to a cartesian shift compared to plane center*/
				
				uvToXYZ(u, v, phi, th, &dx, &dy, &dz);
				
				/* Find shperical angles of this point */
				
				xyzToThPhi(&tempphi, &tempth, cx+dx, cy+dy, cz+dz);
				
				/* Get corresponding pixel on the spherical map */
				
				pixel = getpixel(map, (tempphi+PI)/(2*PI)*map->w, tempth/PI*map->h);
				putpixel(screen, i, j, pixel);
			}
		}
		
		SDL_UnlockSurface(screen);
		SDL_UnlockSurface(map);
		
		
		SDL_Flip(screen);
	}
	
	SDL_Quit();
	return 0;
}

void uvToXYZ(float u, float v, float phi, float th, float *x, float *y, float *z)
{
	*x = cos(th)*cos(phi)*v - sin(phi)*u;
	*y = cos(th)*sin(phi)*v + cos(phi)*u;
	*z = -sin(th)*v;
}

void xyzToThPhi(float *phi, float *th, float x, float y, float z)
{
	*th = acos(z/sqrt(x*x + y*y + z*z));
	*phi = atan2(y,x);
}

/* th [0 ; pi]		phi [-pi ; pi] */

void thPhiRToXYZ(float r, float phi, float th, float *x, float *y, float *z)
{
	*x = r * cos(phi) * sin(th);
	*y = r * sin(phi) * sin(th);
	*z = r * cos(th);
}

/*
 * Return the pixel value at (x, y)
 * NOTE: The surface must be locked before calling this!
 */
Uint32 getpixel(SDL_Surface *surface, int x, int y)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to retrieve */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch(bpp) {
    case 1:
        return *p;

    case 2:
        return *(Uint16 *)p;

    case 3:
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
        else
            return p[0] | p[1] << 8 | p[2] << 16;

    case 4:
        return *(Uint32 *)p;

    default:
        return 0;       /* shouldn't happen, but avoids warnings */
    }
}


/*
 * Set the pixel at (x, y) to the given value
 * NOTE: The surface must be locked before calling this!
 */
void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to set */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch(bpp) {
    case 1:
        *p = pixel;
        break;

    case 2:
        *(Uint16 *)p = pixel;
        break;

    case 3:
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
        } else {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
        }
        break;

    case 4:
        *(Uint32 *)p = pixel;
        break;
    }
}
