public static void CreateFleetFromDataAt(FleetDesign data, Empire Owner, Vector2 Position, float facing)
 {
     Fleet fleet = new Fleet()
     {
         Position = Position,
         facing = facing,
         Owner = Owner,
         DataNodes = new BatchRemovalCollection<FleetDataNode>()
     };
     foreach (FleetDataNode node in data.Data)
     {
         fleet.DataNodes.Add(node);
     }
     fleet.AssignDataPositions(facing);
     fleet.Name = data.Name;
     fleet.FleetIconIndex = data.FleetIconIndex;
     fleet.DataNodes.thisLock.EnterWriteLock();
     foreach (FleetDataNode node in fleet.DataNodes)
     {
         Ship s = ResourceManager.CreateShipAtPoint(node.ShipName, Owner, Position + node.OrdersOffset, facing);
         s.RelativeFleetOffset = node.FleetOffset;
         node.SetShip(s);
         fleet.AddShip(s);
     }
     fleet.DataNodes.thisLock.ExitWriteLock();
     foreach (Ship s in Owner.GetFleetsDict()[1].Ships)
     {
         s.fleet = null;
     }
     Owner.GetFleetsDict()[1] = fleet;
 }
        public void AcceptThreat(Offer ToUs, Offer FromUs, Empire us, Empire Them)
        {
            if (ToUs.PeaceTreaty)
            {
                this.empire.GetRelations()[Them].AtWar = false;
                this.empire.GetRelations()[Them].PreparingForWar = false;
                this.empire.GetRelations()[Them].ActiveWar.EndStarDate = this.empire.GetUS().StarDate;
                this.empire.GetRelations()[Them].WarHistory.Add(this.empire.GetRelations()[Them].ActiveWar);
                this.empire.GetRelations()[Them].Posture = Posture.Neutral;
                if (this.empire.GetRelations()[Them].Anger_FromShipsInOurBorders > (float)(this.empire.data.DiplomaticPersonality.Territorialism / 3))
                {
                    this.empire.GetRelations()[Them].Anger_FromShipsInOurBorders = (float)(this.empire.data.DiplomaticPersonality.Territorialism / 3);
                }
                if (this.empire.GetRelations()[Them].Anger_TerritorialConflict > (float)(this.empire.data.DiplomaticPersonality.Territorialism / 3))
                {
                    this.empire.GetRelations()[Them].Anger_TerritorialConflict = (float)(this.empire.data.DiplomaticPersonality.Territorialism / 3);
                }
                this.empire.GetRelations()[Them].Anger_MilitaryConflict = 0f;
                this.empire.GetRelations()[Them].WarnedAboutShips = false;
                this.empire.GetRelations()[Them].WarnedAboutColonizing = false;
                this.empire.GetRelations()[Them].HaveRejected_Demand_Tech = false;
                this.empire.GetRelations()[Them].HaveRejected_OpenBorders = false;
                this.empire.GetRelations()[Them].HaveRejected_TRADE = false;
                this.empire.GetRelations()[Them].HasDefenseFleet = false;
                if (this.empire.GetRelations()[Them].DefenseFleet != -1)
                {
                    this.empire.GetFleetsDict()[this.empire.GetRelations()[Them].DefenseFleet].Task.EndTask();
                }
                lock (GlobalStats.TaskLocker)
                {
                    foreach (MilitaryTask task in this.TaskList)
                    {
                        if (task.GetTargetPlanet() == null || task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner != Them)
                        {
                            continue;
                        }
                        task.EndTask();
                    }
                }
                this.empire.GetRelations()[Them].ActiveWar = null;
                Them.GetRelations()[this.empire].AtWar = false;
                Them.GetRelations()[this.empire].PreparingForWar = false;
                Them.GetRelations()[this.empire].ActiveWar.EndStarDate = Them.GetUS().StarDate;
                Them.GetRelations()[this.empire].WarHistory.Add(Them.GetRelations()[this.empire].ActiveWar);
                Them.GetRelations()[this.empire].Posture = Posture.Neutral;
                if (EmpireManager.GetEmpireByName(Them.GetUS().PlayerLoyalty) != Them)
                {
                    if (Them.GetRelations()[this.empire].Anger_FromShipsInOurBorders > (float)(Them.data.DiplomaticPersonality.Territorialism / 3))
                    {
                        Them.GetRelations()[this.empire].Anger_FromShipsInOurBorders = (float)(Them.data.DiplomaticPersonality.Territorialism / 3);
                    }
                    if (Them.GetRelations()[this.empire].Anger_TerritorialConflict > (float)(Them.data.DiplomaticPersonality.Territorialism / 3))
                    {
                        Them.GetRelations()[this.empire].Anger_TerritorialConflict = (float)(Them.data.DiplomaticPersonality.Territorialism / 3);
                    }
                    Them.GetRelations()[this.empire].Anger_MilitaryConflict = 0f;
                    Them.GetRelations()[this.empire].WarnedAboutShips = false;
                    Them.GetRelations()[this.empire].WarnedAboutColonizing = false;
                    Them.GetRelations()[this.empire].HaveRejected_Demand_Tech = false;
                    Them.GetRelations()[this.empire].HaveRejected_OpenBorders = false;
                    Them.GetRelations()[this.empire].HaveRejected_TRADE = false;
                    if (Them.GetRelations()[this.empire].DefenseFleet != -1)
                    {
                        Them.GetFleetsDict()[Them.GetRelations()[this.empire].DefenseFleet].Task.EndTask();
                    }
                    lock (GlobalStats.TaskLocker)
                    {
                        foreach (MilitaryTask task in Them.GetGSAI().TaskList)
                        {
                            if (task.GetTargetPlanet() == null || task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner != this.empire)
                            {
                                continue;
                            }
                            task.EndTask();
                        }
                    }
                }
                Them.GetRelations()[this.empire].ActiveWar = null;
            }
            if (ToUs.NAPact)
            {
                us.GetRelations()[Them].Treaty_NAPact = true;
                FearEntry te = new FearEntry();
                if (EmpireManager.GetEmpireByName(this.empire.GetUS().PlayerLoyalty) != us)
                {
                    string name = us.data.DiplomaticPersonality.Name;
                    string str = name;
                    if (name != null)
                    {
                        if (str == "Pacifist")
                        {
                            te.FearCost = 0f;
                        }
                        else if (str == "Cunning")
                        {
                            te.FearCost = 0f;
                        }
                        else if (str == "Xenophobic")
                        {
                            te.FearCost = 15f;
                        }
                        else if (str == "Aggressive")
                        {
                            te.FearCost = 35f;
                        }
                        else if (str == "Honorable")
                        {
                            te.FearCost = 5f;
                        }
                        else if (str == "Ruthless")
                        {
                            te.FearCost = 50f;
                        }
                    }
                }
                us.GetRelations()[Them].FearEntries.Add(te);
            }
            if (FromUs.NAPact)
            {
                Them.GetRelations()[us].Treaty_NAPact = true;
                if (EmpireManager.GetEmpireByName(this.empire.GetUS().PlayerLoyalty) != Them)
                {
                    FearEntry te = new FearEntry();
                    string name1 = Them.data.DiplomaticPersonality.Name;
                    string str1 = name1;
                    if (name1 != null)
                    {
                        if (str1 == "Pacifist")
                        {
                            te.FearCost = 0f;
                        }
                        else if (str1 == "Cunning")
                        {
                            te.FearCost = 0f;
                        }
                        else if (str1 == "Xenophobic")
                        {
                            te.FearCost = 15f;
                        }
                        else if (str1 == "Aggressive")
                        {
                            te.FearCost = 35f;
                        }
                        else if (str1 == "Honorable")
                        {
                            te.FearCost = 5f;
                        }
                        else if (str1 == "Ruthless")
                        {
                            te.FearCost = 50f;
                        }
                    }
                    Them.GetRelations()[us].FearEntries.Add(te);
                }
            }
            if (ToUs.TradeTreaty)
            {
                us.GetRelations()[Them].Treaty_Trade = true;
                us.GetRelations()[Them].Treaty_Trade_TurnsExisted = 0;
                FearEntry te = new FearEntry()
                {
                    FearCost = 5f
                };
                us.GetRelations()[Them].FearEntries.Add(te);
            }
            if (FromUs.TradeTreaty)
            {
                Them.GetRelations()[us].Treaty_Trade = true;
                Them.GetRelations()[us].Treaty_Trade_TurnsExisted = 0;
                FearEntry te = new FearEntry()
                {
                    FearCost = 0.1f
                };
                Them.GetRelations()[us].FearEntries.Add(te);
            }
            if (ToUs.OpenBorders)
            {
                us.GetRelations()[Them].Treaty_OpenBorders = true;
                FearEntry te = new FearEntry()
                {
                    FearCost = 5f
                };
                us.GetRelations()[Them].FearEntries.Add(te);
            }
            if (FromUs.OpenBorders)
            {
                Them.GetRelations()[us].Treaty_OpenBorders = true;
                FearEntry te = new FearEntry()
                {
                    FearCost = 5f
                };
                Them.GetRelations()[us].FearEntries.Add(te);
            }
            foreach (string tech in FromUs.TechnologiesOffered)
            {
                Them.UnlockTech(tech);
                if (EmpireManager.GetEmpireByName(this.empire.GetUS().PlayerLoyalty) == us)
                {
                    continue;
                }
                FearEntry te = new FearEntry()
                {
                    FearCost = (us.data.EconomicPersonality.Name == "Technologists" ? ResourceManager.TechTree[tech].Cost / 100f * 0.25f + ResourceManager.TechTree[tech].Cost / 100f : ResourceManager.TechTree[tech].Cost / 100f),
                    TurnTimer = 40
                };
                us.GetRelations()[Them].FearEntries.Add(te);
            }
            foreach (string tech in ToUs.TechnologiesOffered)
            {
                us.UnlockTech(tech);
                if (EmpireManager.GetEmpireByName(this.empire.GetUS().PlayerLoyalty) == Them)
                {
                    continue;
                }
                FearEntry te = new FearEntry()
                {
                    FearCost = (Them.data.EconomicPersonality.Name == "Technologists" ? ResourceManager.TechTree[tech].Cost / 100f * 0.25f + ResourceManager.TechTree[tech].Cost / 100f : ResourceManager.TechTree[tech].Cost / 100f)
                };
                Them.GetRelations()[us].FearEntries.Add(te);
            }
            foreach (string Art in FromUs.ArtifactsOffered)
            {
                Artifact toGive = ResourceManager.ArtifactsDict[Art];
                foreach (Artifact arti in us.data.OwnedArtifacts)
                {
                    if (arti.Name != Art)
                    {
                        continue;
                    }
                    toGive = arti;
                }
                us.RemoveArtifact(toGive);
                Them.AddArtifact(toGive);
            }
            foreach (string Art in ToUs.ArtifactsOffered)
            {
                Artifact toGive = ResourceManager.ArtifactsDict[Art];
                foreach (Artifact arti in Them.data.OwnedArtifacts)
                {
                    if (arti.Name != Art)
                    {
                        continue;
                    }
                    toGive = arti;
                }
                Them.RemoveArtifact(toGive);
                us.AddArtifact(toGive);

            }
            foreach (string planetName in FromUs.ColoniesOffered)
            {
                List<Planet> toRemove = new List<Planet>();
                List<Ship> TroopShips = new List<Ship>();
                foreach (Planet p in us.GetPlanets())
                {
                    if (p.Name != planetName)
                    {
                        continue;
                    }
                    foreach (PlanetGridSquare pgs in p.TilesList)
                    {
                        if (pgs.TroopsHere.Count <= 0 || pgs.TroopsHere[0].GetOwner() != this.empire)
                        {
                            continue;
                        }
                        TroopShips.Add(pgs.TroopsHere[0].Launch());
                    }
                    toRemove.Add(p);
                    p.Owner = Them;
                    Them.AddPlanet(p);
                    p.system.OwnerList.Clear();
                    foreach (Planet pl in p.system.PlanetList)
                    {
                        if (pl.Owner == null || p.system.OwnerList.Contains(pl.Owner))
                        {
                            continue;
                        }
                        p.system.OwnerList.Add(pl.Owner);
                    }
                    float value = p.Population / 1000f + p.FoodHere / 50f + p.ProductionHere / 50f + p.Fertility + p.MineralRichness + p.MaxPopulation / 10000f;
                    foreach (Building b in p.BuildingList)
                    {
                        value = value + b.Cost / 50f;
                    }
                    FearEntry te = new FearEntry();
                    if (value < 15f)
                    {
                        value = 15f;
                    }
                    te.FearCost = (us.data.EconomicPersonality.Name == "Expansionists" ? value + value : value + 0.5f * value);
                    te.TurnTimer = 40;
                    us.GetRelations()[Them].FearEntries.Add(te);
                }
                foreach (Planet p in toRemove)
                {
                    us.GetPlanets().Remove(p);
                }
                foreach (Ship ship in TroopShips)
                {
                    ship.GetAI().OrderRebaseToNearest();
                }
            }
            foreach (string planetName in ToUs.ColoniesOffered)
            {
                List<Planet> toRemove = new List<Planet>();
                List<Ship> TroopShips = new List<Ship>();
                foreach (Planet p in Them.GetPlanets())
                {
                    if (p.Name != planetName)
                    {
                        continue;
                    }
                    toRemove.Add(p);
                    p.Owner = us;
                    us.AddPlanet(p);
                    p.system.OwnerList.Clear();
                    foreach (Planet pl in p.system.PlanetList)
                    {
                        if (pl.Owner == null || p.system.OwnerList.Contains(pl.Owner))
                        {
                            continue;
                        }
                        p.system.OwnerList.Add(pl.Owner);
                    }
                    float value = p.Population / 1000f + p.FoodHere / 50f + p.ProductionHere / 50f + p.Fertility + p.MineralRichness + p.MaxPopulation / 10000f;
                    foreach (Building b in p.BuildingList)
                    {
                        value = value + b.Cost / 50f;
                    }
                    foreach (PlanetGridSquare pgs in p.TilesList)
                    {
                        if (pgs.TroopsHere.Count <= 0 || pgs.TroopsHere[0].GetOwner() != Them)
                        {
                            continue;
                        }
                        TroopShips.Add(pgs.TroopsHere[0].Launch());
                    }
                    if (EmpireManager.GetEmpireByName(this.empire.GetUS().PlayerLoyalty) == Them)
                    {
                        continue;
                    }
                    FearEntry te = new FearEntry()
                    {
                        FearCost = (Them.data.EconomicPersonality.Name == "Expansionists" ? value + value : value + 0.5f * value),
                        TurnTimer = 40
                    };
                    Them.GetRelations()[us].FearEntries.Add(te);
                }
                foreach (Planet p in toRemove)
                {
                    Them.GetPlanets().Remove(p);
                }
                foreach (Ship ship in TroopShips)
                {
                    ship.GetAI().OrderRebaseToNearest();
                }
            }
            us.GetRelations()[Them].UpdateRelationship(us, Them);
        }
        public static void CreateFleetAt(string FleetUID, Empire Owner, Vector2 Position)
        {
            FileInfo theFleetFI;

            if (GlobalStats.ActiveMod != null && Directory.Exists(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/FleetDesigns")) && File.Exists(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/FleetDesigns/", FleetUID, ".xml")))
            {
                theFleetFI = new FileInfo(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/FleetDesigns/", FleetUID, ".xml"));
            }
            else if (File.Exists(string.Concat("Content/FleetDesigns/", FleetUID, ".xml")))
            {
                theFleetFI = new FileInfo(string.Concat("Content/FleetDesigns/", FleetUID, ".xml"));
            }
            else
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                theFleetFI = new FileInfo(string.Concat(path, "/StarDrive/Fleet Designs/", FleetUID, ".xml"));
            }
            XmlSerializer serializer1 = new XmlSerializer(typeof(FleetDesign));
            FleetDesign data = (FleetDesign)serializer1.Deserialize(theFleetFI.OpenRead());
            Fleet fleet = new Fleet()
            {
                Position = Position,
                Owner = Owner,
                DataNodes = new BatchRemovalCollection<FleetDataNode>()
            };
            foreach (FleetDataNode node in data.Data)
            {
                fleet.DataNodes.Add(node);
            }
            fleet.Name = data.Name;
            fleet.FleetIconIndex = data.FleetIconIndex;
            fleet.DataNodes.thisLock.EnterWriteLock();
            foreach (FleetDataNode node in fleet.DataNodes)
            {
                Ship s = ResourceManager.CreateShipAtPoint(node.ShipName, Owner, Position + node.FleetOffset);
                s.RelativeFleetOffset = node.FleetOffset;
                node.SetShip(s);
                fleet.AddShip(s);
            }
            fleet.DataNodes.thisLock.ExitWriteLock();
            foreach (Ship s in Owner.GetFleetsDict()[1].Ships)
            {
                s.fleet = null;
            }
            Owner.GetFleetsDict()[1] = fleet;
        }
        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;
        }