/* contains the implementation of the texture class files */

# include <iostream.h>
# include <math.h>
#include <fstream.h>
#include"headers.h"
void texture::load_texturefile()
{
	ifstream in("marble.tga",ios::nocreate);
	if(!(in.fail()))
	{
		unsigned char buffer[20];
		in.read((char*)&buffer,sizeof(buffer));
		int i=0,x,y;
		 width=*(buffer+12)+256* *(buffer+13);
		 height=*(buffer+14)+256* *(buffer+15);

		cout<<"width ="<<width<<"\n";
		cout<<"height ="<<height<<"\n";
		unsigned char t[120000];

		in.read((char*)&t,sizeof(t));
		

		for(y=0;y<height;y++)
		for(x=0;x<width;x++)

		data[height-y-1][x]=new color(t[(((y*width+x)+0) *3)],t[(((width*y+x)+0) *3)],t[(((width*y+x)+0) *3)]);
		

in.close();
	}

}


color texture::return_texturecolor(double u,double v)
{
	if(bilinear==0)
	{
int x= (width-1)*u;
int y= (height-1)*v;
return(*data[y][x]);
	}
else
	{

color texture_color,color1,color2,color3,color4;
int u1,u2,v1,v2;
double fractu,fractv,x,y;
 x= (width-1)*u;
 y= (height-1)*v;
u1=floor(x);
v1=floor(y);
fractu=x-u1;
fractv=y-v1;

if(fractu<=.5)
{
	u2=u1 - 1;
	fractu = fractu + .5;
}
else
{
	u2 = u1;
	u1 = u2+1;
	fractu = fractu - .5;
}

if(fractv<=.5)
{
	v2 = v1 - 1;
	fractv = fractv + .5;
}
else
{
	v2 = v1;
	v1 = v2+1;
	fractv = fractv - .5;
}

double w1 = (1 - fractu) * (1 - fractv);
double w2 = fractu * (1 - fractv);
double w3 = (1 - fractu) * fractv;
double w4 = fractu *  fractv;
if(u2<0)
{
u2=0;
u1=u2+1;
}
if(v2<0)
{
v2=0;
v1=v2+1;
}
color1.r=(data[u2][v2])->r*w1;
color1.g=(data[u2][v2])->g*w1;
color1.b=(data[u2][v2])->b*w1;
color2.r=(data[u1][v2])->r*w2;
color2.g=(data[u1][v2])->g*w2;
color2.b=(data[u1][v2])->b*w2;
color3.r=(data[u2][v1])->r*w3;
color3.g=(data[u2][v1])->g*w3;
color3.b=(data[u2][v1])->b*w3;
color4.r=(data[u1][v1])->r*w4;
color4.g=(data[u1][v1])->g*w4;
color4.b=(data[u1][v1])->b*w4;

texture_color= color1+color2+color3+color4;

return(texture_color);
	}

}