#include "common_header.h"
#include "texture.h"

CTexture::CTexture()
{
	Texture = 0;
}
CTexture::~CTexture()
{
}

CTexture::operator GLuint ()
{
	return Texture;
}

bool CTexture::loadTexture2D(char *FileName)
{
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(FileName);

	if(fif == FIF_UNKNOWN)
	{
		fif = FreeImage_GetFIFFromFilename(FileName);
	}

	if(fif == FIF_UNKNOWN)
	{
		return false;
	}

	FIBITMAP *dib = NULL;

	if(FreeImage_FIFSupportsReading(fif))
	{
		dib = FreeImage_Load(fif, FileName);
	}

	if(dib == NULL)
	{
		return false;
	}

	int Width = FreeImage_GetWidth(dib);
	int Height = FreeImage_GetHeight(dib);

	if(Width == 0 || Height == 0)
	{
		return false;
	}

	BYTE *Data = FreeImage_GetBits(dib);

	if(Data == NULL)
	{
		return false;
	}

	GLenum Format = 0;
	
	switch(FreeImage_GetBPP(dib))
	{
		case 32:
			Format = GL_BGRA;
			break;

		case 24:
			Format = GL_BGR;
			break;
	}

	if(Format == 0)
	{
		return false;
	}

	glGenTextures(1, &Texture);

	glBindTexture(GL_TEXTURE_2D, Texture);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	if(GLEW_EXT_texture_filter_anisotropic)
	{
		int gl_max_texture_max_anisotropy_ext;
		glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max_texture_max_anisotropy_ext);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_max_texture_max_anisotropy_ext);
	}

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data);

	glGenerateMipmap(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D, 0);

	FreeImage_Unload(dib);

	return true;
}

void CTexture::releaseTexture()
{
	glDeleteTextures(1, &Texture);
}
