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

#include <math.h>

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

void Kukinto::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 Kukinto::renderScene(float pos, float alpha)
{
    int i;

    Vector cam = Vector(0, 0, -2);
    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);

    glRotatef(pos*600, 0, 1, 0);


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

    for (i=0;i<pcount;i++)
    {
        float t = Mathematics::calcPosFloat(pos, particles[i]->st, particles[i]->et);
        if (t > 0.0001f && t < 0.99999f)
        {
            float size = t * sinf(fmodf(pos * particles[i]->speed + particles[i]->phase, 1)*3.141592f)*particles[i]->size;
            Vector p = particles[i]->pos * (1-t) + particles[i]->pos2*t;
//            Primitives::drawFlare(&p, size);
        }
        

    }
}

KukintoParticle::KukintoParticle()
{
    this->st = Mathematics::randFloat();
    this->et = this->st + 0.1f + 0.1f*Mathematics::randFloat();
    this->pos = Mathematics::randVectSphere() * Mathematics::randFloat();
    this->pos2 = this->pos + Mathematics::randVectSphere() * powf(Mathematics::randFloat(), 0.4f)*2.2f;
    this->phase = Mathematics::randFloat();
    this->speed = 15 + 30*Mathematics::randFloat();
    this->size = 0.02f + 0.03f*Mathematics::randFloat();
}


Kukinto::Kukinto()
{	
    int i;
    pcount = 3000;
    particles = new KukintoParticle*[pcount];

    srand(15691);
    for (i=0;i<pcount;i++)
    {
        particles[i] = new KukintoParticle();
    }
}

Kukinto::~Kukinto()
{

}


bool Kukinto::init(unsigned long s, unsigned long e)
{
	startTime = s;
	endTime = e;
	return true;
}

