// Notes:
// - respawning vehicles with turrets (bomber/tank) will not setup the turret properly

//Damage Rate for entering Liquid
$VehicleDamageLava       = 0.0325;
$VehicleDamageHotLava    = 0.035;
$VehicleDamageCrustyLava = 0.03;

$NumVehiclesDeploy = 0;

//**************************************************************
//* GENERAL PURPOSE FUNCTIONS
//**************************************************************
function VehicleData::setInvincible(%data, %Vehicle, %OnOff)
{
   %Vehicle.invulnerable = %OnOff;
}

function VehicleData::onAdd(%data, %obj)
{
   Parent::onAdd(%data, %obj);
   if((%data.sensorData !$= "") && (%obj.getTarget() != -1))
      setTargetSensorData(%obj.getTarget(), %data.sensorData);
   %obj.setRechargeRate(%data.rechargeRate);
   // set full energy
   %obj.setEnergyLevel(%data.MaxEnergy);

   if(%obj.disableMove)
      %obj.immobilized = true;

   if(%obj.deployed)
   {
      if($countDownStarted)
         %data.schedule(($Host::WarmupTime * 1000) / 2, "vehicleDeploy", %obj, 0, 1);
      else
      {
         $VehiclesDeploy[$NumVehiclesDeploy] = %obj;
         $NumVehiclesDeploy++;
      }
   }
   if(%obj.mountable || %obj.mountable $= "")
      %data.isMountable(%obj, true);
   else
      %data.isMountable(%obj, false);
   
   %obj.setSelfPowered();
//   %data.canObserve = true;
}

function VehicleData::onRemove(%this, %obj)
{
   // if there are passengers/driver, kick them out
   %this.deleteAllMounted(%obj);
   for(%i = 0; %i < %obj.getDatablock().numMountPoints; %i++)
      if (%obj.getMountNodeObject(%i)) {
         %passenger = %obj.getMountNodeObject(%i);
         %passenger.unmount();
      }
   vehicleListRemove(%obj.getDataBlock(), %obj);
   if(%obj.lastPilot.lastVehicle == %obj)
      %obj.lastPilot.lastVehicle = "";      

   Parent::onRemove(%this, %obj);
}

function VehicleData::onDamage(%this,%obj)
{
   %damage = %obj.getDamageLevel();
   if (%damage >= %this.destroyedLevel)
   {
      if(%obj.getDamageState() !$= "Destroyed")
      {
         if(%obj.respawnTime !$= "")
            %obj.marker.schedule = %obj.marker.data.schedule(%obj.respawnTime, "respawn", %obj.marker); 
         %obj.setDamageState(Destroyed);
      }
   }
   else
   {
      if(%obj.getDamageState() !$= "Enabled")
         %obj.setDamageState(Enabled);
   }
} 

function VehicleData::playerDismounted(%data, %obj, %player)
{
	//this function is declared to prevent console error msg spam...
}

function HoverVehicle::useCreateHeight()
{
	//this function is declared to prevent console error msg spam...
}

function WheeledVehicle::useCreateHeight()
{
	//this function is declared to prevent console error msg spam...
}

function AssaultVehicle::onDamage(%this, %obj)
{
   (%obj.getMountNodeObject(10)).setDamagelevel(%obj.getDamageLevel());
   Parent::onDamage(%this, %obj);
}

function BomberFlyer::onDamage(%this, %obj)
{
   (%obj.getMountNodeObject(10)).setDamagelevel(%obj.getDamageLevel());
   Parent::onDamage(%this, %obj);
}

function MobileBaseVehicle::onDamage(%this, %obj)
{
   if(isObject(%obj.getMountNodeObject(1)))
      (%obj.getMountNodeObject(1)).setDamagelevel(%obj.getDamageLevel());
   Parent::onDamage(%this, %obj);
}


function VehicleData::onEnterLiquid(%Data, %Vehicle, %Coverage, %Type)
{
   // If entering the liquid too quickly, then do damage based on that
   %Velocity = %Vehicle.getVelocity();
   %Speed = VectorLen(%Velocity);

   if (%Speed > $SafeEnterWaterSpeed)
   {
      %DamageScale = %Data.speedDamageScale;
      %DamageAmount = (%Speed - $SafeEnterWaterSpeed) * %DamageScale;

      if (%Type >= 4 && %Type <= 6)
         %Data.damageObject(%Vehicle, 0, %Position, %DamageAmount, $DamageType::Lava, %Velocity);
      else
         %Data.damageObject(%Vehicle, 0, %Position, %DamageAmount, $DamageType::Water, %Velocity);
   }

   switch(%Type)
   {
      case 0:
         //Water

      case 1:
         //Ocean Water

      case 2:
         //River Water

      case 3:
         //Stagnant Water

      case 4:
         //Lava
         %Vehicle.liquidDamage(%Data, $VehicleDamageLava, $DamageType::Lava);

      case 5:
         //Hot Lava
         %Vehicle.liquidDamage(%Data, $VehicleDamageHotLava, $DamageType::Lava);

      case 6:    
         //Crusty Lava
         %Vehicle.liquidDamage(%Data, $VehicleDamageCrustyLava, $DamageType::Lava);

      case 7:
         //Quick Sand
   }

   %Vehicle.setHeat(0.0);
   %Vehicle.InWater = true;

   // Allow the OnEnter Liquid to play out for the passengers as well.
   %i = 0;
   %MountPoints = %Data.numMountPoints;

   while (%i < %MountPoints)
   {
      %Passenger = %Vehicle.getMountNodeObject(%i);
      if (%Passenger > 0)
         %Passenger.getDataBlock().onEnterLiquid(%Passenger, %Type); 

      %i++;      
   }
}

function VehicleData::onLeaveLiquid(%Data, %Vehicle, %Type)
{
   // Set the heat back to 1 and mark the vehicle as no longer in the water
   %Vehicle.setHeat(1.0);
   %Vehicle.InWater = false;

   // If taking damage because of lava, stop it now
   if(%Vehicle.lDamageSchedule !$= "")
   {
      cancel(%Vehicle.lDamageSchedule);
      %Vehicle.lDamageSchedule = "";
   }

   // Allow the OnEnter Liquid to play out for the passengers as well.
   %i = 0;
   %MountPoints = %Data.numMountPoints;

   while (%i < %MountPoints)
   {
      %Passenger = %Vehicle.getMountNodeObject(%i);
      if (%Passenger > 0)
         %Passenger.getDataBlock().onLeaveLiquid(%Passenger, %Type); 

      %i++;      
   }
}

function FlyingVehicle::liquidDamage(%obj, %data, %damageAmount, %damageType)
{
   if(%obj.getDamageState() !$= "Destroyed")
   {
      %data.damageObject(%obj, 0, "0 0 0", %damageAmount, %damageType); 
      %obj.lDamageSchedule = %obj.schedule(50, "liquidDamage", %data, %damageAmount, %damageType);
      passengerLiquidDamage(%obj, %damageAmount, %damageType);
   }
   else
      %obj.lDamageSchedule = "";
}

function WheeledVehicle::liquidDamage(%obj, %data, %damageAmount, %damageType)
{
   if(%obj.getDamageState() !$= "Destroyed")
   {
      %data.damageObject(%obj, 0, "0 0 0", %damageAmount, %damageType); 
      %obj.lDamageSchedule = %obj.schedule(50, "liquidDamage", %data, %damageAmount, %damageType);
      passengerLiquidDamage(%obj, %damageAmount, %damageType);
   }
   else
      %obj.lDamageSchedule = "";
}

function HoverVehicle::liquidDamage(%obj, %data, %damageAmount, %damageType)
{
   if(%obj.getDamageState() !$= "Destroyed")
   {
      %data.damageObject(%obj, 0, "0 0 0", %damageAmount, %damageType); 
      %obj.lDamageSchedule = %obj.schedule(50, "liquidDamage", %data, %damageAmount, %damageType);
      passengerLiquidDamage(%obj, %damageAmount, %damageType);
   }
   else
      %obj.lDamageSchedule = "";
}

function VehicleData::onDestroyed(%Data, %Vehicle, %prevState)
{
   // If someone is in the turret, eject them.
   if(%Vehicle.turretObject && %Vehicle.turretObject.getControllingClient())
      %Vehicle.turretObject.getDataBlock().playerDismount(%Vehicle.turretObject);

   %Position = %Vehicle.getWorldBoxCenter();
   %MountPoints = %Vehicle.getDatablock().numMountPoints;

   // Eject everyone else on board
   %i = 0;
   while (%i < %MountPoints)
   {
      if (%Vehicle.getMountNodeObject(%i) > 0)
      {
         // Get the player out of the Vehicle
         %Player = %Vehicle.getMountNodeObject(%i);
         %Player.getDataBlock().doDismount(%Player, true);
         %PlayerPosition = posFromTransform(%Player.getTransform());

         // Determine a random vector for them to thrown
         %xVelocity = 250.0 - (getRandom() * 500.0);
         %yVelocity = 250.0 - (getRandom() * 500.0);
         %zVelocity = (getRandom() * 150.0) + 50.0;
         %Velocity = %xVelocity @ " " @ %yVelocity @ " " @ %zVelocity;
         %Flingee.applyImpulse(%PlayerPosition, %Velocity);
      }
      %i++;
   }

   // If there is a marked location, delete it
   if (%Vehicle.beacon)
   {
      %Vehicle.beacon.delete();
      %Vehicle.beacon = "";
   }   

   // Damage everything around the vehicle
   %Radius = %Data.explosionRadius;
   %Damage = %Data.explosionDamage;
   %Impulse = %Data.explosionForce;
   %DamageType = $DamageType::Explosion;

   RadiusExplosion(%Vehicle, %Position, %Radius, %Damage, %Impulse, 0, %DamageType);

   %Vehicle.schedule(600, delete);

   MakeVehicleDebris(%Position, %Data.debrisBase, %Data.debrisVariance, %Data.debrisEjectionScale);
}

datablock GrenadeProjectileData(DebrisProjectile)
{
   projectileShapeName = "debris_generic.dts";

   emitterDelay        = -1;
   directDamage        = 0.25;
   hasDamageRadius     = true;

   indirectDamage      = 0.40;
   damageRadius        = 12.0;
   radiusDamageType    = $DamageType::Explosion;
   kickBackStrength    = 1100;
   bubbleEmitTime      = 1.0;

   explosion           = "GrenadeExplosion";
   underwaterExplosion = "UnderwaterGrenadeExplosion";
   velInheritFactor    = 0.7;
   splash              = GrenadeSplash;

   baseEmitter         = "DebrisRainEmitter";
   bubbleEmitter       = GrenadeBubbleEmitter;

   grenadeElasticity = 0.35;
   grenadeFriction   = 0.2;

   armingDelayMS     = 250;

   muzzleVelocity    = 10.00;
   drag = 0.1;

   rearDamageFactor    = 1.2;
};

function MakeVehicleDebris(%Position, %DebrisBase, %DebrisVariance, %Scale)
{
   %i = 0;
   %Count = getRandom() * %DebrisVariance + %DebrisBase;

   while (%i < %Count)
   {
      %Random = getRandom();
      %x = 1 - %Random * 2;
      %Random = getRandom();
      %y = 1 - %Random * 2;
      %Random = getRandom();
      %Z = 1 - %Random * 1.5;

      %Vector = VectorScale(%X @ " " @ %y @ " " @ %z, %Scale);

      %Projectile = new GrenadeProjectile()
      {
         dataBlock        = DebrisProjectile;
         initialDirection = %Vector;
         initialPosition  = %Position;
      };
      MissionCleanUp.Add(%Projectile);

      %i++;
   }
}

function VehicleData::deleteAllMounted()
{

}

//**************************************************************
//* VEHICLE CREATION
//**************************************************************
// (NOTE: No entry for Wildcat Grav Cycle is here. -- DG)

//----------------------------
// THUNDERSWORD BOMBER
//----------------------------

function BomberFlyer::onAdd(%this, %Vehicle)
{
   Parent::onAdd(%this, %Vehicle);
  
   %turret = TurretData::create(BomberTurret);
   MissionCleanup.add(%turret);

   %turret.team = %Vehicle.teamBought;
   %turret.selectedWeapon = 1;
   %turret.setSelfPowered();

   %Vehicle.mountObject(%turret, 10);

   %turret.mountImage(BomberTurretBarrel,2);
   %turret.mountImage(BomberTurretBarrelPair,3);
//   %turret.mountImage(BomberBombImage, 4);
   %turret.mountImage(BomberTargetingImage, 6);
   %vehicle.turretObject = %turret;

   %turret.vehicleMounted = %Vehicle;
   %turret.vehicle = %Vehicle;
   
   //vehicle turrets should not auto fire at targets
   %turret.setAutoFire(false);

   //for this particular weapon - a non-firing datablock used only so the AI can aim the turret
   //Also needed so we can set the turret parameters..
   %turret.mountImage(AIAimingTurretBarrel, 0);

   // setup the turret's target info
   setTargetSensorGroup(%turret.getTarget(), %turret.team);
   setTargetNeverVisMask(%turret.getTarget(), 0xffffffff);
}

//----------------------------
// HAVOC TRANSPORT FLIER
//----------------------------

function HAPCFlyer::onAdd(%this, %obj)
{
   Parent::onAdd(%this, %obj);
   %obj.schedule(6000, "playThread", $ActivateThread, "activate");
}

//----------------------------
// BEOWULF ASSAULT VEHICLE
//----------------------------
function AssaultVehicle::onAdd(%this, %Vehicle)
{
   Parent::onAdd(%this, %Vehicle);

   %Team = %Vehicle.team;

   // Make the turret    
   %Turret = TurretData::create(AssaultTurret);
   MissionCleanup.add(%Turret);
   %Turret.team = %Team;
   %Turret.setSelfPowered();
   %Turret.setAutoFire(false);
   %Turret.Vehicle = %Vehicle;
   %Turret.selectedWeapon = 1;

   // Attach the Turret to the Vehicle
   %Vehicle.TurretObject = %Turret;
   %Vehicle.mountObject(%Turret, 10);

   // Add the weapons to the turret, there are 2 code controlled turrets
   %Turret.mountImage(AssaultChaingunTurretBarrel, 2);
   %Turret.mountImage(AssaultChaingunImage, 3);
   %Turret.mountImage(AssaultCannonTurretBarrel, 4);
   %Turret.mountImage(AssaultTurretParam, 0);

   // Start the deploying once the vehicle pad field clears
   %Vehicle.schedule(6000, "playThread", $ActivateThread, "activate");

   // set the turret's target info
   setTargetSensorGroup(%Turret.getTarget(), %Turret.team);
   setTargetNeverVisMask(%Turret.getTarget(), 0xffffffff);
}

//**************************************************************
//* MULTI-CREW VEHICLE DELETION
//**************************************************************

//----------------------------
//BEOWULF ASSAULT VEHICLE
//----------------------------

function AssaultVehicle::deleteAllMounted(%data, %obj)
{
   %turret = %obj.getMountNodeObject(10);
   if(!%turret)
      return;

   if(%client = %turret.getControllingClient())
   {
      %client.player.setControlObject(%client.player);
      %client.player.mountImage(%client.player.lastWeapon, $WeaponSlot);   
      %client.player.mountVehicle = false;
   }
   %turret.delete();
}

//----------------------------
// THUNDERSWORD BOMBER
//----------------------------

function BomberFlyer::deleteAllMounted(%data, %obj)
{
   if(%obj.beacon)
      %obj.beacon.delete();

   %turret = %obj.getMountNodeObject(10);
   if(!%turret)
      return;

   %turret.altTrigger = 0;
   %turret.fireTrigger = 0;
   
   if(%client = %turret.getControllingClient())
   {
      commandToClient(%client, 'endBomberSight');
      %client.player.setControlObject(%client.player);
      %client.player.mountImage(%client.player.lastWeapon, $WeaponSlot);
      %client.player.mountVehicle = false;

      %client.player.bomber = false;
   }
   %turret.delete();
}

//----------------------------
// JERICHO FORWARD BASE
//----------------------------

function MobileBaseVehicle::deleteAllMounted(%data, %obj)
{
   if(%obj.station !$= "")
   {
      %obj.station.getDataBlock().onLosePowerDisabled(%obj.station);
      %obj.unmountObject(%obj.station);
      %obj.station.trigger.delete();
      %obj.station.delete();
   }
   if(%obj.turret !$= "")
   {
      %obj.turret.getDataBlock().onLosePowerDisabled(%obj.turret);
      %obj.unmountObject(%obj.turret);
      %obj.turret.delete();
   }
   if(isObject(%obj.shield))
      %obj.shield.delete();
                            
   if (isObject(%obj.teleporter))
   {
      %obj.teleporter.setThreadDir($ActivateThread, FALSE);
      %obj.teleporter.playThread($ActivateThread,"activate");	
      %obj.teleporter.playAudio($ActivateSound, StationTeleportDeacitvateSound);
   }
   if(isObject(%obj.beacon))
   {
      %obj.beacon.delete();   	
   }
}

function NotifyPassengers(%Data, %Vehicle)
{
   // build a space-separated string representing passengers for those with and without
   // the Havoc Client download
   %PassengerString = buildPassengerString(%Vehicle);
   %HavocPassengerString = HavocBuildPassengerString(%Vehicle);

   // send the string of passengers to all mounted players
   %i = 0;
   %MountPoints = %Data.numMountPoints;

   while (%i < %MountPoints)
   {
      %Passenger = %Vehicle.getMountNodeObject(%i);

      if (%Passenger > 0)
      {
         %Client = %Passenger.client;
         if (%Client.HavocClient == true)
         {
            commandToClient(%Passenger.client, 'checkPassengers', %HavocPassengerString);
         } else {
            commandToClient(%Passenger.client, 'checkPassengers', %PassengerString);
         }
      }

      %i++;
   }
}

// ----------------------------------------------------------------------------------------
// Bomber
// ----------------------------------------------------------------------------------------

function BomberFlyer::playerMounted(%Data, %Vehicle, %Player, %MountPoint)
{
   switch (%MountPoint)
   {
      case 0 :
         // pilot position
         %Player.setPilot(true);

         // Take the players weapon and record what the weapon was
         %Player.lastWeapon = %Player.getMountedImage($WeaponSlot);
         %Player.unmountImage($WeaponSlot);

	 commandToClient(%Player.client, 'setHudMode', 'Pilot', "Bomber", %MountPoint);

      case 1 :
         // bombardier position
         %Turret = %Vehicle.getMountNodeObject(10);
         %Player.vehicleTurret = %Turret;
         %Player.setTransform("0 0 0 0 0 1 0");

         if (%Player.client.isAIControlled() == false)
         {
            %Player.setControlObject(%turret);
            %Player.client.setObjectActiveImage(%turret, 2);
         }

         // Take the players weapon and record what the weapon was
         %Player.lastWeapon = %Player.getMountedImage($WeaponSlot);
         %Player.unmountImage($WeaponSlot);

         commandToClient(%Player.client, 'startBomberSight');
         %Turret.bomber = %Player;
         $bWeaponActive = 0;
         %Vehicle.getMountNodeObject(10).selectedWeapon = 1;

         commandToClient(%Player.client,'SetWeaponryVehicleKeys', true, true);
         commandToClient(%Player.client, 'setHudMode', 'Pilot', "Bomber", %MountPoint);

      case 2 :
         // tail gunner position     
         commandToClient(%Player.client, 'setHudMode', 'Passenger', "Bomber", %MountPoint);

   }

   NotifyPassengers(%Data, %Vehicle);
}

//----------------------------
// HAVOC TRANSPORT FLIER
//----------------------------

function HAPCFlyer::playerMounted(%Data, %Vehicle, %Player, %MountPoint)
{
   if (%MountPoint == 0)
   {
      // pilot position
      %Player.setPilot(true);

      // Take the players weapon and record what the weapon was
      %Player.lastWeapon = %Player.getMountedImage($WeaponSlot);
      %Player.unmountImage($WeaponSlot);

      commandToClient(%Player.client, 'setHudMode', 'Pilot', "HAPC", %MountPoint);
   } else {

      commandToClient(%Player.client, 'setHudMode', 'Passenger', "HAPC", %MountPoint);
   }

   NotifyPassengers(%Data, %Vehicle);
}

//----------------------------
// WILDCAT GRAV CYCLE
//----------------------------

function ScoutVehicle::playerMounted(%data, %obj, %player, %node)
{
   // scout vehicle == SUV (single-user vehicle)
   commandToClient(%player.client, 'setHudMode', 'Pilot', "Hoverbike", %node);
}

//----------------------------
// BEOWULF ASSAULT VEHICLE
//----------------------------

// ----------------------------------------------------------------------------------------
// Tank
// ----------------------------------------------------------------------------------------
function AssaultVehicle::playerMounted(%Data, %Vehicle, %Player, %MountPoint)
{
   // Take the players weapon and record what the weapon was
   %Player.lastWeapon = %Player.getMountedImage($WeaponSlot);
   %Player.unmountImage($WeaponSlot);

   if (%MountPoint == 0)
   {
      // driver position
      %Player.setPilot(true);

      commandToClient(%Player.client, 'setHudMode', 'Pilot', "Assault", %MountPoint);

      // If waiting to deploy, then stop.
      if (%Vehicle.deploySchedule !$= "")
      {
         cancel(%Vehicle.deploySchedule);
         %Vehicle.deploySchedule = "";
      }

      %Vehicle.setFrozenState(false);

      // If Vehicle is deployed completely we raise it back up.
      if (%Vehicle.deployed == true)
      {
         %Vehicle.playAudio($DeploySound, CameraGrenadeAttachSound);
         %Data.schedule(750, RaiseTank, %Vehicle);
      }

   } else {
      // Turreteer position
      %Turret = %Vehicle.getMountNodeObject(10);
      %Player.vehicleTurret = %Turret;   
      %Player.setTransform("0 0 0 0 0 1 0");

      if (%Player.client.isAIControlled() == false)
      {
         %Player.setControlObject(%Turret);
         %Player.client.setObjectActiveImage(%Turret, 2);
      }

      %Turret.turreteer = %Player;
      $aWeaponActive = 0;

      commandToClient(%Player.client,'SetWeaponryVehicleKeys', true);
      %Vehicle.getMountNodeObject(10).selectedWeapon = 1;
      commandToClient(%Player.client, 'setHudMode', 'Pilot', "Assault", %MountPoint);

   }

   NotifyPassengers(%Data, %Vehicle);
}

// This loops through and builds a string of 0,1 for each mountpoint on a vehicle
function buildPassengerString(%Vehicle)
{
   %PassengerString = "";
   %MountPoints = %Vehicle.getDatablock().numMountPoints;
   %i = 0;

   while (%i < %MountPoints)
   {
      %Object = %Vehicle.getMountNodeObject(%i);

      if(%Object > 0)
         %PassengerString = %PassengerString @ "1 ";
      else
         %PassengerString = %PassengerString @ "0 ";

      %i++;
   }

   return(%PassengerString);

}

// This loops through and builds a string of Player Names for each mountpoint on a vehicle
function HavocbuildPassengerString(%Vehicle)
{
   %MountPoints = %Vehicle.getDatablock().numMountPoints;
   %i = 0;

   %PassengerString = %MountPoints @ " ";

   while (%i < %MountPoints)
   {
      %Object = %Vehicle.getMountNodeObject(%i);

      if(%Object > 0)
      {
         if (%Object.team == %Vehicle.team)
            %PassengerString = %PassengerString @ "1 ";
         else
            %PassengerString = %PassengerString @ "2 ";
         %Client = %Object.client;
         %PassengerString = %PassengerString @ (%Client.NameBase) @ " ";
      } else {
         %PassengerString = %PassengerString @ "0 0 ";
      }
 
      %i++;
   }

   return(%PassengerString);
}

function MobileBaseVehicle::playerDismounted(%data, %obj, %player)
{
   %obj.schedule(500, "deployVehicle", %data, %player);
}

function WheeledVehicle::deployVehicle(%obj, %data, %player)
{
   if (!%data.vehicleDeploy(%obj, %player))
      %obj.schedule(500, "deployVehicle", %data, %player);
}

//**************************************************************
//* JERICHO DEPLOYMENT and UNDEPLOYMENT
//**************************************************************

function MobileBaseVehicle::onEndSequence(%data, %obj, %thread)
{
   if(%thread == $DeployThread && !%obj.deployed)
   {
      %obj.unmountObject(%obj.station);
      %obj.station.trigger.delete();
      %obj.station.delete();
      %obj.station = "";

	  %obj.beacon.delete();
      
      %obj.unmountObject(%obj.turret);
      %obj.turret.delete();
      %obj.turret = "";

      if(!%obj.immobilized)
      {
         %obj.disableMove = false;
         %obj.setFrozenState(false);
      }
      setTargetSensorData(%obj.getTarget(), %data.sensorData);
   }
   else
   {
      %obj.station.startFade(0,0,false);
      %obj.station.setThreadDir($DeployThread, true);
      %obj.station.playThread($DeployThread,"deploy");
      %obj.station.playAudio($DeploySound, MobileBaseStationDeploySound);
      %obj.station.goingOut = true;  
      %obj.shield.setTransform(%obj.getSlotTransform(3));            
      %obj.shield.close();
      %obj.isDeployed = true;
      %obj.noEnemyControl = 1;
   }
      
   Parent::onEndSequence(%data, %obj, %thread);
}

function MobileInvStation::onEndSequence(%data, %obj, %thread)
{
   if(!%obj.goingOut)
      %obj.startFade(0,0,true);
   else
   {
      %obj.notDeployed = 0;
      %obj.vehicle.fullyDeployed = 1;
      %obj.vehicle.teleporter.setThreadDir($ActivateThread, TRUE);
      %obj.vehicle.teleporter.playThread($ActivateThread,"activate");	
      %obj.vehicle.teleporter.playAudio($ActivateSound, StationTeleportAcitvateSound);
   }
   Parent::onEndSequence(%data, %obj, %thread);
}

                                                   
function MobileBaseVehicle::checkDeploy(%data, %obj)
{
   %mask = $TypeMasks::VehicleObjectType | $TypeMasks::MoveableObjectType |
           $TypeMasks::StaticShapeObjectType | $TypeMasks::ForceFieldObjectType |
           $TypeMasks::ItemObjectType | $TypeMasks::PlayerObjectType | 
           $TypeMasks::TurretObjectType | //$TypeMasks::StaticTSObjectType | 
           $TypeMasks::InteriorObjectType;

   //%slot 1 = turret   %slot 2 = station
   %height[1] = 0;
   %height[2] = 0;
   %radius[1] = 2.4;
   %radius[2] = 2.4;
   %stationFailed = false;
   %turretFailed = false;
   
   for(%x = 1; %x < 3; %x++)
   {
      %posXY = getWords(%obj.getSlotTransform(%x), 0, 1);
      %posZ = (getWord(%obj.getSlotTransform(%x), 2) + %height[%x]);
      InitContainerRadiusSearch(%posXY @ " " @ %posZ, %radius[%x], %mask); 
   
      while ((%objFound = ContainerSearchNext()) != 0)
      {
         if(%objFound != %obj)
         {   
            if(%x == 1)
               %turretFailed = true;   
            else
               %stationFailed = true;   
            break;
         }
      }
   }
   
   //If turret, station or both fail the send back the error message...
   if(%turretFailed &&  %stationFailed)
      return "Both Turret and Station are blocked and unable to deploy.";
   if(%turretFailed)
      return "Turret is blocked and unable to deploy.";
   if(%stationFailed)
      return "Station is blocked and unable to deploy.";

   //Check the station for collision with the Terrain
   %mat = %obj.getTransform();
   for(%x = 1; %x < 7; %x+=2)
   {
      %startPos = MatrixMulPoint(%mat, %data.stationPoints[%x]);
      %endPos = MatrixMulPoint(%mat, %data.stationPoints[%x+1]);

      %rayCastObj = containerRayCast(%startPos, %endPos, $TypeMasks::TerrainObjectType, 0);
      if(%rayCastObj)
         return "Station is blocked by terrain and unable to deploy.";      
   }
   
   return "";   
}
function MobileBaseVehicle::checkTurretDistance(%data, %obj)
{
   %pos = getWords(%obj.getTransform(), 0, 2);
   InitContainerRadiusSearch(%pos, 40, $TypeMasks::TurretObjectType | $TypeMasks::InteriorObjectType);
   while ((%objFound = ContainerSearchNext()) != 0)
   {
      if(%objFound.getType() & $TypeMasks::TurretObjectType)
      {
         if(%objFound.getDataBlock().ClassName $= "TurretBase")
            return "Turret Base is in the area. Unable to deploy.";
      }
      else
      {
         %subStr = getSubStr(%objFound.interiorFile, 1, 4);
         if(%subStr !$= "rock" && %subStr !$= "spir" && %subStr !$= "misc")
            return "Obstruction in the area; unable to deploy.";
      }        
   }
   return "";
}


//**************************************************************
//* VEHICLE INVENTORY MANAGEMENT
//**************************************************************

//--------------------------------------------------------------
// NUMBER OF PURCHASEABLE VEHICLES PER TEAM
//--------------------------------------------------------------

function vehicleListRemove(%data, %obj)
{
   %blockName = %data.getName();
   for($i = 0; %i < $VehicleMax[%blockName]; %i++)
      if($VehicleInField[%obj.team, %blockName, %i] == %obj)
      {
         $VehicleInField[%obj.team, %blockName, %i] = 0;
         $VehicleTotalCount[%obj.team, %blockName]--;   
         break;
      }   
}

function vehicleListAdd(%blockName, %obj)
{
   for($i = 0; %i < $VehicleMax[%blockName]; %i++)
   {
      if($VehicleInField[%obj.team, %blockName, %i] $= "" || $VehicleInField[%obj.team, %blockName, %i] == 0)
      {
         $VehicleInField[%obj.team, %blockName, %i] = %obj;
         $VehicleTotalCount[%obj.team, %blockName]++;   
         break;
      }      
   }
}

function clearVehicleCount(%team)
{
   $VehicleTotalCount[%team, ScoutVehicle]      = 0;
   $VehicleTotalCount[%team, AssaultVehicle]    = 0;
   $VehicleTotalCount[%team, MobileBaseVehicle] = 0;
   $VehicleTotalCount[%team, ScoutFlyer]        = 0;
   $VehicleTotalCount[%team, BomberFlyer]       = 0;
   $VehicleTotalCount[%team, HAPCFlyer]         = 0;
}

//**************************************************************
//* VEHICLE HUD SEAT INDICATOR LIGHTS
//**************************************************************

function findAIEmptySeat(%vehicle, %player)
{
   %dataBlock = %vehicle.getDataBlock();
	if (%dataBlock.getName() $= "BomberFlyer")
		%num = 2;
	else
		%num = 1;
	%node = -1;
	for(%i = %num; %i < %dataBlock.numMountPoints; %i++)
	{
	   if (!%vehicle.getMountNodeObject(%i))
	   {
	      //cheap hack - for now, AI's will mount the next available node regardless of where they collided
	      %node = %i;
	      break;
	   }
	}

	//return the empty seat
	return %node;
}

function findEmptySeat(%vehicle, %player, %forceNode)
{
   %minNode = 1;
   %node = -1;
   %dataBlock = %vehicle.getDataBlock();
   %dis = %dataBlock.minMountDist;
   %playerPos = getWords(%player.getTransform(), 0, 2);
   %message = "";
   if(%dataBlock.lightOnly)
   {
      if(%player.client.armor $= "Light")
         %minNode = 0;
      else 
         %message = '\c2Only Scout Armors can pilot this vehicle.~wfx/misc/misc.error.wav';
   }
   else if(%player.client.armor $= "Light" || %player.client.armor $= "Medium")
      %minNode = 0;
   else
      %minNode = findFirstHeavyNode(%dataBlock);
   
   if(%forceNode !$= "")
      %node = %forceNode;
   else
   {
      for(%i = 0; %i < %dataBlock.numMountPoints; %i++)
         if(!%vehicle.getMountNodeObject(%i))
         {
            %seatPos = getWords(%vehicle.getSlotTransform(%i), 0, 2);
            %disTemp = VectorLen(VectorSub(%seatPos, %playerPos));
            if(%disTemp <= %dis)
            {
               %node = %i;
               %dis = %disTemp;
            }
         }
    }
   if(%node != -1 && %node < %minNode)
   {
      if(%message $= "")
      {
         if(%node == 0)
            %message = '\c2Only Scout or Assault Armors can pilot this vehicle.~wfx/misc/misc.error.wav';
         else
            %message = '\c2Only Scout or Assault Armors can use that position.~wfx/misc/misc.error.wav';
      }
      
      messageClient(%player.client, 'MsgArmorCantMountVehicle', %message);   
      %node = -1;
   }
   return %node;
}

function findFirstHeavyNode(%data)
{
   for(%i = 0; %i < %data.numMountPoints; %i++)
      if(%data.mountPose[%i] $= "")
         return %i;
   return %data.numMountPoints;
}

//**************************************************************
//* DAMAGE FUNCTIONS
//**************************************************************

function VehicleData::damageObject(%data, %targetObject, %sourceObject, %position, %amount, %damageType, %momVec)
{
   if (%targetobject.invulnerable == true)
      return;

   // check for team damage
   %sourceClient = %sourceObject ? %sourceObject.getOwnerClient() : 0;
   %targetTeam = getTargetSensorGroup(%targetObject.getTarget());

   if (%sourceClient)
      %sourceTeam = %sourceClient.getSensorGroup();
   else if(isObject(%sourceObject) && %sourceObject.getClassName() $= "Turret")
      %sourceTeam = getTargetSensorGroup(%sourceObject.getTarget());
   else
      %sourceTeam = %sourceObject ? getTargetSensorGroup(%sourceObject.getTarget()) : -1;

   if (!$teamDamage && (%targetTeam == %sourceTeam) && %targetObject.getDamagePercent() > 0.5)
      return;

   // Scale damage type & include shield calculations...
   if (%data.isShielded)
      %amount = %data.checkShields(%targetObject, %position, %amount, %damageType);

   if (%amount == 0)
      return;
   
   %damageScale = %data.damageScale[%damageType];
   if (%damageScale !$= "")
      %amount *= %damageScale;
      
   if (%amount != 0)
      %targetObject.applyDamage(%amount);
      
   if (%targetObject.getDamageState() $= "Destroyed")
   {
      if (%momVec !$= "")
         %TargetObject.setMomentumVector(%momVec);

      return;
   }

   if (%TargetObject.RepairCheck !$= "")
      cancel(%TargetObject.RepairCheck);

   %TargetObject.RepairCheck = %Data.schedule(250, CheckRepairs, %TargetObject);

   if (%TargetObject.DisturbanceCheck $= "" && %Data.NoDisturbance != true)
      %TargetObject.DisturbanceCheck = %Data.schedule(250, MakeDisturbance, %TargetObject);
}

function VehicleData::CheckRepairs(%Data, %VehicleObject)
{
   if (isObject(%VehicleObject) == false)
      return;

   %Damage = %VehicleObject.getDamageLevel();
   %DamagePercent = 1 - ((%Damage / %Data.maxDamage) * 0.85);
   %RechargeRate = %DamagePercent * %Data.rechargeRate;

   %VehicleObject.setRechargeRate(%RechargeRate);

   if (%Damage > 0)
   {
      %Data.schedule(2500, CheckRepairs, %VehicleObject);
   } else {
      %VehicleObject.RepairCheck = "";

      cancel(%VehicleObject.DisturbanceCheck);
      %VehicleObject.DisturbanceCheck = "";
   }
}

function VehicleData::MakeDisturbance(%Data, %VehicleObject)
{
   if (isObject(%VehicleObject) == false)
      return;

   %Damage = %VehicleObject.getDamageLevel();
   %DamagePercent = %Damage / %Data.maxDamage;

   %DisturbanceForce = (%Data.mass / 8) * %DamagePercent;
   
   %Speed = VectorLen(%VehicleObject.getVelocity()) * 2 + 10;

   %Random = getRandom();
   %VectorX = %Random * 2 - %Random;
   %Random = getRandom();
   %VectorY = %Random * 2 - %Random;
   %Random = getRandom();
   %VectorZ = -1 * %Random;

   %DisturbanceVector = VectorScale(%VectorX @ " " @ %VectorY @ " " @ %VectorZ, %Speed * %DisturbanceForce);

   %Position = %VehicleObject.getWorldBoxCenter();
   %VehicleObject.ApplyImpulse(%Position, %DisturbanceVector);

   %VehicleObject.DisturbanceCheck = %Data.schedule(1250, MakeDisturbance, %VehicleObject);
}

function VehicleData::onImpact(%data, %vehicleObject, %collidedObject, %vec, %vecLen)
{
   if(%vecLen > %data.minImpactSpeed)
      %data.damageObject(%vehicleObject, 0, VectorAdd(%vec, %vehicleObject.getPosition()), 
                         %vecLen * %data.speedDamageScale, $DamageType::Ground);

   // associated "crash" sounds
   if(%vecLen > %vDataBlock.hardImpactSpeed)
      %vehicleObject.playAudio(0, %vDataBlock.hardImpactSound);
   else if(%vecLen > %vDataBlock.softImpactSpeed)
      %vehicleObject.playAudio(0, %vDataBlock.softImpactSound);
}            

//**************************************************************
//* VEHICLE TIMEOUTS
//**************************************************************

function vehicleAbandonTimeOut(%vehicle)
{
   if(%vehicle.getDatablock().cantAbandon $= "" && %vehicle.lastPilot $= "")
   {
      for(%i = 0; %i < %vehicle.getDatablock().numMountPoints; %i++)
         if (%vehicle.getMountNodeObject(%i))
         {
            %passenger = %vehicle.getMountNodeObject(%i);
            if(%passenger.lastVehicle !$= "")
               schedule(15000, %passenger.lastVehicle,"vehicleAbandonTimeOut", %passenger.lastVehicle);
            %passenger.lastVehicle = %vehicle;   
            %vehicle.lastPilot = %passenger;   
            return;
         }
      
      if(%vehicle.respawnTime !$= "")
         %vehicle.marker.schedule = %vehicle.marker.data.schedule(%vehicle.respawnTime, "respawn", %vehicle.marker); 
      %vehicle.mountable = 0;
      %vehicle.startFade(1000, 0, true);
      %vehicle.schedule(1001, "delete");
   }
}

//------------------------------------------------------------------------------
function HoverVehicleData::create(%block, %team, %oldObj)
{
   if(%oldObj $= "")
   {
      %obj = new HoverVehicle() 
      {
         dataBlock  = %block;
         respawn    = "0";
         teamBought = %team;
         team = %team;
      };
   }
   else
   {
      %obj = new HoverVehicle() 
      {
         dataBlock  = %data;
         respawn    = "0";
         teamBought = %team;
         team = %team;
         mountable = %oldObj.mountable;
         disableMove = %oldObj.disableMove;
         resetPos = %oldObj.resetPos;
         respawnTime = %oldObj.respawnTime;
         marker = %oldObj;
      }; 
   }
   return(%obj);
}

function WheeledVehicleData::create(%data, %team, %oldObj)
{
   if(%oldObj $= "")
   {
      %obj = new WheeledVehicle() 
      {
         dataBlock  = %data;
         respawn    = "0";
         teamBought = %team;
         team = %team;
      };
   }
   else
   {
      %obj = new WheeledVehicle() 
      {
         dataBlock  = %data;
         respawn    = "0";
         teamBought = %team;
         team = %team;
         mountable = %oldObj.mountable;
         disableMove = %oldObj.disableMove;
         resetPos = %oldObj.resetPos;
         deployed = %oldObj.deployed;
         respawnTime = %oldObj.respawnTime;
         marker = %oldObj;
      };   
   }
   
   return(%obj);
}

function FlyingVehicleData::create(%data, %team, %oldObj)
{
   if(%oldObj $= "")
   {
      %obj = new FlyingVehicle() 
      {
         dataBlock  = %data;
         respawn    = "0";
         teamBought = %team;
         team = %team;
      };
   }      
   else
   {
      %obj = new FlyingVehicle() 
      {
         dataBlock  = %data;
         teamBought = %team;
         team = %team;
         mountable = %oldObj.mountable;
         disableMove = %oldObj.disableMove;
         resetPos = %oldObj.resetPos;
         respawnTime = %oldObj.respawnTime;
         marker = %oldObj;
      };      
   }
   
   return(%obj);
}
                                    
function FlyingVehicleData::switchSidesSetPos(%data, %oldObj)
{
   %team = %oldObj.curTeam == 1 ? 2 : 1;
   %oldObj.curTeam = %team;
   %obj = new FlyingVehicle() 
   {
      dataBlock  = %data;
      teamBought = %team;
      team = %team;
      mountable = %oldObj.mountable;
      disableMove = %oldObj.disableMove;
      resetPos = %oldObj.resetPos;
      respawnTime = %oldObj.respawnTime;
      marker = %oldObj;
   };   
   %obj.setTransform(%oldObj.getTransform());

   return(%obj);
}

function WheeledVehicleData::switchSidesSetPos(%data, %oldObj)
{
   %team = %oldObj.curTeam == 1 ? 2 : 1;
   %oldObj.curTeam = %team;
   %obj = new WheeledVehicle() 
   {
      dataBlock  = %data;
      respawn    = "0";
      teamBought = %team;
      team = %team;
      mountable = %oldObj.mountable;
      disableMove = %oldObj.disableMove;
      resetPos = %oldObj.resetPos;
      deployed = %oldObj.deployed;
      respawnTime = %oldObj.respawnTime;
      marker = %oldObj;
   };   
   %obj.setTransform(%oldObj.getTransform());
   return(%obj);
}

function HoverVehicleData::switchSides(%data, %oldObj)
{
   %team = %oldObj.curTeam == 1 ? 2 : 1;
   %oldObj.curTeam = %team;
   %obj = new HoverVehicle() 
   {
      dataBlock  = %data;
      respawn    = "0";
      teamBought = %team;
      team = %team;
      mountable = %oldObj.mountable;
      disableMove = %oldObj.disableMove;
      resetPos = %oldObj.resetPos;
      respawnTime = %oldObj.respawnTime;
      marker = %oldObj;
   }; 
   %obj.setTransform(%oldObj.getTransform());
   return(%obj);
}

function resetNonStaticObjPositions()
{
   MissionGroup.setupPositionMarkers(false);
   MissionCleanup.positionReset();
}

function next(%team)
{
   ResetObjsPositions(%team);
}

function SimGroup::positionReset(%group)
{
   for(%i = %group.getCount() - 1; %i >=0 ; %i--)
   {               
      %obj = %group.getObject(%i);
      if(%obj.resetPos && %obj.getName() !$= PosMarker)
         %obj.delete();
      else
         %obj.positionReset();
   }

   for(%i = 0; %i < %group.getCount(); %i++)
   {
      %obj = %group.getObject(%i);
      if(%obj.getName() $= PosMarker)
      {
         cancel(%obj.schedule);
         %newObj =  %obj.data.switchSidesSetPos(%obj);
         MissionCleanup.add(%newObj);
         setTargetSensorGroup(%newObj.target, %newObj.team);
      }
      else 
         %obj.positionReset();
   }
}

function VehicleData::respawn(%data, %marker)
{
   %mask = $TypeMasks::PlayerObjectType | $TypeMasks::VehicleObjectType | $TypeMasks::TurretObjectType;
   InitContainerRadiusSearch(%marker.getWorldBoxCenter(), %data.checkRadius, %mask);
   if(containerSearchNext() == 0)    
   {
      %newObj = %data.create(%marker.curTeam, %marker);
      %newObj.startFade(1000, 0, false);
      %newObj.setTransform(%marker.getTransform());

      setTargetSensorGroup(%newObj.target, %newObj.team);
      MissionCleanup.add(%newObj);
   }
   else
   {
      %marker.schedule = %data.schedule(3000, "respawn", %marker);
   }
}

function SimObject::positionReset(%group, %team)
{
   //Used to avoid warnings
}

function Terraformer::positionReset(%group, %team)
{
   //Used to avoid warnings
}

function SimGroup::setupPositionMarkers(%group, %create)
{
   for(%i = %group.getCount() - 1; %i >= 0; %i--)
   {               
      %obj = %group.getObject(%i);
      if(%obj.resetPos || %obj.respawnTime !$= "")
      {
         if(%create)
         {
            %marker = %obj.getDataBlock().createPositionMarker(%obj);
            MissionCleanup.add(%marker);
            %obj.marker = %marker;
         }
         else
         {
            %obj.delete();
         }
      }
      else
         %obj.setupPositionMarkers(%create);
   }               
}

function SimObject::setupPositionMarkers(%group, %create)
{
   //Used to avoid warnings
}

function VehicleData::createPositionMarker(%data, %obj)
{
   %marker = new Trigger(PosMarker)
   {
      dataBlock = markerTrigger;
      mountable = %obj.mountable;
      disableMove = %obj.disableMove;
      resetPos = %obj.resetPos;
      data = %obj.getDataBlock().getName();
      deployed = %obj.deployed;
      curTeam = %obj.team;
      respawnTime = %obj.respawnTime;
   };   
   %marker.setTransform(%obj.getTransform());
   return %marker;
}

function VehicleData::hasDismountOverrides(%data, %obj)
{
   return false;
}


// The shrike now allows players to switch weapons
function ScoutFlyer::playerMounted(%data, %Object, %Player, %Node)
{
   commandToClient(%Player.client, 'setHudMode', 'Pilot', "Shrike", %Node);
   commandToClient(%Player.client,'SetWeaponryVehicleKeys', true);
   $numVWeapons = 3;
}

function AssaultVehicle::playerDismounted(%Data, %Vehicle, %Player)
{
   if (%Vehicle.getMountNodeObject(0) > 0)
      return;

   if (%Vehicle.deployed == true)
      return;

   %Vehicle.deploySchedule = %Data.schedule(500, vehicleDeploy, %Vehicle, %Player, false);
}

function AssaultVehicle::vehicleDeploy(%Data, %Vehicle, %Player, %ForcedDeploy)
{ 
   if (%ForcedDeploy $= "")
      %ForcedDeploy = false;

   if (%ForcedDeploy == false)
   {
      // Make sure the vehicle has come to a stop or close enough.
      %Speed = VectorLen(%Vehicle.getVelocity());
      if(%Speed > 1.15)
      {
         %Vehicle.deploySchedule = %Data.schedule(500, vehicleDeploy, %Vehicle, %Player, false);
         return;
      }
   }

   // Make sure the vehicle is over a solid terrain
   %FacingVector = VectorNormalize(%Vehicle.getForwardVector());
   %Transform = %Vehicle.getTransform();
   %Position = posFromTransform(%Transform);
   %Rotation = rotFromTransform(%Transform);

   // Check under the Nose First
   %PositionSearch = VectorAdd(%Position, VectorScale(%FacingVector, 4));
   %SearchDepth = %Data.stabLenMax + 0.5;

   %SearchMask = $TypeMasks::TerrainObjectType | $TypeMasks::InteriorObjectType;

   %EndSearch = VectorAdd(%PositionSearch, VectorScale("0 0 -1", %SearchDepth));

   %Terrain = ContainerRayCast(%PositionSearch, %EndSearch, %SearchMask, %Vehicle);

   if (%Terrain $= "0")
   {   
      messageClient(%Player.client, '', 'No solid terrain found under the nose of the tank.');
      return;
   } else {
      %TerrainPosition1 = getWords(%Terrain, 1, 3);

      %TerrainAngel = getTerrainAngle(normalFromRaycast(%Terrain));

      if (%TerrainAngel > 20)
      {
         messageClient(%Player.client, '', 'Terrain too steep/broken under the nose of the tank.');
         return;
      }
   }

   // Check under the Tail Next
   %PositionSearch2 = VectorAdd(%Position, VectorScale(%FacingVector, -4));
   %SearchDepth = %Data.stabLenMax + 0.5;

   %EndSearch = VectorAdd(%PositionSearch2, VectorScale("0 0 -1", %SearchDepth));

   %Terrain = ContainerRayCast(%PositionSearch2, %EndSearch, %SearchMask, %Vehicle);

   if (%Terrain $= "0")
   {   
      messageClient(%Player.client, '', 'No solid terrain found under the tail of the tank.');
      return;
   } else {
      %TerrainPosition2 = getWords(%Terrain, 1, 3);

      %TerrainAngel = getTerrainAngle(normalFromRaycast(%Terrain));

      if (%TerrainAngel > 20)
      {
         messageClient(%Player.client, '', 'Terrain too steep/broken under the tail of the tank.');
         return;
      }
   }

   // Everything seems ok, lets start the deploying 
   %Vehicle.deploySchedule = "";
   %Vehicle.deployed = true;

   %Vehicle.RaisedTransform = %Transform;

   // Find the "average" position of the terrain.
   %TerrainAverage = (getWord(%TerrainPosition1, 2) + getWord(%TerrainPosition2, 2)) / 2;
   %Vehicle.LoweredPosition = getWords(%Position, 0, 1) @ " " @ %TerrainAverage;

   %Data.schedule(850, LowerTank, %Vehicle);
   %Vehicle.playAudio($DeploySound, CameraGrenadeAttachSound);
}

// Function to lower the tank.
function AssaultVehicle::LowerTank(%Data, %Vehicle)
{
   %Rotation = rotFromTransform(%Vehicle.getTransform());
   %Transform = %Vehicle.LoweredPosition @ " " @ %Rotation;

   %Vehicle.setTransform(%Transform);

   %Vehicle.playAudio($PlaySound, LFootHeavyMetalSound);

   %Vehicle.setFrozenState(true);
}

// Function to raise the Tank and restart it's 
function AssaultVehicle::RaiseTank(%Data, %Vehicle)
{
   %Vehicle.setTransform(%Vehicle.RaisedTransform);

   %Vehicle.deployed = false;
}

function ResetTurret(%Turret, %Vehicle, %EnergyRequired)
{
   %Energy = %Vehicle.getEnergyLevel();
   %ReserveEnergy = %Vehicle.getDataBlock().maxEnergy * 0.05;
   if (%Energy < %EnergyRequired + %ReserveEnergy)
   {
      %Turret.ReloadSchedule = schedule(1000, 0, ResetTurret, %Turret, %Vehicle, %EnergyRequired);
      return;
   }
   %Vehicle.getEnergyLevel(%Energy - %EnergyRequired);

   // Set the Turret as able to fire again
   %Turret.NoFire = "";

   // Play reloading Sound
   %ReloadSound = "BomberBombReloadSound";
   
   %Turret.playAudio(0, %ReloadSound);
}

// The shrike now has a single missile launcher under it's nose
function ScoutFlyer::onAdd(%this, %Vehicle)
{
   Parent::onAdd(%this, %Vehicle);

   %Vehicle.nextWeaponFire = 2;
   %Vehicle.schedule(5500, "playThread", $ActivateThread, "activate");
   %Vehicle.selectedWeapon = 1;

   %Vehicle.mountImage(ScoutChaingunParam, 1);

   %Vehicle.mountImage(ScoutChaingunImage, 2);
   %Vehicle.mountImage(ScoutChaingunPairImage, 3);

   %Vehicle.mountImage(ShrikeTargetingImage, 5);

   %Vehicle.mountImage(ScoutMissileImage, 4);
}

function ResetTurret(%Turret, %Vehicle, %EnergyRequired)
{
   if (isObject(%Turret) == false)
      return;

   %Energy = %Vehicle.getEnergyLevel();
   %ReserveEnergy = %Vehicle.getDataBlock().maxEnergy * 0.2;
   if (%Energy < %EnergyRequired + %ReserveEnergy)
   {
      %Turret.ReloadSchedule = schedule(1000, 0, ResetTurret, %Turret, %Vehicle, %EnergyRequired);
      return;
   }
   %Vehicle.setEnergyLevel(%Energy - %EnergyRequired);

   // Set the Turret as able to fire again
   %Turret.NoFire = "";

   %ReloadSound = %Turret.getDataBlock().reloadSound;

   // Play reloading Sound
   %Turret.playAudio(0, %ReloadSound);
}