//added by gremlin deveksmod military planner
        private void RunMilitaryPlanner()
        {
            float SizeLimiter = GlobalStats.MemoryLimiter;
             int ShipCountLimit = GlobalStats.ShipCountLimit;
            List<AO>.Enumerator enumerator;
            if(!this.empire.MinorRace)
                this.RunGroundPlanner();
            this.numberOfShipGoals = 0;
            foreach (Planet p in this.empire.GetPlanets())
            {
               // if (!p.HasShipyard || (p.GetMaxProductionPotential() <2f
                if ((p.GetMaxProductionPotential() < 2f //||( this.empire.data.Traits.Cybernetic !=0 && p.GetMaxProductionPotential()-p.consumption <2f)
                    || p.ps == Planet.GoodState.IMPORT
                    ))   //p.GetNetProductionPerTurn() < .5f))
                {
                    continue;
                }

                this.numberOfShipGoals = this.numberOfShipGoals + (int)((p.ProductionHere)/50); //(int)(p.ProductionHere /(1+ p.ConstructionQueue.Sum(q => q.Cost)));
            }
            float numgoals = 0f;
            float offenseUnderConstruction = 0f;
            float UnderConstruction = 0f;
            float TroopStrengthUnderConstruction = 0f;
            foreach (Goal g in this.Goals)
            //Parallel.ForEach(this.Goals, g =>
            {
                if (g.GoalName == "BuildOffensiveShips")
                {
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                    {
                        UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                    }
                    else
                    {
                        UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                    }
                    offenseUnderConstruction += ResourceManager.ShipsDict[g.ToBuildUID].BaseStrength;
                    foreach (Troop t in ResourceManager.ShipsDict[g.ToBuildUID].TroopList)
                    {
                        TroopStrengthUnderConstruction = TroopStrengthUnderConstruction + (float)t.Strength;
                    }
                    numgoals = numgoals + 1f;
                }
                if (g.GoalName != "BuildConstructionShip")
                {
                    continue;
                }
                if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                {
                    UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                }
                else
                {
                    UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                }
            }
            //this.GetAShip(0);
            //float offensiveStrength = offenseUnderConstruction + this.empire.GetForcePoolStrength();

            bool atWar = this.empire.GetRelations().Where(war => war.Value.AtWar).Count() > 0;
            //int prepareWar = this.empire.GetRelations().Where(angry => angry.Value.TotalAnger > angry.Value.Trust).Count();
            //prepareWar += this.empire.GetRelations().Where(angry => angry.Value.PreparingForWar).Count();
            float noIncome = this.FindTaxRateToReturnAmount(UnderConstruction);

            //float tax = atWar ? .40f + (prepareWar * .05f) : .25f + (prepareWar * .05f);  //.45f - (tasks);
            //float offenseNeeded = this.empire.GetRelations().Where(war => war.Value.AtWar || war.Value.PreparingForWar || war.Value.Trust < war.Value.TotalAnger).Sum(power => power.Key.currentMilitaryStrength);
            float offenseNeeded =  this.empire.GetRelations().Where(war => !war.Key.isFaction && war.Value.AtWar || war.Value.PreparingForWar).Sum(power => power.Key.currentMilitaryStrength);
            float offenseNeededThreat = this.ThreatMatrix.Pins.Values.Sum(power => power.Strength); //.Where(faction=>  EmpireManager.GetEmpireByName(faction.EmpireName).isFaction).Sum(power => power.Strength);
            //if (offenseNeededThreat > 0)
            //    System.Diagnostics.Debug.WriteLine("threat: " + offenseNeededThreat);
            float offenseNeededRatio = ((offenseNeeded  + offenseNeededThreat)+1) / (this.empire.currentMilitaryStrength +1);
            //float prepareWar2 = this.empire.GetRelations().Where(angry => angry.Value.TotalAnger > angry.Value.Trust).Sum(power => power.Key.currentMilitaryStrength / (power.Value.Trust /power.Value.TotalAnger) );

            //float tax = offenseNeededRatio > 0.0 ? offenseNeededRatio * (.6f - (this.empire.data.TaxRate)) : this.empire.data.TaxRate;
            float tax = offenseNeededRatio*.1f;// > 0.0 ? offenseNeededRatio * (.6f - (this.empire.data.TaxRate)) : this.empire.data.TaxRate;
            if (tax > .25f)
                tax = .25f;
            else
                if (tax < .05f)
                    tax = .05f;

            //float Capacity = this.empire.EstimateIncomeAtTaxRate(tax) + this.empire.Money * -.1f -UnderConstruction + this.empire.GetAverageNetIncome();
            float Capacity = this.empire.Money * .1f - UnderConstruction -this.empire.GetTotalShipMaintenance();// +this.empire.GetAverageNetIncome();
            float allowable_deficit = this.empire.Money * -.1f; //>0?(1 - (this.empire.Money * 10 / this.empire.Money)):0); //-Capacity;// +(this.empire.Money * -.1f);
                //-Capacity;

            //if ((allowable_deficit >= 0f || noIncome >.5f) && atWar)
            //{
            //    allowable_deficit = -(this.empire.Money*.5f );//- this.empire.GrossTaxes );// 0f;
            //}

            this.buildCapacity = Capacity - allowable_deficit;// +this.empire.GetTotalShipMaintenance(); ;
                //this.empire.GetTotalShipMaintenance();

            this.GetAShip(0);
            if (Capacity <= allowable_deficit )//|| (this.empire.data.TaxRate >=.5f && this.empire.GetAverageNetIncome()<0)) //(Capacity <= 0f)
            {
                float HowMuchWeAreScrapping = 0f;

                foreach (Ship ship1 in this.empire.GetShips())
                {
                    if (ship1.GetAI().State != AIState.Scrap)
                    {
                        continue;
                    }
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                    {
                        HowMuchWeAreScrapping = HowMuchWeAreScrapping + ship1.GetMaintCostRealism();
                    }
                    else
                    {
                        HowMuchWeAreScrapping = HowMuchWeAreScrapping + ship1.GetMaintCost(this.empire);
                    }
                }
                if (HowMuchWeAreScrapping < Math.Abs(Capacity))
                {
                    float Added = 0f;

                    //added by gremlin clear out building ships before active ships.
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                    {
                        foreach (Goal g in this.Goals.Where(goal => goal.GoalName == "BuildOffensiveShips").OrderByDescending(goal => ResourceManager.ShipsDict[goal.ToBuildUID].GetMaintCostRealism()))
                        {
                            bool flag = false;
                            if (g.GetPlanetWhereBuilding() == null)
                                continue;
                            foreach (QueueItem shipToRemove in g.GetPlanetWhereBuilding().ConstructionQueue)
                            {

                                if (shipToRemove.Goal != g)
                                {
                                    continue;

                                }
                                g.GetPlanetWhereBuilding().ProductionHere += shipToRemove.productionTowards;
                                g.GetPlanetWhereBuilding().ConstructionQueue.QueuePendingRemoval(shipToRemove);
                                this.Goals.QueuePendingRemoval(g);
                                Added += ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                                flag = true;
                                break;

                            }
                            if (flag)
                                g.GetPlanetWhereBuilding().ConstructionQueue.ApplyPendingRemovals();

                        }
                    }
                    else
                    {
                        foreach (Goal g in this.Goals.Where(goal => goal.GoalName == "BuildOffensiveShips").OrderByDescending(goal => ResourceManager.ShipsDict[goal.ToBuildUID].GetMaintCost(this.empire)))
                        {
                            bool flag = false;
                            if (g.GetPlanetWhereBuilding() == null)
                                continue;
                            foreach (QueueItem shipToRemove in g.GetPlanetWhereBuilding().ConstructionQueue)
                            {

                                if (shipToRemove.Goal != g)
                                {
                                    continue;

                                }
                                g.GetPlanetWhereBuilding().ProductionHere += shipToRemove.productionTowards;
                                g.GetPlanetWhereBuilding().ConstructionQueue.QueuePendingRemoval(shipToRemove);
                                this.Goals.QueuePendingRemoval(g);
                                Added += ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                                flag = true;
                                break;

                            }
                            if (flag)
                                g.GetPlanetWhereBuilding().ConstructionQueue.ApplyPendingRemovals();

                        }
                    }

                    this.Goals.ApplyPendingRemovals();

                }

            }
            //Capacity = this.empire.EstimateIncomeAtTaxRate(tax) - UnderConstruction;

            //if (allowable_deficit > 0f || noIncome > tax)
            //{
            //    allowable_deficit = Math.Abs(allowable_deficit);
            //}

            while (Capacity > 0 //this.buildCapacity > 0 //Capacity > allowable_deficit
                && numgoals < this.numberOfShipGoals
                && (Empire.universeScreen.globalshipCount < ShipCountLimit+ recyclepool
                || this.empire.empireShipTotal <this.empire.EmpireShipCountReserve)) //shipsize < SizeLimiter)
            {

                string s = this.GetAShip(this.buildCapacity-allowable_deficit);//Capacity - allowable_deficit);
                if (s == null)
                {
                    break;
                }
                if(this.recyclepool>0)
                {
                    this.recyclepool--;
                }

                Goal g = new Goal(s, "BuildOffensiveShips", this.empire)
                {
                    type = GoalType.BuildShips
                };
                this.Goals.Add(g);
                if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                {
                    Capacity = Capacity - ResourceManager.ShipsDict[s].GetMaintCostRealism();
                }
                else
                {
                    Capacity = Capacity - ResourceManager.ShipsDict[s].GetMaintCost(this.empire);
                }
                numgoals = numgoals + 1f;
            }

            //this.GetAShip(0);
            int numWars = 0;
            foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
            {
                if (!Relationship.Value.AtWar || Relationship.Key.isFaction)
                {
                    continue;
                }
                numWars++;
            }
            foreach (Goal g in this.Goals)
            //Parallel.ForEach(this.Goals, g =>
            {
                if (g.type != GoalType.Colonize || g.Held)
                {
                    if (g.type != GoalType.Colonize || !g.Held || g.GetMarkedPlanet().Owner == null)
                    {
                        continue;
                    }
                    foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
                    {
                        this.empire.GetGSAI().CheckClaim(Relationship, g.GetMarkedPlanet());
                    }
                    this.Goals.QueuePendingRemoval(g);
                    lock (GlobalStats.TaskLocker)
                    {
                        foreach (MilitaryTask task in this.TaskList)
                        {
                            foreach (Guid held in task.HeldGoals)
                            {
                                if (held != g.guid)
                                {
                                    continue;
                                }
                                this.TaskList.QueuePendingRemoval(task);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (g.GetMarkedPlanet() != null)
                    {
                        foreach (KeyValuePair<Guid, ThreatMatrix.Pin> pin in this.ThreatMatrix.Pins.Where(pin => !((Vector2.Distance(g.GetMarkedPlanet().Position, pin.Value.Position) >= 75000f) || EmpireManager.GetEmpireByName(pin.Value.EmpireName) == this.empire || pin.Value.Strength <= 0f || !this.empire.GetRelations()[EmpireManager.GetEmpireByName(pin.Value.EmpireName)].AtWar)))
                        {
                            if (Vector2.Distance(g.GetMarkedPlanet().Position, pin.Value.Position) >= 75000f || EmpireManager.GetEmpireByName(pin.Value.EmpireName) == this.empire || pin.Value.Strength <= 0f || !this.empire.GetRelations()[EmpireManager.GetEmpireByName(pin.Value.EmpireName)].AtWar && !EmpireManager.GetEmpireByName(pin.Value.EmpireName).isFaction)
                            {
                                continue;
                            }
                            List<Goal> tohold = new List<Goal>()
                        {
                            g
                        };
                            MilitaryTask task = new MilitaryTask(g.GetMarkedPlanet().Position, 125000f, tohold, this.empire);
                            lock (GlobalStats.TaskLocker)
                            {
                                this.TaskList.Add(task);
                                break;
                            }
                        }
                    }
                }
            }
            if (this.empire.data.DiplomaticPersonality.Name == "Aggressive" || this.empire.data.DiplomaticPersonality.Name == "Ruthless" || this.empire.data.EconomicPersonality.Name == "Expansionist")
            {
                foreach (Goal g in this.Goals)
                {
                    if (g.type != GoalType.Colonize || g.Held)
                    {
                        continue;
                    }
                    bool OK = true;
                    lock (GlobalStats.TaskLocker)
                    {
                        foreach (MilitaryTask mt in this.TaskList)
                        //Parallel.ForEach(this.TaskList, (mt,state) =>
                        {
                            if ((mt.type != MilitaryTask.TaskType.DefendClaim
                                && mt.type != MilitaryTask.TaskType.ClearAreaOfEnemies )
                                || g.GetMarkedPlanet() != null
                                && !(mt.TargetPlanetGuid == g.GetMarkedPlanet().guid))

                            {
                                continue;
                            }
                            OK = false;
                            break;
                        }
                    }
                    if (!OK)
                    {
                        continue;
                    }
                    if (g.GetMarkedPlanet() == null)
                        continue;
                    MilitaryTask task = new MilitaryTask()
                    {
                        AO = g.GetMarkedPlanet().Position
                    };
                    task.SetEmpire(this.empire);
                    task.AORadius = 75000f;
                    task.SetTargetPlanet(g.GetMarkedPlanet());
                    task.TargetPlanetGuid = g.GetMarkedPlanet().guid;
                    task.type = MilitaryTask.TaskType.DefendClaim;
                    lock (GlobalStats.TaskLocker)
                    {
                        this.TaskList.Add(task);
                    }
                }
            }
            this.Goals.ApplyPendingRemovals();
            lock (GlobalStats.TaskLocker)
            {
                List<MilitaryTask> ToughNuts = new List<MilitaryTask>();
                List<MilitaryTask> InOurSystems = new List<MilitaryTask>();
                List<MilitaryTask> InOurAOs = new List<MilitaryTask>();
                List<MilitaryTask> Remainder = new List<MilitaryTask>();
                foreach (MilitaryTask task in this.TaskList.OrderBy(target=> target.GetTargetPlanet()!=null ? Vector2.Distance(target.GetTargetPlanet().Position,this.empire.GetWeightedCenter()):0f))
                {
                    if (task.type != MilitaryTask.TaskType.AssaultPlanet)
                    {
                        continue;
                    }
                    if (task.IsToughNut)
                    {
                        ToughNuts.Add(task);
                    }
                    else if (!this.empire.GetOwnedSystems().Contains(task.GetTargetPlanet().system))
                    {
                        bool dobreak = false;
                        foreach (KeyValuePair<Guid, Planet> entry in Ship.universeScreen.PlanetsDict)
                        {
                            if (task.GetTargetPlanet() != entry.Value)
                            {
                                continue;
                            }
                            enumerator = this.AreasOfOperations.GetEnumerator();
                            try
                            {
                                while (enumerator.MoveNext())
                                {
                                    AO area = enumerator.Current;
                                    if (Vector2.Distance(entry.Value.Position, area.Position) >= area.Radius)
                                    {
                                        continue;
                                    }
                                    InOurAOs.Add(task);
                                    dobreak = true;
                                    break;
                                }
                                break;
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        if (dobreak)
                        {
                            continue;
                        }
                        Remainder.Add(task);
                    }
                    else
                    {
                        InOurSystems.Add(task);
                    }
                }
                List<MilitaryTask> TNInOurSystems = new List<MilitaryTask>();
                List<MilitaryTask> TNInOurAOs = new List<MilitaryTask>();
                List<MilitaryTask> TNRemainder = new List<MilitaryTask>();
                foreach (MilitaryTask task in ToughNuts)
                {
                    if (!this.empire.GetOwnedSystems().Contains(task.GetTargetPlanet().system))
                    {
                        bool dobreak = false;
                        foreach (KeyValuePair<Guid, Planet> entry in Ship.universeScreen.PlanetsDict)
                        {
                            if (task.GetTargetPlanet() != entry.Value)
                            {
                                continue;
                            }
                            enumerator = this.AreasOfOperations.GetEnumerator();
                            try
                            {
                                while (enumerator.MoveNext())
                                {
                                    AO area = enumerator.Current;
                                    if (Vector2.Distance(entry.Value.Position, area.Position) >= area.Radius)
                                    {
                                        continue;
                                    }
                                    TNInOurAOs.Add(task);
                                    dobreak = true;
                                    break;
                                }
                                break;
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        if (dobreak)
                        {
                            continue;
                        }
                        TNRemainder.Add(task);
                    }
                    else
                    {
                        TNInOurSystems.Add(task);
                    }
                }
                foreach (MilitaryTask task in TNInOurAOs.OrderBy(target=>  Vector2.Distance(target.GetTargetPlanet().Position,this.empire.GetWeightedCenter())))
                //Parallel.ForEach(TNInOurAOs, task =>
                {
                    if (task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner == this.empire || this.empire.GetRelations()[task.GetTargetPlanet().Owner].ActiveWar == null || (float)this.empire.TotalScore <= (float)task.GetTargetPlanet().Owner.TotalScore * 1.5f)
                    {
                        continue;
                        //return;
                    }
                    task.Evaluate(this.empire);
                }//);
                foreach (MilitaryTask task in TNInOurSystems)
                //Parallel.ForEach(TNInOurSystems, task =>
                {
                    task.Evaluate(this.empire);
                }//);
                foreach (MilitaryTask task in TNRemainder)
                {
                    if (task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner == this.empire || this.empire.GetRelations()[task.GetTargetPlanet().Owner].ActiveWar == null || (float)this.empire.TotalScore <= (float)task.GetTargetPlanet().Owner.TotalScore * 1.5f)
                    {
                        continue;
                    }
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in InOurAOs)
                {
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in InOurSystems)
                {
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in Remainder)
                {
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in this.TaskList)
                {
                    if (task.type != MilitaryTask.TaskType.AssaultPlanet)
                    {
                        task.Evaluate(this.empire);
                    }
                    if (task.type != MilitaryTask.TaskType.AssaultPlanet && task.type != MilitaryTask.TaskType.GlassPlanet || task.GetTargetPlanet().Owner != null && task.GetTargetPlanet().Owner != this.empire)
                    {
                        continue;
                    }
                    task.EndTask();
                }
                this.TaskList.AddRange(this.TasksToAdd);
                this.TasksToAdd.Clear();
                this.TaskList.ApplyPendingRemovals();
            }
        }
        private void DoAssaultPlanet(MilitaryTask Task)
        {
            if (Task.GetTargetPlanet().Owner == this.Owner || Task.GetTargetPlanet().Owner == null || Task.GetTargetPlanet().Owner != null && !this.Owner.GetRelations()[Task.GetTargetPlanet().Owner].AtWar)
            {
                if (Task.GetTargetPlanet().Owner == this.Owner)
                {
                    MilitaryTask militaryTask = new MilitaryTask();
                    militaryTask.AO = Task.GetTargetPlanet().Position;
                    militaryTask.AORadius = 50000f;
                    militaryTask.WhichFleet = Task.WhichFleet;
                    militaryTask.SetEmpire(this.Owner);
                    militaryTask.type = MilitaryTask.TaskType.DefendPostInvasion;
                    this.Owner.GetGSAI().TaskList.QueuePendingRemoval(Task);
                    this.Task = militaryTask;
                    lock (GlobalStats.TaskLocker)
                        this.Owner.GetGSAI().TaskList.Add(Task);
                }
                else
                    Task.EndTask();
            }
            else
            {
                float num1 = 0.0f;
                foreach (Ship ship in (List<Ship>)this.Ships)
                    num1 += ship.GetStrength();
                if ((double)num1 == 0.0)
                    Task.EndTask();
                int num2 = 0;
                int num3 = 0;
                foreach (Ship ship in (List<Ship>)this.Ships)
                {
                    if ((double)ship.GetStrength() > 0.0)
                        ++num3;
                    num2 += ship.TroopList.Count;
                }
                if (num2 == 0)
                {
                    foreach (Troop troop in Task.GetTargetPlanet().TroopsHere)
                    {
                        if (troop.GetOwner() == this.Owner)
                            ++num2;
                    }
                }
                if (num2 == 0 || num3 == 0)
                {
                    if (num3 == 0)
                        Task.IsCoreFleetTask = false;
                    Task.EndTask();
                    this.Task = (MilitaryTask)null;
                    this.TaskStep = 0;
                }
                else
                {
                    switch (this.TaskStep)
                    {
                        case 0:
                            List<Planet> list1 = new List<Planet>();
                            this.Owner.GetPlanets().thisLock.EnterReadLock();
                            foreach (Planet planet in this.Owner.GetPlanets().OrderBy(combat=> combat.ParentSystem.DangerTimer))
                            {
                                if (planet.HasShipyard )
                                    list1.Add(planet);
                            }
                            this.Owner.GetPlanets().thisLock.ExitReadLock();
                            IOrderedEnumerable<Planet> orderedEnumerable1 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list1, (Func<Planet, float>)(planet => Vector2.Distance(Task.AO, planet.Position)));
                            if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable1) > 0)
                            {
                                Vector2 fVec = Vector2.Normalize(Task.AO - Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position);
                                Vector2 vector2 = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position;
                                this.MoveToNow(vector2, Math.Abs(MathHelper.ToRadians(HelperFunctions.findAngleToTarget(vector2, Task.AO))), fVec);
                                foreach (Ship ship in (List<Ship>)this.Ships)
                                    ship.GetAI().HasPriorityOrder = true;
                                this.TaskStep = 1;
                                break;
                            }
                            else
                            {
                                Task.EndTask();
                                break;
                            }
                        case 1:
                            bool flag1 = true;
                            this.Ships.thisLock.EnterReadLock();
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                if (!ship.disabled && ship.hasCommand && ship.Active)
                                {
                                    if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 5000.0)
                                    {
                                        flag1 = false;
                                        this.Ships.thisLock.ExitReadLock();
                                    }
                                    else if (ship.GetAI().BadGuysNear)
                                    {
                                        this.Ships.thisLock.ExitReadLock();
                                        Task.EndTask();
                                        flag1 = false;

                                    }
                                    int num4 = ship.InCombat ? 1 : 0;
                                    if (!flag1)
                                        break;
                                }
                            }

                            if (!flag1)
                                break;
                            this.Ships.thisLock.ExitReadLock();
                            this.TaskStep = 2;
                            Vector2 MovePosition = Task.GetTargetPlanet().Position + Vector2.Normalize(this.findAveragePosition() - Task.GetTargetPlanet().Position) * 125000f;
                            this.Position = MovePosition;
                            this.FormationWarpTo(MovePosition, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.findAveragePosition(), Task.AO)), Vector2.Normalize(Task.AO - this.findAveragePosition()));
                            break;
                        case 2:
                            bool flag2 = true;
                            this.Ships.thisLock.EnterReadLock();
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                if (!ship.disabled && ship.hasCommand && ship.Active)
                                {
                                    if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 25000.0)
                                        flag2 = false;
                                    if (!flag2)
                                        break;
                                }
                            }
                            this.Ships.thisLock.ExitReadLock();
                            if (!flag2)
                                break;
                            this.Ships.thisLock.EnterReadLock();
                                foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                ship.GetAI().HasPriorityOrder = false;
                                ship.GetAI().State = AIState.HoldPosition;
                                if (ship.BombBays.Count > 0)
                                    ship.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                                else if (ship.Role == "troop")
                                    ship.GetAI().HoldPosition();
                            }
                                this.Ships.thisLock.ExitReadLock();
                            this.InterceptorDict.Clear();
                            this.TaskStep = 3;
                            break;
                        case 3:
                            float num5 = 0.0f;
                            float num6 = 0.0f;
                            float num7 = 0.0f;
                            float num8 = 0.0f;
                            this.Ships.thisLock.EnterReadLock();
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                num5 += ship.Ordinance;
                                num6 += ship.OrdinanceMax;
                                foreach (Weapon weapon in ship.Weapons)
                                {
                                    if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                                        num7 = weapon.DamageAmount / weapon.fireDelay;
                                    if ((double)weapon.PowerRequiredToFire > 0.0)
                                        num8 = weapon.DamageAmount / weapon.fireDelay;
                                }
                            }
                            this.Ships.thisLock.ExitReadLock();
                            float num9 = num7 + num8;
                            if ((double)num7 >= 0.5 * (double)num9 && (double)num5 <= 0.100000001490116 * (double)num6)
                            {
                                this.TaskStep = 5;
                                break;
                            }
                            else
                            {

                                foreach (Ship key in (List<Ship>)Task.GetTargetPlanet().system.ShipList)
                                {
                                    if (key.loyalty != this.Owner && (key.loyalty.isFaction || this.Owner.GetRelations()[key.loyalty].AtWar) && ((double)Vector2.Distance(key.Center, Task.GetTargetPlanet().Position) < 15000.0 && !this.InterceptorDict.ContainsKey(key)))
                                        this.InterceptorDict.Add(key, new List<Ship>());
                                }
                                List<Ship> list2 = new List<Ship>();
                                foreach (KeyValuePair<Ship, List<Ship>> keyValuePair in this.InterceptorDict)
                                {
                                    List<Ship> list3 = new List<Ship>();
                                    if ((double)Vector2.Distance(keyValuePair.Key.Center, Task.GetTargetPlanet().Position) > 20000.0 || !keyValuePair.Key.Active)
                                    {
                                        list2.Add(keyValuePair.Key);
                                        foreach (Ship ship in keyValuePair.Value)
                                        {
                                            lock (ship)
                                            {
                                                ship.GetAI().OrderQueue.Clear();
                                                ship.GetAI().Intercepting = false;
                                                ship.GetAI().OrderOrbitPlanet(Task.GetTargetPlanet());
                                                ship.GetAI().State = AIState.AwaitingOrders;
                                                ship.GetAI().Intercepting = false;
                                            }
                                        }
                                    }
                                    foreach (Ship ship in keyValuePair.Value)
                                    {
                                        if (!ship.Active)
                                            list3.Add(ship);
                                    }
                                    foreach (Ship ship in list3)
                                        keyValuePair.Value.Remove(ship);
                                }
                                foreach (Ship key in list2)
                                    this.InterceptorDict.Remove(key);
                                foreach (KeyValuePair<Ship, List<Ship>> keyValuePair1 in this.InterceptorDict)
                                {
                                    List<Ship> list3 = new List<Ship>();
                                    foreach (Ship ship in (List<Ship>)this.Ships)
                                    {
                                        if (ship.Role != "troop")
                                            list3.Add(ship);
                                    }
                                    List<Ship> list4 = new List<Ship>();
                                    foreach (KeyValuePair<Ship, List<Ship>> keyValuePair2 in this.InterceptorDict)
                                    {
                                        list4.Add(keyValuePair2.Key);
                                        foreach (Ship ship in keyValuePair2.Value)
                                            list3.Remove(ship);
                                    }
                                    foreach (Ship toAttack in (IEnumerable<Ship>)Enumerable.OrderByDescending<Ship, float>((IEnumerable<Ship>)list4, (Func<Ship, float>)(ship => ship.GetStrength())))
                                    {
                                        IOrderedEnumerable<Ship> orderedEnumerable2 = Enumerable.OrderByDescending<Ship, float>((IEnumerable<Ship>)list3, (Func<Ship, float>)(ship => ship.GetStrength()));
                                        float num4 = 0.0f;
                                        foreach (Ship ship in (IEnumerable<Ship>)orderedEnumerable2)
                                        {
                                            if ((double)num4 != 0.0)
                                            {
                                                if ((double)num4 >= (double)toAttack.GetStrength() * 1.5)
                                                    break;
                                            }
                                            ship.GetAI().Intercepting = true;
                                            list3.Remove(ship);
                                            ship.GetAI().OrderAttackSpecificTarget(toAttack);
                                            this.InterceptorDict[toAttack].Add(ship);
                                            num4 += ship.GetStrength();
                                        }
                                    }
                                }
                                if (this.InterceptorDict.Count == 0 || (double)this.Owner.GetGSAI().ThreatMatrix.PingRadarStr(Task.GetTargetPlanet().Position, 25000f, this.Owner) < 500.0)
                                    this.TaskStep = 4;
                                lock (GlobalStats.TaskLocker)
                                {
                                    this.Owner.GetGSAI().TaskList.thisLock.EnterReadLock();
                                    using (List<MilitaryTask>.Enumerator resource_0 = this.Owner.GetGSAI().TaskList.GetEnumerator())
                                    {
                                        while (resource_0.MoveNext())
                                        {
                                            MilitaryTask local_43 = resource_0.Current;
                                            if (local_43.WaitForCommand && local_43.GetTargetPlanet() != null && local_43.GetTargetPlanet() == Task.GetTargetPlanet())
                                                local_43.WaitForCommand = false;
                                        }
                                        this.Owner.GetGSAI().TaskList.thisLock.ExitReadLock();
                                        break;
                                    }
                                    this.Owner.GetGSAI().TaskList.thisLock.ExitReadLock();
                                }
                            }
                        case 4:
                            int num10 = 0;
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                if (ship.BombBays.Count > 0 && (double)ship.Ordinance / (double)ship.OrdinanceMax > 0.200000002980232)
                                {
                                    num10 += ship.BombBays.Count;
                                    ship.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                                }
                            }
                            float num11 = 0.0f;
                            float num12 = 0.0f;
                            float num13 = 0.0f;
                            float num14 = 0.0f;
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                num11 += ship.Ordinance;
                                num12 += ship.OrdinanceMax;
                                foreach (Weapon weapon in ship.Weapons)
                                {
                                    if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                                        num13 = weapon.DamageAmount / weapon.fireDelay;
                                    if ((double)weapon.PowerRequiredToFire > 0.0)
                                        num14 = weapon.DamageAmount / weapon.fireDelay;
                                }
                            }
                            float num15 = num13 + num14;
                            if ((double)num13 >= 0.5 * (double)num15 && (double)num11 <= 0.100000001490116 * (double)num12)
                            {
                                this.TaskStep = 5;
                                break;
                            }
                            else
                            {
                                bool flag3 = true;
                                float groundStrOfPlanet = this.GetGroundStrOfPlanet(Task.GetTargetPlanet());
                                float num4 = 0.0f;
                                foreach (Ship ship in (List<Ship>)this.Ships)
                                {
                                    foreach (Troop troop in ship.TroopList)
                                        num4 += (float)troop.Strength;
                                }
                                if ((double)num4 > (double)groundStrOfPlanet || num10 < 6)
                                {
                                    flag3 = true;
                                }
                                else
                                {
                                    int num16 = 0;
                                    foreach (Ship ship in (List<Ship>)this.Ships)
                                    {
                                        if (ship.BombBays.Count > 0)
                                        {
                                            ++num16;
                                            if ((double)ship.Ordinance / (double)ship.OrdinanceMax > 0.200000002980232)
                                            {
                                                flag3 = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (num16 == 0)
                                        flag3 = true;
                                }
                                if (flag3)
                                {
                                    foreach (Ship ship in (List<Ship>)this.Ships)
                                    {
                                        if (ship.BombBays.Count > 0)
                                        {
                                            ship.GetAI().State = AIState.AwaitingOrders;
                                            ship.GetAI().OrderQueue.Clear();
                                        }
                                    }
                                    this.Position = Task.GetTargetPlanet().Position;
                                    this.AssembleFleet(this.facing, Vector2.Normalize(this.Position - this.findAveragePosition()));
                                    using (List<Ship>.Enumerator enumerator = this.Ships.GetEnumerator())
                                    {
                                        while (enumerator.MoveNext())
                                            enumerator.Current.GetAI().OrderLandAllTroops(Task.GetTargetPlanet());
                                        break;
                                    }
                                }
                                else
                                {
                                    this.Ships.thisLock.EnterReadLock();
                                    using (List<Ship>.Enumerator enumerator = this.Ships.GetEnumerator())
                                    {
                                        while (enumerator.MoveNext())
                                        {
                                            Ship current = enumerator.Current;
                                            if (current.BombBays.Count > 0)
                                                current.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                                        }
                                        this.Ships.thisLock.ExitReadLock();
                                        break;
                                    }
                                    this.Ships.thisLock.ExitReadLock();
                                }
                            }
                        case 5:
                            List<Planet> list5 = new List<Planet>();
                            this.Owner.GetPlanets().thisLock.EnterReadLock();
                            foreach (Planet planet in this.Owner.GetPlanets())
                            {
                                if (planet.HasShipyard)
                                    list5.Add(planet);
                            }
                            this.Owner.GetPlanets().thisLock.ExitReadLock();
                            IOrderedEnumerable<Planet> orderedEnumerable3 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list5, (Func<Planet, float>)(p => Vector2.Distance(this.Position, p.Position)));
                            if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable3) > 0)
                            {
                                this.Position = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable3).Position;
                                foreach (Ship ship in (List<Ship>)this.Ships)
                                    ship.GetAI().OrderResupply(Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable3), true);
                                this.TaskStep = 6;
                                break;
                            }
                            else
                            {
                                Task.EndTask();
                                break;
                            }
                        case 6:
                            float num17 = 0.0f;
                            float num18 = 0.0f;
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                ship.GetAI().HasPriorityOrder = true;
                                num17 += ship.Ordinance;
                                num18 += ship.OrdinanceMax;
                            }
                            if ((double)num17 < (double)num18 * 0.899999976158142)
                                break;
                            this.TaskStep = 0;
                            break;
                    }
                }
            }
        }
        public override void Update(float elapsedTime)
        {
            if (!this.Active)
                return;
            //if (!GlobalStats.WarpInSystem && this.system != null)
            //    this.InhibitedTimer = 1f;
            //else
                if (this.FTLmodifier < 1.0 && this.system != null && (this.engineState == Ship.MoveState.Warp && this.velocityMaximum < this.GetSTLSpeed()))
                this.HyperspaceReturn();
            if (this.ScuttleTimer > -1.0 || this.ScuttleTimer <-1.0)
            {
                this.ScuttleTimer -= elapsedTime;
                if (this.ScuttleTimer <= 0.0)
                    this.Die((GameplayObject)null, true);
            }
            if ((this.system != null && this.system.isVisible) || this.system == null)
            {
                BoundingSphere sphere = new BoundingSphere(new Vector3(this.Position, 0.0f), 2000f);
                if (Ship.universeScreen.Frustum.Contains(sphere) != ContainmentType.Disjoint && Ship.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
                {
                    this.InFrustum = true;
                    this.ShipSO.Visibility = ObjectVisibility.Rendered;
                }
                else
                {
                    this.InFrustum = false;
                    this.ShipSO.Visibility = ObjectVisibility.None;
                }

            }
            else
            {
                this.InFrustum = false;
                this.ShipSO.Visibility = ObjectVisibility.None;
            }
            foreach (ProjectileTracker projectileTracker in (List<ProjectileTracker>)this.ProjectilesFired)
            {
                projectileTracker.Timer -= elapsedTime;
                if ((double)projectileTracker.Timer <= 0.0)
                    this.ProjectilesFired.QueuePendingRemoval(projectileTracker);
            }
            this.ProjectilesFired.ApplyPendingRemovals();
            this.ShieldRechargeTimer += elapsedTime;
            this.InhibitedTimer -= elapsedTime;
            this.Inhibited = this.InhibitedTimer > 0.0;
            if (this.Inhibited && this.engineState == Ship.MoveState.Warp)
            {
                this.HyperspaceReturn();
            }
            if (this.TetheredTo != null)
            {
                this.Position = this.TetheredTo.Position + this.TetherOffset;
                this.Center = this.TetheredTo.Position + this.TetherOffset;
            }
            if (this.Mothership != null && !this.Mothership.Active)
                this.Mothership = (Ship)null;
            if (this.dying)
            {
                this.ThrusterList.Clear();
                this.dietimer -= elapsedTime;
                if ((double)this.dietimer <= 1.89999997615814 && this.dieCue == null && this.InFrustum)
                {
                    if (this.Size < 80)
                    {
                        this.dieCue = AudioManager.GetCue("sd_explosion_ship_warpdet_small");
                        this.dieCue.Apply3D(Ship.universeScreen.listener, this.emitter);
                        this.dieCue.Play();
                    }
                    else if (this.Size >= 80 && this.Size < 250)
                    {
                        this.dieCue = AudioManager.GetCue("sd_explosion_ship_warpdet_medium");
                        this.dieCue.Apply3D(Ship.universeScreen.listener, this.emitter);
                        this.dieCue.Play();
                    }
                    else
                    {
                        this.dieCue = AudioManager.GetCue("sd_explosion_ship_warpdet_large");
                        this.dieCue.Apply3D(Ship.universeScreen.listener, this.emitter);
                        this.dieCue.Play();
                    }
                }
                if ((double)this.dietimer <= 0.0)
                {
                    this.reallyDie = true;
                    this.Die(this.LastDamagedBy, true);
                    return;
                }
                else
                {
                    if ((double)this.Velocity.Length() > (double)this.velocityMaximum)
                        this.Velocity = Vector2.Normalize(this.Velocity) * this.velocityMaximum;
                    Ship ship1 = this;
                    Vector2 vector2_1 = ship1.Position + this.Velocity * elapsedTime;
                    ship1.Position = vector2_1;
                    Ship ship2 = this;
                    Vector2 vector2_2 = ship2.Center + this.Velocity * elapsedTime;
                    ship2.Center = vector2_2;
                    int num1 = (int)(this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, 60f);
                    if (num1 >= 57 && this.InFrustum)
                    {
                        float radius = this.ShipSO.WorldBoundingSphere.Radius;
                        Vector3 vector3 = new Vector3((this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius));
                        ExplosionManager.AddExplosion(vector3, radius, 2.5f, 0.2f);
                        Ship.universeScreen.flash.AddParticleThreadA(vector3, Vector3.Zero);
                    }
                    if (num1 >= 40)
                    {
                        Vector3 position = new Vector3((this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius));
                        Ship.universeScreen.sparks.AddParticleThreadA(position, Vector3.Zero);
                    }
                    this.yRotation += this.xdie * elapsedTime;
                    this.xRotation += this.ydie * elapsedTime;
                    Ship ship3 = this;
                    double num2 = (double)ship3.Rotation + (double)this.zdie * (double)elapsedTime;
                    ship3.Rotation = (float)num2;
                    if (this.ShipSO == null)
                        return;
                    if (Ship.universeScreen.viewState == UniverseScreen.UnivScreenState.ShipView && this.inSensorRange)
                    {
                        this.ShipSO.World = Matrix.Identity * Matrix.CreateRotationY(this.yRotation) * Matrix.CreateRotationX(this.xRotation) * Matrix.CreateRotationZ(this.Rotation) * Matrix.CreateTranslation(new Vector3(this.Center, 0.0f));
                        if (this.shipData.Animated)
                        {
                            this.ShipSO.SkinBones = this.animationController.SkinnedBoneTransforms;
                            this.animationController.Update(Game1.Instance.TargetElapsedTime, Matrix.Identity);
                        }
                    }
                    for (int index = 0; index < this.Projectiles.Count; ++index)
                    {
                        Projectile projectile = this.Projectiles[index];
                        if (projectile != null)
                        {
                            if (projectile.Active)
                                projectile.Update(elapsedTime);
                            else
                                this.Projectiles.QueuePendingRemoval(projectile);
                        }
                    }
                    this.emitter.Position = new Vector3( this.Center, 0);//GlobalStats.Config.EffectsVolume * -5000);
                    foreach (ModuleSlot moduleSlot in this.ModuleSlotList)
                    //Parallel.ForEach<ModuleSlot>(this.ModuleSlotList, moduleSlot =>
                    {
                        moduleSlot.module.UpdateWhileDying(elapsedTime);
                    }//);
                }
            }
            else if (!this.dying)
            {
                if (this.system != null && (double)elapsedTime > 0.0)
                {
                    foreach (Planet p in this.system.PlanetList)
                    {
                        if ((double)Vector2.Distance(p.Position, this.Center) < 3000.0)
                        {
                            if (this.loyalty == Ship.universeScreen.player && !p.ExploredDict[this.loyalty])
                            {
                                foreach (Building building in p.BuildingList)
                                {
                                    if (!string.IsNullOrEmpty(building.EventTriggerUID))
                                        Ship.universeScreen.NotificationManager.AddFoundSomethingInteresting(p);
                                }
                            }
                            if (!p.ExploredDict[this.loyalty])
                            {
                                p.ExploredDict[this.loyalty] = true;
                                foreach (Building building in p.BuildingList)
                                {
                                    if (!string.IsNullOrEmpty(building.EventTriggerUID) && this.loyalty != Ship.universeScreen.player && p.Owner == null)
                                    {
                                        MilitaryTask militaryTask = new MilitaryTask();
                                        militaryTask.AO = p.Position;
                                        militaryTask.AORadius = 50000f;
                                        militaryTask.SetTargetPlanet(p);
                                        militaryTask.type = MilitaryTask.TaskType.Exploration;
                                        militaryTask.SetEmpire(this.loyalty);
                                        lock (GlobalStats.TaskLocker)
                                            this.loyalty.GetGSAI().TaskList.Add(militaryTask);
                                    }
                                }
                                //added by gremlin put shahmatts exploration notifications here
                            }
                        }
                    }
                    if (this.InCombat && this.GetAI().Target != null && this.GetAI().Target.GetSystem() != null && this.GetAI().Target.GetSystem() == this.GetSystem())
                    {
                        this.system.CombatInSystem = true;
                        this.system.combatTimer = 15f;
                    }
                }
                if (this.disabled)
                {
                    for (int index = 0; index < 5; ++index)
                    {
                        Vector3 vector3 = new Vector3((this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween((float)(-(double)this.radius / 3.0), this.radius / 3f), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween((float)(-(double)this.radius / 3.0), this.radius / 3f), 0.0f);
                        Ship.universeScreen.lightning.AddParticleThreadA(new Vector3(this.Center, 0.0f) + vector3, Vector3.Zero);
                    }
                }
                Ship ship1 = this;
                double num1 = (double)ship1.Rotation + (double)this.RotationalVelocity * (double)elapsedTime;
                ship1.Rotation = (float)num1;
                if ((double)Math.Abs(this.RotationalVelocity) > 0.0)
                    this.isTurning = true;
                if (!this.isSpooling && this.Afterburner != null && this.Afterburner.IsPlaying)
                    this.Afterburner.Stop(AudioStopOptions.Immediate);
                this.ClickTimer -= elapsedTime;
                if ((double)this.ClickTimer < 0.0)
                    this.ClickTimer = 10f;
                if (this.Active)
                {
                    this.InCombatTimer -= elapsedTime;
                    if (this.InCombatTimer > 0.0)
                    {
                        this.InCombat = true;
                    }
                    else
                    {
                        if (this.InCombat)
                            this.InCombat = false;
                        try
                        {
                            if (this.AI.State == AIState.Combat)
                            {
                                if (this.loyalty != Ship.universeScreen.player)
                                {
                                    this.AI.State = AIState.AwaitingOrders;
                                    this.GetAI().OrderQueue.Clear();
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    this.Velocity.Length();
                    Ship ship2 = this;
                    Vector2 vector2_1 = ship2.Position + this.Velocity * elapsedTime;
                    ship2.Position = vector2_1;
                    Ship ship3 = this;
                    Vector2 vector2_2 = ship3.Center + this.Velocity * elapsedTime;
                    ship3.Center = vector2_2;
                    this.UpdateShipStatus(elapsedTime);
                    if (!this.Active)
                        return;
                    if (!this.disabled && !Ship.universeScreen.Paused) //this.hasCommand &&
                        this.AI.Update(elapsedTime);
                    if (this.InFrustum)
                    {
                        if (this.ShipSO == null)
                            return;
                        this.ShipSO.World = Matrix.Identity * Matrix.CreateRotationY(this.yRotation) * Matrix.CreateRotationZ(this.Rotation) * Matrix.CreateTranslation(new Vector3(this.Center, 0.0f));
                        if (this.shipData.Animated && this.animationController != null)
                        {
                            this.ShipSO.SkinBones = this.animationController.SkinnedBoneTransforms;
                            this.animationController.Update(Game1.Instance.TargetElapsedTime, Matrix.Identity);
                        }
                        else if (this.shipData != null && this.animationController != null && this.shipData.Animated)
                        {
                            this.ShipSO.SkinBones = this.animationController.SkinnedBoneTransforms;
                            this.animationController.Update(Game1.Instance.TargetElapsedTime, Matrix.Identity);
                        }
                        foreach (Thruster thruster in this.ThrusterList)
                        {
                            thruster.SetPosition();
                            Vector2 vector2_3 = new Vector2((float)Math.Sin((double)this.Rotation), -(float)Math.Cos((double)this.Rotation));
                            vector2_3 = Vector2.Normalize(vector2_3);
                            float num2 = this.Velocity.Length() / this.velocityMaximum;
                            if (this.isThrusting)
                            {
                                if (this.engineState == Ship.MoveState.Warp)
                                {
                                    if ((double)thruster.heat < (double)num2)
                                        thruster.heat += 0.06f;
                                    this.pointat = new Vector3(vector2_3.X, vector2_3.Y, 0.0f);
                                    this.scalefactors = new Vector3(thruster.tscale, thruster.tscale, thruster.tscale);
                                    thruster.update(thruster.WorldPos, this.pointat, this.scalefactors, thruster.heat, 0.004f, Color.OrangeRed, Color.LightBlue, Ship.universeScreen.camPos);
                                }
                                else
                                {
                                    if ((double)thruster.heat < (double)num2)
                                        thruster.heat += 0.06f;
                                    if ((double)thruster.heat > 0.600000023841858)
                                        thruster.heat = 0.6f;
                                    this.pointat = new Vector3(vector2_3.X, vector2_3.Y, 0.0f);
                                    this.scalefactors = new Vector3(thruster.tscale, thruster.tscale, thruster.tscale);
                                    thruster.update(thruster.WorldPos, this.pointat, this.scalefactors, thruster.heat, 1.0f / 500.0f, Color.OrangeRed, Color.LightBlue, Ship.universeScreen.camPos);
                                }
                            }
                            else
                            {
                                this.pointat = new Vector3(vector2_3.X, vector2_3.Y, 0.0f);
                                this.scalefactors = new Vector3(thruster.tscale, thruster.tscale, thruster.tscale);
                                thruster.heat = 0.01f;
                                thruster.update(thruster.WorldPos, this.pointat, this.scalefactors, 0.1f, 1.0f / 500.0f, Color.OrangeRed, Color.LightBlue, Ship.universeScreen.camPos);
                            }
                        }
                    }
                    if (this.isSpooling)
                        this.fightersOut = false;
                    if (this.isSpooling && !this.Inhibited)
                    {
                        this.JumpTimer -= elapsedTime;
                        //task gremlin move fighter recall here.

                        if (this.JumpTimer <= 4.0) // let's see if we can sync audio to behaviour with new timers
                        {
                            if (Vector2.Distance(this.Center, new Vector2(Ship.universeScreen.camPos.X, Ship.universeScreen.camPos.Y)) < 100000.0 && (this.Jump == null || this.Jump != null && !this.Jump.IsPlaying) && Ship.universeScreen.camHeight < 250000)
                            {
                                this.Jump = AudioManager.GetCue(this.GetStartWarpCue());
                                this.Jump.Apply3D(GameplayObject.audioListener, this.emitter);
                                this.Jump.Play();

                            }
                        }
                        if (this.JumpTimer <= 0.1)
                        {
                            if (this.engineState == Ship.MoveState.Sublight )//&& (!this.Inhibited && this.GetFTLSpeed() > this.velocityMaximum))
                            {
                                FTL ftl = new FTL();
                                ftl.Center = new Vector2(this.Center.X, this.Center.Y);
                                //lock (FTLManager.FTLLock)
                                FTLManager.FTLList.thisLock.EnterWriteLock();
                                    FTLManager.FTLList.Add(ftl);
                                    FTLManager.FTLList.thisLock.ExitWriteLock();
                                this.engineState = Ship.MoveState.Warp;
                            }
                            else
                                this.engineState = Ship.MoveState.Sublight;
                            this.isSpooling = false;
                            this.ResetJumpTimer();
                        }
                    }
                    if (this.isPlayerShip())
                    {
                        if ((!this.isSpooling || !this.Active) && this.Afterburner != null)
                        {
                            if (this.Afterburner.IsPlaying)
                                this.Afterburner.Stop(AudioStopOptions.Immediate);
                            this.Afterburner = (Cue)null;
                        }
                        if (this.isThrusting && this.drone == null && this.AI.State == AIState.ManualControl)
                        {
                            this.drone = AudioManager.GetCue("starcruiser_drone01");
                            this.drone.Play();
                        }
                        else if ((!this.isThrusting || !this.Active) && this.drone != null)
                        {
                            if (this.drone.IsPlaying)
                                this.drone.Stop(AudioStopOptions.Immediate);
                            this.drone = (Cue)null;
                        }
                    }
                    this.emitter.Position = new Vector3(this.Center, 0);

                }
                if (elapsedTime > 0.0f)
                {
                    //if (this.GetAI().fireTask != null && !this.GetAI().fireTask.IsCompleted)
                    //{
                    //    this.GetAI().fireTask.Wait();

                    //}
                    //task gremlin look at parallel here for weapons
                    foreach (Projectile projectile in (List<Projectile>)this.Projectiles)
                    //Parallel.ForEach<Projectile>(this.projectiles, projectile =>
                    {
                        if (projectile != null && projectile.Active)
                            projectile.Update(elapsedTime);
                        else
                        {
                           // projectile.Die(null, true);
                            this.Projectiles.QueuePendingRemoval(projectile);
                        }
                    }//);

                    foreach (Beam beam in (List<Beam>)this.beams)
                    {
                        Vector2 origin = new Vector2();
                        if (beam.moduleAttachedTo != null)
                        {
                            ShipModule shipModule = beam.moduleAttachedTo;
                            origin = (int)shipModule.XSIZE != 1 || (int)shipModule.YSIZE != 3 ? ((int)shipModule.XSIZE != 2 || (int)shipModule.YSIZE != 5 ? new Vector2(shipModule.Center.X - 8f + (float)(16 * (int)shipModule.XSIZE / 2), shipModule.Center.Y - 8f + (float)(16 * (int)shipModule.YSIZE / 2)) : new Vector2(shipModule.Center.X - 80f + (float)(16 * (int)shipModule.XSIZE / 2), shipModule.Center.Y - 8f + (float)(16 * (int)shipModule.YSIZE / 2))) : new Vector2(shipModule.Center.X - 50f + (float)(16 * (int)shipModule.XSIZE / 2), shipModule.Center.Y - 8f + (float)(16 * (int)shipModule.YSIZE / 2));
                            Vector2 target = new Vector2(shipModule.Center.X - 8f, shipModule.Center.Y - 8f);
                            float angleToTarget = HelperFunctions.findAngleToTarget(origin, target);
                            Vector2 angleAndDistance = HelperFunctions.findPointFromAngleAndDistance(shipModule.Center, MathHelper.ToDegrees(shipModule.Rotation) - angleToTarget, 8f * (float)Math.Sqrt(2.0));
                            float num2 = (float)((int)shipModule.XSIZE * 16 / 2);
                            float num3 = (float)((int)shipModule.YSIZE * 16 / 2);
                            float distance = (float)Math.Sqrt((double)((float)Math.Pow((double)num2, 2.0) + (float)Math.Pow((double)num3, 2.0)));
                            float radians = 3.141593f - (float)Math.Asin((double)num2 / (double)distance) + shipModule.GetParent().Rotation;
                            origin = HelperFunctions.findPointFromAngleAndDistance(angleAndDistance, MathHelper.ToDegrees(radians), distance);

                            int Thickness = this.system != null ? (int)this.system.RNG.RandomBetween((float)beam.thickness - 0.25f * (float)beam.thickness, (float)beam.thickness + 0.1f * (float)beam.thickness) : (int)Ship.universeScreen.DeepSpaceRNG.RandomBetween((float)beam.thickness - 0.25f * (float)beam.thickness, (float)beam.thickness + 0.1f * (float)beam.thickness);
                            beam.Update(beam.moduleAttachedTo != null ? origin : beam.owner.Center, beam.followMouse ? Ship.universeScreen.mouseWorldPos : beam.Destination, Thickness, Ship.universeScreen.view, Ship.universeScreen.projection, elapsedTime);
                            if ((double)beam.duration < 0.0 && !beam.infinite)
                            {
                                beam.Die(null, false);
                                this.beams.QueuePendingRemoval(beam);
                            }
                        }
                        else
                        {
                            beam.Die(null, false);
                            this.beams.QueuePendingRemoval(beam);
                        }
                    }//);
                    //this.beams.thisLock.ExitReadLock();

                    this.beams.ApplyPendingRemovals();
                    //foreach (Projectile projectile in this.projectiles.pendingRemovals)
                    //    projectile.Die(null,false);
                    this.Projectiles.ApplyPendingRemovals();

                }
            }
        }