#include "GunBullet.h"

CGunBullet::CGunBullet()
{
      sVector scale;
      scale.x = 0.5;
      scale.y = 0.5;
      scale.z = 0.5;
      
      mesh.LoadObjFile("./models/Bullet.obj");
      mesh.setSmoothRender(true);
      mesh.setScale(scale);
}

CGunBullet::~CGunBullet()
{
}

void CGunBullet::Render()
{
     int numBullets = bulletList.GetNumItems();
     
     for(int i = 0; i < numBullets; i++)
     {
             sBullet *bullet = (sBullet *)bulletList.GetItem(i);
     
             mesh.setPos(bullet->pos);
             mesh.Render();
     }
}

void CGunBullet::update()
{
     bulletTimer--;
     
     if(bulletTimer < 0)
                    bulletTimer = 0;
     
     int numBullets = bulletList.GetNumItems();
     
     for(int i = 0; i < numBullets; i++)
     {
             sBullet *bullet = (sBullet *)bulletList.GetItem(i);
             bullet->pos.x += bullet->direction.x * 10;
             bullet->pos.y -= bullet->direction.y * 10;
             bullet->pos.z += bullet->direction.z * 10;        
             
             if(bullet->pos.z > 4000 || bullet->pos.y < 0)
             {
                      delete bullet;
                      bulletList.DeleteItem(i);
                      numBullets = bulletList.GetNumItems();
                      i--;
             }
     }     
}

bool CGunBullet::hitTest(sVector pos)
{
     int numBullets = bulletList.GetNumItems();
     
     for(int i = 0; i < numBullets; i++)
     {
             sBullet *bullet = (sBullet *)bulletList.GetItem(i);
             
             sVector distance = pos.Difference(&bullet->pos);
             if(distance.x < 0)
                distance.x = -distance.x;
             if(distance.y < 0)
                distance.y = -distance.y;
             if(distance.z < 0)
                distance.z = -distance.z;
             
             if(distance.x < 50)
                if(distance.y < 50)
                   if(distance.z < 50)
                       return true;
     }
     
     return false;
}

void CGunBullet::loadSound()
{
     this->sound = FSOUND_Sample_Load(10, "./sound/shot.wav", FSOUND_NORMAL, 0, 0); 


}

void CGunBullet::addBullet(sVector pos, sVector direction)
{
     if(bulletList.GetNumItems() > 40)
       return;
     if(bulletTimer > 0)
       return;
      
     sBullet *bullet = new sBullet();
     if(bullet == NULL)
      return;
      
     bullet->pos = pos;
     bullet->direction = direction;
     
     bulletList.AppendItem(bullet);
     
     bulletTimer = 10;
     FSOUND_PlaySound(30, sound);
}
