public bool CanBeApplied(XElement element, UpgradePrefab prefab)
        {
            if (string.Equals("Structure", element.Name.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(IsWallUpgrade);
            }

            string identifier = element.GetAttributeString("identifier", string.Empty);

            if (string.IsNullOrWhiteSpace(identifier))
            {
                return(false);
            }

            ItemPrefab?item = ItemPrefab.Find(null, identifier);

            if (item == null)
            {
                return(false);
            }

            string[] disallowedUpgrades = element.GetAttributeStringArray("disallowedupgrades", new string[0]);

            if (disallowedUpgrades.Any(s => s.Equals(Identifier, StringComparison.OrdinalIgnoreCase) || s.Equals(prefab.Identifier, StringComparison.OrdinalIgnoreCase)))
            {
                return(false);
            }

            return(item.GetAllowedUpgrades().Contains(Identifier) ||
                   ItemTags.Any(tag => item.Tags.Contains(tag) || item.Identifier.Equals(tag, StringComparison.OrdinalIgnoreCase)));
        }
        public void AutoPurchaseExisting()
        {
            if (GameMain.Client != null)
            {
                return;
            }
            var campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode);

            int totalitems = 0;
            int totalcost  = 0;

            foreach (CampaignPurchase cp in GameMain.NilMod.ServerExistingCampaignAutobuy)
            {
                if (!cp.isvalid)
                {
                    continue;
                }

                ItemPrefab prefab = (ItemPrefab)ItemPrefab.Find(cp.itemprefab);
                for (int i = 0; i < cp.count; i++)
                {
                    if (campaign.Money >= prefab.Price)
                    {
                        totalitems += 1;
                        totalcost  += prefab.Price;
                        campaign.CargoManager.PurchaseItem(prefab);
                    }
                }
            }
            GameMain.Server.ServerLog.WriteLine("AUTOBUY: Added " + totalitems + " Items costing "
                                                + totalcost + " money.", ServerLog.MessageType.ServerMessage);
            LastUpdateID++;
        }
            public ItemProduction(XElement element)
            {
                Items = new List <Item>();

                HungerRate       = element.GetAttributeFloat("hungerrate", 0.0f);
                InvHungerRate    = element.GetAttributeFloat("invhungerrate", 0.0f);
                HappinessRate    = element.GetAttributeFloat("happinessrate", 0.0f);
                InvHappinessRate = element.GetAttributeFloat("invhappinessrate", 0.0f);

                string[] requiredHappinessStr = element.GetAttributeString("requiredhappiness", "0-100").Split('-');
                string[] requiredHungerStr    = element.GetAttributeString("requiredhunger", "0-100").Split('-');
                HappinessRange = new Vector2(0, 100);
                HungerRange    = new Vector2(0, 100);
                float tempF;

                if (requiredHappinessStr.Length >= 2)
                {
                    if (float.TryParse(requiredHappinessStr[0], NumberStyles.Any, CultureInfo.InvariantCulture, out tempF))
                    {
                        HappinessRange.X = tempF;
                    }
                    if (float.TryParse(requiredHappinessStr[1], NumberStyles.Any, CultureInfo.InvariantCulture, out tempF))
                    {
                        HappinessRange.Y = tempF;
                    }
                }
                if (requiredHungerStr.Length >= 2)
                {
                    if (float.TryParse(requiredHungerStr[0], NumberStyles.Any, CultureInfo.InvariantCulture, out tempF))
                    {
                        HungerRange.X = tempF;
                    }
                    if (float.TryParse(requiredHungerStr[1], NumberStyles.Any, CultureInfo.InvariantCulture, out tempF))
                    {
                        HungerRange.Y = tempF;
                    }
                }
                Rate            = element.GetAttributeFloat("rate", 0.016f);
                totalCommonness = 0.0f;
                foreach (XElement subElement in element.Elements())
                {
                    switch (subElement.Name.LocalName.ToLowerInvariant())
                    {
                    case "item":
                        string identifier       = subElement.GetAttributeString("identifier", "");
                        Item   newItemToProduce = new Item
                        {
                            Prefab     = string.IsNullOrEmpty(identifier) ? null : ItemPrefab.Find("", subElement.GetAttributeString("identifier", "")),
                            Commonness = subElement.GetAttributeFloat("commonness", 0.0f)
                        };
                        totalCommonness += newItemToProduce.Commonness;
                        Items.Add(newItemToProduce);
                        break;
                    }
                }

                timer = 1.0f;
            }
Exemple #4
0
        private static XElement ParseDecon(ItemPrefab prefab)
        {
            List <ItemPrefab> deconOutput = prefab.DeconstructItems.Select(item => ItemPrefab.Find(null, item.ItemIdentifier)).Where(outputPrefab => outputPrefab != null).ToList();

            return(new XElement("Deconstruct",
                                new XAttribute("time", prefab.DeconstructTime),
                                new XAttribute("outputs", FormatArray(deconOutput.Select(ip => ip.Name))),
                                new XAttribute("values", FormatArray(deconOutput.Select(ip => ip.DefaultPrice?.Price ?? 0)))
                                ));
        }
        public int DetermineItemSwapCost(Item item, ItemPrefab?replacement)
        {
            if (replacement == null)
            {
                replacement = ItemPrefab.Find("", item.Prefab.SwappableItem.ReplacementOnUninstall);
                if (replacement == null)
                {
                    DebugConsole.ThrowError("Failed to determine swap cost for item \"{}\". Trying to uninstall the item but no replacement item found.");
                    return(0);
                }
            }

            int price = 0;

            if (replacement == item.Prefab)
            {
                if (item.PendingItemSwap != null)
                {
                    //refund the pending swap
                    price -= item.PendingItemSwap.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
                    //buy back the current item
                    price += item.Prefab.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
                }
            }
            else
            {
                price = replacement.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
                if (item.PendingItemSwap != null)
                {
                    //refund the pending swap
                    price -= item.PendingItemSwap.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
                    //buy back the current item
                    price += item.Prefab.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
                }
                //refund the current item
                if (replacement != item.prefab)
                {
                    price -= item.Prefab.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
                }
            }
            return(price);
        }
        public void ServerRead(IReadMessage msg, Client sender)
        {
            UInt16 currentLocIndex  = msg.ReadUInt16();
            UInt16 selectedLocIndex = msg.ReadUInt16();

            byte       selectedMissionCount   = msg.ReadByte();
            List <int> selectedMissionIndices = new List <int>();

            for (int i = 0; i < selectedMissionCount; i++)
            {
                selectedMissionIndices.Add(msg.ReadByte());
            }

            bool purchasedHullRepairs  = msg.ReadBoolean();
            bool purchasedItemRepairs  = msg.ReadBoolean();
            bool purchasedLostShuttles = msg.ReadBoolean();

            UInt16 buyCrateItemCount           = msg.ReadUInt16();
            List <PurchasedItem> buyCrateItems = new List <PurchasedItem>();

            for (int i = 0; i < buyCrateItemCount; i++)
            {
                string itemPrefabIdentifier = msg.ReadString();
                int    itemQuantity         = msg.ReadRangedInteger(0, CargoManager.MaxQuantity);
                buyCrateItems.Add(new PurchasedItem(ItemPrefab.Prefabs[itemPrefabIdentifier], itemQuantity));
            }

            UInt16 purchasedItemCount           = msg.ReadUInt16();
            List <PurchasedItem> purchasedItems = new List <PurchasedItem>();

            for (int i = 0; i < purchasedItemCount; i++)
            {
                string itemPrefabIdentifier = msg.ReadString();
                int    itemQuantity         = msg.ReadRangedInteger(0, CargoManager.MaxQuantity);
                purchasedItems.Add(new PurchasedItem(ItemPrefab.Prefabs[itemPrefabIdentifier], itemQuantity));
            }

            UInt16          soldItemCount = msg.ReadUInt16();
            List <SoldItem> soldItems     = new List <SoldItem>();

            for (int i = 0; i < soldItemCount; i++)
            {
                string itemPrefabIdentifier = msg.ReadString();
                UInt16 id       = msg.ReadUInt16();
                bool   removed  = msg.ReadBoolean();
                byte   sellerId = msg.ReadByte();
                soldItems.Add(new SoldItem(ItemPrefab.Prefabs[itemPrefabIdentifier], id, removed, sellerId));
            }

            ushort purchasedUpgradeCount = msg.ReadUInt16();
            List <PurchasedUpgrade> purchasedUpgrades = new List <PurchasedUpgrade>();

            for (int i = 0; i < purchasedUpgradeCount; i++)
            {
                string        upgradeIdentifier = msg.ReadString();
                UpgradePrefab prefab            = UpgradePrefab.Find(upgradeIdentifier);

                string          categoryIdentifier = msg.ReadString();
                UpgradeCategory category           = UpgradeCategory.Find(categoryIdentifier);

                int upgradeLevel = msg.ReadByte();

                if (category == null || prefab == null)
                {
                    continue;
                }
                purchasedUpgrades.Add(new PurchasedUpgrade(prefab, category, upgradeLevel));
            }

            ushort purchasedItemSwapCount = msg.ReadUInt16();
            List <PurchasedItemSwap> purchasedItemSwaps = new List <PurchasedItemSwap>();

            for (int i = 0; i < purchasedItemSwapCount; i++)
            {
                UInt16 itemToRemoveID = msg.ReadUInt16();
                Item   itemToRemove   = Entity.FindEntityByID(itemToRemoveID) as Item;

                string     itemToInstallIdentifier = msg.ReadString();
                ItemPrefab itemToInstall           = string.IsNullOrEmpty(itemToInstallIdentifier) ? null : ItemPrefab.Find(string.Empty, itemToInstallIdentifier);

                if (itemToRemove == null)
                {
                    continue;
                }

                purchasedItemSwaps.Add(new PurchasedItemSwap(itemToRemove, itemToInstall));
            }

            if (!AllowedToManageCampaign(sender))
            {
                DebugConsole.ThrowError("Client \"" + sender.Name + "\" does not have a permission to manage the campaign");
                return;
            }

            Location location            = Map.CurrentLocation;
            int      hullRepairCost      = location?.GetAdjustedMechanicalCost(HullRepairCost) ?? HullRepairCost;
            int      itemRepairCost      = location?.GetAdjustedMechanicalCost(ItemRepairCost) ?? ItemRepairCost;
            int      shuttleRetrieveCost = location?.GetAdjustedMechanicalCost(ShuttleReplaceCost) ?? ShuttleReplaceCost;

            if (purchasedHullRepairs != this.PurchasedHullRepairs)
            {
                if (purchasedHullRepairs && Money >= hullRepairCost)
                {
                    this.PurchasedHullRepairs = true;
                    Money -= hullRepairCost;
                }
                else if (!purchasedHullRepairs)
                {
                    this.PurchasedHullRepairs = false;
                    Money += hullRepairCost;
                }
            }
            if (purchasedItemRepairs != this.PurchasedItemRepairs)
            {
                if (purchasedItemRepairs && Money >= itemRepairCost)
                {
                    this.PurchasedItemRepairs = true;
                    Money -= itemRepairCost;
                }
                else if (!purchasedItemRepairs)
                {
                    this.PurchasedItemRepairs = false;
                    Money += itemRepairCost;
                }
            }
            if (purchasedLostShuttles != this.PurchasedLostShuttles)
            {
                if (GameMain.GameSession?.SubmarineInfo != null &&
                    GameMain.GameSession.SubmarineInfo.LeftBehindSubDockingPortOccupied)
                {
                    GameMain.Server.SendDirectChatMessage(TextManager.FormatServerMessage("ReplaceShuttleDockingPortOccupied"), sender, ChatMessageType.MessageBox);
                }
                else if (purchasedLostShuttles && Money >= shuttleRetrieveCost)
                {
                    this.PurchasedLostShuttles = true;
                    Money -= shuttleRetrieveCost;
                }
                else if (!purchasedItemRepairs)
                {
                    this.PurchasedLostShuttles = false;
                    Money += shuttleRetrieveCost;
                }
            }

            if (currentLocIndex < Map.Locations.Count && Map.AllowDebugTeleport)
            {
                Map.SetLocation(currentLocIndex);
            }

            Map.SelectLocation(selectedLocIndex == UInt16.MaxValue ? -1 : selectedLocIndex);
            if (Map.SelectedLocation == null)
            {
                Map.SelectRandomLocation(preferUndiscovered: true);
            }
            if (Map.SelectedConnection != null)
            {
                Map.SelectMission(selectedMissionIndices);
            }

            CheckTooManyMissions(Map.CurrentLocation, sender);

            List <PurchasedItem> currentBuyCrateItems = new List <PurchasedItem>(CargoManager.ItemsInBuyCrate);

            currentBuyCrateItems.ForEach(i => CargoManager.ModifyItemQuantityInBuyCrate(i.ItemPrefab, -i.Quantity));
            buyCrateItems.ForEach(i => CargoManager.ModifyItemQuantityInBuyCrate(i.ItemPrefab, i.Quantity));

            CargoManager.SellBackPurchasedItems(new List <PurchasedItem>(CargoManager.PurchasedItems));
            CargoManager.PurchaseItems(purchasedItems, false);

            // for some reason CargoManager.SoldItem is never cleared by the server, I've added a check to SellItems that ignores all
            // sold items that are removed so they should be discarded on the next message
            CargoManager.BuyBackSoldItems(new List <SoldItem>(CargoManager.SoldItems));
            CargoManager.SellItems(soldItems);

            foreach (var(prefab, category, _) in purchasedUpgrades)
            {
                UpgradeManager.PurchaseUpgrade(prefab, category);

                // unstable logging
                int price = prefab.Price.GetBuyprice(UpgradeManager.GetUpgradeLevel(prefab, category), Map?.CurrentLocation);
                int level = UpgradeManager.GetUpgradeLevel(prefab, category);
                GameServer.Log($"SERVER: Purchased level {level} {category.Identifier}.{prefab.Identifier} for {price}", ServerLog.MessageType.ServerMessage);
            }

            foreach (var purchasedItemSwap in purchasedItemSwaps)
            {
                if (purchasedItemSwap.ItemToInstall == null)
                {
                    UpgradeManager.CancelItemSwap(purchasedItemSwap.ItemToRemove);
                }
                else
                {
                    UpgradeManager.PurchaseItemSwap(purchasedItemSwap.ItemToRemove, purchasedItemSwap.ItemToInstall);
                }
            }
            foreach (Item item in Item.ItemList)
            {
                if (item.PendingItemSwap != null && !purchasedItemSwaps.Any(it => it.ItemToRemove == item))
                {
                    UpgradeManager.CancelItemSwap(item);
                    item.PendingItemSwap = null;
                }
            }
        }
Exemple #7
0
        public void GameInitialize()
        {
            if (!GameMain.NilMod.EnableGriefWatcher)
            {
                return;
            }

            for (int i = GWListDetonators.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListDetonators[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListDetonators[i] + ").", Color.Red);
                    GWListDetonators.RemoveAt(i);
                }
                else
                {
                    GWListDetonators[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListExplosives.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListExplosives[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListExplosives[i] + ").", Color.Red);
                    GWListExplosives.RemoveAt(i);
                }
                else
                {
                    GWListExplosives[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListThrown.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListThrown[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListThrown[i] + ").", Color.Red);
                    GWListThrown.RemoveAt(i);
                }
                else
                {
                    GWListThrown[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListMaskItems.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListMaskItems[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListMaskItems[i] + ").", Color.Red);
                    GWListMaskItems.RemoveAt(i);
                }
                else
                {
                    GWListMaskItems[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListMaskHazardous.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListMaskHazardous[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListMaskHazardous[i] + ").", Color.Red);
                    GWListMaskHazardous.RemoveAt(i);
                }
                else
                {
                    GWListMaskHazardous[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListWireKeyDevices.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListWireKeyDevices[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListWireKeyDevices[i] + ").", Color.Red);
                    GWListWireKeyDevices.RemoveAt(i);
                }
                else
                {
                    GWListWireKeyDevices[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListWireJunctions.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListWireJunctions[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListWireJunctions[i] + ").", Color.Red);
                    GWListWireJunctions.RemoveAt(i);
                }
                else
                {
                    GWListWireJunctions[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListSyringes.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListSyringes[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListSyringes[i] + ").", Color.Red);
                    GWListSyringes.RemoveAt(i);
                }
                else
                {
                    GWListSyringes[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListSyringechems.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListSyringechems[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListSyringechems[i] + ").", Color.Red);
                    GWListSyringechems.RemoveAt(i);
                }
                else
                {
                    GWListSyringechems[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListRanged.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListRanged[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListRanged[i] + ").", Color.Red);
                    GWListRanged.RemoveAt(i);
                }
                else
                {
                    GWListRanged[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListRangedAmmo.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListRangedAmmo[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListRangedAmmo[i] + ").", Color.Red);
                    GWListRangedAmmo.RemoveAt(i);
                }
                else
                {
                    GWListRangedAmmo[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListRailgunLaunch.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListRailgunLaunch[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListRailgunLaunch[i] + ").", Color.Red);
                    GWListRailgunLaunch.RemoveAt(i);
                }
                else
                {
                    GWListRailgunLaunch[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListRailgunRacks.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListRailgunRacks[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListRailgunRacks[i] + ").", Color.Red);
                    GWListRailgunRacks.RemoveAt(i);
                }
                else
                {
                    GWListRailgunRacks[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListRailgunAmmo.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListRailgunAmmo[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListRailgunAmmo[i] + ").", Color.Red);
                    GWListRailgunAmmo.RemoveAt(i);
                }
                else
                {
                    GWListRailgunAmmo[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListUse.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListUse[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListUse[i] + ").", Color.Red);
                    GWListUse.RemoveAt(i);
                }
                else
                {
                    GWListUse[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListFabricated.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListFabricated[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListFabricated[i] + ").", Color.Red);
                    GWListFabricated.RemoveAt(i);
                }
                else
                {
                    GWListFabricated[i] = PrefabCheck.Name;
                }
            }

            for (int i = GWListHandcuffs.Count - 1; i >= 0; i--)
            {
                MapEntityPrefab PrefabCheck = ItemPrefab.Find(GWListHandcuffs[i]);
                if (PrefabCheck == null)
                {
                    DebugConsole.NewMessage("NilModGriefWatcher Error - Prefab does not exist! ("
                                            + GWListHandcuffs[i] + ").", Color.Red);
                    GWListHandcuffs.RemoveAt(i);
                }
                else
                {
                    GWListHandcuffs[i] = PrefabCheck.Name;
                }
            }
        }
Exemple #8
0
        public static List <MapEntity> LoadAll(Submarine submarine, XElement parentElement, string filePath, int idOffset)
        {
            IdRemap idRemap = new IdRemap(parentElement, idOffset);

            List <MapEntity> entities = new List <MapEntity>();

            foreach (XElement element in parentElement.Elements())
            {
                string typeName = element.Name.ToString();

                Type t;
                try
                {
                    t = Type.GetType("Barotrauma." + typeName, true, true);
                    if (t == null)
                    {
                        DebugConsole.ThrowError("Error in " + filePath + "! Could not find a entity of the type \"" + typeName + "\".");
                        continue;
                    }
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Error in " + filePath + "! Could not find a entity of the type \"" + typeName + "\".", e);
                    continue;
                }

                if (t == typeof(Structure))
                {
                    string          name            = element.Attribute("name").Value;
                    string          identifier      = element.GetAttributeString("identifier", "");
                    StructurePrefab structurePrefab = Structure.FindPrefab(name, identifier);
                    if (structurePrefab == null)
                    {
                        ItemPrefab itemPrefab = ItemPrefab.Find(name, identifier);
                        if (itemPrefab != null)
                        {
                            t = typeof(Item);
                        }
                    }
                }

                try
                {
                    MethodInfo loadMethod = t.GetMethod("Load", new[] { typeof(XElement), typeof(Submarine), typeof(IdRemap) });
                    if (loadMethod == null)
                    {
                        DebugConsole.ThrowError("Could not find the method \"Load\" in " + t + ".");
                    }
                    else if (!loadMethod.ReturnType.IsSubclassOf(typeof(MapEntity)))
                    {
                        DebugConsole.ThrowError("Error loading entity of the type \"" + t.ToString() + "\" - load method does not return a valid map entity.");
                    }
                    else
                    {
                        object newEntity = loadMethod.Invoke(t, new object[] { element, submarine, idRemap });
                        if (newEntity != null)
                        {
                            entities.Add((MapEntity)newEntity);
                        }
                    }
                }
                catch (TargetInvocationException e)
                {
                    DebugConsole.ThrowError("Error while loading entity of the type " + t + ".", e.InnerException);
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Error while loading entity of the type " + t + ".", e);
                }
            }
            return(entities);
        }
Exemple #9
0
        protected override void StartMissionSpecific(Level level)
        {
            if (SpawnedResources.Any())
            {
#if DEBUG
                throw new Exception($"SpawnedResources.Count > 0 ({SpawnedResources.Count})");
#else
                DebugConsole.AddWarning("Spawned resources list was not empty at the start of a mineral mission. The mission instance may not have been ended correctly on previous rounds.");
                SpawnedResources.Clear();
#endif
            }

            if (RelevantLevelResources.Any())
            {
#if DEBUG
                throw new Exception($"RelevantLevelResources.Count > 0 ({RelevantLevelResources.Count})");
#else
                DebugConsole.AddWarning("Relevant level resources list was not empty at the start of a mineral mission. The mission instance may not have been ended correctly on previous rounds.");
                RelevantLevelResources.Clear();
#endif
            }

            if (MissionClusterPositions.Any())
            {
#if DEBUG
                throw new Exception($"MissionClusterPositions.Count > 0 ({MissionClusterPositions.Count})");
#else
                DebugConsole.AddWarning("Mission cluster positions list was not empty at the start of a mineral mission. The mission instance may not have been ended correctly on previous rounds.");
                MissionClusterPositions.Clear();
#endif
            }

            caves.Clear();

            if (IsClient)
            {
                return;
            }
            foreach (var kvp in ResourceClusters)
            {
                var prefab = ItemPrefab.Find(null, kvp.Key);
                if (prefab == null)
                {
                    DebugConsole.ThrowError("Error in MineralMission - " +
                                            "couldn't find an item prefab with the identifier " + kvp.Key);
                    continue;
                }
                var spawnedResources = level.GenerateMissionResources(prefab, kvp.Value.First, out float rotation);
                if (spawnedResources.Count < kvp.Value.First)
                {
                    DebugConsole.ThrowError("Error in MineralMission - " +
                                            "spawned " + spawnedResources.Count + "/" + kvp.Value.First + " of " + prefab.Name);
                }
                if (spawnedResources.None())
                {
                    continue;
                }
                SpawnedResources.Add(kvp.Key, spawnedResources);
                kvp.Value.Second = rotation;

                foreach (Level.Cave cave in Level.Loaded.Caves)
                {
                    foreach (Item spawnedResource in spawnedResources)
                    {
                        if (cave.Area.Contains(spawnedResource.WorldPosition))
                        {
                            cave.DisplayOnSonar = true;
                            caves.Add(cave);
                            break;
                        }
                    }
                }
            }
            CalculateMissionClusterPositions();
            FindRelevantLevelResources();
        }
        //static because we may need to instantiate the campaign if it hasn't been done yet
        public static void ClientRead(IReadMessage msg)
        {
            bool   isFirstRound     = msg.ReadBoolean();
            byte   campaignID       = msg.ReadByte();
            UInt16 updateID         = msg.ReadUInt16();
            UInt16 saveID           = msg.ReadUInt16();
            string mapSeed          = msg.ReadString();
            UInt16 currentLocIndex  = msg.ReadUInt16();
            UInt16 selectedLocIndex = msg.ReadUInt16();

            byte       selectedMissionCount   = msg.ReadByte();
            List <int> selectedMissionIndices = new List <int>();

            for (int i = 0; i < selectedMissionCount; i++)
            {
                selectedMissionIndices.Add(msg.ReadByte());
            }

            bool  allowDebugTeleport = msg.ReadBoolean();
            float?reputation         = null;

            if (msg.ReadBoolean())
            {
                reputation = msg.ReadSingle();
            }

            Dictionary <string, float> factionReps = new Dictionary <string, float>();
            byte factionsCount = msg.ReadByte();

            for (int i = 0; i < factionsCount; i++)
            {
                factionReps.Add(msg.ReadString(), msg.ReadSingle());
            }

            bool forceMapUI = msg.ReadBoolean();

            int  money = msg.ReadInt32();
            bool purchasedHullRepairs  = msg.ReadBoolean();
            bool purchasedItemRepairs  = msg.ReadBoolean();
            bool purchasedLostShuttles = msg.ReadBoolean();

            byte missionCount = msg.ReadByte();
            List <Pair <string, byte> > availableMissions = new List <Pair <string, byte> >();

            for (int i = 0; i < missionCount; i++)
            {
                string missionIdentifier = msg.ReadString();
                byte   connectionIndex   = msg.ReadByte();
                availableMissions.Add(new Pair <string, byte>(missionIdentifier, connectionIndex));
            }

            UInt16?storeBalance = null;

            if (msg.ReadBoolean())
            {
                storeBalance = msg.ReadUInt16();
            }

            UInt16 buyCrateItemCount           = msg.ReadUInt16();
            List <PurchasedItem> buyCrateItems = new List <PurchasedItem>();

            for (int i = 0; i < buyCrateItemCount; i++)
            {
                string itemPrefabIdentifier = msg.ReadString();
                int    itemQuantity         = msg.ReadRangedInteger(0, CargoManager.MaxQuantity);
                buyCrateItems.Add(new PurchasedItem(ItemPrefab.Prefabs[itemPrefabIdentifier], itemQuantity));
            }

            UInt16 purchasedItemCount           = msg.ReadUInt16();
            List <PurchasedItem> purchasedItems = new List <PurchasedItem>();

            for (int i = 0; i < purchasedItemCount; i++)
            {
                string itemPrefabIdentifier = msg.ReadString();
                int    itemQuantity         = msg.ReadRangedInteger(0, CargoManager.MaxQuantity);
                purchasedItems.Add(new PurchasedItem(ItemPrefab.Prefabs[itemPrefabIdentifier], itemQuantity));
            }

            UInt16          soldItemCount = msg.ReadUInt16();
            List <SoldItem> soldItems     = new List <SoldItem>();

            for (int i = 0; i < soldItemCount; i++)
            {
                string itemPrefabIdentifier = msg.ReadString();
                UInt16 id       = msg.ReadUInt16();
                bool   removed  = msg.ReadBoolean();
                byte   sellerId = msg.ReadByte();
                soldItems.Add(new SoldItem(ItemPrefab.Prefabs[itemPrefabIdentifier], id, removed, sellerId));
            }

            ushort pendingUpgradeCount = msg.ReadUInt16();
            List <PurchasedUpgrade> pendingUpgrades = new List <PurchasedUpgrade>();

            for (int i = 0; i < pendingUpgradeCount; i++)
            {
                string          upgradeIdentifier  = msg.ReadString();
                UpgradePrefab   prefab             = UpgradePrefab.Find(upgradeIdentifier);
                string          categoryIdentifier = msg.ReadString();
                UpgradeCategory category           = UpgradeCategory.Find(categoryIdentifier);
                int             upgradeLevel       = msg.ReadByte();
                if (prefab == null || category == null)
                {
                    continue;
                }
                pendingUpgrades.Add(new PurchasedUpgrade(prefab, category, upgradeLevel));
            }

            ushort purchasedItemSwapCount = msg.ReadUInt16();
            List <PurchasedItemSwap> purchasedItemSwaps = new List <PurchasedItemSwap>();

            for (int i = 0; i < purchasedItemSwapCount; i++)
            {
                UInt16 itemToRemoveID = msg.ReadUInt16();
                Item   itemToRemove   = Entity.FindEntityByID(itemToRemoveID) as Item;

                string     itemToInstallIdentifier = msg.ReadString();
                ItemPrefab itemToInstall           = string.IsNullOrEmpty(itemToInstallIdentifier) ? null : ItemPrefab.Find(string.Empty, itemToInstallIdentifier);

                if (itemToRemove == null)
                {
                    continue;
                }

                purchasedItemSwaps.Add(new PurchasedItemSwap(itemToRemove, itemToInstall));
            }

            bool          hasCharacterData = msg.ReadBoolean();
            CharacterInfo myCharacterInfo  = null;

            if (hasCharacterData)
            {
                myCharacterInfo = CharacterInfo.ClientRead(CharacterPrefab.HumanSpeciesName, msg);
            }

            if (!(GameMain.GameSession?.GameMode is MultiPlayerCampaign campaign) || campaignID != campaign.CampaignID)
            {
                string savePath = SaveUtil.CreateSavePath(SaveUtil.SaveType.Multiplayer);

                GameMain.GameSession = new GameSession(null, savePath, GameModePreset.MultiPlayerCampaign, CampaignSettings.Unsure, mapSeed);
                campaign             = (MultiPlayerCampaign)GameMain.GameSession.GameMode;
                campaign.CampaignID  = campaignID;
                GameMain.NetLobbyScreen.ToggleCampaignMode(true);
            }

            //server has a newer save file
            if (NetIdUtils.IdMoreRecent(saveID, campaign.PendingSaveID))
            {
                campaign.PendingSaveID = saveID;
            }

            if (NetIdUtils.IdMoreRecent(updateID, campaign.lastUpdateID))
            {
                campaign.SuppressStateSending = true;
                campaign.IsFirstRound         = isFirstRound;

                //we need to have the latest save file to display location/mission/store
                if (campaign.LastSaveID == saveID)
                {
                    campaign.ForceMapUI = forceMapUI;

                    UpgradeStore.WaitForServerUpdate = false;

                    campaign.Map.SetLocation(currentLocIndex == UInt16.MaxValue ? -1 : currentLocIndex);
                    campaign.Map.SelectLocation(selectedLocIndex == UInt16.MaxValue ? -1 : selectedLocIndex);
                    campaign.Map.SelectMission(selectedMissionIndices);
                    campaign.Map.AllowDebugTeleport = allowDebugTeleport;
                    campaign.CargoManager.SetItemsInBuyCrate(buyCrateItems);
                    campaign.CargoManager.SetPurchasedItems(purchasedItems);
                    campaign.CargoManager.SetSoldItems(soldItems);
                    if (storeBalance.HasValue)
                    {
                        campaign.Map.CurrentLocation.StoreCurrentBalance = storeBalance.Value;
                    }
                    campaign.UpgradeManager.SetPendingUpgrades(pendingUpgrades);
                    campaign.UpgradeManager.PurchasedUpgrades.Clear();

                    campaign.UpgradeManager.PurchasedUpgrades.Clear();
                    foreach (var purchasedItemSwap in purchasedItemSwaps)
                    {
                        if (purchasedItemSwap.ItemToInstall == null)
                        {
                            campaign.UpgradeManager.CancelItemSwap(purchasedItemSwap.ItemToRemove, force: true);
                        }
                        else
                        {
                            campaign.UpgradeManager.PurchaseItemSwap(purchasedItemSwap.ItemToRemove, purchasedItemSwap.ItemToInstall, force: true);
                        }
                    }
                    foreach (Item item in Item.ItemList)
                    {
                        if (item.PendingItemSwap != null && !purchasedItemSwaps.Any(it => it.ItemToRemove == item))
                        {
                            item.PendingItemSwap = null;
                        }
                    }

                    foreach (var(identifier, rep) in factionReps)
                    {
                        Faction faction = campaign.Factions.FirstOrDefault(f => f.Prefab.Identifier.Equals(identifier, StringComparison.OrdinalIgnoreCase));
                        if (faction?.Reputation != null)
                        {
                            faction.Reputation.Value = rep;
                        }
                        else
                        {
                            DebugConsole.ThrowError($"Received an update for a faction that doesn't exist \"{identifier}\".");
                        }
                    }

                    if (reputation.HasValue)
                    {
                        campaign.Map.CurrentLocation.Reputation.Value = reputation.Value;
                        campaign?.CampaignUI?.UpgradeStore?.RefreshAll();
                    }

                    foreach (var availableMission in availableMissions)
                    {
                        MissionPrefab missionPrefab = MissionPrefab.List.Find(mp => mp.Identifier == availableMission.First);
                        if (missionPrefab == null)
                        {
                            DebugConsole.ThrowError($"Error when receiving campaign data from the server: mission prefab \"{availableMission.First}\" not found.");
                            continue;
                        }
                        if (availableMission.Second == 255)
                        {
                            campaign.Map.CurrentLocation.UnlockMission(missionPrefab);
                        }
                        else
                        {
                            if (availableMission.Second < 0 || availableMission.Second >= campaign.Map.CurrentLocation.Connections.Count)
                            {
                                DebugConsole.ThrowError($"Error when receiving campaign data from the server: connection index for mission \"{availableMission.First}\" out of range (index: {availableMission.Second}, current location: {campaign.Map.CurrentLocation.Name}, connections: {campaign.Map.CurrentLocation.Connections.Count}).");
                                continue;
                            }
                            LocationConnection connection = campaign.Map.CurrentLocation.Connections[availableMission.Second];
                            campaign.Map.CurrentLocation.UnlockMission(missionPrefab, connection);
                        }
                    }

                    GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                }

                bool shouldRefresh = campaign.Money != money ||
                                     campaign.PurchasedHullRepairs != purchasedHullRepairs ||
                                     campaign.PurchasedItemRepairs != purchasedItemRepairs ||
                                     campaign.PurchasedLostShuttles != purchasedLostShuttles;

                campaign.Money = money;
                campaign.PurchasedHullRepairs  = purchasedHullRepairs;
                campaign.PurchasedItemRepairs  = purchasedItemRepairs;
                campaign.PurchasedLostShuttles = purchasedLostShuttles;

                if (shouldRefresh)
                {
                    campaign?.CampaignUI?.UpgradeStore?.RefreshAll();
                }

                if (myCharacterInfo != null)
                {
                    GameMain.Client.CharacterInfo = myCharacterInfo;
                    GameMain.NetLobbyScreen.SetCampaignCharacterInfo(myCharacterInfo);
                }
                else
                {
                    GameMain.NetLobbyScreen.SetCampaignCharacterInfo(null);
                }

                campaign.lastUpdateID         = updateID;
                campaign.SuppressStateSending = false;
            }
        }