private void RunGroundPlanner()
        {
            float totalideal = 0;
            float totalwanted = 0;
            Troop troop;
            Troop LowCosttroop = new Troop();
            Troop highCosttroop = new Troop();
            foreach (KeyValuePair<String, Troop> troops in ResourceManager.TroopsDict.OrderBy(cost => cost.Value.Cost))
            {
                if (!this.empire.WeCanBuildTroop(troops.Key))
                    continue;
                if (troops.Value.Cost > highCosttroop.Cost)
                    highCosttroop = troops.Value;
                if (LowCosttroop.Cost == 0)
                    LowCosttroop = troops.Value;
                else if (troops.Value.Cost < LowCosttroop.Cost)
                    LowCosttroop = troops.Value;
            }

            troop = highCosttroop;

            foreach (SolarSystem system in this.empire.GetOwnedSystems())
            {

                SystemCommander defenseSystem = this.DefensiveCoordinator.DefenseDict[system];
                //int planetcount = system.PlanetList.Where(planet => planet.Owner == empire).Count();
                //planetcount = planetcount == 0 ? 1 : planetcount;

                if (defenseSystem.TroopStrengthNeeded <= 0)
                {
                    continue;
                }
                totalwanted += defenseSystem.TroopStrengthNeeded;// >0 ?defenseSystem.TroopStrengthNeeded : 1;
                totalideal += defenseSystem.IdealTroopStr;// >0 ? defenseSystem.IdealTroopStr : 1;
            }
            if (totalwanted / totalideal > .5f)
            {
                troop = LowCosttroop;
            }
            if (totalwanted / totalideal <= .1f)
                return;
            Planet targetBuild = this.empire.GetPlanets()
                .Where(planet => planet.AllowInfantry
                    && planet.GetMaxProductionPotential() > 2
                    && (planet.ProductionHere) -(planet.ConstructionQueue.Where(goal => goal.Goal != null
                        && goal.Goal.type == GoalType.BuildTroop).Sum(cost => cost.Cost)) > 0//10 turns to build curremt troops in queue

                        )
                        .OrderBy(noshipyard => !noshipyard.HasShipyard)
                        .ThenByDescending(build => build.GrossProductionPerTurn).FirstOrDefault();
            if (targetBuild == null)
                return;

            Goal g = new Goal(troop, this.empire, targetBuild);
            this.Goals.Add(g);
        }
        private void RunGroundPlanner2()
        {
            //float requiredStrength =  (float)(this.empire.GetPlanets().Count * 50);
            float requiredStrength = 0;//(float)(this.empire.GetPlanets().Sum(planet =>planet.GetPotentialGroundTroops(this.empire)));
            float developmentlevel = (float)this.empire.GetPlanets().Average(planet => planet.developmentLevel) *.5f;
            //requiredStrength *= developmentlevel;
            //requiredStrength *= 10;
            foreach(KeyValuePair<SolarSystem,SystemCommander> defensiveStrength in this.DefensiveCoordinator.DefenseDict)
            {
                requiredStrength += defensiveStrength.Value.IdealTroopStr ;
            }

            requiredStrength = requiredStrength + requiredStrength * this.empire.data.Traits.GroundCombatModifier;

            if (Ship.universeScreen.GameDifficulty < UniverseData.GameDifficulty.Hard)
            {
                requiredStrength = requiredStrength * .5f;
            }
            if (Ship.universeScreen.GameDifficulty == UniverseData.GameDifficulty.Easy)
            {
                requiredStrength = requiredStrength * .5f;
            }
            this.numberTroopGoals = this.AreasOfOperations.Count * 2;
            float currentStrength = 0f;
            foreach (Planet p in this.empire.GetPlanets())
            {

                foreach (Troop t in p.TroopsHere)
                {
                    if (t.GetOwner() == null || t.GetOwner() != this.empire)
                    {
                        continue;
                    }
                    currentStrength = currentStrength + (float)t.Strength;
                }
            }
            for (int i = 0; i < this.empire.GetShips().Count; i++)
            {
                Ship ship = this.empire.GetShips()[i];
                if (ship != null)
                {
                    for (int j = 0; j < ship.TroopList.Count; j++)
                    {
                        Troop t = ship.TroopList[j];
                        if (t != null)
                        {
                            currentStrength = currentStrength + (float)t.Strength;
                        }
                    }
                }
            }
            int currentgoals = 0;
            int goalStrength =0;
            for (int i = 0; i < this.Goals.Count; i++)
            {
                Goal g = this.Goals[i];
                if (g != null && g.GoalName == "Build Troop")
                {
                    currentgoals++;
                    goalStrength += (int)ResourceManager.TroopsDict[g.ToBuildUID].Strength;
                }
            }
            int wantedStrength = (int)(requiredStrength - (currentStrength + goalStrength));
            //if (currentStrength < requiredStrength || currentgoals < this.numberTroopGoals)
            //if(wantedStrength >0 || )
            {
                List<Planet> Potentials = new List<Planet>();
                float totalProduction = 0f;
                foreach (AO area in this.AreasOfOperations)
                {
                    if (!area.GetPlanet().AllowInfantry)
                    {
                        continue;
                    }
                    Potentials.Add(area.GetPlanet());
                    totalProduction = totalProduction + area.GetPlanet().GetNetProductionPerTurn();
                }
                if (Potentials.Count > 0)
                {

                    //for (int i = 0; i < (int)wantedStrength * .1f; i++)
                    while(wantedStrength >0 &&  currentgoals <= this.empire.GetPlanets().Count*3)//  this.Goals.Where(goal=>goal.type == GoalType.BuildTroop).Count() <= Potentials.Count*5)

                    {
                        Planet selectedPlanet = null;

                        foreach (Planet p in Potentials.OrderByDescending(queue=> queue.Owner.GetGSAI().Goals.Where(goals=> goals.GetPlanetWhereBuilding() ==queue).Count()).ThenBy(production=> production.GetNetProductionPerTurn()))
                        {

                            //float random = RandomMath.RandomBetween(0f, totalProduction);

                            //if (random <= prodPick || random >= prodPick + p.GetNetProductionPerTurn())
                            //{
                            //    prodPick = prodPick + p.GetNetProductionPerTurn();
                            //}
                            //else
                            //{
                            //    selectedPlanet = p;
                            //}
                            selectedPlanet = p;
                            if (selectedPlanet != null)
                            {
                                List<string> PotentialTroops = new List<string>();
                                foreach (KeyValuePair<string, Troop> troop in ResourceManager.TroopsDict)
                                {
                                    if (!this.empire.WeCanBuildTroop(troop.Key))
                                    {
                                        continue;
                                    }
                                    PotentialTroops.Add(troop.Key);
                                }
                                if (PotentialTroops.Count > 0)
                                {
                                    int ran = (int)RandomMath.RandomBetween(0f, (float)PotentialTroops.Count + 0.75f);
                                    if (ran > PotentialTroops.Count - 1)
                                    {
                                        ran = PotentialTroops.Count - 1;
                                    }
                                    if (ran < 0)
                                    {
                                        ran = 0;
                                    }
                                    Troop troop = ResourceManager.TroopsDict[PotentialTroops[ran]];
                                    wantedStrength -= (int)troop.Strength;
                                    Goal g = new Goal(troop, this.empire, selectedPlanet);
                                    this.Goals.Add(g);
                                    currentgoals++;

                                }
                            }
                        }
                    }
                }
            }
        }
        //Added By Gremlin ExpansionPlanner
        private void RunExpansionPlanner()
        {
            int numColonyGoals = 0;
            this.desired_ColonyGoals = ((int)Ship.universeScreen.GameDifficulty+3) ;
            foreach (Goal g in this.Goals)
            {
                if (g.type != GoalType.Colonize)
                {
                    continue;
                }
                //added by Gremlin: Colony expansion changes
                if (g.GetMarkedPlanet() != null)
                {
                    if (g.GetMarkedPlanet().ParentSystem.ShipList.Where(ship => ship.loyalty != null && ship.loyalty.isFaction).Count() > 0)
                    {
                        numColonyGoals--;
                    }
                    //foreach (Ship enemy in g.GetMarkedPlanet().ParentSystem.ShipList)
                    //{
                    //    if (enemy.loyalty != this.empire)
                    //    {
                    //        numColonyGoals--;
                    //        break;
                    //    }
                    //}
                    numColonyGoals++;
                }
            }
            if (numColonyGoals < this.desired_ColonyGoals + (this.empire.data.EconomicPersonality != null ? this.empire.data.EconomicPersonality.ColonyGoalsPlus : 0) )//
            {
                Planet toMark = null;
                float DistanceInJumps = 0;
                Vector2 WeightedCenter = new Vector2();
                int numPlanets = 0;
                foreach (Planet p in this.empire.GetPlanets())
                {
                    for (int i = 0; (float)i < p.Population / 1000f; i++)
                    {
                        WeightedCenter = WeightedCenter + p.Position;
                        numPlanets++;
                    }
                }
                WeightedCenter = WeightedCenter / (float)numPlanets;
                List<Goal.PlanetRanker> ranker = new List<Goal.PlanetRanker>();
                List<Goal.PlanetRanker> allPlanetsRanker = new List<Goal.PlanetRanker>();
                foreach (SolarSystem s in UniverseScreen.SolarSystemList)
                {
                    //added by gremlin make non offensive races act like it.
                    bool systemOK = true;
                    if (!this.empire.isFaction && this.empire.data != null && this.empire.data.DiplomaticPersonality != null
                        && !(
                        (this.empire.GetRelations().Where(war => war.Value.AtWar).Count() > 0 && this.empire.data.DiplomaticPersonality.Name != "Honorable")
                        || this.empire.data.DiplomaticPersonality.Name == "Agressive"
                        || this.empire.data.DiplomaticPersonality.Name == "Ruthless"
                        || this.empire.data.DiplomaticPersonality.Name == "Cunning")
                        )
                    {
                        foreach (Empire enemy in s.OwnerList)
                        {
                            if (enemy != this.empire && !enemy.isFaction && !this.empire.GetRelations()[enemy].Treaty_Alliance)
                            {

                                systemOK = false;

                                break;
                            }
                        }
                    }
                    if (!systemOK) continue;
                    if (!s.ExploredDict[this.empire])
                    {

                        continue;
                    }
                    foreach (Planet planetList in s.PlanetList)
                    {

                        bool ok = true;
                        foreach (Goal g in this.Goals)
                        {
                            if (g.type != GoalType.Colonize || g.GetMarkedPlanet() != planetList)
                            {
                                continue;
                            }
                            ok = false;
                        }
                        if (!ok)
                        {
                            continue;
                        }
                        IOrderedEnumerable<AO> sorted =
                            from ao in this.empire.GetGSAI().AreasOfOperations
                            orderby Vector2.Distance(planetList.Position, ao.Position)
                            select ao;
                        if (sorted.Count<AO>() > 0)
                        {
                            AO ClosestAO = sorted.First<AO>();
                            if (Vector2.Distance(planetList.Position, ClosestAO.Position) > ClosestAO.Radius * 2f)
                            {
                                continue;
                            }
                        }
                        int commodities = 0;
                        //Added by gremlin adding in commodities
                        foreach (Building commodity in planetList.BuildingList)
                        {
                            if (!commodity.IsCommodity) continue;
                            commodities += 1;
                        }

                        if (planetList.ExploredDict[this.empire]
                            && planetList .habitable
                            && planetList.Owner == null)
                        {
                            if (this.empire == EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty)
                                && this.ThreatMatrix.PingRadarStr(planetList.Position, 50000f, this.empire) > 0f)
                            {
                                continue;
                            }
                            Goal.PlanetRanker r2 = new Goal.PlanetRanker()
                            {
                                Distance = Vector2.Distance(WeightedCenter, planetList.Position)
                            };
                            DistanceInJumps = r2.Distance / 400000f;
                            if (DistanceInJumps < 1f)
                            {
                                DistanceInJumps = 1f;
                            }
                            r2.planet = planetList;
            //Cyberbernetic planet picker
                            if (this.empire.data.Traits.Cybernetic != 0)
                            {

                                r2.PV = (commodities + planetList.MineralRichness + planetList.MaxPopulation / 1000f) / DistanceInJumps;
                            }
                            else
                            {
                                r2.PV = (commodities + planetList.MineralRichness + planetList.Fertility + planetList.MaxPopulation / 1000f) / DistanceInJumps;
                            }

                            if (commodities > 0)
                                ranker.Add(r2);

                            if (planetList.Type == "Barren"
                                && commodities > 0
                                    || this.empire.GetBDict()["Biospheres"]
                                    || this.empire.data.Traits.Cybernetic != 0
                            )
                            {
                                ranker.Add(r2);
                            }
                            else if (planetList.Type != "Barren"
                                && commodities > 0
                                    || ((double)planetList.Fertility >= .5f || (this.empire.data.Traits.Cybernetic != 0 && (double)planetList.MineralRichness >= .5f))
                                    || (this.empire.GetTDict()["Aeroponics"].Unlocked))
                                    //|| (this.empire.data.Traits.Cybernetic != 0 && this.empire.GetBDict()["Biospheres"]))
                            {
                                ranker.Add(r2);
                            }
                            else if (planetList.Type != "Barren")
                            {
                                if (this.empire.data.Traits.Cybernetic == 0)
                                    foreach (Planet food in this.empire.GetPlanets())
                                    {
                                        if (food.FoodHere > food.MAX_STORAGE * .7f && food.fs == Planet.GoodState.EXPORT)
                                        {
                                            ranker.Add(r2);
                                            break;
                                        }
                                    }
                                else
                                {

                                    if (planetList.MineralRichness < .5f)
                                    {

                                        foreach (Planet food in this.empire.GetPlanets())
                                        {
                                            if (food.ProductionHere > food.MAX_STORAGE * .7f || food.ps == Planet.GoodState.EXPORT)
                                            {
                                                ranker.Add(r2);
                                                break;
                                            }
                                        }

                                    }
                                    else
                                    {
                                        ranker.Add(r2);
                                    }

                                }
                            }

                        }
                        if (!planetList.ExploredDict[this.empire]
                            || !planetList.habitable
                            || planetList.Owner == this.empire
                            || this.empire == EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty)
                                && this.ThreatMatrix.PingRadarStr(planetList.Position, 50000f, this.empire) > 0f)
                        {
                            continue;
                        }
                        Goal.PlanetRanker r = new Goal.PlanetRanker()
                        {
                            Distance = Vector2.Distance(WeightedCenter, planetList.Position)
                        };
                        DistanceInJumps = r.Distance / 400000f;
                        if (DistanceInJumps < 1f)
                        {
                            DistanceInJumps = 1f;
                        }
                        r.planet = planetList;
                        if (this.empire.data.Traits.Cybernetic != 0)
                        {
                            r.PV = (commodities + planetList.MineralRichness + planetList.MaxPopulation / 1000f) / DistanceInJumps;
                        }
                        else
                        {
                            r.PV = (commodities + planetList.MineralRichness + planetList.Fertility + planetList.MaxPopulation / 1000f) / DistanceInJumps;
                        }
                        //if (planetList.Type == "Barren" && (commodities > 0 || this.empire.GetTDict()["Biospheres"].Unlocked || (this.empire.data.Traits.Cybernetic != 0 && (double)planetList.MineralRichness >= .5f)))
                        //if (!(planetList.Type == "Barren") || !this.empire.GetTDict()["Biospheres"].Unlocked)
                        if (planetList.Type == "Barren"
                            && commodities > 0
                            || this.empire.GetBDict()["Biospheres"]
                            || this.empire.data.Traits.Cybernetic != 0)

                        {
                            if (!(planetList.Type != "Barren")
                                || (double)planetList.Fertility < .5
                                && !this.empire.GetTDict()["Aeroponics"].Unlocked
                                && this.empire.data.Traits.Cybernetic == 0)
                            {

                                foreach (Planet food in this.empire.GetPlanets())
                                {
                                    if (food.FoodHere > food.MAX_STORAGE * .9f && food.fs == Planet.GoodState.EXPORT)
                                    {
                                        allPlanetsRanker.Add(r);
                                        break;
                                    }
                                }

                                continue;
                            }

                            allPlanetsRanker.Add(r);

                        }
                        else
                        {
                            allPlanetsRanker.Add(r);
                        }
                    }
                }
                if (ranker.Count > 0)
                {
                    Goal.PlanetRanker winner = new Goal.PlanetRanker();
                    float highest = 0f;
                    foreach (Goal.PlanetRanker pr in ranker)
                    {
                        if (pr.PV <= highest)
                        {
                            continue;
                        }
                        bool ok = true;
                        foreach (Goal g in this.Goals)
                        {
                            if (g.GetMarkedPlanet() == null || g.GetMarkedPlanet() != pr.planet)
                            {
                                if (!g.Held || g.GetMarkedPlanet() == null || g.GetMarkedPlanet().system != pr.planet.system)
                                {
                                    continue;
                                }
                                ok = false;
                                break;
                            }
                            else
                            {
                                ok = false;
                                break;
                            }
                        }
                        if (!ok)
                        {
                            continue;
                        }
                        winner = pr;
                        highest = pr.PV;
                    }
                    toMark = winner.planet;
                }
                if (allPlanetsRanker.Count > 0)
                {
                    this.DesiredPlanets.Clear();
                    IOrderedEnumerable<Goal.PlanetRanker> sortedList =
                        from ran in allPlanetsRanker
                        orderby ran.PV descending
                        select ran;
                    for (int i = 0; i < allPlanetsRanker.Count; i++)
                    {
                        this.DesiredPlanets.Add(sortedList.ElementAt<Goal.PlanetRanker>(i).planet);
                    }
                }
                if (toMark != null)
                {
                    bool ok = true;
                    foreach (Goal g in this.Goals)
                    {
                        if (g.type != GoalType.Colonize || g.GetMarkedPlanet() != toMark)
                        {
                            continue;
                        }
                        ok = false;
                    }
                    if (ok)
                    {
                        Goal cgoal = new Goal(toMark, this.empire)
                        {
                            GoalName = "MarkForColonization"
                        };
                        this.Goals.Add(cgoal);
                        numColonyGoals++;
                    }
                }
            }
        }
 private void RunExpansionPlannerORIG()
 {
     int numColonyGoals = 0;
     foreach (Goal g in this.Goals)
     {
         if (g.type != GoalType.Colonize)
         {
             continue;
         }
         numColonyGoals++;
     }
     if (numColonyGoals < this.desired_ColonyGoals + (this.empire.data.EconomicPersonality != null ? this.empire.data.EconomicPersonality.ColonyGoalsPlus : 0))
     {
         Planet toMark = null;
         Vector2 WeightedCenter = new Vector2();
         int numPlanets = 0;
         foreach (Planet p in this.empire.GetPlanets())
         {
             for (int i = 0; (float)i < p.Population / 1000f; i++)
             {
                 WeightedCenter = WeightedCenter + p.Position;
                 numPlanets++;
             }
         }
         WeightedCenter = WeightedCenter / (float)numPlanets;
         List<Goal.PlanetRanker> ranker = new List<Goal.PlanetRanker>();
         List<Goal.PlanetRanker> allPlanetsRanker = new List<Goal.PlanetRanker>();
         foreach (SolarSystem s in UniverseScreen.SolarSystemList)
         {
             if (!s.ExploredDict[this.empire])
             {
                 continue;
             }
             foreach (Planet planetList in s.PlanetList)
             {
                 bool ok = true;
                 foreach (Goal g in this.Goals)
                 {
                     if (g.type != GoalType.Colonize || g.GetMarkedPlanet() != planetList)
                     {
                         continue;
                     }
                     ok = false;
                 }
                 if (!ok)
                 {
                     continue;
                 }
                 IOrderedEnumerable<AO> sorted =
                     from ao in this.empire.GetGSAI().AreasOfOperations
                     orderby Vector2.Distance(planetList.Position, ao.Position)
                     select ao;
                 if (sorted.Count<AO>() > 0)
                 {
                     AO ClosestAO = sorted.First<AO>();
                     if (Vector2.Distance(planetList.Position, ClosestAO.Position) > ClosestAO.Radius * 1.5f)
                     {
                         continue;
                     }
                 }
                 if (planetList.ExploredDict[this.empire] && planetList.habitable && planetList.Owner == null)
                 {
                     if (this.empire == EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty) && this.ThreatMatrix.PingRadarStr(planetList.Position, 50000f, this.empire) > 0f)
                     {
                         continue;
                     }
                     Goal.PlanetRanker r = new Goal.PlanetRanker()
                     {
                         Distance = Vector2.Distance(WeightedCenter, planetList.Position)
                     };
                     float DistanceInJumps = r.Distance / 400000f;
                     if (DistanceInJumps < 1f)
                     {
                         DistanceInJumps = 1f;
                     }
                     r.planet = planetList;
                     if (this.empire.data.Traits.Cybernetic != 0)
                     {
                         //if (planetList.MineralRichness < 1f)
                         //{
                         //    continue;
                         //}
                         r.PV = (planetList.MineralRichness + planetList.MaxPopulation / 1000f) / DistanceInJumps;
                     }
                     else
                     {
                         r.PV = (planetList.MineralRichness + planetList.Fertility + planetList.MaxPopulation / 1000f) / DistanceInJumps;
                     }
                     //Added by McShooterz: changed the requirement from having research to having the building
                     if (planetList.Type == "Barren" && this.empire.GetBDict()["Biospheres"])
                     {
                         ranker.Add(r);
                     }
                     else if (planetList.Type != "Barren" && ((double)planetList.Fertility >= 1 || this.empire.GetBDict()["Aeroponic Farm"] || this.empire.data.Traits.Cybernetic != 0))
                     {
                         ranker.Add(r);
                     }
                 }
                 if (!planetList.ExploredDict[this.empire] || !planetList.habitable || planetList.Owner == this.empire || this.empire == EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty) && this.ThreatMatrix.PingRadarStr(planetList.Position, 50000f, this.empire) > 0f)
                 {
                     continue;
                 }
                 Goal.PlanetRanker r0 = new Goal.PlanetRanker()
                 {
                     Distance = Vector2.Distance(WeightedCenter, planetList.Position)
                 };
                 float DistanceInJumps0 = r0.Distance / 400000f;
                 if (DistanceInJumps0 < 1f)
                 {
                     DistanceInJumps0 = 1f;
                 }
                 r0.planet = planetList;
                 if (this.empire.data.Traits.Cybernetic != 0)
                 {
                     r0.PV = (planetList.MineralRichness + planetList.MaxPopulation / 1000f) / DistanceInJumps0;
                 }
                 else
                 {
                     r0.PV = (planetList.MineralRichness + planetList.Fertility + planetList.MaxPopulation / 1000f) / DistanceInJumps0;
                 }
                 if (!(planetList.Type == "Barren") || !this.empire.GetBDict()["Biospheres"])
                 {
                     if (!(planetList.Type != "Barren") || (double)planetList.Fertility < 1 && !this.empire.GetBDict()["Aeroponic Farm"] && this.empire.data.Traits.Cybernetic == 0)
                     {
                         continue;
                     }
                     allPlanetsRanker.Add(r0);
                 }
                 else
                 {
                     allPlanetsRanker.Add(r0);
                 }
             }
         }
         if (ranker.Count > 0)
         {
             Goal.PlanetRanker winner = new Goal.PlanetRanker();
             float highest = 0f;
             foreach (Goal.PlanetRanker pr in ranker)
             {
                 if (pr.PV <= highest)
                 {
                     continue;
                 }
                 bool ok = true;
                 foreach (Goal g in this.Goals)
                 {
                     if (g.GetMarkedPlanet() == null || g.GetMarkedPlanet() != pr.planet)
                     {
                         if (!g.Held || g.GetMarkedPlanet() == null || g.GetMarkedPlanet().system != pr.planet.system)
                         {
                             continue;
                         }
                         ok = false;
                         break;
                     }
                     else
                     {
                         ok = false;
                         break;
                     }
                 }
                 if (!ok)
                 {
                     continue;
                 }
                 winner = pr;
                 highest = pr.PV;
             }
             toMark = winner.planet;
         }
         if (allPlanetsRanker.Count > 0)
         {
             this.DesiredPlanets.Clear();
             IOrderedEnumerable<Goal.PlanetRanker> sortedList =
                 from ran in allPlanetsRanker
                 orderby ran.PV descending
                 select ran;
             for (int i = 0; i < allPlanetsRanker.Count; i++)
             {
                 this.DesiredPlanets.Add(sortedList.ElementAt<Goal.PlanetRanker>(i).planet);
             }
         }
         if (toMark != null)
         {
             bool ok = true;
             foreach (Goal g in this.Goals)
             {
                 if (g.type != GoalType.Colonize || g.GetMarkedPlanet() != toMark)
                 {
                     continue;
                 }
                 ok = false;
             }
             if (ok)
             {
                 Goal cgoal = new Goal(toMark, this.empire)
                 {
                     GoalName = "MarkForColonization"
                 };
                 this.Goals.Add(cgoal);
                 numColonyGoals++;
             }
         }
     }
 }
        public void HandleInput(InputState input)
        {
            if (!HelperFunctions.CheckIntersection(this.SendTroops.Rect, input.CursorPosition))
            {
                this.SendTroops.State = UIButton.PressState.Normal;
            }
            else
            {
                this.SendTroops.State = UIButton.PressState.Hover;
                if (input.InGameSelect)
                {
                    //this.SendTroops.Text = "Send Troops";
                    this.screen.empUI.empire.GetShips().thisLock.EnterReadLock();
                    List<Ship> troopShips = new List<Ship>(this.screen.empUI.empire.GetShips()
                        .Where(troop => troop.TroopList.Count > 0
                            && troop.GetAI().State == AIState.AwaitingOrders
                            && troop.fleet == null && !troop.InCombat).OrderBy(distance => Vector2.Distance(distance.Center, this.planet.Position)));
                    this.screen.empUI.empire.GetShips().thisLock.ExitReadLock();
                    this.screen.empUI.empire.GetPlanets().thisLock.EnterReadLock();
                    List<Planet> planetTroops = new List<Planet>(this.screen.empUI.empire.GetPlanets()
                        .Where(troops => troops.TroopsHere.Count > 1).OrderBy(distance => Vector2.Distance(distance.Position, this.planet.Position))
                        .Where(Name => Name.Name != this.planet.Name));
                    this.screen.empUI.empire.GetPlanets().thisLock.ExitReadLock();
                    if (troopShips.Count > 0)
                    {
                        AudioManager.PlayCue("echo_affirm");
                        troopShips.First().GetAI().OrderAssaultPlanet(this.planet);
                    }
                    else
                        if (planetTroops.Count > 0)
                        {
                            {
                                Ship troop = planetTroops.First().TroopsHere.First().Launch();
                                if (troop != null)
                                {
                                    AudioManager.PlayCue("echo_affirm");
                                    troop.GetAI().OrderAssaultPlanet(this.planet);
                                }
                            }
                        }
                        else
                        {
                            AudioManager.PlayCue("blip_click");
                        }
                }
            }
            if (!HelperFunctions.CheckIntersection(this.Colonize.Rect, input.CursorPosition))
            {
                this.Colonize.State = UIButton.PressState.Normal;
            }
            else
            {
                this.Colonize.State = UIButton.PressState.Hover;
                if (input.InGameSelect)
                {
                    if (!this.marked)
                    {
                        AudioManager.PlayCue("echo_affirm");
                        Goal g = new Goal(this.planet, Ship.universeScreen.player);
                        Ship.universeScreen.player.GetGSAI().Goals.Add(g);
                        this.Colonize.Text = "Cancel Colonize";
                        this.Colonize.NormalTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"];
                        this.Colonize.HoverTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_hover"];
                        this.Colonize.PressedTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_pressed"];
                        this.marked = true;
                        return;
                    }
                    foreach (Goal g in Ship.universeScreen.player.GetGSAI().Goals)
                    {
                        if (g.GetMarkedPlanet() == null || g.GetMarkedPlanet() != this.planet)
                        {
                            continue;
                        }
                        AudioManager.PlayCue("echo_affirm");
                        if (g.GetColonyShip() != null)
                        {
                            g.GetColonyShip().GetAI().OrderOrbitNearest(true);
                        }
                        Ship.universeScreen.player.GetGSAI().Goals.QueuePendingRemoval(g);
                        this.marked = false;
                        this.Colonize.Text = "Colonize";
                        this.Colonize.NormalTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip"];
                        this.Colonize.HoverTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip_hover"];
                        this.Colonize.PressedTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip_pressed"];
                        break;
                    }
                    Ship.universeScreen.player.GetGSAI().Goals.ApplyPendingRemovals();
                    return;
                }

            }
        }
        //private string Status_Text;
        public PlanetListScreenEntry(Planet p, int x, int y, int width1, int height, PlanetListScreen caller)
        {
            this.screen = caller;
            this.planet = p;
            this.TotalEntrySize = new Rectangle(x, y, width1 - 60, height);
            this.SysNameRect = new Rectangle(x, y, (int)((float)this.TotalEntrySize.Width * 0.12f), height);
            this.PlanetNameRect = new Rectangle(x + this.SysNameRect.Width, y, (int)((float)this.TotalEntrySize.Width * 0.25f), height);
            this.FertRect = new Rectangle(x + this.SysNameRect.Width + this.PlanetNameRect.Width, y, 100, height);
            this.RichRect = new Rectangle(x + this.SysNameRect.Width + this.PlanetNameRect.Width + this.FertRect.Width, y, 120, height);
            this.PopRect = new Rectangle(x + this.SysNameRect.Width + this.PlanetNameRect.Width + this.FertRect.Width + this.RichRect.Width, y, 200, height);
            this.OwnerRect = new Rectangle(x + this.SysNameRect.Width + this.PlanetNameRect.Width + this.FertRect.Width + this.RichRect.Width + this.PopRect.Width, y, 100, height);
            this.OrdersRect = new Rectangle(x + this.SysNameRect.Width + this.PlanetNameRect.Width + this.FertRect.Width + this.RichRect.Width + this.PopRect.Width + this.OwnerRect.Width, y, 100, height);
            //this.Status_Text = "";
            this.ShipIconRect = new Rectangle(this.PlanetNameRect.X + 5, this.PlanetNameRect.Y + 5, 50, 50);
            string shipName = this.planet.Name;
            this.ShipNameEntry.ClickableArea = new Rectangle(this.ShipIconRect.X + this.ShipIconRect.Width + 10, 2 + this.SysNameRect.Y + this.SysNameRect.Height / 2 - Fonts.Arial20Bold.LineSpacing / 2, (int)Fonts.Arial20Bold.MeasureString(shipName).X, Fonts.Arial20Bold.LineSpacing);
            this.ShipNameEntry.Text = shipName;
            float width = (float)((int)((float)this.FertRect.Width * 0.8f));
            while (width % 10f != 0f)
            {
                width = width + 1f;
            }

            Goal goal = new Goal();
            foreach (Goal g in Ship.universeScreen.player.GetGSAI().Goals)
            {
                if (g.GetMarkedPlanet() == null || g.GetMarkedPlanet() != p)
                {
                    continue;
                }
                this.marked = true;
            }

            if (this.marked)
                this.Colonize = new UIButton()
                {
                    Rect = new Rectangle(this.OrdersRect.X + 10, this.OrdersRect.Y + this.OrdersRect.Height / 2 - ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"].Height / 2, ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"].Width, ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"].Height),
                    NormalTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"],
                    HoverTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_hover"],
                    PressedTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_pressed"]
                };
            else
                this.Colonize = new UIButton()
                {
                    Rect = new Rectangle(this.OrdersRect.X + 10, this.OrdersRect.Y + this.OrdersRect.Height / 2 - ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"].Height / 2, ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"].Width, ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px"].Height),
                    NormalTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip"],
                    HoverTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip_hover"],
                    PressedTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip_pressed"]
                };
            if (!this.marked)
                this.Colonize.Text = Localizer.Token(1425);
            else
                this.Colonize.Text = "Cancel Colonize";
            this.Colonize.Launches = Localizer.Token(1425);

            this.SendTroops = new UIButton()
            {
                Rect = new Rectangle(this.OrdersRect.X + this.Colonize.Rect.Width + 10, this.Colonize.Rect.Y, this.Colonize.Rect.Width, this.Colonize.Rect.Height),
                NormalTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip"],
                HoverTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip_hover"],
                PressedTexture = ResourceManager.TextureDict["EmpireTopBar/empiretopbar_btn_168px_dip_pressed"]
            };
        }
 public void GoColonize(Planet p, Goal g)
 {
     this.State = AIState.Colonize;
     this.ColonizeTarget = p;
     this.ColonizeGoal = g;
     this.GotoStep = 0;
     this.OrderColonization(p);
 }
 private void AssignExplorationTasks()
 {
     bool flag1 = false;
     foreach (SolarSystem solarSystem in UniverseScreen.SolarSystemList)
     {
         if (!solarSystem.ExploredDict[this])
         {
             flag1 = true;
             break;
         }
     }
     int num = 0;
     if (flag1)
     {
         foreach (Ship ship in (List<Ship>)this.OwnedShips)
         {
             if (num < 2)
             {
                 if (ship.Role == "scout" && !ship.isPlayerShip())
                 {
                     ship.DoExplore();
                     ++num;
                 }
             }
             else
                 break;
         }
         if (num == 0)
         {
             bool flag2 = true;
             foreach (Goal goal in (List<Goal>)this.GSAI.Goals)
             {
                 if (goal.type == GoalType.BuildScout)
                 {
                     flag2 = false;
                     break;
                 }
             }
             if (!flag2)
                 return;
             Goal goal1 = new Goal();
             goal1.type = GoalType.BuildScout;
             goal1.empire = this;
             goal1.GoalName = "Build Scout";
             this.GSAI.Goals.Add(goal1);
             this.GSAI.Goals.Add(goal1);
         }
         else
         {
             if (num >= 2 || this.data.DiplomaticPersonality == null)
                 return;
             bool flag2 = true;
             foreach (Goal goal in (List<Goal>)this.GSAI.Goals)
             {
                 if (goal.type == GoalType.BuildScout)
                 {
                     flag2 = false;
                     break;
                 }
             }
             if (flag2)
                 this.GSAI.Goals.Add(new Goal()
                 {
                     type = GoalType.BuildScout,
                     empire = this,
                     GoalName = "Build Scout"
                 });
             if (!(this.data.DiplomaticPersonality.Name == "Expansionist") || !flag2)
                 return;
             this.GSAI.Goals.Add(new Goal()
             {
                 type = GoalType.BuildScout,
                 empire = this,
                 GoalName = "Build Scout"
             });
         }
     }
     else
     {
         foreach (Ship ship in (List<Ship>)this.OwnedShips)
         {
             if (ship.GetAI().State == AIState.Explore)
                 ship.GetAI().OrderRebaseToNearest();
         }
     }
 }
 private void CreateShipGoals()
 {
     foreach (FleetDataNode node in this.f.DataNodes)
     {
         if (node.GetShip() != null)
         {
             continue;
         }
         Goal g = new Goal(node.ShipName, "FleetRequisition", this.f.Owner);
         g.SetFleet(this.f);
         node.GoalGUID = g.guid;
         this.f.Owner.GetGSAI().Goals.Add(g);
     }
 }
        //added by gremlin refit while in fleet
        private void DoRefit(float elapsedTime, ArtificialIntelligence.ShipGoal goal)
        {
            QueueItem qi = new QueueItem()
            {
                isShip = true,
                productionTowards = 0f,
                sData = ResourceManager.ShipsDict[goal.VariableString].GetShipData()
            };

            if (qi.sData == null)
            {
                this.OrderQueue.Clear();
                this.State = AIState.AwaitingOrders;
            }
            int cost = (int)(ResourceManager.ShipsDict[goal.VariableString].GetCost(this.Owner.loyalty) - this.Owner.GetCost(this.Owner.loyalty));
            if (cost < 0)
            {
                cost = 0;
            }
            cost = cost + 10 * (int)UniverseScreen.GamePaceStatic;
            qi.Cost = (float)cost;
            qi.isRefit = true;
            //Added by McShooterz: refit keeps name and level
            if(this.Owner.VanityName != this.Owner.Name)
                qi.RefitName = this.Owner.VanityName;
            qi.sData.Level = (byte)this.Owner.Level;
            if (this.Owner.fleet != null)
            {

                FleetDataNode node = this.Owner.fleet.DataNodes.Where(thenode => thenode.GetShip() == this.Owner).First();

                Goal refitgoal = new Goal
                {
                    beingBuilt = ResourceManager.ShipsDict[goal.VariableString],

                    GoalName = "FleetRequisition",

                };
                refitgoal.Step = 1;
                refitgoal.beingBuilt.fleet = this.Owner.fleet;
                refitgoal.beingBuilt.RelativeFleetOffset = node.FleetOffset;
                node.GoalGUID = refitgoal.guid;
                refitgoal.SetFleet(this.Owner.fleet);
                refitgoal.SetPlanetWhereBuilding(this.OrbitTarget);

                this.Owner.loyalty.GetGSAI().Goals.Add(refitgoal);

                qi.Goal = refitgoal;
            }
            this.OrbitTarget.ConstructionQueue.Add(qi);
            this.Owner.QueueTotalRemoval();
        }
        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;
        }
 public bool HandleInput(InputState input)
 {
     this.selector = null;
     this.SL.HandleInput(input);
     Vector2 MousePos = input.CursorPosition;
     for (int i = 0; i < this.SL.Entries.Count; i++)
     {
         ScrollList.Entry e = this.SL.Entries[i];
         if (!HelperFunctions.CheckIntersection(e.clickRect, MousePos))
         {
             e.clickRectHover = 0;
         }
         else
         {
             this.selector = new Selector(this.ScreenManager, e.clickRect);
             if (e.clickRectHover == 0)
             {
                 AudioManager.PlayCue("sd_ui_mouseover");
             }
             e.clickRectHover = 1;
             if (input.CurrentMouseState.LeftButton == ButtonState.Pressed && input.LastMouseState.LeftButton == ButtonState.Released)
             {
                 this.itemToBuild = e.item as Ship;
                 return true;
             }
         }
     }
     if (this.itemToBuild == null || HelperFunctions.CheckIntersection(this.win, MousePos) || input.CurrentMouseState.LeftButton != ButtonState.Pressed || input.LastMouseState.LeftButton != ButtonState.Released)
     {
         if (input.CurrentMouseState.RightButton == ButtonState.Pressed && input.LastMouseState.RightButton == ButtonState.Released)
         {
             this.itemToBuild = null;
         }
         if (!HelperFunctions.CheckIntersection(this.ConstructionSubMenu.Menu, input.CursorPosition) || !input.RightMouseClick)
         {
             return false;
         }
         this.screen.showingDSBW = false;
         return true;
     }
     Viewport viewport = this.ScreenManager.GraphicsDevice.Viewport;
     Vector3 nearPoint = viewport.Unproject(new Vector3((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y, 0f), this.screen.projection, this.screen.view, Matrix.Identity);
     Viewport viewport1 = this.ScreenManager.GraphicsDevice.Viewport;
     Vector3 farPoint = viewport1.Unproject(new Vector3((float)input.CurrentMouseState.X, (float)input.CurrentMouseState.Y, 1f), this.screen.projection, this.screen.view, Matrix.Identity);
     Vector3 direction = farPoint - nearPoint;
     direction.Normalize();
     Ray pickRay = new Ray(nearPoint, direction);
     float k = -pickRay.Position.Z / pickRay.Direction.Z;
     Vector3 pickedPosition = new Vector3(pickRay.Position.X + k * pickRay.Direction.X, pickRay.Position.Y + k * pickRay.Direction.Y, 0f);
     Goal buildstuff = new Goal(new Vector2(pickedPosition.X, pickedPosition.Y), this.itemToBuild.Name, EmpireManager.GetEmpireByName(this.screen.PlayerLoyalty));
     if (this.TargetPlanet != Guid.Empty)
     {
         buildstuff.TetherOffset = this.TetherOffset;
         buildstuff.TetherTarget = this.TargetPlanet;
     }
     EmpireManager.GetEmpireByName(this.screen.PlayerLoyalty).GetGSAI().Goals.Add(buildstuff);
     AudioManager.PlayCue("echo_affirm");
     lock (GlobalStats.ClickableItemLocker)
     {
         this.screen.UpdateClickableItems();
     }
     if (!input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift) && (!input.CurrentKeyboardState.IsKeyDown(Keys.RightShift)))
     {
         this.itemToBuild = null;
     }
     return true;
 }
 public void DoColonize(Planet p, Goal g)
 {
     this.AI.OrderColonization(p);
 }
        private void RunInfrastructurePlanner()
        {
            //if (this.empire.SpaceRoadsList.Sum(node=> node.NumberOfProjectors) < ShipCountLimit * GlobalStats.spaceroadlimit)
            float sspBudget = this.empire.Money * (.01f *(1-this.empire.data.TaxRate));
            if (sspBudget < 0 || this.empire.data.SSPBudget > this.empire.Money * .1)
            {
                sspBudget = 0;

            }
            else
            {
                this.empire.Money -= sspBudget;
                this.empire.data.SSPBudget += sspBudget;
            }
            sspBudget = this.empire.data.SSPBudget *.1f;
            float roadMaintenance = 0;
            float nodeMaintenance = ResourceManager.ShipsDict["Subspace Projector"].GetMaintCost(this.empire);
            foreach (SpaceRoad roadBudget in this.empire.SpaceRoadsList)
            {
                if (roadBudget.NumberOfProjectors == 0)
                    roadBudget.NumberOfProjectors = roadBudget.RoadNodesList.Count;
                roadMaintenance += roadBudget.NumberOfProjectors * nodeMaintenance;
            }

            sspBudget -= roadMaintenance;

            //this.empire.data.SSPBudget += sspBudget;
            //sspBudget = this.empire.data.SSPBudget;
            float UnderConstruction = 0f;
            foreach (Goal g in this.Goals)
            {
                //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);
                //        }
                //    }
                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);
                }
            }
            sspBudget -= UnderConstruction;
            if (sspBudget > nodeMaintenance*2) //- nodeMaintenance * 5
            {
                foreach (SolarSystem ownedSystem in this.empire.GetOwnedSystems())
                //ReaderWriterLockSlim roadlock = new ReaderWriterLockSlim();
                //Parallel.ForEach(this.empire.GetOwnedSystems(), ownedSystem =>
                {

                    IOrderedEnumerable<SolarSystem> sortedList =
                        from otherSystem in this.empire.GetOwnedSystems()
                        orderby Vector2.Distance(otherSystem.Position, ownedSystem.Position)
                        select otherSystem;
                    int devLevelos = 0;
                    foreach (Planet p in ownedSystem.PlanetList)
                    {
                        if (p.Owner != this.empire)
                            continue;
                        //if (p.ps != Planet.GoodState.EXPORT && p.fs != Planet.GoodState.EXPORT)
                        //    continue;
                        devLevelos += p.developmentLevel;

                    }
                    if (devLevelos == 0)
                        //return;
                        continue;
                    foreach (SolarSystem Origin in sortedList)
                    {
                        if (Origin == ownedSystem)
                        {
                            continue;
                        }
                        int devLevel = devLevelos;
                        bool createRoad = true;
                        //roadlock.EnterReadLock();
                        foreach (SpaceRoad road in this.empire.SpaceRoadsList)
                        {
                            if (road.GetOrigin() != ownedSystem && road.GetDestination() != ownedSystem)
                            {
                                continue;
                            }
                            createRoad = false;
                        }
                       // roadlock.ExitReadLock();
                        foreach (Planet p in Origin.PlanetList)
                        {
                            if (p.Owner != this.empire)
                                continue;
                            devLevel += p.developmentLevel;
                        }
                        if (!createRoad)
                        {
                            continue;
                        }
                        SpaceRoad newRoad = new SpaceRoad(Origin, ownedSystem, this.empire, sspBudget, nodeMaintenance);

                        //roadlock.EnterWriteLock();
                        if (sspBudget <= 0 || newRoad.NumberOfProjectors == 0 || newRoad.NumberOfProjectors > devLevel)
                        {
                           // roadlock.ExitWriteLock();
                            continue;
                        }
                        sspBudget -= newRoad.NumberOfProjectors * nodeMaintenance;
                        UnderConstruction += newRoad.NumberOfProjectors * nodeMaintenance;

                            this.empire.SpaceRoadsList.Add(newRoad);
                           // roadlock.ExitWriteLock();
                    }
                }//);
            }
            sspBudget = this.empire.data.SSPBudget-roadMaintenance - UnderConstruction;
            List<SpaceRoad> ToRemove = new List<SpaceRoad>();
            //float income = this.empire.Money +this.empire.GrossTaxes; //this.empire.EstimateIncomeAtTaxRate(0.25f) +
            foreach (SpaceRoad road in this.empire.SpaceRoadsList.OrderBy(ssps => ssps.NumberOfProjectors))
            {

                if (road.RoadNodesList.Count == 0 ||sspBudget <= 0.0f )// || road.NumberOfProjectors ==0)
                {
                    //if(road.NumberOfProjectors ==0)
                    //{
                        //int rnc=0;
                        //foreach(RoadNode rn in road.RoadNodesList)
                        //{
                        //    foreach(Goal G in this.Goals)
                        //    {
                        //            if (G.type != GoalType.DeepSpaceConstruction || !(g.BuildPosition == rn.Position))
                        //            {
                        //                continue;
                        //            }

                        //    }
                        //    if (rn.Platform == null)
                        //        continue;
                        //    rnc++;
                        //}
                        //if (rnc > 0)
                        //    road.NumberOfProjectors = rnc;
                        //else
                     //       ToRemove.Add(road);

                    //else
                    ToRemove.Add(road);
                    sspBudget += road.NumberOfProjectors * nodeMaintenance;
                    continue;
                }

                RoadNode ssp = road.RoadNodesList.Where(notNull => notNull != null && notNull.Platform !=null).FirstOrDefault();
                if ((ssp != null && (!road.GetOrigin().OwnerList.Contains(this.empire) || !road.GetDestination().OwnerList.Contains(this.empire))))
                {
                    ToRemove.Add(road);
                    sspBudget += road.NumberOfProjectors * nodeMaintenance;
                    //if(ssp!=null )
                    //{
                    //    this.SSPBudget += road.NumberOfProjectors * nodeMaintenance;
                    //}
                }
                else
                {
                    foreach (RoadNode node in road.RoadNodesList)
                    {
                        if (node.Platform != null && (node.Platform == null || node.Platform.Active))
                        {
                            continue;
                        }
                        bool AddNew = true;
                        foreach (Goal g in this.Goals)
                        {
                            if (g.type != GoalType.DeepSpaceConstruction || !(g.BuildPosition == node.Position))
                            {
                                continue;
                            }
                            AddNew = false;
                        }
                        this.empire.BorderNodeLocker.EnterReadLock();
                        {
                            foreach (Empire.InfluenceNode bordernode in this.empire.BorderNodes)
                            {
                                if (Vector2.Distance(node.Position, bordernode.Position) >= bordernode.Radius)
                                {
                                    continue;
                                }
                                AddNew = false;
                            }
                        }
                        this.empire.BorderNodeLocker.ExitReadLock();
                        if (!AddNew)
                        {
                            continue;
                        }
                        Goal newRoad = new Goal(node.Position, "Subspace Projector", this.empire);
                        this.Goals.Add(newRoad);
                    }
                }
            }
            if (this.empire != Ship.universeScreen.player)
            {
                foreach (SpaceRoad road in ToRemove)
                {
                    this.empire.SpaceRoadsList.Remove(road);
                    foreach (RoadNode node in road.RoadNodesList)
                    {
                        if (node.Platform != null && node.Platform.Active ) //(node.Platform == null || node.Platform.Active))
                        {
                            node.Platform.Die(null,true); //.GetAI().OrderScrapShip();

                            continue;
                        }

                        foreach (Goal g in this.Goals)
                        {
                            if (g.type != GoalType.DeepSpaceConstruction || !(g.BuildPosition == node.Position))
                            {
                                continue;
                            }
                            this.Goals.QueuePendingRemoval(g);
                            foreach (Planet p in this.empire.GetPlanets())
                            {
                                foreach (QueueItem qi in p.ConstructionQueue)
                                {
                                    if (qi.Goal != g)
                                    {
                                        continue;
                                    }
                                    Planet productionHere = p;
                                    productionHere.ProductionHere = productionHere.ProductionHere + qi.productionTowards;
                                    if (p.ProductionHere > p.MAX_STORAGE)
                                    {
                                        p.ProductionHere = p.MAX_STORAGE;
                                    }
                                    p.ConstructionQueue.QueuePendingRemoval(qi);
                                }
                                p.ConstructionQueue.ApplyPendingRemovals();
                            }
                            this.empire.GetShips().thisLock.EnterReadLock();

                            foreach (Ship ship in this.empire.GetShips())
                            {
                                ship.GetAI().orderqueue.EnterReadLock();
                                bool flag = false;
                                ArtificialIntelligence.ShipGoal goal = ship.GetAI().OrderQueue.LastOrDefault();

                                if (goal == null || goal.goal == null || goal.goal.type != GoalType.DeepSpaceConstruction || goal.goal.BuildPosition != node.Position)
                                {
                                    flag = true;
                                }
                                ship.GetAI().orderqueue.ExitReadLock();
                                if (flag)
                                    continue;
                                ship.GetAI().OrderScrapShip();

                                break;

                            }
                            this.empire.GetShips().thisLock.ExitReadLock();

                        }
                        this.Goals.ApplyPendingRemovals();
                    }
                    this.empire.SpaceRoadsList.Remove(road);
                }
            }
        }
 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);
 }
        //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();
            }
        }
 public void ReportGoalComplete(Goal g)
 {
     for (int index = 0; index < this.GSAI.Goals.Count; ++index)
     {
         if (this.GSAI.Goals[index] == g)
             this.GSAI.Goals.QueuePendingRemoval(this.GSAI.Goals[index]);
     }
 }