#include "StdAfx.h"
#include "EnvImage.h"

#include <LibGeo/Mesh/BaseMeshGen.h>


namespace gl
{


EnvImage::EnvImage(void)
{
	m_VisibleEnvSphere = false;
	m_IsEnableReflection = true;
	m_TexTrans.m_FlipY = false;

	m_EnvReflection = 0.2f;
}


void EnvImage::InitEnvMap(void)
{
	lib_geo::BaseMeshGen::GenSphere( m_EnvSphere , 1.0f , 32 , 40 );
}

void EnvImage::ClearEnv(void)
{
	m_Tex.FinalizeTexture();
}

void EnvImage::LoadTexture(const char* filename)
{
	ClearEnv();

	gl::TextureConfig config;
	config.m_EnableCompress = false;
	config.m_EnableMipmap = false;

	m_Tex.InitializeTexture();
	m_Tex.LoadTextureFromFile(filename, false);
	m_Tex.SetTextureGLAndReleaseImage(config);
}


void EnvImage::Draw(float radius, const lm::vec3f& center)
{
	if(!m_VisibleEnvSphere)
		return;

	glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glDepthMask(GL_FALSE);
	glDisable(GL_CULL_FACE);

	glPushMatrix();
	glTranslatef(center.x, center.y, center.z);
	glScalef(radius, radius, radius);

	if(m_Tex.HasTextureObject())
		ShowTexture();
	else
		ShowWire();

	glPopMatrix();

	glPopAttrib();
}

void EnvImage::ShowWire(void)
{
	glColor3d(1,0,0);
	for(size_t i = 0; i < m_EnvSphere.m_Faces.size(); ++i)
	{
		const lib_geo::BaseFace& f = m_EnvSphere.m_Faces[i];

		glBegin(GL_LINE_LOOP);
		for(size_t j = 0; j < f.m_VertIds.size(); ++j)
		{
			glVertex3fv(m_EnvSphere.m_Verts[f.m_VertIds[j]].v());
		}
		glEnd();
	}
}

void EnvImage::ShowTexture(void)
{
	glEnable(GL_TEXTURE_2D);
	m_Tex.BindGL();

	m_TexTrans.SetGLTransform();

	glMatrixMode(GL_MODELVIEW);

	glColor3d(1, 1, 1);
	for(size_t i = 0; i < m_EnvSphere.m_Faces.size(); ++i)
	{
		const lib_geo::BaseFace& f = m_EnvSphere.m_Faces[i];

		glBegin(GL_TRIANGLE_FAN);
		for(size_t j = 0; j < f.m_VertIds.size(); ++j)
		{
			glTexCoord2fv(m_EnvSphere.m_UVs[f.m_UVIds[j]].v());
			glVertex3fv(m_EnvSphere.m_Verts[f.m_VertIds[j]].v());
		}
		glEnd();
	}
}


void EnvImage::BindTexture(void)
{
	m_Tex.BindGL();
}


}
