#include "Cparticle.h"
#include <string.h>

Cparticle::Cparticle(){

	m_pos = Vector3 (0.0,0.0,0.0);
	m_vel = Vector3 (0.0,0.0,0.0);
	m_color[0] = m_color[1] = m_color[2] = 1.0f;
	m_color[3] = .2f;
	m_size=1.0f;
	m_current_time=0;

	m_time_to_life = 10;

	fade_in = true;
	fade_out = false;
	m_fade_vel = 0.4;

	is_dead=false;

}

Cparticle::Cparticle (Cpart_emitter* p_emitter)
{
	m_emitter = p_emitter;
	m_pos = Vector3 (0.0,0.0,0.0);
	m_vel = Vector3 (0.0,0.0,0.0);
	m_color[0] = m_color[1] = m_color[2] = m_color[3] = 1.0f;
	m_size=1.0f;
	m_current_time=0;

	m_time_to_life = 10;

	fade_in = true;
	fade_out = false;
	m_fade_vel = 0.4;



	is_dead=false;
}


void Cparticle::set_particle(Vector3 pos, Vector3 vel, float color[], float size, int time_to_life, float fade_vel)
{
	m_pos = pos;
	m_vel = vel;
	memcpy (m_color, color, sizeof(float)*4);
	m_size = size;
	m_time_to_life = time_to_life;
	m_fade_vel = fade_vel;

}

void Cparticle::update ()
{
	if (fade_in)
	{
		if (m_color[3]>=0.9){ m_color[3]=1.0; fade_in=false;}
		m_color[3] += m_fade_vel;
	}


	if (!is_dead) {
		float time = 0.05;//m_emitter->m_frame_time;

		m_pos = m_pos + m_vel*time;
		m_current_time++;

		if (!fade_out) {if (m_current_time >= m_time_to_life - 1/m_fade_vel) fade_out = true;}

		if (fade_out)
			{
				if (m_color[3]<=0.1){ m_color[3]=0.0;}
				else m_color[3] -= m_fade_vel;
			}

		if (m_current_time >= m_time_to_life)
			is_dead = true;

	}

}
void Cparticle::render ()
{
	
	glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, m_color);

	
	glBegin(GL_TRIANGLE_STRIP); 
		//upper right
		glTexCoord2i(1,1); 
		glVertex3f(m_pos.x+m_size,m_pos.y+m_size,m_pos.z);
		
		// upper left
		glTexCoord2i(0,1);
		glVertex3f(m_pos.x-m_size,m_pos.y+m_size,m_pos.z);
		
		// lower right
		glTexCoord2i(1,0);
		glVertex3f(m_pos.x+m_size,m_pos.y-m_size,m_pos.z);
		
		// lower left
		glTexCoord2i(0,0); 
		glVertex3f(m_pos.x-m_size,m_pos.y-m_size,m_pos.z);
	glEnd();		

}


Cparticle::~Cparticle(void)
{
}
