#include "Planet.h"


Planet::Planet( )
{
	m_Life		= false;
	m_fRadius	= 1.0f;
	m_fP		= 60.0f;
	m_vPosition	= GL3DVector(0,0,0);
	m_fSpeed	= 1.0f;
}

Planet::~Planet( )
{

}

bool Planet::SetTexture( char* chTextureName )
{
	AUX_RGBImageRec* pImage = NULL;
	FILE* hFile = NULL;
	if( !chTextureName ) return NULL;
	hFile = fopen(chTextureName, "r");

	if(hFile)
	{
		fclose(hFile);
		pImage = auxDIBImageLoad(chTextureName);
	}

	glGenTextures(1,&m_nTextureNum);

	glBindTexture(GL_TEXTURE_2D, m_nTextureNum);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glTexImage2D(GL_TEXTURE_2D, 0, 3, pImage->sizeX, pImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE,pImage->data);

	if(pImage)
	{
		if(pImage->data) delete pImage->data;
		delete pImage;
	}
	
	// Texture사용을 가능하게 렌더상태 설정
	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	return true;
}

void Planet::Update(  )
{
	m_vPosition.z += m_fSpeed;
}

void Planet::Render( )
{
	int i,j;
	const float PI     = 3.14159265358979f;
	const float TWOPI  = 6.28318530717958f;
	const float PIDIV2 = 1.57079632679489f;
	float theta1,theta2,theta3 = 0.0f;
	float ex,ey,ez = 0.0f;
	float px,py,pz = 0.0f;

	if(m_fRadius < 0)
		m_fRadius = -m_fRadius;
	if(m_fP <0)
		m_fP = -m_fP;
	if( m_fP < 4 || m_fRadius <= 0 ) 
	{
		glBegin( GL_POINTS );
		glVertex3f( m_vPosition.x, m_vPosition.y, m_vPosition.z );
		glEnd();
		return;
	}
	for(i = 0; i < m_fP/2; ++i )
	{
		theta1 = i * TWOPI / m_fP - PIDIV2;
		theta2 = (i + 1) * TWOPI / m_fP - PIDIV2;
		glBindTexture(GL_TEXTURE_2D, m_nTextureNum);
		glBegin(GL_TRIANGLE_STRIP); 
		{
			for(j = 0; j <= m_fP; ++j )
			{
				theta3 = j * TWOPI / m_fP;

				ex = cos(theta2) * cos(theta3);
				ey = sin(theta2);
				ez = cos(theta2) * sin(theta3);
				px = m_vPosition.x + m_fRadius * ex;
				py = m_vPosition.y + m_fRadius * ey;
				pz = m_vPosition.z + m_fRadius * ez;

				glNormal3f( ex, ey, ez );
				glTexCoord2f( -(j/(float)m_fP) , 2*(i+1)/(float)m_fP );
				glVertex3f( px, py, pz );

				ex = cos(theta1) * cos(theta3);
				ey = sin(theta1);
				ez = cos(theta1) * sin(theta3);
				px = m_vPosition.x + m_fRadius * ex;
				py = m_vPosition.y + m_fRadius * ey;
				pz = m_vPosition.z + m_fRadius * ez;

				glNormal3f( ex, ey, ez );
				glTexCoord2f( -(j/(float)m_fP), 2*i/(float)m_fP );
				glVertex3f( px, py, pz );
			}
		}
		glEnd();
	}
	
}