#ifdef _DEBUG
	#include <stdlib.h>
	#include "../mmgr.h"
#endif

#include <math.h>

#include "Kasvirunko.hpp"
#include "../mathematics.hpp"
#include "../primitives.hpp"

void Runkopala::updateAndDraw(float time)
{

	float from = Mathematics::calcPosFloat(time, this->life, this->life+0.1f);//growTime);
	// 10 kpl
	if(from>0.9f) from = 0.9f;

	Vector v1 = this->pos+Vector(0, 0, 0);
	Vector v2 = this->pos+Vector(20,0, 0);
	Vector v3 = this->pos+Vector(20,8, 0);
	Vector v4 = this->pos+Vector(0, 8, 0);

	glBegin(GL_QUADS);
		glTexCoord2f(0,from);
		//glTexCoord2f(0,0);
		glVertex3fv((float *)&(v1));
		glTexCoord2f(1,from);
		//glTexCoord2f(1,0);
		glVertex3fv((float *)&(v2));
		glTexCoord2f(1,from+0.1f);
		//glTexCoord2f(1,1);
		glVertex3fv((float *)&(v3));
		glTexCoord2f(0,from+0.1f);
		//glTexCoord2f(0,1);
		glVertex3fv((float *)&(v4));
	glEnd();
}


void Kasvirunko::draw()
{
	const float pos = (time - startTime) / (endTime - startTime);
	float alpha = 1.0f;

	const float fadeinstart = 0.0f;
	const float fadeinstop = 0.1f;
	const float fadeoutstart = 0.90f;
	const float fadeoutstop = 1.0f;

	if (pos >= fadeinstart && pos <= fadeinstop)
		alpha *= (pos-fadeinstart) / (fadeinstop-fadeinstart);
	if (pos >= fadeoutstart && pos <= fadeoutstop)
		alpha *= 1-(pos-fadeoutstart) / (fadeoutstop-fadeoutstart);

//    filter.init(true);
	renderScene(pos, alpha);
//    filter.glow(8, 0.005f, 0.005f, 0.92f, -1.0f, 1.0f);
}

void Kasvirunko::renderScene(float pos, float alpha)
{
    Vector cam = Vector(0, 0, -7);
    Vector tgt = Vector(0, 0, 0);
    Vector upw = Vector(0, 1, 0);

    glLoadIdentity();
    gluLookAt(cam.x, cam.y, cam.z, tgt.x, tgt.y, tgt.z, upw.x, upw.y, upw.z);
	
	dmsPerspective2D(800, 600);

	glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_DEPTH_TEST);
    glBindTexture(GL_TEXTURE_2D, dmsGetTexture("pixel_trunk.png")->getID());
    glColor4f(1,1,1, alpha);

	Vector k = Vector(400,300,0)+Vector(sinf(pos*12.0f), cosf(pos*12.0f), 0) * 200.0f;
	Runkopala *t = 0;
	t = new Runkopala();
	t->life = pos;
	t->pos = k;
	trunk->add(t);

	Runkopala *p = 0;
	trunk->goToStart();
	p = (Runkopala *)trunk->getCurrent();
	while(trunk->goForward())
	{
		p->updateAndDraw(pos);
		p = (Runkopala *)trunk->getCurrent();
	}


	dmsPerspective3D();

}




Kasvirunko::Kasvirunko()
{	
}

Kasvirunko::~Kasvirunko()
{
	trunk->destroy();
	delete trunk;
}


bool Kasvirunko::init(unsigned long s, unsigned long e)
{
	trunk = new Lista();

	trunkTex = dmsGetTexture("flower64x64.png");

	startTime = s;
	endTime = e;
	return true;
}

