Пример #1
0
        public override void Entry(IModHelper helper)
        {
            ModInstance = this;

            LoadUserConfig();
            LoadGlobalConfig();
            LoadModdedItems();
            LoadModdedBags();
            BagConfig.AfterLoaded();

            helper.Events.Display.MenuChanged   += Display_MenuChanged;
            helper.Events.Display.WindowResized += Display_WindowResized;

            helper.Events.GameLoop.UpdateTicked += GameLoop_UpdateTicked;

            helper.Events.GameLoop.Saving     += (sender, e) => { SaveLoadHelpers.OnSaving(); };
            helper.Events.GameLoop.Saved      += (sender, e) => { SaveLoadHelpers.OnSaved(); };
            helper.Events.GameLoop.SaveLoaded += (sender, e) => { SaveLoadHelpers.OnLoaded(); };

            helper.Events.GameLoop.GameLaunched += (sender, e) =>
            {
                //  Add compatibility with the Save Anywhere mod
                string SaveAnywhereUniqueId    = "Omegasis.SaveAnywhere";
                bool   IsSaveAnywhereInstalled = Helper.ModRegistry.IsLoaded(SaveAnywhereUniqueId) ||
                                                 Helper.ModRegistry.GetAll().Any(x => x.Manifest.Name.Equals("Save Anywhere", StringComparison.CurrentCultureIgnoreCase));
                if (IsSaveAnywhereInstalled)
                {
                    try
                    {
                        ISaveAnywhereAPI API = Helper.ModRegistry.GetApi <ISaveAnywhereAPI>(SaveAnywhereUniqueId);
                        if (API != null)
                        {
                            API.addBeforeSaveEvent(ModUniqueId, () => { SaveLoadHelpers.OnSaving(); });
                            API.addAfterSaveEvent(ModUniqueId, () => { SaveLoadHelpers.OnSaved(); });
                            API.addAfterLoadEvent(ModUniqueId, () => { SaveLoadHelpers.OnLoaded(); });
                        }
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log(string.Format("Failed to bind to Save Anywhere's Mod API. Your game may crash while saving with Save Anywhere! Error: {0}", ex.Message), LogLevel.Warn);
                    }
                }

                ModdedBag.OnGameLaunched();
            };

            InputHandler.OnModEntry(helper);
            CraftingHandler.OnModEntry(helper);
            CommandHandler.OnModEntry(helper);
            AutofillHandler.OnModEntry(helper);
            MultiplayerHandler.OnModEntry(helper);
            MonsterLootHandler.OnModEntry(helper);
        }
Пример #2
0
        private static void LoadModdedBags()
        {
            try
            {
                List <ModdedBag> ModdedBags          = new List <ModdedBag>();
                string           ModdedBagsDirectory = Path.Combine(ModInstance.Helper.DirectoryPath, "assets", "Modded Bags");
                string[]         ModdedBagFiles      = Directory.GetFiles(ModdedBagsDirectory, "*.json", SearchOption.TopDirectoryOnly);
                if (ModdedBagFiles.Length > 0)
                {
                    if (!ModInstance.Helper.ModRegistry.IsLoaded(JAUniqueId))
                    {
                        ModInstance.Monitor.Log("Modded bags could not be loaded because you do not have Json Assets mod installed.", LogLevel.Warn);
                    }
                    else
                    {
                        foreach (string File in ModdedBagFiles)
                        {
                            string    RelativePath = File.Replace(ModInstance.Helper.DirectoryPath + Path.DirectorySeparatorChar, "");
                            ModdedBag ModdedBag    = ModInstance.Helper.Data.ReadJsonFile <ModdedBag>(RelativePath);

                            if (ModdedBag.IsEnabled && (string.IsNullOrEmpty(ModdedBag.ModUniqueId) || ModInstance.Helper.ModRegistry.IsLoaded(ModdedBag.ModUniqueId)))
                            {
                                if (!ModdedBags.Any(x => x.Guid == ModdedBag.Guid))
                                {
                                    ModdedBags.Add(ModdedBag);
                                }
                                else
                                {
                                    ModInstance.Monitor.Log(string.Format("Failed to load modded bag '{0}' because there is already another modded bag with the same Id", ModdedBag.BagName), LogLevel.Warn);
                                }
                            }
                        }

                        ModInstance.Monitor.Log(string.Format("Loaded {0} modded bag(s): {1}", ModdedBags.Count, string.Join(", ", ModdedBags.Select(x => x.BagName))), LogLevel.Info);
                    }
                }

                TemporaryModdedBagTypes = new Dictionary <ModdedBag, BagType>();
                foreach (ModdedBag Bag in ModdedBags)
                {
                    BagType Placeholder = Bag.GetBagTypePlaceholder();
                    TemporaryModdedBagTypes.Add(Bag, Placeholder);
                    BagConfig.BagTypes.Add(Placeholder);
                }
            }
            catch (Exception ex)
            {
                ModInstance.Monitor.Log(string.Format("Error while loading modded bag json files: {0}\n\n{1}", ex.Message, ex.ToString()), LogLevel.Error);
            }
        }
 private static void Multiplayer_ModMessageReceived(object sender, ModMessageReceivedEventArgs e)
 {
     if (e.FromModID == ItemBagsMod.ModUniqueId)
     {
         if (e.Type == ForceResyncCommandType)
         {
             Dictionary <int, string> LatestItemData = e.ReadAs <Dictionary <int, string> >();
             foreach (var KVP in LatestItemData)
             {
                 int    InventoryIndex = KVP.Key;
                 string Data           = KVP.Value;
                 if (Game1.player.Items[InventoryIndex] is ItemBag IB)
                 {
                     IB.TryDeserializeFromString(Data, out Exception Error);
                 }
             }
         }
         else if (e.Type == OnConnectedCommandType)
         {
             ModdedBag.OnConnectedToHost();
         }
     }
 }
Пример #4
0
        private static void RegisterGenerateModdedBagCommand()
        {
            string CommandName = "generate_modded_bag";
            string CommandHelp = string.Format("Creates a json file that defines a modded Item Bag for a particular mod.\n"
                                               + "Arguments: <BagName> <ModUniqueID> (This is the 'ModUniqueID' value of the mod's manifest.json that you want to generate the file for. All modded items belonging to this mod will be included in the generated modded bag)\n"
                                               + "If the BagName is multiple words, wrap it in double quotes."
                                               + "Example: {0} \"Artisan Valley Bag\" ppja.artisanvalleymachinegoods\n\n",
                                               CommandName);

            Helper.ConsoleCommands.Add(CommandName, CommandHelp, (string Name, string[] Args) =>
            {
                try
                {
                    if (!Helper.ModRegistry.IsLoaded(ItemBagsMod.JAUniqueId))
                    {
                        Monitor.Log("Unable to execute command: JsonAssets mod is not installed. Modded bags only support modded objects added through JsonAssets.", LogLevel.Alert);
                    }
                    else if (!Context.IsWorldReady)
                    {
                        Monitor.Log("Unable to execute command: JsonAssets has not finished loading modded items. You must load a save file before using this command.", LogLevel.Alert);
                    }
                    else if (Args.Length < 2)
                    {
                        Monitor.Log("Unable to execute command: Required arguments missing. You must specify a Bag Name and a ModUniqueID. All modded items from the given ModUniqueID will be included in the generated bag.", LogLevel.Alert);
                    }
                    else
                    {
                        string BagName     = Args[0];
                        string ModUniqueId = string.Join(" ", Args.Skip(1));
                        if (!Helper.ModRegistry.IsLoaded(ModUniqueId))
                        {
                            string Message = string.Format("Unable to execute command: ModUniqueID = '{0}' is not installed. "
                                                           + "Either install this mod first, or double check that you used the correct value for ModUniqueID. "
                                                           + "The ModUniqueID can be found in the mod's manifest.json file.", ModUniqueId);
                            Monitor.Log(Message, LogLevel.Alert);
                        }
                        else
                        {
                            IJsonAssetsAPI API = Helper.ModRegistry.GetApi <IJsonAssetsAPI>(ItemBagsMod.JAUniqueId);
                            if (API != null)
                            {
#if NEVER //DEBUG
                                //  Trying to figure out how to get seed ids belonging to a particular mod.
                                //  It seems like GetAllObjectsFromContentPack doesn't include the seeds, even though they are in GetAllObjectIds
                                string TestSeedName = "Adzuki Bean Seeds";
                                IDictionary <string, int> AllObjectIds = API.GetAllObjectIds();
                                List <string> AllObjectsInMod          = API.GetAllObjectsFromContentPack(ModUniqueId);
                                bool IsSeedFoundAnywhere = AllObjectIds != null && AllObjectIds.ContainsKey(TestSeedName);
                                bool IsSeedFoundInMod    = AllObjectsInMod != null && AllObjectsInMod.Contains(TestSeedName);
                                int SeedId = API.GetObjectId(TestSeedName);
#endif
                                List <ContainerSize> AllSizes = Enum.GetValues(typeof(ContainerSize)).Cast <ContainerSize>().ToList();

                                ModdedBag ModdedBag = new ModdedBag()
                                {
                                    IsEnabled      = true,
                                    ModUniqueId    = ModUniqueId,
                                    Guid           = ModdedBag.StringToGUID(ModUniqueId + BagName).ToString(),
                                    BagName        = BagName,
                                    BagDescription = string.Format("A bag for storing items belonging to {0} mod", ModUniqueId),
                                    IconTexture    = BagType.SourceTexture.SpringObjects,
                                    IconPosition   = new Rectangle(),
                                    Prices         = AllSizes.ToDictionary(x => x, x => BagTypeFactory.DefaultPrices[x]),
                                    Capacities     = AllSizes.ToDictionary(x => x, x => BagTypeFactory.DefaultCapacities[x]),
                                    Sellers        = AllSizes.ToDictionary(x => x, x => new List <BagShop>()
                                    {
                                        BagShop.Pierre
                                    }),
                                    MenuOptions = AllSizes.ToDictionary(x => x, x => new BagMenuOptions()
                                    {
                                        GroupedLayoutOptions = new BagMenuOptions.GroupedLayout()
                                        {
                                            GroupsPerRow = 5
                                        }
                                    }),
                                    Items = ModdedBag.GetModdedItems(ModUniqueId)
                                };

                                string OutputDirectory = Path.Combine(Helper.DirectoryPath, "assets", "Modded Bags");
                                string DesiredFilename = ModdedBag.ModUniqueId;
                                string CurrentFilename = DesiredFilename;
                                int CurrentIndex       = 0;
                                while (File.Exists(Path.Combine(OutputDirectory, CurrentFilename + ".json")))
                                {
                                    CurrentIndex++;
                                    CurrentFilename = string.Format("{0} ({1})", DesiredFilename, CurrentIndex);
                                }

                                string RelativePath = Path.Combine("assets", "Modded Bags", CurrentFilename + ".json");
                                Helper.Data.WriteJsonFile(RelativePath, ModdedBag);

                                Monitor.Log(string.Format("File exported to: {0}\nYou will need to re-launch the game for this file to be loaded.", Path.Combine(Helper.DirectoryPath, RelativePath)), LogLevel.Alert);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log(string.Format("ItemBags: Unhandled error while executing command: {0}", ex.Message), LogLevel.Error);
                }
            });

            CommandName = "generate_category_modded_bag";
            CommandHelp = string.Format("Creates a json file that defines a modded Item Bag for a particular category of items.\n"
                                        + "Arguments: <IncludeVanillaItems> <IncludeModdedItems> <SortingOrder> <BagName> <CategoryIdOrName>\n"
                                        + "IncludeVanillaItems: Possible values are 'true' or 'false' (without the quotes).\n\tIf true, the generated bag will be able to store vanilla (non-modded) items of the desired category(s).\n"
                                        + "IncludeModdedItems: Possible values are 'true' or 'false' (without the quotes).\n\tIf true, the generated bag will be able to store modded items of the desired category(s).\n"
                                        + "SortingOrder: A comma-separated list of what properties to sort the items by before exporting them.\n\tValid properties are {0}/{1}/{2}/{3}.\n\tYou can also choose {4} or {5} order for each property.\n\t"
                                        + "For example, '{6}-{7},{8}-{9}' would first sort by the {10} name in {11} order,\n\tand then sort by the item {12} in {13} order.\n"
                                        + "BagName: The name of the exported bag.\n\tIf the name is multiple words, enclose it in double quotes.\n"
                                        + "CategoryIdOrName: The name of the category, or its internal Id.\n\tMost categories can be found here: https://stardewcommunitywiki.com/Modding:Object_data#Categories \n\tYou can specify as many categories as you want.\n\tIf a category name is multiple words long, enclose it in double quotes.\n"
                                        + "Example: {14} true true \"Dairy Bag\" -5 -6\n\t"
                                        + "This would generate a bag that can store any items belonging to the Egg or Milk categories.\n\tNote that those categories are both named 'Animal Product', so to avoid amibiguity,\n\tthe category ids were used instead of the name.",
                                        SortingProperty.Name, SortingProperty.Id, SortingProperty.Category, SortingProperty.SingleValue,
                                        SortingOrder.Ascending, SortingOrder.Descending,
                                        SortingProperty.Category, SortingOrder.Ascending, SortingProperty.Id, SortingOrder.Descending, SortingProperty.Category, SortingOrder.Ascending, SortingProperty.Id, SortingOrder.Descending,
                                        CommandName);
            Helper.ConsoleCommands.Add(CommandName, CommandHelp, (string Name, string[] Args) =>
            {
                try
                {
                    if (!Context.IsWorldReady)
                    {
                        Monitor.Log("Unable to execute command: You must load a save file before using this command.", LogLevel.Alert);
                    }
                    else if (Args.Length < 5)
                    {
                        Monitor.Log(string.Format("Unable to execute command: Required arguments missing. Type 'help {0}' for more details on using this command.", CommandName), LogLevel.Alert);
                    }
                    else if (!bool.TryParse(Args[0], out bool IncludeVanillaItems))
                    {
                        Monitor.Log(string.Format("Unable to execute command: '{0}' is not a valid value for the IncludeVanillaItems parameter. Expected values are 'true' or 'false' (without the quotes)", Args[0]), LogLevel.Alert);
                    }
                    else if (!bool.TryParse(Args[1], out bool IncludeModdedItems))
                    {
                        Monitor.Log(string.Format("Unable to execute command: '{0}' is not a valid value for the IncludeModdedItems parameter. Expected values are 'true' or 'false' (without the quotes)", Args[1]), LogLevel.Alert);
                    }
                    else
                    {
                        string[] SortingArgs = Args[2].Split(',');
                        if (SortingArgs.Length == 0)
                        {
                            Monitor.Log(string.Format("Unable to execute command: '{0}' is not a valid value for the SortingOrder parameter. Type 'help {1}' for more details on using this command.", Args[2], CommandName), LogLevel.Alert);
                        }
                        else
                        {
                            bool IsOrderValid = true;
                            List <Persistence.KeyValuePair <SortingProperty, SortingOrder> > OrderBy = new List <Persistence.KeyValuePair <SortingProperty, SortingOrder> >();
                            foreach (string Value in SortingArgs)
                            {
                                string PropertyName;
                                string OrderName;
                                if (Value.Contains('-'))
                                {
                                    PropertyName = Value.Split('-')[0];
                                    OrderName    = Value.Split('-')[1];
                                }
                                else
                                {
                                    PropertyName = Value;
                                    OrderName    = SortingOrder.Ascending.ToString();
                                }

                                if (!Enum.TryParse(PropertyName, out SortingProperty Property))
                                {
                                    Monitor.Log(string.Format("Unable to execute command: '{0}' is not a valid sorting property. Expected values are: {1} {2} {3} {4}. " +
                                                              "Type 'help {5}' for more details on using this command.",
                                                              PropertyName, SortingProperty.Name, SortingProperty.Id, SortingProperty.Category, SortingProperty.SingleValue, CommandName), LogLevel.Alert);
                                    IsOrderValid = false;
                                    break;
                                }

                                if (!Enum.TryParse(OrderName, out SortingOrder Direction))
                                {
                                    Monitor.Log(string.Format("Unable to execute command: '{0}' is not a valid sorting direction. Expected values are: {1} or {2}. " +
                                                              "Type 'help {3}' for more details on using this command.",
                                                              OrderName, SortingOrder.Ascending, SortingOrder.Descending, CommandName), LogLevel.Alert);
                                    IsOrderValid = false;
                                    break;
                                }

                                OrderBy.Add(new Persistence.KeyValuePair <SortingProperty, SortingOrder>(Property, Direction));
                            }

                            if (IsOrderValid)
                            {
                                string BagName = Args[3];

                                HashSet <string> CategoryValues = new HashSet <string>(Args.Skip(4));

                                //  Get all modded item names
                                HashSet <string> ModdedItemNames = new HashSet <string>();
                                IJsonAssetsAPI API = Helper.ModRegistry.GetApi <IJsonAssetsAPI>(ItemBagsMod.JAUniqueId);
                                if (API != null)
                                {
                                    foreach (string ItemName in API.GetAllBigCraftableIds().Keys)
                                    {
                                        ModdedItemNames.Add(ItemName);
                                    }
                                    foreach (string ItemName in API.GetAllObjectIds().Keys)
                                    {
                                        ModdedItemNames.Add(ItemName);
                                    }
                                }

                                //  Get the items that match the desired conditions
                                List <SObject> TargetItems = new List <SObject>();
                                foreach (var KVP in Game1.objectInformation)
                                {
                                    int Id            = KVP.Key;
                                    SObject Instance  = new SObject(Id, 1);
                                    bool IsModdedItem = ModdedItemNames.Contains(Instance.DisplayName);

                                    if ((IsModdedItem && IncludeModdedItems) || (!IsModdedItem && IncludeVanillaItems))
                                    {
                                        if (CategoryValues.Contains(Instance.getCategoryName()) || CategoryValues.Contains(Instance.Category.ToString()))
                                        {
                                            TargetItems.Add(Instance);
                                        }
                                    }
                                }
                                foreach (var KVP in Game1.bigCraftablesInformation)
                                {
                                    int Id            = KVP.Key;
                                    SObject Instance  = new SObject(Vector2.Zero, Id, false);
                                    bool IsModdedItem = ModdedItemNames.Contains(Instance.DisplayName);

                                    if ((IsModdedItem && IncludeModdedItems) || (!IsModdedItem && IncludeVanillaItems))
                                    {
                                        if (CategoryValues.Contains(Instance.getCategoryName()) || CategoryValues.Contains(Instance.Category.ToString()))
                                        {
                                            TargetItems.Add(Instance);
                                        }
                                    }
                                }

                                List <string> Names = TargetItems.Select(x => x.DisplayName).ToList();

                                //  Sort the items
                                IOrderedEnumerable <SObject> SortedItems = ApplySorting(TargetItems, OrderBy[0].Key, OrderBy[0].Value);
                                Names = SortedItems.Select(x => x.DisplayName).ToList();
                                foreach (var KVP in OrderBy.Skip(1))
                                {
                                    SortedItems = ApplySorting(SortedItems, KVP.Key, KVP.Value);
                                    Names       = SortedItems.Select(x => x.DisplayName).ToList();
                                }

                                //  Generate the bag
                                List <ContainerSize> AllSizes = Enum.GetValues(typeof(ContainerSize)).Cast <ContainerSize>().ToList();
                                ModdedBag ModdedBag           = new ModdedBag()
                                {
                                    IsEnabled      = true,
                                    ModUniqueId    = ItemBagsMod.ModUniqueId,
                                    Guid           = ModdedBag.StringToGUID(ItemBagsMod.ModUniqueId + BagName).ToString(),
                                    BagName        = BagName,
                                    BagDescription = "A bag for storing items of specific category(s)",
                                    IconTexture    = BagType.SourceTexture.SpringObjects,
                                    IconPosition   = new Rectangle(),
                                    Prices         = AllSizes.ToDictionary(x => x, x => BagTypeFactory.DefaultPrices[x]),
                                    Capacities     = AllSizes.ToDictionary(x => x, x => BagTypeFactory.DefaultCapacities[x]),
                                    Sellers        = AllSizes.ToDictionary(x => x, x => new List <BagShop>()
                                    {
                                        BagShop.Pierre
                                    }),
                                    MenuOptions = AllSizes.ToDictionary(x => x, x => new BagMenuOptions()
                                    {
                                        GroupedLayoutOptions = new BagMenuOptions.GroupedLayout()
                                        {
                                            GroupsPerRow = 5
                                        },
                                        UngroupedLayoutOptions = new BagMenuOptions.UngroupedLayout()
                                        {
                                            Columns = 18
                                        }
                                    }),
                                    Items = SortedItems.Select(x => new ModdedItem(x, !ModdedItemNames.Contains(x.DisplayName))).ToList()
                                };

                                string OutputDirectory = Path.Combine(Helper.DirectoryPath, "assets", "Modded Bags");
                                string DesiredFilename = string.Format("Category-{0}", BagName);
                                string CurrentFilename = DesiredFilename;
                                int CurrentIndex       = 0;
                                while (File.Exists(Path.Combine(OutputDirectory, CurrentFilename + ".json")))
                                {
                                    CurrentIndex++;
                                    CurrentFilename = string.Format("{0} ({1})", DesiredFilename, CurrentIndex);
                                }

                                string RelativePath = Path.Combine("assets", "Modded Bags", CurrentFilename + ".json");
                                Helper.Data.WriteJsonFile(RelativePath, ModdedBag);

                                Monitor.Log(string.Format("File exported to: {0}\nYou will need to re-launch the game for this file to be loaded.", Path.Combine(Helper.DirectoryPath, RelativePath)), LogLevel.Alert);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log(string.Format("ItemBags: Unhandled error while executing command: {0}", ex.Message), LogLevel.Error);
                }
            });
        }
Пример #5
0
        private static void RegisterGenerateModdedBagCommand()
        {
            string CommandName = "generate_modded_bag";
            string CommandHelp = string.Format("Creates a json file that defines a modded Item Bag for a particular mod.\n"
                                               + "Arguments: <BagName> <ModUniqueID> (This is the 'ModUniqueID' value of the mod's manifest.json that you want to generate the file for. All modded items belonging to this mod will be included in the generated modded bag)\n"
                                               + "If the BagName is multiple words, wrap it in double quotes."
                                               + "Example: {0} \"Artisan Valley Bag\" ppja.artisanvalleymachinegoods\n\n",
                                               CommandName);

            Helper.ConsoleCommands.Add(CommandName, CommandHelp, (string Name, string[] Args) =>
            {
                try
                {
                    if (!Helper.ModRegistry.IsLoaded(ItemBagsMod.JAUniqueId))
                    {
                        Monitor.Log("Unable to execute command: JsonAssets mod is not installed. Modded bags only support modded objects added through JsonAssets.", LogLevel.Alert);
                    }
                    else if (!Context.IsWorldReady)
                    {
                        Monitor.Log("Unable to execute command: JsonAssets has not finished loading modded items. You must load a save file before using this command.", LogLevel.Alert);
                    }
                    else if (Args.Length < 2)
                    {
                        Monitor.Log("Unable to execute command: Required arguments missing. You must specify a Bag Name and a ModUniqueID. All modded items from the given ModUniqueID will be included in the generated bag.", LogLevel.Alert);
                    }
                    else
                    {
                        string BagName     = Args[0];
                        string ModUniqueId = string.Join(" ", Args.Skip(1));
                        if (!Helper.ModRegistry.IsLoaded(ModUniqueId))
                        {
                            string Message = string.Format("Unable to execute command: ModUniqueID = '{0}' is not installed. "
                                                           + "Either install this mod first, or double check that you used the correct value for ModUniqueID. "
                                                           + "The ModUniqueID can be found in the mod's manifest.json file.", ModUniqueId);
                            Monitor.Log(Message, LogLevel.Alert);
                        }
                        else
                        {
                            IJsonAssetsAPI API = Helper.ModRegistry.GetApi <IJsonAssetsAPI>(ItemBagsMod.JAUniqueId);
                            if (API != null)
                            {
#if NEVER //DEBUG
                                //  Trying to figure out how to get seed ids belonging to a particular mod.
                                //  It seems like GetAllObjectsFromContentPack doesn't include the seeds, even though they are in GetAllObjectIds
                                string TestSeedName = "Adzuki Bean Seeds";
                                IDictionary <string, int> AllObjectIds = API.GetAllObjectIds();
                                List <string> AllObjectsInMod          = API.GetAllObjectsFromContentPack(ModUniqueId);
                                bool IsSeedFoundAnywhere = AllObjectIds != null && AllObjectIds.ContainsKey(TestSeedName);
                                bool IsSeedFoundInMod    = AllObjectsInMod != null && AllObjectsInMod.Contains(TestSeedName);
                                int SeedId = API.GetObjectId(TestSeedName);
#endif
                                List <ContainerSize> AllSizes = Enum.GetValues(typeof(ContainerSize)).Cast <ContainerSize>().ToList();

                                ModdedBag ModdedBag = new ModdedBag()
                                {
                                    IsEnabled      = true,
                                    ModUniqueId    = ModUniqueId,
                                    Guid           = ModdedBag.StringToGUID(ModUniqueId + BagName).ToString(),
                                    BagName        = BagName,
                                    BagDescription = string.Format("A bag for storing items belonging to {0} mod", ModUniqueId),
                                    IconTexture    = BagType.SourceTexture.SpringObjects,
                                    IconPosition   = new Rectangle(),
                                    Prices         = AllSizes.ToDictionary(x => x, x => BagTypeFactory.DefaultPrices[x]),
                                    Capacities     = AllSizes.ToDictionary(x => x, x => BagTypeFactory.DefaultCapacities[x]),
                                    Sellers        = AllSizes.ToDictionary(x => x, x => new List <BagShop>()
                                    {
                                        BagShop.Pierre
                                    }),
                                    MenuOptions = AllSizes.ToDictionary(x => x, x => new BagMenuOptions()
                                    {
                                        GroupedLayoutOptions = new BagMenuOptions.GroupedLayout()
                                        {
                                            GroupsPerRow = 5
                                        }
                                    }),
                                    Items = ModdedBag.GetModdedItems(ModUniqueId)
                                };

                                string OutputDirectory = Path.Combine(Helper.DirectoryPath, "assets", "Modded Bags");
                                string DesiredFilename = ModdedBag.ModUniqueId;
                                string CurrentFilename = DesiredFilename;
                                int CurrentIndex       = 0;
                                while (File.Exists(Path.Combine(OutputDirectory, CurrentFilename + ".json")))
                                {
                                    CurrentIndex++;
                                    CurrentFilename = string.Format("{0} ({1})", DesiredFilename, CurrentIndex);
                                }

                                string RelativePath = Path.Combine("assets", "Modded Bags", CurrentFilename + ".json");
                                Helper.Data.WriteJsonFile(RelativePath, ModdedBag);

                                Monitor.Log(string.Format("File exported to: {0}\nYou will need to re-launch the game for this file to be loaded.", Path.Combine(Helper.DirectoryPath, RelativePath)), LogLevel.Alert);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log(string.Format("ItemBags: Unhandled error while executing command: {0}", ex.Message), LogLevel.Error);
                }
            });
        }
Пример #6
0
        public override void Entry(IModHelper helper)
        {
            ModInstance = this;

            if (Constants.TargetPlatform != GamePlatform.Android) // Android version saves items without the use of PyTK. See Helpers\SaveLoadHelpers.cs
            {
                //  SpaceCore v1.5.0 introduced a breaking change to the game's saving/loading logic that is not compatible with my custom items
                if (Helper.ModRegistry.IsLoaded(SpaceCoreUniqueId))
                {
                    IModInfo SpaceCoreInfo = Helper.ModRegistry.Get(SpaceCoreUniqueId);
                    if (SpaceCoreInfo.Manifest.Version.IsNewerThan("1.4.1"))
                    {
                        throw new InvalidOperationException("This mod is not compatible with SpaceCore v1.5.0 due to the changes SpaceCore makes to the game's save serializer, " +
                                                            "which are not compatible with PyTK's CustomElementHandler.ISaveElement that this mod utilizes. " +
                                                            "To use Item Bags, consider downgrading to an earlier version of SpaceCore such as v1.3.5.");
                    }
                }
            }

            LoadUserConfig();
            LoadGlobalConfig();
            LoadModdedItems();
            LoadModdedBags();
            BagConfig.AfterLoaded();

            helper.Events.Display.MenuChanged   += Display_MenuChanged;
            helper.Events.Display.WindowResized += Display_WindowResized;

            helper.Events.GameLoop.UpdateTicked += GameLoop_UpdateTicked;

            helper.Events.GameLoop.Saving     += (sender, e) => { SaveLoadHelpers.OnSaving(); };
            helper.Events.GameLoop.Saved      += (sender, e) => { SaveLoadHelpers.OnSaved(); };
            helper.Events.GameLoop.SaveLoaded += (sender, e) => { SaveLoadHelpers.OnLoaded(); };

            helper.Events.GameLoop.GameLaunched += (sender, e) =>
            {
                //  Add compatibility with the Save Anywhere mod
                bool IsSaveAnywhereInstalled = Helper.ModRegistry.IsLoaded(SaveAnywhereUniqueId) ||
                                               Helper.ModRegistry.GetAll().Any(x => x.Manifest.Name.Equals("Save Anywhere", StringComparison.CurrentCultureIgnoreCase));
                if (IsSaveAnywhereInstalled)
                {
                    try
                    {
                        ISaveAnywhereAPI API = Helper.ModRegistry.GetApi <ISaveAnywhereAPI>(SaveAnywhereUniqueId);
                        if (API != null)
                        {
                            API.addBeforeSaveEvent(ModUniqueId, () => { SaveLoadHelpers.OnSaving(); });
                            API.addAfterSaveEvent(ModUniqueId, () => { SaveLoadHelpers.OnSaved(); });
                            API.addAfterLoadEvent(ModUniqueId, () => { SaveLoadHelpers.OnLoaded(); });
                        }
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log(string.Format("Failed to bind to Save Anywhere's Mod API. Your game may crash while saving with Save Anywhere! Error: {0}", ex.Message), LogLevel.Warn);
                    }
                }

                //  Add compatibility with v1.5.0 of SpaceCore (v1.5.0 added changes that use Harmony to override the game's XmlSerializer for saving/loading save files)

                /*if (Helper.ModRegistry.IsLoaded(SpaceCoreUniqueId))
                 * {
                 *  IModInfo SpaceCoreInfo = Helper.ModRegistry.Get(SpaceCoreUniqueId);
                 *  if (SpaceCoreInfo.Manifest.Version.IsNewerThan("1.4.0"))
                 *  {
                 *      try
                 *      {
                 *          SpaceCoreAPI API = Helper.ModRegistry.GetApi<SpaceCoreAPI>(SpaceCoreUniqueId);
                 *          if (API != null)
                 *          {
                 *              //  I couldn't get this to work with PyTK. Most of my items' data is loaded via PyTK's ISaveElement.rebuild function, which doesn't play nicely with SpaceCore
                 *              //  (I'm not sure what's happening, but I assume that either rebuild isn't getting called, or it's getting called before SpaceCore finishes deserializing, so the data is overwritten with default values.)
                 *              API.RegisterSerializerType(typeof(BoundedBag));
                 *              API.RegisterSerializerType(typeof(BundleBag));
                 *              API.RegisterSerializerType(typeof(OmniBag));
                 *              API.RegisterSerializerType(typeof(Rucksack));
                 *          }
                 *      }
                 *      catch (Exception ex)
                 *      {
                 *          Monitor.Log(string.Format("Failed to bind to SpaceCore's Mod API. If your bags are not loading or you have errors while saving, " +
                 *              "try downgrading to SpaceCore version 1.4.0! Error: {0}", ex.Message), LogLevel.Warn);
                 *      }
                 *  }
                 * }*/

                ModdedBag.OnGameLaunched();
            };

            InputHandler.OnModEntry(helper);
            CraftingHandler.OnModEntry(helper);
            CommandHandler.OnModEntry(helper);
            AutofillHandler.OnModEntry(helper);
            MultiplayerHandler.OnModEntry(helper);
            MonsterLootHandler.OnModEntry(helper);
        }
Пример #7
0
        public override void Entry(IModHelper helper)
        {
            ModInstance = this;

            if (Helper.ModRegistry.IsLoaded(EntoaroxFrameworkUniqueId) && Helper.ModRegistry.Get(EntoaroxFrameworkUniqueId).Manifest.Version.IsOlderThan("2.5.5"))
            {
                Monitor.Log("WARNING - Your game may fail to save with ItemBags and Entoarox Framework installed, " +
                            "since both of these mods attempt to override the game's save serializer to handle saving/loading of custom items. " +
                            "Consider updating to a newer version of Entoarox Framework to resolve this compatibility issue.", LogLevel.Warn);
            }

            LoadUserConfig();
            LoadGlobalConfig();
            LoadModdedItems();
            LoadModdedBags();
            BagConfig.AfterLoaded();

            helper.Events.Display.MenuChanged   += Display_MenuChanged;
            helper.Events.Display.WindowResized += Display_WindowResized;

            helper.Events.GameLoop.UpdateTicked += GameLoop_UpdateTicked;

            helper.Events.GameLoop.Saving     += (sender, e) => { SaveLoadHelpers.OnSaving(); };
            helper.Events.GameLoop.Saved      += (sender, e) => { SaveLoadHelpers.OnSaved(); };
            helper.Events.GameLoop.SaveLoaded += (sender, e) => { SaveLoadHelpers.OnLoaded(); };

            helper.Events.GameLoop.GameLaunched += (sender, e) =>
            {
                //  Add compatibility with the Save Anywhere mod
                bool IsSaveAnywhereInstalled = Helper.ModRegistry.IsLoaded(SaveAnywhereUniqueId) ||
                                               Helper.ModRegistry.GetAll().Any(x => x.Manifest.Name.Equals("Save Anywhere", StringComparison.CurrentCultureIgnoreCase));
                if (IsSaveAnywhereInstalled)
                {
                    try
                    {
                        ISaveAnywhereAPI API = Helper.ModRegistry.GetApi <ISaveAnywhereAPI>(SaveAnywhereUniqueId);
                        if (API != null)
                        {
                            API.addBeforeSaveEvent(ModUniqueId, () => { SaveLoadHelpers.OnSaving(); });
                            API.addAfterSaveEvent(ModUniqueId, () => { SaveLoadHelpers.OnSaved(); });
                            API.addAfterLoadEvent(ModUniqueId, () => { SaveLoadHelpers.OnLoaded(); });
                        }
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log(string.Format("Failed to bind to Save Anywhere's Mod API. Your game may crash while saving with Save Anywhere! Error: {0}", ex.Message), LogLevel.Warn);
                    }
                }

                //  Add compatibility with Entoarox Framework mod
                //  (By default, Entoarox Framework overrides the game's save serializer. SpaceCore also overrides the serializer, causing a conflicts since this mod relies on SpaceCore to handle saving/loading items)
                if (Helper.ModRegistry.IsLoaded(EntoaroxFrameworkUniqueId) && !Helper.ModRegistry.Get(EntoaroxFrameworkUniqueId).Manifest.Version.IsOlderThan("2.5.5"))
                {
                    try
                    {
                        IEntoaroxFrameworkAPI API = Helper.ModRegistry.GetApi <IEntoaroxFrameworkAPI>(EntoaroxFrameworkUniqueId);
                        if (API != null)
                        {
                            //  Disable Entoarox Frameworks logic for overriding the save serializer
                            API.HoistSerializerOwnership();
                        }
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log(string.Format("Failed to bind to Entoarox Framework's Mod API. Your game may crash while saving with Entoarox Framework! Error: {0}", ex.Message), LogLevel.Warn);
                    }
                }


                //  Register custom types for serialization
#if !ANDROID
                if (Helper.ModRegistry.IsLoaded(SpaceCoreUniqueId))
                {
                    IModInfo      SpaceCoreInfo = Helper.ModRegistry.Get(SpaceCoreUniqueId);
                    ISpaceCoreAPI API           = Helper.ModRegistry.GetApi <ISpaceCoreAPI>(SpaceCoreUniqueId);
                    API.RegisterSerializerType(typeof(BoundedBag));
                    API.RegisterSerializerType(typeof(BundleBag));
                    API.RegisterSerializerType(typeof(OmniBag));
                    API.RegisterSerializerType(typeof(Rucksack));
                }
#endif

                ModdedBag.OnGameLaunched();
            };

            InputHandler.OnModEntry(helper);
            CraftingHandler.OnModEntry(helper);
            CommandHandler.OnModEntry(helper);
            AutofillHandler.OnModEntry(helper);
            MultiplayerHandler.OnModEntry(helper);
            MonsterLootHandler.OnModEntry(helper);
            LegacyDataMigrator.OnModEntry(helper);
        }