#include "StdAfx.h"
#include "GlTexture.h"
#include "SDLExt.h"

#include <C2/gl/GlApiExt.h>
#include <C2/gl/SDL/SDLImageExt.h>

#include <C2/graph/SDL_ImageLoadExt.h>

#include <boost/algorithm/string.hpp>



namespace gl
{


GlTexture::GlTexture(void)
{
	m_TexSDL = NULL;
}

GlTexture::~GlTexture(void)
{
	FinalizeTexture();
}


bool GlTexture::InitializeTexture(void)
{
	if (!m_TexObject.GenerateTexture())
		return false;

	return true;
}

void GlTexture::FinalizeTexture(void)
{
	ReleaseImage();

	m_TexObject.ReleaseTexture();
}

// テクスチャオブジェクトをプライマリに指定する
void GlTexture::BindGL(void)
{
	m_TexObject.Bind();
}

void GlTexture::SetTextureGL(const TextureConfig& config)
{
	assert(m_TexSDL != NULL);

	BindGL();

	if(config.m_EnableMipmap)
		glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR);
	else
		glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR);

	lib_gl::TEXTURE_MODE     texmode  = (config.m_EnableMipmap ? lib_gl::TEXTURE_MIPMAP : lib_gl::TEXTURE_NORMAL);
	lib_gl::TEXTURE_COMPRESS compress = (config.m_EnableCompress ? lib_gl::TEXCOMP_ENABLE : lib_gl::TEXCOMP_DISABLE);
	lib_gl::SetSDLTexture(m_TexSDL, texmode, compress);
}

//! OpenGLにテクスチャオブジェクトを登録した後, 画像バッファをクリアする
void GlTexture::SetTextureGLAndReleaseImage(const TextureConfig& config)
{
	SetTextureGL(config);

	ReleaseImageBufMain();
}

void GlTexture::ReleaseImage(void)
{
	ReleaseImageBufMain();
	m_Name = "";
	m_SourceFile = "";
}

void GlTexture::ReleaseImageBufMain(void)
{
	if (m_TexSDL == NULL)
		return;

	SDL_FreeSurface(m_TexSDL);
	m_TexSDL = NULL;
}

bool GlTexture::HasImage(void) const
{
	return m_TexSDL != NULL;
}

bool GlTexture::HasTextureObject(void) const
{
	return m_TexObject.IsValid();
}


bool GlTexture::LoadTextureFromFile(const char* filename, bool flip_y)
{
	ReleaseImage();

	LibTiffExt::BeginDisableWarningMsg();

	std::string ext = filename;
	std::string::size_type i = ext.find_last_of(',');
	ext = ext.substr(i + 1);
	boost::algorithm::to_lower(ext);

	if (ext == "spa")
		ext = "bmp";
	m_TexSDL = lib_graph::LoadSDLSurface(filename, &ext[0]);

	LibTiffExt::EndDisableWarningMsg();

	if (m_TexSDL == NULL)
		return false;

	if (flip_y)
		lib_gl::SDL_FlipY(m_TexSDL);

	m_SourceFile = filename;

	return true;
}

bool GlTexture::SetFromSDLSurface(SDL_Surface* surface)
{
	ReleaseImage();

	if (surface == NULL)
		return false;

	m_TexSDL = surface;
	return true;
}


}
