/*  camera.c  */
/*  camera functions:
		camera_init() - initializes camera object
		camera_load_attributes() - loads attributes from input file
		camera_print() - prints value loaded from input file
		camera_getdir() - gets unit vector from viewpoint to pixel
		get_rgb() - converts, scales & clamps each r, g, or b 
		camera_store_pixel() - stores the converted pixel
		camera_write_image() - writes image to file
*/



#include "ray.h"


//=============================================================================
// ******* camera_init( ) *******
// 
// Initializes a camera structure
// calls camera_load_attributes( )
//=============================================================================
void camera_init(FILE *in, model_t *model, int attrmax) {
	int attribcount;

	// Allocate camera structure and store cookie code 
	camera_t *cam = (camera_t *)malloc(sizeof(camera_t));
	cam->cookie = CAM_COOKIE;
	
	// Read attributes into camera data structure 
	attribcount = camera_load_attributes(in, cam);
	assert(attribcount == 3);

	// Allocate an image structure to hold the ppm image data 
	cam->pixmap = (irgb_t *)malloc(sizeof(irgb_t) * cam->pixel_dim[X] * 
																	cam->pixel_dim[Y]);
		
	// Save camera pointer in model structure 
	model->cam = cam;
}

//=============================================================================
// ******* camera_load_attributes( ) *******
//
// reads the info in from the file that contains the 3 camera
// 	attributes: pixeldim, worlddim, and viewpoint 
// attrcount should be 3 after reading in 3 attributes
//=============================================================================
int camera_load_attributes(FILE *in, camera_t *cam) {
	char attrib_name[NAME_LEN];
	int count = 0;     // number of items read
	int attrcount = 0; // total number of attributes

	// First read camera name string into cam->name 
	count = fscanf(in, "%s", cam->name);
	assert(count == 1);

	// Now consume "{" 
	count = fscanf(in, "%s", attrib_name);
	assert(count == 1);
	assert(attrib_name[0] == '{');

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

	// '}' means end of the camera definition 
	while (attrib_name[0] != '}') {
		if (strcmp(attrib_name, "pixeldim") == 0) {
			count = fscanf(in, "%d %d", &cam->pixel_dim[X], &cam->pixel_dim[Y]);
			assert(count == 2);
			attrcount += 1;
		}

		else if (strcmp(attrib_name, "worlddim") == 0) {
			count = fscanf(in, "%lf %lf", &cam->world_dim[X], &cam->world_dim[Y]);
			assert(count == 2);
			attrcount += 1;
		}
			
		else if (strcmp(attrib_name, "viewpoint") == 0) {
			count = fscanf(in, "%lf %lf %lf", 
				 &cam->view_point.x, &cam->view_point.y, &cam->view_point.z);
			assert(count == 3);
			attrcount += 1;
		}

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

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

	return(attrcount);
}

//=============================================================================
// ******* camera_print( ) *******
//
// will print to the file specified by "out"
// 	the attributes read in from camera.txt 
//=============================================================================
void camera_print (camera_t *cam, FILE *out) {
	assert(cam->cookie == CAM_COOKIE);

	fprintf(out, "%-12s %s \n", "camera", cam->name);
	fprintf(out, "%-12s %5i %5i \n", "pixeldim", 
		cam->pixel_dim[X], 
		cam->pixel_dim[Y]);
	fprintf(out, "%-12s %5.1lf %5.1lf \n", "worlddim", 
		cam->world_dim[X], 
		cam->world_dim[Y]);
	fprintf(out, "%-12s %5.1lf %5.1lf %5.1lf \n\n", "viewpoint", 
		cam->view_point.x, 
		cam->view_point.y, 
		cam->view_point.z); 
}

//=============================================================================
// ******* camera_getdir( ) *******
// 
// computes the unit vector from the viewpoint to the 
// 	(x,y) pixel coordinates passed in as parameters
// vec_t *uvec is the resulting unit vector 
//=============================================================================
void camera_getdir(camera_t *cam, int x, int y, vec_t *uvec) {
	assert(cam->cookie == CAM_COOKIE);

	vec_t world;  // temporary vector for converted values

	// fill in world with converted values 
	world.x = (double)x / (cam->pixel_dim[X] - 1) * cam->world_dim[X];
	world.y = (double)y / (cam->pixel_dim[Y] - 1) * cam->world_dim[Y];
	world.z = 0.0;

	vec_copy(&world, uvec);  // copy temporary into result
	vec_diff(&cam->view_point, uvec, uvec);  // get the vector
	vec_unit(uvec, uvec);  // get the unit vector
}
	
//=============================================================================
// ******* get_rgb( ) *******
//
// will do the computation for each r, g, or b value sent to it 
//=============================================================================
unsigned char get_rgb(float pixel_color) {
	// scale by 255 and add for integer rounding
	float new_value = pixel_color * 255.0 + .5;

	// clamp extreme values
	if (new_value < 0.0)
		return (unsigned char)0;
	else if (new_value > 255.0)
		return (unsigned char)255;
	else
		return (unsigned char)new_value;
}

//=============================================================================
// ******* camera_store_pixel( ) *******
//
// converts a pixel from drgb_t to irgb_t and
// 	stores it in the image associated with the camera 
//=============================================================================
void camera_store_pixel(camera_t *cam, int x, int y, drgb_t *pix) {
	assert(cam->cookie == CAM_COOKIE);

	int row, col;
	// get target coordinate (col, row) because origin is now at bottom left
	// col is x
	// row is converted y
	row = cam->pixel_dim[Y] - y - 1;
	col = x;

	// declare a pointer to point to the pixel in the camera's image
	irgb_t *ipix;
	ipix = cam->pixmap + row * cam->pixel_dim[X] + col;	

	// scale and clamp each r, g, b value and put into location being pointed to
	ipix->r = get_rgb(pix->r);
	ipix->g = get_rgb(pix->g);
	ipix->b = get_rgb(pix->b);

	/* alternate algorithm:
		scale and clamp pixel pix
		declare an irgb_t called ipix
		for r, g, b value of scaled & clamped pixel pix:
			cast int to each and
			store those converted int values to the irgb_t ipix
		calculate target row (converted y)
		save to cam->pixmap[row * cam->pixel_dim[X] + x] the ipix

		pix->r = get_rgb(pix->r);
		pix->g = get_rgb(pix->g);
		pix->b = get_rgb(pix->b);

		irgb_t ipix;
		ipix.r = (int) pix->r;
		ipix.g = (int) pix->g;
		ipix.b = (int) pix->b;

		int row = cam->pixel_dim[Y] - y - 1;
		cam->pixmap[row * cam->pixel_dim[X] + x] = ipix;
	*/
}

//=============================================================================
// ******* camera_write_image( ) *******
//
// uses the fprintf( ) to write the .ppm header
// and fwrite() to write the image to the file
//=============================================================================
void camera_write_image(camera_t *cam, FILE *out) {
	fprintf(out, "P6\n");
	fprintf(out, "%d %d 255\n", cam->pixel_dim[X], cam->pixel_dim[Y]);

	fwrite(cam->pixmap, sizeof(irgb_t), cam->pixel_dim[X] * 
													cam->pixel_dim[Y], out);
}



