#include "Unit.h"
#include "LD.h"



Unit::Unit() :
  Type( LD::GO_INVALID ),
  RemoveMe( false ),
  LifeTime( 0.0f ),
  Color( 0xffffffff ),
  Size( 30 ),
  HP( 1 )
{
}



Unit::~Unit()
{
}



void Unit::Display( IDirect3DDevice8* pDevice )
{
  theApp.RenderTextureSection2d( Position.x, Position.y, theApp.m_TexSec[TexSection], Color );
}



void Unit::UpdateFixedTimeStep( Level& theLevel )
{
}



void Unit::Update( Level& theLevel, float ElapsedTime )
{
  if ( LifeTime > 0.0f )
  {
    LifeTime -= ElapsedTime;
    if ( LifeTime <= 0.0f )
    {
      RemoveMe = true;
    }
  }
}



void Unit::AdjustFractPos( bool BounceOffBorder )
{
  const int borderOffsetSize = 32;

  while ( ( FractPos.x < 0.0f )
  ||      ( FractPos.x >= 1.0f )
  ||      ( FractPos.y < 0.0f )
  ||      ( FractPos.y >= 1.0f ) )
  {
    while ( FractPos.x < 0.0f )
    {
      if ( ( BounceOffBorder )
      &&   ( Position.x == borderOffsetSize ) )
      {
        FractPos.x = 0.0f;
        Speed.x = -Speed.x;
        break;
      }
      --Position.x;
      FractPos.x += 1.0f;
    }
    while ( FractPos.x >= 1.0f )
    {
      if ( ( BounceOffBorder )
      &&   ( Position.x == 1024 - borderOffsetSize ) )
      {
        FractPos.x = 0.0f;
        Speed.x = -Speed.x;
        break;
      }
      ++Position.x;
      FractPos.x -= 1.0f;
    }
    while ( FractPos.y < 0.0f )
    {
      if ( ( BounceOffBorder )
      &&   ( Position.y == borderOffsetSize ) )
      {
        FractPos.y = 0.0f;
        Speed.y = -Speed.y;
        break;
      }
      --Position.y;
      FractPos.y += 1.0f;
    }
    while ( FractPos.y >= 1.0f )
    {
      if ( ( BounceOffBorder )
      &&   ( Position.y == 768 - borderOffsetSize ) )
      {
        FractPos.y = 0.0f;
        Speed.y = -Speed.y;
        break;
      }
      ++Position.y;
      FractPos.y -= 1.0f;
    }
  }
}



LD::Point Unit::TilePos()
{
  LD::Point     pt;

  pt.x = Position.x / 32;
  if ( Position.x < 0 )
  {
    --pt.x;
  }
  pt.y = Position.y / 32;
  if ( Position.y < 0 )
  {
    --pt.y;
  }

  return pt;
}