public void OrderExterminatePlanet(Planet toBombard)
 {
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.State = AIState.Exterminate;
     this.OrderQueue.Clear();
     ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Exterminate, Vector2.Zero, 0f)
     {
         TargetPlanet = toBombard
     };
     this.OrderQueue.AddLast(combat);
 }
 public void OrderLandAllTroops(Planet target)
 {
     if ((this.Owner.Role == "troop" || this.Owner.HasTroopBay || this.Owner.hasTransporter) &&  this.Owner.TroopList.Count > 0  && target.GetGroundLandingSpots() >0 )
     {
         this.HasPriorityOrder = true;
         this.State = AIState.AssaultPlanet;
         this.OrbitTarget = target;
         this.OrderQueue.Clear();
         ArtificialIntelligence.ShipGoal goal = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.LandTroop, Vector2.Zero, 0f)
         {
             TargetPlanet = target
         };
         this.OrderQueue.AddLast(goal);
     }
     else if (this.Owner.BombBays.Count > 0 && target.GetGroundStrength(this.Owner.loyalty) ==0)  //universeScreen.player == this.Owner.loyalty &&
     {
         this.State = AIState.Bombard;
         this.OrderBombardTroops(target);
     }
 }
        /**
           This method orders this ship to bombard the specified planet
           @param toBombard - the planet that this ship is directed to bombard.

           */
        public void OrderBombardTroops(Planet toBombard)
        {
            lock (this.wayPointLocker)
            {
                this.ActiveWayPoints.Clear();
            }
            this.State = AIState.BombardTroops;
            this.Owner.InCombatTimer = 15f;
            this.OrderQueue.Clear();
            this.HasPriorityOrder = true;
            ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.BombTroops, Vector2.Zero, 0f)
            {
                TargetPlanet = toBombard
            };
            this.OrderQueue.AddLast(combat);
        }
 public void OrderDeepSpaceBuild(Goal goal)
 {
     this.OrderQueue.Clear();
     this.OrderMoveTowardsPosition(goal.BuildPosition, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.Owner.Center, goal.BuildPosition)), this.findVectorToTarget(this.Owner.Center, goal.BuildPosition), true,null);
     ArtificialIntelligence.ShipGoal Deploy = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DeployStructure, goal.BuildPosition, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.Owner.Center, goal.BuildPosition)))
     {
         goal = goal,
         VariableString = goal.ToBuildUID
     };
     this.OrderQueue.AddLast(Deploy);
 }
 public void OrderAllStop()
 {
     this.OrderQueue.Clear();
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.State = AIState.HoldPosition;
     this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateInlineWithVelocity, Vector2.Zero, 0f));
     ArtificialIntelligence.ShipGoal stop = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Stop, Vector2.Zero, 0f);
     this.OrderQueue.AddLast(stop);
 }
        public void OrderAttackSpecificTarget(Ship toAttack)
        {
            this.TargetQueue.Clear();

            if (toAttack == null)
            {
                return;
            }

            if (this.Owner.loyalty.GetRelations().ContainsKey(toAttack.loyalty))
            {
                if (!this.Owner.loyalty.GetRelations()[toAttack.loyalty].Treaty_Peace)
                {
                    if (this.State == AIState.AttackTarget && this.Target == toAttack)
                    {
                        return;
                    }
                    if (this.State == AIState.SystemDefender && this.Target == toAttack)
                    {
                        return;
                    }
                    if (this.Owner.Weapons.Count == 0 || this.Owner.Role == "troop")
                    {
                        this.OrderInterceptShip(toAttack);
                        return;
                    }
                    this.Intercepting = true;
                    lock (this.wayPointLocker)
                    {
                        this.ActiveWayPoints.Clear();
                    }
                    this.State = AIState.AttackTarget;
                    this.Target = toAttack;
                    this.Owner.InCombatTimer = 15f;
                    this.OrderQueue.Clear();
                    this.IgnoreCombat = false;
                    this.TargetQueue.Add(toAttack);
                    this.hasPriorityTarget = true;
                    this.HasPriorityOrder = false;
                    ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
                    this.OrderQueue.AddLast(combat);
                    return;
                }
                this.OrderInterceptShip(toAttack);
            }
        }
 public void OrderRefitTo(string toRefit)
 {
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.HasPriorityOrder = true;
     this.IgnoreCombat = true;
     this.orderqueue.EnterWriteLock();
     this.OrderQueue.Clear();
     this.orderqueue.ExitWriteLock();
     IOrderedEnumerable<Ship_Game.Planet> sortedList =
         from planet in this.Owner.loyalty.GetPlanets()
         orderby Vector2.Distance(this.Owner.Center, planet.Position)
         select planet;
     this.OrbitTarget = null;
     foreach (Ship_Game.Planet Planet in sortedList)
     {
         if (!Planet.HasShipyard)
         {
             continue;
         }
         this.OrbitTarget = Planet;
         break;
     }
     if (this.OrbitTarget == null)
     {
         this.State = AIState.AwaitingOrders;
         return;
     }
     this.OrderMoveTowardsPosition(this.OrbitTarget.Position, 0f, Vector2.One, true,this.OrbitTarget);
     ArtificialIntelligence.ShipGoal refit = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Refit, Vector2.Zero, 0f)
     {
         TargetPlanet = this.OrbitTarget,
         VariableString = toRefit
     };
     this.OrderQueue.AddLast(refit);
     this.State = AIState.Refit;
 }
 private void SetCombatStatusorig(float elapsedTime)
 {
     if (this.Owner.fleet != null)
     {
         if (!this.hasPriorityTarget)
         {
             this.Target = this.ScanForCombatTargets(this.Owner.Center, 30000f);
         }
         else
         {
             this.ScanForCombatTargets(this.Owner.Center, 30000f);
         }
     }
     else if (!this.hasPriorityTarget)
     {
         this.Target = this.ScanForCombatTargets(this.Owner.Center, 30000f);
     }
     else
     {
         this.ScanForCombatTargets(this.Owner.Center, 30000f);
     }
     if (this.State == AIState.Resupply)
     {
         return;
     }
     if ((this.Owner.Role == "freighter" || this.Owner.Role == "scout" || this.Owner.Role == "construction" || this.Owner.Role == "troop" || this.IgnoreCombat || this.State == AIState.Resupply || this.State == AIState.ReturnToHangar) && !this.Owner.IsSupplyShip)
     {
         return;
     }
     if (this.Owner.fleet != null && this.State == AIState.FormationWarp)
     {
         bool doreturn = true;
         if (this.Owner.fleet != null && this.State == AIState.FormationWarp && Vector2.Distance(this.Owner.Center, this.Owner.fleet.Position + this.Owner.FleetOffset) < 15000f)
         {
             doreturn = false;
         }
         if (doreturn)
         {
             return;
         }
     }
     if (this.Owner.fleet != null)
     {
         foreach (FleetDataNode datanode in this.Owner.fleet.DataNodes)
         {
             if (datanode.GetShip() != this.Owner)
             {
                 continue;
             }
             this.node = datanode;
             break;
         }
     }
     if (this.Target != null && !this.Owner.InCombat)
     {
         this.Owner.InCombat = true;
         this.Owner.InCombatTimer = 15f;
         if (!this.HasPriorityOrder && this.OrderQueue.Count > 0 && this.OrderQueue.ElementAt<ArtificialIntelligence.ShipGoal>(0).Plan != ArtificialIntelligence.Plan.DoCombat)
         {
             ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
             this.State = AIState.Combat;
             this.OrderQueue.AddFirst(combat);
             return;
         }
         if (!this.HasPriorityOrder)
         {
             ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
             this.State = AIState.Combat;
             this.OrderQueue.AddFirst(combat);
             return;
         }
         if (this.HasPriorityOrder && this.CombatState != Ship_Game.Gameplay.CombatState.HoldPosition && this.OrderQueue.Count == 0)
         {
             ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
             this.State = AIState.Combat;
             this.OrderQueue.AddFirst(combat);
             return;
         }
     }
     else if (this.Target == null)
     {
         this.Owner.InCombat = false;
     }
 }
        public void OrderRebase(Planet p, bool ClearOrders)
        {
            lock (this.wayPointLocker)
            {
                this.ActiveWayPoints.Clear();
            }
            if (ClearOrders)
            {
                this.OrderQueue.Clear();
            }
            int troops = this.Owner.loyalty.GetShips()
            .Where(troop => troop.TroopList.Count > 0)
            .Where(troopAI => troopAI.GetAI().OrderQueue
            .Where(goal => goal.TargetPlanet != null && goal.TargetPlanet == p).Count() > 0).Count();

            if (troops >= p.GetGroundLandingSpots())
            {
                this.OrderQueue.Clear();
                this.State = AIState.AwaitingOrders;
                return;
            }

            this.OrderMoveTowardsPosition(p.Position, 0f, new Vector2(0f, -1f), false,p);
            this.IgnoreCombat = true;
            ArtificialIntelligence.ShipGoal rebase = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Rebase, Vector2.Zero, 0f)
            {
                TargetPlanet = p
            };
            this.OrderQueue.AddLast(rebase);
            this.State = AIState.Rebase;
            this.HasPriorityOrder = true;
        }
        public void OrderRebaseToNearest()
        {
            ////added by gremlin if rebasing dont rebase.
            //if (this.State == AIState.Rebase && this.OrbitTarget.Owner == this.Owner.loyalty)
            //    return;
            lock (this.wayPointLocker)
            {
                this.ActiveWayPoints.Clear();
            }

            IOrderedEnumerable<Planet> sortedList =
                from planet in this.Owner.loyalty.GetPlanets()
                //added by gremlin if the planet is full of troops dont rebase there. RERC2 I dont think the about looking at incoming troops works.
                where this.Owner.loyalty.GetShips()
            .Where(troop => troop.TroopList.Count > 0 )
            .Where(troopAI => troopAI.GetAI().OrderQueue
            .Where(goal => goal.TargetPlanet != null && goal.TargetPlanet == planet).Count() > 0).Count() <= planet.GetGroundLandingSpots()

                /*where planet.TroopsHere.Count + this.Owner.loyalty.GetShips()
                .Where(troop => troop.Role == "troop"

                    && troop.GetAI().State == AIState.Rebase
                    && troop.GetAI().OrbitTarget == planet).Count() < planet.TilesList.Sum(space => space.number_allowed_troops)*/
                orderby Vector2.Distance(this.Owner.Center, planet.Position)
                select planet;

            if (sortedList.Count<Planet>() <= 0)
            {
                this.State = AIState.AwaitingOrders;
                return;
            }
            Planet p = sortedList.First<Planet>();
            this.OrderMoveTowardsPosition(p.Position, 0f, new Vector2(0f, -1f), false,p);
            this.IgnoreCombat = true;
            ArtificialIntelligence.ShipGoal rebase = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Rebase, Vector2.Zero, 0f)
            {
                TargetPlanet = p
            };

            this.orderqueue.EnterWriteLock();
            this.OrderQueue.AddLast(rebase);
            this.orderqueue.ExitWriteLock();
            this.State = AIState.Rebase;
            this.HasPriorityOrder = true;
        }
 public void OrderOrbitPlanet(Planet p)
 {
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.Target = null;
     this.Intercepting = false;
     this.Owner.HyperspaceReturn();
     this.OrbitTarget = p;
     this.OrderQueue.Clear();
     ArtificialIntelligence.ShipGoal orbit = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Orbit, Vector2.Zero, 0f)
     {
         TargetPlanet = p
     };
     this.resupplyTarget = p;
     this.OrderQueue.AddLast(orbit);
     this.State = AIState.Orbit;
 }
        public void OrderMoveTowardsPosition( Vector2  position , float desiredFacing, Vector2 fVec, bool ClearOrders, Planet TargetPlanet)
        {
            this.DistanceLast = 0f;
            this.Target = null;
            this.hasPriorityTarget = false;
            Vector2 wantedForward = Vector2.Normalize(HelperFunctions.FindVectorToTarget(this.Owner.Center, position));
            Vector2 forward = new Vector2((float)Math.Sin((double)this.Owner.Rotation), -(float)Math.Cos((double)this.Owner.Rotation));
            Vector2 right = new Vector2(-forward.Y, forward.X);
            float angleDiff = (float)Math.Acos((double)Vector2.Dot(wantedForward, forward));
            Vector2.Dot(wantedForward, right);
            if (angleDiff > 0.2f)
            {
                this.Owner.HyperspaceReturn();
            }
            this.OrderQueue.Clear();
            if (ClearOrders)
            {
                lock (this.wayPointLocker)
                {
                    this.ActiveWayPoints.Clear();
                }
            }
            if (ArtificialIntelligence.universeScreen != null && this.Owner.loyalty == EmpireManager.GetEmpireByName(ArtificialIntelligence.universeScreen.PlayerLoyalty))
            {
                this.HasPriorityOrder = true;
            }
            this.State = AIState.MoveTo;
            this.MovePosition = position;
            try
            {
                this.PlotCourseToNew(position, (this.ActiveWayPoints.Count > 0 ? this.ActiveWayPoints.Last<Vector2>() : this.Owner.Center));
            }
            catch
            {
                lock (this.wayPointLocker)
                {
                    this.ActiveWayPoints.Clear();
                }
            }
            this.FinalFacingVector = fVec;
            this.DesiredFacing = desiredFacing;

            lock (this.wayPointLocker)
            {
                            Planet p;
            Vector2 waypoint;
                int AWPC = this.ActiveWayPoints.Count;
                for (int i = 0; i < AWPC; i++)
                {
                    p =null;
                    waypoint = this.ActiveWayPoints.ToArray()[i];
                    if (i != 0)
                    {
                        if (AWPC - 1 == i)
                            p = TargetPlanet;

                        ArtificialIntelligence.ShipGoal to1k = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MoveToWithin1000, waypoint, desiredFacing)
                        {
                            TargetPlanet=p,
                            SpeedLimit = this.Owner.speed
                        };
                        this.OrderQueue.AddLast(to1k);
                    }
                    else
                    {
                        if(AWPC -1 ==i)
                            p = TargetPlanet;
                        this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateToFaceMovePosition, waypoint, 0f));
                        ArtificialIntelligence.ShipGoal to1k = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MoveToWithin1000, waypoint, desiredFacing)
                        {
                            TargetPlanet = p,
                            SpeedLimit = this.Owner.speed
                        };
                        this.OrderQueue.AddLast(to1k);
                    }
                    if (i == AWPC - 1)
                    {
                        ArtificialIntelligence.ShipGoal finalApproach = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MakeFinalApproach, waypoint, desiredFacing)
                        {
                            TargetPlanet=p,
                            SpeedLimit = this.Owner.speed
                        };
                        this.OrderQueue.AddLast(finalApproach);
                        ArtificialIntelligence.ShipGoal slow = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.StopWithBackThrust, waypoint, 0f)
                        {
                            TargetPlanet = TargetPlanet,
                            SpeedLimit = this.Owner.speed
                        };
                        this.OrderQueue.AddLast(slow);
                        this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateToDesiredFacing, waypoint, desiredFacing));
                    }
                }
            }
        }
 public void OrderMoveToFleetPosition(Vector2 position, float desiredFacing, Vector2 fVec, bool ClearOrders, float SpeedLimit, Fleet fleet)
 {
     SpeedLimit = this.Owner.speed;
     if (ClearOrders)
     {
         this.OrderQueue.Clear();
         lock (this.wayPointLocker)
         {
             this.ActiveWayPoints.Clear();
         }
     }
     this.State = AIState.MoveTo;
     this.MovePosition = position;
     this.FinalFacingVector = fVec;
     this.DesiredFacing = desiredFacing;
     bool inCombat = this.Owner.InCombat;
     this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateToFaceMovePosition, this.MovePosition, 0f));
     ArtificialIntelligence.ShipGoal to1k = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MoveToWithin1000Fleet, this.MovePosition, desiredFacing)
     {
         SpeedLimit = SpeedLimit,
         fleet = fleet
     };
     this.OrderQueue.AddLast(to1k);
     ArtificialIntelligence.ShipGoal finalApproach = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MakeFinalApproachFleet, this.MovePosition, desiredFacing)
     {
         SpeedLimit = SpeedLimit,
         fleet = fleet
     };
     this.OrderQueue.AddLast(finalApproach);
     this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateInlineWithVelocity, Vector2.Zero, 0f));
     ArtificialIntelligence.ShipGoal slow = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.StopWithBackThrust, position, 0f)
     {
         SpeedLimit = this.Owner.speed
     };
     this.OrderQueue.AddLast(slow);
     this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateToDesiredFacing, this.MovePosition, desiredFacing));
 }
 private void OrderSupplyShip(Ship tosupply, float ord_amt)
 {
     ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.SupplyShip, Vector2.Zero, 0f);
     this.EscortTarget = tosupply;
     g.VariableNumber = ord_amt;
     this.IgnoreCombat = true;
     this.OrderQueue.Clear();
     this.OrderQueue.AddLast(g);
     this.State = AIState.Ferrying;
 }
 public void OrderReturnToHangar()
 {
     ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.ReturnToHangar, Vector2.Zero, 0f);
     this.orderqueue.EnterWriteLock();
     this.OrderQueue.Clear();
     this.OrderQueue.AddLast(g);
     this.orderqueue.ExitWriteLock();
     this.HasPriorityOrder = true;
     this.State = AIState.ReturnToHangar;
 }
        private void SetCombatStatus(float elapsedTime)
        {
            //if(this.State==AIState.Scrap)
            //{
            //    this.Target = null;
            //    this.Owner.InCombatTimer = 0f;
            //    this.Owner.InCombat = false;
            //    this.TargetQueue.Clear();
            //    return;

            //}
            float radius = 30000f;
            Vector2 senseCenter = this.Owner.Center;
            if (UseSensorsForTargets)
            {
                if (this.Owner.Mothership != null)
                {
                    if (Vector2.Distance(this.Owner.Center, this.Owner.Mothership.Center) <= this.Owner.Mothership.SensorRange - this.Owner.SensorRange)
                    {
                        senseCenter = this.Owner.Mothership.Center;
                        radius = this.Owner.Mothership.SensorRange;
                    }
                }
                else
                {
                    radius = this.Owner.SensorRange;
                    if (this.Owner.inborders) radius += 10000;
                }
            }
            if (this.Owner.fleet != null)
            {
                if (!this.hasPriorityTarget)
                {
                    this.Target = this.ScanForCombatTargets(senseCenter, radius);
                }
                else
                {
                    this.ScanForCombatTargets(senseCenter, radius);
                }
            }
            else if (!this.hasPriorityTarget)
            {
            //#if DEBUG
            //                if (this.State == AIState.Intercept && this.Target != null)
            //                    System.Diagnostics.Debug.WriteLine(this.Target);
            //#endif
                this.Target = this.ScanForCombatTargets(senseCenter, radius);
            }
            else
            {
                this.ScanForCombatTargets(senseCenter, radius);
            }
            if (this.State == AIState.Resupply)
            {
                return;
            }
            if (((this.Owner.Role == "freighter" && this.Owner.CargoSpace_Max > 0) || this.Owner.Role == "scout" || this.Owner.Role == "construction" || this.Owner.Role == "troop" || this.IgnoreCombat || this.State == AIState.Resupply || this.State == AIState.ReturnToHangar || this.State == AIState.Colonize) || this.Owner.VanityName == "Resupply Shuttle")
            {
                return;
            }
            if (this.Owner.fleet != null && this.State == AIState.FormationWarp)
            {
                bool doreturn = true;
                if (this.Owner.fleet != null && this.State == AIState.FormationWarp && Vector2.Distance(this.Owner.Center, this.Owner.fleet.Position + this.Owner.FleetOffset) < 15000f)
                {
                    doreturn = false;
                }
                if (doreturn)
                {
                    //if (this.Owner.engineState == Ship.MoveState.Sublight && this.NearbyShips.Count > 0)
                    //{
                    //    this.Owner.ShieldsUp = true;
                    //}
                    return;
                }
            }
            if (this.Owner.fleet != null)
            {
                foreach (FleetDataNode datanode in this.Owner.fleet.DataNodes)
                {
                    if (datanode.GetShip() != this.Owner)
                    {
                        continue;
                    }
                    this.node = datanode;
                    break;
                }
            }
            if (this.Target != null && !this.Owner.InCombat)
            {
                this.Owner.InCombatTimer = 15f;
                if (!this.HasPriorityOrder && this.OrderQueue.Count > 0 && this.OrderQueue.ElementAt<ArtificialIntelligence.ShipGoal>(0).Plan != ArtificialIntelligence.Plan.DoCombat)
                {
                    ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
                    this.State = AIState.Combat;
                    this.OrderQueue.AddFirst(combat);
                    return;
                }
                else if (!this.HasPriorityOrder)
                {
                    ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
                    this.State = AIState.Combat;
                    this.OrderQueue.AddFirst(combat);
                    return;
                }
                else
                {
                    if (!this.HasPriorityOrder || this.CombatState == CombatState.HoldPosition || this.OrderQueue.Count != 0)
                        return;
                    ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.DoCombat, Vector2.Zero, 0f);
                    this.State = AIState.Combat;
                    this.OrderQueue.AddFirst(combat);

                }
            }
        }
        public void OrderScrapShip()
        {
            #if SHOWSCRUB
            System.Diagnostics.Debug.WriteLine(string.Concat(this.Owner.loyalty.PortraitName, " : ", this.Owner.Role));
            #endif

            if((this.Owner.Role=="platform" || this.Owner.Role == "station" )&& this.Owner.ScuttleTimer<1)
            {
                this.Owner.ScuttleTimer = 1;
                this.State = AIState.Scuttle;
                this.HasPriorityOrder = true;
                return;
            }
            lock (this.wayPointLocker)
            {
                this.ActiveWayPoints.Clear();
            }
            this.Owner.loyalty.ForcePoolRemove(this.Owner);

            if (this.Owner.fleet != null)
                this.Owner.fleet = null;
            this.HasPriorityOrder = true;
            this.IgnoreCombat = true;
            this.OrderQueue.Clear();
            IOrderedEnumerable<Ship_Game.Planet> sortedList =
                from planet in this.Owner.loyalty.GetPlanets()
                orderby Vector2.Distance(this.Owner.Center, planet.Position)
                select planet;
            this.OrbitTarget = null;
            foreach (Ship_Game.Planet Planet in sortedList)
            {
                if (!Planet.HasShipyard)
                {
                    continue;
                }
                this.OrbitTarget = Planet;
                break;
            }
            if (this.OrbitTarget == null)
            {
                this.State = AIState.AwaitingOrders;
            }
            else
            {
                this.OrderMoveTowardsPosition(this.OrbitTarget.Position, 0f, Vector2.One, true,this.OrbitTarget);
                ArtificialIntelligence.ShipGoal scrap = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Scrap, Vector2.Zero, 0f)
                {
                    TargetPlanet = this.OrbitTarget
                };
                this.OrderQueue.AddLast(scrap);
                this.State = AIState.Scrap;
            }
            this.State = AIState.Scrap;
        }
        private void StopWithBackwardsThrustbroke(float elapsedTime, ArtificialIntelligence.ShipGoal Goal)
        {
            if (this.Owner.loyalty == EmpireManager.GetEmpireByName(ArtificialIntelligence.universeScreen.PlayerLoyalty))
            {
                this.HadPO = true;
            }
            this.HasPriorityOrder = false;
            float Distance = Vector2.Distance(this.Owner.Center, Goal.MovePosition);
            if (Distance < 200 )//&& Distance > 25f)
            {
                this.OrderQueue.RemoveFirst();
                lock (this.wayPointLocker)
                {
                    this.ActiveWayPoints.Clear();
                }
                this.Owner.Velocity = Vector2.Zero;
                if (this.Owner.loyalty == EmpireManager.GetEmpireByName(ArtificialIntelligence.universeScreen.PlayerLoyalty))
                {
                    this.HadPO = true;
                }
                this.HasPriorityOrder = false;
            }
            this.Owner.HyperspaceReturn();
            Vector2 forward = new Vector2((float)Math.Sin((double)this.Owner.Rotation), -(float)Math.Cos((double)this.Owner.Rotation));
            if (this.Owner.Velocity == Vector2.Zero || Vector2.Distance(this.Owner.Center + ( this.Owner.Velocity * elapsedTime), Goal.MovePosition) > Vector2.Distance(this.Owner.Center, Goal.MovePosition))
            {
                this.Owner.Velocity = Vector2.Zero;
                this.OrderQueue.RemoveFirst();
                if (this.ActiveWayPoints.Count > 0)
                {
                    lock (this.wayPointLocker)
                    {
                        this.ActiveWayPoints.Dequeue();
                    }
                }
                return;
            }
            Vector2 velocity = this.Owner.Velocity;
            float timetostop = (int)velocity.Length() / Goal.SpeedLimit;
            if (Vector2.Distance(this.Owner.Center, Goal.MovePosition) / Goal.SpeedLimit <= timetostop + .005) //(this.Owner.Velocity.Length() + 1)
                if (Math.Abs((int)(DistanceLast - Distance)) < 10)
                {

                    ArtificialIntelligence.ShipGoal to1k = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MakeFinalApproach, Goal.MovePosition, 0f)
                                    {
                                        SpeedLimit = this.Owner.speed > Distance ? Distance : this.Owner.GetSTLSpeed()
                                    };
                    lock (this.wayPointLocker)
                        this.OrderQueue.AddFirst(to1k);
                    this.DistanceLast = Distance;
                    return;
                }
            if (Vector2.Distance(this.Owner.Center, Goal.MovePosition) / (this.Owner.Velocity.Length() + 0.001f) <= timetostop)
            {
                Ship owner = this.Owner;
                owner.Velocity = owner.Velocity + (Vector2.Normalize(-forward) * (elapsedTime * Goal.SpeedLimit));
                if (this.Owner.Velocity.Length() > Goal.SpeedLimit)
                {
                    this.Owner.Velocity = Vector2.Normalize(this.Owner.Velocity) * Goal.SpeedLimit;
                }
            }
            else
            {
                Ship ship = this.Owner;
                ship.Velocity = ship.Velocity + (Vector2.Normalize(forward) * (elapsedTime * Goal.SpeedLimit));
                if (this.Owner.Velocity.Length() > Goal.SpeedLimit)
                {
                    this.Owner.Velocity = Vector2.Normalize(this.Owner.Velocity) * Goal.SpeedLimit;
                    return;
                }
            }

            this.DistanceLast = Distance;
        }
 public void OrderThrustTowardsPosition(Vector2 position, float desiredFacing, Vector2 fVec, bool ClearOrders)
 {
     if (ClearOrders)
     {
         this.OrderQueue.Clear();
         lock (this.wayPointLocker)
         {
             this.ActiveWayPoints.Clear();
         }
     }
     this.FinalFacingVector = fVec;
     this.DesiredFacing = desiredFacing;
     lock (this.wayPointLocker)
     {
         for (int i = 0; i < this.ActiveWayPoints.Count; i++)
         {
             Vector2 waypoint = this.ActiveWayPoints.ToArray()[i];
             if (i == 0)
             {
                 this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateInlineWithVelocity, Vector2.Zero, 0f));
                 ArtificialIntelligence.ShipGoal stop = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Stop, Vector2.Zero, 0f);
                 this.OrderQueue.AddLast(stop);
                 this.OrderQueue.AddLast(new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.RotateToFaceMovePosition, waypoint, 0f));
                 ArtificialIntelligence.ShipGoal to1k = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.MoveToWithin1000, waypoint, desiredFacing)
                 {
                     SpeedLimit = this.Owner.speed
                 };
                 this.OrderQueue.AddLast(to1k);
             }
         }
     }
 }
 //added by gremlin : troop asssault planet
 public void OrderAssaultPlanet(Planet p)
 {
     this.State = AIState.AssaultPlanet;
     this.OrbitTarget = p;
     ArtificialIntelligence.ShipGoal shipGoal = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.LandTroop, Vector2.Zero, 0f)
     {
         TargetPlanet = OrbitTarget
     };
     this.orderqueue.EnterWriteLock();
     this.OrderQueue.Clear();
     this.OrderQueue.AddLast(shipGoal);
     this.orderqueue.ExitWriteLock();
 }
 public void OrderToOrbit(Planet toOrbit, bool ClearOrders)
 {
     if (ClearOrders)
     {
         this.OrderQueue.Clear();
     }
     this.HasPriorityOrder = true;
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.State = AIState.Orbit;
     this.OrbitTarget = toOrbit;
     ArtificialIntelligence.ShipGoal orbit = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Orbit, Vector2.Zero, 0f)
     {
         TargetPlanet = toOrbit
     };
     this.OrderQueue.AddLast(orbit);
 }
 /**
     This method orders this ship to bombard the specified planet.
     @param toBombard - the planet that this ship is directed to bombard.
 */
 public void OrderBombardPlanet(Planet toBombard)
 {
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.State = AIState.Bombard;
     this.Owner.InCombatTimer = 15f;
     this.OrderQueue.Clear(); //rescind any current directives before adding "bombard" directive to order queue
     this.HasPriorityOrder = true;
     ArtificialIntelligence.ShipGoal combat = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Bombard, Vector2.Zero, 0f)
     {
         TargetPlanet = toBombard
     };
     this.OrderQueue.AddLast(combat);
 }
 public void OrderTroopToBoardShip(Ship s)
 {
     this.HasPriorityOrder = true;
     this.EscortTarget = s;
     ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.BoardShip, Vector2.Zero, 0f);
     this.orderqueue.EnterWriteLock();
     this.OrderQueue.Clear();
     this.OrderQueue.AddLast(g);
     this.orderqueue.ExitWriteLock();
 }
 public void OrderColonization(Planet toColonize)
 {
     if (toColonize == null)
     {
         return;
     }
     this.ColonizeTarget = toColonize;
     this.OrderMoveTowardsPosition(toColonize.Position, 0f, new Vector2(0f, -1f), true, toColonize);
     ArtificialIntelligence.ShipGoal colonize = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Colonize, toColonize.Position, 0f)
     {
         TargetPlanet = this.ColonizeTarget
     };
     this.OrderQueue.AddLast(colonize);
     this.State = AIState.Colonize;
 }
 public void OrderTroopToShip(Ship s)
 {
     this.EscortTarget = s;
     ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.TroopToShip, Vector2.Zero, 0f);
     this.OrderQueue.Clear();
     this.OrderQueue.AddLast(g);
 }
 public void OrderExplore()
 {
     if (this.State == AIState.Explore && this.ExplorationTarget != null)
     {
         return;
     }
     lock (this.wayPointLocker)
     {
         this.ActiveWayPoints.Clear();
     }
     this.OrderQueue.Clear();
     this.State = AIState.Explore;
     ArtificialIntelligence.ShipGoal Explore = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Explore, Vector2.Zero, 0f);
     this.OrderQueue.AddLast(Explore);
 }
        //added by gremlin Deveksmod Scan for combat targets.
        public GameplayObject ScanForCombatTargets(Vector2 Position, float Radius)
        {
            RandomThreadMath randomThreadMath;
            //reset target lists; ScanForTargets "refreshes" lists
            this.BadGuysNear = false;
            this.FriendliesNearby.Clear();
            this.PotentialTargets.Clear();
            this.NearbyShips.Clear();
            //this.TrackProjectiles.Clear();

            //if hasPriorityTarget, and target is null
            if (this.hasPriorityTarget && this.Target == null)
            {
                //remove boolean  hasPriorityTarget state: target is null
                this.hasPriorityTarget = false;
                //this ship has queued target orders
                if (this.TargetQueue.Count > 0)
                {
                    this.hasPriorityTarget = true;
                    this.Target = this.TargetQueue.First<Ship>();// dequeue
                }
            }
            //ship has a target
            if (this.Target != null)
            {
                //ship cannot friendly-fire
                if ((this.Target as Ship).loyalty == this.Owner.loyalty)
                {
                    this.Target = null;
                    this.hasPriorityTarget = false;
                }

                //target ship is hostile & at warp & not currently intercepted
                //disengage pursuit
                else if (!this.Intercepting && (this.Target as Ship).engineState == Ship.MoveState.Warp) //||((double)Vector2.Distance(Position, this.Target.Center) > (double)Radius ||
                {
                    //remove target from consideration
                    this.Target = (GameplayObject)null;
                    //ship does not have priority order
                    //& ship does not belong to player (I assume this exists to allow the Human Player to target units at warp; thus make exception case)
                    //return ship to AIState.AwaitingOrders
                    if (!this.HasPriorityOrder && this.Owner.loyalty != ArtificialIntelligence.universeScreen.player)
                        this.State = AIState.AwaitingOrders;
                    return (GameplayObject)null;
                }
            }
            this.CombatAI.PreferredEngagementDistance = this.Owner.maxWeaponsRange * 0.66f;
            SolarSystem thisSystem = this.Owner.GetSystem(); //determine system this ship currently occupies
            {
                #region Ship Escort Logic
                if (this.EscortTarget != null && this.EscortTarget.Active && this.EscortTarget.GetAI().Target != null)
                {
                    ArtificialIntelligence.ShipWeight sw = new ArtificialIntelligence.ShipWeight();
                    sw.ship = this.EscortTarget.GetAI().Target as Ship;
                    sw.weight = 2f;
                    this.NearbyShips.Add(sw);
                }
                List<GameplayObject> nearby = UniverseScreen.ShipSpatialManager.GetNearby(Owner);
                for (int i = 0; i < nearby.Count; i++)
                {
                    Ship item1 = nearby[i] as Ship;
                    if (item1 != null && item1.Active && !item1.dying &&(Vector2.Distance(this.Owner.Center, item1.Center) <= Radius))
                    {
                        Empire empire = item1.loyalty;
                        Ship shipTarget = item1.GetAI().Target as Ship;
                        if (empire == Owner.loyalty)
                        {
                            this.FriendliesNearby.Add(item1);
                        }
                        else if (empire != this.Owner.loyalty
                            && shipTarget != null
                            && shipTarget == this.EscortTarget && item1.engineState != Ship.MoveState.Warp)
                        {

                            ArtificialIntelligence.ShipWeight sw = new ArtificialIntelligence.ShipWeight();
                            sw.ship = item1;
                            sw.weight = 3f;

                            this.NearbyShips.Add(sw);
                            this.BadGuysNear = true;
                            //this.PotentialTargets.Add(item1);
                        }
                        else if ((item1.loyalty != this.Owner.loyalty
                            && this.Owner.loyalty.GetRelations()[item1.loyalty].AtWar
                            || this.Owner.loyalty.isFaction || item1.loyalty.isFaction))//&& Vector2.Distance(this.Owner.Center, item.Center) < 15000f)
                        {
                            ArtificialIntelligence.ShipWeight sw = new ArtificialIntelligence.ShipWeight();
                            sw.ship = item1;
                            sw.weight = 1f;
                            this.NearbyShips.Add(sw);
                            //this.PotentialTargets.Add(item1);
                            this.BadGuysNear = Vector2.Distance(Position, item1.Position) <= Radius;
                        }

                    }
                }
                #endregion
            }
            //if target is !null but inactive
            //set inactive target to null; reset hasPriorityTarget boolean
            if (this.Target != null && !this.Target.Active) //What is the "Active" boolean used for?
            {
                this.Target = null;
                this.hasPriorityTarget = false;
            }
            //if target is !null, and active, and priority this ship has priority target
            else if (this.Target != null && this.Target.Active && this.hasPriorityTarget)
            {
                //if at war with target ship
                //this.Owner.loyalty.isFaction   : a hostile?
                if (this.Owner.loyalty.GetRelations()[(this.Target as Ship).loyalty].AtWar || this.Owner.loyalty.isFaction || (this.Target as Ship).loyalty.isFaction)
                {
                    //this.PotentialTargets.Add(this.Target as Ship); //why was this commented out? To be replaced with targetQueue?
                    this.TargetQueue.Add(this.Target as Ship); //added by Ermenildo V. Castro, Jr.
                                                               //07/28/15
                                                               //Perhaps unnecessary since the method returns this.Target
                                                               //Whichever invokes ScanForCombatTargets may already add this Target to the TargetQueue, therefore redundant method call.
                    this.BadGuysNear = true;
                }
                return this.Target;
            }
            if (this.Owner.GetHangars().Where(hangar => hangar.IsSupplyBay).Count() > 0 && this.Owner.engineState != Ship.MoveState.Warp && !this.Owner.isSpooling)
            #region supply ship logic
            {
                IOrderedEnumerable<Ship> sortedList = null;
                //if (this.Owner.Role == "station" || this.Owner.Role == "platform")
                //{
                //    sortedList = this.Owner.loyalty.GetShips().Where(ship => Vector2.Distance(this.Owner.Center, ship.Center) < 10 * this.Owner.SensorRange && ship != this.Owner && ship.engineState != Ship.MoveState.Warp && ship.Mothership == null && ship.OrdinanceMax > 0 && ship.Ordinance / ship.OrdinanceMax < .5 && !ship.IsTethered()).OrderBy(ship => ship.HasSupplyBays).ThenBy(ship => ship.OrdAddedPerSecond).ThenBy(ship => Math.Truncate((Vector2.Distance(this.Owner.Center, ship.Center) + 9999)) / 10000).ThenBy(ship => ship.OrdinanceMax - ship.Ordinance);
                //}
                //else
                {
                    sortedList = FriendliesNearby.Where(ship => ship != this.Owner
                        && ship.engineState != Ship.MoveState.Warp
                        && ship.Mothership == null
                        && ship.OrdinanceMax > 0
                        && ship.Ordinance / ship.OrdinanceMax < .5
                        && !ship.IsTethered())
                        .OrderBy(ship => ship.HasSupplyBays).ThenBy(ship => ship.OrdAddedPerSecond).ThenBy(ship => Math.Truncate((Vector2.Distance(this.Owner.Center, ship.Center) + 4999)) / 5000).ThenBy(ship => ship.OrdinanceMax - ship.Ordinance);
                }

                    if (sortedList.Count() > 0)
                    {
                        int skip = 0;
                        float inboundOrdinance = 0f;
                        foreach (ShipModule hangar in this.Owner.GetHangars().Where(hangar => hangar.IsSupplyBay))
                        {
                            if (hangar.GetHangarShip() != null)
                            {
                                if (hangar.GetHangarShip().GetAI().State != AIState.Ferrying)
                                {
                                    if (sortedList.Skip(skip).Count() > 0)
                                    {
                                        ArtificialIntelligence.ShipGoal g1 = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.SupplyShip, Vector2.Zero, 0f);
                                        hangar.GetHangarShip().GetAI().EscortTarget = sortedList.Skip(skip).First();//.Where(ship => !ship.IsTethered()).FirstOrDefault();//sortedList.ElementAt<Ship>(y);

                                        hangar.GetHangarShip().GetAI().IgnoreCombat = true;
                                        hangar.GetHangarShip().GetAI().OrderQueue.Clear();
                                        hangar.GetHangarShip().GetAI().OrderQueue.AddLast(g1);
                                        hangar.GetHangarShip().GetAI().State = AIState.Ferrying;
                                        continue;
                                    }
                                    else
                                    {
                                        hangar.GetHangarShip().QueueTotalRemoval();
                                        continue;
                                    }
                                }
                                else if (sortedList.Skip(skip).Count() > 0 && hangar.GetHangarShip().GetAI().EscortTarget == sortedList.Skip(skip).First())
                                {
                                    inboundOrdinance = inboundOrdinance + 50f;
                                    if (inboundOrdinance + sortedList.Skip(skip).First().Ordinance / sortedList.First().OrdinanceMax > .5f)
                                    {
                                        skip++;
                                        inboundOrdinance = 0;
                                        continue;
                                    }
                                }
                                continue;
                            }
                            if (!hangar.Active || hangar.hangarTimer > 0f || this.Owner.Ordinance < 50f || sortedList.Skip(skip).Count() <= 0)
                            {
                                continue;
                            }
                            inboundOrdinance = inboundOrdinance + 50f;
                            Ship shuttle = ResourceManager.CreateShipFromHangar(this.Owner.loyalty.data.StartingScout, this.Owner.loyalty, this.Owner.Center, this.Owner);
                            shuttle.VanityName = "Resupply Shuttle";
                            shuttle.Role = "supply";
                            shuttle.GetAI().IgnoreCombat = true;
                            shuttle.GetAI().DefaultAIState = AIState.Flee;
                            Ship ship1 = shuttle;
                            randomThreadMath = (this.Owner.GetSystem() != null ? this.Owner.GetSystem().RNG : ArtificialIntelligence.universeScreen.DeepSpaceRNG);
                            ship1.Velocity = (randomThreadMath.RandomDirection() * shuttle.speed) + this.Owner.Velocity;
                            if (shuttle.Velocity.Length() > shuttle.velocityMaximum)
                            {
                                shuttle.Velocity = Vector2.Normalize(shuttle.Velocity) * shuttle.speed;
                            }
                            float ord_amt = 50f;
                            Ship owner = this.Owner;
                            owner.Ordinance = owner.Ordinance - 50f;
                            hangar.SetHangarShip(shuttle);
                            ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.SupplyShip, Vector2.Zero, 0f);
                            shuttle.GetAI().EscortTarget = sortedList.Skip(skip).First();
                            g.VariableNumber = ord_amt;
                            shuttle.GetAI().IgnoreCombat = true;
                            shuttle.GetAI().OrderQueue.Clear();
                            shuttle.GetAI().OrderQueue.AddLast(g);
                            shuttle.GetAI().State = AIState.Ferrying;
                            break;
                        }
                    }

            }
            #endregion
            if (this.Owner.VanityName == "Resupply Shuttle" && this.Owner.Mothership == null)
            {
                {
                    this.Owner.QueueTotalRemoval();
                }
            }
            //}
            foreach (ArtificialIntelligence.ShipWeight nearbyShip in this.NearbyShips )
            //Parallel.ForEach(this.NearbyShips, nearbyShip =>
            {
                //opposition ship
                if (nearbyShip.ship.loyalty != this.Owner.loyalty)
                {
                    if (nearbyShip.ship.Weapons.Count ==0)
                    {
                        ArtificialIntelligence.ShipWeight vultureWeight = nearbyShip;
                        vultureWeight.weight = vultureWeight.weight + this.CombatAI.PirateWeight;
                    }

                    if (nearbyShip.ship.Health / nearbyShip.ship.HealthMax < 0.5f)
                    {
                        ArtificialIntelligence.ShipWeight vultureWeight = nearbyShip;
                        vultureWeight.weight = vultureWeight.weight + this.CombatAI.VultureWeight;
                    }
                    if (nearbyShip.ship.Size < 30)
                    {
                        ArtificialIntelligence.ShipWeight smallAttackWeight = nearbyShip;
                        smallAttackWeight.weight = smallAttackWeight.weight + this.CombatAI.SmallAttackWeight;
                    }
                    if (nearbyShip.ship.Size > 30 && nearbyShip.ship.Size < 100)
                    {
                        ArtificialIntelligence.ShipWeight mediumAttackWeight = nearbyShip;
                        mediumAttackWeight.weight = mediumAttackWeight.weight + this.CombatAI.MediumAttackWeight;
                    }
                    if (nearbyShip.ship.Size > 100)
                    {
                        ArtificialIntelligence.ShipWeight largeAttackWeight = nearbyShip;
                        largeAttackWeight.weight = largeAttackWeight.weight + this.CombatAI.LargeAttackWeight;
                    }
                    float rangeToTarget = Vector2.Distance(nearbyShip.ship.Center, this.Owner.Center);
                    if (rangeToTarget <= this.CombatAI.PreferredEngagementDistance)
                       // && Vector2.Distance(nearbyShip.ship.Center, this.Owner.Center) >= this.Owner.maxWeaponsRange)
                    {
                        ArtificialIntelligence.ShipWeight shipWeight = nearbyShip;
                        shipWeight.weight = shipWeight.weight + 2.5f;
                    }
                    else if (rangeToTarget > this.CombatAI.PreferredEngagementDistance)
                    {
                        ArtificialIntelligence.ShipWeight shipWeight1 = nearbyShip;
                        shipWeight1.weight = shipWeight1.weight - 2.5f *(rangeToTarget /(this.CombatAI.PreferredEngagementDistance+1));
                    }
                    if(nearbyShip.ship.Weapons.Count <1)
                    {
                        nearbyShip.weight -= 3;
                    }

                    foreach (ArtificialIntelligence.ShipWeight otherShip in this.NearbyShips)
                    {
                        if (otherShip.ship.loyalty != this.Owner.loyalty)
                        {
                            if (otherShip.ship.GetAI().Target != this.Owner)
                            {
                                continue;
                            }
                            ArtificialIntelligence.ShipWeight selfDefenseWeight = nearbyShip;
                            selfDefenseWeight.weight = selfDefenseWeight.weight + 0.2f * this.CombatAI.SelfDefenseWeight;
                        }
                        else if (otherShip.ship.GetAI().Target != nearbyShip.ship)
                        {
                            continue;
                        }
                    }

                }
                else
                {
                    this.NearbyShips.QueuePendingRemoval(nearbyShip);
                }

            }
               //this.PotentialTargets = this.NearbyShips.Where(loyalty=> loyalty.ship.loyalty != this.Owner.loyalty) .OrderBy(weight => weight.weight).Select(ship => ship.ship).ToList();
            //if (this.Owner.Role == "platform")
            //{
            //    this.NearbyShips.ApplyPendingRemovals();
            //    IEnumerable<ArtificialIntelligence.ShipWeight> sortedList =
            //        from potentialTarget in this.NearbyShips
            //        orderby Vector2.Distance(this.Owner.Center, potentialTarget.ship.Center)
            //        select potentialTarget;
            //    if (sortedList.Count<ArtificialIntelligence.ShipWeight>() > 0)
            //    {
            //        this.Target = sortedList.ElementAt<ArtificialIntelligence.ShipWeight>(0).ship;
            //    }
            //    return this.Target;
            //}
            this.NearbyShips.ApplyPendingRemovals();
            IEnumerable<ArtificialIntelligence.ShipWeight> sortedList2 =
                from potentialTarget in this.NearbyShips
                orderby potentialTarget.weight descending
                select potentialTarget;
            this.PotentialTargets = sortedList2.Select(ship => ship.ship)
                .ToList();

            //trackprojectiles in scan for targets.

            this.PotentialTargets = this.PotentialTargets.Where(potentialTarget => Vector2.Distance(potentialTarget.Center, this.Owner.Center) < this.CombatAI.PreferredEngagementDistance).ToList();
            if (sortedList2.Count<ArtificialIntelligence.ShipWeight>() > 0)
            {
                if (this.Owner.Role == "supply" && this.Owner.VanityName != "Resupply Shuttle")
                {
                    this.Target = sortedList2.ElementAt<ArtificialIntelligence.ShipWeight>(0).ship;
                }
                this.Target = sortedList2.ElementAt<ArtificialIntelligence.ShipWeight>(0).ship;
            }
            if (this.Owner.Weapons.Count > 0 || this.Owner.GetHangars().Count > 0)
                return this.Target;
            return null;
        }
        //added by gremlin to run away
        public void OrderFlee(bool ClearOrders)
        {
            lock (this.wayPointLocker)
            {
                this.ActiveWayPoints.Clear();
            }
            this.Target = null;
            this.Intercepting = false;
            this.Owner.HyperspaceReturn();
            if (ClearOrders)
            {
                this.OrderQueue.Clear();
            }

            IOrderedEnumerable<SolarSystem> systemList =
                from solarsystem in this.Owner.loyalty.GetOwnedSystems()
                where solarsystem.combatTimer <=0 && Vector2.Distance(solarsystem.Position,this.Owner.Position) >300000
                orderby Vector2.Distance(this.Owner.Center, solarsystem.Position)
                select solarsystem;
            if (systemList.Count<SolarSystem>() > 0)
            {
                Planet item = systemList.First<SolarSystem>().PlanetList[0];
                this.OrbitTarget = item;
                ArtificialIntelligence.ShipGoal orbit = new ArtificialIntelligence.ShipGoal(ArtificialIntelligence.Plan.Orbit, Vector2.Zero, 0f)
                {
                    TargetPlanet = item
                };
                this.resupplyTarget = item;
                this.OrderQueue.AddLast(orbit);
                this.State = AIState.Flee;
            }
        }
        private void LoadEverything(object sender, RunWorkerCompletedEventArgs ev)
        {
            bool stop;
            List<SolarSystem>.Enumerator enumerator;
            base.ScreenManager.inter.ObjectManager.Clear();
            this.data = new UniverseData();
            RandomEventManager.ActiveEvent = this.savedData.RandomEvent;
            UniverseScreen.DeepSpaceManager = new SpatialManager();
            this.ThrusterEffect = base.ScreenManager.Content.Load<Effect>("Effects/Thrust");
            int count = this.data.SolarSystemsList.Count;
            this.data.loadFogPath = this.savedData.FogMapName;
            this.data.difficulty = UniverseData.GameDifficulty.Normal;
            this.data.difficulty = this.savedData.gameDifficulty;
            this.data.Size = this.savedData.Size;
            this.data.FTLSpeedModifier = this.savedData.FTLModifier;
            this.data.EnemyFTLSpeedModifier = this.savedData.EnemyFTLModifier;
            this.data.GravityWells = this.savedData.GravityWells;
            //added by gremlin: adjuse projector radius to map size. but only normal or higher.
            //this is pretty bad as its not connected to the creating game screen code that sets the map sizes. If someone changes the map size they wont know to change this as well.
            if (this.data.Size.X > 7300000f)
            Empire.ProjectorRadius = this.data.Size.X / 70f;
            EmpireManager.EmpireList.Clear();
            if (Empire.universeScreen!=null && Empire.universeScreen.MasterShipList != null)
                Empire.universeScreen.MasterShipList.Clear();

            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e =new Empire();
                e.data = new EmpireData();
                    e= this.CreateEmpireFromEmpireSaveData(d);
                this.data.EmpireList.Add(e);
                if (e.data.Traits.Name == this.PlayerLoyalty)
                {
                    e.AutoColonize = this.savedData.AutoColonize;
                    e.AutoExplore = this.savedData.AutoExplore;
                    e.AutoFreighters = this.savedData.AutoFreighters;
                    e.AutoBuild = this.savedData.AutoProjectors;
                }
                EmpireManager.EmpireList.Add(e);
            }
            foreach (Empire e in this.data.EmpireList)
            {
                if (e.data.AbsorbedBy == null)
                {
                    continue;
                }
                foreach (KeyValuePair<string, TechEntry> tech in EmpireManager.GetEmpireByName(e.data.AbsorbedBy).GetTDict())
                {
                    if (!tech.Value.Unlocked)
                    {
                        continue;
                    }
                    EmpireManager.GetEmpireByName(e.data.AbsorbedBy).UnlockHullsSave(tech.Key, e.data.Traits.ShipType);
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                foreach (Relationship r in d.Relations)
                {
                    e.GetRelations().Add(EmpireManager.GetEmpireByName(r.Name), r);
                    if (r.ActiveWar == null)
                    {
                        continue;
                    }
                    r.ActiveWar.SetCombatants(e, EmpireManager.GetEmpireByName(r.Name));
                }
            }
            this.data.SolarSystemsList = new List<SolarSystem>();
            foreach (SavedGame.SolarSystemSaveData sdata in this.savedData.SolarSystemDataList)
            {
                SolarSystem system = this.CreateSystemFromData(sdata);
                system.guid = sdata.guid;
                this.data.SolarSystemsList.Add(system);
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.empireData.Traits.Name);
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    Ship ship = Ship.LoadSavedShip(shipData.data);
                    ship.guid = shipData.guid;
                    ship.Name = shipData.Name;
                    if (!string.IsNullOrEmpty(shipData.VanityName))
                        ship.VanityName = shipData.VanityName;
                    else
                    {
                        if (ship.Role == "troop")
                        {
                            if (shipData.TroopList.Count > 0)
                            {
                                ship.VanityName = shipData.TroopList[0].Name;
                            }
                            else
                                ship.VanityName = shipData.Name;
                        }
                        else
                            ship.VanityName = shipData.Name;
                    }
                    ship.Position = shipData.Position;
                    if (shipData.IsPlayerShip)
                    {
                        this.playerShip = ship;
                        this.playerShip.PlayerShip = true;
                        this.data.playerShip = this.playerShip;
                    }
                    ship.experience = shipData.experience;
                    ship.kills = shipData.kills;
                    if (!Ship_Game.ResourceManager.ShipsDict.ContainsKey(shipData.Name))
                    {
                        shipData.data.Hull = shipData.Hull;
                        Ship newShip = Ship.CreateShipFromShipData(shipData.data);
                        newShip.SetShipData(shipData.data);
                        if (!newShip.InitForLoad())
                        {
                            continue;
                        }
                        newShip.InitializeStatus();
                        newShip.IsPlayerDesign = false;
                        newShip.FromSave = true;
                        Ship_Game.ResourceManager.ShipsDict.Add(shipData.Name, newShip);
                    }
                    else if (Ship_Game.ResourceManager.ShipsDict[shipData.Name].FromSave)
                    {
                        ship.IsPlayerDesign = false;
                        ship.FromSave = true;
                    }
                    float oldbasestr = ship.BaseStrength;
                    float newbasestr = ResourceManager.CalculateBaseStrength(ship);
                    ship.BaseStrength = newbasestr;

                    foreach(ModuleSlotData moduleSD in shipData.data.ModuleSlotList)
                    {
                        ShipModule mismatch =null;
                        bool exists =ResourceManager.ShipModulesDict.TryGetValue(moduleSD.InstalledModuleUID,out mismatch);
                        if (exists)
                            continue;
                        System.Diagnostics.Debug.WriteLine(string.Concat("mismatch =", moduleSD.InstalledModuleUID));
                    }

                    ship.PowerCurrent = shipData.Power;
                    ship.yRotation = shipData.yRotation;
                    ship.Ordinance = shipData.Ordnance;
                    ship.Rotation = shipData.Rotation;
                    ship.Velocity = shipData.Velocity;
                    ship.isSpooling = shipData.AfterBurnerOn;
                    ship.InCombatTimer = shipData.InCombatTimer;
                    foreach (Troop t in shipData.TroopList)
                    {
                        t.SetOwner(EmpireManager.GetEmpireByName(t.OwnerString));
                        ship.TroopList.Add(t);
                    }

                    foreach (Rectangle AOO in shipData.AreaOfOperation)
                    {
                        ship.AreaOfOperation.Add(AOO);
                    }
                    ship.TetherGuid = shipData.TetheredTo;
                    ship.TetherOffset = shipData.TetherOffset;
                    if (ship.InCombatTimer > 0f)
                    {
                        ship.InCombat = true;
                    }
                    ship.loyalty = e;
                    ship.InitializeAI();
                    ship.GetAI().CombatState = shipData.data.CombatState;
                    ship.GetAI().FoodOrProd = shipData.AISave.FoodOrProd;
                    ship.GetAI().State = shipData.AISave.state;
                    ship.GetAI().DefaultAIState = shipData.AISave.defaultstate;
                    ship.GetAI().GotoStep = shipData.AISave.GoToStep;
                    ship.GetAI().MovePosition = shipData.AISave.MovePosition;
                    ship.GetAI().OrbitTargetGuid = shipData.AISave.OrbitTarget;
                    ship.GetAI().ColonizeTargetGuid = shipData.AISave.ColonizeTarget;
                    ship.GetAI().TargetGuid = shipData.AISave.AttackTarget;
                    ship.GetAI().SystemToDefendGuid = shipData.AISave.SystemToDefend;
                    ship.GetAI().EscortTargetGuid = shipData.AISave.EscortTarget;
                    bool hasCargo = false;
                    if (shipData.FoodCount > 0f)
                    {
                        ship.AddGood("Food", (int)shipData.FoodCount);
                        ship.GetAI().FoodOrProd = "Food";
                        hasCargo = true;
                    }
                    if (shipData.ProdCount > 0f)
                    {
                        ship.AddGood("Production", (int)shipData.ProdCount);
                        ship.GetAI().FoodOrProd = "Prod";
                        hasCargo = true;
                    }
                    if (shipData.PopCount > 0f)
                    {
                        ship.AddGood("Colonists_1000", (int)shipData.PopCount);
                    }
                    AIState state = ship.GetAI().State;
                    if (state == AIState.SystemTrader)
                    {
                        ship.GetAI().OrderTradeFromSave(hasCargo, shipData.AISave.startGuid, shipData.AISave.endGuid);
                    }
                    else if (state == AIState.PassengerTransport)
                    {
                        ship.GetAI().OrderTransportPassengersFromSave();
                    }
                    e.AddShip(ship);
                    foreach (SavedGame.ProjectileSaveData pdata in shipData.Projectiles)
                    {
                        Weapon w = Ship_Game.ResourceManager.GetWeapon(pdata.Weapon);
                        Projectile p = w.LoadProjectiles(pdata.Velocity, ship);
                        p.Velocity = pdata.Velocity;
                        p.Position = pdata.Position;
                        p.Center = pdata.Position;
                        p.duration = pdata.Duration;
                        ship.Projectiles.Add(p);
                    }
                    this.data.MasterShipList.Add(ship);
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                foreach (SavedGame.FleetSave fleetsave in d.FleetsList)
                {
                    Ship_Game.Gameplay.Fleet fleet = new Ship_Game.Gameplay.Fleet()
                    {
                        guid = fleetsave.FleetGuid,
                        IsCoreFleet = fleetsave.IsCoreFleet,
                        facing = fleetsave.facing
                    };
                    foreach (SavedGame.FleetShipSave ssave in fleetsave.ShipsInFleet)
                    {
                        foreach (Ship ship in this.data.MasterShipList)
                        {
                            if (ship.guid != ssave.shipGuid)
                            {
                                continue;
                            }
                            ship.RelativeFleetOffset = ssave.fleetOffset;
                            fleet.AddShip(ship);
                        }
                    }
                    foreach (FleetDataNode node in fleetsave.DataNodes)
                    {
                        fleet.DataNodes.Add(node);
                    }
                    foreach (FleetDataNode node in fleet.DataNodes)
                    {
                        foreach (Ship ship in fleet.Ships)
                        {
                            if (!(node.ShipGuid != Guid.Empty) || !(ship.guid == node.ShipGuid))
                            {
                                continue;
                            }
                            node.SetShip(ship);
                            node.ShipName = ship.Name;
                            break;
                        }
                    }
                    fleet.AssignPositions(fleet.facing);
                    fleet.Name = fleetsave.Name;
                    fleet.TaskStep = fleetsave.TaskStep;
                    fleet.Owner = e;
                    fleet.Position = fleetsave.Position;

                    if (e.GetFleetsDict().ContainsKey(fleetsave.Key))
                    {
                        e.GetFleetsDict()[fleetsave.Key] = fleet;
                    }
                    else
                    {
                        e.GetFleetsDict().TryAdd(fleetsave.Key, fleet);
                    }
                    e.GetFleetsDict()[fleetsave.Key].SetSpeed();
                    fleet.findAveragePositionset();
                    fleet.Setavgtodestination();

                }
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    foreach (Ship ship in e.GetShips())
                    {
                        if (ship.Position != shipData.Position)
                        {
                            continue;
                        }
                    }
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                e.SpaceRoadsList = new List<SpaceRoad>();
                foreach (SavedGame.SpaceRoadSave roadsave in d.SpaceRoadData)
                {
                    SpaceRoad road = new SpaceRoad();
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        if (roadsave.OriginGUID == s.guid)
                        {
                            road.SetOrigin(s);
                        }
                        if (roadsave.DestGUID != s.guid)
                        {
                            continue;
                        }
                        road.SetDestination(s);
                    }
                    foreach (SavedGame.RoadNodeSave nodesave in roadsave.RoadNodes)
                    {
                        RoadNode node = new RoadNode();
                        foreach (Ship s in this.data.MasterShipList)
                        {
                            if (nodesave.Guid_Platform != s.guid)
                            {
                                continue;
                            }
                            node.Platform = s;
                        }
                        node.Position = nodesave.Position;
                        road.RoadNodesList.Add(node);
                    }
                    e.SpaceRoadsList.Add(road);
                }
                foreach (SavedGame.GoalSave gsave in d.GSAIData.Goals)
                {
                    Goal g = new Goal()
                    {
                        empire = e,
                        type = gsave.type
                    };
                    if (g.type == GoalType.BuildShips && gsave.ToBuildUID != null && !Ship_Game.ResourceManager.ShipsDict.ContainsKey(gsave.ToBuildUID))
                    {
                        continue;
                    }
                    g.ToBuildUID = gsave.ToBuildUID;
                    g.Step = gsave.GoalStep;
                    g.guid = gsave.GoalGuid;
                    g.GoalName = gsave.GoalName;
                    g.BuildPosition = gsave.BuildPosition;
                    if (gsave.fleetGuid != Guid.Empty)
                    {
                        foreach (KeyValuePair<int, Ship_Game.Gameplay.Fleet> Fleet in e.GetFleetsDict())
                        {
                            if (Fleet.Value.guid != gsave.fleetGuid)
                            {
                                continue;
                            }
                            g.SetFleet(Fleet.Value);
                        }
                    }
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        foreach (Planet p in s.PlanetList)
                        {
                            if (p.guid == gsave.planetWhereBuildingAtGuid)
                            {
                                g.SetPlanetWhereBuilding(p);
                            }
                            if (p.guid != gsave.markedPlanetGuid)
                            {
                                continue;
                            }
                            g.SetMarkedPlanet(p);
                        }
                    }
                    foreach (Ship s in this.data.MasterShipList)
                    {
                        if (gsave.colonyShipGuid == s.guid)
                        {
                            g.SetColonyShip(s);
                        }
                        if (gsave.beingBuiltGUID != s.guid)
                        {
                            continue;
                        }
                        g.SetBeingBuilt(s);
                    }
                    e.GetGSAI().Goals.Add(g);
                }
                for (int i = 0; i < d.GSAIData.PinGuids.Count; i++)
                {
                    e.GetGSAI().ThreatMatrix.Pins.TryAdd(d.GSAIData.PinGuids[i], d.GSAIData.PinList[i]);
                }
                e.GetGSAI().UsedFleets = d.GSAIData.UsedFleets;
                lock (GlobalStats.TaskLocker)
                {
                    foreach (MilitaryTask task in d.GSAIData.MilitaryTaskList)
                    {
                        task.SetEmpire(e);
                        e.GetGSAI().TaskList.Add(task);
                        if (task.TargetPlanetGuid != Guid.Empty)
                        {
                            enumerator = this.data.SolarSystemsList.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    SolarSystem s = enumerator.Current;
                                    stop = false;
                                    foreach (Planet p in s.PlanetList)
                                    {
                                        if (p.guid != task.TargetPlanetGuid)
                                        {
                                            continue;
                                        }
                                        task.SetTargetPlanet(p);
                                        stop = true;
                                        break;
                                    }
                                }
                                while (!stop);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        foreach (Guid guid in task.HeldGoals)
                        {
                            foreach (Goal g in e.GetGSAI().Goals)
                            {
                                if (g.guid != guid)
                                {
                                    continue;
                                }
                                g.Held = true;
                            }
                        }
                        try
                        {
                            if (task.WhichFleet != -1)
                            {
                                e.GetFleetsDict()[task.WhichFleet].Task = task;
                            }
                        }
                        catch
                        {
                            task.WhichFleet = 0;
                        }
                    }
                }
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    foreach (Ship ship in this.data.MasterShipList)
                    {
                        if (ship.guid != shipData.guid)
                        {
                            continue;
                        }
                        foreach (Vector2 waypoint in shipData.AISave.ActiveWayPoints)
                        {
                            ship.GetAI().ActiveWayPoints.Enqueue(waypoint);
                        }
                        foreach (SavedGame.ShipGoalSave sg in shipData.AISave.ShipGoalsList)
                        {
                            ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(sg.Plan, sg.MovePosition, sg.FacingVector);
                            foreach (SolarSystem s in this.data.SolarSystemsList)
                            {
                                foreach (Planet p in s.PlanetList)
                                {
                                    if (sg.TargetPlanetGuid == p.guid)
                                    {
                                        g.TargetPlanet = p;
                                        ship.GetAI().ColonizeTarget = p;
                                    }
                                    if (p.guid == shipData.AISave.startGuid)
                                    {
                                        ship.GetAI().start = p;
                                    }
                                    if (p.guid != shipData.AISave.endGuid)
                                    {
                                        continue;
                                    }
                                    ship.GetAI().end = p;
                                }
                            }
                            if (sg.fleetGuid != Guid.Empty)
                            {
                                foreach (KeyValuePair<int, Ship_Game.Gameplay.Fleet> fleet in e.GetFleetsDict())
                                {
                                    if (fleet.Value.guid != sg.fleetGuid)
                                    {
                                        continue;
                                    }
                                    g.fleet = fleet.Value;
                                }
                            }
                            g.VariableString = sg.VariableString;
                            g.DesiredFacing = sg.DesiredFacing;
                            g.SpeedLimit = sg.SpeedLimit;
                            foreach (Goal goal in ship.loyalty.GetGSAI().Goals)
                            {
                                if (sg.goalGuid != goal.guid)
                                {
                                    continue;
                                }
                                g.goal = goal;
                            }
                            ship.GetAI().OrderQueue.AddLast(g);
                        }
                    }
                }
            }
            foreach (SavedGame.SolarSystemSaveData sdata in this.savedData.SolarSystemDataList)
            {
                foreach (SavedGame.RingSave rsave in sdata.RingList)
                {
                    Planet p = new Planet();
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        foreach (Planet p1 in s.PlanetList)
                        {
                            if (p1.guid != rsave.Planet.guid)
                            {
                                continue;
                            }
                            p = p1;
                            break;
                        }
                    }
                    if (p.Owner == null)
                    {
                        continue;
                    }
                    foreach (SavedGame.QueueItemSave qisave in rsave.Planet.QISaveList)
                    {
                        QueueItem qi = new QueueItem();
                        if (qisave.isBuilding)
                        {
                            qi.isBuilding = true;
                            qi.Building = Ship_Game.ResourceManager.BuildingsDict[qisave.UID];
                            qi.Cost = qi.Building.Cost * this.savedData.GamePacing;
                            qi.NotifyOnEmpty = false;
                            foreach (PlanetGridSquare pgs in p.TilesList)
                            {
                                if ((float)pgs.x != qisave.pgsVector.X || (float)pgs.y != qisave.pgsVector.Y)
                                {
                                    continue;
                                }
                                pgs.QItem = qi;
                                qi.pgs = pgs;
                                break;
                            }
                        }
                        if (qisave.isTroop)
                        {
                            qi.isTroop = true;
                            qi.troop = Ship_Game.ResourceManager.TroopsDict[qisave.UID];
                            qi.Cost = qi.troop.GetCost();
                            qi.NotifyOnEmpty = false;
                        }
                        if (qisave.isShip)
                        {
                            qi.isShip = true;
                            if (!Ship_Game.ResourceManager.ShipsDict.ContainsKey(qisave.UID))
                            {
                                continue;
                            }
                            qi.sData = Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData();
                            qi.DisplayName = qisave.DisplayName;
                            qi.Cost = 0f;
                            foreach (ModuleSlot slot in Ship_Game.ResourceManager.GetShip(qisave.UID).ModuleSlotList)
                            {
                                if (slot.InstalledModuleUID == null)
                                {
                                    continue;
                                }
                                QueueItem cost = qi;
                                cost.Cost = cost.Cost + Ship_Game.ResourceManager.GetModule(slot.InstalledModuleUID).Cost * this.savedData.GamePacing;
                            }
                            QueueItem queueItem = qi;
                            queueItem.Cost += qi.Cost * p.Owner.data.Traits.ShipCostMod;
                            queueItem.Cost *= (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useHullBonuses && ResourceManager.HullBonuses.ContainsKey(Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData().Hull) ? 1f - ResourceManager.HullBonuses[Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData().Hull].CostBonus : 1);
                            if (qi.sData.HasFixedCost)
                            {
                                qi.Cost = (float)qi.sData.FixedCost;
                            }
                            if (qisave.IsRefit)
                            {
                                qi.isRefit = true;
                                qi.Cost = qisave.RefitCost;
                            }
                        }
                        foreach (Goal g in p.Owner.GetGSAI().Goals)
                        {
                            if (g.guid != qisave.GoalGUID)
                            {
                                continue;
                            }
                            qi.Goal = g;
                            qi.NotifyOnEmpty = false;
                        }
                        if (qisave.isShip && qi.Goal != null)
                        {
                            qi.Goal.beingBuilt = Ship_Game.ResourceManager.GetShip(qisave.UID);
                        }
                        qi.productionTowards = qisave.ProgressTowards;
                        p.ConstructionQueue.Add(qi);
                    }
                }
            }
            this.Loaded = true;
        }