
#include "game.h"
#include "droidworld.h"


DroidWorld::DroidWorld( float w, float h)
{
    objectList = 0;
    width = w;
    height = h;
}


DroidWorld::~DroidWorld()
{
    releaseAll();
}

void DroidWorld::prepeare()
{
    // Images
    imageBall = loadVGImage("images/planet.png");
    imageAsteroid = loadVGImage("images/asteroid.png");

}

void DroidWorld::release()
{
    if (imageBall!=VG_INVALID_HANDLE) {
        vgDestroyImage(imageBall); imageBall=VG_INVALID_HANDLE;
    }

    if (imageAsteroid!=VG_INVALID_HANDLE) {
        vgDestroyImage(imageAsteroid); imageAsteroid=VG_INVALID_HANDLE;
    }
}

DroidObject* DroidWorld::addObject( DroidObject *toAdd )
{
    SDObjectCapsule *ncap = new SDObjectCapsule;
    ncap->next = objectList;
    ncap->obj = toAdd;
    objectList = ncap;
    return toAdd;
}

void DroidWorld::releaseAll() {
    SDObjectCapsule *l = objectList;
    while (l) {
        SDObjectCapsule *n = l->next;
        if (l->obj) {
            delete l->obj;
            l->obj = 0;
        }
        delete l;
        l = n;
    }
    objectList = 0;
}


void DroidWorld::run( float secsPassed )
{
    float sqDistance;
    QVector3D temp;
    SDObjectCapsule *prev = 0;
    SDObjectCapsule *l = objectList;
    while (l) {
        if (l->obj) {
            if (l->obj->isAlive()) {
                l->obj->run( secsPassed );
                // mass against other object

                SDObjectCapsule *gravl = objectList;
                while (gravl) {
                    if (l!=gravl && gravl->obj && gravl->obj->isAlive()) {         // ignore self, empty and dead.
                        temp = l->obj->getPosition() - gravl->obj->getPosition();
                        sqDistance = QVector3D::dotProduct( temp, temp );

                        temp = temp/(sqDistance+0.1f) * GENERAL_GRAVITY_POWER;

                        l->obj->getDirection() += -temp*gravl->obj->getMass() / l->obj->getMass() * secsPassed;
                        gravl->obj->getDirection() += temp*l->obj->getMass() / gravl->obj->getMass() * secsPassed;
                    }
                    gravl = gravl->next;
                }

            } else {
                // should be dead, . remove the capsule
            }
        }
        prev = l;
        l = l->next;
    }
}


void DroidWorld::draw()
{
    SDObjectCapsule *l = objectList;
    while (l) {
        if (l->obj) {
            if (l->obj->isAlive()) l->obj->draw();
        }
        l = l->next;
    }
}

void DroidWorld::setMyTransform( DroidObject *o ) {
    vgLoadIdentity();
    vgTranslate( width/2, height/2);
    vgRotate( o->getAngle() );

    vgTranslate( o->getPosition().x() * width - o->getDrawSize()/2,
                 o->getPosition().y()*height - o->getDrawSize()/2.0f );





    //vgScale();            // scale here.
}
