diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..5bfc44bd --- /dev/null +++ b/.editorconfig @@ -0,0 +1,67 @@ +# topmost editorconfig +root: true + +########## +## General formatting +## documentation: https://editorconfig.org +########## +[*] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +[*.{csproj,json,nuspec,targets}] +indent_size = 2 + +[*.csproj] +insert_final_newline = false + +########## +## C# formatting +## documentation: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference +########## +[*.cs] + +#sort 'system' usings first +dotnet_sort_system_directives_first = true + +# use 'this.' qualifier +dotnet_style_qualification_for_field = true:error +dotnet_style_qualification_for_property = true:error +dotnet_style_qualification_for_method = true:error +dotnet_style_qualification_for_event = true:error + +# use language keywords (like int) instead of type (like Int32) +dotnet_style_predefined_type_for_locals_parameters_members = true:error +dotnet_style_predefined_type_for_member_access = true:error + +# don't use 'var' for language keywords +csharp_style_var_for_built_in_types = false:error + +# suggest modern C# features where simpler +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion + +# prefer method block bodies +csharp_style_expression_bodied_methods = false:suggestion +csharp_style_expression_bodied_constructors = false:suggestion + +# prefer property expression bodies +csharp_style_expression_bodied_properties = true:suggestion +csharp_style_expression_bodied_indexers = true:suggestion +csharp_style_expression_bodied_accessors = true:suggestion + +# prefer inline out variables +csharp_style_inlined_variable_declaration = true:warning + +# avoid superfluous braces +csharp_prefer_braces = false:suggestion diff --git a/GeneralMods/AdvancedSaveBackup/AdvancedSaveBackup.csproj b/GeneralMods/AdvancedSaveBackup/AdvancedSaveBackup.csproj index eeae3c37..46bf2a7a 100644 --- a/GeneralMods/AdvancedSaveBackup/AdvancedSaveBackup.csproj +++ b/GeneralMods/AdvancedSaveBackup/AdvancedSaveBackup.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ AdvancedSaveBackup v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -83,19 +84,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/AdvancedSaveBackup/Framework/ModConfig.cs b/GeneralMods/AdvancedSaveBackup/Framework/ModConfig.cs index 1612c9f8..be464717 100644 --- a/GeneralMods/AdvancedSaveBackup/Framework/ModConfig.cs +++ b/GeneralMods/AdvancedSaveBackup/Framework/ModConfig.cs @@ -1,4 +1,4 @@ -namespace Omegasis.SaveBackup.Framework +namespace Omegasis.SaveBackup.Framework { /// The mod configuration. internal class ModConfig diff --git a/GeneralMods/AdvancedSaveBackup/SaveBackup.cs b/GeneralMods/AdvancedSaveBackup/SaveBackup.cs index b10f0878..592b6b35 100644 --- a/GeneralMods/AdvancedSaveBackup/SaveBackup.cs +++ b/GeneralMods/AdvancedSaveBackup/SaveBackup.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.IO.Compression; using System.Linq; @@ -12,7 +12,7 @@ namespace Omegasis.SaveBackup public class SaveBackup : Mod { /********* - ** Properties + ** Fields *********/ /// The folder path containing the game's app data. private static readonly string AppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley"); @@ -41,17 +41,17 @@ namespace Omegasis.SaveBackup this.BackupSaves(SaveBackup.PrePlayBackupsPath); - SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; + helper.Events.GameLoop.Saving += this.OnSaving; } /********* ** Private methods *********/ - /// The method invoked before the save is updated. + /// Raised before the game begins writes data to the save file (except the initial save creation). /// The event sender. - /// The event data. - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + private void OnSaving(object sender, SavingEventArgs e) { this.BackupSaves(SaveBackup.NightlyBackupsPath); } diff --git a/GeneralMods/AdvancedSaveBackup/manifest.json b/GeneralMods/AdvancedSaveBackup/manifest.json index f4afb5a4..bb113ace 100644 --- a/GeneralMods/AdvancedSaveBackup/manifest.json +++ b/GeneralMods/AdvancedSaveBackup/manifest.json @@ -1,10 +1,10 @@ { "Name": "Advanced Save Backup", "Author": "Alpha_Omegasis", - "Version": "1.5.0", + "Version": "1.6.0", "Description": "Backs up your save files when loading SMAPI and every in game night when saving.", "UniqueID": "Omegasis.AdvancedSaveBackup", "EntryDll": "AdvancedSaveBackup.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:435" ] } diff --git a/GeneralMods/AdvancedSaveBackup/packages.config b/GeneralMods/AdvancedSaveBackup/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/AdvancedSaveBackup/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/AutoSpeed/AutoSpeed.cs b/GeneralMods/AutoSpeed/AutoSpeed.cs index ec6bb545..d4859a35 100644 --- a/GeneralMods/AutoSpeed/AutoSpeed.cs +++ b/GeneralMods/AutoSpeed/AutoSpeed.cs @@ -1,4 +1,3 @@ -using System; using Omegasis.AutoSpeed.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; @@ -10,7 +9,7 @@ namespace Omegasis.AutoSpeed public class AutoSpeed : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -23,7 +22,7 @@ namespace Omegasis.AutoSpeed /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { - GameEvents.UpdateTick += this.GameEvents_UpdateTick; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; this.Config = helper.ReadConfig(); } @@ -31,10 +30,10 @@ namespace Omegasis.AutoSpeed /********* ** Private methods *********/ - /// The method invoked when the game updates (roughly 60 times per second). + /// Raised after the game state is updated (≈60 times per second). /// The event sender. - /// The event data. - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { if (Context.IsPlayerFree) Game1.player.addedSpeed = this.Config.Speed; diff --git a/GeneralMods/AutoSpeed/AutoSpeed.csproj b/GeneralMods/AutoSpeed/AutoSpeed.csproj index 23545179..50269de6 100644 --- a/GeneralMods/AutoSpeed/AutoSpeed.csproj +++ b/GeneralMods/AutoSpeed/AutoSpeed.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ AutoSpeed v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -81,19 +82,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/AutoSpeed/Framework/ModConfig.cs b/GeneralMods/AutoSpeed/Framework/ModConfig.cs index ee3eef38..2e6dc10f 100644 --- a/GeneralMods/AutoSpeed/Framework/ModConfig.cs +++ b/GeneralMods/AutoSpeed/Framework/ModConfig.cs @@ -1,4 +1,4 @@ -namespace Omegasis.AutoSpeed.Framework +namespace Omegasis.AutoSpeed.Framework { /// The mod configuration. internal class ModConfig diff --git a/GeneralMods/AutoSpeed/manifest.json b/GeneralMods/AutoSpeed/manifest.json index 5dd4808f..acc444d5 100644 --- a/GeneralMods/AutoSpeed/manifest.json +++ b/GeneralMods/AutoSpeed/manifest.json @@ -1,10 +1,10 @@ { "Name": "Auto Speed", "Author": "Alpha_Omegasis", - "Version": "1.6.0", + "Version": "1.7.0", "Description": "Got to go fast!", "UniqueID": "Omegasis.AutoSpeed", "EntryDll": "AutoSpeed.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:443" ] } diff --git a/GeneralMods/AutoSpeed/packages.config b/GeneralMods/AutoSpeed/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/AutoSpeed/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/BillboardAnywhere/BillboardAnywhere.cs b/GeneralMods/BillboardAnywhere/BillboardAnywhere.cs index 50480d7b..494db12c 100644 --- a/GeneralMods/BillboardAnywhere/BillboardAnywhere.cs +++ b/GeneralMods/BillboardAnywhere/BillboardAnywhere.cs @@ -1,4 +1,4 @@ -using Omegasis.BillboardAnywhere.Framework; +using Omegasis.BillboardAnywhere.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; @@ -10,7 +10,7 @@ namespace Omegasis.BillboardAnywhere public class BillboardAnywhere : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -25,20 +25,20 @@ namespace Omegasis.BillboardAnywhere { this.Config = helper.ReadConfig(); - ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; + helper.Events.Input.ButtonPressed += this.OnButtonPressed; } /********* ** Private methods *********/ - /// The method invoked when the presses a keyboard button. + /// Raised after the player presses a button on the keyboard, controller, or mouse. /// The event sender. - /// The event data. - public void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) + /// The event arguments. + public void OnButtonPressed(object sender, ButtonPressedEventArgs e) { // load menu if key pressed - if (Context.IsPlayerFree && e.KeyPressed.ToString() == this.Config.KeyBinding) + if (Context.IsPlayerFree && e.Button == this.Config.KeyBinding) Game1.activeClickableMenu = new Billboard(); } } diff --git a/GeneralMods/BillboardAnywhere/BillboardAnywhere.csproj b/GeneralMods/BillboardAnywhere/BillboardAnywhere.csproj index a3638df8..d98ba599 100644 --- a/GeneralMods/BillboardAnywhere/BillboardAnywhere.csproj +++ b/GeneralMods/BillboardAnywhere/BillboardAnywhere.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ BillboardAnywhere v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -83,19 +84,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/BillboardAnywhere/Framework/ModConfig.cs b/GeneralMods/BillboardAnywhere/Framework/ModConfig.cs index e57f51ce..8f16e667 100644 --- a/GeneralMods/BillboardAnywhere/Framework/ModConfig.cs +++ b/GeneralMods/BillboardAnywhere/Framework/ModConfig.cs @@ -1,9 +1,11 @@ -namespace Omegasis.BillboardAnywhere.Framework +using StardewModdingAPI; + +namespace Omegasis.BillboardAnywhere.Framework { /// The mod configuration. internal class ModConfig { /// The key which shows the billboard menu. - public string KeyBinding { get; set; } = "B"; + public SButton KeyBinding { get; set; } = SButton.B; } } diff --git a/GeneralMods/BillboardAnywhere/manifest.json b/GeneralMods/BillboardAnywhere/manifest.json index d8d45b95..5685e1ec 100644 --- a/GeneralMods/BillboardAnywhere/manifest.json +++ b/GeneralMods/BillboardAnywhere/manifest.json @@ -1,10 +1,10 @@ { "Name": "Billboard Anywhere", "Author": "Alpha_Omegasis", - "Version": "1.6.0", + "Version": "1.7.0", "Description": "Lets you view the billboard from anywhere.", "UniqueID": "Omegasis.BillboardAnywhere", "EntryDll": "BillboardAnywhere.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:492" ] } diff --git a/GeneralMods/BillboardAnywhere/packages.config b/GeneralMods/BillboardAnywhere/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/BillboardAnywhere/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/BuildEndurance/BuildEndurance.cs b/GeneralMods/BuildEndurance/BuildEndurance.cs index 763e619a..4c8f5a6e 100644 --- a/GeneralMods/BuildEndurance/BuildEndurance.cs +++ b/GeneralMods/BuildEndurance/BuildEndurance.cs @@ -1,6 +1,4 @@ -using System; using System.IO; -using System.Linq; using Omegasis.BuildEndurance.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; @@ -12,13 +10,10 @@ namespace Omegasis.BuildEndurance public class BuildEndurance : Mod { /********* - ** Properties + ** Fields *********/ /// The relative path for the current player's data file. - private string DataFilePath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); - - /// The absolute path for the current player's legacy data file. - private string LegacyDataFilePath => Path.Combine(this.Helper.DirectoryPath, "PlayerData", $"BuildEndurance_data_{Game1.player.Name}.txt"); + private string RelativeDataPath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); /// The mod settings. private ModConfig Config; @@ -38,10 +33,10 @@ namespace Omegasis.BuildEndurance /// Whether the player was eating last time we checked. private bool WasEating; - public IModHelper ModHelper; public IMonitor ModMonitor; + /********* ** Public methods *********/ @@ -51,10 +46,9 @@ namespace Omegasis.BuildEndurance { this.Config = helper.ReadConfig(); - GameEvents.UpdateTick += this.GameEvents_UpdateTick; - GameEvents.OneSecondTick += this.GameEvents_OneSecondTick; - SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; - SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; + helper.Events.GameLoop.Saving += this.OnSaving; this.ModHelper = this.Helper; this.ModMonitor = this.Monitor; @@ -64,24 +58,18 @@ namespace Omegasis.BuildEndurance /********* ** Private methods *********/ - /// The method invoked once per second during a game update. + /// Raised after the game state is updated (≈60 times per second). /// The event sender. - /// The event data. - private void GameEvents_OneSecondTick(object sender, EventArgs e) - { - // nerf how quickly tool xp is gained (I hope) - if (this.HasRecentToolExp) - this.HasRecentToolExp = false; - } - - /// The method invoked when the game updates (roughly 60 times per second). - /// The event sender. - /// The event data. - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { if (!Context.IsWorldReady) return; + // nerf how quickly tool xp is gained (I hope) + if (e.IsOneSecond && this.HasRecentToolExp) + this.HasRecentToolExp = false; + // give XP when player finishes eating if (Game1.player.isEating) this.WasEating = true; @@ -107,19 +95,19 @@ namespace Omegasis.BuildEndurance } // give XP when player stays up too late or collapses - if (!this.WasCollapsed && shouldFarmerPassout()) + if (!this.WasCollapsed && this.shouldFarmerPassout()) { - + this.PlayerData.CurrentExp += this.Config.ExpForCollapsing; this.WasCollapsed = true; //this.Monitor.Log("The player has collapsed!"); } } - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - private void SaveEvents_AfterLoad(object sender, EventArgs e) + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { // reset state this.WasExhausted = false; @@ -128,8 +116,7 @@ namespace Omegasis.BuildEndurance this.WasEating = false; // load player data - this.MigrateLegacyData(); - this.PlayerData = this.Helper.ReadJsonFile(this.DataFilePath) ?? new PlayerData(); + this.PlayerData = this.Helper.Data.ReadJsonFile(this.RelativeDataPath) ?? new PlayerData(); if (this.PlayerData.OriginalMaxStamina == 0) this.PlayerData.OriginalMaxStamina = Game1.player.MaxStamina; @@ -155,10 +142,10 @@ namespace Omegasis.BuildEndurance } } - /// The method invoked just before the game is saved. + /// Raised before the game begins writes data to the save file (except the initial save creation). /// The event sender. - /// The event data. - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + private void OnSaving(object sender, SavingEventArgs e) { // reset data this.WasExhausted = false; @@ -184,47 +171,10 @@ namespace Omegasis.BuildEndurance this.PlayerData.NightlyStamina = Game1.player.MaxStamina; // save data - this.Helper.WriteJsonFile(this.DataFilePath, this.PlayerData); + this.Helper.Data.WriteJsonFile(this.RelativeDataPath, this.PlayerData); } - /// Migrate the legacy settings for the current player. - private void MigrateLegacyData() - { - // skip if no legacy data or new data already exists - if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath)) - return; - - // migrate to new file - try - { - string[] text = File.ReadAllLines(this.LegacyDataFilePath); - this.Helper.WriteJsonFile(this.DataFilePath, new PlayerData - { - CurrentLevel = Convert.ToInt32(text[3]), - CurrentExp = Convert.ToDouble(text[5]), - ExpToNextLevel = Convert.ToDouble(text[7]), - BaseStaminaBonus = Convert.ToInt32(text[9]), - CurrentLevelStaminaBonus = Convert.ToInt32(text[11]), - ClearModEffects = Convert.ToBoolean(text[14]), - OriginalMaxStamina = Convert.ToInt32(text[16]), - NightlyStamina = Convert.ToInt32(text[18]) - }); - - FileInfo file = new FileInfo(this.LegacyDataFilePath); - file.Delete(); - if (!file.Directory.EnumerateFiles().Any()) - file.Directory.Delete(); - } - catch (Exception ex) - { - this.Monitor.Log($"Error migrating data from the legacy 'PlayerData' folder for the current player. Technical details:\n {ex}", LogLevel.Error); - } - } - - /// - /// Try and emulate the old Game1.shouldFarmerPassout logic. - /// - /// + /// Try and emulate the old Game1.shouldFarmerPassout logic. public bool shouldFarmerPassout() { if (Game1.player.stamina <= 0 || Game1.player.health <= 0 || Game1.timeOfDay >= 2600) return true; diff --git a/GeneralMods/BuildEndurance/BuildEndurance.csproj b/GeneralMods/BuildEndurance/BuildEndurance.csproj index 0fd10fa4..83e9f2df 100644 --- a/GeneralMods/BuildEndurance/BuildEndurance.csproj +++ b/GeneralMods/BuildEndurance/BuildEndurance.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ BuildEndurance v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -82,19 +83,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/BuildEndurance/manifest.json b/GeneralMods/BuildEndurance/manifest.json index 6829e663..965d6449 100644 --- a/GeneralMods/BuildEndurance/manifest.json +++ b/GeneralMods/BuildEndurance/manifest.json @@ -1,10 +1,10 @@ { "Name": "Build Endurance", "Author": "Alpha_Omegasis", - "Version": "1.6.0", + "Version": "1.7.0", "Description": "Increase your health as you play.", "UniqueID": "Omegasis.BuildEndurance", "EntryDll": "BuildEndurance.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:445" ] } diff --git a/GeneralMods/BuildEndurance/packages.config b/GeneralMods/BuildEndurance/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/BuildEndurance/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/BuildHealth/BuildHealth.cs b/GeneralMods/BuildHealth/BuildHealth.cs index 1ba8210c..c27a2185 100644 --- a/GeneralMods/BuildHealth/BuildHealth.cs +++ b/GeneralMods/BuildHealth/BuildHealth.cs @@ -1,6 +1,4 @@ -using System; using System.IO; -using System.Linq; using Omegasis.BuildHealth.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; @@ -12,13 +10,10 @@ namespace Omegasis.BuildHealth public class BuildHealth : Mod { /********* - ** Properties + ** Fields *********/ /// The relative path for the current player's data file. - private string DataFilePath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); - - /// The absolute path for the current player's legacy data file. - private string LegacyDataFilePath => Path.Combine(this.Helper.DirectoryPath, "PlayerData", $"BuildHealth_data_{Game1.player.Name}.txt"); + private string RelativeDataPath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); /// The mod settings and player data. private ModConfig Config; @@ -46,10 +41,9 @@ namespace Omegasis.BuildHealth /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { - GameEvents.UpdateTick += this.GameEvents_UpdateTick; - GameEvents.OneSecondTick += this.GameEvents_OneSecondTick; - TimeEvents.AfterDayStarted += this.SaveEvents_BeforeSave; - SaveEvents.AfterLoad += this.SaveEvents_AfterLoaded; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + helper.Events.GameLoop.DayStarted += this.OnDayStarted; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; this.Config = helper.ReadConfig(); } @@ -58,24 +52,18 @@ namespace Omegasis.BuildHealth /********* ** Private methods *********/ - /// The method invoked once per second during a game update. + /// Raised after the game state is updated (≈60 times per second). /// The event sender. - /// The event data. - private void GameEvents_OneSecondTick(object sender, EventArgs e) - { - // nerf how quickly tool xp is gained (I hope) - if (this.HasRecentToolExp) - this.HasRecentToolExp = false; - } - - /// The method invoked when the game updates (roughly 60 times per second). - /// The event sender. - /// The event data. - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { if (!Context.IsWorldReady) return; + // nerf how quickly tool xp is gained (I hope) + if (e.IsOneSecond && this.HasRecentToolExp) + this.HasRecentToolExp = false; + // give XP when player finishes eating if (Game1.player.isEating) this.WasEating = true; @@ -103,17 +91,17 @@ namespace Omegasis.BuildHealth this.LastHealth = player.health; // give XP when player stays up too late or collapses - if (!this.WasCollapsed && shouldFarmerPassout()) + if (!this.WasCollapsed && this.shouldFarmerPassout()) { this.PlayerData.CurrentExp += this.Config.ExpForCollapsing; this.WasCollapsed = true; } } - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - private void SaveEvents_AfterLoaded(object sender, EventArgs e) + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { // reset state this.HasRecentToolExp = false; @@ -122,8 +110,7 @@ namespace Omegasis.BuildHealth this.WasCollapsed = false; // load player data - this.MigrateLegacyData(); - this.PlayerData = this.Helper.ReadJsonFile(this.DataFilePath) ?? new PlayerData(); + this.PlayerData = this.Helper.Data.ReadJsonFile(this.RelativeDataPath) ?? new PlayerData(); if (this.PlayerData.OriginalMaxHealth == 0) this.PlayerData.OriginalMaxHealth = Game1.player.maxHealth; @@ -145,10 +132,10 @@ namespace Omegasis.BuildHealth Game1.player.maxHealth = this.PlayerData.BaseHealthBonus + this.PlayerData.CurrentLevelHealthBonus + this.PlayerData.OriginalMaxHealth; } - /// The method invoked just before the game saves. + /// Raised after the game begins a new day (including when the player loads a save). /// The event sender. - /// The event data. - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + private void OnDayStarted(object sender, DayStartedEventArgs e) { // reset data this.LastHealth = Game1.player.maxHealth; @@ -174,40 +161,7 @@ namespace Omegasis.BuildHealth } // save data - this.Helper.WriteJsonFile(this.DataFilePath, this.PlayerData); - } - - /// Migrate the legacy settings for the current player. - private void MigrateLegacyData() - { - // skip if no legacy data or new data already exists - if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath)) - return; - - // migrate to new file - try - { - string[] text = File.ReadAllLines(this.LegacyDataFilePath); - this.Helper.WriteJsonFile(this.DataFilePath, new PlayerData - { - CurrentLevel = Convert.ToInt32(text[3]), - CurrentExp = Convert.ToDouble(text[5]), - ExpToNextLevel = Convert.ToDouble(text[7]), - BaseHealthBonus = Convert.ToInt32(text[9]), - CurrentLevelHealthBonus = Convert.ToInt32(text[11]), - ClearModEffects = Convert.ToBoolean(text[14]), - OriginalMaxHealth = Convert.ToInt32(text[16]) - }); - - FileInfo file = new FileInfo(this.LegacyDataFilePath); - file.Delete(); - if (!file.Directory.EnumerateFiles().Any()) - file.Directory.Delete(); - } - catch (Exception ex) - { - this.Monitor.Log($"Error migrating data from the legacy 'PlayerData' folder for the current player. Technical details:\n {ex}", LogLevel.Error); - } + this.Helper.Data.WriteJsonFile(this.RelativeDataPath, this.PlayerData); } public bool shouldFarmerPassout() diff --git a/GeneralMods/BuildHealth/BuildHealth.csproj b/GeneralMods/BuildHealth/BuildHealth.csproj index d1627a93..f1846f3b 100644 --- a/GeneralMods/BuildHealth/BuildHealth.csproj +++ b/GeneralMods/BuildHealth/BuildHealth.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ BuildHealth v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -82,19 +83,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/BuildHealth/Framework/ModConfig.cs b/GeneralMods/BuildHealth/Framework/ModConfig.cs index e0849f74..e627f69b 100644 --- a/GeneralMods/BuildHealth/Framework/ModConfig.cs +++ b/GeneralMods/BuildHealth/Framework/ModConfig.cs @@ -1,4 +1,4 @@ -namespace Omegasis.BuildHealth.Framework +namespace Omegasis.BuildHealth.Framework { /// The mod settings and player data. internal class ModConfig diff --git a/GeneralMods/BuildHealth/Framework/PlayerData.cs b/GeneralMods/BuildHealth/Framework/PlayerData.cs index 1e9cbb8e..2995d74f 100644 --- a/GeneralMods/BuildHealth/Framework/PlayerData.cs +++ b/GeneralMods/BuildHealth/Framework/PlayerData.cs @@ -1,4 +1,4 @@ -namespace Omegasis.BuildHealth.Framework +namespace Omegasis.BuildHealth.Framework { /// The data for the current player. internal class PlayerData diff --git a/GeneralMods/BuildHealth/manifest.json b/GeneralMods/BuildHealth/manifest.json index dff2d592..f68687dd 100644 --- a/GeneralMods/BuildHealth/manifest.json +++ b/GeneralMods/BuildHealth/manifest.json @@ -1,10 +1,10 @@ { "Name": "Build Health", "Author": "Alpha_Omegasis", - "Version": "1.6.0", + "Version": "1.7.0", "Description": "Increase your health as you play.", "UniqueID": "Omegasis.BuildHealth", "EntryDll": "BuildHealth.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:446" ] } diff --git a/GeneralMods/BuildHealth/packages.config b/GeneralMods/BuildHealth/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/BuildHealth/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/BuyBackCollectables/BuyBackCollectables.cs b/GeneralMods/BuyBackCollectables/BuyBackCollectables.cs index 91d89a06..30817b29 100644 --- a/GeneralMods/BuyBackCollectables/BuyBackCollectables.cs +++ b/GeneralMods/BuyBackCollectables/BuyBackCollectables.cs @@ -1,4 +1,4 @@ -using Omegasis.BuyBackCollectables.Framework; +using Omegasis.BuyBackCollectables.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; @@ -9,7 +9,7 @@ namespace Omegasis.BuyBackCollectables public class BuyBackCollectables : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -24,19 +24,19 @@ namespace Omegasis.BuyBackCollectables { this.Config = helper.ReadConfig(); - ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; + helper.Events.Input.ButtonPressed += this.OnButtonPressed; } /********* ** Private methods *********/ - /// The method invoked when the presses a keyboard button. + /// Raised after the player presses a button on the keyboard, controller, or mouse. /// The event sender. - /// The event data. - public void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) + /// The event arguments. + private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { - if (Context.IsPlayerFree && e.KeyPressed.ToString() == this.Config.KeyBinding) + if (Context.IsPlayerFree && e.Button == this.Config.KeyBinding) Game1.activeClickableMenu = new BuyBackMenu(this.Config.CostMultiplier); } } diff --git a/GeneralMods/BuyBackCollectables/BuyBackCollectables.csproj b/GeneralMods/BuyBackCollectables/BuyBackCollectables.csproj index 488853fb..dcba9f4e 100644 --- a/GeneralMods/BuyBackCollectables/BuyBackCollectables.csproj +++ b/GeneralMods/BuyBackCollectables/BuyBackCollectables.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ BuyBackCollectables v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -84,19 +85,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/BuyBackCollectables/Framework/BuyBackMenu.cs b/GeneralMods/BuyBackCollectables/Framework/BuyBackMenu.cs index 92e6b3e6..85efc9bd 100644 --- a/GeneralMods/BuyBackCollectables/Framework/BuyBackMenu.cs +++ b/GeneralMods/BuyBackCollectables/Framework/BuyBackMenu.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; @@ -13,7 +13,7 @@ namespace Omegasis.BuyBackCollectables.Framework internal class BuyBackMenu : IClickableMenu { /********* - ** Properties + ** Fields *********/ /// The organics tab ID. private const int OrganicsTab = 0; diff --git a/GeneralMods/BuyBackCollectables/Framework/ModConfig.cs b/GeneralMods/BuyBackCollectables/Framework/ModConfig.cs index deee9c28..27288986 100644 --- a/GeneralMods/BuyBackCollectables/Framework/ModConfig.cs +++ b/GeneralMods/BuyBackCollectables/Framework/ModConfig.cs @@ -1,10 +1,12 @@ -namespace Omegasis.BuyBackCollectables.Framework +using StardewModdingAPI; + +namespace Omegasis.BuyBackCollectables.Framework { /// The mod configuration. internal class ModConfig { /// The key which shows the menu. - public string KeyBinding { get; set; } = "B"; + public SButton KeyBinding { get; set; } = SButton.B; /// The multiplier applied to the cost of buying back a collectable. public double CostMultiplier { get; set; } = 3.0; diff --git a/GeneralMods/BuyBackCollectables/manifest.json b/GeneralMods/BuyBackCollectables/manifest.json index e700b1b2..c4349ae3 100644 --- a/GeneralMods/BuyBackCollectables/manifest.json +++ b/GeneralMods/BuyBackCollectables/manifest.json @@ -1,10 +1,10 @@ { "Name": "Buy Back Collectables", "Author": "Alpha_Omegasis", - "Version": "1.5.0", + "Version": "1.6.0", "Description": "Lets you buy back any obtained collectable.", "UniqueID": "Omegasis.BuyBackCollectables", "EntryDll": "BuyBackCollectables.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:507" ] } diff --git a/GeneralMods/BuyBackCollectables/packages.config b/GeneralMods/BuyBackCollectables/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/BuyBackCollectables/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/CustomFurnitureFramework/Class1.cs b/GeneralMods/CustomFurnitureFramework/Class1.cs new file mode 100644 index 00000000..b81717cd --- /dev/null +++ b/GeneralMods/CustomFurnitureFramework/Class1.cs @@ -0,0 +1,19 @@ +using StardewModdingAPI; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using PyTK; +using PyTK.CustomElementHandler; + +namespace CustomFurnitureFramework +{ + public class Class1 : Mod + { + public override void Entry(IModHelper helper) + { + + } + } +} diff --git a/GeneralMods/CustomFurnitureFramework/CustomFurnitureFramework.csproj b/GeneralMods/CustomFurnitureFramework/CustomFurnitureFramework.csproj new file mode 100644 index 00000000..9fb3791b --- /dev/null +++ b/GeneralMods/CustomFurnitureFramework/CustomFurnitureFramework.csproj @@ -0,0 +1,62 @@ + + + + + Debug + AnyCPU + {2FA81A17-D9A1-46D9-A5F7-A76AF9C70526} + Library + Properties + CustomFurnitureFramework + CustomFurnitureFramework + v4.6.1 + 512 + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + \ No newline at end of file diff --git a/GeneralMods/CustomFurnitureFramework/Properties/AssemblyInfo.cs b/GeneralMods/CustomFurnitureFramework/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4b409a25 --- /dev/null +++ b/GeneralMods/CustomFurnitureFramework/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomFurnitureFramework")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomFurnitureFramework")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2fa81a17-d9a1-46d9-a5f7-a76af9c70526")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/GeneralMods/FarmersMarketStall/packages.config b/GeneralMods/CustomFurnitureFramework/packages.config similarity index 100% rename from GeneralMods/FarmersMarketStall/packages.config rename to GeneralMods/CustomFurnitureFramework/packages.config diff --git a/GeneralMods/CustomNPCFramework/Class1.cs b/GeneralMods/CustomNPCFramework/Class1.cs index 03bac289..bbb7091e 100644 --- a/GeneralMods/CustomNPCFramework/Class1.cs +++ b/GeneralMods/CustomNPCFramework/Class1.cs @@ -1,20 +1,16 @@ -using CustomNPCFramework.Framework.Enums; -using CustomNPCFramework.Framework.Graphics; -using CustomNPCFramework.Framework.ModularNPCS; -using CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases; -using CustomNPCFramework.Framework.ModularNPCS.ColorCollections; -using CustomNPCFramework.Framework.NPCS; -using CustomNPCFramework.Framework.Utilities; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using StardewModdingAPI; -using StardewValley; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using CustomNPCFramework.Framework.Enums; +using CustomNPCFramework.Framework.Graphics; +using CustomNPCFramework.Framework.ModularNpcs.ColorCollections; +using CustomNPCFramework.Framework.NPCS; +using CustomNPCFramework.Framework.Utilities; +using Microsoft.Xna.Framework; +using StardewModdingAPI; +using StardewModdingAPI.Events; +using StardewValley; namespace CustomNPCFramework { @@ -44,90 +40,75 @@ namespace CustomNPCFramework /// Find way to make sideways shirts render correctly. /// ///Get suggestions from modding community on requests and ways to improve the mod. - /// - public class Class1 : Mod { - /// - /// The mod helper for the mod. - /// + /// The mod helper for the mod. public static IModHelper ModHelper; - /// - /// The mod monitor for the mod. - /// + + /// The mod monitor for the mod. public static IMonitor ModMonitor; - /// - /// The npc tracker for the mod. Keeps track of all npcs added by the custom framework and cleans them up during saving. - /// - public static NPCTracker npcTracker; - /// - /// Keeps track of all of the asets/textures added in by the framework. Also manages all of the asset managers that are the ones actually managing the textures. - /// + /// The npc tracker for the mod. Keeps track of all npcs added by the custom framework and cleans them up during saving. + public static NpcTracker npcTracker; + + /// Keeps track of all of the asets/textures added in by the framework. Also manages all of the asset managers that are the ones actually managing the textures. public static AssetPool assetPool; - - /// - /// Ran when loading the SMAPI. Used to initialize data. - /// - /// + + public static IManifest Manifest; + + /// The mod entry point, called after the mod is first loaded. + /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { ModHelper = this.Helper; ModMonitor = this.Monitor; + Manifest = this.ModManifest; - StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_LoadChar; - - StardewModdingAPI.Events.SaveEvents.BeforeSave += SaveEvents_BeforeSave; - StardewModdingAPI.Events.SaveEvents.AfterSave += SaveEvents_AfterSave; - - StardewModdingAPI.Events.PlayerEvents.Warped += LocationEvents_CurrentLocationChanged; - StardewModdingAPI.Events.GameEvents.UpdateTick += GameEvents_UpdateTick; - npcTracker = new NPCTracker(); + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; + helper.Events.GameLoop.Saving += this.OnSaving; + helper.Events.GameLoop.Saved += this.OnSaved; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + npcTracker = new NpcTracker(); assetPool = new AssetPool(); var assetManager = new AssetManager(); assetPool.addAssetManager(new KeyValuePair("testNPC", assetManager)); - initializeExamples(); - initializeAssetPool(); + this.initializeExamples(); + this.initializeAssetPool(); assetPool.loadAllAssets(); } - /// - /// Initialize the asset pool with some test variables. - /// + /// Initialize the asset pool with some test variables. public void initializeAssetPool() { - string path = Path.Combine(ModHelper.DirectoryPath, "Content", "Graphics", "NPCS"); - assetPool.getAssetManager("testNPC").addPathCreateDirectory(new KeyValuePair("characters", path)); + string relativePath = Path.Combine("Content", "Graphics", "NPCS"); + assetPool.getAssetManager("testNPC").addPathCreateDirectory(new KeyValuePair("characters", relativePath)); } - /// - /// A function that is called when the game finishes saving. - /// - /// - /// - private void SaveEvents_AfterSave(object sender, EventArgs e) + /// Raised after the game finishes writing data to the save file (except the initial save creation). + /// The event sender. + /// The event arguments. + private void OnSaved(object sender, SavedEventArgs e) { npcTracker.afterSave(); } - /// - /// A function that is called when the game is about to load. Used to clean up all the npcs from the game world to prevent it from crashing. - /// - /// - /// - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// Raised before the game begins writes data to the save file (except the initial save creation). + /// The event sender. + /// The event arguments. + private void OnSaving(object sender, SavingEventArgs e) { + // clean up all the npcs from the game world to prevent it from crashing npcTracker.cleanUpBeforeSave(); } - /// - /// Called upon 60 times a second. For testing purposes only. Will remove in future release. - /// - /// - /// - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// Raised after the game state is updated (≈60 times per second). + /// The event sender. + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { + // TODO For testing purposes only. Will remove in future release. + /* if (Game1.player.currentLocation == null) return; if (Game1.activeClickableMenu != null) return; @@ -144,93 +125,59 @@ namespace CustomNPCFramework */ } - /// - /// Called when the player's location changes. - /// - /// - /// - private void LocationEvents_CurrentLocationChanged(object sender, StardewModdingAPI.Events.EventArgsPlayerWarped e) + /// Raised after the player loads a save slot and the world is initialised. + /// The event sender. + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { - - } + // TODO Used to spawn a custom npc just as an example. Don't keep this code. GENERATE NPC AND CALL THE CODE - /// - /// Used to spawn a custom npc just as an example. Don't keep this code. - /// GENERATE NPC AND CALL THE CODE - /// - /// - /// - private void SaveEvents_LoadChar(object sender, EventArgs e) - { - ExtendedNPC myNpc3 = assetPool.generateNPC(Genders.female, 0, 1,new StandardColorCollection(null, null, Color.Blue, null, Color.Yellow, null)); - MerchantNPC merch = new MerchantNPC(new List() + ExtendedNpc myNpc3 = assetPool.generateNPC(Genders.female, 0, 1, new StandardColorCollection(null, null, Color.Blue, null, Color.Yellow, null)); + MerchantNpc merch = new MerchantNpc(new List() { new StardewValley.Object(475,999) }, myNpc3); - npcTracker.addNewNPCToLocation(Game1.getLocationFromName("BusStop", false), merch,new Vector2(2,23)); + npcTracker.addNewNpcToLocation(Game1.getLocationFromName("BusStop", false), merch, new Vector2(2, 23)); } - /// - /// Used to initialize examples for other modders to look at as reference. - /// + /// Used to initialize examples for other modders to look at as reference. public void initializeExamples() { return; - string dirPath = Path.Combine(ModHelper.DirectoryPath, "Content", "Templates"); - var aManager=assetPool.getAssetManager("testNPC"); - aManager.addPathCreateDirectory(new KeyValuePair("templates", dirPath)); - string filePath =Path.Combine(dirPath, "Example.json"); - if (!File.Exists(filePath)) - { - string getRelativePath = getShortenedDirectory(filePath); - ModMonitor.Log("THIS IS THE PATH::: " + getRelativePath); - AssetInfo info = new AssetInfo("MyExample",new NamePairings("StandingExampleL", "StandingExampleR", "StandingExampleU", "StandingExampleD"), new NamePairings("MovingExampleL", "MovingExampleR", "MovingExampleU", "MovingExampleD"), new NamePairings("SwimmingExampleL", "SwimmingExampleR", "SwimmingExampleU", "SwimmingExampleD"), new NamePairings("SittingExampleL", "SittingExampleR", "SittingExampleU", "SittingExampleD"), new Vector2(16, 16), false); - info.writeToJson(filePath); + string relativeDirPath = Path.Combine("Content", "Templates"); + var aManager = assetPool.getAssetManager("testNPC"); + aManager.addPathCreateDirectory(new KeyValuePair("templates", relativeDirPath)); + // write example + { + string relativeFilePath = Path.Combine(relativeDirPath, "Example.json"); + if (!File.Exists(Path.Combine(this.Helper.DirectoryPath, relativeFilePath))) + { + ModMonitor.Log("THIS IS THE PATH::: " + relativeFilePath); + AssetInfo info = new AssetInfo("MyExample", new NamePairings("StandingExampleL", "StandingExampleR", "StandingExampleU", "StandingExampleD"), new NamePairings("MovingExampleL", "MovingExampleR", "MovingExampleU", "MovingExampleD"), new NamePairings("SwimmingExampleL", "SwimmingExampleR", "SwimmingExampleU", "SwimmingExampleD"), new NamePairings("SittingExampleL", "SittingExampleR", "SittingExampleU", "SittingExampleD"), new Vector2(16, 16), false); + info.writeToJson(relativeFilePath); + + } } - string filePath2 = Path.Combine(dirPath, "AdvancedExample.json"); - if (!File.Exists(filePath2)) - { - ExtendedAssetInfo info2 = new ExtendedAssetInfo("AdvancedExample", new NamePairings("AdvancedStandingExampleL", "AdvancedStandingExampleR", "AdvancedStandingExampleU", "AdvancedStandingExampleD"), new NamePairings("AdvancedMovingExampleL", "AdvancedMovingExampleR", "AdvancedMovingExampleU", "AdvancedMovingExampleD"), new NamePairings("AdvancedSwimmingExampleL", "AdvancedSwimmingExampleR", "AdvancedSwimmingExampleU", "AdvancedSwimmingExampleD"), new NamePairings("AdvancedSittingExampleL", "AdvancedSittingExampleR", "AdvancedSittingExampleU", "AdvancedSittingExampleD"), new Vector2(16, 16), false, Genders.female, new List() + // write advanced example { - Seasons.spring, - Seasons.summer - }, PartType.hair - ); - info2.writeToJson(filePath2); + string relativeFilePath = Path.Combine(relativeDirPath, "AdvancedExample.json"); + if (!File.Exists(Path.Combine(this.Helper.DirectoryPath, relativeFilePath))) + { + ExtendedAssetInfo info2 = new ExtendedAssetInfo("AdvancedExample", new NamePairings("AdvancedStandingExampleL", "AdvancedStandingExampleR", "AdvancedStandingExampleU", "AdvancedStandingExampleD"), new NamePairings("AdvancedMovingExampleL", "AdvancedMovingExampleR", "AdvancedMovingExampleU", "AdvancedMovingExampleD"), new NamePairings("AdvancedSwimmingExampleL", "AdvancedSwimmingExampleR", "AdvancedSwimmingExampleU", "AdvancedSwimmingExampleD"), new NamePairings("AdvancedSittingExampleL", "AdvancedSittingExampleR", "AdvancedSittingExampleU", "AdvancedSittingExampleD"), new Vector2(16, 16), false, Genders.female, new List() { Seasons.spring, Seasons.summer }, PartType.hair); + info2.writeToJson(relativeFilePath); + } } } - /// - /// Used to splice the mod directory to get relative paths. - /// - /// - /// - public static string getShortenedDirectory(string path) - { - string lol = (string)path.Clone(); - string[] spliter = lol.Split(new string[] { ModHelper.DirectoryPath },StringSplitOptions.None); - try - { - return spliter[1]; - } - catch(Exception err) - { - err.ToString(); - return spliter[0]; - } - } - - /// - /// Used to finish cleaning up absolute asset paths into a shortened relative path. - /// - /// - /// + /// Used to finish cleaning up absolute asset paths into a shortened relative path. public static string getRelativeDirectory(string path) { - string s = getShortenedDirectory(path); - return s.Remove(0, 1); + return path + .Split(new[] { ModHelper.DirectoryPath }, 2, StringSplitOptions.None) + .Last() + .TrimStart(Path.DirectorySeparatorChar); } } } diff --git a/GeneralMods/CustomNPCFramework/CustomNPCFramework.csproj b/GeneralMods/CustomNPCFramework/CustomNPCFramework.csproj index 20071e85..a6467cf3 100644 --- a/GeneralMods/CustomNPCFramework/CustomNPCFramework.csproj +++ b/GeneralMods/CustomNPCFramework/CustomNPCFramework.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,9 +11,6 @@ CustomNPCFramework v4.5 512 - - - true @@ -70,6 +67,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -93,20 +93,20 @@ - - - - + + + + - - - - - - - - - + + + + + + + + + @@ -116,24 +116,7 @@ - - - - + - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - \ No newline at end of file diff --git a/GeneralMods/CustomNPCFramework/Framework/Enums/AnimationType.cs b/GeneralMods/CustomNPCFramework/Framework/Enums/AnimationType.cs index 15fa24b8..9f3300b2 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Enums/AnimationType.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Enums/AnimationType.cs @@ -1,31 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace CustomNPCFramework.Framework.Enums { - /// - /// A enum of different types of animations supported by the framework. - /// + /// A enum of different types of animations supported by the framework. public enum AnimationType { - /// - /// A key to be used whenever an npc uses a standing animation. - /// + /// A key to be used whenever an npc uses a standing animation. standing, - /// - /// A key to be used wheneven an npc uses a walking/moving animation. - /// + + /// A key to be used wheneven an npc uses a walking/moving animation. walking, - /// - /// A key to be used whenever an npc uses a swimming animation. - /// + + /// A key to be used whenever an npc uses a swimming animation. swimming, - /// - /// A key to be used whenever an npc uses a sitting animation. - /// + + /// A key to be used whenever an npc uses a sitting animation. sitting } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Enums/Direction.cs b/GeneralMods/CustomNPCFramework/Framework/Enums/Direction.cs index e894f068..6d0c753f 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Enums/Direction.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Enums/Direction.cs @@ -1,36 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace CustomNPCFramework.Framework.Enums { - /// - /// An enum to be used to signify directions. - /// The enum order corresponds to the same order Stardew Valley uses for directions where - /// Up=0 - /// Right=1 - /// Down=2 - /// Left=3 - /// + /// An enum to be used to signify directions. The enum order corresponds to the same order Stardew Valley uses for directions. public enum Direction { - /// - /// Used to signify something to face/move up. - /// - up, - /// - /// Used to signify something to face/move right. - /// - right, - /// - /// Used to signify something to face/move down. - /// - down, - /// - /// Used to signify something to face/move left. - /// - left + /// Used to signify something to face/move up. + up = 0, + + /// Used to signify something to face/move right. + right = 1, + + /// Used to signify something to face/move down. + down = 2, + + /// Used to signify something to face/move left. + left = 3 } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Enums/Genders.cs b/GeneralMods/CustomNPCFramework/Framework/Enums/Genders.cs index b1299af0..15050941 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Enums/Genders.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Enums/Genders.cs @@ -1,28 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley; namespace CustomNPCFramework.Framework.Enums { - /// - /// Gender enum to signify the different genders for npcs. - /// Do what you want with this. For code simplicity anything that is non-binary is specified under other. - /// + /// Gender enum to signify the different genders for NPCs. Do what you want with this. For code simplicity anything that is non-binary is specified under other. public enum Genders { - /// - /// Used for npcs to signify that they are the male gender. - /// - male, - /// - /// Used for npcs to signify that they are the female gender. - /// - female, - /// - /// Used for npcs to signify that they are a non gender binary gender. - /// - other + /// Used for npcs to signify that they are the male gender. + male = NPC.male, + + /// Used for npcs to signify that they are the female gender. + female = NPC.female, + + /// Used for npcs to signify that they are a non gender binary gender. + other = NPC.undefined } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Enums/PartType.cs b/GeneralMods/CustomNPCFramework/Framework/Enums/PartType.cs index aab5d3b7..46712e60 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Enums/PartType.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Enums/PartType.cs @@ -1,55 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace CustomNPCFramework.Framework.Enums { - /// - /// An enum used to signify the different asset types that can be used for npcs. - /// + /// An enum used to signify the different asset types that can be used for NPCs. public enum PartType { - /// - /// Used to signify that the asset is of the body part category. Without this the npc is basically a ghost. - /// + /// Used to signify that the asset is of the body part category. Without this the npc is basically a ghost. body, - /// - /// Used to signify that the asset is of the eyes part category. The window to the soul. - /// + + /// Used to signify that the asset is of the eyes part category. The window to the soul. eyes, - /// - /// Used to signify that the asset is of the hair part category. Volume looks good in 2D. - /// + + /// Used to signify that the asset is of the hair part category. Volume looks good in 2D. hair, - /// - /// Used to signify that the asset is of the shirt part category.No shirt = no service. - /// + + /// Used to signify that the asset is of the shirt part category.No shirt = no service. shirt, - /// - /// Used to signify that the asset is of the pants/bottoms part category. Also known as bottoms, skirts, shorts, etc. - /// + + /// Used to signify that the asset is of the pants/bottoms part category. Also known as bottoms, skirts, shorts, etc. pants, - /// - /// Used to signify that the asset is of the shoes part category. Lace up those kicks. - /// + + /// Used to signify that the asset is of the shoes part category. Lace up those kicks. shoes, - /// - /// Used to signify that the asset is of the accessort part category. Got to wear that bling. - /// + + /// Used to signify that the asset is of the accessort part category. Got to wear that bling. accessory, - /// - /// Used to signify that the asset is of the other part category. Who knows what this really is... - /// + + /// Used to signify that the asset is of the other part category. Who knows what this really is... other, - /// - /// Used to signify that the asset is of the swimsuit part category. Got to be decent when taking a dip. - /// + + /// Used to signify that the asset is of the swimsuit part category. Got to be decent when taking a dip. swimsuit, - /// - /// Used to signify that the asset is of the amrs part category. Arms need to be rendered above a shirt on npcs otherwise they get covered. - /// + + /// Used to signify that the asset is of the amrs part category. Arms need to be rendered above a shirt on npcs otherwise they get covered. arms } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Enums/Seasons.cs b/GeneralMods/CustomNPCFramework/Framework/Enums/Seasons.cs index e8e6cd7f..47f0a22b 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Enums/Seasons.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Enums/Seasons.cs @@ -1,36 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - - namespace CustomNPCFramework.Framework.Enums { - /// - /// An enum signifying the different seasons that are supported when chosing npc graphics. - /// + /// An enum signifying the different seasons that are supported when choosing NPC graphics. public enum Seasons { - /// - /// The spring season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the spring time. - /// Also used for functionality to check seasons. - /// + /// The spring season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the spring time. Also used for functionality to check seasons. spring, - /// - /// The summer season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the summer time. - /// Also used for functionality to check seasons. - /// + + /// The summer season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the summer time. Also used for functionality to check seasons. summer, - /// - /// The fall season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the fall time. - /// Also used for functionality to check seasons. - /// + + /// The fall season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the fall time. Also used for functionality to check seasons. fall, - /// - /// The winter season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the winter time. - /// Also used for functionality to check seasons. - /// + + /// The winter season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the winter time. Also used for functionality to check seasons. winter } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetInfo.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetInfo.cs index adc5d387..ad4ab1e2 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetInfo.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetInfo.cs @@ -1,92 +1,65 @@ -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Microsoft.Xna.Framework; namespace CustomNPCFramework.Framework.Graphics { - /// - /// A class to be used to hold information regarding assets such as the name of the assets and the paths to the images. - /// + /// A class to be used to hold information regarding assets such as the name of the assets and the paths to the images. public class AssetInfo { - /// - /// The name of the asset to be used in the main asset pool. - /// + /// The name of the asset to be used in the main asset pool. public string assetName; - /// - /// The list of files to be used for the standing animation. - /// + + /// The list of files to be used for the standing animation. public NamePairings standingAssetPaths; - /// - /// The list of files to be used for the swimming animation. - /// + + /// The list of files to be used for the swimming animation. public NamePairings swimmingAssetPaths; - /// - /// The list of files to be used with the moving animation. - /// + + /// The list of files to be used with the moving animation. public NamePairings movingAssetPaths; - /// - /// The list of files to be used with the sitting animation. - /// + + /// The list of files to be used with the sitting animation. public NamePairings sittingAssetPaths; - /// - /// The size of the asset texture. Width and height. - /// + + /// The size of the asset texture. Width and height. public Vector2 assetSize; - /// - /// Not really used anymore. More of a legacy feature. - /// + + /// Not really used anymore. More of a legacy feature. public bool randomizeUponLoad; - - /// - /// Empty constructor. - /// - public AssetInfo() - { - } + /// Construct an instance. + public AssetInfo() { } - /// - /// Constructor that assigns values to the class. - /// + /// Construct an instance. /// The name of the asset. This is the name that will be referenced in any asset manager or asset pool. - /// The name of the files to be used for the standing animation. - /// The name of the files to be used for the moving animation. - /// The name of the files to be used for the swimming animation. - /// The name of the files to be used for the sitting animation. + /// The name of the files to be used for the standing animation. + /// The name of the files to be used for the moving animation. + /// The name of the files to be used for the swimming animation. + /// The name of the files to be used for the sitting animation. /// The size of the asset. Width and height of the texture. /// Legacy, not really used anymore. - public AssetInfo(string assetName,NamePairings StandingAssetPaths, NamePairings MovingAssetPaths, NamePairings SwimmingAssetPaths, NamePairings SittingAssetPaths, Vector2 assetSize, bool randomizeUponLoad) + public AssetInfo(string assetName, NamePairings standingAssetPaths, NamePairings movingAssetPaths, NamePairings swimmingAssetPaths, NamePairings sittingAssetPaths, Vector2 assetSize, bool randomizeUponLoad) { this.assetName = assetName; - this.sittingAssetPaths = SittingAssetPaths; - this.standingAssetPaths = StandingAssetPaths; - this.movingAssetPaths = MovingAssetPaths; - this.swimmingAssetPaths = SwimmingAssetPaths; + this.sittingAssetPaths = sittingAssetPaths; + this.standingAssetPaths = standingAssetPaths; + this.movingAssetPaths = movingAssetPaths; + this.swimmingAssetPaths = swimmingAssetPaths; this.assetSize = assetSize; this.randomizeUponLoad = randomizeUponLoad; } - /// - /// Save the json to a certain location. - /// - /// - public void writeToJson(string path) + /// Save the json to a certain location. + /// The relative path to save. + public void writeToJson(string relativeFilePath) { - Class1.ModHelper.WriteJsonFile(path, this); + Class1.ModHelper.Data.WriteJsonFile(relativeFilePath, this); } - /// - /// Read the json from a certain location. - /// - /// - /// - public static AssetInfo readFromJson(string path) + /// Read the json from a certain location. + /// The relative path to save. + public static AssetInfo readFromJson(string relativePath) { - return Class1.ModHelper.ReadJsonFile(path); + return Class1.ModHelper.Data.ReadJsonFile(relativePath); } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetManager.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetManager.cs index 1cd90755..82a27c43 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetManager.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetManager.cs @@ -1,286 +1,211 @@ -using CustomNPCFramework.Framework.Enums; -using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using CustomNPCFramework.Framework.Enums; namespace CustomNPCFramework.Framework.Graphics { - /// - /// Used to hold assets from specified directories. - /// + /// Used to hold assets from specified directories. public class AssetManager { - /// - /// A list of all of the assets held by this asset manager. - /// - public List assets; - /// - /// A list of all of the directories managed by this asset manager. - /// - public Dictionary paths; + /// A list of all of the assets held by this asset manager. + public List assets { get; } = new List(); - /// - /// Basic constructor. - /// - public AssetManager() - { - this.assets = new List(); - this.paths = new Dictionary(); - } + /// A list of directories managed by this asset manager, relative to the mod folder. + public Dictionary relativePaths { get; } = new Dictionary(); - /// - /// Constructor. - /// - /// A list of all directories to be managed by the asset manager. Name, path is the key pair value. - public AssetManager(Dictionary assetsPathsToLoadFrom) - { - this.assets = new List(); - this.paths = assetsPathsToLoadFrom; - } - - /// - /// Default loading function from hard coded paths. - /// + /// Default loading function from hardcoded paths. public void loadAssets() { - foreach(var path in this.paths) - { - ProcessDirectory(path.Value); - } + foreach (var relativePath in this.relativePaths) + this.ProcessDirectory(relativePath.Value); } - /// - /// Taken from Microsoft c# documented webpages. - /// Process all .json files in the given directory. If there are more nested directories, keep digging to find more .json files. Also allows us to specify a broader directory like Content/Grahphics/ModularNPC/Hair to have multiple hair styles. - /// - /// - private void ProcessDirectory(string targetDirectory) + /// Process all .json files in the given directory. If there are more nested directories, keep digging to find more .json files. Also allows us to specify a broader directory like Content/Grahphics/ModularNPC/Hair to have multiple hair styles. + /// The relative directory path to process. + /// Taken from Microsoft c# documented webpages. + private void ProcessDirectory(string relativeDirPath) { - // Process the list of files found in the directory. - string[] files = Directory.GetFiles(targetDirectory, "*.json"); - foreach (var file in files) - { - ProcessFile(file,targetDirectory); - } + DirectoryInfo root = new DirectoryInfo(Path.Combine(Class1.ModHelper.DirectoryPath, relativeDirPath)); + foreach (FileInfo file in root.GetFiles("*.json")) + this.ProcessFile(Path.Combine(relativeDirPath, file.Name), relativeDirPath); + // Recurse into subdirectories of this directory. - string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); - foreach (string subdirectory in subdirectoryEntries) - ProcessDirectory(subdirectory); + foreach (DirectoryInfo subdir in root.GetDirectories()) + this.ProcessDirectory(Path.Combine(relativeDirPath, subdir.Name)); } - /// - /// Actually load in the asset information. - /// - /// - /// - private void ProcessFile(string file,string path) + /// Actually load in the asset information. + /// The relative path to the file to process. + /// The relative path containing the file. + private void ProcessFile(string relativeFilePath, string relativeDirPath) { try { - ExtendedAssetInfo info = ExtendedAssetInfo.readFromJson(file); - AssetSheet sheet = new AssetSheet(info, path); - addAsset(sheet); + ExtendedAssetInfo info = ExtendedAssetInfo.readFromJson(relativeFilePath); + AssetSheet sheet = new AssetSheet(info, relativeDirPath); + this.addAsset(sheet); Class1.ModMonitor.Log("Loaded in new modular asset: " + info.assetName + " asset type: " + info.type); } - catch (Exception err) + catch { - AssetInfo info = AssetInfo.readFromJson(file); - AssetSheet sheet = new AssetSheet(info, path); - addAsset(sheet); + AssetInfo info = AssetInfo.readFromJson(relativeFilePath); + AssetSheet sheet = new AssetSheet(info, relativeDirPath); + this.addAsset(sheet); } } - /// - /// Add an asset to be handled from the asset manager. - /// - /// + /// Add an asset to be handled from the asset manager. + /// The asset sheet. public void addAsset(AssetSheet asset) { this.assets.Add(asset); } - /// - /// Get an individual asset by its name. - /// - /// - /// + /// Get an individual asset by its name. + /// The asset name. public AssetSheet getAssetByName(string s) { - foreach(var v in assets) + foreach (var v in this.assets) { - if (v.assetInfo.assetName == s) return v; + if (v.assetInfo.assetName == s) + return v; } return null; } - - /// - /// Add a new path to the asset manager and create the directory for it. - /// - /// - public void addPathCreateDirectory(KeyValuePair path) + + /// Add a new path to the asset manager and create the directory for it. + /// The absolute path to add. + public void addPathCreateDirectory(KeyValuePair path) { this.addPath(path); string dir = Path.Combine(Class1.ModHelper.DirectoryPath, path.Value); if (!Directory.Exists(dir)) - { Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath, path.Value)); - } } - /// - /// Add a path to the dictionary. - /// - /// - private void addPath(KeyValuePair path) + /// Add a path to the dictionary. + /// The relative path to add. + private void addPath(KeyValuePair path) { - this.paths.Add(path.Key, path.Value); + this.relativePaths.Add(path.Key, path.Value); } - /// - /// Create appropriate directories for the path. - /// + /// Create appropriate directories for the path. private void createDirectoriesFromPaths() { - foreach(var v in paths) - { - Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath,v.Value)); - } + foreach (var v in this.relativePaths) + Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath, v.Value)); } - /// - /// Returns a list of assets from this manager that match the given critera. - /// - /// The criteria we are searching for this time is gender. - /// + /// Get a list of assets which match the given critera. + /// The gender to match. public List getListOfAssetsThatMatchThisCriteria(Genders gender) { - List aSheet = new List(); - foreach(var v in this.assets) + List sheets = new List(); + foreach (var v in this.assets) { - if(v.assetInfo is ExtendedAssetInfo) + if (v.assetInfo is ExtendedAssetInfo info) { - if ((v.assetInfo as ExtendedAssetInfo).gender == gender) aSheet.Add(v); + if (info.gender == gender) + sheets.Add(v); } } - return aSheet; + return sheets; } - /// - /// Get a list of all the assets of this kind of part. - /// - /// The type of part to return a list of from this asset manager. - /// + /// Get a list of assets which match the given critera. + /// The part type to match. public List getListOfAssetsThatMatchThisCriteria(PartType type) { - List aSheet = new List(); + List sheets = new List(); foreach (var v in this.assets) { - if (v.assetInfo is ExtendedAssetInfo) + if (v.assetInfo is ExtendedAssetInfo info) { - if ((v.assetInfo as ExtendedAssetInfo).type == type) aSheet.Add(v); + if (info.type == type) + sheets.Add(v); } } - return aSheet; + return sheets; } - /// - /// Get a list of assets that match the critera. - /// - /// The gender criteria for this asset, such as if this part belongs to either a female or male character. - /// The type of asset to return. Hair eyes, shoes, etc. - /// - public List getListOfAssetsThatMatchThisCriteria(Genders gender,PartType type) + /// Get a list of assets which match the given critera. + /// The gender to match. + /// The part type to match. + public List getListOfAssetsThatMatchThisCriteria(Genders gender, PartType type) { - List aSheet = new List(); + List sheets = new List(); foreach (var v in this.assets) { - if (v.assetInfo is ExtendedAssetInfo) + if (v.assetInfo is ExtendedAssetInfo info) { - if ((v.assetInfo as ExtendedAssetInfo).type == type && (v.assetInfo as ExtendedAssetInfo).gender == gender) aSheet.Add(v); + if (info.type == type && info.gender == gender) + sheets.Add(v); } } - return aSheet; + return sheets; } - /// - /// Returns a list of assets from this manager that match the given critera. - /// - /// The criteria we are searching for this time is gender. - /// + /// Get a list of assets which match the given critera. + /// The season to match. public List getListOfAssetsThatMatchThisCriteria(Seasons season) { - List aSheet = new List(); + List sheets = new List(); foreach (var v in this.assets) { - if (v.assetInfo is ExtendedAssetInfo) + if (v.assetInfo is ExtendedAssetInfo info) { - foreach (var sea in (v.assetInfo as ExtendedAssetInfo).seasons) { - if (sea == season) aSheet.Add(v); - break; //Only need to find first validation that this is a valid asset. - } - } - } - return aSheet; - } - - /// - /// Get a list of assets that match this criteria of gender and seasons. - /// - /// - /// - /// - public List getListOfAssetsThatMatchThisCriteria(Genders gender,Seasons season) - { - List aSheet = new List(); - foreach (var v in this.assets) - { - if (v.assetInfo is ExtendedAssetInfo) - { - foreach (var sea in (v.assetInfo as ExtendedAssetInfo).seasons) + foreach (var sea in info.seasons) { - if (sea == season && (v.assetInfo as ExtendedAssetInfo).gender==gender) aSheet.Add(v); + if (sea == season) + sheets.Add(v); break; //Only need to find first validation that this is a valid asset. } } } - return aSheet; + return sheets; } - /// - /// Get a list of asssets that match certain critera. - /// - /// The gengder certain assets belong to, such as male or female. - /// The season that an asset can be displayed in. Good for seasonal assets. - /// The type of part to return a list of such as hair, eyes, or pants. - /// + /// Get a list of assets which match the given critera. + /// The gender to match. + /// The season to match. + public List getListOfAssetsThatMatchThisCriteria(Genders gender, Seasons season) + { + List sheets = new List(); + foreach (var v in this.assets) + { + if (v.assetInfo is ExtendedAssetInfo info) + { + foreach (var sea in info.seasons) + { + if (sea == season && info.gender == gender) + sheets.Add(v); + break; //Only need to find first validation that this is a valid asset. + } + } + } + return sheets; + } + + /// Get a list of assets which match the given critera. + /// The gender to match. + /// The season to match. + /// The part type to match. public List getListOfAssetsThatMatchThisCriteria(Genders gender, Seasons season, PartType type) { - List aSheet = new List(); + List sheets = new List(); foreach (var v in this.assets) { - if (v.assetInfo is ExtendedAssetInfo) + if (v.assetInfo is ExtendedAssetInfo info) { - foreach (var sea in (v.assetInfo as ExtendedAssetInfo).seasons) + foreach (var sea in info.seasons) { - //Class1.ModMonitor.Log("Searching: seasons"); - if (sea == season && (v.assetInfo as ExtendedAssetInfo).gender == gender && (v.assetInfo as ExtendedAssetInfo).type == type) - { - aSheet.Add(v); - } - else - { - //Class1.ModMonitor.Log("Not what I was looking for."); - } + if (sea == season && info.gender == gender && info.type == type) + sheets.Add(v); } } } - //Class1.ModMonitor.Log("ok it's over: "+aSheet.Count.ToString()); - return aSheet; + return sheets; } - - } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetPool.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetPool.cs index 5b1f593d..0361206c 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetPool.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetPool.cs @@ -1,32 +1,26 @@ - -using CustomNPCFramework.Framework.Enums; -using CustomNPCFramework.Framework.ModularNPCS; -using CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases; -using CustomNPCFramework.Framework.ModularNPCS.ColorCollections; -using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers; -using CustomNPCFramework.Framework.NPCS; -using Microsoft.Xna.Framework; -using StardewValley; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using CustomNPCFramework.Framework.Enums; +using CustomNPCFramework.Framework.ModularNpcs; +using CustomNPCFramework.Framework.ModularNpcs.CharacterAnimationBases; +using CustomNPCFramework.Framework.ModularNpcs.ColorCollections; +using CustomNPCFramework.Framework.ModularNpcs.ModularRenderers; +using CustomNPCFramework.Framework.NPCS; +using StardewValley; namespace CustomNPCFramework.Framework.Graphics { - - /// - /// Used to hold a collection of strings. - /// + /// Used to hold a collection of strings. public class NamePairings { public string leftString; public string rightString; public string upString; public string downString; - public NamePairings(string LeftString,string RightString, string UpString, string DownString) + + public NamePairings(string LeftString, string RightString, string UpString, string DownString) { this.leftString = LeftString; this.rightString = RightString; @@ -35,37 +29,26 @@ namespace CustomNPCFramework.Framework.Graphics } } - /// - /// Used to contain all of the asset managers. - /// + /// Used to contain all of the asset managers. public class AssetPool { - - /// - /// A dictionary holding all of the asset managers. (Name, AssetManager) - /// + /// A dictionary holding all of the asset managers. (Name, AssetManager) public Dictionary assetPool; - /// - /// Constructor. - /// + /// Construct an instance. public AssetPool() { this.assetPool = new Dictionary(); } - /// - /// Adds an asset manager to the asset pool. - /// + /// Adds an asset manager to the asset pool. /// A key value pair with the convention being (Manager Name, Asset Manager) public void addAssetManager(KeyValuePair pair) { this.assetPool.Add(pair.Key, pair.Value); } - /// - /// Adds an asset manager to the asset pool. - /// + /// Adds an asset manager to the asset pool. /// The name of the asset manager to be added. /// The asset manager object to be added to the asset pool. public void addAssetManager(string assetManagerName, AssetManager assetManager) @@ -73,99 +56,74 @@ namespace CustomNPCFramework.Framework.Graphics this.assetPool.Add(assetManagerName, assetManager); } - /// - /// Get an asset manager from the asset pool from a name. - /// + /// Get an asset manager from the asset pool from a name. /// The name of the asset manager to return. - /// public AssetManager getAssetManager(string name) { - assetPool.TryGetValue(name, out AssetManager asset); + this.assetPool.TryGetValue(name, out AssetManager asset); return asset; } - /// - /// Remove an asset manager from the asset pool. - /// + /// Remove an asset manager from the asset pool. /// The name of the asset manager to remove. public void removeAssetManager(string key) { - assetPool.Remove(key); + this.assetPool.Remove(key); } - /// - /// Go through all of the asset managers and load assets according to their respective paths. - /// + /// Go through all of the asset managers and load assets according to their respective paths. public void loadAllAssets() { foreach (KeyValuePair assetManager in this.assetPool) - { assetManager.Value.loadAssets(); - } } - /// - /// Creates an extended animated sprite object given the asset name in the asset manager. - /// - /// - /// + /// Creates an extended animated sprite object given the asset name in the asset manager. + /// The asset name. public AnimatedSpriteExtended getAnimatedSpriteFromAsset(string name) { - assetPool.TryGetValue(name, out AssetManager asset); + this.assetPool.TryGetValue(name, out AssetManager asset); var assetSheet = asset.getAssetByName(name); - return new AnimatedSpriteExtended(assetSheet.path.Clone().ToString(),assetSheet.index, (int)assetSheet.assetInfo.assetSize.X, (int)assetSheet.assetInfo.assetSize.Y); + return new AnimatedSpriteExtended(assetSheet.path.Clone().ToString(), assetSheet.index, (int)assetSheet.assetInfo.assetSize.X, (int)assetSheet.assetInfo.assetSize.Y); } - - /// - /// Generates a new AnimatedSpriteCollection object from the data held in an asset sheet. - /// + /// Generates a new AnimatedSpriteCollection object from the data held in an asset sheet. /// An asset sheet that holds the data for textures. /// The type of asset to get from the sheet. Hair, eyes, shoes, etc. - /// public AnimatedSpriteCollection getSpriteCollectionFromSheet(AssetSheet assetSheet, AnimationType type) - { - var left = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.left, type),assetSheet); - var right = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.right, type), assetSheet); - var up = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.up, type), assetSheet); - var down = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.down, type), assetSheet); - return new AnimatedSpriteCollection(left, right, up, down, Direction.down); + { + var left = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.left, type), assetSheet); + var right = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.right, type), assetSheet); + var up = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.up, type), assetSheet); + var down = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.down, type), assetSheet); + return new AnimatedSpriteCollection(left, right, up, down, Direction.down); } - - /// - /// Gets an animated sprite collection (ie a hair style facing all four directions) from a list of asset names. - /// + /// Gets an animated sprite collection (ie a hair style facing all four directions) from a list of asset names. /// The name of the asset for the left facing sprite. /// The name of the asset for the right facing sprite. /// The name of the asset for the up facing sprite. /// The name of the asset for the down facing sprite. - /// - /// + /// The sprite's starting direction. public AnimatedSpriteCollection getAnimatedSpriteCollectionFromAssets(string left, string right, string up, string down, Direction startingDirection = Direction.down) { - var Left = getAnimatedSpriteFromAsset(left); - var Right = getAnimatedSpriteFromAsset(right); - var Up = getAnimatedSpriteFromAsset(up); - var Down = getAnimatedSpriteFromAsset(down); - return new AnimatedSpriteCollection(Left, Right, Up, Down, startingDirection); + var leftSprite = this.getAnimatedSpriteFromAsset(left); + var rightSprite = this.getAnimatedSpriteFromAsset(right); + var upSprite = this.getAnimatedSpriteFromAsset(up); + var downSprite = this.getAnimatedSpriteFromAsset(down); + return new AnimatedSpriteCollection(leftSprite, rightSprite, upSprite, downSprite, startingDirection); } - /// - /// Get an AnimatedSpriteCollection from a name pairing. - /// + /// Get an AnimatedSpriteCollection from a name pairing. /// A collection of strings that hold information on directional textures. /// The direction in which the sprite should face. - /// public AnimatedSpriteCollection getAnimatedSpriteCollectionFromAssets(NamePairings pair, Direction startingDirection = Direction.down) { - return getAnimatedSpriteCollectionFromAssets(pair.leftString, pair.rightString, pair.upString, pair.downString); + return this.getAnimatedSpriteCollectionFromAssets(pair.leftString, pair.rightString, pair.upString, pair.downString); } - /// - /// Get a collection of sprites to generate a collective animated sprite. - /// + /// Get a collection of sprites to generate a collective animated sprite. /// The collection of sprites to be used for the boyd of the npc. /// The collection of sprites to be used for the eye of the npc. /// The collection of sprites to be used for the hair of the npc. @@ -174,48 +132,44 @@ namespace CustomNPCFramework.Framework.Graphics /// The collection of sprites to be used for the shoes of the npc. /// The collection of sprites to be used for the accessories of the npc. /// The collection of collors to be used for chaing the color of an individual asset. - /// - public StandardCharacterAnimation GetStandardCharacterAnimation(NamePairings BodySprites, NamePairings EyeSprites, NamePairings HairSprites, NamePairings ShirtsSprites, NamePairings PantsSprites, NamePairings ShoesSprites,List AccessoriesSprites,StandardColorCollection DrawColors=null) + public StandardCharacterAnimation GetStandardCharacterAnimation(NamePairings BodySprites, NamePairings EyeSprites, NamePairings HairSprites, NamePairings ShirtsSprites, NamePairings PantsSprites, NamePairings ShoesSprites, List AccessoriesSprites, StandardColorCollection DrawColors = null) { - var body = getAnimatedSpriteCollectionFromAssets(BodySprites); - var eyes = getAnimatedSpriteCollectionFromAssets(EyeSprites); - var hair = getAnimatedSpriteCollectionFromAssets(HairSprites); - var shirts = getAnimatedSpriteCollectionFromAssets(ShirtsSprites); - var pants = getAnimatedSpriteCollectionFromAssets(PantsSprites); - var shoes = getAnimatedSpriteCollectionFromAssets(ShoesSprites); + var body = this.getAnimatedSpriteCollectionFromAssets(BodySprites); + var eyes = this.getAnimatedSpriteCollectionFromAssets(EyeSprites); + var hair = this.getAnimatedSpriteCollectionFromAssets(HairSprites); + var shirts = this.getAnimatedSpriteCollectionFromAssets(ShirtsSprites); + var pants = this.getAnimatedSpriteCollectionFromAssets(PantsSprites); + var shoes = this.getAnimatedSpriteCollectionFromAssets(ShoesSprites); + List accessories = new List(); - foreach(var v in AccessoriesSprites) - { - accessories.Add(getAnimatedSpriteCollectionFromAssets(v)); - } - if (DrawColors == null) DrawColors = new StandardColorCollection(); - return new StandardCharacterAnimation(body,eyes,hair,shirts,pants,shoes,accessories,DrawColors); + foreach (var v in AccessoriesSprites) + accessories.Add(this.getAnimatedSpriteCollectionFromAssets(v)); + + if (DrawColors == null) + DrawColors = new StandardColorCollection(); + + return new StandardCharacterAnimation(body, eyes, hair, shirts, pants, shoes, accessories, DrawColors); } - /// - /// Get a list of parts that can apply for this criteria. - /// + /// Get a list of parts that can apply for this criteria. /// The name of the asset manager. /// The gender critera. /// The season critera. /// The part type critera. - /// - public List getListOfApplicableBodyParts(string assetManagerName,Genders gender, Seasons season, PartType type) + public List getListOfApplicableBodyParts(string assetManagerName, Genders gender, Seasons season, PartType type) { var parts = this.getAssetManager(assetManagerName).getListOfAssetsThatMatchThisCriteria(gender, season, type); return parts; } - - /// - /// Generate a basic npc based off of all all of the NPC data here. - /// - /// - /// - /// - public ExtendedNPC generateNPC(Genders gender, int minNumOfAccessories, int maxNumOfAccessories ,StandardColorCollection DrawColors=null) + /// Generate a basic NPC based on the NPC data here. + /// The NPC gender. + /// The minimum number of accessories to generate. + /// The maximum number of accessories to generate. + /// The colors for the NPC's different assets. + public ExtendedNpc generateNPC(Genders gender, int minNumOfAccessories, int maxNumOfAccessories, StandardColorCollection drawColors = null) { - Seasons myseason=Seasons.spring; + Seasons myseason = Seasons.spring; if (Game1.currentSeason == "spring") myseason = Seasons.spring; if (Game1.currentSeason == "summer") myseason = Seasons.summer; @@ -233,95 +187,87 @@ namespace CustomNPCFramework.Framework.Graphics //Get all applicable parts from this current asset manager foreach (var assetManager in this.assetPool) { - var body = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.body); + var body = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.body); foreach (var piece in body) bodyList.Add(piece); - var eyes = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.eyes); + var eyes = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.eyes); foreach (var piece in eyes) eyesList.Add(piece); - var hair = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.hair); + var hair = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.hair); foreach (var piece in hair) hairList.Add(piece); - var shirt = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shirt); + var shirt = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shirt); foreach (var piece in shirt) shirtList.Add(piece); - var pants = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.pants); + var pants = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.pants); foreach (var piece in pants) pantsList.Add(piece); - var shoes = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shoes); + var shoes = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shoes); foreach (var piece in shoes) shoesList.Add(piece); - var accessory = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.accessory); + var accessory = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.accessory); foreach (var piece in accessory) accessoryList.Add(piece); } - - Random r = new Random(System.DateTime.Now.Millisecond); - int amount = 0; - - amount = r.Next(minNumOfAccessories,maxNumOfAccessories + 1); //Necessary since r.next returns a num between min and (max-1) - int bodyIndex = 0; - int eyesIndex = 0; - int hairIndex = 0; - int shirtIndex = 0; - int pantsIndex = 0; - int shoesIndex = 0; + Random r = new Random(DateTime.Now.Millisecond); + int amount = r.Next(minNumOfAccessories, maxNumOfAccessories + 1); - if (bodyList.Count != 0) { + int bodyIndex; + int eyesIndex; + int hairIndex; + int shirtIndex; + int pantsIndex; + int shoesIndex; + + if (bodyList.Count != 0) bodyIndex = r.Next(0, bodyList.Count - 1); - } else { Class1.ModMonitor.Log("Error: Not enough body templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); return null; } - if (eyesList.Count != 0) { + if (eyesList.Count != 0) eyesIndex = r.Next(0, eyesList.Count - 1); - } else { Class1.ModMonitor.Log("Error: Not enough eyes templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); return null; } - if (hairList.Count != 0) { + if (hairList.Count != 0) hairIndex = r.Next(0, hairList.Count - 1); - } else { Class1.ModMonitor.Log("Error: Not enough hair templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); return null; } - if (shirtList.Count != 0) { + if (shirtList.Count != 0) shirtIndex = r.Next(0, shirtList.Count - 1); - } else { Class1.ModMonitor.Log("Error: Not enough shirt templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); return null; } - if (pantsList.Count != 0) { + if (pantsList.Count != 0) pantsIndex = r.Next(0, pantsList.Count - 1); - } else { Class1.ModMonitor.Log("Error: Not enough pants templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); return null; } - if (shoesList.Count != 0) { + if (shoesList.Count != 0) shoesIndex = r.Next(0, shoesList.Count - 1); - - } else { Class1.ModMonitor.Log("Error: Not enough shoes templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); return null; } + List accIntList = new List(); if (accessoryList.Count != 0) { @@ -333,97 +279,80 @@ namespace CustomNPCFramework.Framework.Graphics } //Get a single sheet to pull from. - AssetSheet bodySheet; - AssetSheet eyesSheet; - AssetSheet hairSheet; - AssetSheet shirtSheet; - AssetSheet shoesSheet; - AssetSheet pantsSheet; - - bodySheet = bodyList.ElementAt(bodyIndex); - eyesSheet = eyesList.ElementAt(eyesIndex); - hairSheet = hairList.ElementAt(hairIndex); - shirtSheet = shirtList.ElementAt(shirtIndex); - pantsSheet = pantsList.ElementAt(pantsIndex); - shoesSheet = shoesList.ElementAt(shoesIndex); - + AssetSheet bodySheet = bodyList.ElementAt(bodyIndex); + AssetSheet eyesSheet = eyesList.ElementAt(eyesIndex); + AssetSheet hairSheet = hairList.ElementAt(hairIndex); + AssetSheet shirtSheet = shirtList.ElementAt(shirtIndex); + AssetSheet pantsSheet = pantsList.ElementAt(pantsIndex); + AssetSheet shoesSheet = shoesList.ElementAt(shoesIndex); List accessorySheet = new List(); - - foreach (var v in accIntList) - { + foreach (int v in accIntList) accessorySheet.Add(accessoryList.ElementAt(v)); - } - if (DrawColors == null) DrawColors = new StandardColorCollection(); - var render = generateBasicRenderer(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet,DrawColors); - ExtendedNPC npc = new ExtendedNPC(new Sprite(getDefaultSpriteImage(bodySheet)), render, new Microsoft.Xna.Framework.Vector2(0,0) * Game1.tileSize, 2, NPCNames.getRandomNPCName(gender)); - return npc; - } - /// - /// Creates a character renderer (a collection of textures) from a bunch of different asset sheets. - /// - /// The textures for the npc's body. - /// The textures for the npc's eyes. - /// The textures for the npc's hair. - /// The textures for the npc's shirt. - /// The textures for the npc's pants. - /// The textures for the npc's shoes. - /// The textures for the npc's accessories. - /// The colors for the npc's different assets. - /// - public virtual BasicRenderer generateBasicRenderer(AssetSheet bodySheet, AssetSheet eyesSheet, AssetSheet hairSheet, AssetSheet shirtSheet, AssetSheet pantsSheet, AssetSheet shoesSheet, List accessorySheet, StandardColorCollection DrawColors=null) - { - if (DrawColors == null) DrawColors = new StandardColorCollection(); - //Get all of the appropriate animations. - AnimationType type = AnimationType.standing; - var standingAnimation = generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, type,DrawColors); - type = AnimationType.walking; - var movingAnimation = generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, type,DrawColors); - type = AnimationType.swimming; - var swimmingAnimation = generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, type,DrawColors); + if (drawColors == null) + drawColors = new StandardColorCollection(); - BasicRenderer render = new BasicRenderer(standingAnimation, movingAnimation, swimmingAnimation); - return render; + var render = this.generateBasicRenderer(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, drawColors); + return new ExtendedNpc(new Sprite(this.getDefaultSpriteImage(bodySheet)), render, new Microsoft.Xna.Framework.Vector2(0, 0) * Game1.tileSize, 2, NpcNames.getRandomNpcName(gender)); } - /// - /// Generate a Standard Character Animation from some asset sheets. - /// (collection of textures to animations) - /// - /// The textures for the npc's body. - /// The textures for the npc's eyes. - /// The textures for the npc's hair. - /// The textures for the npc's shirt. - /// The textures for the npc's pants. - /// The textures for the npc's shoes. - /// The textures for the npc's accessories. - /// The colors for the npc's different assets. - /// - public virtual StandardCharacterAnimation generateCharacterAnimation(AssetSheet body, AssetSheet eyes, AssetSheet hair, AssetSheet shirt, AssetSheet pants, AssetSheet shoes,List accessories, AnimationType animationType, StandardColorCollection DrawColors=null) + /// Creates a character renderer (a collection of textures) from a bunch of different asset sheets. + /// The textures for the NPC's body. + /// The textures for the NPC's eyes. + /// The textures for the NPC's hair. + /// The textures for the NPC's shirt. + /// The textures for the NPC's pants. + /// The textures for the NPC's shoes. + /// The textures for the NPC's accessories. + /// The colors for the NPC's different assets. + public virtual BasicRenderer generateBasicRenderer(AssetSheet bodySheet, AssetSheet eyesSheet, AssetSheet hairSheet, AssetSheet shirtSheet, AssetSheet pantsSheet, AssetSheet shoesSheet, List accessorySheet, StandardColorCollection drawColors = null) { - var bodySprite = getSpriteCollectionFromSheet(body, animationType); - var eyesSprite = getSpriteCollectionFromSheet(eyes, animationType); - var hairSprite = getSpriteCollectionFromSheet(hair, animationType); - var shirtSprite = getSpriteCollectionFromSheet(shirt, animationType); - var pantsSprite = getSpriteCollectionFromSheet(pants, animationType); - var shoesSprite = getSpriteCollectionFromSheet(shoes, animationType); + if (drawColors == null) + drawColors = new StandardColorCollection(); + + // Get all of the appropriate animations. + StandardCharacterAnimation standingAnimation = this.generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, AnimationType.standing, drawColors); + StandardCharacterAnimation movingAnimation = this.generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, AnimationType.walking, drawColors); + StandardCharacterAnimation swimmingAnimation = this.generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, AnimationType.swimming, drawColors); + + return new BasicRenderer(standingAnimation, movingAnimation, swimmingAnimation); + } + + /// Generate a Standard Character Animation from some asset sheets. (collection of textures to animations) + /// The textures for the NPC's body. + /// The textures for the NPC's eyes. + /// The textures for the NPC's hair. + /// The textures for the NPC's shirt. + /// The textures for the NPC's pants. + /// The textures for the NPC's shoes. + /// The textures for the NPC's accessories. + /// The animation type to generate. + /// The colors for the NPC's different assets. + public virtual StandardCharacterAnimation generateCharacterAnimation(AssetSheet body, AssetSheet eyes, AssetSheet hair, AssetSheet shirt, AssetSheet pants, AssetSheet shoes, List accessories, AnimationType animationType, StandardColorCollection drawColors = null) + { + AnimatedSpriteCollection bodySprite = this.getSpriteCollectionFromSheet(body, animationType); + AnimatedSpriteCollection eyesSprite = this.getSpriteCollectionFromSheet(eyes, animationType); + AnimatedSpriteCollection hairSprite = this.getSpriteCollectionFromSheet(hair, animationType); + AnimatedSpriteCollection shirtSprite = this.getSpriteCollectionFromSheet(shirt, animationType); + AnimatedSpriteCollection pantsSprite = this.getSpriteCollectionFromSheet(pants, animationType); + AnimatedSpriteCollection shoesSprite = this.getSpriteCollectionFromSheet(shoes, animationType); + List accessoryCollection = new List(); foreach (var v in accessories) { - AnimatedSpriteCollection acc = getSpriteCollectionFromSheet(v, AnimationType.standing); + AnimatedSpriteCollection acc = this.getSpriteCollectionFromSheet(v, AnimationType.standing); accessoryCollection.Add(acc); } - if (DrawColors == null) DrawColors = new StandardColorCollection(); - StandardCharacterAnimation standingAnimation = new StandardCharacterAnimation(bodySprite, eyesSprite, hairSprite, shirtSprite, pantsSprite, shoesSprite, accessoryCollection,DrawColors); - return standingAnimation; + + if (drawColors == null) + drawColors = new StandardColorCollection(); + + return new StandardCharacterAnimation(bodySprite, eyesSprite, hairSprite, shirtSprite, pantsSprite, shoesSprite, accessoryCollection, drawColors); } - /// - /// Get the string for the standard character sprite to be used from this asset sheet. - /// + /// Get the relative path for the standard character sprite to be used from this asset sheet. /// The standard asset sheet to be used. - /// public virtual string getDefaultSpriteImage(AssetSheet imageGraphics) { return Class1.getRelativeDirectory(Path.Combine(imageGraphics.path, imageGraphics.assetInfo.standingAssetPaths.downString)); diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetSheet.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetSheet.cs index d2b7eabc..93126765 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetSheet.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/AssetSheet.cs @@ -1,131 +1,87 @@ -using CustomNPCFramework.Framework.Enums; +using System.Collections.Generic; +using CustomNPCFramework.Framework.Enums; using CustomNPCFramework.Framework.Graphics.TextureGroups; using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; using StardustCore.UIUtilities; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace CustomNPCFramework.Framework.Graphics { - /// - /// Used to handle loading different textures and handling opperations on those textures. - /// + /// Used to handle loading different textures and handling opperations on those textures. public class AssetSheet { - /// - /// Used to hold the textures for the AssetSheet. - /// - public TextureGroups.TextureGroup textures; + /// Used to hold the textures for the AssetSheet. + public TextureGroup textures; - /// - /// Used to hold the info for the paths to these textures. - /// + /// Used to hold the info for the paths to these textures. public AssetInfo assetInfo; - - /// - /// The path to this assetinfo.json file - /// + + /// The path to this assetinfo.json file public string path; - /// - /// The soruce rectangle for the current texture to draw. - /// + /// The source rectangle for the current texture to draw. public Rectangle currentAsset; public int index; - /// - /// Constructor. - /// + + /// Construct an instance. /// The asset info file to be read in or created. Holds path information. - /// The path to the assetinfo file. + /// The relative path to the assetinfo file. /// The direction to set the animation. - public AssetSheet(AssetInfo info,string path,Direction direction=Direction.down) + public AssetSheet(AssetInfo info, string relativeDirPath, Direction direction = Direction.down) { this.assetInfo = info; - this.textures = new TextureGroup(info,path,direction); - try - { - this.path = Class1.getShortenedDirectory(path); - } - catch(Exception err) - { - this.path = path; - } - + this.textures = new TextureGroup(info, relativeDirPath, direction); + this.path = relativeDirPath; this.index = 0; } - /// - /// Get the path to the current texture. - /// - /// + + /// Get the path to the current texture. public virtual KeyValuePair getPathTexturePair() { return new KeyValuePair(this.path, this.textures.currentTexture.currentTexture); } - - /// - /// Used just to get a copy of this asset sheet. - /// + /// Used just to get a copy of this asset sheet. public virtual AssetSheet clone() { - var asset = new AssetSheet(this.assetInfo,(string)this.path.Clone()); + var asset = new AssetSheet(this.assetInfo, (string)this.path.Clone()); return asset; } - /// - /// Sets the textures for this sheet to face left. - /// + /// Sets the textures for this sheet to face left. public virtual void setLeft() { this.textures.setLeft(); } - /// - /// Sets the textures for this sheet to face up. - /// + /// Sets the textures for this sheet to face up. public virtual void setUp() { this.textures.setUp(); } - /// - /// Sets the textures for this sheet to face down. - /// + /// Sets the textures for this sheet to face down. public virtual void setDown() { this.textures.setDown(); } - /// - /// Sets the textures for this sheet to face left. - /// + /// Sets the textures for this sheet to face left. public virtual void setRight() { this.textures.setRight(); } - /// - /// Get the current animation texture. - /// - /// + /// Get the current animation texture. public virtual Texture2DExtended getCurrentSpriteTexture() { return this.textures.currentTexture.currentTexture; } - /// - /// Get the specific texture depending on the direction and animation type. - /// - /// - /// - /// - public virtual Texture2DExtended getTexture(Direction direction,AnimationType type) + /// Get the specific texture depending on the direction and animation type. + /// The facing direction. + /// The animation type. + public virtual Texture2DExtended getTexture(Direction direction, AnimationType type) { return this.textures.getTextureFromAnimation(type).getTextureFromDirection(direction); } diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/DirectionalTexture.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/DirectionalTexture.cs index d5a3aca5..2834ea98 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/DirectionalTexture.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/DirectionalTexture.cs @@ -1,134 +1,133 @@ -using CustomNPCFramework.Framework.Enums; -using Microsoft.Xna.Framework.Graphics; +using System.IO; +using CustomNPCFramework.Framework.Enums; using StardewModdingAPI; using StardustCore.UIUtilities; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace CustomNPCFramework.Framework.Graphics { - /// - /// A class that's used to hold textures for different directions. - /// + /// A class that's used to hold textures for different directions. public class DirectionalTexture { - /// - /// The left texture for this group. - /// + /// The left texture for this group. public Texture2DExtended leftTexture; - /// - /// The right texture for this group. - /// + + /// The right texture for this group. public Texture2DExtended rightTexture; - - /// - /// The down textiure for this group. - /// + + /// The down textiure for this group. public Texture2DExtended downTexture; - /// - /// The up texture for this group. - /// + + /// The up texture for this group. public Texture2DExtended upTexture; - /// - /// The current texture for this group. - /// + /// The current texture for this group. public Texture2DExtended currentTexture; - /// - /// Constructor. - /// + /// Construct an instance. /// The left texture to use. /// The right texture to use. /// The up texture to use. /// The down texture to use. /// The direction texture for the sprite to face. - public DirectionalTexture(Texture2DExtended left, Texture2DExtended right, Texture2DExtended up, Texture2DExtended down, Direction direction=Direction.down) + public DirectionalTexture(Texture2DExtended left, Texture2DExtended right, Texture2DExtended up, Texture2DExtended down, Direction direction = Direction.down) { this.leftTexture = left; this.rightTexture = right; this.upTexture = up; this.downTexture = down; - if (direction == Direction.left) this.currentTexture = leftTexture; - if (direction == Direction.right) this.currentTexture = rightTexture; - if (direction == Direction.up) this.currentTexture = upTexture; - if (direction == Direction.down) this.currentTexture = downTexture; + switch (direction) + { + case Direction.left: + this.currentTexture = this.leftTexture; + break; + case Direction.right: + this.currentTexture = this.rightTexture; + break; + case Direction.up: + this.currentTexture = this.upTexture; + break; + + case Direction.down: + this.currentTexture = this.downTexture; + break; + } } - - public DirectionalTexture(IModHelper helper ,NamePairings info, string path, Direction direction = Direction.down) + public DirectionalTexture(IModHelper helper, NamePairings info, string relativePath, Direction direction = Direction.down) { + this.leftTexture = new Texture2DExtended(helper, Path.Combine(relativePath, $"{info.leftString}.png")); + this.rightTexture = new Texture2DExtended(helper, Path.Combine(relativePath, $"{info.rightString}.png")); + this.upTexture = new Texture2DExtended(helper, Path.Combine(relativePath, $"{info.upString}.png")); + this.downTexture = new Texture2DExtended(helper, Path.Combine(relativePath, $"{info.downString}.png")); - new Texture2DExtended(helper, path); + switch (direction) + { + case Direction.left: + this.currentTexture = this.leftTexture; + break; - string leftString= Class1.getShortenedDirectory(Path.Combine(path, info.leftString + ".png")).Remove(0, 1); - string rightString = Class1.getShortenedDirectory(Path.Combine(path, info.rightString + ".png")).Remove(0, 1); - string upString = Class1.getShortenedDirectory(Path.Combine(path, info.upString + ".png")).Remove(0, 1); - string downString = Class1.getShortenedDirectory(Path.Combine(path, info.downString + ".png")).Remove(0, 1); + case Direction.right: + this.currentTexture = this.rightTexture; + break; + case Direction.up: + this.currentTexture = this.upTexture; + break; - this.leftTexture = new Texture2DExtended(helper, leftString); - this.rightTexture = new Texture2DExtended(helper, rightString); - this.upTexture = new Texture2DExtended(helper, upString); - this.downTexture = new Texture2DExtended(helper, downString); - - if (direction == Direction.left) this.currentTexture = leftTexture; - if (direction == Direction.right) this.currentTexture = rightTexture; - if (direction == Direction.up) this.currentTexture = upTexture; - if (direction == Direction.down) this.currentTexture = downTexture; + case Direction.down: + this.currentTexture = this.downTexture; + break; + } } - /// - /// Sets the direction of this current texture to left. - /// + /// Sets the direction of this current texture to left. public void setLeft() { - this.currentTexture = leftTexture; + this.currentTexture = this.leftTexture; } - /// - /// Sets the direction of this current texture to up. - /// + /// Sets the direction of this current texture to up. public void setUp() { - this.currentTexture = upTexture; + this.currentTexture = this.upTexture; } - /// - /// Sets the direction of this current texture to down. - /// + /// Sets the direction of this current texture to down. public void setDown() { - this.currentTexture = downTexture; + this.currentTexture = this.downTexture; } - /// - /// Sets the direction of this current texture to right. - /// + /// Sets the direction of this current texture to right. public void setRight() { - this.currentTexture = rightTexture; + this.currentTexture = this.rightTexture; } - /// - /// Gets the texture from this texture group depending on the direction. - /// - /// - /// + /// Gets the texture from this texture group depending on the direction. + /// The facing direction. public virtual Texture2DExtended getTextureFromDirection(Direction direction) { - if (direction == Direction.left) return this.leftTexture; - if (direction == Direction.right) return this.rightTexture; - if (direction == Direction.up) return this.upTexture; - if (direction == Direction.down) return this.downTexture; - return null; + switch (direction) + { + case Direction.left: + return this.leftTexture; + + case Direction.right: + return this.rightTexture; + + case Direction.up: + return this.upTexture; + + case Direction.down: + return this.downTexture; + + default: + return null; + } } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/ExtendedAssetInfo.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/ExtendedAssetInfo.cs index 0590fee3..58d020d5 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/ExtendedAssetInfo.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/ExtendedAssetInfo.cs @@ -1,73 +1,55 @@ -using CustomNPCFramework.Framework.Enums; -using Microsoft.Xna.Framework; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using CustomNPCFramework.Framework.Enums; +using Microsoft.Xna.Framework; namespace CustomNPCFramework.Framework.Graphics { - /// - /// An expanded Asset info class that deals with seasons and genders. - /// - public class ExtendedAssetInfo :AssetInfo + /// An expanded Asset info class that deals with seasons and genders. + public class ExtendedAssetInfo : AssetInfo { - /// - /// The genders this part is associated with. 0=Male, 1=female, 2=other. - /// + /// The genders this part is associated with. public Genders gender; - /// - /// A list of seasons where this part can be displayed - /// - public List seasons=new List(); - /// - /// The part type to be used for this asset such as hair, eyes, etc. - /// + + /// A list of seasons where this part can be displayed. + public List seasons = new List(); + + /// The part type to be used for this asset such as hair, eyes, etc. public PartType type; - - /// - /// Constructor. - /// - public ExtendedAssetInfo() + + /// Construct an instance. + public ExtendedAssetInfo() { } + + /// Construct an instance. + /// The name of the asset. This is the name that will be referenced in any asset manager or asset pool. + /// The name of the files to be used for the standing animation. + /// The name of the files to be used for the moving animation. + /// The name of the files to be used for the swimming animation. + /// The name of the files to be used for the sitting animation. + /// The size of the asset. Width and height of the texture. + /// Legacy, not really used anymore. + /// The type of gender this asset will be associated with. + /// The type of season this asset will be associated with. + /// The part type to be used for this asset such as hair, eyes, etc. + public ExtendedAssetInfo(string name, NamePairings standingAssetPaths, NamePairings movingAssetPaths, NamePairings swimmingAssetPaths, NamePairings sittingAssetPaths, Vector2 assetSize, bool randomizeOnLoad, Genders gender, List season, PartType type) + : base(name, standingAssetPaths, movingAssetPaths, swimmingAssetPaths, sittingAssetPaths, assetSize, randomizeOnLoad) { - this.seasons = new List(); - } - - /// - /// Constructor. - /// - /// - /// - /// - /// The type of gender this asset will be associated with. - /// The type of season this asset will be associated with. - public ExtendedAssetInfo(string name, NamePairings StandingAssetPaths, NamePairings MovingAssetPaths, NamePairings SwimmingAssetPaths, NamePairings SittingAssetPaths, Vector2 assetSize, bool randomizeOnLoad, Genders Gender, List Season, PartType Type): base(name,StandingAssetPaths,MovingAssetPaths,SwimmingAssetPaths,SittingAssetPaths, assetSize, randomizeOnLoad) - { - this.gender = Gender; - this.seasons = Season; - if (this.seasons == null) this.seasons = new List(); - this.type = Type; + this.gender = gender; + this.seasons = season ?? new List(); + this.type = type; } - /// - /// Save the json to a certain location. - /// - /// - public new void writeToJson(string path) + /// Save the json to a certain location. + /// The relative path to write. + public new void writeToJson(string relativePath) { - Class1.ModHelper.WriteJsonFile(path, this); + Class1.ModHelper.Data.WriteJsonFile(relativePath, this); } - /// - /// Read the json from a certain location. - /// - /// - /// - public new static ExtendedAssetInfo readFromJson(string path) + /// Read the json from a certain location. + /// The relative path to read. + public new static ExtendedAssetInfo readFromJson(string relativePath) { - return Class1.ModHelper.ReadJsonFile(path); + return Class1.ModHelper.Data.ReadJsonFile(relativePath); } - } } diff --git a/GeneralMods/CustomNPCFramework/Framework/Graphics/TextureGroups/TextureGroup.cs b/GeneralMods/CustomNPCFramework/Framework/Graphics/TextureGroups/TextureGroup.cs index 7b9f67d6..c5e9bd47 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Graphics/TextureGroups/TextureGroup.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Graphics/TextureGroups/TextureGroup.cs @@ -1,96 +1,67 @@ -using CustomNPCFramework.Framework.Enums; -using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using CustomNPCFramework.Framework.Enums; namespace CustomNPCFramework.Framework.Graphics.TextureGroups { - /// - /// A group of a textures used to hold all of the textures associated with a single asset such as a hair style or a shirt. - /// + /// A group of a textures used to hold all of the textures associated with a single asset such as a hair style or a shirt. public class TextureGroup { - /// - /// The directional (Left, Right, Up, Down) textures to be used when the NPC is standing. - /// + /// The directional (Left, Right, Up, Down) textures to be used when the NPC is standing. public DirectionalTexture standingTexture; - /// - /// The directional (Left, Right, Up, Down) textures to be used when the NPC is sitting. - /// + + /// The directional (Left, Right, Up, Down) textures to be used when the NPC is sitting. public DirectionalTexture sittingTexture; - /// - /// The directional (Left, Right, Up, Down) textures to be used when the NPC is swimming. - /// + + /// The directional (Left, Right, Up, Down) textures to be used when the NPC is swimming. public DirectionalTexture swimmingTexture; - /// - /// The directional (Left, Right, Up, Down) textures to be used when the NPC is moving. - /// + + /// The directional (Left, Right, Up, Down) textures to be used when the NPC is moving. public DirectionalTexture movingTexture; - /// - /// The current directional texture to be used by the npc. Can be things such as the standing, swimming, moving, or sitting texture. - /// + /// The current directional texture to be used by the npc. Can be things such as the standing, swimming, moving, or sitting texture. public DirectionalTexture currentTexture; - /// - /// Asset info loaded in from the corresponding .json file. - /// - private AssetInfo info; - /// - /// The path to the .json file. - /// - private string path; - /// - /// The current direction of the texture group. See Direction.cs - /// - private Direction dir; - /// - /// The type of asset this is. Body, hair, eyes, shirt,etc... - /// - private AnimationType type; + /// Asset info loaded in from the corresponding .json file. + private readonly AssetInfo info; - /// - /// Constructor. - /// + /// The path to the .json file. + private readonly string path; + + /// The current direction of the texture group. + private readonly Direction dir; + + /// The type of asset this is. Body, hair, eyes, shirt, etc. + private readonly AnimationType type; + + /// Construct an instance. /// The asset info file to be stored with this texture group. /// Use to locate the files on disk. /// Used to determine the current direction/animation to load /// The type of asset this is. Eyes, Hair, Shirts, etc - public TextureGroup(AssetInfo info, string path,Direction direction ,AnimationType animationType=AnimationType.standing) + public TextureGroup(AssetInfo info, string path, Direction direction, AnimationType animationType = AnimationType.standing) { - this.standingTexture = new DirectionalTexture(Class1.ModHelper,info.standingAssetPaths, path, direction); + this.standingTexture = new DirectionalTexture(Class1.ModHelper, info.standingAssetPaths, path, direction); this.sittingTexture = new DirectionalTexture(Class1.ModHelper, info.sittingAssetPaths, path, direction); this.swimmingTexture = new DirectionalTexture(Class1.ModHelper, info.swimmingAssetPaths, path, direction); - this.movingTexture = new DirectionalTexture(Class1.ModHelper,info.movingAssetPaths, path, direction); + this.movingTexture = new DirectionalTexture(Class1.ModHelper, info.movingAssetPaths, path, direction); this.info = info; this.path = path; this.dir = direction; this.type = animationType; - if (animationType == AnimationType.standing) this.currentTexture = standingTexture; - if (animationType == AnimationType.sitting) this.currentTexture = sittingTexture; - if (animationType == AnimationType.swimming) this.currentTexture = swimmingTexture; - if (animationType == AnimationType.walking) this.currentTexture = movingTexture; - + if (animationType == AnimationType.standing) this.currentTexture = this.standingTexture; + if (animationType == AnimationType.sitting) this.currentTexture = this.sittingTexture; + if (animationType == AnimationType.swimming) this.currentTexture = this.swimmingTexture; + if (animationType == AnimationType.walking) this.currentTexture = this.movingTexture; } - /// - /// Gets a clone of this texture group. - /// - /// + /// Gets a clone of this texture group. public TextureGroup clone() { return new TextureGroup(this.info, this.path, this.dir, this.type); } - - /// - /// Sets all of the different animations to use their left facing sprites. - /// + /// Sets all of the different animations to use their left facing sprites. public virtual void setLeft() { this.movingTexture.setLeft(); @@ -99,9 +70,7 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups this.swimmingTexture.setLeft(); } - /// - /// Sets all of the different animations to use their up facing sprites. - /// + /// Sets all of the different animations to use their up facing sprites. public virtual void setUp() { this.movingTexture.setUp(); @@ -110,9 +79,7 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups this.swimmingTexture.setUp(); } - /// - /// Sets all of the different animations to use their down facing sprites. - /// + /// Sets all of the different animations to use their down facing sprites. public virtual void setDown() { this.movingTexture.setDown(); @@ -121,9 +88,7 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups this.swimmingTexture.setDown(); } - /// - /// Sets all of the different animations to use their right facing sprites. - /// + /// Sets all of the different animations to use their right facing sprites. public virtual void setRight() { this.movingTexture.setRight(); @@ -132,11 +97,8 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups this.swimmingTexture.setRight(); } - /// - /// Get's the appropriate animation texture based on the type of animation key passed in. - /// - /// - /// + /// Gets the appropriate animation texture based on the type of animation key passed in. + /// The animation type. public virtual DirectionalTexture getTextureFromAnimation(AnimationType type) { if (type == AnimationType.standing) return this.standingTexture; @@ -145,6 +107,5 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups if (type == AnimationType.sitting) return this.sittingTexture; return null; } - } } diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteCollection.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteCollection.cs index 33f7caef..ce1160af 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteCollection.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteCollection.cs @@ -1,78 +1,62 @@ -using CustomNPCFramework.Framework.Enums; +using CustomNPCFramework.Framework.Enums; using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS +namespace CustomNPCFramework.Framework.ModularNpcs { - /// - /// Used to hold all of the sprites for a single asset such as hair or bodies. - /// + /// Used to hold all of the sprites for a single asset such as hair or bodies. public class AnimatedSpriteCollection { - /// - /// The left sprite for this sprite asset part. - /// + /// The left sprite for this sprite asset part. AnimatedSpriteExtended leftSprite; - /// - /// The right sprite for this sprite asset part. - /// + + /// The right sprite for this sprite asset part. AnimatedSpriteExtended rightSprite; - /// - /// The up sprite for this sprite asset part. - /// + + /// The up sprite for this sprite asset part. AnimatedSpriteExtended upSprite; - /// - /// The down sprite for this sprite asset part. - /// + + /// The down sprite for this sprite asset part. AnimatedSpriteExtended downSprite; - /// - /// The current sprite for this sprite collection. This is one of the four directions for this collection. - /// + /// The current sprite for this sprite collection. This is one of the four directions for this collection. public AnimatedSpriteExtended currentSprite; - /// - /// Constructor. - /// + /// Construct an instance. /// Left animated sprite for this piece. /// Right animated sprite for this piece. /// Up animated sprite for this piece. /// Down animated sprite for this piece. - /// - public AnimatedSpriteCollection(AnimatedSpriteExtended LeftSprite,AnimatedSpriteExtended RightSprite,AnimatedSpriteExtended UpSprite,AnimatedSpriteExtended DownSprite,Direction startingSpriteDirection) + /// The sprite's initial facing direction. + public AnimatedSpriteCollection(AnimatedSpriteExtended LeftSprite, AnimatedSpriteExtended RightSprite, AnimatedSpriteExtended UpSprite, AnimatedSpriteExtended DownSprite, Direction startingSpriteDirection) { this.leftSprite = LeftSprite; this.rightSprite = RightSprite; this.upSprite = UpSprite; this.downSprite = DownSprite; - if (startingSpriteDirection == Direction.down) + switch (startingSpriteDirection) { - setDown(); - } - if (startingSpriteDirection == Direction.left) - { - setLeft(); - } - if (startingSpriteDirection == Direction.right) - { - setRight(); - } - if (startingSpriteDirection == Direction.up) - { - setUp(); + case Direction.down: + this.setDown(); + break; + + case Direction.left: + this.setLeft(); + break; + + case Direction.right: + this.setRight(); + break; + + case Direction.up: + this.setUp(); + break; } } - /// - /// Reloads all of the directional textures for this texture collection. - /// + /// Reloads all of the directional textures for this texture collection. public virtual void reload() { this.leftSprite.reload(); @@ -81,109 +65,66 @@ namespace CustomNPCFramework.Framework.ModularNPCS this.downSprite.reload(); } - /// - /// Sets the current sprite direction to face left. - /// + /// Sets the current sprite direction to face left. public void setLeft() { - this.currentSprite = leftSprite; + this.currentSprite = this.leftSprite; } - /// - /// Sets the current sprite direction to face right. - /// + /// Sets the current sprite direction to face right. public void setRight() { - this.currentSprite = rightSprite; + this.currentSprite = this.rightSprite; } - /// - /// Sets the current sprite direction to face down. - /// + /// Sets the current sprite direction to face down. public void setDown() { - this.currentSprite = downSprite; + this.currentSprite = this.downSprite; } - /// - /// Sets the current sprite direction to face up. - /// + /// Sets the current sprite direction to face up. public void setUp() { - this.currentSprite = upSprite; + this.currentSprite = this.upSprite; } - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// + /// Used to draw the sprite to the screen. public void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) { b.Draw(this.currentSprite.sprite.Texture, screenPosition, new Rectangle?(this.currentSprite.sprite.sourceRect), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, this.currentSprite.sprite.currentAnimation == null || !this.currentSprite.sprite.currentAnimation[this.currentSprite.sprite.currentAnimationIndex].flip ? SpriteEffects.None : SpriteEffects.FlipHorizontally, layerDepth); } - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// Used to draw the sprite to the screen. public void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) { b.Draw(this.currentSprite.sprite.Texture, screenPosition, new Rectangle?(new Rectangle(this.currentSprite.sprite.sourceRect.X + xOffset, this.currentSprite.sprite.sourceRect.Y + yOffset, this.currentSprite.sprite.sourceRect.Width, this.currentSprite.sprite.sourceRect.Height)), c, rotation, characterSourceRectOffset ? new Vector2((float)(this.currentSprite.sprite.SpriteWidth / 2), (float)((double)this.currentSprite.sprite.SpriteHeight * 3.0 / 4.0)) : Vector2.Zero, scale, flip || this.currentSprite.sprite.currentAnimation != null && this.currentSprite.sprite.currentAnimation[this.currentSprite.sprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, layerDepth); } - /// - /// A very verbose asset drawer. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle,Color color, float alpha,Vector2 origin,float scale,SpriteEffects effects,float layerDepth) + /// A very verbose asset drawer. + public void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { //DEFINITELY FIX THIS PART. Something is wrong with how these two functions handle the drawing of my npc to the scene. //this.draw(b, position, layerDepth); - b.Draw(this.currentSprite.sprite.Texture,position,this.currentSprite.sprite.sourceRect, color, 0.0f, origin,scale,effects,layerDepth); + b.Draw(this.currentSprite.sprite.Texture, position, this.currentSprite.sprite.sourceRect, color, 0.0f, origin, scale, effects, layerDepth); //b.Draw(this.Sprite.Texture, npc.getLocalPosition(Game1.viewport) + new Vector2((float)(this.sprite.spriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), Color.White * alpha, this.rotation, new Vector2((float)(this.sprite.spriteWidth / 2), (float)((double)this.sprite.spriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom, this.flip || this.sprite.currentAnimation != null && this.sprite.currentAnimation[this.sprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.991f : (float)this.getStandingY() / 10000f)); } - - /// - /// Animate the current sprite. Theoreticlly works from index offset to how many frames - /// + /// Animate the current sprite. Theoreticlly works from index offset to how many frames /// The delay in milliseconds between frames. - public void Animate(float intervalDelay,bool loop=true) + public void Animate(float intervalDelay, bool loop = true) { - this.Animate(Game1.currentGameTime, 0,2, intervalDelay,this.currentSprite.sprite,loop); + this.Animate(Game1.currentGameTime, 0, 2, intervalDelay, this.currentSprite.sprite, loop); } - /// - /// Animate the current sprite. - /// + /// Animate the current sprite. /// The game time from Monogames/XNA /// The starting frame of the animation on the sprite sheet. /// The number of frames to animate the sprite. /// The delay between frames in milliseconds. /// The animated sprite from the npc. /// If true, the animation plays over and over again. - /// - public virtual bool Animate(GameTime gameTime, int startFrame, int numberOfFrames, float interval, AnimatedSprite sprite, bool loop=true) + public virtual bool Animate(GameTime gameTime, int startFrame, int numberOfFrames, float interval, AnimatedSprite sprite, bool loop = true) { if (sprite.CurrentFrame >= startFrame + numberOfFrames + 1 || sprite.CurrentFrame < startFrame) sprite.CurrentFrame = startFrame + sprite.CurrentFrame % numberOfFrames; @@ -204,10 +145,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS return false; } - /// - /// Update the source rectangle on the sprite sheet. Needed for animation. - /// - /// + /// Update the source rectangle on the sprite sheet. Needed for animation. public virtual void UpdateSourceRect(AnimatedSprite sprite) { if (sprite.ignoreSourceRectUpdates) @@ -217,11 +155,8 @@ namespace CustomNPCFramework.Framework.ModularNPCS //sprite.SourceRect = new Rectangle(, 0, sprite.spriteWidth, sprite.spriteHeight); } - /// - /// Animate the current sprite. Theoreticlly works from index offset to how many frames - /// - /// - public void Animate(float intervalFromCharacter,int startFrame,int endFrame, bool loop) + /// Animate the current sprite. Theoreticlly works from index offset to how many frames + public void Animate(float intervalFromCharacter, int startFrame, int endFrame, bool loop) { this.currentSprite.sprite.loop = loop; this.currentSprite.sprite.Animate(Game1.currentGameTime, startFrame, endFrame, intervalFromCharacter); diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteExtended.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteExtended.cs index e7132923..36952747 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteExtended.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/AnimatedSpriteExtended.cs @@ -1,36 +1,25 @@ -using CustomNPCFramework.Framework.Graphics; -using Microsoft.Xna.Framework.Content; +using CustomNPCFramework.Framework.Graphics; using Microsoft.Xna.Framework.Graphics; using StardewValley; using StardustCore.UIUtilities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS +namespace CustomNPCFramework.Framework.ModularNpcs { - /// - /// Used as a wrapper for the AnimatedSprite class. - /// + /// Used as a wrapper for the AnimatedSprite class. public class AnimatedSpriteExtended { - /// - /// The actual sprite of the object. - /// + /// The actual sprite of the object. public AnimatedSprite sprite; - /// - /// The path to the texture to load the sprite from. - /// + + /// The path to the texture to load the sprite from. public string path; - - public AnimatedSpriteExtended(Texture2DExtended texture,AssetSheet assetSheet) + /// Construct an instance. + public AnimatedSpriteExtended(Texture2DExtended texture, AssetSheet assetSheet) { //Set the sprite texture this.sprite = new AnimatedSprite(); - Texture2D load = texture.Copy().texture; + Texture2D load = texture.Copy().Texture; var thing = Class1.ModHelper.Reflection.GetField(this.sprite, "Texture", true); thing.SetValue(load); @@ -39,25 +28,17 @@ namespace CustomNPCFramework.Framework.ModularNPCS this.sprite.SpriteWidth = (int)assetSheet.assetInfo.assetSize.X; this.sprite.SpriteHeight = (int)assetSheet.assetInfo.assetSize.Y; - - } - /// - /// Constructor. - /// - /// - /// - /// - /// - public AnimatedSpriteExtended(string path ,int currentFrame, int spriteWidth, int spriteHeight) + /// Construct an instance. + public AnimatedSpriteExtended(string path, int currentFrame, int spriteWidth, int spriteHeight) { this.path = Class1.getRelativeDirectory(path); //Set the sprite texture this.sprite = new AnimatedSprite(); Texture2D load = Class1.ModHelper.Content.Load(this.path); - var thing=Class1.ModHelper.Reflection.GetField(this.sprite, "Texture", true); + var thing = Class1.ModHelper.Reflection.GetField(this.sprite, "Texture", true); thing.SetValue(load); //Set the fields. @@ -68,9 +49,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS //this.sprite = new AnimatedSprite(texture, currentFrame, spriteWidth, spriteHeight); } - /// - /// Reloads the asset from disk. - /// + /// Reloads the asset from disk. public void reload() { //Set the sprite texture diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/CharacterAnimationBase.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/CharacterAnimationBase.cs index 2eb3f08b..c4073e35 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/CharacterAnimationBase.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/CharacterAnimationBase.cs @@ -1,131 +1,43 @@ -using CustomNPCFramework.Framework.NPCS; +using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS +namespace CustomNPCFramework.Framework.ModularNpcs { - /// - /// Used as a base class for character animations. - /// + /// Used as a base class for character animations. public class CharacterAnimationBase { + /// Set the character sprites to left. + public virtual void setLeft() { } - /// - /// Constructor. - /// - public CharacterAnimationBase() - { - } + /// Set the character sprites to right. + public virtual void setRight() { } - /// - /// Set the character sprites to left. - /// - public virtual void setLeft() - { - } + /// Set the character sprites to up. + public virtual void setUp() { } - /// - /// Set the character sprites to right. - /// - public virtual void setRight() - { + /// Set the character sprites to down. + public virtual void setDown() { } - } + /// Used to reload the sprite textures. + public virtual void reload() { } - /// - /// Set the character sprites to up. - /// - public virtual void setUp() - { - - } - /// - /// Set the character sprites to down. - /// - public virtual void setDown() - { - - } - - /// - /// Used to reload the sprite textures. - /// - public virtual void reload() - { - } - - /// - /// Animate the sprites. - /// + /// Animate the sprites. /// How long between animation frames in milliseconds. - public virtual void Animate(float animationInterval) - { + public virtual void Animate(float animationInterval) { } - } - - /// - /// Used to animate sprites. - /// + /// Used to animate sprites. /// How long between animation frames in milliseconds. /// Loop the animation. - public virtual void Animate(float animationInterval, bool loop=true) - { + public virtual void Animate(float animationInterval, bool loop = true) { } - } + /// Used to draw the sprite to the screen. + public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) { } - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// - public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) - { - - } - - - - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) - { - - } - - /// - /// A very verbose asset drawer. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) - { - - } + /// Used to draw the sprite to the screen. + public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) { } + /// A very verbose asset drawer. + public virtual void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/StandardCharacterAnimation.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/StandardCharacterAnimation.cs index c563354b..20f5e843 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/StandardCharacterAnimation.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/CharacterAnimationBases/StandardCharacterAnimation.cs @@ -1,54 +1,39 @@ -using CustomNPCFramework.Framework.ModularNPCS.ColorCollections; +using System; +using System.Collections.Generic; +using CustomNPCFramework.Framework.ModularNpcs.ColorCollections; using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases +namespace CustomNPCFramework.Framework.ModularNpcs.CharacterAnimationBases { - /// - /// A class used to reference the different textures used to comprise the different parts for character rendering. - /// - public class StandardCharacterAnimation :CharacterAnimationBase + /// A class used to reference the different textures used to comprise the different parts for character rendering. + public class StandardCharacterAnimation : CharacterAnimationBase { - /// - /// Used to hold all of the information for the npc hair part. - /// + /// Used to hold all of the information for the npc hair part. public AnimatedSpriteCollection hair; - /// - /// Used to hold all of the information for the npc body part. - /// + + /// Used to hold all of the information for the npc body part. public AnimatedSpriteCollection body; - /// - /// Used to hold all of the information for the npc eyes part. - /// + + /// Used to hold all of the information for the npc eyes part. public AnimatedSpriteCollection eyes; - /// - /// Used to hold all of the information for the npc shirt part. - /// + + /// Used to hold all of the information for the npc shirt part. public AnimatedSpriteCollection shirt; - /// - /// Used to hold all of the information for the npc pants part. - /// + + /// Used to hold all of the information for the npc pants part. public AnimatedSpriteCollection pants; - /// - /// Used to hold all of the information for the npc shoes part. - /// + + /// Used to hold all of the information for the npc shoes part. public AnimatedSpriteCollection shoes; - /// - /// Used to hold all of the information for draw colors for the different parts. - /// + + /// Used to hold all of the information for draw colors for the different parts. public StandardColorCollection drawColors; public List accessories; - /// - /// Constructor. - /// + /// Construct an instance. /// The collection of textures to be used for the body part for the npc. /// The collection of textures to be used for the eyes part for the npc. /// The collection of textures to be used for the hair part for the npc. @@ -57,7 +42,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases /// The collection of textures to be used for the shoes part for the npc. /// The collection of textures to be used for the accessories part for the npc. /// The collection of draw colors for the different parts for the npc. - public StandardCharacterAnimation(AnimatedSpriteCollection bodyAnimation, AnimatedSpriteCollection eyeAnimation, AnimatedSpriteCollection hairAnimation, AnimatedSpriteCollection shirtAnimation, AnimatedSpriteCollection pantsAnimation, AnimatedSpriteCollection shoesAnimation,List accessoriesWithAnimations, StandardColorCollection DrawColors) :base() + public StandardCharacterAnimation(AnimatedSpriteCollection bodyAnimation, AnimatedSpriteCollection eyeAnimation, AnimatedSpriteCollection hairAnimation, AnimatedSpriteCollection shirtAnimation, AnimatedSpriteCollection pantsAnimation, AnimatedSpriteCollection shoesAnimation, List accessoriesWithAnimations, StandardColorCollection DrawColors) { this.body = bodyAnimation; this.hair = hairAnimation; @@ -69,9 +54,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases this.drawColors = DrawColors; } - /// - /// Sets all of the different textures to face left. - /// + /// Sets all of the different textures to face left. public override void setLeft() { this.body.setLeft(); @@ -81,14 +64,11 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases this.pants.setLeft(); this.shoes.setLeft(); - foreach(var accessory in this.accessories) - { + foreach (var accessory in this.accessories) accessory.setLeft(); - } } - /// - /// Sets all of the different textures to face right. - /// + + /// Sets all of the different textures to face right. public override void setRight() { this.body.setRight(); @@ -99,13 +79,10 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases this.shoes.setRight(); foreach (var accessory in this.accessories) - { accessory.setRight(); - } } - /// - /// Sets all of the different textures to face up. - /// + + /// Sets all of the different textures to face up. public override void setUp() { this.body.setUp(); @@ -116,13 +93,10 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases this.shoes.setUp(); foreach (var accessory in this.accessories) - { accessory.setUp(); - } } - /// - /// Sets all of the different textures to face down. - /// + + /// Sets all of the different textures to face down. public override void setDown() { this.body.setDown(); @@ -133,14 +107,10 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases this.shoes.setDown(); foreach (var accessory in this.accessories) - { accessory.setDown(); - } } - /// - /// Reloads all of the sprite textures. - /// + /// Reloads all of the sprite textures. public override void reload() { this.body.reload(); @@ -151,119 +121,77 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases this.shoes.reload(); } - /// - /// Animates all of the textures for this sprite. - /// + /// Animates all of the textures for this sprite. /// The delay in milliseconds between animation frames. /// Determines if the animation continuously plays over and over. - public override void Animate(float animationInterval,bool loop=true) + public override void Animate(float animationInterval, bool loop = true) { - this.body.Animate(animationInterval,loop); - this.hair.Animate(animationInterval,loop); - this.eyes.Animate(animationInterval,loop); - this.shirt.Animate(animationInterval,loop); - this.pants.Animate(animationInterval,loop); - this.shoes.Animate(animationInterval,loop); - foreach(var accessory in this.accessories) - { - accessory.Animate(animationInterval,loop); - } - + this.body.Animate(animationInterval, loop); + this.hair.Animate(animationInterval, loop); + this.eyes.Animate(animationInterval, loop); + this.shirt.Animate(animationInterval, loop); + this.pants.Animate(animationInterval, loop); + this.shoes.Animate(animationInterval, loop); + foreach (var accessory in this.accessories) + accessory.Animate(animationInterval, loop); } - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// + /// Used to draw the sprite to the screen. public override void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) { - this.body.draw(b,screenPosition,layerDepth); + this.body.draw(b, screenPosition, layerDepth); this.hair.draw(b, screenPosition, layerDepth); this.eyes.draw(b, screenPosition, layerDepth); this.shirt.draw(b, screenPosition, layerDepth); this.pants.draw(b, screenPosition, layerDepth); this.shoes.draw(b, screenPosition, layerDepth); foreach (var accessory in this.accessories) - { accessory.draw(b, screenPosition, layerDepth); - } //b.Draw(this.currentSprite.Texture, screenPosition, new Rectangle?(this.currentSprite.sourceRect), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, this.currentSprite.currentAnimation == null || !this.currentSprite.currentAnimation[this.currentSprite.currentAnimationIndex].flip ? SpriteEffects.None : SpriteEffects.FlipHorizontally, layerDepth); } - - - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// Used to draw the sprite to the screen. public override void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) { // b.Draw(this.currentSprite.Texture, screenPosition, new Rectangle?(new Rectangle(this.currentSprite.sourceRect.X + xOffset, this.currentSprite.sourceRect.Y + yOffset, this.currentSprite.sourceRect.Width, this.currentSprite.sourceRect.Height)), c, rotation, characterSourceRectOffset ? new Vector2((float)(this.currentSprite.spriteWidth / 2), (float)((double)this.currentSprite.spriteHeight * 3.0 / 4.0)) : Vector2.Zero, scale, flip || this.currentSprite.currentAnimation != null && this.currentSprite.currentAnimation[this.currentSprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, layerDepth); - this.body.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c,this.drawColors.bodyColor), flip, scale, rotation, characterSourceRectOffset); + this.body.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.bodyColor), flip, scale, rotation, characterSourceRectOffset); this.hair.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.hairColor), flip, scale, rotation, characterSourceRectOffset); this.eyes.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.eyeColor), flip, scale, rotation, characterSourceRectOffset); this.shirt.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.shirtColor), flip, scale, rotation, characterSourceRectOffset); this.pants.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.bottomsColor), flip, scale, rotation, characterSourceRectOffset); this.shoes.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.shoesColor), flip, scale, rotation, characterSourceRectOffset); - foreach(var accessory in this.accessories) - { + foreach (var accessory in this.accessories) accessory.draw(b, screenPosition, layerDepth, xOffset, yOffset, c, flip, scale, rotation, characterSourceRectOffset); - } } - /// - /// A very verbose asset drawer. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) + /// A very verbose asset drawer. + public override void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { //Class1.ModMonitor.Log(sourceRectangle.ToString()); - Vector2 generalOffset = new Vector2(0, 1*Game1.tileSize); //Puts the sprite at the correct positioning. + Vector2 generalOffset = new Vector2(0, 1 * Game1.tileSize); //Puts the sprite at the correct positioning. position -= new Vector2(0, 0.25f * Game1.tileSize); float smallOffset = 0.001f; float tinyOffset = 0.0001f; //Class1.ModMonitor.Log((position - generalOffset).ToString()); float num = Math.Max(0.0f, (float)(Math.Ceiling(Math.Sin(Game1.currentGameTime.TotalGameTime.TotalMilliseconds / 600.0 + (double)npc.DefaultPosition.X * 20.0)) / 4.0)); - this.body.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bodyColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset); - this.eyes.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.eyeColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset *1)); - this.hair.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.hairColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset *2)); + this.body.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bodyColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset); + this.eyes.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.eyeColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 1)); + this.hair.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.hairColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 2)); if (num > 0.0f) { Vector2 shirtOffset = new Vector2((1 * Game1.tileSize) / 4, (1 * Game1.tileSize) / 4); - this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, new Vector2(0.5f,1), scale * Game1.pixelZoom + num, effects, layerDepth + smallOffset + (tinyOffset * 3)); + this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, new Vector2(0.5f, 1), scale * Game1.pixelZoom + num, effects, layerDepth + smallOffset + (tinyOffset * 3)); } else { this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 3)); } - this.pants.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bottomsColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset*4)); - this.shoes.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shoesColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset*5)); - foreach(var accessory in this.accessories) - { - accessory.draw(b, npc, position-generalOffset, sourceRectangle, color, alpha, origin, scale, effects, layerDepth +0.0006f); - } - } + this.pants.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bottomsColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 4)); + this.shoes.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shoesColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 5)); + foreach (var accessory in this.accessories) + accessory.draw(b, npc, position - generalOffset, sourceRectangle, color, alpha, origin, scale, effects, layerDepth + 0.0006f); + } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ColorCollections/StandardColorCollection.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ColorCollections/StandardColorCollection.cs index c27922e7..7b50eceb 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ColorCollections/StandardColorCollection.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ColorCollections/StandardColorCollection.cs @@ -1,93 +1,72 @@ -using Microsoft.Xna.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Microsoft.Xna.Framework; -namespace CustomNPCFramework.Framework.ModularNPCS.ColorCollections +namespace CustomNPCFramework.Framework.ModularNpcs.ColorCollections { - /// - /// Collection of colors to be used for the StandardCharacterAnimation object. - /// + /// Collection of colors to be used for the StandardCharacterAnimation object. public class StandardColorCollection { - /// - /// The draw color to be used for the body sprite for the npc. - /// + /// The draw color to be used for the body sprite for the npc. public Color bodyColor; - /// - /// The draw color to be used for the eye sprite for the npc. - /// + + /// The draw color to be used for the eye sprite for the npc. public Color eyeColor; - /// - /// The draw color to be used for the hair sprite for the npc. - /// + + /// The draw color to be used for the hair sprite for the npc. public Color hairColor; - /// - /// The draw color to be used for the shirt sprite for the npc. - /// + + /// The draw color to be used for the shirt sprite for the npc. public Color shirtColor; - /// - /// The draw color to be used for the bottoms/pants sprite for the npc. - /// + + /// The draw color to be used for the bottoms/pants sprite for the npc. public Color bottomsColor; - /// - /// The draw color to be used for the shoes sprite for the npc. - /// + + /// The draw color to be used for the shoes sprite for the npc. public Color shoesColor; - /// - /// Default constrctor that sets all of the draw colors to white. - /// + /// Construct an instance. public StandardColorCollection() { - defaultColor(this.bodyColor); - defaultColor(this.eyeColor); - defaultColor(this.hairColor); - defaultColor(this.shirtColor); - defaultColor(this.bottomsColor); - defaultColor(this.shoesColor); + this.defaultColor(this.bodyColor); + this.defaultColor(this.eyeColor); + this.defaultColor(this.hairColor); + this.defaultColor(this.shirtColor); + this.defaultColor(this.bottomsColor); + this.defaultColor(this.shoesColor); } - /// - /// Constructor that takes different colors as parameters. - /// - /// Color for the body texture. - /// Color for the eyes texture. - /// Color for the hair texture. - /// Color for the shirt texture. - /// Color for the bottoms texture. - /// Color for the shoes texture. - public StandardColorCollection(Color? BodyColor, Color? EyeColor, Color? HairColor, Color? ShirtColor, Color? BottomsColor, Color? ShoesColor) + /// Construct an instance. + /// Color for the body texture. + /// Color for the eyes texture. + /// Color for the hair texture. + /// Color for the shirt texture. + /// Color for the bottoms texture. + /// Color for the shoes texture. + public StandardColorCollection(Color? bodyColor, Color? eyeColor, Color? hairColor, Color? shirtColor, Color? bottomsColor, Color? shoesColor) { - this.bodyColor = (Color)BodyColor.GetValueOrDefault(Color.White); - this.eyeColor = (Color)EyeColor.GetValueOrDefault(Color.White); - this.hairColor = (Color)HairColor.GetValueOrDefault(Color.White); - this.shirtColor = (Color)ShirtColor.GetValueOrDefault(Color.White); - this.bottomsColor = (Color)BottomsColor.GetValueOrDefault(Color.White); - this.shoesColor = (Color)ShoesColor.GetValueOrDefault(Color.White); + this.bodyColor = bodyColor.GetValueOrDefault(Color.White); + this.eyeColor = eyeColor.GetValueOrDefault(Color.White); + this.hairColor = hairColor.GetValueOrDefault(Color.White); + this.shirtColor = shirtColor.GetValueOrDefault(Color.White); + this.bottomsColor = bottomsColor.GetValueOrDefault(Color.White); + this.shoesColor = shoesColor.GetValueOrDefault(Color.White); - defaultColor(this.bodyColor); - defaultColor(this.eyeColor); - defaultColor(this.hairColor); - defaultColor(this.shirtColor); - defaultColor(this.bottomsColor); - defaultColor(this.shoesColor); + this.defaultColor(this.bodyColor); + this.defaultColor(this.eyeColor); + this.defaultColor(this.hairColor); + this.defaultColor(this.shirtColor); + this.defaultColor(this.bottomsColor); + this.defaultColor(this.shoesColor); } - /// - /// If a color is null, make it white. - /// - /// + /// If a color is null, make it white. + /// The color to check. public void defaultColor(Color color) { - if (color == null) color = Color.White; + if (color == null) + color = Color.White; } - /// - /// Used to mix colors together. - /// + /// Used to mix colors together. /// The base color to mix. /// The modifier color to mix. /// A color that is a mix between the two colors passed in. diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/AnimationKeys.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/AnimationKeys.cs index de9249ae..d862d2be 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/AnimationKeys.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/AnimationKeys.cs @@ -1,31 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CustomNPCFramework.Framework.ModularNPCS.ModularRenderers +namespace CustomNPCFramework.Framework.ModularNpcs.ModularRenderers { - /// - /// A class used instead of an enum to hold keys for all of the different animations. - /// + /// A class used instead of an enum to hold keys for all of the different animations. public class AnimationKeys { - /// - /// The string that is used for the standing animation. - /// + /// The string that is used for the standing animation. public static string standingKey = "standing"; - /// - /// The string that is used for the walking/moving animation. - /// + + /// The string that is used for the walking/moving animation. public static string walkingKey = "walking"; - /// - /// The string that is used for the sitting animation. - /// + + /// The string that is used for the sitting animation. public static string sittingKey = "sitting"; - /// - /// The string that is used for the swimming animation. - /// + + /// The string that is used for the swimming animation. public static string swimmingKey = "swimming"; } } diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/BasicRenderer.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/BasicRenderer.cs index 6ea6629b..eb4ae60f 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/BasicRenderer.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/ModularRenderers/BasicRenderer.cs @@ -1,205 +1,137 @@ -using CustomNPCFramework.Framework.Enums; -using CustomNPCFramework.Framework.Graphics; -using CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases; +using System.Collections.Generic; +using CustomNPCFramework.Framework.Enums; +using CustomNPCFramework.Framework.ModularNpcs.CharacterAnimationBases; using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS.ModularRenderers +namespace CustomNPCFramework.Framework.ModularNpcs.ModularRenderers { - /// - /// A class used to hold all of the textures/animations/information to make modular npc rendering possible. - /// + /// A class used to hold all of the textures/animations/information to make modular npc rendering possible. public class BasicRenderer { - /// - /// Dictionary that holds key pair values of (animationName,Animation). USed to manage multiple animations. - /// + /// Dictionary that holds key pair values of (animationName,Animation). USed to manage multiple animations. public Dictionary animationList; - /// - /// Used to keep track of what animation is currently being used. - /// + + /// Used to keep track of what animation is currently being used. public StandardCharacterAnimation currentAnimation; - /// - /// Constructor. - /// + /// Construct an instance. /// The animation information to be used when the character is standing. /// The animation information to be used when the character is walking/moving. /// The animation information to be used when the character is walking/moving. - public BasicRenderer(StandardCharacterAnimation standingAnimation,StandardCharacterAnimation walkingAnimation, StandardCharacterAnimation swimmingAnimation) + public BasicRenderer(StandardCharacterAnimation standingAnimation, StandardCharacterAnimation walkingAnimation, StandardCharacterAnimation swimmingAnimation) { - animationList = new Dictionary(); - animationList.Add(AnimationKeys.standingKey, standingAnimation); - animationList.Add(AnimationKeys.walkingKey, walkingAnimation); - animationList.Add(AnimationKeys.swimmingKey, swimmingAnimation); - setAnimation(AnimationKeys.standingKey); + this.animationList = new Dictionary(); + this.animationList.Add(AnimationKeys.standingKey, standingAnimation); + this.animationList.Add(AnimationKeys.walkingKey, walkingAnimation); + this.animationList.Add(AnimationKeys.swimmingKey, swimmingAnimation); + this.setAnimation(AnimationKeys.standingKey); } - /// - /// Sets the animation associated with the key name; If it fails the npc will just default to standing. - /// + /// Sets the animation associated with the key name; If it fails the npc will just default to standing. /// The name of the animation to swap the current animation to. public virtual void setAnimation(string key) { - this.currentAnimation = animationList[key]; + this.currentAnimation = this.animationList[key]; if (this.currentAnimation == null) { - Class1.ModMonitor.Log("ERROR SETTING AN ANIMATION: "+key); + Class1.ModMonitor.Log("ERROR SETTING AN ANIMATION: " + key); this.setAnimation(AnimationKeys.standingKey); } } - /// - /// Sets the direction of the current animated sprite respectively. - /// + /// Sets the direction of the current animated sprite respectively. /// The direction to face. 0=up, 1=right, 2= down, 3=left. public virtual void setDirection(int facingDirection) { - if (facingDirection == 0) setUp(); - if (facingDirection == 1) setRight(); - if (facingDirection == 2) setDown(); - if (facingDirection == 2) setLeft(); + this.setDirection((Direction)facingDirection); } - /// - /// Sets the direction of the current animated sprite respectively to the direction passed in. - /// + /// Sets the direction of the current animated sprite respectively to the direction passed in. /// The direction to face. public virtual void setDirection(Direction direction) { - if (direction == Direction.up) setUp(); - if (direction == Direction.right) setRight(); - if (direction == Direction.down) setDown(); - if (direction == Direction.left) setLeft(); + switch (direction) + { + case Direction.up: + this.setUp(); + break; + + case Direction.right: + this.setRight(); + break; + + case Direction.down: + this.setDown(); + break; + + case Direction.left: + this.setLeft(); + break; + } } - - /// - /// Sets the current animated sprite to face left. - /// + /// Sets the current animated sprite to face left. public virtual void setLeft() { this.currentAnimation.setLeft(); } - /// - /// Sets the current animated sprite to face right. - /// + /// Sets the current animated sprite to face right. public virtual void setRight() { this.currentAnimation.setRight(); } - /// - /// Sets the current animated sprite to face up. - /// + /// Sets the current animated sprite to face up. public virtual void setUp() { this.currentAnimation.setUp(); } - - /// - /// Sets the current animated sprite to face down. - /// + + /// Sets the current animated sprite to face down. public virtual void setDown() { this.currentAnimation.setDown(); } - /// - /// Used to reload all of the sprites pertaining to all of the animations stored in this renderer. - /// + /// Used to reload all of the sprites pertaining to all of the animations stored in this renderer. public virtual void reloadSprites() { - foreach(var v in this.animationList) - { + foreach (var v in this.animationList) v.Value.reload(); - } } - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// + /// Used to draw the sprite to the screen. public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) { this.currentAnimation.draw(b, screenPosition, layerDepth); } - /// - /// Used to draw the sprite to the screen. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// Used to draw the sprite to the screen. public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) { this.currentAnimation.draw(b, screenPosition, layerDepth, xOffset, yOffset, c, flip, scale, rotation, characterSourceRectOffset); } - /// - /// A very verbose asset drawer. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) + /// A very verbose asset drawer. + public virtual void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { - this.currentAnimation.draw(b, npc, position, sourceRectangle, color, alpha, origin, scale, effects, layerDepth); } - /// - /// Animates the current animation for the current sprite. - /// - /// - /// - public virtual void Animate(float interval, bool loop=true) + /// Animates the current animation for the current sprite. + public virtual void Animate(float interval, bool loop = true) { - this.currentAnimation.Animate(interval,loop); + this.currentAnimation.Animate(interval, loop); } - - /// - /// Wrapper for a draw function that accepts rectangles to be null. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual void draw(SpriteBatch b, ExtendedNPC extendedNPC, Vector2 position, Rectangle? v1, Color white, float rotation, Vector2 origin, float scale, SpriteEffects spriteEffects, float v3) + /// Wrapper for a draw function that accepts rectangles to be null. + public virtual void draw(SpriteBatch b, ExtendedNpc extendedNPC, Vector2 position, Rectangle? v1, Color white, float rotation, Vector2 origin, float scale, SpriteEffects spriteEffects, float v3) { - this.draw(b, extendedNPC, position, new Rectangle(0,0,16,32), white, rotation, origin, scale, spriteEffects, v3); + this.draw(b, extendedNPC, position, new Rectangle(0, 0, 16, 32), white, rotation, origin, scale, spriteEffects, v3); } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Portrait.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Portrait.cs index 4e6b10aa..2ec8b3e6 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Portrait.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Portrait.cs @@ -1,49 +1,32 @@ -using CustomNPCFramework.Framework.NPCS; +using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework.Graphics; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS +namespace CustomNPCFramework.Framework.ModularNpcs { - /// - /// Used as a wrapper for npc portraits. - /// + /// Used as a wrapper for npc portraits. public class Portrait { - /// - /// Used to display the npc portrait. - /// + /// Used to display the npc portrait. public Texture2D portrait; - /// - /// Used to hold the path to the texture to use for the npc portrait. - /// + + /// Used to hold the path to the texture to use for the npc portrait. public string relativePath; - /// - /// A class for handling portraits. - /// + /// /// The full path to the file. public Portrait(string path) { - this.relativePath =Class1.getRelativeDirectory(path); - this.portrait=Class1.ModHelper.Content.Load(path); + this.relativePath = Class1.getRelativeDirectory(path); + this.portrait = Class1.ModHelper.Content.Load(path); } - /// - /// Sets the npc's portrait to be this portrait texture. - /// - /// - public void setCharacterPortraitFromThis(ExtendedNPC npc) + /// Sets the npc's portrait to be this portrait texture. + public void setCharacterPortraitFromThis(ExtendedNpc npc) { npc.Portrait = this.portrait; } - /// - /// Reloads the texture for the NPC portrait. - /// + /// Reloads the texture for the NPC portrait. public void reload() { this.portrait = Class1.ModHelper.Content.Load(this.relativePath); diff --git a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Sprite.cs b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Sprite.cs index e821bebc..0ee288e4 100644 --- a/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Sprite.cs +++ b/GeneralMods/CustomNPCFramework/Framework/ModularNPCS/Sprite.cs @@ -1,52 +1,32 @@ -using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers; using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework.Graphics; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace CustomNPCFramework.Framework.ModularNPCS +namespace CustomNPCFramework.Framework.ModularNpcs { - /// - /// Used as a wrapper for the npcs to hold sprite information. - /// + /// Used as a wrapper for the npcs to hold sprite information. public class Sprite { - /// - /// The actual sprite to draw for the npc. - /// + /// The actual sprite to draw for the npc. public AnimatedSprite sprite; - /// - /// The path to the texture to use for the animated sprite. - /// + + /// The path to the texture to use for the animated sprite. public string relativePath; - /// - /// A class for handling character sprites. - /// - /// The full path to the file. - public Sprite(string path) + /// Construct an instance. + /// The relative path to the file. + public Sprite(string relativePath) { - try - { - this.relativePath = Class1.getShortenedDirectory(path); - } - catch(Exception err) - { - this.relativePath = path; - } + this.relativePath = relativePath; try { this.sprite = new AnimatedSprite(); Texture2D text = Class1.ModHelper.Content.Load(this.relativePath); - var reflect=Class1.ModHelper.Reflection.GetField(this.sprite, "Texture", true); + var reflect = Class1.ModHelper.Reflection.GetField(this.sprite, "Texture", true); reflect.SetValue(text); - + } - catch(Exception err) + catch { this.sprite = new AnimatedSprite(); Texture2D text = Class1.ModHelper.Content.Load(this.relativePath); @@ -57,9 +37,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS this.sprite.SpriteHeight = this.sprite.Texture.Height; } - /// - /// Constructor. - /// + /// Construct an instance. /// Used to hold the path to the asset. /// Used to assign the texture to the sprite from a pre-loaded asset. public Sprite(string path, string texture) @@ -70,75 +48,42 @@ namespace CustomNPCFramework.Framework.ModularNPCS this.sprite.SpriteHeight = this.sprite.Texture.Height; } - /// - /// Sets the npc's portrait to be this portrait texture. - /// - /// - public void setCharacterSpriteFromThis(ExtendedNPC npc) + /// Sets the npc's portrait to be this portrait texture. + public void setCharacterSpriteFromThis(ExtendedNpc npc) { npc.Sprite = this.sprite; } - /// - /// Reloads the texture for the NPC portrait. - /// + /// Reloads the texture for the NPC portrait. public void reload() { - var text=CustomNPCFramework.Class1.ModHelper.Reflection.GetField(this.sprite.Texture, "Texture", true); - Texture2D loaded= Class1.ModHelper.Content.Load(this.relativePath); + var text = Class1.ModHelper.Reflection.GetField(this.sprite.Texture, "Texture", true); + Texture2D loaded = Class1.ModHelper.Content.Load(this.relativePath); text.SetValue(loaded); } - /// - /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. - /// - /// - public void setLeft(ExtendedNPC npc) + /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. + public void setLeft(ExtendedNpc npc) { - if (npc.characterRenderer == null) - { - return; - } - else npc.characterRenderer.setLeft(); + npc.characterRenderer?.setLeft(); } - /// - /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. - /// - /// - public void setRight(ExtendedNPC npc) + /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. + public void setRight(ExtendedNpc npc) { - if (npc.characterRenderer == null) - { - return; - } - else npc.characterRenderer.setRight(); + npc.characterRenderer?.setRight(); } - /// - /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. - /// - /// - public void setDown(ExtendedNPC npc) + /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. + public void setDown(ExtendedNpc npc) { - if (npc.characterRenderer == null) - { - return; - } - else npc.characterRenderer.setDown(); + npc.characterRenderer?.setDown(); } - /// - /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. - /// - /// - public void setUp(ExtendedNPC npc) + /// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. + public void setUp(ExtendedNpc npc) { - if (npc.characterRenderer == null) - { - return; - } - else npc.characterRenderer.setUp(); + npc.characterRenderer?.setUp(); } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/NPCNames.cs b/GeneralMods/CustomNPCFramework/Framework/NPCNames.cs index 6ede8e02..f511193a 100644 --- a/GeneralMods/CustomNPCFramework/Framework/NPCNames.cs +++ b/GeneralMods/CustomNPCFramework/Framework/NPCNames.cs @@ -1,77 +1,59 @@ -using CustomNPCFramework.Framework.Enums; -using StardewValley; -using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using CustomNPCFramework.Framework.Enums; +using StardewValley; namespace CustomNPCFramework.Framework { - /// - /// Used as a class to hold all of the possible npc names. - /// - public class NPCNames + /// Used as a class to hold all of the possible NPC names. + public class NpcNames { - /// - /// Holds all of the npc male names. - /// - public static List maleNames = new List() + /// Holds all of the NPC male names. + public static List maleNames = new List { "Freddy", "Josh", "Ash" }; - /// - /// Holds all of the npc female names. - /// - public static List femaleNames = new List() + /// Holds all of the NPC female names. + public static List femaleNames = new List { "Rebecca", "Sierra", "Lisa" }; - /// - /// Holds all of the npc gender non-binary names. - /// - public static List otherGenderNames = new List() + /// Holds all of the NPC gender non-binary names. + public static List otherGenderNames = new List { "Jayden", "Ryanne", "Skylar" }; - /// - /// Get a gender appropriate name from the pool of npc names. - /// - /// - /// - public static string getRandomNPCName(Genders gender) + /// Get a gender appropriate name from the pool of NPC names. + public static string getRandomNpcName(Genders gender) { - if (gender == Genders.female) { - + if (gender == Genders.female) + { int rand = Game1.random.Next(0, femaleNames.Count - 1); return femaleNames.ElementAt(rand); } if (gender == Genders.male) { - int rand = Game1.random.Next(0, maleNames.Count - 1); return maleNames.ElementAt(rand); } if (gender == Genders.other) { - int rand = Game1.random.Next(0, otherGenderNames.Count - 1); return otherGenderNames.ElementAt(rand); } return ""; - } } } diff --git a/GeneralMods/CustomNPCFramework/Framework/NPCS/ExtendedNPC.cs b/GeneralMods/CustomNPCFramework/Framework/NPCS/ExtendedNPC.cs index 925fd7c3..9a3e4d08 100644 --- a/GeneralMods/CustomNPCFramework/Framework/NPCS/ExtendedNPC.cs +++ b/GeneralMods/CustomNPCFramework/Framework/NPCS/ExtendedNPC.cs @@ -1,35 +1,22 @@ -using CustomNPCFramework.Framework.Enums; -using CustomNPCFramework.Framework.ModularNPCS; -using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers; +using System; +using CustomNPCFramework.Framework.Enums; +using CustomNPCFramework.Framework.ModularNpcs; +using CustomNPCFramework.Framework.ModularNpcs.ModularRenderers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; -using StardewValley.Buildings; -using StardewValley.Characters; -using StardewValley.Locations; -using StardewValley.Menus; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using xTile.Dimensions; -using xTile.ObjectModel; -using xTile.Tiles; namespace CustomNPCFramework.Framework.NPCS { - /// - /// TODO: Add in an resource loader for all of the character graphics and use it to populate some character graphics. - /// Make .json way to load in assets to the mod. - /// Organize it all. - /// Profit??? - /// - public class ExtendedNPC :StardewValley.NPC + // TODO: + // - Add in an resource loader for all of the character graphics and use it to populate some character graphics. + // - Make .json way to load in assets to the mod. + // - Organize it all. + // - Profit??? + + public class ExtendedNpc : NPC { - /// - /// The custom character renderer for this npc. - /// + /// The custom character renderer for this npc. public BasicRenderer characterRenderer; public bool hasBeenKissedToday; public Point previousEndPoint; @@ -37,122 +24,89 @@ namespace CustomNPCFramework.Framework.NPCS public bool hasSaidAfternoonDialogue; public int timeAfterSquare; - /// - /// Used to hold sprite information to be used in the case the npc renderer is null. - /// + /// Used to hold sprite information to be used in the case the npc renderer is null. public Sprite spriteInformation; - /// - /// Used to hold the portrait information for the npc and display it. - /// + /// Used to hold the portrait information for the npc and display it. public Portrait portraitInformation; - /// - /// The default location for this npc to reside in. - /// + /// The default location for this npc to reside in. public GameLocation defaultLocation; - /// - /// Empty Constructor. - /// - public ExtendedNPC() :base() - { - } + /// Construct an instance. + public ExtendedNpc() { } - /// - /// Non modular npc Constructor. - /// + /// Construct an instance. /// The sprite for the character. /// The position of the npc on the map. /// The direction of the npc /// The name of the npc. - public ExtendedNPC(Sprite sprite, Vector2 position, int facingDirection, string name) : base(sprite.sprite, position, facingDirection, name, null) + public ExtendedNpc(Sprite sprite, Vector2 position, int facingDirection, string name) + : base(sprite.sprite, position, facingDirection, name) { this.characterRenderer = null; - this.Portrait = (Texture2D)null; + this.Portrait = null; this.portraitInformation = null; this.spriteInformation = sprite; - if (this.spriteInformation != null) - { - this.spriteInformation.setCharacterSpriteFromThis(this); - } + this.spriteInformation?.setCharacterSpriteFromThis(this); this.swimming.Value = false; } - /// - /// Non modular npc Constructor. - /// + /// Construct an instance. /// The sprite for the character. /// The portrait texture for this npc. /// The position of the npc on the map. /// The direction of the npc /// The name of the npc. - public ExtendedNPC(Sprite sprite, Portrait portrait, Vector2 position, int facingDirection, string name) : base(sprite.sprite, position, facingDirection, name, null) + public ExtendedNpc(Sprite sprite, Portrait portrait, Vector2 position, int facingDirection, string name) + : base(sprite.sprite, position, facingDirection, name) { this.characterRenderer = null; this.portraitInformation = portrait; - if (this.portraitInformation != null) - { - this.portraitInformation.setCharacterPortraitFromThis(this); - } + this.portraitInformation?.setCharacterPortraitFromThis(this); this.spriteInformation = sprite; this.spriteInformation.setCharacterSpriteFromThis(this); this.swimming.Value = false; } - /// - /// Modular npc constructor. - /// + /// Construct an instance. /// The sprite for the character to use incase the renderer is null. /// The custom npc render. Used to draw the npcfrom a collection of assets. - /// The portrait texture for this npc. /// The position of the npc on the map. /// The direction of the npc /// The name of the npc. - public ExtendedNPC(Sprite sprite,BasicRenderer renderer,Vector2 position,int facingDirection,string name): base(sprite.sprite, position, facingDirection, name, null) + public ExtendedNpc(Sprite sprite, BasicRenderer renderer, Vector2 position, int facingDirection, string name) + : base(sprite.sprite, position, facingDirection, name) { this.characterRenderer = renderer; - this.Portrait = (Texture2D)null; + this.Portrait = null; this.portraitInformation = null; this.spriteInformation = sprite; - if (this.spriteInformation != null) - { - this.spriteInformation.setCharacterSpriteFromThis(this); - } + this.spriteInformation?.setCharacterSpriteFromThis(this); this.swimming.Value = false; } - /// - /// Modular constructor for the npc. - /// + /// Construct an instance. /// The sprite for the npc to use incase the renderer is null. /// The custom npc renderer used to draw the npc from the collection of textures. /// The portrait texture for the npc. /// The positon for the npc to be. /// The direction for the npc to face. /// The name for the npc. - public ExtendedNPC(Sprite sprite,BasicRenderer renderer,Portrait portrait, Vector2 position, int facingDirection, string name) : base(sprite.sprite, position, facingDirection, name, null) + public ExtendedNpc(Sprite sprite, BasicRenderer renderer, Portrait portrait, Vector2 position, int facingDirection, string name) + : base(sprite.sprite, position, facingDirection, name) { this.characterRenderer = renderer; this.portraitInformation = portrait; - if (this.portraitInformation != null) - { - this.portraitInformation.setCharacterPortraitFromThis(this); - } + this.portraitInformation?.setCharacterPortraitFromThis(this); this.spriteInformation = sprite; - if (this.spriteInformation != null) - { - this.spriteInformation.setCharacterSpriteFromThis(this); - } + this.spriteInformation?.setCharacterSpriteFromThis(this); this.swimming.Value = false; } - /// - /// Used to reload the sprite for the npc. - /// + /// Used to reload the sprite for the npc. public void reloadSprite() { - if (this.characterRenderer == null) { this.spriteInformation.reload(); @@ -160,10 +114,9 @@ namespace CustomNPCFramework.Framework.NPCS { this.portraitInformation.reload(); } - catch (Exception ex) + catch { - ex.ToString(); - this.Portrait = (Texture2D)null; + this.Portrait = null; } } else @@ -173,14 +126,12 @@ namespace CustomNPCFramework.Framework.NPCS { this.portraitInformation.reload(); } - catch (Exception ex) + catch { - ex.ToString(); - this.Portrait = (Texture2D)null; + this.Portrait = null; } } - int num = this.IsInvisible ? 1 : 0; - if (!Game1.newDay && (int)Game1.gameMode != 6) + if (!Game1.newDay && Game1.gameMode != 6) return; this.faceDirection(this.DefaultFacingDirection); this.scheduleTimeToTry = 9999999; @@ -188,164 +139,133 @@ namespace CustomNPCFramework.Framework.NPCS this.Schedule = this.getSchedule(Game1.dayOfMonth); this.faceDirection(this.defaultFacingDirection); this.Sprite.standAndFaceDirection(this.defaultFacingDirection); - + if (this.isMarried()) this.marriageDuties(); - bool flag = Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason); try { this.displayName = this.Name; } - catch (Exception ex) - { - ex.ToString(); - } - + catch { } } - /// - /// Functionality used when interacting with the npc. - /// - /// - /// - /// - public override bool checkAction(StardewValley.Farmer who, GameLocation l) + /// Functionality used when interacting with the npc. + public override bool checkAction(Farmer who, GameLocation l) { base.checkAction(who, l); return false; } - /// - /// Used to move the npc. Different code is used depending if the character renderer is null or not. - /// - /// - /// - /// + /// Used to move the npc. Different code is used depending if the character renderer is null or not. public override void MovePosition(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation) { if (this.characterRenderer != null) - { - ModularMovement(time,viewport,currentLocation); - } + this.ModularMovement(time, viewport, currentLocation); else - { - NonModularMovement(time,viewport,currentLocation); - } - return; - + this.NonModularMovement(time, viewport, currentLocation); } - /// - /// Set's the npc to move a certain direction and then executes the movement. - /// - /// - /// - /// - /// The direction to move the npc. + /// Set's the npc to move a certain direction and then executes the movement. + /// The direction to move the npc. /// Set's the npc's sprite to halt if Move=false. Else set it to true. - public virtual void SetMovingAndMove(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation, Direction MoveDirection, bool Move=true) + public virtual void SetMovingAndMove(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation, Direction moveDirection, bool Move = true) { - if (MoveDirection == Direction.down) this.SetMovingDown(Move); - if (MoveDirection == Direction.left) this.SetMovingLeft(Move); - if (MoveDirection == Direction.up) this.SetMovingUp(Move); - if (MoveDirection == Direction.right) this.SetMovingRight(Move); + switch (moveDirection) + { + case Direction.down: + this.SetMovingDown(Move); + break; + + case Direction.left: + this.SetMovingLeft(Move); + break; + + case Direction.up: + this.SetMovingUp(Move); + break; + + case Direction.right: + this.SetMovingRight(Move); + break; + } + this.MovePosition(time, viewport, currentLocation); } - /// - /// USed to move the npc if the character renderer is null. - /// - /// - /// - /// + /// USed to move the npc if the character renderer is null. public virtual void NonModularMovement(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation location) { - base.MovePosition(time, viewport, currentLocation); - return; + base.MovePosition(time, viewport, this.currentLocation); } - /// - /// Used to determine if the npc can move past the next location. - /// - /// - /// + /// Used to determine if the npc can move past the next location. public virtual bool canMovePastNextLocation(xTile.Dimensions.Rectangle viewport) { //Up - if (!currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot) - { + if (!this.currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot) return false; - } + //Right - if (!currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot) - { + if (!this.currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot) return false; - } + //Down - if (!currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot) - { + if (!this.currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot) return false; - } + //Left - if (!currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot) - { + if (!this.currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot) return false; - } + return true; } - /// - /// Used to move the npc if the character renderer is valid. Handles animating all of the sprites associated with the renderer. - /// - /// - /// - /// - /// + /// Used to move the npc if the character renderer is valid. Handles animating all of the sprites associated with the renderer. public virtual void ModularMovement(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation location, float interval = 1000f) { this.characterRenderer.setAnimation(AnimationKeys.walkingKey); - if (this.canMovePastNextLocation(viewport) == false) + if (!this.canMovePastNextLocation(viewport)) { this.Halt(); return; } if (this.GetType() == typeof(FarmAnimal)) this.willDestroyObjectsUnderfoot = false; - if ((double)this.xVelocity != 0.0 || (double)this.yVelocity != 0.0) + if (this.xVelocity != 0.0 || this.yVelocity != 0.0) { - Microsoft.Xna.Framework.Rectangle boundingBox = this.GetBoundingBox(); + var boundingBox = this.GetBoundingBox(); boundingBox.X += (int)this.xVelocity; boundingBox.Y -= (int)this.yVelocity; - if (currentLocation == null || !currentLocation.isCollidingPosition(boundingBox, viewport, false, 0, false, this)) + if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(boundingBox, viewport, false, 0, false, this)) { this.position.X += this.xVelocity; this.position.Y -= this.yVelocity; } - this.xVelocity = (float)(int)((double)this.xVelocity - (double)this.xVelocity / 2.0); - this.yVelocity = (float)(int)((double)this.yVelocity - (double)this.yVelocity / 2.0); + this.xVelocity = (int)(this.xVelocity - this.xVelocity / 2.0); + this.yVelocity = (int)(this.yVelocity - this.yVelocity / 2.0); } else if (this.moveUp) { - if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(0), viewport, false, 0, false, this) || this.isCharging) + if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(0), viewport, false, 0, false, this) || this.isCharging) { - this.position.Y -= (float)(this.speed + this.addedSpeed); + this.position.Y -= this.speed + this.addedSpeed; if (!this.ignoreMovementAnimation) { this.spriteInformation.setUp(this); - this.characterRenderer.Animate(interval,true); + this.characterRenderer.Animate(interval); //this.sprite.AnimateUp(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); this.faceDirection(0); } } - else if (!currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot) + else if (!this.currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot) this.Halt(); else if (this.willDestroyObjectsUnderfoot) { - Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize), (float)(this.getStandingY() / Game1.tileSize - 1)); - if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(0), true)) + Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize, this.getStandingY() / Game1.tileSize - 1); + if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(0), true)) { - this.doEmote(12, true); - this.position.Y -= (float)(this.speed + this.addedSpeed); + this.doEmote(12); + this.position.Y -= this.speed + this.addedSpeed; } else this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; @@ -353,27 +273,27 @@ namespace CustomNPCFramework.Framework.NPCS } else if (this.moveRight) { - if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(1), viewport, false, 0, false, this) || this.isCharging) + if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(1), viewport, false, 0, false, this) || this.isCharging) { - this.position.X += (float)(this.speed + this.addedSpeed); + this.position.X += this.speed + this.addedSpeed; if (!this.ignoreMovementAnimation) { this.spriteInformation.setRight(this); - this.characterRenderer.Animate(interval,true); + this.characterRenderer.Animate(interval); //this.spriteInformation.sprite.Animate(time, 0, 3, 1f); //this.sprite.AnimateRight(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); this.faceDirection(1); } } - else if (!currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot) + else if (!this.currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot) this.Halt(); else if (this.willDestroyObjectsUnderfoot) { - Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize + 1), (float)(this.getStandingY() / Game1.tileSize)); - if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(1), true)) + Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize + 1, this.getStandingY() / Game1.tileSize); + if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(1), true)) { - this.doEmote(12, true); - this.position.X += (float)(this.speed + this.addedSpeed); + this.doEmote(12); + this.position.X += this.speed + this.addedSpeed; } else this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; @@ -381,27 +301,27 @@ namespace CustomNPCFramework.Framework.NPCS } else if (this.moveDown) { - if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(2), viewport, false, 0, false, this) || this.isCharging) + if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(2), viewport, false, 0, false, this) || this.isCharging) { - this.position.Y += (float)(this.speed + this.addedSpeed); + this.position.Y += this.speed + this.addedSpeed; if (!this.ignoreMovementAnimation) { this.spriteInformation.setDown(this); - this.characterRenderer.Animate(interval,true); + this.characterRenderer.Animate(interval); //this.spriteInformation.sprite.Animate(time, 0, 3, 1f); //this.sprite.AnimateDown(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); this.faceDirection(2); } } - else if (!currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot) + else if (!this.currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot) this.Halt(); else if (this.willDestroyObjectsUnderfoot) { - Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize), (float)(this.getStandingY() / Game1.tileSize + 1)); - if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(2), true)) + Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize, this.getStandingY() / Game1.tileSize + 1); + if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(2), true)) { - this.doEmote(12, true); - this.position.Y += (float)(this.speed + this.addedSpeed); + this.doEmote(12); + this.position.Y += this.speed + this.addedSpeed; } else this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; @@ -409,35 +329,35 @@ namespace CustomNPCFramework.Framework.NPCS } else if (this.moveLeft) { - if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(3), viewport, false, 0, false, this) || this.isCharging) + if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(3), viewport, false, 0, false, this) || this.isCharging) { - this.position.X -= (float)(this.speed + this.addedSpeed); + this.position.X -= this.speed + this.addedSpeed; if (!this.ignoreMovementAnimation) { this.spriteInformation.setLeft(this); - this.characterRenderer.Animate(interval,true); + this.characterRenderer.Animate(interval); //this.spriteInformation.sprite.Animate(time, 0, 3, 1f); //this.sprite.AnimateLeft(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); this.faceDirection(3); } } - else if (!currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot) + else if (!this.currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot) this.Halt(); else if (this.willDestroyObjectsUnderfoot) { - Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize - 1), (float)(this.getStandingY() / Game1.tileSize)); - if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(3), true)) + Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize - 1, this.getStandingY() / Game1.tileSize); + if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(3), true)) { - this.doEmote(12, true); - this.position.X -= (float)(this.speed + this.addedSpeed); + this.doEmote(12); + this.position.X -= this.speed + this.addedSpeed; } else this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; } } - if (this.blockedInterval >= 3000 && (double)this.blockedInterval <= 3750.0 && !Game1.eventUp) + if (this.blockedInterval >= 3000 && this.blockedInterval <= 3750.0 && !Game1.eventUp) { - this.doEmote(Game1.random.NextDouble() < 0.5 ? 8 : 40, true); + this.doEmote(Game1.random.NextDouble() < 0.5 ? 8 : 40); this.blockedInterval = 3750; } else @@ -450,33 +370,15 @@ namespace CustomNPCFramework.Framework.NPCS } } - /// - /// Used to halt the npc sprite. Sets the npc's animation to the standing animation if the character renderer is not null. - /// + /// Used to halt the npc sprite. Sets the npc's animation to the standing animation if the character renderer is not null. public override void Halt() { - if (this.characterRenderer != null) - { - this.characterRenderer.setAnimation(AnimationKeys.standingKey); - } + this.characterRenderer?.setAnimation(AnimationKeys.standingKey); base.Halt(); } - /// - /// Used to update npc information. - /// - /// - /// - public override void update(GameTime time, GameLocation location) - { - base.update(time, location); - } - - /// - /// Pathfinding code. - /// - /// - public virtual void routeEndAnimationFinished(StardewValley.Farmer who) + /// Pathfinding code. + public virtual void routeEndAnimationFinished(Farmer who) { this.doingEndOfRouteAnimation.Value = false; this.freezeMotion = false; @@ -493,26 +395,15 @@ namespace CustomNPCFramework.Framework.NPCS this.timeAfterSquare = Game1.timeOfDay; } - /// - /// Pathfinding code. - /// - /// - /// - public virtual void doAnimationAtEndOfScheduleRoute(Character c, GameLocation l) - { - } + /// Pathfinding code. + public virtual void doAnimationAtEndOfScheduleRoute(Character c, GameLocation l) { } - /// - /// Pathfinding code. - /// - /// + /// Pathfinding code. public virtual void startRouteBehavior(string behaviorName) { if (behaviorName.Length > 0 && (int)behaviorName[0] == 34) - { this.endOfRouteMessage.Value = behaviorName.Replace("\"", ""); - } else { if (behaviorName.Contains("square_")) @@ -524,24 +415,20 @@ namespace CustomNPCFramework.Framework.NPCS } else { - Utility.getGameLocationOfCharacter(this).temporarySprites.Add(new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Microsoft.Xna.Framework.Rectangle(167, 1714, 19, 14), 100f, 3, 999999, new Vector2(2f, 3f) * (float)Game1.tileSize + new Vector2(7f, 12f) * (float)Game1.pixelZoom, false, false, 0.0002f, 0.0f, Color.White, (float)Game1.pixelZoom, 0.0f, 0.0f, 0.0f, false) + Utility.getGameLocationOfCharacter(this).temporarySprites.Add(new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Microsoft.Xna.Framework.Rectangle(167, 1714, 19, 14), 100f, 3, 999999, new Vector2(2f, 3f) * (float)Game1.tileSize + new Vector2(7f, 12f) * (float)Game1.pixelZoom, false, false, 0.0002f, 0.0f, Color.White, (float)Game1.pixelZoom, 0.0f, 0.0f, 0.0f) { id = 688f }); - this.doEmote(52, true); + this.doEmote(52); } } } - /// - /// Occurs when the npc gets hit by the player. - /// - /// - /// + /// Occurs when the npc gets hit by the player. public new void getHitByPlayer(StardewValley.Farmer who, GameLocation location) { - this.doEmote(12, true); + this.doEmote(12); if (who == null) { if (Game1.IsMultiplayer) @@ -550,8 +437,7 @@ namespace CustomNPCFramework.Framework.NPCS } if (who.friendshipData.ContainsKey(this.Name)) { - Friendship f; - who.friendshipData.TryGetValue(this.Name, out f); + who.friendshipData.TryGetValue(this.Name, out Friendship f); f.Points -= 30; if (who.IsMainPlayer) { @@ -570,7 +456,7 @@ namespace CustomNPCFramework.Framework.NPCS public override void dayUpdate(int dayOfMonth) { if (this.currentLocation != null) - Game1.warpCharacter(this, this.DefaultMap, this.DefaultPosition / (float)Game1.tileSize); + Game1.warpCharacter(this, this.DefaultMap, this.DefaultPosition / Game1.tileSize); Game1.player.mailReceived.Remove(this.Name); Game1.player.mailReceived.Remove(this.Name + "Cooking"); this.doingEndOfRouteAnimation.Value = false; @@ -582,18 +468,18 @@ namespace CustomNPCFramework.Framework.NPCS this.hasSaidAfternoonDialogue = false; this.ignoreScheduleToday = false; this.Halt(); - this.controller = (PathFindController)null; - this.temporaryController = (PathFindController)null; - this.DirectionsToNewLocation = (SchedulePathDescription)null; + this.controller = null; + this.temporaryController = null; + this.DirectionsToNewLocation = null; this.faceDirection(this.DefaultFacingDirection); this.scheduleTimeToTry = 9999999; this.previousEndPoint = new Point((int)this.DefaultPosition.X / Game1.tileSize, (int)this.DefaultPosition.Y / Game1.tileSize); this.IsWalkingInSquare = false; this.returningToEndPoint = false; - this.lastCrossroad = Microsoft.Xna.Framework.Rectangle.Empty; + this.lastCrossroad = Rectangle.Empty; if (this.isVillager()) this.Schedule = this.getSchedule(dayOfMonth); - this.endOfRouteMessage.Value = (string)null; + this.endOfRouteMessage.Value = null; bool flag = Utility.isFestivalDay(dayOfMonth, Game1.currentSeason); if (!this.isMarried()) return; @@ -602,18 +488,10 @@ namespace CustomNPCFramework.Framework.NPCS //this.daysMarried = this.daysMarried + 1; } - /// - /// Does effectively nothing. - /// - public new void setUpForOutdoorPatioActivity() - { - } + /// Does effectively nothing. + public new void setUpForOutdoorPatioActivity() { } - /// - /// Used to draw the npc with the custom renderer. - /// - /// - /// + /// Used to draw the npc with the custom renderer. public virtual void drawModular(SpriteBatch b, float alpha = 1f) { if (this.characterRenderer == null || this.IsInvisible || !Utility.isOnScreen(this.position, 2 * Game1.tileSize)) @@ -623,7 +501,7 @@ namespace CustomNPCFramework.Framework.NPCS { this.characterRenderer.setAnimation(AnimationKeys.swimmingKey); this.characterRenderer.setDirection(this.facingDirection); - this.characterRenderer.draw(b,this,this.getLocalPosition(Game1.viewport) + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize + Game1.tileSize / 4 + this.yJumpOffset * 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero) - new Vector2(0.0f, this.yOffset), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.Sprite.SourceRect.X, this.Sprite.SourceRect.Y, this.Sprite.SourceRect.Width, this.Sprite.SourceRect.Height / 2 - (int)((double)this.yOffset / (double)Game1.pixelZoom))), Color.White, this.rotation, new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize * 3 / 2)) / 4f, Math.Max(0.2f, this.Scale) * (float)Game1.pixelZoom, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, (float)this.getStandingY() / 10000f)); + this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize + Game1.tileSize / 4 + this.yJumpOffset * 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero) - new Vector2(0.0f, this.yOffset), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.Sprite.SourceRect.X, this.Sprite.SourceRect.Y, this.Sprite.SourceRect.Width, this.Sprite.SourceRect.Height / 2 - (int)((double)this.yOffset / (double)Game1.pixelZoom))), Color.White, this.rotation, new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize * 3 / 2)) / 4f, Math.Max(0.2f, this.Scale) * (float)Game1.pixelZoom, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, (float)this.getStandingY() / 10000f)); //Vector2 localPosition = this.getLocalPosition(Game1.viewport); //b.Draw(Game1.staminaRect, new Microsoft.Xna.Framework.Rectangle((int)localPosition.X + (int)this.yOffset + Game1.pixelZoom * 2, (int)localPosition.Y - 32 * Game1.pixelZoom + this.sprite.SourceRect.Height * Game1.pixelZoom + Game1.tileSize * 3 / 4 + this.yJumpOffset * 2 - (int)this.yOffset, this.sprite.SourceRect.Width * Game1.pixelZoom - (int)this.yOffset * 2 - Game1.pixelZoom * 4, Game1.pixelZoom), new Microsoft.Xna.Framework.Rectangle?(Game1.staminaRect.Bounds), Color.White * 0.75f, 0.0f, Vector2.Zero, SpriteEffects.None, (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0)); } @@ -655,7 +533,7 @@ namespace CustomNPCFramework.Framework.NPCS sourceRect.Height /= 2; } //The actual character drawing to the screen? - this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation,Vector2.Zero, Math.Max(0.2f, this.Scale), this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); + this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, Vector2.Zero, Math.Max(0.2f, this.Scale), this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); //this.characterRenderer.draw(b,this, this.getLocalPosition(Game1.viewport) + vector2 + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, new Vector2((float)(sourceRect.Width / 2), (float)(sourceRect.Height / 2 + 1)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom + num, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); //this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + vector2 + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, new Vector2((float)(sourceRect.Width / 2), (float)(sourceRect.Height / 2 + 1)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom + num, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, .99f); } @@ -667,7 +545,7 @@ namespace CustomNPCFramework.Framework.NPCS //Checks if the npc is glowing. if (this.isGlowing) - this.characterRenderer.draw(b,this, this.getLocalPosition(Game1.viewport) + new Vector2((float)(this.Sprite.SpriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), this.glowingColor * this.glowingTransparency, this.rotation, new Vector2((float)(this.Sprite.SpriteWidth / 2), (float)((double)this.Sprite.SpriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.Scale) * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.99f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); + this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + new Vector2((float)(this.Sprite.SpriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), this.glowingColor * this.glowingTransparency, this.rotation, new Vector2((float)(this.Sprite.SpriteWidth / 2), (float)((double)this.Sprite.SpriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.Scale) * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.99f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); //This code runs if the npc is emoting. if (!this.IsEmoting || Game1.eventUp) @@ -677,9 +555,7 @@ namespace CustomNPCFramework.Framework.NPCS b.Draw(Game1.emoteSpriteSheet, localPosition1, new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.CurrentEmoteIndex * 16 % Game1.emoteSpriteSheet.Width, this.CurrentEmoteIndex * 16 / Game1.emoteSpriteSheet.Width * 16, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, (float)this.getStandingY() / 10000f); } - /// - /// Used to draw the sprite without the modular npc renderer - /// + /// Used to draw the sprite without the modular npc renderer /// /// public virtual void drawNonModularSprite(SpriteBatch b, float alpha = 1f) @@ -728,9 +604,7 @@ namespace CustomNPCFramework.Framework.NPCS } - /// - /// Basic draw functionality to checkn whether or not to draw the npc using it's default sprite or using a custom character renderer. - /// + /// Basic draw functionality to checkn whether or not to draw the npc using it's default sprite or using a custom character renderer. /// /// public override void draw(SpriteBatch b, float alpha = 1f) diff --git a/GeneralMods/CustomNPCFramework/Framework/NPCS/MerchantNPC.cs b/GeneralMods/CustomNPCFramework/Framework/NPCS/MerchantNPC.cs index 457523cc..34433679 100644 --- a/GeneralMods/CustomNPCFramework/Framework/NPCS/MerchantNPC.cs +++ b/GeneralMods/CustomNPCFramework/Framework/NPCS/MerchantNPC.cs @@ -1,56 +1,41 @@ -using CustomNPCFramework.Framework.ModularNPCS; -using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers; +using System.Collections.Generic; +using CustomNPCFramework.Framework.ModularNpcs; +using CustomNPCFramework.Framework.ModularNpcs.ModularRenderers; using Microsoft.Xna.Framework; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace CustomNPCFramework.Framework.NPCS { - /// - /// Extended merchant npc from ExtendedNPC. - /// - class MerchantNPC: ExtendedNPC + /// Extended merchant npc from ExtendedNPC. + class MerchantNpc : ExtendedNpc { - /// - /// Thelist of items this npc has for sale. - /// + /// The list of items this npc has for sale. public List stock; - /// - /// Constructor. - /// + + /// Construct an instance. /// The list of items this npc will sell. /// The sprite for the npc to use. /// The renderer for the npc to use. /// The position for the npc to use. /// The facing direction for the player to face. /// The name for the npc. - public MerchantNPC(List Stock, Sprite sprite, BasicRenderer renderer,Vector2 position,int facingDirection,string name): base(sprite,renderer,position,facingDirection,name) + public MerchantNpc(List Stock, Sprite sprite, BasicRenderer renderer, Vector2 position, int facingDirection, string name) + : base(sprite, renderer, position, facingDirection, name) { this.stock = Stock; } - - /// - /// Constructor. - /// + /// Construct an instance. /// The list of items for the npc to sell. /// The npc base for the character to be expanded upon. - public MerchantNPC(List Stock, ExtendedNPC npcBase) : base(npcBase.spriteInformation, npcBase.characterRenderer, npcBase.portraitInformation, npcBase.position, npcBase.facingDirection, npcBase.Name) + public MerchantNpc(List Stock, ExtendedNpc npcBase) + : base(npcBase.spriteInformation, npcBase.characterRenderer, npcBase.portraitInformation, npcBase.position, npcBase.facingDirection, npcBase.Name) { this.stock = Stock; } - /// - /// Used to interact with the npc. When interacting pulls up a shop menu for the npc with their current stock. - /// - /// - /// - /// - public override bool checkAction(StardewValley.Farmer who, GameLocation l) + /// Used to interact with the npc. When interacting pulls up a shop menu for the npc with their current stock. + public override bool checkAction(Farmer who, GameLocation l) { if (Game1.activeClickableMenu == null) { diff --git a/GeneralMods/CustomNPCFramework/Framework/Utilities/NPCTracker.cs b/GeneralMods/CustomNPCFramework/Framework/Utilities/NPCTracker.cs index 4240bd0d..571aca1c 100644 --- a/GeneralMods/CustomNPCFramework/Framework/Utilities/NPCTracker.cs +++ b/GeneralMods/CustomNPCFramework/Framework/Utilities/NPCTracker.cs @@ -1,89 +1,64 @@ -using CustomNPCFramework.Framework.NPCS; +using System.Collections.Generic; +using CustomNPCFramework.Framework.NPCS; using Microsoft.Xna.Framework; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace CustomNPCFramework.Framework.Utilities { - /// - /// Used to keep track of all of the custom npcs. - /// - public class NPCTracker + /// Used to keep track of all of the custom npcs. + public class NpcTracker { - /// - /// A list used to keep track of the npcs. - /// - public List moddedNPCS; + /// A list used to keep track of the npcs. + public List moddedNpcs; - /// - /// Constructor. - /// - public NPCTracker() + /// Construct an instance. + public NpcTracker() { - this.moddedNPCS = new List(); + this.moddedNpcs = new List(); } - /// - /// Use this to add a new npc into the game. - /// + /// Use this to add a new npc into the game. /// The game location to add the npc to. /// The extended npc to add to the location. - public void addNewNPCToLocation(GameLocation loc,ExtendedNPC npc) + public void addNewNpcToLocation(GameLocation loc, ExtendedNpc npc) { - this.moddedNPCS.Add(npc); + this.moddedNpcs.Add(npc); npc.defaultLocation = loc; npc.currentLocation = loc; loc.addCharacter(npc); } - /// - /// Add a npc to a location. - /// + /// Add a npc to a location. /// The game location to add an npc to. /// The extended npc to add to the location. /// The tile position at the game location to add the mpc to. - public void addNewNPCToLocation(GameLocation loc, ExtendedNPC npc, Vector2 tilePosition) + public void addNewNpcToLocation(GameLocation loc, ExtendedNpc npc, Vector2 tilePosition) { - this.moddedNPCS.Add(npc); + this.moddedNpcs.Add(npc); npc.defaultLocation = loc; npc.currentLocation = loc; - npc.position.Value = tilePosition*Game1.tileSize; + npc.position.Value = tilePosition * Game1.tileSize; loc.addCharacter(npc); } - /// - /// Use this simply to remove a single npc from a location. - /// - /// - /// - public void removeCharacterFromLocation(GameLocation loc, ExtendedNPC npc) + /// Use this simply to remove a single npc from a location. + public void removeCharacterFromLocation(GameLocation loc, ExtendedNpc npc) { loc.characters.Remove(npc); } - - /// - /// Use this to completly remove and npc from the game as it is removed from the location and is no longer tracked. - /// + + /// Use this to completly remove and npc from the game as it is removed from the location and is no longer tracked. /// The npc to remove from the location. - public void removeFromLocationAndTrackingList(ExtendedNPC npc) + public void removeFromLocationAndTrackingList(ExtendedNpc npc) { - if (npc.currentLocation != null) - { - npc.currentLocation.characters.Remove(npc); - } - this.moddedNPCS.Remove(npc); + npc.currentLocation?.characters.Remove(npc); + this.moddedNpcs.Remove(npc); } - /// - /// Use this to clean up all of the npcs before the game is saved. - /// + /// Use this to clean up all of the npcs before the game is saved. public void cleanUpBeforeSave() { - foreach(ExtendedNPC npc in this.moddedNPCS) + foreach (ExtendedNpc npc in this.moddedNpcs) { //npc.currentLocation.characters.Remove(npc); //Game1.removeThisCharacterFromAllLocations(npc); @@ -91,19 +66,13 @@ namespace CustomNPCFramework.Framework.Utilities Class1.ModMonitor.Log("Removed an npc!"); //Do some saving code here. } - } - /// - /// Use this to load in all of the npcs again after saving. - /// + /// Use this to load in all of the npcs again after saving. public void afterSave() { - foreach(ExtendedNPC npc in this.moddedNPCS) - { + foreach (ExtendedNpc npc in this.moddedNpcs) npc.defaultLocation.addCharacter(npc); - } } - } } diff --git a/GeneralMods/CustomNPCFramework/manifest.json b/GeneralMods/CustomNPCFramework/manifest.json index 56346973..6b916b5b 100644 --- a/GeneralMods/CustomNPCFramework/manifest.json +++ b/GeneralMods/CustomNPCFramework/manifest.json @@ -1,10 +1,13 @@ { - "Name": "CustomNPCFramework", + "Name": "Custom NPC Framework", "Author": "Alpha_Omegasis", "Version": "0.1.0", - "Description": "A system to add custom npcs to Stardew.", + "Description": "A system to add custom NPCs to Stardew.", "UniqueID": "Omegasis.CustomNPCFramework", "EntryDll": "CustomNPCFramework.dll", - "MinimumApiVersion": "2.0", - "UpdateKeys": [ ] + "MinimumApiVersion": "2.10.1", + "UpdateKeys": [], + "Dependencies": [ + { "UniqueID": "Omegasis.StardustCore" } + ] } diff --git a/GeneralMods/CustomNPCFramework/packages.config b/GeneralMods/CustomNPCFramework/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/CustomNPCFramework/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/CustomObjectFramework/App.config b/GeneralMods/CustomObjectFramework/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/GeneralMods/CustomObjectFramework/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/GeneralMods/CustomObjectFramework/CustomObjectFramework.csproj b/GeneralMods/CustomObjectFramework/CustomObjectFramework.csproj new file mode 100644 index 00000000..9f4e4e1d --- /dev/null +++ b/GeneralMods/CustomObjectFramework/CustomObjectFramework.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {901B46C9-38B6-469F-BB2F-E1BE2B770FC0} + Exe + CustomObjectFramework + CustomObjectFramework + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GeneralMods/CustomObjectFramework/Program.cs b/GeneralMods/CustomObjectFramework/Program.cs new file mode 100644 index 00000000..2691193e --- /dev/null +++ b/GeneralMods/CustomObjectFramework/Program.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CustomObjectFramework +{ + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/GeneralMods/CustomObjectFramework/Properties/AssemblyInfo.cs b/GeneralMods/CustomObjectFramework/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..30da100b --- /dev/null +++ b/GeneralMods/CustomObjectFramework/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CustomObjectFramework")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CustomObjectFramework")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("901b46c9-38b6-469f-bb2f-e1be2b770fc0")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.cs b/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.cs index 0be9151e..058b9167 100644 --- a/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.cs +++ b/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.cs @@ -1,22 +1,21 @@ -using Omegasis.DailyQuestAnywhere.Framework; +using System; +using Omegasis.DailyQuestAnywhere.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using StardewValley.Menus; using StardewValley.Quests; -using System; namespace Omegasis.DailyQuestAnywhere { /* *TODO: Make quest core mod??? */ - /// The mod entry point. public class DailyQuestAnywhere : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -33,67 +32,69 @@ namespace Omegasis.DailyQuestAnywhere { this.Config = helper.ReadConfig(); - ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; - StardewModdingAPI.Events.SaveEvents.AfterSave += SaveEvents_AfterSave; + helper.Events.Input.ButtonPressed += this.OnButtonPressed; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; } - - /********* ** Private methods *********/ - /// The method invoked when the presses a keyboard button. + /// Raised after the player presses a button on the keyboard, controller, or mouse. /// The event sender. - /// The event data. - private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) + /// The event arguments. + private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { - if (Context.IsPlayerFree && e.KeyPressed.ToString() == this.Config.KeyBinding) - if (Game1.player.hasDailyQuest() == false ) + if (Context.IsPlayerFree && e.Button == this.Config.KeyBinding) + { + if (!Game1.player.hasDailyQuest()) { if (this.dailyQuest == null) - { - this.dailyQuest = generateDailyQuest(); - } + this.dailyQuest = this.generateDailyQuest(); Game1.questOfTheDay = this.dailyQuest; Game1.activeClickableMenu = new Billboard(true); - } + } + } } - /// - /// Makes my daily quest referene null so we can't just keep getting a new reference. - /// - /// - /// - private void SaveEvents_AfterSave(object sender, System.EventArgs e) + /// Raised after the player loads a save slot and the world is initialised. + /// The event sender. + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { - this.dailyQuest = null; //Nullify my quest reference. + // makes daily quest null so we can't just keep getting a new reference + this.dailyQuest = null; } - /// - /// Generate a daily quest for sure. - /// - /// + /// Generate a daily quest for sure. public Quest generateDailyQuest() { - Random chanceRandom = new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.DaysPlayed); int chance = chanceRandom.Next(0, 101); float actualChance = chance / 100; //If we hit the chance for actually generating a daily quest do so, otherwise don't generate a daily quest. - if (actualChance <= Config.chanceForDailyQuest) + if (actualChance <= this.Config.chanceForDailyQuest) { Random r = new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.DaysPlayed); int rand = r.Next(0, 7); - - if (rand == 0) return new ItemDeliveryQuest(); - if (rand == 1) return new FishingQuest(); - if (rand == 2) return new StardewValley.Quests.CraftingQuest(); - if (rand == 3) return new StardewValley.Quests.ItemDeliveryQuest(); - if (rand == 4) return new StardewValley.Quests.ItemHarvestQuest(); - if (rand == 5) return new StardewValley.Quests.ResourceCollectionQuest(); - if (rand == 6) return new StardewValley.Quests.SlayMonsterQuest(); + switch (rand) + { + case 0: + return new ItemDeliveryQuest(); + case 1: + return new FishingQuest(); + case 2: + return new CraftingQuest(); + case 3: + return new ItemDeliveryQuest(); + case 4: + return new ItemHarvestQuest(); + case 5: + return new ResourceCollectionQuest(); + case 6: + return new SlayMonsterQuest(); + } } return null; //This should never happen. } diff --git a/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.csproj b/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.csproj index 2d0790fc..13cf5c50 100644 --- a/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.csproj +++ b/GeneralMods/DailyQuestAnywhere/DailyQuestAnywhere.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ DailyQuestAnywhere v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -83,19 +84,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/DailyQuestAnywhere/Framework/ModConfig.cs b/GeneralMods/DailyQuestAnywhere/Framework/ModConfig.cs index a6f01664..9190d89f 100644 --- a/GeneralMods/DailyQuestAnywhere/Framework/ModConfig.cs +++ b/GeneralMods/DailyQuestAnywhere/Framework/ModConfig.cs @@ -1,14 +1,14 @@ -namespace Omegasis.DailyQuestAnywhere.Framework +using StardewModdingAPI; + +namespace Omegasis.DailyQuestAnywhere.Framework { /// The mod configuration. internal class ModConfig { /// The key which shows the menu. - public string KeyBinding { get; set; } = "H"; + public SButton KeyBinding { get; set; } = SButton.H; - /// - /// The chance for a daily quest to actually happen. - /// + /// The chance for a daily quest to actually happen. public float chanceForDailyQuest { get; set; } = .75f; } } diff --git a/GeneralMods/DailyQuestAnywhere/manifest.json b/GeneralMods/DailyQuestAnywhere/manifest.json index 1bc9f1fb..f573351b 100644 --- a/GeneralMods/DailyQuestAnywhere/manifest.json +++ b/GeneralMods/DailyQuestAnywhere/manifest.json @@ -1,10 +1,10 @@ { "Name": "Daily Quest Anywhere", "Author": "Alpha_Omegasis", - "Version": "1.5.0", + "Version": "1.6.0", "Description": "Open the daily quest board from anywhere in the game.", "UniqueID": "Omegasis.DailyQuestAnywhere", "EntryDll": "DailyQuestAnywhere.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:513" ] } diff --git a/GeneralMods/DailyQuestAnywhere/packages.config b/GeneralMods/DailyQuestAnywhere/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/DailyQuestAnywhere/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/Fall28SnowDay/Fall28SnowDay.cs b/GeneralMods/Fall28SnowDay/Fall28SnowDay.cs index 58d7f373..14b3e63a 100644 --- a/GeneralMods/Fall28SnowDay/Fall28SnowDay.cs +++ b/GeneralMods/Fall28SnowDay/Fall28SnowDay.cs @@ -1,4 +1,3 @@ -using System; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; @@ -15,17 +14,17 @@ namespace Omegasis.Fall28SnowDay /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { - SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; + helper.Events.GameLoop.Saving += this.OnSaving; } /********* ** Private methods *********/ - /// The method invoked just before the game saves. + /// Raised before the game begins writes data to the save file (except the initial save creation). /// The event sender. - /// The event data. - public void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + public void OnSaving(object sender, SavingEventArgs e) { if (Game1.IsFall && Game1.dayOfMonth == 27) Game1.weatherForTomorrow = Game1.weather_snow; diff --git a/GeneralMods/Fall28SnowDay/Fall28SnowDay.csproj b/GeneralMods/Fall28SnowDay/Fall28SnowDay.csproj index e0b9c753..23b5bc04 100644 --- a/GeneralMods/Fall28SnowDay/Fall28SnowDay.csproj +++ b/GeneralMods/Fall28SnowDay/Fall28SnowDay.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ Fall28SnowDay v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -82,19 +83,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/Fall28SnowDay/manifest.json b/GeneralMods/Fall28SnowDay/manifest.json index be64d502..35210825 100644 --- a/GeneralMods/Fall28SnowDay/manifest.json +++ b/GeneralMods/Fall28SnowDay/manifest.json @@ -1,10 +1,10 @@ { "Name": "Fall 28 Snow Day", "Author": "Alpha_Omegasis", - "Version": "1.5.0", + "Version": "1.6.0", "Description": "Makes it snow on Fall 28, which makes a good explanation for all the snow on the next day.", "UniqueID": "Omegasis.Fall28SnowDay", "EntryDll": "Fall28SnowDay.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:486" ] } diff --git a/GeneralMods/Fall28SnowDay/packages.config b/GeneralMods/Fall28SnowDay/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/Fall28SnowDay/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/FarmersMarketStall/Class1.cs b/GeneralMods/FarmersMarketStall/Class1.cs index 036a74a5..1c08ebd9 100644 --- a/GeneralMods/FarmersMarketStall/Class1.cs +++ b/GeneralMods/FarmersMarketStall/Class1.cs @@ -1,17 +1,13 @@ -using EventSystem.Framework.FunctionEvents; +using System; +using EventSystem.Framework.FunctionEvents; using FarmersMarketStall.Framework.MapEvents; using Microsoft.Xna.Framework; using StardewModdingAPI; +using StardewModdingAPI.Events; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FarmersMarketStall { - /// /// TODO: /// Make a farmers market menu @@ -21,32 +17,39 @@ namespace FarmersMarketStall /// Make a selling menu /// Make a minigame event for bonus money to earn. /// - /// - - public class Class1 :Mod + public class Class1 : Mod { - public static IModHelper ModHelper; public static IMonitor ModMonitor; - public static FarmersMarketStall.Framework.MarketStall marketStall; + public static Framework.MarketStall marketStall; + + /// The mod entry point, called after the mod is first loaded. + /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { - ModHelper = Helper; - ModMonitor = Monitor; + ModHelper = this.Helper; + ModMonitor = this.Monitor; - StardewModdingAPI.Events.SaveEvents.BeforeSave += SaveEvents_BeforeSave; - StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_AfterLoad; + helper.Events.GameLoop.Saving += this.OnSaving; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; marketStall = new Framework.MarketStall(); } - private void SaveEvents_AfterLoad(object sender, EventArgs e) + /// Raised after the player loads a save slot and the world is initialised. + /// The event sender. + /// The event arguments. + private void OnSaveLoaded(object sender, EventArgs e) { EventSystem.EventSystem.eventManager.addEvent(Game1.getLocationFromName("BusStop"), new ShopInteractionEvent("FarmersMarketStall", Game1.getLocationFromName("BusStop"), new Vector2(6, 11), new MouseButtonEvents(null, true), new MouseEntryLeaveEvent(null, null))); } - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// Raised before the game begins writes data to the save file (except the initial save creation). + /// The event sender. + /// The event arguments. + private void OnSaving(object sender, SavingEventArgs e) { - if (marketStall.stock.Count > 0) { + if (marketStall.stock.Count > 0) + { // Game1.endOfNightMenus.Push(new StardewValley.Menus.ShippingMenu(marketStall.stock)); marketStall.sellAllItems(); } diff --git a/GeneralMods/FarmersMarketStall/FarmersMarketStall.csproj b/GeneralMods/FarmersMarketStall/FarmersMarketStall.csproj index c2b0dbbc..d77edb4c 100644 --- a/GeneralMods/FarmersMarketStall/FarmersMarketStall.csproj +++ b/GeneralMods/FarmersMarketStall/FarmersMarketStall.csproj @@ -11,8 +11,6 @@ FarmersMarketStall v4.6.1 512 - - true @@ -68,9 +66,9 @@ MinimumRecommendedRules.ruleset - - ..\MapEvents\bin\Release\EventSystem.dll - + + + @@ -88,17 +86,13 @@ - + + {bb737337-2d82-4245-aa46-f3b82fc6f228} + EventSystem + - + - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/FarmersMarketStall/Framework/MapEvents/ShopInteractionEvent.cs b/GeneralMods/FarmersMarketStall/Framework/MapEvents/ShopInteractionEvent.cs index 25fbd4b1..7ee285b6 100644 --- a/GeneralMods/FarmersMarketStall/Framework/MapEvents/ShopInteractionEvent.cs +++ b/GeneralMods/FarmersMarketStall/Framework/MapEvents/ShopInteractionEvent.cs @@ -1,18 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using EventSystem; using EventSystem.Framework.FunctionEvents; using Microsoft.Xna.Framework; using StardewValley; namespace FarmersMarketStall.Framework.MapEvents { - public class ShopInteractionEvent :EventSystem.Framework.MapEvent + public class ShopInteractionEvent : EventSystem.Framework.MapEvent { - public ShopInteractionEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents, MouseEntryLeaveEvent EntryLeave) : base(Name, Location, Position) + public ShopInteractionEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents, MouseEntryLeaveEvent EntryLeave) + : base(Name, Location, Position) { this.name = Name; this.location = Location; @@ -24,18 +19,17 @@ namespace FarmersMarketStall.Framework.MapEvents this.mouseEntryLeaveEvents = EntryLeave; } - public override bool OnLeftClick() { - if (base.OnLeftClick() == false) return false; - if (this.location.isObjectAt((int)this.tilePosition.X * Game1.tileSize, (int)this.tilePosition.Y * Game1.tileSize)) return false; + if (!base.OnLeftClick()) + return false; + if (this.location.isObjectAt((int)this.tilePosition.X * Game1.tileSize, (int)this.tilePosition.Y * Game1.tileSize)) + return false; Game1.activeClickableMenu = Menus.MarketStallMenu.openMenu(Class1.marketStall); return true; } - /// - /// Used to update the event and check for interaction. - /// + /// Used to update the event and check for interaction. public override void update() { this.clickEvent(); @@ -43,6 +37,5 @@ namespace FarmersMarketStall.Framework.MapEvents this.OnMouseEnter(); this.OnMouseLeave(); } - } } diff --git a/GeneralMods/FarmersMarketStall/Framework/MarketStall.cs b/GeneralMods/FarmersMarketStall/Framework/MarketStall.cs index c043bcf6..5ae3c5e6 100644 --- a/GeneralMods/FarmersMarketStall/Framework/MarketStall.cs +++ b/GeneralMods/FarmersMarketStall/Framework/MarketStall.cs @@ -1,9 +1,5 @@ -using StardewValley; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley; namespace FarmersMarketStall.Framework { @@ -11,10 +7,7 @@ namespace FarmersMarketStall.Framework { public List stock; - public MarketStall() - { - - } + public MarketStall() { } public void addItemToSell(Item item) { @@ -28,12 +21,10 @@ namespace FarmersMarketStall.Framework public void sellAllItems() { - foreach(var item in stock) - { - Game1.player.money+=(int)(item.salePrice() * 1.10f); //Replace the multiplier with some sort of level. - } + foreach (var item in this.stock) + Game1.player.money += (int)(item.salePrice() * 1.10f); //Replace the multiplier with some sort of level. + this.stock.Clear(); } - } } diff --git a/GeneralMods/FarmersMarketStall/Framework/Menus/MarketStallMenu.cs b/GeneralMods/FarmersMarketStall/Framework/Menus/MarketStallMenu.cs index 466833db..47b8cecc 100644 --- a/GeneralMods/FarmersMarketStall/Framework/Menus/MarketStallMenu.cs +++ b/GeneralMods/FarmersMarketStall/Framework/Menus/MarketStallMenu.cs @@ -1,10 +1,5 @@ -using StardewValley; -using StardewValley.Menus; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley.Menus; namespace FarmersMarketStall.Framework.Menus { @@ -17,9 +12,8 @@ namespace FarmersMarketStall.Framework.Menus public static IClickableMenu openMenu(MarketStall marketStall) { - throw new NotImplementedException("This menu isn't implemented because the author is busy/lazy. Please encorage Omegasis to finish it!",null); + throw new NotImplementedException("This menu isn't implemented because the author is busy/lazy. Please encorage Omegasis to finish it!", null); //return new StardewValley.Menus.InventoryMenu((int)(Game1.viewport.Width*.25f),(int)(Game1.viewport.Height*.25f),true,marketStall.stock); } - } } diff --git a/GeneralMods/FarmersMarketStall/manifest.json b/GeneralMods/FarmersMarketStall/manifest.json index c6ed000c..be2231a3 100644 --- a/GeneralMods/FarmersMarketStall/manifest.json +++ b/GeneralMods/FarmersMarketStall/manifest.json @@ -1,16 +1,13 @@ { - "Name": "FarmersMarketStall", + "Name": "Farmers Market Stall", "Author": "Alpha_Omegasis", "Version": "0.1.0", "Description": "A system to add a farmers market stall to Sundrop.", "UniqueID": "SunDrop.SunDropMapEvents.FarmersMarketStall", "EntryDll": "FarmersMarketStall.dll", - "MinimumApiVersion": "2.0", - "UpdateKeys": [ ], + "MinimumApiVersion": "2.10.1", + "UpdateKeys": [], "Dependencies": [ - { - "UniqueID": "Omegasis.EventSystem", - "IsRequired": true - } -] + { "UniqueID": "Omegasis.EventSystem" } + ] } diff --git a/GeneralMods/HappyBirthday/BirthdayEvents.cs b/GeneralMods/HappyBirthday/BirthdayEvents.cs index 1d71cd3d..8da384ae 100644 --- a/GeneralMods/HappyBirthday/BirthdayEvents.cs +++ b/GeneralMods/HappyBirthday/BirthdayEvents.cs @@ -1,16 +1,9 @@ -using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley; namespace Omegasis.HappyBirthday { - /// - /// TODO:Make all the events - /// Resources:https://stardewvalleywiki.com/Modding:Event_data - /// + // TODO: Make all the events + // Resources:https://stardewvalleywiki.com/Modding:Event_data public class BirthdayEvents { public Event communityCenterJunimoEvent; @@ -21,7 +14,7 @@ namespace Omegasis.HappyBirthday public BirthdayEvents() { - initializeEvents(); + this.initializeEvents(); } public void initializeEvents() @@ -29,7 +22,5 @@ namespace Omegasis.HappyBirthday Event e = new Event("", -1, Game1.player); Game1.player.currentLocation.currentEvent = new Event(); } - - } } diff --git a/GeneralMods/HappyBirthday/BirthdayMessages.cs b/GeneralMods/HappyBirthday/BirthdayMessages.cs index 67dfe5ba..149d522c 100644 --- a/GeneralMods/HappyBirthday/BirthdayMessages.cs +++ b/GeneralMods/HappyBirthday/BirthdayMessages.cs @@ -1,25 +1,16 @@ -using Newtonsoft.Json; -using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Newtonsoft.Json; namespace Omegasis.HappyBirthday { public class BirthdayMessages { - /// - /// The actual birthday wishes given by an npc. - /// + /// The actual birthday wishes given by an npc. public Dictionary birthdayWishes; public Dictionary spouseBirthdayWishes; - /// - /// TODO: Make this. - /// public Dictionary defaultSpouseBirthdayWishes = new Dictionary() { ["Alex"] = "", @@ -36,9 +27,7 @@ namespace Omegasis.HappyBirthday ["Penny"] = "", }; - /// - /// Used to contain - /// + /// Used to contain birthday wishes should the mod not find any available. public Dictionary defaultBirthdayWishes = new Dictionary() { ["Robin"] = "Hey @, happy birthday! I'm glad you choose this town to move here to. ", @@ -76,12 +65,79 @@ namespace Omegasis.HappyBirthday ["Krobus"] = "I have heard that it is tradition to give a gift to others on their birthday. In that case, happy birthday @." }; - /// - /// Used to load all of the default birthday greetings. - /// + public BirthdayMessages() + { + createBirthdayGreetings(); + loadTranslationStrings(); + } + + + public Dictionary> translatedStrings = new Dictionary>() + { + [StardewValley.LocalizedContentManager.LanguageCode.de] = new Dictionary() + { + ["Mail:birthdayMom"] = "", + ["Mail:birthdayDad"] = "", + ["Happy Birthday: Star Message"] = "", + ["Happy Birthday: Farmhand Birthday Message"] = "" + }, + [StardewValley.LocalizedContentManager.LanguageCode.en] = new Dictionary() + { + ["Mail:birthdayMom"] = "Dear @,^ Happy birthday sweetheart. It's been amazing watching you grow into the kind, hard working person that I've always dreamed that you would become. I hope you continue to make many more fond memories with the ones you love. ^ Love, Mom ^ P.S. Here's a little something that I made for you. %item object 221 1 %%", + ["Mail:birthdayDad"] = "Dear @,^ Happy birthday kiddo. It's been a little quiet around here on your birthday since you aren't around, but your mother and I know that you are making both your grandpa and us proud. We both know that living on your own can be tough but we believe in you one hundred percent, just keep following your dreams.^ Love, Dad ^ P.S. Here's some spending money to help you out on the farm. Good luck! %item money 5000 5001 %%", + ["Happy Birthday: Star Message"] = "It's your birthday today! Happy birthday!", + ["Happy Birthday: Farmhand Birthday Message"] = "It's @'s birthday! Happy birthday to them!" + }, + [StardewValley.LocalizedContentManager.LanguageCode.es] = new Dictionary() + { + ["Mail:birthdayMom"] = "", + ["Mail:birthdayDad"] = "", + ["Happy Birthday: Star Message"] = "", + ["Happy Birthday: Farmhand Birthday Message"] = "" + }, + [StardewValley.LocalizedContentManager.LanguageCode.ja] = new Dictionary() + { + ["Mail:birthdayMom"] = "", + ["Mail:birthdayDad"] = "", + ["Happy Birthday: Star Message"] = "", + ["Happy Birthday: Farmhand Birthday Message"] = "" + }, + [StardewValley.LocalizedContentManager.LanguageCode.pt] = new Dictionary() + { + ["Mail:birthdayMom"] = "", + ["Mail:birthdayDad"] = "", + ["Happy Birthday: Star Message"] = "", + ["Happy Birthday: Farmhand Birthday Message"] = "" + }, + [StardewValley.LocalizedContentManager.LanguageCode.ru] = new Dictionary() + { + ["Mail:birthdayMom"] = "", + ["Mail:birthdayDad"] = "", + ["Happy Birthday: Star Message"] = "", + ["Happy Birthday: Farmhand Birthday Message"] = "" + }, + [StardewValley.LocalizedContentManager.LanguageCode.th] = new Dictionary() + { + ["Mail:birthdayMom"] = "", + ["Mail:birthdayDad"] = "", + ["Happy Birthday: Star Message"] = "", + ["Happy Birthday: Farmhand Birthday Message"] = "" + }, + [StardewValley.LocalizedContentManager.LanguageCode.zh] = new Dictionary() + { + ["Mail:birthdayMom"] = "亲爱的@,^ 生日快乐宝贝。看着你成长成为一个善良努力的人,就如我一直梦想着你成为的样子,我感到十分欣喜。我希望你能继续跟你爱的人制造更多美好的回忆。 ^ 爱你的,妈妈 ^ 附言:这是我给你做的一点小礼物。 %item object 221 1 %%", + ["Mail:birthdayDad"] = "亲爱的@,^ 生日快乐孩子。你生日的这天没有你,我们这儿还挺寂寞的,但我和你妈妈都知道你让我们和你爷爷感到骄傲。我们知道你一个人生活可能会很艰难,但我们百分百相信你能做到,所以继续追求你的梦想吧。^ 爱你的,爸爸 ^ 附言:这是能在农场上帮到你的一些零用钱。祝你好运! %item money 5000 5001 %%", + ["Happy Birthday: Star Message"] = "今天是你的生日!生日快乐!", + ["Happy Birthday: Farmhand Birthday Message"] = "" + } + }; + + + + + /// Used to load all of the default birthday greetings. public void createBirthdayGreetings() { - var serializer = JsonSerializer.Create(); serializer.Formatting = Formatting.Indented; @@ -89,75 +145,64 @@ namespace Omegasis.HappyBirthday string defaultPath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath, "Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation); if (!Directory.Exists(defaultPath)) Directory.CreateDirectory(defaultPath); - string birthdayFileDict=HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation); - string path = Path.Combine( "Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, birthdayFileDict); + string birthdayFileDict = HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation); + string path = Path.Combine("Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, birthdayFileDict); //Handle normal birthday wishes. - if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath,path))) + if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, path))) { - - HappyBirthday.ModHelper.Data.WriteJsonFile>(path, defaultBirthdayWishes); - this.birthdayWishes = defaultBirthdayWishes; + HappyBirthday.ModMonitor.Log("Creating Villager Birthday Messages", StardewModdingAPI.LogLevel.Alert); + HappyBirthday.ModHelper.Data.WriteJsonFile>(path, this.defaultBirthdayWishes); + this.birthdayWishes = this.defaultBirthdayWishes; } else - { - birthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile>(path); - } + this.birthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile>(path); //handle spouse birthday wishes. string spouseBirthdayFileDict = HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation); string spousePath = Path.Combine("Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, spouseBirthdayFileDict); - if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath,spousePath))) + if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, spousePath))) { HappyBirthday.ModMonitor.Log("Creating Spouse Messages", StardewModdingAPI.LogLevel.Alert); - HappyBirthday.ModHelper.Data.WriteJsonFile>(spousePath, defaultSpouseBirthdayWishes); - this.spouseBirthdayWishes = defaultSpouseBirthdayWishes; + HappyBirthday.ModHelper.Data.WriteJsonFile>(spousePath, this.defaultSpouseBirthdayWishes); + this.spouseBirthdayWishes = this.defaultSpouseBirthdayWishes; } else - { - spouseBirthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile>(spousePath); - } + this.spouseBirthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile>(spousePath); //Non-english logic for creating templates. - foreach(var translation in HappyBirthday.Config.translationInfo.translationCodes) + foreach (var translation in HappyBirthday.Config.translationInfo.translationCodes) { - if (translation.Key == "English") continue; - string basePath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath,"Content", "Dialogue", translation.Key); - if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath); - string tempBirthdayFile =Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", translation.Key)); - string tempSpouseBirthdayFile =Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", translation.Key)); + if (translation.Key == "English") + continue; + + string basePath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath, "Content", "Dialogue", translation.Key); + if (!Directory.Exists(basePath)) + Directory.CreateDirectory(basePath); + string tempBirthdayFile = Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", translation.Key)); + string tempSpouseBirthdayFile = Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", translation.Key)); Dictionary tempBirthdayDict = new Dictionary(); if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, tempBirthdayFile))) { - - foreach (var pair in defaultBirthdayWishes) - { + foreach (var pair in this.defaultBirthdayWishes) tempBirthdayDict.Add(pair.Key, ""); - } HappyBirthday.ModHelper.Data.WriteJsonFile>(tempBirthdayFile, tempBirthdayDict); } else - { tempBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile>(tempBirthdayFile); - } Dictionary tempSpouseBirthdayDict = new Dictionary(); if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, tempSpouseBirthdayFile))) { - - foreach (var pair in defaultSpouseBirthdayWishes) - { + foreach (var pair in this.defaultSpouseBirthdayWishes) tempSpouseBirthdayDict.Add(pair.Key, ""); - } HappyBirthday.ModHelper.Data.WriteJsonFile>(tempSpouseBirthdayFile, tempSpouseBirthdayDict); } else - { - tempBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile>(tempSpouseBirthdayFile); - } + tempSpouseBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile>(tempSpouseBirthdayFile); //Set translated birthday info. if (HappyBirthday.Config.translationInfo.currentTranslation == translation.Key) @@ -166,10 +211,50 @@ namespace Omegasis.HappyBirthday this.spouseBirthdayWishes = tempSpouseBirthdayDict; HappyBirthday.ModMonitor.Log("Language set to: " + translation); } + } + } + + public static string GetTranslatedString(string key) + { + StardewValley.LocalizedContentManager.LanguageCode code = HappyBirthday.Config.translationInfo.translationCodes[HappyBirthday.Config.translationInfo.currentTranslation]; + string value= HappyBirthday.Instance.messages.translatedStrings[code][key]; + if (string.IsNullOrEmpty(value)) + { + return GetEnglishMessageString(key); + } + else return value; + } + + public static string GetEnglishMessageString(string key) + { + StardewValley.LocalizedContentManager.LanguageCode code = StardewValley.LocalizedContentManager.LanguageCode.en; + return HappyBirthday.Instance.messages.translatedStrings[code][key]; + } + + public void loadTranslationStrings() + { + + //Non-english logic for creating templates. + foreach (var translation in HappyBirthday.Config.translationInfo.translationCodes) + { + + StardewValley.LocalizedContentManager.LanguageCode code = translation.Value; + + string basePath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath, "Content", "Dialogue", translation.Key); + if (!Directory.Exists(basePath)) + Directory.CreateDirectory(basePath); + string stringsFile = Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("TranslatedStrings", translation.Key)); + + + if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, stringsFile))) + { + HappyBirthday.ModHelper.Data.WriteJsonFile>(stringsFile, this.translatedStrings[code]); + } + else + this.translatedStrings[code] = HappyBirthday.ModHelper.Data.ReadJsonFile>(stringsFile); } } - } } diff --git a/GeneralMods/HappyBirthday/Changelog.txt b/GeneralMods/HappyBirthday/Changelog.txt index 0ce95022..e4b23240 100644 --- a/GeneralMods/HappyBirthday/Changelog.txt +++ b/GeneralMods/HappyBirthday/Changelog.txt @@ -1,26 +1,27 @@ Happy Birthday Change Log ~~~~~~~~~~~~~~~~ -1.8.0 Changelog +Manifest 1.8.0 Changelog ~~~~~~~~~~~~~~~~ -General Changes +General Changes + -NPCs now wish you a happy birthday if you have 2+ hearts with them. (Configurable in config file) + -A language can be set for birthday messages in the Config.json file. -Added support for birthday messages to be in .json files for easier editing. -Added support for birthday messages to be in multiple supported languages - -English - -Spanish - -German - -Chinese - -Japanese - -Brazillian Portuguese - -Added in spouse specific birthday dialogue messages which can be selected by the players. - -Added in multiple langages for spouse birthday messages. + -English + -Spanish + -German + -Chinese + -Japanese + -Brazilian Portuguese + -Added in spouse specific birthday dialogue messages which can be created by the players. + -Added in multiple languages for spouse birthday messages. -Added in birthday gifts to be in .json files. -Added in a new pool of spouse specific gifts that can be set by the player located in SpouseBirthdayGifts.json -Added in support for loading legacy birthday gift.xnb info from StardewValley/Content/Data/PossibleBirthdayGifts.xnb -Added in support for loading legacy birthday messages from StardewValley/Content/Data/BirthdayMessages.xnb -Added in player portraits to be shown on the callendar. - Multiplayer changes: - -Added in multiplayer portraits to be shown on the callendar. + -Added in multiplayer farmhand portraits to be shown on the callendar. -Added in a hud message that displays when another player has a birthday. \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/BirthdayWishes.pt-BR.json b/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/BirthdayWishes.pt-BR.json new file mode 100644 index 00000000..45c6c1b2 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/BirthdayWishes.pt-BR.json @@ -0,0 +1,35 @@ +{ + "Robin": "", + "Demetrius": "", + "Maru": "", + "Sebastian": "", + "Linus": "", + "Pierre": "", + "Caroline": "", + "Abigail": "", + "Alex": "", + "George": "", + "Evelyn": "", + "Lewis": "", + "Clint": "", + "Penny": "", + "Pam": "", + "Emily": "", + "Haley": "", + "Jas": "", + "Vincent": "", + "Jodi": "", + "Kent": "", + "Sam": "", + "Leah": "", + "Shane": "", + "Marnie": "", + "Elliott": "", + "Gus": "", + "Dwarf": "", + "Wizard": "", + "Harvey": "", + "Sandy": "", + "Willy": "", + "Krobus": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/SpouseBirthdayWishes.pt-BR.json b/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/SpouseBirthdayWishes.pt-BR.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/SpouseBirthdayWishes.pt-BR.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/TranslatedStrings.pt-BR.json b/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/TranslatedStrings.pt-BR.json new file mode 100644 index 00000000..b1aa5c2e --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Brazillian Portuguese/TranslatedStrings.pt-BR.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "", + "Mail:birthdayDad": "", + "Happy Birthday: Star Message": "", + "Happy Birthday: Farmhand Birthday Message": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/BirthdayWishes.zh-CN.json b/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/BirthdayWishes.zh-CN.json new file mode 100644 index 00000000..e566f0e4 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/BirthdayWishes.zh-CN.json @@ -0,0 +1,35 @@ +{ + "Robin": "嘿,@,生日快乐!我很高兴你选择搬到这里来。", + "Demetrius": "生日快乐@!记得偶尔要抽出时间来好好享受一下。$h", + "Maru": "生日快乐@。我本来想给我做个永恒不灭的蜡烛,但是好像行不通。也许明年再给你吧?$h", + "Sebastian": "生日快乐@。又是平静的一年。", + "Linus": "生日快乐@。谢谢你在你生日的这天依旧来看我。这让我很开心。", + "Pierre": "嘿@,生日快乐!希望你的下一年会更好!", + "Caroline": "生日快乐@。谢谢你为这个社区做的一切。我相信你的父母一定都很为你骄傲。$h", + "Abigail": "生日快乐@!希望之后的一年我们可以一起去更多的地方冒险!$h", + "Alex": "哟@,生日快乐!也许这会是你有生以来最棒的一年。$h", + "George": "等你到我的年纪,生日就像其他的日子一样来去匆匆。不过还是祝你生日快乐,@。", + "Evelyn": "生日快乐@。你成长成为了一个优秀的人,我相信你还会继续成长的。", + "Lewis": "生日快乐@!我很感激你为这个小镇做的一切,我相信你爷爷也会为你骄傲的。", + "Clint": "嘿生日快乐@。我相信接下来对你来说会是很棒的一年。", + "Penny": "生日快乐@。希望你这一年都能得到所有的祝福。", + "Pam": "生日快乐孩子。我们应该一起去喝一杯,庆祝你生命的又一年。", + "Emily": "我今天感受到了很多关于你的正能量,所以一定是你的生日到了。生日快乐@!$h", + "Haley": "生日快乐@。希望你今年能收到些很棒的礼物!$h", + "Jas": "生日快乐@。希望你过个愉快的生日。", + "Vincent": "嘿@,你是来玩的……哦今天是你的生日?生日快乐!", + "Jodi": "你好啊@。听说今天是你的生日。既然如此,祝你生日快乐!$h", + "Kent": "乔迪告诉我今天是你的生日,@。生日快乐,记得要珍惜每一天。", + "Sam": "哟@,生日快乐!有机会我们来给你办个生日派对吧!$h", + "Leah": "嘿@,生日快乐!我们今晚去酒吧庆祝一下吧!$h", + "Shane": "生日快乐@。继续努力工作,我相信你接下来的这一年会更好。", + "Marnie": "你好@。今天大家都在谈论你的生日,我也想跟你说一声生日快乐,那么,生日快乐!$h", + "Elliott": "真是美好的一天不是吗,@?尤其今天是你的生日。我本想给你写一首诗,但我觉得简单的才是最好的,生日快乐。$h", + "Gus": "嘿@,生日快乐!希望你今天过得愉快,酒吧永远都欢迎你!", + "Dwarf": "生日快乐@。我希望我给你的东西是人类可以接受的。", + "Wizard": "有精灵告诉我今天是你的生日。这么说,生日快乐@。希望你下一年辉煌灿烂!", + "Harvey": "嘿@,生日快乐!有空记得到我这来做检查,这能让你多活很多年!", + "Sandy": "你好啊@。我听说今天是你的生日,我可不想让你觉得被冷落了。生日快乐!", + "Willy": "哎@,生日快乐。看到你让我想起了我曾经一个人漂在海上的日子。继续享受青春吧年轻人。$h", + "Krobus": "我听说在别人生日的时候送一份礼物是传统。那么,生日快乐@。" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/SpouseBirthdayWishes.zh-CN.json b/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/SpouseBirthdayWishes.zh-CN.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/SpouseBirthdayWishes.zh-CN.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/TranslatedStrings.zh-CN.json b/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/TranslatedStrings.zh-CN.json new file mode 100644 index 00000000..c3215da2 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Chinese/TranslatedStrings.zh-CN.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "亲爱的@,^ 生日快乐宝贝。看着你成长成为一个善良努力的人,就如我一直梦想着你成为的样子,我感到十分欣喜。我希望你能继续跟你爱的人制造更多美好的回忆。 ^ 爱你的,妈妈 ^ 附言:这是我给你做的一点小礼物。 %item object 221 1 %%", + "Mail:birthdayDad": "亲爱的@,^ 生日快乐孩子。你生日的这天没有你,我们这儿还挺寂寞的,但我和你妈妈都知道你让我们和你爷爷感到骄傲。我们知道你一个人生活可能会很艰难,但我们百分百相信你能做到,所以继续追求你的梦想吧。^ 爱你的,爸爸 ^ 附言:这是能在农场上帮到你的一些零用钱。祝你好运! %item money 5000 5001 %%", + "Happy Birthday: Star Message": "今天是你的生日!生日快乐!", + "Happy Birthday: Farmhand Birthday Message": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/English/BirthdayWishes.json b/GeneralMods/HappyBirthday/Content/Dialogue/English/BirthdayWishes.json new file mode 100644 index 00000000..bc441d22 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/English/BirthdayWishes.json @@ -0,0 +1,35 @@ +{ + "Robin": "Hey @, happy birthday! I'm glad you choose this town to move here to. ", + "Demetrius": "Happy birthday @! Make sure you take some time off today to enjoy yourself. $h", + "Maru": "Happy birthday @. I tried to make you an everlasting candle for you, but sadly that didn't work out. Maybe next year right? $h", + "Sebastian": "Happy birthday @. Here's to another year of chilling. ", + "Linus": "Happy birthday @. Thanks for visiting me even on your birthday. It makes me really happy. ", + "Pierre": "Hey @, happy birthday! Hopefully this next year for you will be a great one! ", + "Caroline": "Happy birthday @. Thank you for all that you've done for our community. I'm sure your parents must be proud of you.$h", + "Abigail": "Happy birthday @! Hopefully this year we can go on even more adventures together $h!", + "Alex": "Yo @, happy birthday! Maybe this will be your best year yet.$h", + "George": "When you get to my age birthdays come and go. Still happy birthday @.", + "Evelyn": "Happy birthday @. You have grown up to be such a fine individual and I'm sure you'll continue to grow. ", + "Lewis": "Happy birthday @! I'm thankful for what you have done for the town and I'm sure your grandfather would be proud of you.", + "Clint": "Hey happy birthday @. I'm sure this year is going to be great for you.", + "Penny": "Happy birthday @. May you enjoy all of life's blessings this year. ", + "Pam": "Happy birthday kid. We should have a drink to celebrate another year of life for you! $h", + "Emily": "I'm sensing a strong positive life energy about you, so it must be your birthday. Happy birthday @!$h", + "Haley": "Happy birthday @. Hopefully this year you'll get some good presents!$h", + "Jas": "Happy birthday @. I hope you have a good birthday.", + "Vincent": "Hey @ have you come to pl...oh it's your birthday? Happy birthday! ", + "Jodi": "Hello there @. Rumor has it that today is your birthday. In that case, happy birthday!$h", + "Kent": "Jodi told me that it was your birthday today @. Happy birthday and make sure to cherish every single day.", + "Sam": "Yo @ happy birthday! We'll have to have a birthday jam session for you some time!$h ", + "Leah": "Hey @ happy birthday! We should go to the saloon tonight and celebrate!$h ", + "Shane": "Happy birthday @. Keep working hard and I'm sure this next year for you will be a great one.", + "Marnie": "Hello there @. Everyone is talking about your birthday today and I wanted to make sure that I wished you a happy birthday as well, so happy birthday! $h ", + "Elliott": "What a wonderful day isn't it @? Especially since today is your birthday. I tried to make you a poem but I feel like the best way of putting it is simply, happy birthday. $h ", + "Gus": "Hey @ happy birthday! Hopefully you enjoy the rest of the day and make sure you aren't a stranger at the saloon!", + "Dwarf": "Happy birthday @. I hope that what I got you is acceptable for humans as well. ", + "Wizard": "The spirits told me that today is your birthday. In that case happy birthday @. May your year shine bright! ", + "Harvey": "Hey @, happy birthday! Make sure to come in for a checkup some time to make sure you live many more years! ", + "Sandy": "Hello there @. I heard that today was your birthday and I didn't want you feeling left out, so happy birthday!", + "Willy": "Aye @ happy birthday. Looking at you reminds me of ye days when I was just a guppy swimming out to sea. Continue to enjoy them youngin.$h", + "Krobus": "I have heard that it is tradition to give a gift to others on their birthday. In that case, happy birthday @." +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/English/SpouseBirthdayWishes.json b/GeneralMods/HappyBirthday/Content/Dialogue/English/SpouseBirthdayWishes.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/English/SpouseBirthdayWishes.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/English/TranslatedStrings.json b/GeneralMods/HappyBirthday/Content/Dialogue/English/TranslatedStrings.json new file mode 100644 index 00000000..03e0814b --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/English/TranslatedStrings.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "Dear @,^ Happy birthday sweetheart. It's been amazing watching you grow into the kind, hard working person that I've always dreamed that you would become. I hope you continue to make many more fond memories with the ones you love. ^ Love, Mom ^ P.S. Here's a little something that I made for you. %item object 221 1 %%", + "Mail:birthdayDad": "Dear @,^ Happy birthday kiddo. It's been a little quiet around here on your birthday since you aren't around, but your mother and I know that you are making both your grandpa and us proud. We both know that living on your own can be tough but we believe in you one hundred percent, just keep following your dreams.^ Love, Dad ^ P.S. Here's some spending money to help you out on the farm. Good luck! %item money 5000 5001 %%", + "Happy Birthday: Star Message": "It's your birthday today! Happy birthday!", + "Happy Birthday: Farmhand Birthday Message": "It's @'s birthday! Happy birthday to them!" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/German/BirthdayWishes.de-DE.json b/GeneralMods/HappyBirthday/Content/Dialogue/German/BirthdayWishes.de-DE.json new file mode 100644 index 00000000..45c6c1b2 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/German/BirthdayWishes.de-DE.json @@ -0,0 +1,35 @@ +{ + "Robin": "", + "Demetrius": "", + "Maru": "", + "Sebastian": "", + "Linus": "", + "Pierre": "", + "Caroline": "", + "Abigail": "", + "Alex": "", + "George": "", + "Evelyn": "", + "Lewis": "", + "Clint": "", + "Penny": "", + "Pam": "", + "Emily": "", + "Haley": "", + "Jas": "", + "Vincent": "", + "Jodi": "", + "Kent": "", + "Sam": "", + "Leah": "", + "Shane": "", + "Marnie": "", + "Elliott": "", + "Gus": "", + "Dwarf": "", + "Wizard": "", + "Harvey": "", + "Sandy": "", + "Willy": "", + "Krobus": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/German/SpouseBirthdayWishes.de-DE.json b/GeneralMods/HappyBirthday/Content/Dialogue/German/SpouseBirthdayWishes.de-DE.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/German/SpouseBirthdayWishes.de-DE.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/German/TranslatedStrings.de-DE.json b/GeneralMods/HappyBirthday/Content/Dialogue/German/TranslatedStrings.de-DE.json new file mode 100644 index 00000000..b1aa5c2e --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/German/TranslatedStrings.de-DE.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "", + "Mail:birthdayDad": "", + "Happy Birthday: Star Message": "", + "Happy Birthday: Farmhand Birthday Message": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/BirthdayWishes.ja-JP.json b/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/BirthdayWishes.ja-JP.json new file mode 100644 index 00000000..45c6c1b2 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/BirthdayWishes.ja-JP.json @@ -0,0 +1,35 @@ +{ + "Robin": "", + "Demetrius": "", + "Maru": "", + "Sebastian": "", + "Linus": "", + "Pierre": "", + "Caroline": "", + "Abigail": "", + "Alex": "", + "George": "", + "Evelyn": "", + "Lewis": "", + "Clint": "", + "Penny": "", + "Pam": "", + "Emily": "", + "Haley": "", + "Jas": "", + "Vincent": "", + "Jodi": "", + "Kent": "", + "Sam": "", + "Leah": "", + "Shane": "", + "Marnie": "", + "Elliott": "", + "Gus": "", + "Dwarf": "", + "Wizard": "", + "Harvey": "", + "Sandy": "", + "Willy": "", + "Krobus": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/SpouseBirthdayWishes.ja-JP.json b/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/SpouseBirthdayWishes.ja-JP.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/SpouseBirthdayWishes.ja-JP.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/TranslatedStrings.ja-JP.json b/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/TranslatedStrings.ja-JP.json new file mode 100644 index 00000000..b1aa5c2e --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Japanese/TranslatedStrings.ja-JP.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "", + "Mail:birthdayDad": "", + "Happy Birthday: Star Message": "", + "Happy Birthday: Farmhand Birthday Message": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Russian/BirthdayWishes.ru-RU.json b/GeneralMods/HappyBirthday/Content/Dialogue/Russian/BirthdayWishes.ru-RU.json new file mode 100644 index 00000000..45c6c1b2 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Russian/BirthdayWishes.ru-RU.json @@ -0,0 +1,35 @@ +{ + "Robin": "", + "Demetrius": "", + "Maru": "", + "Sebastian": "", + "Linus": "", + "Pierre": "", + "Caroline": "", + "Abigail": "", + "Alex": "", + "George": "", + "Evelyn": "", + "Lewis": "", + "Clint": "", + "Penny": "", + "Pam": "", + "Emily": "", + "Haley": "", + "Jas": "", + "Vincent": "", + "Jodi": "", + "Kent": "", + "Sam": "", + "Leah": "", + "Shane": "", + "Marnie": "", + "Elliott": "", + "Gus": "", + "Dwarf": "", + "Wizard": "", + "Harvey": "", + "Sandy": "", + "Willy": "", + "Krobus": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Russian/SpouseBirthdayWishes.ru-RU.json b/GeneralMods/HappyBirthday/Content/Dialogue/Russian/SpouseBirthdayWishes.ru-RU.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Russian/SpouseBirthdayWishes.ru-RU.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Russian/TranslatedStrings.ru-RU.json b/GeneralMods/HappyBirthday/Content/Dialogue/Russian/TranslatedStrings.ru-RU.json new file mode 100644 index 00000000..b1aa5c2e --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Russian/TranslatedStrings.ru-RU.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "", + "Mail:birthdayDad": "", + "Happy Birthday: Star Message": "", + "Happy Birthday: Farmhand Birthday Message": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/BirthdayWishes.es-ES.json b/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/BirthdayWishes.es-ES.json new file mode 100644 index 00000000..45c6c1b2 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/BirthdayWishes.es-ES.json @@ -0,0 +1,35 @@ +{ + "Robin": "", + "Demetrius": "", + "Maru": "", + "Sebastian": "", + "Linus": "", + "Pierre": "", + "Caroline": "", + "Abigail": "", + "Alex": "", + "George": "", + "Evelyn": "", + "Lewis": "", + "Clint": "", + "Penny": "", + "Pam": "", + "Emily": "", + "Haley": "", + "Jas": "", + "Vincent": "", + "Jodi": "", + "Kent": "", + "Sam": "", + "Leah": "", + "Shane": "", + "Marnie": "", + "Elliott": "", + "Gus": "", + "Dwarf": "", + "Wizard": "", + "Harvey": "", + "Sandy": "", + "Willy": "", + "Krobus": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/SpouseBirthdayWishes.es-ES.json b/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/SpouseBirthdayWishes.es-ES.json new file mode 100644 index 00000000..91388dd7 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/SpouseBirthdayWishes.es-ES.json @@ -0,0 +1,14 @@ +{ + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/TranslatedStrings.es-ES.json b/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/TranslatedStrings.es-ES.json new file mode 100644 index 00000000..b1aa5c2e --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Dialogue/Spanish/TranslatedStrings.es-ES.json @@ -0,0 +1,6 @@ +{ + "Mail:birthdayMom": "", + "Mail:birthdayDad": "", + "Happy Birthday: Star Message": "", + "Happy Birthday: Farmhand Birthday Message": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Gifts/BirthdayGifts.json b/GeneralMods/HappyBirthday/Content/Gifts/BirthdayGifts.json new file mode 100644 index 00000000..5a6f0e1d --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Gifts/BirthdayGifts.json @@ -0,0 +1,38 @@ +{ + "Universal_Love_Gift": "74 1 446 1 204 1 446 5 773 1", + "Universal_Like_Gift": "-2 3 -7 1 -26 2 -75 5 -80 3 72 1 220 1 221 1 395 1 613 1 634 1 635 1 636 1 637 1 638 1 724 1 233 1 223 1 465 20 -79 5", + "Universal_Neutral_Gift": "194 1 262 5 -74 5 -75 3 334 5 335 1 390 20 388 20 -81 5 -79 3", + "Robin": " BestGifts/224 1 426 1 636 1/GoodGift/-6 5 -79 5 424 1 709 1/NeutralGift//", + "Demetrius": " Best Gifts/207 1 232 1 233 1 400 1/Good Gifts/-5 3 -79 5 422 1/NeutralGift/-4 3/", + "Maru": " BestGift/72 1 197 1 190 1 215 1 222 1 243 1 336 1 337 1 400 1 787 1/Good Gift/-260 1 62 1 64 1 66 1 68 1 70 1 334 1 335 1 725 1 726 1/NeutralGift/", + "Sebastian": " Best/84 1 227 1 236 1 575 1 305 1 /Good/267 1 276 1/Neutral/-4 3/", + "Linus": " Best/88 1 90 1 234 1 242 1 280 1/Good/-5 3 -6 5 -79 5 -81 10/Neutral/-4 3/", + "Pierre": " Best/202 1/Good/-5 3 -6 5 -7 1 18 1 22 1 402 1 418 1 259 1/Neutral//", + "Caroline": " Best/213 1 593 1/Good/-7 1 18 1 402 1 418 1/Neutral// ", + "Abigail": " Best/66 1 128 1 220 1 226 1 276 1 611 1/Good//Neutral// ", + "Alex": " Best/201 1 212 1 662 1 664 1/Good/-5 3/Neutral// ", + "George": " Best/20 1 205 1/Good/18 1 195 1 199 1 200 1 214 1 219 1 223 1 231 1 233 1/Neutral// ", + "Evelyn": " Best/72 1 220 1 239 1 284 1 591 1 595 1/Good/-6 5 18 1 402 1 418 1/Neutral// ", + "Lewis": " Best/200 1 208 1 235 1 260 1/Good/-80 5 24 1 88 1 90 1 192 1 258 1 264 1 272 1 274 1 278 1/Neutral// ", + "Clint": " Best/60 1 62 1 64 1 66 1 68 1 70 1 336 1 337 1 605 1 649 1 749 1 337 5/Good/334 20 335 10 336 5/Neutral// ", + "Penny": " Best/60 1 376 1 651 1 72 1 164 1 218 1 230 1 244 1 254 1/Good/-6 5 20 1 22 1/Neutral// ", + "Pam": " Best/24 1 90 1 199 1 208 1 303 1 346 1/Good/-6 5 -75 5 -79 5 18 1 227 1 228 1 231 1 232 1 233 1 234 1 235 1 236 1 238 1 402 1 418 1/Neutral/-4 3/ ", + "Emily": " Best/60 1 62 1 64 1 66 1 68 1 70 1 241 1 428 1 440 1 /Good/18 1 82 1 84 1 86 1 196 1 200 1 207 1 230 1 235 1 402 1 418 1/Neutral// ", + "Haley": " Best/221 1 421 1 610 1 88 1 /Good/18 1 60 1 62 1 64 1 70 1 88 1 222 1 223 1 232 1 233 1 234 1 402 1 418 1 /Neutral// ", + "Jas": " Best/221 1 595 1 604 1 /Good/18 1 60 1 64 1 70 1 88 1 232 1 233 1 234 1 222 1 223 1 340 1 344 1 402 1 418 1 /Neutral// ", + "Vincent": " Best/221 1 398 1 612 1 /Good/18 1 60 1 64 1 70 1 88 1 232 1 233 1 234 1 222 1 223 1 340 1 344 1 402 1 418 1 /Neutral// ", + "Jodi": " Best/72 1 200 1 211 1 214 1 220 1 222 1 225 1 231 1 /Good/-5 3 -6 5 -79 5 18 1 402 1 418 1 /Neutral// ", + "Kent": " Best/607 1 649 1 /Good/-5 3 -79 5 18 1 402 1 418 1 /Neutral// ", + "Sam": " Best/90 1 206 1 655 1 658 1 562 1 731 1/Good/167 1 210 1 213 1 220 1 223 1 224 1 228 1 232 1 233 1 239 1 -5 3/Neutral// ", + "Leah": " Best/196 1 200 1 348 1 606 1 651 1 650 1 426 1 430 1 /Good/-5 3 -6 5 -79 5 -81 10 18 1 402 1 406 1 408 1 418 1 86 1 /Neutral// ", + "Shane": " Best/206 1 215 1 260 1 346 1 /Good/-5 3 -79 5 303 1 /Neutral// ", + "Marnie": " Best/72 1 221 1 240 1 608 1 /Good/-5 3 -6 5 402 1 418 1 /Neutral// ", + "Elliott": " Best/715 1 732 1 218 1 444 1 /Good/727 1 728 1 -79 5 60 1 80 1 82 1 84 1 149 1 151 1 346 1 348 1 728 1 /Neutral/-4 3 / ", + "Gus": " Best/72 1 213 1 635 1 729 1 /Good/348 1 303 1 -7 1 18 1 /Neutral// ", + "Dwarf": " Best/60 1 62 1 64 1 66 1 68 1 70 1 749 1 /Good/82 1 84 1 86 1 96 1 97 1 98 1 99 1 121 1 122 1 /Neutral/-28 20 / ", + "Wizard": " Best/107 1 155 1 422 1 769 1 768 1 /Good/-12 3 72 1 82 1 84 1/Neutral// ", + "Harvey": " Best/348 1 237 1 432 1 395 1 342 1 /Good/-81 10 -79 5 -7 1 402 1 418 1 422 1 436 1 438 1 442 1 444 1 422 1 /Neutral// ", + "Sandy": " Best/18 1 402 1 418 1 /Good/-75 5 -79 5 88 1 428 1 436 1 438 1 440 1 /Neutral// ", + "Willy": " Best/72 1 143 1 149 1 154 1 276 1 337 1 698 1 /Good/66 1 336 1 340 1 699 1 707 1 /Neutral/-4 3 / ", + "Krobus": " Best/72 1 16 1 276 1 337 1 305 1 /Good/66 1 336 1 340 1 /Neutral// " +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Content/Gifts/SpouseBirthdayGifts.json b/GeneralMods/HappyBirthday/Content/Gifts/SpouseBirthdayGifts.json new file mode 100644 index 00000000..1533b327 --- /dev/null +++ b/GeneralMods/HappyBirthday/Content/Gifts/SpouseBirthdayGifts.json @@ -0,0 +1,15 @@ +{ + "Universal_Gifts": "74 1 446 1 204 1 446 5 773 1", + "Alex": "", + "Elliott": "", + "Harvey": "", + "Sam": "", + "Sebastian": "", + "Shane": "", + "Abigail": "", + "Emily": "", + "Haley": "", + "Leah": "", + "Maru": "", + "Penny": "" +} \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/Framework/BirthdayMenu.cs b/GeneralMods/HappyBirthday/Framework/BirthdayMenu.cs index 4e9d1c9c..9824db59 100644 --- a/GeneralMods/HappyBirthday/Framework/BirthdayMenu.cs +++ b/GeneralMods/HappyBirthday/Framework/BirthdayMenu.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -11,7 +11,7 @@ namespace Omegasis.HappyBirthday.Framework internal class BirthdayMenu : IClickableMenu { /********* - ** Properties + ** Fields *********/ /// The labels to draw. private readonly List Labels = new List(); @@ -50,9 +50,7 @@ namespace Omegasis.HappyBirthday.Framework this.OnChanged = onChanged; this.SetUpPositions(); } - - - + /// The method called when the game window changes size. /// The former viewport. /// The new viewport. @@ -155,7 +153,7 @@ namespace Omegasis.HappyBirthday.Framework case "OK": if (this.BirthdayDay >= 1 || this.BirthdayDay <= 28) MultiplayerSupport.SendBirthdayInfoToOtherPlayers(); //Send updated info to others. - Game1.exitActiveMenu(); + Game1.exitActiveMenu(); break; default: diff --git a/GeneralMods/HappyBirthday/Framework/Messages.cs b/GeneralMods/HappyBirthday/Framework/Messages.cs index 14d720bd..4cf68e86 100644 --- a/GeneralMods/HappyBirthday/Framework/Messages.cs +++ b/GeneralMods/HappyBirthday/Framework/Messages.cs @@ -1,6 +1,5 @@ - + using StardewValley; -using System.Collections.Generic; namespace Omegasis.HappyBirthday.Framework { @@ -28,8 +27,6 @@ namespace Omegasis.HappyBirthday.Framework Game1.player.mailReceived.Add("BackpackTip"); Game1.addMailForTomorrow("pierreBackpack", false, false); } - - } } diff --git a/GeneralMods/HappyBirthday/Framework/ModConfig.cs b/GeneralMods/HappyBirthday/Framework/ModConfig.cs index fb501b14..a4d9b010 100644 --- a/GeneralMods/HappyBirthday/Framework/ModConfig.cs +++ b/GeneralMods/HappyBirthday/Framework/ModConfig.cs @@ -1,19 +1,17 @@ -namespace Omegasis.HappyBirthday.Framework +using StardewModdingAPI; + +namespace Omegasis.HappyBirthday.Framework { /// The mod configuration. public class ModConfig { /// The key which shows the menu. - public string KeyBinding { get; set; } = "O"; + public SButton KeyBinding { get; set; } = SButton.O; - /// - /// The minimum amount of friendship needed to get a birthday gift. - /// + /// The minimum amount of friendship needed to get a birthday gift. public int minNeutralFriendshipGiftLevel = 3; - /// - /// The max amount of friendship needed to get a neutral gift from an npc. - /// + /// The max amount of friendship needed to get a neutral gift from an npc. public int maxNeutralFriendshipGiftLevel = 4; /// @@ -21,34 +19,22 @@ /// public int minLikeFriendshipLevel = 5; - /// - /// The max amount of friendship needed to get a liked gift from an npc. - /// + /// The max amount of friendship needed to get a liked gift from an npc. public int maxLikeFriendshipLevel = 6; - /// - /// The minimum amount of friendship needed to get a loved gift from an npc. - /// + /// The minimum amount of friendship needed to get a loved gift from an npc. public int minLoveFriendshipLevel = 7; - /// - /// The minimum amount of friendship needed to get a happy birthday greeting from an npc. - /// - public int minimumFriendshipLevelForBirthdayWish=2; + /// The minimum amount of friendship needed to get a happy birthday greeting from an npc. + public int minimumFriendshipLevelForBirthdayWish = 2; - /// - /// Handles different translations of files. - /// + /// Handles different translations of files. public TranslationInfo translationInfo; - /// - /// Whether or not to load from the old BirthdayGifts.xnb located in StardewValley/Data or from the new BirthdayGifts.json located in the mod directory. - /// + /// Whether or not to load from the old BirthdayGifts.xnb located in StardewValley/Data or from the new BirthdayGifts.json located in the mod directory. public bool useLegacyBirthdayFiles; - /// - /// Constructor. - /// + /// Construct an instance. public ModConfig() { this.translationInfo = new TranslationInfo(); diff --git a/GeneralMods/HappyBirthday/Framework/MultiplayerSupport.cs b/GeneralMods/HappyBirthday/Framework/MultiplayerSupport.cs index 83eb234f..f6e9fa4b 100644 --- a/GeneralMods/HappyBirthday/Framework/MultiplayerSupport.cs +++ b/GeneralMods/HappyBirthday/Framework/MultiplayerSupport.cs @@ -1,28 +1,22 @@ -using StardewValley; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley; namespace Omegasis.HappyBirthday.Framework { public class MultiplayerSupport { - public static string FSTRING_SendBirthdayMessageToOthers = "Omegasis.HappyBirthday.Framework.Messages.SendBirthdayMessageToOtherPlayers"; public static string FSTRING_SendBirthdayInfoToOthers = "Omegasis.HappyBirthday.Framework.Messages.SendBirthdayInfoToOtherPlayers"; - public static void SendBirthdayMessageToOtherPlayers() { - HUDMessage message = new HUDMessage("It's " + Game1.player.Name + "'s birthday! Happy birthday to them!", 1); + string str = BirthdayMessages.GetTranslatedString("Happy Birthday: Farmhand Birthday Message"); + str.Replace("@", Game1.player.name); + HUDMessage message = new HUDMessage(str, 1); - - foreach (KeyValuePair f in Game1.otherFarmers) + foreach (KeyValuePair f in Game1.otherFarmers) { - HappyBirthday.ModHelper.Multiplayer.SendMessage(message.message, FSTRING_SendBirthdayMessageToOthers,new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key }); - //ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f); + HappyBirthday.ModHelper.Multiplayer.SendMessage(message.message, FSTRING_SendBirthdayMessageToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key }); } } @@ -30,18 +24,13 @@ namespace Omegasis.HappyBirthday.Framework { foreach (KeyValuePair f in Game1.otherFarmers) { - HappyBirthday.ModHelper.Multiplayer.SendMessage>(new KeyValuePair(Game1.player.uniqueMultiplayerID, HappyBirthday.PlayerBirthdayData), FSTRING_SendBirthdayInfoToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key }); - //ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f); + HappyBirthday.ModHelper.Multiplayer.SendMessage>(new KeyValuePair(Game1.player.uniqueMultiplayerID, HappyBirthday.PlayerBirthdayData), FSTRING_SendBirthdayInfoToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key }); } - } public static void SendBirthdayInfoToConnectingPlayer(long id) { HappyBirthday.ModHelper.Multiplayer.SendMessage>(new KeyValuePair(Game1.player.uniqueMultiplayerID, HappyBirthday.PlayerBirthdayData), FSTRING_SendBirthdayInfoToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { id }); - //ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f); - } - } } diff --git a/GeneralMods/HappyBirthday/Framework/ObjectUtility.cs b/GeneralMods/HappyBirthday/Framework/ObjectUtility.cs index 49e9c263..84b12bc0 100644 --- a/GeneralMods/HappyBirthday/Framework/ObjectUtility.cs +++ b/GeneralMods/HappyBirthday/Framework/ObjectUtility.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using StardewValley; using Object = StardewValley.Object; @@ -9,7 +9,7 @@ namespace Omegasis.HappyBirthday.Framework internal class ObjectUtility { /********* - ** Properties + ** Fields *********/ /// The cached object data. private static readonly Object[] ObjectList = ObjectUtility.GetAllObjects().ToArray(); diff --git a/GeneralMods/HappyBirthday/Framework/PlayerData.cs b/GeneralMods/HappyBirthday/Framework/PlayerData.cs index f956b797..bfee948f 100644 --- a/GeneralMods/HappyBirthday/Framework/PlayerData.cs +++ b/GeneralMods/HappyBirthday/Framework/PlayerData.cs @@ -1,4 +1,4 @@ -namespace Omegasis.HappyBirthday.Framework +namespace Omegasis.HappyBirthday.Framework { /// The data for the current player. public class PlayerData diff --git a/GeneralMods/HappyBirthday/Framework/TranslationInfo.cs b/GeneralMods/HappyBirthday/Framework/TranslationInfo.cs index abc244eb..d534dd4d 100644 --- a/GeneralMods/HappyBirthday/Framework/TranslationInfo.cs +++ b/GeneralMods/HappyBirthday/Framework/TranslationInfo.cs @@ -1,70 +1,56 @@ -using StardewValley; -using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley; namespace Omegasis.HappyBirthday.Framework { - /// - /// A class which deals with handling different translations for Vocalization should other voice teams ever wish to voice act for that language. - /// + /// A class which deals with handling different translations for Vocalization should other voice teams ever wish to voice act for that language. public class TranslationInfo { - /// - /// The list of all supported translations by this mod. - /// + /// The list of all supported translations by this mod. public List translations; - /// - /// The current translation mode for the mod, so that it knows what files to load at the beginning of the game. - /// + /// The current translation mode for the mod, so that it knows what files to load at the beginning of the game. public string currentTranslation; - /// - /// Holds the info for what translation has what file extension. - /// + /// Holds the info for what translation has what file extension. public Dictionary translationFileInfo; - public Dictionary translationCodes; - /// - /// Default constructor. - /// + + /// Construct an instance.. public TranslationInfo() { - translations = new List(); + this.translations = new List(); - translationFileInfo = new Dictionary(); - translationCodes = new Dictionary(); - translations.Add("English"); - translations.Add("Spanish"); - translations.Add("Chinese"); - translations.Add("Japanese"); - translations.Add("Russian"); - translations.Add("German"); - translations.Add("Brazillian Portuguese"); + this.translationFileInfo = new Dictionary(); + this.translationCodes = new Dictionary(); + this.translations.Add("English"); + this.translations.Add("Spanish"); + this.translations.Add("Chinese"); + this.translations.Add("Japanese"); + this.translations.Add("Russian"); + this.translations.Add("German"); + this.translations.Add("Brazillian Portuguese"); - currentTranslation = "English"; + this.currentTranslation = "English"; - translationFileInfo.Add("English", ".json"); - translationFileInfo.Add("Spanish", ".es-ES.json"); - translationFileInfo.Add("Chinese", ".zh-CN.json"); - translationFileInfo.Add("Japanese", ".ja-JP.json"); - translationFileInfo.Add("Russian", ".ru-RU.json"); - translationFileInfo.Add("German", ".de-DE.json"); - translationFileInfo.Add("Brazillian Portuguese", ".pt-BR.json"); + this.translationFileInfo.Add("English", ".json"); + this.translationFileInfo.Add("Spanish", ".es-ES.json"); + this.translationFileInfo.Add("Chinese", ".zh-CN.json"); + this.translationFileInfo.Add("Japanese", ".ja-JP.json"); + this.translationFileInfo.Add("Russian", ".ru-RU.json"); + this.translationFileInfo.Add("German", ".de-DE.json"); + this.translationFileInfo.Add("Brazillian Portuguese", ".pt-BR.json"); - translationCodes.Add("English", LocalizedContentManager.LanguageCode.en); - translationCodes.Add("Spanish", LocalizedContentManager.LanguageCode.es); - translationCodes.Add("Chinese", LocalizedContentManager.LanguageCode.zh); - translationCodes.Add("Japanese", LocalizedContentManager.LanguageCode.ja); - translationCodes.Add("Russian", LocalizedContentManager.LanguageCode.ru); - translationCodes.Add("German", LocalizedContentManager.LanguageCode.de); - translationCodes.Add("Brazillian Portuguese", LocalizedContentManager.LanguageCode.pt); + this.translationCodes.Add("English", LocalizedContentManager.LanguageCode.en); + this.translationCodes.Add("Spanish", LocalizedContentManager.LanguageCode.es); + this.translationCodes.Add("Chinese", LocalizedContentManager.LanguageCode.zh); + this.translationCodes.Add("Japanese", LocalizedContentManager.LanguageCode.ja); + this.translationCodes.Add("Russian", LocalizedContentManager.LanguageCode.ru); + this.translationCodes.Add("German", LocalizedContentManager.LanguageCode.de); + this.translationCodes.Add("Brazillian Portuguese", LocalizedContentManager.LanguageCode.pt); } @@ -73,12 +59,11 @@ namespace Omegasis.HappyBirthday.Framework return Path.GetFileName(fullPath); } - public void changeLocalizedContentManagerFromTranslation(string translation) { - string tra = getTranslationNameFromPath(translation); - bool f = translationCodes.TryGetValue(tra, out LocalizedContentManager.LanguageCode code); - if (f == false) LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en; + string tra = this.getTranslationNameFromPath(translation); + bool f = this.translationCodes.TryGetValue(tra, out LocalizedContentManager.LanguageCode code); + if (!f) LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en; else LocalizedContentManager.CurrentLanguageCode = code; return; } @@ -88,24 +73,21 @@ namespace Omegasis.HappyBirthday.Framework LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en; } - /// - /// Gets the proper file extension for the current translation. - /// + /// Gets the proper file extension for the current translation. /// - /// public string getFileExtentionForTranslation(string path) { /* bool f = translationFileInfo.TryGetValue(translation, out string value); - if (f == false) return ".json"; + if (!f) return ".json"; else return value; */ string translation = Path.GetFileName(path); try { - return translationFileInfo[translation]; + return this.translationFileInfo[translation]; } - catch (Exception err) + catch { HappyBirthday.ModMonitor.Log("WTF SOMETHING IS WRONG!", StardewModdingAPI.LogLevel.Warn); //Vocalization.ModMonitor.Log(err.ToString()); @@ -114,45 +96,34 @@ namespace Omegasis.HappyBirthday.Framework } } - /// - /// Gets the proper json for Buildings (aka Blueprints) from the data folder. - /// - /// - /// + /// Gets the proper json for Buildings (aka Blueprints) from the data folder. public string getBuildingjsonForTranslation(string translation) { string buildings = "Blueprints"; - return buildings + getFileExtentionForTranslation(translation); + return buildings + this.getFileExtentionForTranslation(translation); } - /// - /// Gets the proper json file for the name passed in. Combines the file name with it's proper translation extension. - /// + /// Gets the proper json file for the name passed in. Combines the file name with it's proper translation extension. /// /// - /// public string getjsonForTranslation(string jsonFileName, string translation) { - return jsonFileName + getFileExtentionForTranslation(translation); + return jsonFileName + this.getFileExtentionForTranslation(translation); } - /// - /// Loads an json file from StardewValley/Content - /// + /// Loads an json file from StardewValley/Content /// /// /// - /// public string LoadjsonFile(string jsonFileName, string key, string translation) { - string json = jsonFileName + getFileExtentionForTranslation(translation); + string json = jsonFileName + this.getFileExtentionForTranslation(translation); Dictionary loadedDict = Game1.content.Load>(json); - string loaded; - bool f = loadedDict.TryGetValue(key, out loaded); - if (f == false) + bool f = loadedDict.TryGetValue(key, out string loaded); + if (!f) { //Vocalization.ModMonitor.Log("Big issue: Key not found in file:" + json + " " + key); return ""; @@ -160,15 +131,12 @@ namespace Omegasis.HappyBirthday.Framework else return loaded; } - /// - /// Loads a string dictionary from a json file. - /// + /// Loads a string dictionary from a json file. /// /// - /// - public Dictionary LoadJsonFileDictionary(string jsonFileName, string translation) + public Dictionary LoadJsonFileDictionary(string jsonFileName, string translation) { - string json = jsonFileName + getFileExtentionForTranslation(translation); + string json = jsonFileName + this.getFileExtentionForTranslation(translation); Dictionary loadedDict = Game1.content.Load>(json); return loadedDict; @@ -181,9 +149,7 @@ namespace Omegasis.HappyBirthday.Framework { return string.Format(format, sub1, sub2, sub3); } - catch (Exception ex) - { - } + catch { } return format; } @@ -195,9 +161,7 @@ namespace Omegasis.HappyBirthday.Framework { return string.Format(format, sub1, sub2); } - catch (Exception ex) - { - } + catch { } return format; } @@ -209,20 +173,15 @@ namespace Omegasis.HappyBirthday.Framework { return string.Format(format, sub1); } - catch (Exception ex) - { - } + catch { } return format; } public virtual string LoadString(string path, string translation) { - string assetName; - string key; - this.parseStringPath(path, out assetName, out key); - - return LoadjsonFile(assetName, key, translation); + this.parseStringPath(path, out string assetName, out string key); + return this.LoadjsonFile(assetName, key, translation); } public virtual string LoadString(string path, string translation, params object[] substitutions) @@ -234,14 +193,11 @@ namespace Omegasis.HappyBirthday.Framework { return string.Format(format, substitutions); } - catch (Exception ex) - { - } + catch { } } return format; } - private void parseStringPath(string path, out string assetName, out string key) { int length = path.IndexOf(':'); diff --git a/GeneralMods/HappyBirthday/GiftManager.cs b/GeneralMods/HappyBirthday/GiftManager.cs index eb313029..f2631695 100644 --- a/GeneralMods/HappyBirthday/GiftManager.cs +++ b/GeneralMods/HappyBirthday/GiftManager.cs @@ -1,65 +1,60 @@ -using Omegasis.HappyBirthday.Framework; -using StardewModdingAPI; -using StardewValley; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Omegasis.HappyBirthday.Framework; +using StardewValley; +using static System.String; using SObject = StardewValley.Object; namespace Omegasis.HappyBirthday { public class GiftManager { - public ModConfig Config + public ModConfig Config => HappyBirthday.Config; + + private Dictionary defaultBirthdayGifts = new Dictionary() { - get - { - return HappyBirthday.Config; - } - } + ["Universal_Love_Gift"] = "74 1 446 1 204 1 446 5 773 1", + ["Universal_Like_Gift"] = "-2 3 -7 1 -26 2 -75 5 -80 3 72 1 220 1 221 1 395 1 613 1 634 1 635 1 636 1 637 1 638 1 724 1 233 1 223 1 465 20 -79 5", + ["Universal_Neutral_Gift"] = "194 1 262 5 -74 5 -75 3 334 5 335 1 390 20 388 20 -81 5 -79 3", + ["Robin"] = " BestGifts/224 1 426 1 636 1/GoodGift/-6 5 -79 5 424 1 709 1/NeutralGift//", + ["Demetrius"] = " Best Gifts/207 1 232 1 233 1 400 1/Good Gifts/-5 3 -79 5 422 1/NeutralGift/-4 3/", + ["Maru"] = " BestGift/72 1 197 1 190 1 215 1 222 1 243 1 336 1 337 1 400 1 787 1/Good Gift/-260 1 62 1 64 1 66 1 68 1 70 1 334 1 335 1 725 1 726 1/NeutralGift/", + ["Sebastian"] = " Best/84 1 227 1 236 1 575 1 305 1 /Good/267 1 276 1/Neutral/-4 3/", + ["Linus"] = " Best/88 1 90 1 234 1 242 1 280 1/Good/-5 3 -6 5 -79 5 -81 10/Neutral/-4 3/", + ["Pierre"] = " Best/202 1/Good/-5 3 -6 5 -7 1 18 1 22 1 402 1 418 1 259 1/Neutral//", + ["Caroline"] = " Best/213 1 593 1/Good/-7 1 18 1 402 1 418 1/Neutral// ", + ["Abigail"] = " Best/66 1 128 1 220 1 226 1 276 1 611 1/Good//Neutral// ", + ["Alex"] = " Best/201 1 212 1 662 1 664 1/Good/-5 3/Neutral// ", + ["George"] = " Best/20 1 205 1/Good/18 1 195 1 199 1 200 1 214 1 219 1 223 1 231 1 233 1/Neutral// ", + ["Evelyn"] = " Best/72 1 220 1 239 1 284 1 591 1 595 1/Good/-6 5 18 1 402 1 418 1/Neutral// ", + ["Lewis"] = " Best/200 1 208 1 235 1 260 1/Good/-80 5 24 1 88 1 90 1 192 1 258 1 264 1 272 1 274 1 278 1/Neutral// ", + ["Clint"] = " Best/60 1 62 1 64 1 66 1 68 1 70 1 336 1 337 1 605 1 649 1 749 1 337 5/Good/334 20 335 10 336 5/Neutral// ", + ["Penny"] = " Best/60 1 376 1 651 1 72 1 164 1 218 1 230 1 244 1 254 1/Good/-6 5 20 1 22 1/Neutral// ", + ["Pam"] = " Best/24 1 90 1 199 1 208 1 303 1 346 1/Good/-6 5 -75 5 -79 5 18 1 227 1 228 1 231 1 232 1 233 1 234 1 235 1 236 1 238 1 402 1 418 1/Neutral/-4 3/ ", + ["Emily"] = " Best/60 1 62 1 64 1 66 1 68 1 70 1 241 1 428 1 440 1 /Good/18 1 82 1 84 1 86 1 196 1 200 1 207 1 230 1 235 1 402 1 418 1/Neutral// ", + ["Haley"] = " Best/221 1 421 1 610 1 88 1 /Good/18 1 60 1 62 1 64 1 70 1 88 1 222 1 223 1 232 1 233 1 234 1 402 1 418 1 /Neutral// ", + ["Jas"] = " Best/221 1 595 1 604 1 /Good/18 1 60 1 64 1 70 1 88 1 232 1 233 1 234 1 222 1 223 1 340 1 344 1 402 1 418 1 /Neutral// ", + ["Vincent"] = " Best/221 1 398 1 612 1 /Good/18 1 60 1 64 1 70 1 88 1 232 1 233 1 234 1 222 1 223 1 340 1 344 1 402 1 418 1 /Neutral// ", + ["Jodi"] = " Best/72 1 200 1 211 1 214 1 220 1 222 1 225 1 231 1 /Good/-5 3 -6 5 -79 5 18 1 402 1 418 1 /Neutral// ", + ["Kent"] = " Best/607 1 649 1 /Good/-5 3 -79 5 18 1 402 1 418 1 /Neutral// ", + ["Sam"] = " Best/90 1 206 1 655 1 658 1 562 1 731 1/Good/167 1 210 1 213 1 220 1 223 1 224 1 228 1 232 1 233 1 239 1 -5 3/Neutral// ", + ["Leah"] = " Best/196 1 200 1 348 1 606 1 651 1 650 1 426 1 430 1 /Good/-5 3 -6 5 -79 5 -81 10 18 1 402 1 406 1 408 1 418 1 86 1 /Neutral// ", + ["Shane"] = " Best/206 1 215 1 260 1 346 1 /Good/-5 3 -79 5 303 1 /Neutral// ", + ["Marnie"] = " Best/72 1 221 1 240 1 608 1 /Good/-5 3 -6 5 402 1 418 1 /Neutral// ", + ["Elliott"] = " Best/715 1 732 1 218 1 444 1 /Good/727 1 728 1 -79 5 60 1 80 1 82 1 84 1 149 1 151 1 346 1 348 1 728 1 /Neutral/-4 3 / ", + ["Gus"] = " Best/72 1 213 1 635 1 729 1 /Good/348 1 303 1 -7 1 18 1 /Neutral// ", + ["Dwarf"] = " Best/60 1 62 1 64 1 66 1 68 1 70 1 749 1 /Good/82 1 84 1 86 1 96 1 97 1 98 1 99 1 121 1 122 1 /Neutral/-28 20 / ", + ["Wizard"] = " Best/107 1 155 1 422 1 769 1 768 1 /Good/-12 3 72 1 82 1 84 1/Neutral// ", + ["Harvey"] = " Best/348 1 237 1 432 1 395 1 342 1 /Good/-81 10 -79 5 -7 1 402 1 418 1 422 1 436 1 438 1 442 1 444 1 422 1 /Neutral// ", + ["Sandy"] = " Best/18 1 402 1 418 1 /Good/-75 5 -79 5 88 1 428 1 436 1 438 1 440 1 /Neutral// ", + ["Willy"] = " Best/72 1 143 1 149 1 154 1 276 1 337 1 698 1 /Good/66 1 336 1 340 1 699 1 707 1 /Neutral/-4 3 / ", + ["Krobus"] = " Best/72 1 16 1 276 1 337 1 305 1 /Good/66 1 336 1 340 1 /Neutral// " + }; - - private Dictionary defaultBirthdayGifts=new Dictionary() { - ["Universal_Love_Gift"] = "74 1 446 1 204 1 446 5 773 1", - ["Universal_Like_Gift"] = "-2 3 -7 1 -26 2 -75 5 -80 3 72 1 220 1 221 1 395 1 613 1 634 1 635 1 636 1 637 1 638 1 724 1 233 1 223 1 465 20 -79 5", - ["Universal_Neutral_Gift"] = "194 1 262 5 -74 5 -75 3 334 5 335 1 390 20 388 20 -81 5 -79 3", - ["Robin"] = " BestGifts/224 1 426 1 636 1/GoodGift/-6 5 -79 5 424 1 709 1/NeutralGift//", - ["Demetrius"] = " Best Gifts/207 1 232 1 233 1 400 1/Good Gifts/-5 3 -79 5 422 1/NeutralGift/-4 3/", - ["Maru"] = " BestGift/72 1 197 1 190 1 215 1 222 1 243 1 336 1 337 1 400 1 787 1/Good Gift/-260 1 62 1 64 1 66 1 68 1 70 1 334 1 335 1 725 1 726 1/NeutralGift/", - ["Sebastian"] = " Best/84 1 227 1 236 1 575 1 305 1 /Good/267 1 276 1/Neutral/-4 3/", - ["Linus"] = " Best/88 1 90 1 234 1 242 1 280 1/Good/-5 3 -6 5 -79 5 -81 10/Neutral/-4 3/", - ["Pierre"] = " Best/202 1/Good/-5 3 -6 5 -7 1 18 1 22 1 402 1 418 1 259 1/Neutral//", - ["Caroline"] = " Best/213 1 593 1/Good/-7 1 18 1 402 1 418 1/Neutral// ", - ["Abigail"] = " Best/66 1 128 1 220 1 226 1 276 1 611 1/Good//Neutral// ", - ["Alex"] = " Best/201 1 212 1 662 1 664 1/Good/-5 3/Neutral// ", - ["George"] = " Best/20 1 205 1/Good/18 1 195 1 199 1 200 1 214 1 219 1 223 1 231 1 233 1/Neutral// ", - ["Evelyn"] = " Best/72 1 220 1 239 1 284 1 591 1 595 1/Good/-6 5 18 1 402 1 418 1/Neutral// ", - ["Lewis"] = " Best/200 1 208 1 235 1 260 1/Good/-80 5 24 1 88 1 90 1 192 1 258 1 264 1 272 1 274 1 278 1/Neutral// ", - ["Clint"] = " Best/60 1 62 1 64 1 66 1 68 1 70 1 336 1 337 1 605 1 649 1 749 1 337 5/Good/334 20 335 10 336 5/Neutral// ", - ["Penny"] = " Best/60 1 376 1 651 1 72 1 164 1 218 1 230 1 244 1 254 1/Good/-6 5 20 1 22 1/Neutral// ", - ["Pam"] = " Best/24 1 90 1 199 1 208 1 303 1 346 1/Good/-6 5 -75 5 -79 5 18 1 227 1 228 1 231 1 232 1 233 1 234 1 235 1 236 1 238 1 402 1 418 1/Neutral/-4 3/ ", - ["Emily"] = " Best/60 1 62 1 64 1 66 1 68 1 70 1 241 1 428 1 440 1 /Good/18 1 82 1 84 1 86 1 196 1 200 1 207 1 230 1 235 1 402 1 418 1/Neutral// ", - ["Haley"] = " Best/221 1 421 1 610 1 88 1 /Good/18 1 60 1 62 1 64 1 70 1 88 1 222 1 223 1 232 1 233 1 234 1 402 1 418 1 /Neutral// ", - ["Jas"] = " Best/221 1 595 1 604 1 /Good/18 1 60 1 64 1 70 1 88 1 232 1 233 1 234 1 222 1 223 1 340 1 344 1 402 1 418 1 /Neutral// ", - ["Vincent"] = " Best/221 1 398 1 612 1 /Good/18 1 60 1 64 1 70 1 88 1 232 1 233 1 234 1 222 1 223 1 340 1 344 1 402 1 418 1 /Neutral// ", - ["Jodi"] = " Best/72 1 200 1 211 1 214 1 220 1 222 1 225 1 231 1 /Good/-5 3 -6 5 -79 5 18 1 402 1 418 1 /Neutral// ", - ["Kent"] = " Best/607 1 649 1 /Good/-5 3 -79 5 18 1 402 1 418 1 /Neutral// ", - ["Sam"] = " Best/90 1 206 1 655 1 658 1 562 1 731 1/Good/167 1 210 1 213 1 220 1 223 1 224 1 228 1 232 1 233 1 239 1 -5 3/Neutral// ", - ["Leah"] = " Best/196 1 200 1 348 1 606 1 651 1 650 1 426 1 430 1 /Good/-5 3 -6 5 -79 5 -81 10 18 1 402 1 406 1 408 1 418 1 86 1 /Neutral// ", - ["Shane"] = " Best/206 1 215 1 260 1 346 1 /Good/-5 3 -79 5 303 1 /Neutral// ", - ["Marnie"] = " Best/72 1 221 1 240 1 608 1 /Good/-5 3 -6 5 402 1 418 1 /Neutral// ", - ["Elliott"] = " Best/715 1 732 1 218 1 444 1 /Good/727 1 728 1 -79 5 60 1 80 1 82 1 84 1 149 1 151 1 346 1 348 1 728 1 /Neutral/-4 3 / ", - ["Gus"] = " Best/72 1 213 1 635 1 729 1 /Good/348 1 303 1 -7 1 18 1 /Neutral// ", - ["Dwarf"] = " Best/60 1 62 1 64 1 66 1 68 1 70 1 749 1 /Good/82 1 84 1 86 1 96 1 97 1 98 1 99 1 121 1 122 1 /Neutral/-28 20 / ", - ["Wizard"] = " Best/107 1 155 1 422 1 769 1 768 1 /Good/-12 3 72 1 82 1 84 1/Neutral// ", - ["Harvey"] = " Best/348 1 237 1 432 1 395 1 342 1 /Good/-81 10 -79 5 -7 1 402 1 418 1 422 1 436 1 438 1 442 1 444 1 422 1 /Neutral// ", - ["Sandy"] = " Best/18 1 402 1 418 1 /Good/-75 5 -79 5 88 1 428 1 436 1 438 1 440 1 /Neutral// ", - ["Willy"] = " Best/72 1 143 1 149 1 154 1 276 1 337 1 698 1 /Good/66 1 336 1 340 1 699 1 707 1 /Neutral/-4 3 / ", - ["Krobus"] = " Best/72 1 16 1 276 1 337 1 305 1 /Good/66 1 336 1 340 1 /Neutral// " - }; - - public Dictionary defaultSpouseBirthdayGifts = new Dictionary() { + public Dictionary defaultSpouseBirthdayGifts = new Dictionary() + { ["Universal_Gifts"] = "74 1 446 1 204 1 446 5 773 1", ["Alex"] = "", @@ -74,8 +69,6 @@ namespace Omegasis.HappyBirthday ["Leah"] = "", ["Maru"] = "", ["Penny"] = "", - - }; public List BirthdayGifts; @@ -83,7 +76,7 @@ namespace Omegasis.HappyBirthday /// The next birthday gift the player will receive. public Item BirthdayGiftToReceive; - + /// Construct an instance. public GiftManager() { this.BirthdayGifts = new List(); @@ -91,44 +84,36 @@ namespace Omegasis.HappyBirthday this.loadSpouseBirthdayGifts(); } - /// - /// Load birthday gift information from disk. Preferably from BirthdayGift.json in the mod's directory. - /// - /// + /// Load birthday gift information from disk. Preferably from BirthdayGift.json in the mod's directory. public void loadVillagerBirthdayGifts() { - if (HappyBirthday.Config.useLegacyBirthdayFiles == false) + string villagerGifts = Path.Combine("Content", "Gifts", "BirthdayGifts.json"); + if (!HappyBirthday.Config.useLegacyBirthdayFiles) { - string villagerGifts = Path.Combine("Content", "Gifts", "BirthdayGifts.json"); if (File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, villagerGifts))) - { this.defaultBirthdayGifts = HappyBirthday.ModHelper.Data.ReadJsonFile>(villagerGifts); - } else - { HappyBirthday.ModHelper.Data.WriteJsonFile>(villagerGifts, this.defaultBirthdayGifts); - } - } else { - - if (File.Exists(Path.Combine(Game1.content.RootDirectory, "Data", "PossibleBirthdayGifts.xnb"))){ + if (File.Exists(Path.Combine(Game1.content.RootDirectory, "Data", "PossibleBirthdayGifts.xnb"))) + { HappyBirthday.ModMonitor.Log("Legacy loading detected. Attempting to load from StardewValley/Content/Data/PossibleBirthdayGifts.xnb"); this.defaultBirthdayGifts = Game1.content.Load>(Path.Combine("Data", "PossibleBirthdayGifts")); + + HappyBirthday.ModHelper.Data.WriteJsonFile>(villagerGifts, this.defaultBirthdayGifts); } else { - HappyBirthday.ModMonitor.Log("No birthday gift information found. Loading from internal birthday list"); + HappyBirthday.ModMonitor.Log("No birthday gift information found. Loading from internal birthday list and generating villagerGifts.json"); + HappyBirthday.ModHelper.Data.WriteJsonFile>(villagerGifts, this.defaultBirthdayGifts); } } } - /// - /// Used to load spouse birthday gifts from disk. - /// - /// + /// Used to load spouse birthday gifts from disk. public void loadSpouseBirthdayGifts() { string spouseGifts = Path.Combine("Content", "Gifts", "SpouseBirthdayGifts.json"); @@ -144,7 +129,6 @@ namespace Omegasis.HappyBirthday } } - /// Get the default gift items. /// The villager's name. private IEnumerable GetDefaultBirthdayGifts(string name) @@ -153,14 +137,14 @@ namespace Omegasis.HappyBirthday try { // read from birthday gifts file - IDictionary data = defaultBirthdayGifts; + IDictionary data = this.defaultBirthdayGifts; data.TryGetValue(name, out string text); if (text != null) { string[] fields = text.Split('/'); // love - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLoveFriendshipLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLoveFriendshipLevel) { string[] loveFields = fields[1].Split(' '); for (int i = 0; i < loveFields.Length; i += 2) @@ -174,7 +158,7 @@ namespace Omegasis.HappyBirthday } // like - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxLikeFriendshipLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxLikeFriendshipLevel) { string[] likeFields = fields[3].Split(' '); for (int i = 0; i < likeFields.Length; i += 2) @@ -188,7 +172,7 @@ namespace Omegasis.HappyBirthday } // neutral - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxNeutralFriendshipGiftLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxNeutralFriendshipGiftLevel) { string[] neutralFields = fields[5].Split(' '); @@ -204,54 +188,48 @@ namespace Omegasis.HappyBirthday } // get NPC's preferred gifts - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLoveFriendshipLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLoveFriendshipLevel) gifts.AddRange(this.GetUniversalItems("Love", true)); - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxLikeFriendshipLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxLikeFriendshipLevel) this.BirthdayGifts.AddRange(this.GetUniversalItems("Like", true)); - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxNeutralFriendshipGiftLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxNeutralFriendshipGiftLevel) this.BirthdayGifts.AddRange(this.GetUniversalItems("Neutral", true)); } catch { // get NPC's preferred gifts - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLoveFriendshipLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLoveFriendshipLevel) { this.BirthdayGifts.AddRange(this.GetUniversalItems("Love", false)); this.BirthdayGifts.AddRange(this.GetLovedItems(name)); } - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxLikeFriendshipLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxLikeFriendshipLevel) { this.BirthdayGifts.AddRange(this.GetLikedItems(name)); this.BirthdayGifts.AddRange(this.GetUniversalItems("Like", false)); } - if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxNeutralFriendshipGiftLevel) + if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxNeutralFriendshipGiftLevel) this.BirthdayGifts.AddRange(this.GetUniversalItems("Neutral", false)); } - + //Add in spouse specific birthday gifts. if (Game1.player.isMarried()) { if (name == Game1.player.spouse) { - this.BirthdayGifts.AddRange(getSpouseBirthdayGifts(name)); - this.BirthdayGifts.AddRange(getSpouseBirthdayGifts("Universal_Gifts")); + this.BirthdayGifts.AddRange(this.getSpouseBirthdayGifts(name)); + this.BirthdayGifts.AddRange(this.getSpouseBirthdayGifts("Universal_Gifts")); } } return gifts; } - /// - /// Get - /// - /// - /// - /// private IEnumerable getSpouseBirthdayGifts(string npcName) { Dictionary data = this.defaultSpouseBirthdayGifts; data.TryGetValue(npcName, out string text); - if (String.IsNullOrEmpty(text)) + if (IsNullOrEmpty(text)) yield break; // parse @@ -263,7 +241,6 @@ namespace Omegasis.HappyBirthday } } - /// Get the items loved by all villagers. /// The group to get (one of Like, Love, Neutral). /// Whether to get data from Data\BirthdayGifts.xnb instead of the game data. @@ -349,8 +326,6 @@ namespace Omegasis.HappyBirthday : new[] { new SObject(id, 1) }; } - - /// Get the items matching the given ID. /// The category or item ID. /// The stack size. diff --git a/GeneralMods/HappyBirthday/HappyBirthday.cs b/GeneralMods/HappyBirthday/HappyBirthday.cs index f41f8a82..3035f0f3 100644 --- a/GeneralMods/HappyBirthday/HappyBirthday.cs +++ b/GeneralMods/HappyBirthday/HappyBirthday.cs @@ -1,10 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using Newtonsoft.Json; using Omegasis.HappyBirthday.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; @@ -12,7 +11,6 @@ using StardewValley; using StardewValley.Characters; using StardewValley.Menus; using StardewValley.Monsters; -using SObject = StardewValley.Object; namespace Omegasis.HappyBirthday { @@ -20,7 +18,7 @@ namespace Omegasis.HappyBirthday public class HappyBirthday : Mod, IAssetEditor { /********* - ** Properties + ** Fields *********/ /// The relative path for the current player's data file. private string DataFilePath; @@ -34,19 +32,11 @@ namespace Omegasis.HappyBirthday /// The data for the current player. public static PlayerData PlayerBirthdayData; - /// - /// Wrapper for static field PlayerBirthdayData; - /// + /// Wrapper for static field PlayerBirthdayData; public PlayerData PlayerData { - get - { - return PlayerBirthdayData; - } - set - { - PlayerBirthdayData = value; - } + get => PlayerBirthdayData; + set => PlayerBirthdayData = value; } /// Whether the player has chosen a birthday. @@ -55,49 +45,27 @@ namespace Omegasis.HappyBirthday /// The queue of villagers who haven't given a gift yet. private List VillagerQueue; - /// Whether we've already checked for and (if applicable) set up the player's birthday today. private bool CheckedForBirthday; //private Dictionary Dialogue; //private bool SeenEvent; - public bool CanEdit(IAssetInfo asset) - { - return asset.AssetNameEquals(@"Data\mail"); - } - - public void Edit(IAssetData asset) - { - asset - .AsDictionary() - .Set("birthdayMom", "Dear @,^ Happy birthday sweetheart. It's been amazing watching you grow into the kind, hard working person that I've always dreamed that you would become. I hope you continue to make many more fond memories with the ones you love. ^ Love, Mom ^ P.S. Here's a little something that I made for you. %item object 221 1 %%"); - - asset - .AsDictionary() - .Set("birthdayDad", "Dear @,^ Happy birthday kiddo. It's been a little quiet around here on your birthday since you aren't around, but your mother and I know that you are making both your grandpa and us proud. We both know that living on your own can be tough but we believe in you one hundred percent, just keep following your dreams.^ Love, Dad ^ P.S. Here's some spending money to help you out on the farm. Good luck! %item money 5000 5001 %%"); - } - public static IModHelper ModHelper; public static IMonitor ModMonitor; - /// - /// Class to handle all birthday messages for this mod. - /// + /// Class to handle all birthday messages for this mod. public BirthdayMessages messages; - /// - /// Class to handle all birthday gifts for this mod. - /// + /// Class to handle all birthday gifts for this mod. public GiftManager giftManager; - /// - /// Checks if the current billboard is the daily quest screen or not. - /// + /// Checks if the current billboard is the daily quest screen or not. bool isDailyQuestBoard; + Dictionary othersBirthdays; - Dictionary othersBirthdays; + public static HappyBirthday Instance; /********* ** Public methods @@ -106,42 +74,65 @@ namespace Omegasis.HappyBirthday /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { + + Instance = this; + //helper.Content.AssetLoaders.Add(new PossibleGifts()); Config = helper.ReadConfig(); - TimeEvents.AfterDayStarted += this.TimeEvents_AfterDayStarted; - GameEvents.UpdateTick += this.GameEvents_UpdateTick; - SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; - SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; - ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; - MenuEvents.MenuChanged += MenuEvents_MenuChanged; - MenuEvents.MenuClosed += MenuEvents_MenuClosed; + helper.Events.GameLoop.DayStarted += this.OnDayStarted; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; + helper.Events.GameLoop.Saving += this.OnSaving; + helper.Events.Input.ButtonPressed += this.OnButtonPressed; + helper.Events.Display.MenuChanged += this.OnMenuChanged; - - - GraphicsEvents.OnPostRenderGuiEvent += GraphicsEvents_OnPostRenderGuiEvent; - StardewModdingAPI.Events.GraphicsEvents.OnPostRenderHudEvent += GraphicsEvents_OnPostRenderHudEvent; + helper.Events.Display.RenderedActiveMenu += this.OnRenderedActiveMenu; + helper.Events.Display.RenderedHud += this.OnRenderedHud; //MultiplayerSupport.initializeMultiplayerSupport(); - ModHelper = Helper; - ModMonitor = Monitor; + ModHelper = this.Helper; + ModMonitor = this.Monitor; - messages = new BirthdayMessages(); - giftManager = new GiftManager(); - isDailyQuestBoard = false; + this.messages = new BirthdayMessages(); + this.giftManager = new GiftManager(); + this.isDailyQuestBoard = false; - ModHelper.Events.Multiplayer.ModMessageReceived += Multiplayer_ModMessageReceived; + ModHelper.Events.Multiplayer.ModMessageReceived += this.Multiplayer_ModMessageReceived; - ModHelper.Events.Multiplayer.PeerDisconnected += Multiplayer_PeerDisconnected; + ModHelper.Events.Multiplayer.PeerDisconnected += this.Multiplayer_PeerDisconnected; this.othersBirthdays = new Dictionary(); + } - /// - /// Used to check for player disconnections. - /// - /// - /// + /// Get whether this instance can edit the given asset. + /// Basic metadata about the asset being loaded. + public bool CanEdit(IAssetInfo asset) + { + return asset.AssetNameEquals(@"Data\mail"); + } + + /// Edit a matched asset. + /// A helper which encapsulates metadata about an asset and enables changes to it. + public void Edit(IAssetData asset) + { + IDictionary data = asset.AsDictionary().Data; + + string momMail = BirthdayMessages.GetTranslatedString("Mail:birthdayMom"); + string dadMail = BirthdayMessages.GetTranslatedString("Mail:birthdayDad"); + + data["birthdayMom"] = momMail; + data["birthdayDad"] = dadMail; + } + + + /********* + ** Private methods + *********/ + /// Used to check for player disconnections. + /// The event sender. + /// The event arguments. private void Multiplayer_PeerDisconnected(object sender, PeerDisconnectedEventArgs e) { this.othersBirthdays.Remove(e.Peer.PlayerID); @@ -149,216 +140,179 @@ namespace Omegasis.HappyBirthday private void Multiplayer_ModMessageReceived(object sender, ModMessageReceivedEventArgs e) { - if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type==MultiplayerSupport.FSTRING_SendBirthdayMessageToOthers) + if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type == MultiplayerSupport.FSTRING_SendBirthdayMessageToOthers) { string message = e.ReadAs(); - Game1.hudMessages.Add(new HUDMessage(message,1)); + Game1.hudMessages.Add(new HUDMessage(message, 1)); } if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type == MultiplayerSupport.FSTRING_SendBirthdayInfoToOthers) { - KeyValuePair message = e.ReadAs>(); + KeyValuePair message = e.ReadAs>(); if (!this.othersBirthdays.ContainsKey(message.Key)) { - this.othersBirthdays.Add(message.Key,message.Value); + this.othersBirthdays.Add(message.Key, message.Value); MultiplayerSupport.SendBirthdayInfoToConnectingPlayer(e.FromPlayerID); - Monitor.Log("Got other player's birthday data from: "+ Game1.getFarmer(e.FromPlayerID).name); + this.Monitor.Log("Got other player's birthday data from: " + Game1.getFarmer(e.FromPlayerID).name); } else { //Brute force update birthday info if it has already been recevived but dont send birthday info again. this.othersBirthdays.Remove(message.Key); this.othersBirthdays.Add(message.Key, message.Value); - Monitor.Log("Got other player's birthday data from: " + Game1.getFarmer(e.FromPlayerID).name); + this.Monitor.Log("Got other player's birthday data from: " + Game1.getFarmer(e.FromPlayerID).name); } - - - } - } - /// - /// Used to check when a menu is closed. - /// - /// - /// - private void MenuEvents_MenuClosed(object sender, EventArgsClickableMenuClosed e) + /// Raised after drawing the HUD (item toolbar, clock, etc) to the sprite batch, but before it's rendered to the screen. + /// The event sender. + /// The event arguments. + private void OnRenderedHud(object sender, RenderedHudEventArgs e) { - this.isDailyQuestBoard = false; - } + if (Game1.activeClickableMenu == null || this.PlayerData?.BirthdaySeason?.ToLower() != Game1.currentSeason.ToLower()) + return; - - /// - /// Used to properly display hovertext for all events happening on a calendar day. - /// - /// - /// - private void GraphicsEvents_OnPostRenderHudEvent(object sender, EventArgs e) - { - if (Game1.activeClickableMenu == null) return; - if (PlayerData == null) return; - if (PlayerData.BirthdaySeason == null) return; - if (PlayerData.BirthdaySeason.ToLower() != Game1.currentSeason.ToLower()) return; - if (Game1.activeClickableMenu is Billboard) + if (Game1.activeClickableMenu is Billboard billboard) { - if (isDailyQuestBoard) return; - if ((Game1.activeClickableMenu as Billboard).calendarDays == null) return; + if (this.isDailyQuestBoard || billboard.calendarDays == null) + return; //Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 1f, 4f, 2, Game1.player); string hoverText = ""; List texts = new List(); - foreach (var clicky in (Game1.activeClickableMenu as Billboard).calendarDays) + foreach (var clicky in billboard.calendarDays) { if (clicky.containsPoint(Game1.getMouseX(), Game1.getMouseY())) { - if (!String.IsNullOrEmpty(clicky.hoverText)) - { + if (!string.IsNullOrEmpty(clicky.hoverText)) texts.Add(clicky.hoverText); //catches npc birhday names. - } - else if (!String.IsNullOrEmpty(clicky.name)) - { + else if (!string.IsNullOrEmpty(clicky.name)) texts.Add(clicky.name); //catches festival dates. - } } } - - for(int i = 0; i< texts.Count; i++) - { + for (int i = 0; i < texts.Count; i++) + { hoverText += texts[i]; //Append text. - if (i == texts.Count - 1) continue; - else - { + if (i != texts.Count - 1) hoverText += Environment.NewLine; //Append new line. - } } - if (!String.IsNullOrEmpty(hoverText)) + if (!string.IsNullOrEmpty(hoverText)) { - var oldText = Helper.Reflection.GetField(Game1.activeClickableMenu, "hoverText", true); + var oldText = this.Helper.Reflection.GetField(Game1.activeClickableMenu, "hoverText"); oldText.SetValue(hoverText); } - } } - /// - /// Used to show the farmer's portrait on the billboard menu. - /// - /// - /// - private void GraphicsEvents_OnPostRenderGuiEvent(object sender, EventArgs e) + /// When a menu is open ( isn't null), raised after that menu is drawn to the sprite batch but before it's rendered to the screen. + /// The event sender. + /// The event arguments. + private void OnRenderedActiveMenu(object sender, RenderedActiveMenuEventArgs e) { - if (Game1.activeClickableMenu == null) return; - //Don't do anything if birthday has not been chosen yet. - if (PlayerData == null) return; - + if (Game1.activeClickableMenu == null || this.isDailyQuestBoard) + return; + //Don't do anything if birthday has not been chosen yet. + if (this.PlayerData == null) + return; if (Game1.activeClickableMenu is Billboard) { - if (isDailyQuestBoard) return; - - if (!String.IsNullOrEmpty(PlayerData.BirthdaySeason)) + if (!string.IsNullOrEmpty(this.PlayerData.BirthdaySeason)) { - if (PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower()) + if (this.PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower()) { - int index = PlayerData.BirthdayDay; + int index = this.PlayerData.BirthdayDay; Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 0.5f, 4f, 2, Game1.player); } } - foreach(var pair in this.othersBirthdays) + foreach (var pair in this.othersBirthdays) { int index = pair.Value.BirthdayDay; if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue; //Hide out of season birthdays. index = pair.Value.BirthdayDay; Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 0.5f, 4f, 2, Game1.getFarmer(pair.Key)); } - } } - /// - /// Functionality to display the player's birthday on the billboard. - /// - /// - /// - public void MenuEvents_MenuChanged(object sender, EventArgsClickableMenuChanged e) - { - if (Game1.activeClickableMenu == null) - { - isDailyQuestBoard = false; - return; - } - if(Game1.activeClickableMenu is Billboard) - { - isDailyQuestBoard = ModHelper.Reflection.GetField((Game1.activeClickableMenu as Billboard), "dailyQuestBoard", true).GetValue(); - if (isDailyQuestBoard) return; - - - - Texture2D text = new Texture2D(Game1.graphics.GraphicsDevice,1,1); - Color[] col = new Color[1]; - col[0] = new Color(0, 0, 0, 1); - text.SetData(col); - //players birthdy position rect=new .... - - if (!String.IsNullOrEmpty(PlayerData.BirthdaySeason)) - { - if (PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower()) - { - int index = PlayerData.BirthdayDay; - Rectangle birthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124); - (Game1.activeClickableMenu as Billboard).calendarDays.Add(new ClickableTextureComponent("", birthdayRect, "", Game1.player.name + "'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false)); - - } - } - - - foreach (var pair in this.othersBirthdays) - { - if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue; - int index = pair.Value.BirthdayDay; - Rectangle otherBirthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124); - (Game1.activeClickableMenu as Billboard).calendarDays.Add(new ClickableTextureComponent("", otherBirthdayRect, "", Game1.getFarmer(pair.Key).name + "'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false)); - } - - } - } - - - /********* - ** Private methods - *********/ - /// The method invoked after a new day starts. + /// Raised after a game menu is opened, closed, or replaced. /// The event sender. - /// The event data. - private void TimeEvents_AfterDayStarted(object sender, EventArgs e) + /// The event arguments. + private void OnMenuChanged(object sender, MenuChangedEventArgs e) + { + switch (e.NewMenu) + { + case null: + this.isDailyQuestBoard = false; + return; + + case Billboard billboard: + { + this.isDailyQuestBoard = ModHelper.Reflection.GetField((Game1.activeClickableMenu as Billboard), "dailyQuestBoard", true).GetValue(); + if (this.isDailyQuestBoard) + return; + + Texture2D text = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1); + Color[] col = new Color[1]; + col[0] = new Color(0, 0, 0, 1); + text.SetData(col); + //players birthday position rect=new .... + + if (!string.IsNullOrEmpty(this.PlayerData.BirthdaySeason)) + { + if (this.PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower()) + { + int index = this.PlayerData.BirthdayDay; + Rectangle birthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124); + billboard.calendarDays.Add(new ClickableTextureComponent("", birthdayRect, "", $"{Game1.player.Name}'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false)); + } + } + + foreach (var pair in this.othersBirthdays) + { + if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue; + int index = pair.Value.BirthdayDay; + Rectangle otherBirthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124); + billboard.calendarDays.Add(new ClickableTextureComponent("", otherBirthdayRect, "", $"{Game1.getFarmer(pair.Key).Name}'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false)); + } + + break; + } + } + } + + /// Raised after the game begins a new day (including when the player loads a save). + /// The event sender. + /// The event arguments. + private void OnDayStarted(object sender, DayStartedEventArgs e) { this.CheckedForBirthday = false; } - /// The method invoked when the presses a keyboard button. + /// Raised after the player presses a button on the keyboard, controller, or mouse. /// The event sender. - /// The event data. - private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) + /// The event arguments. + private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { // show birthday selection menu if (Game1.activeClickableMenu != null) return; - if (Context.IsPlayerFree && !this.HasChosenBirthday && e.KeyPressed.ToString() == Config.KeyBinding) + if (Context.IsPlayerFree && !this.HasChosenBirthday && e.Button == Config.KeyBinding) Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday); } - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - private void SaveEvents_AfterLoad(object sender, EventArgs e) + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { - this.DataFilePath = Path.Combine("data", Game1.player.Name + "_" + Game1.player.UniqueMultiplayerID+".json"); + this.DataFilePath = Path.Combine("data", $"{Game1.player.Name}_{Game1.player.UniqueMultiplayerID}.json"); // reset state this.VillagerQueue = new List(); @@ -368,7 +322,7 @@ namespace Omegasis.HappyBirthday this.MigrateLegacyData(); this.PlayerData = this.Helper.Data.ReadJsonFile(this.DataFilePath) ?? new PlayerData(); - messages.createBirthdayGreetings(); + ; if (PlayerBirthdayData != null) { @@ -379,36 +333,38 @@ namespace Omegasis.HappyBirthday //this.Dialogue = new Dictionary(); } - /// The method invoked just before the game updates the saves. + /// Raised before the game begins writes data to the save file (except the initial save creation). /// The event sender. - /// The event data. - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + private void OnSaving(object sender, SavingEventArgs e) { if (this.HasChosenBirthday) this.Helper.Data.WriteJsonFile(this.DataFilePath, this.PlayerData); } - /// The method invoked when the game updates (roughly 60 times per second). + /// Raised after the game state is updated (≈60 times per second). /// The event sender. - /// The event data. - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { if (!Context.IsWorldReady || Game1.eventUp || Game1.isFestival()) return; - if (!this.HasChosenBirthday && Game1.activeClickableMenu == null && Game1.player.Name.ToLower()!="unnamed farmhand") + if (!this.HasChosenBirthday && Game1.activeClickableMenu == null && Game1.player.Name.ToLower() != "unnamed farmhand") { Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday); this.CheckedForBirthday = false; } - if (!this.CheckedForBirthday && Game1.activeClickableMenu==null) + if (!this.CheckedForBirthday && Game1.activeClickableMenu == null) { this.CheckedForBirthday = true; // set up birthday if (this.IsBirthday()) { - Messages.ShowStarMessage("It's your birthday today! Happy birthday!"); + string starMessage = BirthdayMessages.GetTranslatedString("Happy Birthday: Star Message"); + + Messages.ShowStarMessage(starMessage); MultiplayerSupport.SendBirthdayMessageToOtherPlayers(); @@ -439,28 +395,26 @@ namespace Omegasis.HappyBirthday { bool spouseMessage = false; //Used to determine if there is a valid spouse message for the player. If false load in the generic birthday wish. //Check if npc name is spouse's name. If no spouse then add in generic dialogue. - if (messages.spouseBirthdayWishes.ContainsKey(npc.Name) && Game1.player.isMarried()) + if (this.messages.spouseBirthdayWishes.ContainsKey(npc.Name) && Game1.player.isMarried()) { - Monitor.Log("Spouse Checks out"); + //this.Monitor.Log("Spouse Checks out"); //Check to see if spouse message exists. - if (!String.IsNullOrEmpty(messages.spouseBirthdayWishes[npc.Name])) + if (!string.IsNullOrEmpty(this.messages.spouseBirthdayWishes[npc.Name])) { spouseMessage = true; - Dialogue d = new Dialogue(messages.spouseBirthdayWishes[npc.Name], npc); + Dialogue d = new Dialogue(this.messages.spouseBirthdayWishes[npc.Name], npc); npc.CurrentDialogue.Push(d); - if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(messages.spouseBirthdayWishes[npc.Name]); + if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(this.messages.spouseBirthdayWishes[npc.Name]); } else - { - Monitor.Log("No spouse message???", LogLevel.Warn); - } + this.Monitor.Log("No spouse message???", LogLevel.Warn); } - if (spouseMessage == false) + if (!spouseMessage) { //Load in - Dialogue d = new Dialogue(messages.birthdayWishes[npc.Name], npc); + Dialogue d = new Dialogue(this.messages.birthdayWishes[npc.Name], npc); npc.CurrentDialogue.Push(d); - if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(messages.birthdayWishes[npc.Name]); + if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(this.messages.birthdayWishes[npc.Name]); } } } @@ -479,12 +433,11 @@ namespace Omegasis.HappyBirthday } //Don't constantly set the birthday menu. - if (Game1.activeClickableMenu != null) - { - if (Game1.activeClickableMenu.GetType() == typeof(BirthdayMenu)) return; - } + if (Game1.activeClickableMenu?.GetType() == typeof(BirthdayMenu)) + return; + // ask for birthday date - if (!this.HasChosenBirthday && Game1.activeClickableMenu==null) + if (!this.HasChosenBirthday && Game1.activeClickableMenu == null) { Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday); this.CheckedForBirthday = false; @@ -495,11 +448,12 @@ namespace Omegasis.HappyBirthday if (Game1.currentSpeaker != null) { string name = Game1.currentSpeaker.Name; + if (Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.minNeutralFriendshipGiftLevel) return; if (this.IsBirthday() && this.VillagerQueue.Contains(name)) { try { - giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name); + this.giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name); this.VillagerQueue.Remove(Game1.currentSpeaker.Name); } catch (Exception ex) @@ -509,15 +463,14 @@ namespace Omegasis.HappyBirthday } //Validate the gift and give it to the player. - if (giftManager.BirthdayGiftToReceive != null) + if (this.giftManager.BirthdayGiftToReceive != null) { - while (giftManager.BirthdayGiftToReceive.Name == "Error Item" || giftManager.BirthdayGiftToReceive.Name == "Rock" || giftManager.BirthdayGiftToReceive.Name == "???") - giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name); - Game1.player.addItemByMenuIfNecessaryElseHoldUp(giftManager.BirthdayGiftToReceive); - giftManager.BirthdayGiftToReceive = null; + while (this.giftManager.BirthdayGiftToReceive.Name == "Error Item" || this.giftManager.BirthdayGiftToReceive.Name == "Rock" || this.giftManager.BirthdayGiftToReceive.Name == "???") + this.giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name); + Game1.player.addItemByMenuIfNecessaryElseHoldUp(this.giftManager.BirthdayGiftToReceive); + this.giftManager.BirthdayGiftToReceive = null; } } - } /// Set the player's birthday/ @@ -562,12 +515,13 @@ namespace Omegasis.HappyBirthday try { if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath)) - if (this.PlayerData == null) this.PlayerData = new PlayerData(); - return; + { + if (this.PlayerData == null) + this.PlayerData = new PlayerData(); + } } - catch(Exception err) + catch { - err.ToString(); // migrate to new file try { @@ -588,10 +542,6 @@ namespace Omegasis.HappyBirthday this.Monitor.Log($"Error migrating data from the legacy 'Player_Birthdays' folder for the current player. Technical details:\n {ex}", LogLevel.Error); } } - } - - - } } diff --git a/GeneralMods/HappyBirthday/HappyBirthday.csproj b/GeneralMods/HappyBirthday/HappyBirthday.csproj index 6d571ee8..a5e12e85 100644 --- a/GeneralMods/HappyBirthday/HappyBirthday.csproj +++ b/GeneralMods/HappyBirthday/HappyBirthday.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ HappyBirthday v4.5 512 - - true @@ -71,9 +69,10 @@ MinimumRecommendedRules.ruleset - - ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll - + + + + @@ -95,25 +94,58 @@ + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/HappyBirthday/manifest.json b/GeneralMods/HappyBirthday/manifest.json index 6b5cc92c..c2a5fe2f 100644 --- a/GeneralMods/HappyBirthday/manifest.json +++ b/GeneralMods/HappyBirthday/manifest.json @@ -1,16 +1,10 @@ { "Name": "Happy Birthday", "Author": "Alpha_Omegasis", - "Version": { - "MajorVersion": 1, - "MinorVersion": 8, - "PatchVersion": 0, - "Build": null - }, - "MinimumApiVersion": "1.15", + "Version": "1.8.3", "Description": "Adds the farmer's birthday to the game.", "UniqueID": "Omegasis.HappyBirthday", "EntryDll": "HappyBirthday.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:520" ] } diff --git a/GeneralMods/HappyBirthday/packages.config b/GeneralMods/HappyBirthday/packages.config deleted file mode 100644 index b8b15c8e..00000000 --- a/GeneralMods/HappyBirthday/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/GeneralMods/MapEvents/EventSystem.cs b/GeneralMods/MapEvents/EventSystem.cs index a173367e..be7b2bfe 100644 --- a/GeneralMods/MapEvents/EventSystem.cs +++ b/GeneralMods/MapEvents/EventSystem.cs @@ -1,42 +1,41 @@ -using EventSystem.Framework; +using EventSystem.Framework; using StardewModdingAPI; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewModdingAPI.Events; namespace EventSystem -{ - /* - *TODO: Make Bed/Sleep Event. - * - * - */ - public class EventSystem: Mod +{ + // TODO: Make Bed/Sleep Event. + public class EventSystem : Mod { public static IModHelper ModHelper; public static IMonitor ModMonitor; public static EventManager eventManager; + + /// The mod entry point, called after the mod is first loaded. + /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { - ModHelper = this.Helper; ModMonitor = this.Monitor; - StardewModdingAPI.Events.GameEvents.UpdateTick += GameEvents_UpdateTick; - StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_AfterLoad; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; } - private void SaveEvents_AfterLoad(object sender, EventArgs e) + /// Raised after the player loads a save slot and the world is initialised. + /// The event sender. + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { eventManager = new EventManager(); } - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// Raised after the game state is updated (≈60 times per second). + /// The event sender. + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { - if (eventManager == null) return; - eventManager.update(); + eventManager?.update(); } } } diff --git a/GeneralMods/MapEvents/EventSystem.csproj b/GeneralMods/MapEvents/EventSystem.csproj index 8dd8ec3a..227d5cbf 100644 --- a/GeneralMods/MapEvents/EventSystem.csproj +++ b/GeneralMods/MapEvents/EventSystem.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ EventSystem v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -92,24 +93,7 @@ - - - - + - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - \ No newline at end of file diff --git a/GeneralMods/MapEvents/Framework/Delegates.cs b/GeneralMods/MapEvents/Framework/Delegates.cs index 617d0080..1447e614 100644 --- a/GeneralMods/MapEvents/Framework/Delegates.cs +++ b/GeneralMods/MapEvents/Framework/Delegates.cs @@ -1,8 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace EventSystem.Framework { diff --git a/GeneralMods/MapEvents/Framework/EventManager.cs b/GeneralMods/MapEvents/Framework/EventManager.cs index e4ddeb32..6be0aedb 100644 --- a/GeneralMods/MapEvents/Framework/EventManager.cs +++ b/GeneralMods/MapEvents/Framework/EventManager.cs @@ -1,9 +1,5 @@ -using StardewValley; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewValley; namespace EventSystem.Framework { @@ -11,111 +7,80 @@ namespace EventSystem.Framework { public Dictionary> mapEvents; - /// - /// Constructor. - /// + /// Construct an instance. public EventManager() { this.mapEvents = new Dictionary>(); - foreach(var v in Game1.locations) - { - addLocation(v.Name, false); - } + foreach (var v in Game1.locations) + this.addLocation(v.Name, false); } - /// - /// Adds an event to the map given the name of the map. - /// - /// - /// - public virtual void addEvent(string mapName,MapEvent mapEvent) - { - foreach(var pair in this.mapEvents) - { - if (pair.Key.Name == mapName) - { - pair.Value.Add(mapEvent); - } - } - } - - /// - /// Adds an event to a map. - /// - /// - /// - public virtual void addEvent(GameLocation Location, MapEvent mapEvent) + /// Adds an event to the map given the name of the map. + public virtual void addEvent(string mapName, MapEvent mapEvent) { foreach (var pair in this.mapEvents) { - if (pair.Key == Location) - { - + if (pair.Key.Name == mapName) pair.Value.Add(mapEvent); - } } } - /// - /// Adds a location to have events handled. - /// - /// The location to handle events. - public virtual void addLocation(GameLocation Location) + /// Adds an event to a map. + public virtual void addEvent(GameLocation location, MapEvent mapEvent) { - EventSystem.ModMonitor.Log("Adding event processing for location: " + Location.Name); - this.mapEvents.Add(Location, new List()); + foreach (var pair in this.mapEvents) + { + if (pair.Key == location) + pair.Value.Add(mapEvent); + } } - /// - /// Adds a location to have events handled. - /// - /// - /// - public virtual void addLocation(GameLocation Location,List Events) + /// Adds a location to have events handled. + /// The location to handle events. + public virtual void addLocation(GameLocation location) { - EventSystem.ModMonitor.Log("Adding event processing for location: " + Location.Name); - this.mapEvents.Add(Location, Events); + EventSystem.ModMonitor.Log($"Adding event processing for location: {location.Name}"); + this.mapEvents.Add(location, new List()); } - /// - /// Adds a location to handle events. - /// - /// The name of the location. Can include farm buildings. + /// Adds a location to have events handled. + public virtual void addLocation(GameLocation location, List events) + { + EventSystem.ModMonitor.Log($"Adding event processing for location: {location.Name}"); + this.mapEvents.Add(location, events); + } + + /// Adds a location to handle events. + /// The name of the location. Can include farm buildings. /// Used if the building is a stucture. True=building. - public virtual void addLocation(string Location,bool isStructure) + public virtual void addLocation(string location, bool isStructure) { - EventSystem.ModMonitor.Log("Adding event processing for location: " + Location); - this.mapEvents.Add(Game1.getLocationFromName(Location,isStructure), new List()); + EventSystem.ModMonitor.Log($"Adding event processing for location: {location}"); + this.mapEvents.Add(Game1.getLocationFromName(location, isStructure), new List()); } - /// - /// Adds a location to have events handled. - /// - /// The name of the location. Can include farm buildings. + /// Adds a location to have events handled. + /// The name of the location. Can include farm buildings. /// Used if the building is a stucture. True=building. - /// A list of pre-initialized events. - public virtual void addLocation(string Location, bool isStructure, List Events) + /// A list of pre-initialized events. + public virtual void addLocation(string location, bool isStructure, List events) { - EventSystem.ModMonitor.Log("Adding event processing for location: " + Location); - this.mapEvents.Add(Game1.getLocationFromName(Location,isStructure), Events); + EventSystem.ModMonitor.Log($"Adding event processing for location: {location}"); + this.mapEvents.Add(Game1.getLocationFromName(location, isStructure), events); } - /// - /// Updates all events associated with the event manager. - /// + /// Updates all events associated with the event manager. public virtual void update() { - List events = new List(); - if (Game1.player == null) return; - if (Game1.hasLoadedGame == false) return; - bool ok=this.mapEvents.TryGetValue(Game1.player.currentLocation, out events); - if (ok == false) return; - else + if (Game1.player == null) + return; + if (!Game1.hasLoadedGame) + return; + + if (this.mapEvents.TryGetValue(Game1.player.currentLocation, out List events)) { - foreach(var v in events) - { + foreach (var v in events) v.update(); - } } } } diff --git a/GeneralMods/MapEvents/Framework/Events/DialogueDisplayEvent.cs b/GeneralMods/MapEvents/Framework/Events/DialogueDisplayEvent.cs index 54e143c1..fec23321 100644 --- a/GeneralMods/MapEvents/Framework/Events/DialogueDisplayEvent.cs +++ b/GeneralMods/MapEvents/Framework/Events/DialogueDisplayEvent.cs @@ -1,19 +1,15 @@ -using EventSystem.Framework.FunctionEvents; -using EventSystem.Framework.Information; +using EventSystem.Framework.FunctionEvents; using Microsoft.Xna.Framework; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace EventSystem.Framework.Events { - public class DialogueDisplayEvent :MapEvent + public class DialogueDisplayEvent : MapEvent { - string dialogue; - public DialogueDisplayEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents,MouseEntryLeaveEvent EntryLeave, string Dialogue) : base(Name, Location, Position) + private readonly string dialogue; + + public DialogueDisplayEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents, MouseEntryLeaveEvent EntryLeave, string Dialogue) + : base(Name, Location, Position) { this.name = Name; this.location = Location; @@ -26,18 +22,15 @@ namespace EventSystem.Framework.Events this.mouseEntryLeaveEvents = EntryLeave; } - public override bool OnLeftClick() { - if (base.OnLeftClick() == false) return false; - if (this.location.isObjectAt((int)this.tilePosition.X*Game1.tileSize, (int)this.tilePosition.Y*Game1.tileSize)) return false; + if (!base.OnLeftClick()) return false; + if (this.location.isObjectAt((int)this.tilePosition.X * Game1.tileSize, (int)this.tilePosition.Y * Game1.tileSize)) return false; Game1.activeClickableMenu = new StardewValley.Menus.DialogueBox(this.dialogue); return true; } - /// - /// Used to update the event and check for interaction. - /// + /// Used to update the event and check for interaction. public override void update() { this.clickEvent(); @@ -45,6 +38,5 @@ namespace EventSystem.Framework.Events this.OnMouseEnter(); this.OnMouseLeave(); } - } } diff --git a/GeneralMods/MapEvents/Framework/Events/WarpEvent.cs b/GeneralMods/MapEvents/Framework/Events/WarpEvent.cs index ac661f48..360f3e3d 100644 --- a/GeneralMods/MapEvents/Framework/Events/WarpEvent.cs +++ b/GeneralMods/MapEvents/Framework/Events/WarpEvent.cs @@ -1,31 +1,23 @@ -using EventSystem.Framework.FunctionEvents; +using EventSystem.Framework.FunctionEvents; using EventSystem.Framework.Information; using Microsoft.Xna.Framework; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace EventSystem.Framework.Events { - /// - /// Used to handle warp events on the map. - /// - public class WarpEvent :MapEvent + /// Used to handle warp events on the map. + public class WarpEvent : MapEvent { - WarpInformation warpInfo; + private readonly WarpInformation warpInfo; - /// - /// Constructor for handling warp events. - /// + /// Constructor for handling warp events. /// The name of the event. /// The game location that this event is located at. /// The x,y tile position of the event. /// The events to occur when the player enters the warp tile before the warp. /// The information for warping the farmer. - public WarpEvent(string Name, GameLocation Location, Vector2 Position, PlayerEvents playerEvents,WarpInformation WarpInfo) : base(Name, Location, Position, playerEvents) + public WarpEvent(string Name, GameLocation Location, Vector2 Position, PlayerEvents playerEvents, WarpInformation WarpInfo) + : base(Name, Location, Position, playerEvents) { this.name = Name; this.location = Location; @@ -36,38 +28,28 @@ namespace EventSystem.Framework.Events this.doesInteractionNeedToRun = true; } - /// - /// Occurs when the player enters the warp tile event position. - /// + /// Occurs when the player enters the warp tile event position. public override bool OnPlayerEnter() { - if (base.OnPlayerEnter() == false) return false; - else - { - - Game1.warpFarmer(this.warpInfo.targetMapName, this.warpInfo.targetX, this.warpInfo.targetY, this.warpInfo.facingDirection, this.warpInfo.isStructure); - return true; - } - } + if (!base.OnPlayerEnter()) + return false; - /// - /// Runs when the player is not on the tile and resets player interaction. - /// - public override bool OnPlayerLeave() - { - if (base.OnPlayerLeave() == false) return false; + Game1.warpFarmer(this.warpInfo.targetMapName, this.warpInfo.targetX, this.warpInfo.targetY, this.warpInfo.facingDirection, this.warpInfo.isStructure); return true; } - /// - /// Used to update the event and check for interaction. - /// + /// Runs when the player is not on the tile and resets player interaction. + public override bool OnPlayerLeave() + { + if (!base.OnPlayerLeave()) return false; + return true; + } + + /// Used to update the event and check for interaction. public override void update() { this.OnPlayerEnter(); this.OnPlayerLeave(); } - - } } diff --git a/GeneralMods/MapEvents/Framework/FunctionEvents/MouseButtonEvents.cs b/GeneralMods/MapEvents/Framework/FunctionEvents/MouseButtonEvents.cs index 634f9086..f2d921e7 100644 --- a/GeneralMods/MapEvents/Framework/FunctionEvents/MouseButtonEvents.cs +++ b/GeneralMods/MapEvents/Framework/FunctionEvents/MouseButtonEvents.cs @@ -1,43 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace EventSystem.Framework.FunctionEvents { - /// - /// Used to handle mouse interactions with button clicks and scrolling the mouse wheel. - /// + /// Used to handle mouse interactions with button clicks and scrolling the mouse wheel. public class MouseButtonEvents { - /// - /// Function that runs when the user left clicks. - /// + /// Function that runs when the user left clicks. public functionEvent onLeftClick; - /// - /// Function that runs when the user right clicks. - /// + + /// Function that runs when the user right clicks. public functionEvent onRightClick; - /// - /// Function that runs when the user scrolls the mouse wheel. - /// + + /// Function that runs when the user scrolls the mouse wheel. public functionEvent onMouseScroll; - /// - /// A constructor used to set a single function to a mouse button. - /// + /// A constructor used to set a single function to a mouse button. /// /// If true the function is set to the left click. If false the function is set to the right click. public MouseButtonEvents(functionEvent clickFunction, bool leftClick) { - if (leftClick == true) this.onLeftClick = clickFunction; + if (leftClick) this.onLeftClick = clickFunction; else this.onRightClick = clickFunction; } - /// - /// A constructor used to map functions to mouse clicks. - /// + /// A constructor used to map functions to mouse clicks. /// A function to be ran when the mouse left clicks this position. /// A function to be ran when the mouse right clicks this position. public MouseButtonEvents(functionEvent OnLeftClick, functionEvent OnRightClick) @@ -46,13 +30,11 @@ namespace EventSystem.Framework.FunctionEvents this.onRightClick = OnRightClick; } - /// - /// A constructor used to map functions to mouse clicks and scrolling the mouse wheel. - /// + /// A constructor used to map functions to mouse clicks and scrolling the mouse wheel. /// A function to be ran when the mouse left clicks this position. /// A function to be ran when the mouse right clicks this position. /// A function to be ran when the user scrolls the mouse - public MouseButtonEvents(functionEvent OnLeftClick,functionEvent OnRightClick, functionEvent OnMouseScroll) + public MouseButtonEvents(functionEvent OnLeftClick, functionEvent OnRightClick, functionEvent OnMouseScroll) { this.onLeftClick = OnLeftClick; this.onRightClick = OnRightClick; diff --git a/GeneralMods/MapEvents/Framework/FunctionEvents/MouseEntryLeaveEvent.cs b/GeneralMods/MapEvents/Framework/FunctionEvents/MouseEntryLeaveEvent.cs index 7ae55635..1a7e408b 100644 --- a/GeneralMods/MapEvents/Framework/FunctionEvents/MouseEntryLeaveEvent.cs +++ b/GeneralMods/MapEvents/Framework/FunctionEvents/MouseEntryLeaveEvent.cs @@ -1,28 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace EventSystem.Framework.FunctionEvents { - /// - /// Used to handle events that happens when a mouse enters/leaves a specified position. - /// + /// Used to handle events that happens when a mouse enters/leaves a specified position. public class MouseEntryLeaveEvent { - /// - /// A function that is called when a mouse enters a certain position. - /// + /// A function that is called when a mouse enters a certain position. public functionEvent onMouseEnter; - /// - /// A function that is called when a mouse leaves a certain position. - /// + + /// A function that is called when a mouse leaves a certain position. public functionEvent onMouseLeave; - /// - /// Constructor. - /// + /// Construct an instance. /// The function that occurs when the mouse enters a certain position. /// The function that occurs when the mouse leaves a certain position. public MouseEntryLeaveEvent(functionEvent OnMouseEnter, functionEvent OnMouseLeave) diff --git a/GeneralMods/MapEvents/Framework/FunctionEvents/PlayerEvents.cs b/GeneralMods/MapEvents/Framework/FunctionEvents/PlayerEvents.cs index e29d55ae..bc30d63d 100644 --- a/GeneralMods/MapEvents/Framework/FunctionEvents/PlayerEvents.cs +++ b/GeneralMods/MapEvents/Framework/FunctionEvents/PlayerEvents.cs @@ -1,30 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace EventSystem.Framework.FunctionEvents { - /// - /// Used to handle various functions that occur on player interaction. - /// + /// Used to handle various functions that occur on player interaction. public class PlayerEvents { - /// - /// Occurs when the player enters the same tile as this event. - /// + /// Occurs when the player enters the same tile as this event. public functionEvent onPlayerEnter; - /// - /// Occurs when the player leaves the same tile as this event. - /// + + /// Occurs when the player leaves the same tile as this event. public functionEvent onPlayerLeave; - /// - /// Constructor. - /// - /// - /// + /// Construct an instance. + /// Occurs when the player enters the same tile as this event. + /// Occurs when the player leaves the same tile as this event. public PlayerEvents(functionEvent OnPlayerEnter, functionEvent OnPlayerLeave) { this.onPlayerEnter = OnPlayerEnter; diff --git a/GeneralMods/MapEvents/Framework/FunctionEvents/functionEvent.cs b/GeneralMods/MapEvents/Framework/FunctionEvents/functionEvent.cs index 896c2050..b3b0ff33 100644 --- a/GeneralMods/MapEvents/Framework/FunctionEvents/functionEvent.cs +++ b/GeneralMods/MapEvents/Framework/FunctionEvents/functionEvent.cs @@ -1,23 +1,15 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using static EventSystem.Framework.Delegates; namespace EventSystem.Framework { - /// - /// Used to pair a function and a parameter list using the super object class to run virtually any function for map events. - /// + /// Used to pair a function and a parameter list using the super object class to run virtually any function for map events. public class functionEvent { public paramFunction function; public List parameters; - /// - /// Constructor. - /// + /// Construct an instance. /// The function to be called when running an event. /// The list of system.objects to be used in the function. Can include objects,strings, ints, etc. Anything can be passed in as a parameter or can be passed in as empty. Passing in null will just create an empty list. public functionEvent(paramFunction Function, List Parameters) @@ -27,17 +19,13 @@ namespace EventSystem.Framework this.parameters = Parameters; } - /// - /// Runs the function with the passed in parameters. - /// + /// Runs the function with the passed in parameters. public void run() { this.function.Invoke(this.parameters); } - /// - /// Simply swaps out the old parameters list for a new one. - /// + /// Simply swaps out the old parameters list for a new one. /// public void updateParameters(List newParameters) { diff --git a/GeneralMods/MapEvents/Framework/Information/WarpInformation.cs b/GeneralMods/MapEvents/Framework/Information/WarpInformation.cs index 7cda2745..f63a4031 100644 --- a/GeneralMods/MapEvents/Framework/Information/WarpInformation.cs +++ b/GeneralMods/MapEvents/Framework/Information/WarpInformation.cs @@ -1,14 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace EventSystem.Framework.Information { - /// - /// Used to store all of the information necessary to warp the farmer. - /// + /// Used to store all of the information necessary to warp the farmer. public class WarpInformation { public string targetMapName; @@ -17,15 +9,13 @@ namespace EventSystem.Framework.Information public int facingDirection; public bool isStructure; - /// - /// Constructor used to bundle together necessary information to warp the player character. - /// + /// Constructor used to bundle together necessary information to warp the player character. /// The target map name to warp the farmer to. /// The target X location on the map to warp the farmer to. /// The target Y location on the map to warp the farmer to. /// The facing direction for the farmer to be facing after the warp. /// Used to determine the position to be warped to when leaving a structure. - public WarpInformation(string MapName, int TargetX,int TargetY, int FacingDirection, bool IsStructure) + public WarpInformation(string MapName, int TargetX, int TargetY, int FacingDirection, bool IsStructure) { this.targetMapName = MapName; this.targetX = TargetX; diff --git a/GeneralMods/MapEvents/Framework/MapEvent.cs b/GeneralMods/MapEvents/Framework/MapEvent.cs index fbf2913d..90e88983 100644 --- a/GeneralMods/MapEvents/Framework/MapEvent.cs +++ b/GeneralMods/MapEvents/Framework/MapEvent.cs @@ -1,27 +1,17 @@ -using EventSystem.Framework.FunctionEvents; +using EventSystem.Framework.FunctionEvents; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace EventSystem.Framework { - /// - /// Base class used to handle map tile events. - /// + /// Base class used to handle map tile events. public class MapEvent { - /// - /// //MAKE NAME FOR EVENTS - /// - + /// //MAKE NAME FOR EVENTS public string name; - + public Vector2 tilePosition; public GameLocation location; @@ -41,84 +31,64 @@ namespace EventSystem.Framework *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #region + /// Empty Constructor. + public MapEvent() { } - - /// - /// Empty Constructor - /// - public MapEvent() - { - - } - - /// - /// A simple map event that doesn't do anything. - /// - /// - /// - public MapEvent(string name,GameLocation Location,Vector2 Position) + /// A simple map event that doesn't do anything. + public MapEvent(string name, GameLocation location, Vector2 position) { this.name = name; - this.location = Location; - this.tilePosition = Position; - } - - /// - /// A simple map function that runs when the player enters and leaves a tile. Set values to null for nothing to happen. - /// - /// The game location where the event is. I.E Farm, Town, Mine etc. - /// The x,y position on the map the event is. - /// Handles various events that runs when the player enters/leaves a tile, etc. - - public MapEvent(string name,GameLocation Location,Vector2 position, PlayerEvents PlayerEvents) - { - this.name = name; - this.location = Location; + this.location = location; this.tilePosition = position; - this.playerEvents = PlayerEvents; } - /// - /// A constructor that handles when the mouse leaves and enters a tile. - /// - /// The game location where the event is. - /// The x,y position of the tile at the game location. - /// A class used to handle mouse entry/leave events. - public MapEvent(string name,GameLocation Location, Vector2 Position, MouseEntryLeaveEvent mouseEvents) + /// A simple map function that runs when the player enters and leaves a tile. Set values to null for nothing to happen. + /// The game location where the event is. I.E Farm, Town, Mine etc. + /// The x,y position on the map the event is. + /// Handles various events that runs when the player enters/leaves a tile, etc. + public MapEvent(string name, GameLocation location, Vector2 position, PlayerEvents playerEvents) { this.name = name; - this.location = Location; - this.tilePosition = Position; + this.location = location; + this.tilePosition = position; + this.playerEvents = playerEvents; + } + + /// A constructor that handles when the mouse leaves and enters a tile. + /// The game location where the event is. + /// The x,y position of the tile at the game location. + /// A class used to handle mouse entry/leave events. + public MapEvent(string name, GameLocation location, Vector2 position, MouseEntryLeaveEvent mouseEvents) + { + this.name = name; + this.location = location; + this.tilePosition = position; this.mouseEntryLeaveEvents = mouseEvents; } - /// - /// A constructor that handles when the mouse leaves and enters a tile. - /// - /// The game location where the event is. - /// The x,y position of the tile at the game location. + /// A constructor that handles when the mouse leaves and enters a tile. + /// The game location where the event is. + /// The x,y position of the tile at the game location. /// A class used to handle mouse click/scroll events. - public MapEvent(string name,GameLocation Location, Vector2 Position, MouseButtonEvents mouseEvents) + public MapEvent(string name, GameLocation location, Vector2 position, MouseButtonEvents mouseEvents) { this.name = name; - this.location = Location; - this.tilePosition = Position; + this.location = location; + this.tilePosition = position; this.mouseButtonEvents = mouseEvents; } - /// - /// A constructor encapsulating player, mouse button, and mouse entry events. - /// - /// The game location for which the event is located. I.E Town, Farm, etc. - /// The x,y cordinates for this event to be located at. + /// A constructor encapsulating player, mouse button, and mouse entry events. + /// The game location for which the event is located. I.E Town, Farm, etc. + /// The x,y cordinates for this event to be located at. /// The events that occur associated with the player. I.E player entry, etc. /// The events associated with clicking a mouse button while on this tile. /// The events that occur when the mouse enters or leaves the same tile position as this event. - public MapEvent(string name,GameLocation Location, Vector2 Position, PlayerEvents playerEvents, MouseButtonEvents mouseButtonEvents, MouseEntryLeaveEvent mouseEntryLeaveEvents) + public MapEvent(string name, GameLocation location, Vector2 position, PlayerEvents playerEvents, MouseButtonEvents mouseButtonEvents, MouseEntryLeaveEvent mouseEntryLeaveEvents) { this.name = name; - this.location = Location; - this.tilePosition = Position; + this.location = location; + this.tilePosition = position; this.playerEvents = playerEvents; this.mouseButtonEvents = mouseButtonEvents; this.mouseEntryLeaveEvents = mouseEntryLeaveEvents; @@ -126,129 +96,109 @@ namespace EventSystem.Framework #endregion - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Player related functions + /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Player related functions - *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ #region - /// - /// Occurs when the player enters the same tile as this event. The function associated with this event is then ran. - /// + /// Occurs when the player enters the same tile as this event. The function associated with this event is then ran. public virtual bool OnPlayerEnter() { if (this.playerEvents == null) return false; - if (isPlayerOnTile() == true && this.doesInteractionNeedToRun==true) + if (this.isPlayerOnTile() && this.doesInteractionNeedToRun) { this.playerOnTile = true; this.doesInteractionNeedToRun = false; - if (this.playerEvents.onPlayerEnter != null) this.playerEvents.onPlayerEnter.run(); + this.playerEvents.onPlayerEnter?.run(); return true; } return false; } - /// - /// Occurs when the player leaves the same tile that this event is on. The function associated with thie event is then ran. - /// + /// Occurs when the player leaves the same tile that this event is on. The function associated with thie event is then ran. public virtual bool OnPlayerLeave() { if (this.playerEvents == null) return false; - if (isPlayerOnTile() == false && this.playerOnTile==true){ + if (!this.isPlayerOnTile() && this.playerOnTile) + { this.playerOnTile = false; this.doesInteractionNeedToRun = true; - if (this.playerEvents.onPlayerLeave != null) this.playerEvents.onPlayerLeave.run(); + this.playerEvents.onPlayerLeave?.run(); return true; } return false; } - /// - /// Checks if the player is on the same tile as this event. - /// - /// + /// Checks if the player is on the same tile as this event. public virtual bool isPlayerOnTile() { - if (Game1.player.getTileX() == this.tilePosition.X && Game1.player.getTileY() == this.tilePosition.Y) return true; - else return false; + return + Game1.player.getTileX() == this.tilePosition.X + && Game1.player.getTileY() == this.tilePosition.Y; } #endregion - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Mouse related functions + /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Mouse related functions - *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ #region - /// - /// Occurs when the player left clicks the same tile that this event is on. - /// + /// Occurs when the player left clicks the same tile that this event is on. public virtual bool OnLeftClick() { - if (this.mouseOnTile==false) return false; + if (!this.mouseOnTile) return false; if (this.mouseButtonEvents == null) return false; - if (this.mouseButtonEvents.onLeftClick != null) this.mouseButtonEvents.onLeftClick.run(); + this.mouseButtonEvents.onLeftClick?.run(); return true; } - /// - /// Occurs when the player right clicks the same tile that this event is on. - /// + /// Occurs when the player right clicks the same tile that this event is on. public virtual bool OnRightClick() { - if (this.mouseOnTile == false) return false; + if (!this.mouseOnTile) return false; if (this.mouseButtonEvents == null) return false; - if (this.mouseButtonEvents.onRightClick != null) this.mouseButtonEvents.onRightClick.run(); + this.mouseButtonEvents.onRightClick?.run(); return true; } - /// - /// Occurs when the mouse tile position is the same as this event's x,y position. - /// + /// Occurs when the mouse tile position is the same as this event's x,y position. public virtual bool OnMouseEnter() { if (this.mouseEntryLeaveEvents == null) return false; - if (isMouseOnTile()) + if (this.isMouseOnTile()) { this.mouseOnTile = true; - if (this.mouseEntryLeaveEvents.onMouseEnter != null) this.mouseEntryLeaveEvents.onMouseEnter.run(); + this.mouseEntryLeaveEvents.onMouseEnter?.run(); return true; } return false; } - /// - /// Occurs when the mouse tile position leaves the the same x,y position as this event. - /// + /// Occurs when the mouse tile position leaves the the same x,y position as this event. public virtual bool OnMouseLeave() { if (this.mouseEntryLeaveEvents == null) return false; - if (isMouseOnTile() == false && this.mouseOnTile == true) + if (!this.isMouseOnTile() && this.mouseOnTile) { this.mouseOnTile = false; - if (this.mouseEntryLeaveEvents.onMouseLeave != null) this.mouseEntryLeaveEvents.onMouseLeave.run(); + this.mouseEntryLeaveEvents.onMouseLeave?.run(); return true; } return false; } - /// - /// UNUSED!!!! - /// Occurs when the mouse is on the same position as the tile AND the user scrolls the mouse wheel. - /// + /// UNUSED!!!! Occurs when the mouse is on the same position as the tile AND the user scrolls the mouse wheel. public virtual bool OnMouseScroll() { - - if (isMouseOnTile() == false) return false; - if (this.mouseButtonEvents.onMouseScroll != null) this.mouseButtonEvents.onMouseScroll.run(); + if (!this.isMouseOnTile()) return false; + this.mouseButtonEvents.onMouseScroll?.run(); return true; } - /// - /// Checks if the mouse is on the tile. - /// - /// + /// Checks if the mouse is on the tile. public virtual bool isMouseOnTile() { Vector2 mousePosition = Game1.currentCursorTile; @@ -256,30 +206,27 @@ namespace EventSystem.Framework return false; } - /// - /// Occurs when the tile is clicked. Runs the appropriate event. - /// + /// Occurs when the tile is clicked. Runs the appropriate event. public virtual void clickEvent() { - if (this.mouseOnTile == false) return; - var mouseState=Mouse.GetState(); - if (mouseState.LeftButton == ButtonState.Pressed) OnLeftClick(); - if (mouseState.RightButton == ButtonState.Pressed) OnRightClick(); + if (!this.mouseOnTile) return; + var mouseState = Mouse.GetState(); + if (mouseState.LeftButton == ButtonState.Pressed) + this.OnLeftClick(); + if (mouseState.RightButton == ButtonState.Pressed) + this.OnRightClick(); } -#endregion + #endregion - - /// - /// Used to check if any sort of events need to run on this tile right now. - /// + /// Used to check if any sort of events need to run on this tile right now. public virtual void update() { if (Game1.activeClickableMenu != null) return; - clickEvent(); //click events - OnPlayerEnter(); //player enter events - OnPlayerLeave(); //player leave events - OnMouseEnter(); //on mouse enter events - OnMouseLeave(); //on mouse leave events. + this.clickEvent(); //click events + this.OnPlayerEnter(); //player enter events + this.OnPlayerLeave(); //player leave events + this.OnMouseEnter(); //on mouse enter events + this.OnMouseLeave(); //on mouse leave events. } } } diff --git a/GeneralMods/MapEvents/manifest.json b/GeneralMods/MapEvents/manifest.json index 4579d6f3..d979dd05 100644 --- a/GeneralMods/MapEvents/manifest.json +++ b/GeneralMods/MapEvents/manifest.json @@ -1,10 +1,10 @@ { - "Name": "EventSystem", + "Name": "Event System", "Author": "Alpha_Omegasis", "Version": "0.1.0", "Description": "A system to manage different events that can happen on the map.", "UniqueID": "Omegasis.EventSystem", "EntryDll": "EventSystem.dll", - "MinimumApiVersion": "2.0", - "UpdateKeys": [ ] + "MinimumApiVersion": "2.10.1", + "UpdateKeys": [] } diff --git a/GeneralMods/MapEvents/packages.config b/GeneralMods/MapEvents/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/MapEvents/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/MoreRain/Framework/ModConfig.cs b/GeneralMods/MoreRain/Framework/ModConfig.cs index ce34e80f..791216b4 100644 --- a/GeneralMods/MoreRain/Framework/ModConfig.cs +++ b/GeneralMods/MoreRain/Framework/ModConfig.cs @@ -1,4 +1,4 @@ -namespace Omegasis.MoreRain.Framework +namespace Omegasis.MoreRain.Framework { /// The mod configuration. internal class ModConfig diff --git a/GeneralMods/MoreRain/MoreRain.cs b/GeneralMods/MoreRain/MoreRain.cs index 8b1adfbd..4194842a 100644 --- a/GeneralMods/MoreRain/MoreRain.cs +++ b/GeneralMods/MoreRain/MoreRain.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Omegasis.MoreRain.Framework; using StardewModdingAPI; @@ -11,7 +11,7 @@ namespace Omegasis.MoreRain public class MoreRain : Mod { /********* - ** Properties + ** Fields *********/ /// The weathers that can be safely overridden. private readonly HashSet NormalWeathers = new HashSet { Game1.weather_sunny, Game1.weather_rain, Game1.weather_lightning, Game1.weather_debris, Game1.weather_snow }; @@ -29,26 +29,26 @@ namespace Omegasis.MoreRain { this.Config = helper.ReadConfig(); - SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; - SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; + helper.Events.GameLoop.Saving += this.OnSaving; } /********* ** Private methods *********/ - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - private void SaveEvents_AfterLoad(object sender, EventArgs e) + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { this.HandleNewDay(); } - /// The method invoked before the game is saved. + /// Raised before the game begins writes data to the save file (except the initial save creation). /// The event sender. - /// The event data. - private void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + private void OnSaving(object sender, SavingEventArgs e) { this.HandleNewDay(); } @@ -88,7 +88,6 @@ namespace Omegasis.MoreRain this.VerboseLog("It will be stormy tomorrow."); return; } - break; case "summer": @@ -143,7 +142,7 @@ namespace Omegasis.MoreRain } } - /// Log a message if is false. + /// Log a message if is false. /// The message to log. private void VerboseLog(string message) { diff --git a/GeneralMods/MoreRain/MoreRain.csproj b/GeneralMods/MoreRain/MoreRain.csproj index 3b5337c8..1517a05e 100644 --- a/GeneralMods/MoreRain/MoreRain.csproj +++ b/GeneralMods/MoreRain/MoreRain.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ MoreRain v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -81,19 +82,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/MoreRain/manifest.json b/GeneralMods/MoreRain/manifest.json index 481fc266..8bc0f494 100644 --- a/GeneralMods/MoreRain/manifest.json +++ b/GeneralMods/MoreRain/manifest.json @@ -1,10 +1,10 @@ { "Name": "More Rain", "Author": "Alpha_Omegasis", - "Version": "1.6.1", + "Version": "1.7.0", "Description": "Change how much it rains in the game.", "UniqueID": "Omegasis.MoreRain", "EntryDll": "MoreRain.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:441" ] } diff --git a/GeneralMods/MoreRain/packages.config b/GeneralMods/MoreRain/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/MoreRain/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/MuseumRearranger/Framework/ModConfig.cs b/GeneralMods/MuseumRearranger/Framework/ModConfig.cs index f14ea7ad..e020ccb7 100644 --- a/GeneralMods/MuseumRearranger/Framework/ModConfig.cs +++ b/GeneralMods/MuseumRearranger/Framework/ModConfig.cs @@ -1,12 +1,14 @@ -namespace Omegasis.MuseumRearranger.Framework +using StardewModdingAPI; + +namespace Omegasis.MuseumRearranger.Framework { /// The mod configuration. internal class ModConfig { /// The key which shows the museum rearranging menu. - public string ShowMenuKey { get; set; } = "R"; + public SButton ShowMenuKey { get; set; } = SButton.R; /// The key which toggles the inventory box when the menu is open. - public string ToggleInventoryKey { get; set; } = "T"; + public SButton ToggleInventoryKey { get; set; } = SButton.T; } } diff --git a/GeneralMods/MuseumRearranger/Framework/NewMuseumMenu.cs b/GeneralMods/MuseumRearranger/Framework/NewMuseumMenu.cs index dcef035a..b24f3e2b 100644 --- a/GeneralMods/MuseumRearranger/Framework/NewMuseumMenu.cs +++ b/GeneralMods/MuseumRearranger/Framework/NewMuseumMenu.cs @@ -1,4 +1,4 @@ -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI; using StardewValley; @@ -11,7 +11,7 @@ namespace Omegasis.MuseumRearranger.Framework internal class NewMuseumMenu : MuseumMenu { /********* - ** Properties + ** Fields *********/ /// Whether to show the inventory screen. private bool ShowInventory = true; diff --git a/GeneralMods/MuseumRearranger/MuseumRearranger.cs b/GeneralMods/MuseumRearranger/MuseumRearranger.cs index 98df59ee..f9014d3f 100644 --- a/GeneralMods/MuseumRearranger/MuseumRearranger.cs +++ b/GeneralMods/MuseumRearranger/MuseumRearranger.cs @@ -1,4 +1,4 @@ -using Omegasis.MuseumRearranger.Framework; +using Omegasis.MuseumRearranger.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; @@ -10,7 +10,7 @@ namespace Omegasis.MuseumRearranger public class MuseumRearranger : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -28,23 +28,23 @@ namespace Omegasis.MuseumRearranger { this.Config = helper.ReadConfig(); - ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; + helper.Events.Input.ButtonPressed += this.OnButtonPressed; } /********* ** Private methods *********/ - /// The method invoked when the presses a keyboard button. + /// Raised after the player presses a button on the keyboard, controller, or mouse. /// The event sender. - /// The event data. - private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) + /// The event arguments. + private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { if (!Context.IsWorldReady) return; // open menu - if (e.KeyPressed.ToString() == this.Config.ShowMenuKey) + if (e.Button == this.Config.ShowMenuKey) { if (Game1.activeClickableMenu != null) return; @@ -55,7 +55,7 @@ namespace Omegasis.MuseumRearranger } // toggle inventory box - if (e.KeyPressed.ToString() == this.Config.ToggleInventoryKey) + if (e.Button == this.Config.ToggleInventoryKey) this.OpenMenu?.ToggleInventory(); } } diff --git a/GeneralMods/MuseumRearranger/MuseumRearranger.csproj b/GeneralMods/MuseumRearranger/MuseumRearranger.csproj index 07ec6f76..7f1ced70 100644 --- a/GeneralMods/MuseumRearranger/MuseumRearranger.csproj +++ b/GeneralMods/MuseumRearranger/MuseumRearranger.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ MuseumRearranger v4.5 512 - - true @@ -69,6 +67,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -84,19 +85,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/MuseumRearranger/manifest.json b/GeneralMods/MuseumRearranger/manifest.json index 4f390cda..7ed4041d 100644 --- a/GeneralMods/MuseumRearranger/manifest.json +++ b/GeneralMods/MuseumRearranger/manifest.json @@ -1,10 +1,10 @@ { "Name": "Museum Rearranger", "Author": "Alpha_Omegasis", - "Version": "1.6.0", + "Version": "1.7.0", "Description": "Lets you rearrange the museum without needing to donate something.", "UniqueID": "Omegasis.MuseumRearranger", "EntryDll": "MuseumRearranger.dll", - "MinimumApiVersion": "2.3", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:428" ] } diff --git a/GeneralMods/MuseumRearranger/packages.config b/GeneralMods/MuseumRearranger/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/MuseumRearranger/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/NightOwl/Framework/ModConfig.cs b/GeneralMods/NightOwl/Framework/ModConfig.cs index 7dfcbed4..43edd686 100644 --- a/GeneralMods/NightOwl/Framework/ModConfig.cs +++ b/GeneralMods/NightOwl/Framework/ModConfig.cs @@ -1,4 +1,4 @@ -namespace Omegasis.NightOwl.Framework +namespace Omegasis.NightOwl.Framework { /// The mod configuration. internal class ModConfig @@ -25,9 +25,7 @@ public bool KeepStaminaAfterCollapse { get; set; } = true; - /// - /// Whether or not to use the internal NightFish asset editor. When false, it will just use the Fish.xnb file. - /// + /// Whether or not to use the internal NightFish asset editor. When false, it will just use the Fish.xnb file. public bool UseInternalNightFishAssetEditor { get; set; } = true; } } diff --git a/GeneralMods/NightOwl/Framework/NightFishing.cs b/GeneralMods/NightOwl/Framework/NightFishing.cs index 79541d6b..ddb4c1a1 100644 --- a/GeneralMods/NightOwl/Framework/NightFishing.cs +++ b/GeneralMods/NightOwl/Framework/NightFishing.cs @@ -1,22 +1,22 @@ -using StardewModdingAPI; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewModdingAPI; namespace Omegasis.NightOwl.Framework { class NightFishing : IAssetEditor { + /// Get whether this instance can edit the given asset. + /// Basic metadata about the asset being loaded. public bool CanEdit(IAssetInfo asset) { return asset.AssetNameEquals(@"Data\Fish"); } + /// Edit a matched asset. + /// A helper which encapsulates metadata about an asset and enables changes to it. public void Edit(IAssetData asset) { - Dictionary nightFish=new Dictionary // (T)(object) is a trick to cast anything to T if we know it's compatible + Dictionary nightFish = new Dictionary { [128] = "Pufferfish/80/floater/1/36/1200 1600/summer/sunny/690 .4 685 .1/4/.3/.5/0", [129] = "Anchovy/30/dart/1/16/600 3000/spring fall/both/682 .2/1/.25/.3/0", @@ -82,10 +82,10 @@ namespace Omegasis.NightOwl.Framework [799] = "Spook Fish/60/dart/8/25/600 3000/spring summer fall winter/both/685 .35/3/.4/.1/0", [800] = "Blobfish/75/floater/8/25/600 3000/spring summer fall winter/both/685 .35/3/.4/.1/0", }; - foreach (KeyValuePair pair in nightFish) { - asset.AsDictionary().Set(pair.Key, pair.Value); - } - } + IDictionary data = asset.AsDictionary().Data; + foreach (KeyValuePair pair in nightFish) + data[pair.Key] = pair.Value; + } } } diff --git a/GeneralMods/NightOwl/NightOwl.cs b/GeneralMods/NightOwl/NightOwl.cs index eb4a978e..86aeaa71 100644 --- a/GeneralMods/NightOwl/NightOwl.cs +++ b/GeneralMods/NightOwl/NightOwl.cs @@ -1,6 +1,5 @@ -using System; +using System; using System.Collections.Generic; -using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Netcode; @@ -11,22 +10,18 @@ using StardewValley; using StardewValley.Characters; using StardewValley.Locations; -/*TODO: -Issues: --Mail can't be wiped without destroying all mail. --Lighting transition does not work if it is raining. - -set the weather to clear if you are stayig up late. - -transition still doesnt work. However atleast it is dark now. - --Known glitched -*/ +// TODO: +// -Mail can't be wiped without destroying all mail. +// -Lighting transition does not work if it is raining. +// -set the weather to clear if you are stayig up late. +// -transition still doesnt work. However atleast it is dark now. namespace Omegasis.NightOwl { /// The mod entry point. public class NightOwl : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -64,32 +59,21 @@ namespace Omegasis.NightOwl /// The player's health before they collapsed. private int PreCollapseHealth; - /// - /// Checks if the player was bathing or not before passing out. - /// + /// Checks if the player was bathing or not before passing out. private bool isBathing; - /// - /// Checks if the player was in their swimsuit before passing out. - /// + /// Checks if the player was in their swimsuit before passing out. private bool isInSwimSuit; - - /// - /// The horse the player was riding before they collapsed. - /// + + /// The horse the player was riding before they collapsed. private Horse horse; - /// - /// Determines whehther or not to rewarp the player's horse to them. - /// + /// Determines whehther or not to rewarp the player's horse to them. private bool shouldWarpHorse; - /// - /// Event in the night taht simulates the earthquake event that should happen. - /// + /// Event in the night taht simulates the earthquake event that should happen. StardewValley.Events.SoundInTheNightEvent eve; - private List oldAnimalHappiness; @@ -103,100 +87,84 @@ namespace Omegasis.NightOwl this.oldAnimalHappiness = new List(); this.Config = helper.ReadConfig(); - if (Config.UseInternalNightFishAssetEditor) - { + if (this.Config.UseInternalNightFishAssetEditor) this.Helper.Content.AssetEditors.Add(new NightFishing()); - } - TimeEvents.TimeOfDayChanged += this.TimeEvents_TimeOfDayChanged; - TimeEvents.AfterDayStarted += this.TimeEvents_AfterDayStarted; - SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; - SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; - GameEvents.FourthUpdateTick += this.GameEvents_FourthUpdateTick; - GameEvents.UpdateTick += GameEvents_UpdateTick; - shouldWarpHorse = false; - } + helper.Events.GameLoop.TimeChanged += this.OnTimeChanged; + helper.Events.GameLoop.DayStarted += this.OnDayStarted; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; + helper.Events.GameLoop.Saving += this.OnSaving; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + this.shouldWarpHorse = false; + } /********* ** Private methods *********/ - - /// - /// Updates the earthquake event. - /// - /// - /// - private void GameEvents_UpdateTick(object sender, EventArgs e) - { - if (eve == null) return; - else - { - eve.tickUpdate(Game1.currentGameTime); - } - } - - /// The method invoked every fourth game update (roughly 15 times per second). + /// Raised after the game state is updated (≈60 times per second). /// The event sender. - /// The event data. - public void GameEvents_FourthUpdateTick(object sender, EventArgs e) + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { - try - { - // reset position after collapse - if (Context.IsWorldReady && this.JustStartedNewDay && this.Config.KeepPositionAfterCollapse) - { - if (this.PreCollapseMap != null) - Game1.warpFarmer(this.PreCollapseMap, this.PreCollapseTile.X, this.PreCollapseTile.Y, false); + this.eve?.tickUpdate(Game1.currentGameTime); - this.PreCollapseMap = null; - this.JustStartedNewDay = false; - this.JustCollapsed = false; + if (e.IsMultipleOf(4)) // ≈15 times per second + { + try + { + // reset position after collapse + if (Context.IsWorldReady && this.JustStartedNewDay && this.Config.KeepPositionAfterCollapse) + { + if (this.PreCollapseMap != null) + Game1.warpFarmer(this.PreCollapseMap, this.PreCollapseTile.X, this.PreCollapseTile.Y, false); + + this.PreCollapseMap = null; + this.JustStartedNewDay = false; + this.JustCollapsed = false; + } + } + catch (Exception ex) + { + this.Monitor.Log(ex.ToString(), LogLevel.Error); + this.WriteErrorLog(); } } - catch (Exception ex) - { - this.Monitor.Log(ex.ToString(), LogLevel.Error); - this.WriteErrorLog(); - } } - - /// The method invoked before the game saves. + + /// Raised before the game begins writes data to the save file (except the initial save creation). /// The event sender. - /// The event data. - public void SaveEvents_BeforeSave(object sender, EventArgs e) + /// The event arguments. + public void OnSaving(object sender, SavingEventArgs e) { int collapseFee = 0; string[] passOutFees = Game1.player.mailbox .Where(p => p.Contains("passedOut")) .ToArray(); - for (int idx=0; idx< passOutFees.Length; idx++) - { - string[] msg = passOutFees[idx].Split(' '); - collapseFee += Int32.Parse(msg[1]); - } - - if (this.Config.KeepMoneyAfterCollapse) - { - Game1.player.money += collapseFee; - } - + foreach (string fee in passOutFees) + { + string[] msg = fee.Split(' '); + collapseFee += int.Parse(msg[1]); + } + + if (this.Config.KeepMoneyAfterCollapse) + Game1.player.money += collapseFee; } - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - public void SaveEvents_AfterLoad(object sender, EventArgs e) + /// The event arguments. + public void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { this.IsUpLate = false; this.JustStartedNewDay = false; this.JustCollapsed = false; } - /// The method invoked when a new day starts. + /// Raised after the game begins a new day (including when the player loads a save). /// The event sender. - /// The event data. - public void TimeEvents_AfterDayStarted(object sender, EventArgs e) + /// The event arguments. + public void OnDayStarted(object sender, DayStartedEventArgs e) { try { @@ -213,51 +181,39 @@ namespace Omegasis.NightOwl if (this.Config.KeepHealthAfterCollapse) Game1.player.health = this.PreCollapseHealth; if (this.Config.KeepPositionAfterCollapse) - if (Game1.weddingToday == false) - { + { + if (!Game1.weddingToday) Game1.warpFarmer(this.PreCollapseMap, this.PreCollapseTile.X, this.PreCollapseTile.Y, false); - } - if (horse != null && shouldWarpHorse==true) - { - Game1.warpCharacter(horse, Game1.player.currentLocation, Game1.player.position); - shouldWarpHorse = false; } - if (isInSwimSuit) + + if (this.horse != null && this.shouldWarpHorse) { + Game1.warpCharacter(this.horse, Game1.player.currentLocation, Game1.player.position); + this.shouldWarpHorse = false; + } + if (this.isInSwimSuit) Game1.player.changeIntoSwimsuit(); - } - if (isBathing) - { + if (this.isBathing) Game1.player.swimming.Value = true; - } + //Reflction to ensure that the railroad becomes properly unblocked. if (Game1.dayOfMonth == 1 && Game1.currentSeason == "summer" && Game1.year == 1) { Mountain mountain = (Mountain)Game1.getLocationFromName("Mountain"); - var reflect2 = Helper.Reflection.GetField(mountain, "railroadAreaBlocked", true); - var netBool2 = reflect2.GetValue(); + NetBool netBool2 = this.Helper.Reflection.GetField(mountain, "railroadAreaBlocked").GetValue(); netBool2.Value = false; - reflect2.SetValue(netBool2); + this.Helper.Reflection.GetField(mountain, "railroadBlockRect").SetValue(Rectangle.Empty); - var reflect3 = Helper.Reflection.GetField(mountain, "railroadBlockRect", true); - var netBool3 = reflect3.GetValue(); - netBool3 = new Rectangle(0, 0, 0, 0); - reflect3.SetValue(netBool3); - - - eve = new StardewValley.Events.SoundInTheNightEvent(4); - eve.setUp(); - eve.makeChangesToLocation(); - + this.eve = new StardewValley.Events.SoundInTheNightEvent(4); + this.eve.setUp(); + this.eve.makeChangesToLocation(); } } - if(Game1.currentSeason!="spring" && Game1.year >= 1) - { - clearRailRoadBlock(); - } + if (Game1.currentSeason != "spring" && Game1.year >= 1) + this.clearRailRoadBlock(); // delete annoying charge messages (if only I could do this with mail IRL) if (this.Config.SkipCollapseMail) @@ -280,29 +236,21 @@ namespace Omegasis.NightOwl } } - /// - /// If the user for this mod never gets the event that makes the railroad blok go away we will always force it to go away if they have met the conditions for it. I.E not being in spring of year 1. - /// + /// If the user for this mod never gets the event that makes the railroad blok go away we will always force it to go away if they have met the conditions for it. I.E not being in spring of year 1. private void clearRailRoadBlock() { Mountain mountain = (Mountain)Game1.getLocationFromName("Mountain"); - var reflect2 = Helper.Reflection.GetField(mountain, "railroadAreaBlocked", true); - var netBool2 = reflect2.GetValue(); + var netBool2 = this.Helper.Reflection.GetField(mountain, "railroadAreaBlocked").GetValue(); netBool2.Value = false; - reflect2.SetValue(netBool2); - - var reflect3 = Helper.Reflection.GetField(mountain, "railroadBlockRect", true); - var netBool3 = reflect3.GetValue(); - netBool3 = new Rectangle(0, 0, 0, 0); - reflect3.SetValue(netBool3); + this.Helper.Reflection.GetField(mountain, "railroadBlockRect").SetValue(Rectangle.Empty); } - /// The method invoked when changes. + /// Raised after the in-game clock time changes. /// The event sender. - /// The event data. - private void TimeEvents_TimeOfDayChanged(object sender, EventArgsIntChanged e) + /// The event arguments. + private void OnTimeChanged(object sender, TimeChangedEventArgs e) { if (!Context.IsWorldReady) return; @@ -322,11 +270,10 @@ namespace Omegasis.NightOwl Game1.isRaining = false; // remove rain, otherwise lighting gets screwy Game1.updateWeatherIcon(); Game1.timeOfDay = 150; //change it from 1:50 am late, to 1:50 am early - foreach(FarmAnimal animal in Game1.getFarm().getAllFarmAnimals()) + foreach (FarmAnimal animal in Game1.getFarm().getAllFarmAnimals()) { this.oldAnimalHappiness.Add(animal.happiness); } - } // collapse player at 6am to save & reset @@ -343,15 +290,11 @@ namespace Omegasis.NightOwl if (character is Horse) { (character as Horse).dismount(); - horse = (character as Horse); - shouldWarpHorse = true; + this.horse = (character as Horse); + this.shouldWarpHorse = true; } - - } - catch (Exception err) - { - } + catch { } } } this.JustCollapsed = true; @@ -366,7 +309,6 @@ namespace Omegasis.NightOwl this.isBathing = Game1.player.swimming.Value; - if (Game1.currentMinigame != null) Game1.currentMinigame = null; @@ -375,14 +317,12 @@ namespace Omegasis.NightOwl Game1.timeOfDay += 2400; //Recalculate for the sake of technically being up a whole day. //Reset animal happiness since it drains over night. - for(int i=0; i < oldAnimalHappiness.Count; i++) + for (int i = 0; i < this.oldAnimalHappiness.Count; i++) { - Game1.getFarm().getAllFarmAnimals()[i].happiness.Value = oldAnimalHappiness[i].Value; + Game1.getFarm().getAllFarmAnimals()[i].happiness.Value = this.oldAnimalHappiness[i].Value; } Game1.player.startToPassOut(); - - } } catch (Exception ex) @@ -408,14 +348,10 @@ namespace Omegasis.NightOwl this.PreCollapseStamina, this.PreCollapseHealth }; - string path = Path.Combine(this.Helper.DirectoryPath, "Error_Logs", "Mod_State.json"); - this.Helper.WriteJsonFile(path, state); + this.Helper.Data.WriteJsonFile("Error_Logs/Mod_State.json", state); } - /// - /// Try and emulate the old Game1.shouldFarmerPassout logic. - /// - /// + /// Try and emulate the old Game1.shouldFarmerPassout logic. public bool shouldFarmerPassout() { if (Game1.player.stamina <= 0 || Game1.player.health <= 0 || Game1.timeOfDay >= 2600) return true; diff --git a/GeneralMods/NightOwl/NightOwl.csproj b/GeneralMods/NightOwl/NightOwl.csproj index a744fce1..7c0f46b8 100644 --- a/GeneralMods/NightOwl/NightOwl.csproj +++ b/GeneralMods/NightOwl/NightOwl.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ NightOwl v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -87,19 +88,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/NightOwl/manifest.json b/GeneralMods/NightOwl/manifest.json index d937a0fe..b7a37179 100644 --- a/GeneralMods/NightOwl/manifest.json +++ b/GeneralMods/NightOwl/manifest.json @@ -1,10 +1,10 @@ { "Name": "Night Owl", "Author": "Alpha_Omegasis", - "Version": "1.7.1", + "Version": "1.8.0", "Description": "Lets you stay up all night.", "UniqueID": "Omegasis.NightOwl", "EntryDll": "NightOwl.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:433" ] } diff --git a/GeneralMods/NightOwl/packages.config b/GeneralMods/NightOwl/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/NightOwl/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/NoMorePets/NoMorePets.cs b/GeneralMods/NoMorePets/NoMorePets.cs index 07982c33..39a8add1 100644 --- a/GeneralMods/NoMorePets/NoMorePets.cs +++ b/GeneralMods/NoMorePets/NoMorePets.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using StardewModdingAPI; using StardewModdingAPI.Events; @@ -17,18 +16,18 @@ namespace Omegasis.NoMorePets /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { - SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; } /********* ** Private methods *********/ - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - public void SaveEvents_AfterLoad(object sender, EventArgs e) - { + /// The event arguments. + public void OnSaveLoaded(object sender, SaveLoadedEventArgs e) + { foreach (Pet pet in Game1.player.currentLocation.getCharacters().OfType().ToArray()) pet.currentLocation.characters.Remove(pet); } diff --git a/GeneralMods/NoMorePets/NoMorePets.csproj b/GeneralMods/NoMorePets/NoMorePets.csproj index 9b5cef2a..d6478fbb 100644 --- a/GeneralMods/NoMorePets/NoMorePets.csproj +++ b/GeneralMods/NoMorePets/NoMorePets.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ NoMorePets v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -82,19 +83,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/NoMorePets/manifest.json b/GeneralMods/NoMorePets/manifest.json index 64ca1569..6c1a9aae 100644 --- a/GeneralMods/NoMorePets/manifest.json +++ b/GeneralMods/NoMorePets/manifest.json @@ -1,10 +1,10 @@ { "Name": "No More Pets", "Author": "Alpha_Omegasis", - "Version": "1.5.0", + "Version": "1.6.0", "Description": "Removes all pets from the game.", "UniqueID": "Omegasis.NoMorePets", "EntryDll": "NoMorePets.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:506" ] } diff --git a/GeneralMods/NoMorePets/packages.config b/GeneralMods/NoMorePets/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/NoMorePets/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/Revitalize/Framework/Crafting/Recipe.cs b/GeneralMods/Revitalize/Framework/Crafting/Recipe.cs new file mode 100644 index 00000000..dcb607c4 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Crafting/Recipe.cs @@ -0,0 +1,173 @@ +using System.Collections.Generic; +using System.Linq; +using Revitalize.Framework.Utilities; +using StardewValley; + +namespace Revitalize.Framework.Crafting +{ + public class Recipe + { + public Dictionary ingredients; + public Dictionary outputs; + + private Item displayItem; + + public Item DisplayItem + { + get => this.displayItem ?? this.outputs.ElementAt(0).Key; + set => this.displayItem = value; + } + + public string outputDescription; + public string outputName; + + public StatCost statCost; + + public Recipe() { } + + /// Constructor for single item output. + /// All the ingredients required to make the output. + /// The item given as output with how many + public Recipe(Dictionary inputs, KeyValuePair output, StatCost StatCost=null) + { + this.ingredients = inputs; + this.DisplayItem = output.Key; + this.outputDescription = output.Key.getDescription(); + this.outputName = output.Key.DisplayName; + this.outputs = new Dictionary + { + [output.Key] = output.Value + }; + this.statCost = StatCost ?? new StatCost(); + } + + public Recipe(Dictionary inputs, Dictionary outputs, string OutputName, string OutputDescription, Item DisplayItem = null,StatCost StatCost=null) + { + this.ingredients = inputs; + this.outputs = outputs; + this.outputName = OutputName; + this.outputDescription = OutputDescription; + this.DisplayItem = DisplayItem; + this.statCost = StatCost ?? new StatCost(); + } + + /// Checks if a player contains all recipe ingredients. + public bool PlayerContainsAllIngredients() + { + return this.InventoryContainsAllIngredient(Game1.player.Items.ToList()); + } + + /// Checks if a player contains a recipe ingredient. + public bool PlayerContainsIngredient(KeyValuePair pair) + { + return this.InventoryContainsIngredient(Game1.player.Items.ToList(), pair); + } + + /// Checks if an inventory contains all items. + public bool InventoryContainsAllIngredient(List items) + { + foreach (KeyValuePair pair in this.ingredients) + if (!this.InventoryContainsIngredient(items, pair)) return false; + return true; + } + + /// Checks if an inventory contains an ingredient. + public bool InventoryContainsIngredient(List items, KeyValuePair pair) + { + foreach (Item i in items) + { + if (i != null && this.ItemEqualsOther(i, pair.Key) && pair.Value == i.Stack) + return true; + } + return false; + } + + /// Checks roughly if two items equal each other. + public bool ItemEqualsOther(Item self, Item other) + { + return + self.Name == other.Name + && self.getCategoryName() == other.getCategoryName() + && self.GetType() == other.GetType(); + } + + public void consume(ref List from) + { + if (this.InventoryContainsAllIngredient(from)==false) + return; + + InventoryManager manager = new InventoryManager(from); + List removalList = new List(); + foreach (KeyValuePair pair in this.ingredients) + { + foreach (Item item in manager.items) + { + if (item == null) continue; + if (this.ItemEqualsOther(item, pair.Key)) + { + if (item.Stack == pair.Value) + removalList.Add(item); //remove the item + else + item.Stack -= pair.Value; //or reduce the stack size. + } + } + } + + foreach (var v in removalList) + manager.items.Remove(v); + removalList.Clear(); + from = manager.items; + } + + public void produce(ref List to, bool dropToGround = false, bool isPlayerInventory = false) + { + var manager = isPlayerInventory + ? new InventoryManager(new List()) + : new InventoryManager(to); + foreach (KeyValuePair pair in this.outputs) + { + Item item = pair.Key.getOne(); + item.addToStack(pair.Value - 1); + bool added = manager.addItem(item); + if (!added && dropToGround) + Game1.createItemDebris(item, Game1.player.getStandingPosition(), Game1.player.getDirection()); + } + to = manager.items; + } + + public void craft(ref List from, ref List to, bool dropToGround = false, bool isPlayerInventory = false) + { + InventoryManager manager = new InventoryManager(to); + if (manager.ItemCount + this.outputs.Count >= manager.capacity) + { + if (isPlayerInventory) + Game1.showRedMessage("Inventory Full"); + else return; + } + this.consume(ref from); + this.produce(ref to, dropToGround, isPlayerInventory); + } + + public void craft() + { + List playerItems = Game1.player.Items.ToList(); + List outPutItems = new List(); + this.craft(ref playerItems, ref outPutItems, true, true); + + Game1.player.Items = playerItems; //Set the items to be post consumption. + foreach (Item I in outPutItems) + Game1.player.addItemToInventory(I); //Add all items produced. + this.statCost.payCost(); + } + + public bool PlayerCanCraft() + { + return this.PlayerContainsAllIngredients() && this.statCost.canSafelyAffordCost(); + } + + public bool CanCraft(List items) + { + return this.InventoryContainsAllIngredient(items); + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Crafting/StatCost.cs b/GeneralMods/Revitalize/Framework/Crafting/StatCost.cs new file mode 100644 index 00000000..682f8c42 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Crafting/StatCost.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using StardewValley; + +namespace Revitalize.Framework.Crafting +{ + public class StatCost + { + int health; + int stamina; + int magic; + int gold; + + public StatCost(int Stamina = 0, int Health = 0, int Gold = 0, int Magic = 0){ + this.stamina = Stamina; + this.health = Health; + this.gold = Gold; + this.magic = Magic; + } + + /// + /// Checks if the player can afford the cost but allows for player to collapse. + /// + /// + public bool canAffordCost() { + + if (Game1.player.stamina >= this.stamina && Game1.player.health >= this.health && Game1.player.Money >= this.gold && Revitalize.ModCore.playerInfo.magicManager.currentMagic >= this.magic) return true; + return false; + + } + + /// + /// Same as affording the cost but prevents the player from collapsing. + /// + /// + public bool canSafelyAffordCost() + { + if (Game1.player.stamina > this.stamina && Game1.player.health > this.health && Game1.player.Money >= this.gold && Revitalize.ModCore.playerInfo.magicManager.currentMagic >= this.magic) return true; + return false; + } + + /// + /// Consume all necessary components for this cost. + /// + public void payCost() + { + if (canSafelyAffordCost()) + { + Game1.player.stamina -= this.stamina; + Game1.player.health -= this.health; + Game1.player.Money = Game1.player.Money - this.gold; + Revitalize.ModCore.playerInfo.magicManager.currentMagic -= this.magic; + } + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Enums/Enums.cs b/GeneralMods/Revitalize/Framework/Enums/Enums.cs new file mode 100644 index 00000000..3d3d7e09 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Enums/Enums.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Revitalize.Framework +{ + public class Enums + { + public enum Direction + { + Up, + Right, + Down, + Left + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Environment/DarkerNight.cs b/GeneralMods/Revitalize/Framework/Environment/DarkerNight.cs new file mode 100644 index 00000000..c0b505cf --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Environment/DarkerNight.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using Microsoft.Xna.Framework; +using StardewValley; + +namespace Revitalize.Framework.Environment +{ + /// Deals with making night time darker in Stardew. + public class DarkerNight + { + /// Darkness intensity. + public static float IncrediblyDark = 0.9f; + + /// Darkness intensity. + public static float VeryDark = 0.75f; + + /// Darkness intensity. + public static float SomewhatDark = 0.50f; + + /// The config file. + public static DarkerNightConfig Config; + + /// The calculated night color. + private static Color CalculatedColor; + + /// Initializes the config for DarkerNight. + public static void InitializeConfig() + { + if (File.Exists(Path.Combine(ModCore.ModHelper.DirectoryPath, "Configs", "DarkerNightConfig.json"))) + Config = ModCore.ModHelper.Data.ReadJsonFile(Path.Combine("Configs", "DarkerNightConfig.json")); + else + { + Config = new DarkerNightConfig(); + ModCore.ModHelper.Data.WriteJsonFile(Path.Combine("Configs", "DarkerNightConfig.json"), Config); + } + } + + /// Sets the color of darkness at night. + public static void SetDarkerColor() + { + if (!Config.Enabled || Game1.player?.currentLocation == null) + return; + + if (Game1.player.currentLocation.IsOutdoors && Game1.timeOfDay >= Game1.getStartingToGetDarkTime()) + Game1.outdoorLight = CalculatedColor; + } + + /// Calculates how dark it should be a night. + public static void CalculateDarkerNightColor() + { + if (!Config.Enabled || Game1.player?.currentLocation == null) + return; + + //Calculate original lighting. + if (Game1.timeOfDay >= Game1.getTrulyDarkTime()) + { + float num = Math.Min(0.93f, (float)(0.75 + ((int)(Game1.timeOfDay - Game1.timeOfDay % 100 + Game1.timeOfDay % 100 / 10 * 16.6599998474121) - Game1.getTrulyDarkTime() + Game1.gameTimeInterval / 7000.0 * 16.6000003814697) * 0.000624999986030161)); + Game1.outdoorLight = (Game1.isRaining ? Game1.ambientLight : Game1.eveningColor) * num; + } + else if (Game1.timeOfDay >= Game1.getStartingToGetDarkTime()) + { + float num = Math.Min(0.93f, (float)(0.300000011920929 + ((int)(Game1.timeOfDay - Game1.timeOfDay % 100 + Game1.timeOfDay % 100 / 10 * 16.6599998474121) - Game1.getStartingToGetDarkTime() + Game1.gameTimeInterval / 7000.0 * 16.6000003814697) * 0.00224999990314245)); + Game1.outdoorLight = (Game1.isRaining ? Game1.ambientLight : Game1.eveningColor) * num; + } + + ModCore.log("OUT: " + Game1.outdoorLight); + + int red = Game1.outdoorLight.R; + + if (Game1.player.currentLocation.IsOutdoors && Game1.timeOfDay >= Game1.getStartingToGetDarkTime()) + { + //Game1.ambientLight = Game1.ambientLight.GreyScaleAverage(); + CalculatedColor = Game1.ambientLight * ((red + 30) / 255f) * Config.DarknessIntensity; + + ModCore.log("OUT: " + CalculatedColor); + ModCore.log("Ambient" + Game1.ambientLight); + } + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Environment/DarkerNightConfig.cs b/GeneralMods/Revitalize/Framework/Environment/DarkerNightConfig.cs new file mode 100644 index 00000000..71819fff --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Environment/DarkerNightConfig.cs @@ -0,0 +1,13 @@ +namespace Revitalize.Framework.Environment +{ + public class DarkerNightConfig + { + public bool Enabled; + public float DarknessIntensity; + public DarkerNightConfig() + { + this.Enabled = true; + this.DarknessIntensity = .9f; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Graphics/Animations/Animation.cs b/GeneralMods/Revitalize/Framework/Graphics/Animations/Animation.cs new file mode 100644 index 00000000..9218b13b --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Graphics/Animations/Animation.cs @@ -0,0 +1,59 @@ +using System.Xml.Serialization; +using Microsoft.Xna.Framework; +using Netcode; + +namespace Revitalize.Framework.Graphics.Animations +{ + /// A custom class used to deal with custom animations/ + public class Animation + { + /// The source rectangle on the texture to display. + public Rectangle sourceRectangle; + + /// The duration of the frame in length. + public int frameDuration; + + /// The duration until the next frame. + public int frameCountUntilNextAnimation; + + [XmlIgnore] + public NetFields NetFields { get; } = new NetFields(); + + public Animation() + { + this.sourceRectangle = new Rectangle(0, 0, 16, 16); + this.frameCountUntilNextAnimation = -1; + this.frameDuration = -1; + } + + /// Constructor that causes the animation frame count to be set to -1; This forces it to never change. + /// The draw source for this animation. + public Animation(Rectangle SourceRectangle) + { + this.sourceRectangle = SourceRectangle; + this.frameCountUntilNextAnimation = -1; + this.frameDuration = -1; + } + + /// Construct an instance. + /// The draw source for this animation. + /// How many on screen frames this animation stays for. Every draw frame decrements an active animation by 1 frame. Set this to -1 to have it be on the screen infinitely. + public Animation(Rectangle SourceRectangle, int existForXFrames) + { + this.sourceRectangle = SourceRectangle; + this.frameDuration = existForXFrames; + } + + /// Decrements the amount of frames this animation is on the screen for by 1. + public void tickAnimationFrame() + { + this.frameCountUntilNextAnimation--; + } + + /// This sets the animation frame count to be the max duration. I.E restart the timer. + public void startAnimation() + { + this.frameCountUntilNextAnimation = this.frameDuration; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Graphics/Animations/AnimationManager.cs b/GeneralMods/Revitalize/Framework/Graphics/Animations/AnimationManager.cs new file mode 100644 index 00000000..566295b2 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Graphics/Animations/AnimationManager.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using StardewValley; + +namespace Revitalize.Framework.Graphics.Animations +{ + /// Used to play animations for Stardust.CoreObject type objects and all objects that extend from it. In draw code of object make sure to use this info instead. + public class AnimationManager + { + public Dictionary> animations = new SerializableDictionary>(); + public string currentAnimationName; + public int currentAnimationListIndex; + public List currentAnimationList = new List(); + public Texture2DExtended objectTexture; ///Might not be necessary if I use the CoreObject texture sheet. + public Animation defaultDrawFrame; + public Animation currentAnimation; + public bool enabled; + + public string animationDataString; + + public bool IsNull => this.defaultDrawFrame == null && this.objectTexture == null; + + /// Construct an instance. + public AnimationManager() { } + + + /// Constructor for Animation Manager class. + /// The texture that will be used for the animation. This is typically the same as the object this class is attached to. + /// This is used if no animations will be available to the animation manager. + /// Whether or not animations play by default. Default value is true. + public AnimationManager(Texture2DExtended ObjectTexture, Animation DefaultFrame, bool EnabledByDefault = true) + { + this.currentAnimationListIndex = 0; + this.objectTexture = ObjectTexture; + this.defaultDrawFrame = DefaultFrame; + this.enabled = EnabledByDefault; + this.currentAnimation = this.defaultDrawFrame; + this.currentAnimationName = ""; + this.animationDataString = ""; + } + + public AnimationManager(Texture2DExtended ObjectTexture, Animation DefaultFrame, string animationString, string startingAnimationKey, int startingAnimationFrame = 0, bool EnabledByDefault = true) + { + this.currentAnimationListIndex = 0; + this.objectTexture = ObjectTexture; + this.defaultDrawFrame = DefaultFrame; + this.enabled = EnabledByDefault; + + this.animationDataString = animationString; + this.animations = parseAnimationsFromXNB(animationString); + if (this.animations.TryGetValue(startingAnimationKey, out this.currentAnimationList)) + this.setAnimation(startingAnimationKey, startingAnimationFrame); + else + { + this.currentAnimation = this.defaultDrawFrame; + this.currentAnimationName = ""; + } + } + + public AnimationManager(Texture2DExtended ObjectTexture, Animation DefaultFrame, Dictionary> animationString, string startingAnimationKey, int startingAnimationFrame = 0, bool EnabledByDefault = true) + { + this.currentAnimationListIndex = 0; + this.objectTexture = ObjectTexture; + this.defaultDrawFrame = DefaultFrame; + this.enabled = EnabledByDefault; + + this.animations = animationString; + if (this.animations.TryGetValue(startingAnimationKey, out this.currentAnimationList)) + this.setAnimation(startingAnimationKey, startingAnimationFrame); + else + { + this.currentAnimation = this.defaultDrawFrame; + this.currentAnimationName = ""; + } + } + + /// Update the animation frame once after drawing the object. + public void tickAnimation() + { + try + { + if (this.currentAnimation.frameDuration == -1 || !this.enabled || this.currentAnimation == this.defaultDrawFrame) + return; //This is if this is a default animation or the animation stops here. + if (this.currentAnimation.frameCountUntilNextAnimation == 0) + this.getNextAnimation(); + this.currentAnimation.tickAnimationFrame(); + } + catch (Exception err) + { + ModCore.ModMonitor.Log("An internal error occured when trying to tick the animation."); + ModCore.ModMonitor.Log(err.ToString(), StardewModdingAPI.LogLevel.Error); + } + } + + /// Get the next animation in the list of animations. + public void getNextAnimation() + { + this.currentAnimationListIndex++; + if (this.currentAnimationListIndex == this.currentAnimationList.Count) //If the animation frame I'm tryting to get is 1 outside my list length, reset the list. + this.currentAnimationListIndex = 0; + + //Get the next animation from the list and reset it's counter to the starting frame value. + this.currentAnimation = this.currentAnimationList[this.currentAnimationListIndex]; + this.currentAnimation.startAnimation(); + } + + /// Gets the animation from the dictionary of all animations available. + /// + /// + public bool setAnimation(string AnimationName, int StartingFrame = 0) + { + if (this.animations.TryGetValue(AnimationName, out List dummyList)) + { + if (dummyList.Count != 0 || StartingFrame >= dummyList.Count) + { + this.currentAnimationList = dummyList; + this.currentAnimation = this.currentAnimationList[StartingFrame]; + this.currentAnimationName = AnimationName; + return true; + } + else + { + if (dummyList.Count == 0) + ModCore.ModMonitor.Log("Error: Current animation " + AnimationName + " has no animation frames associated with it."); + if (dummyList.Count > dummyList.Count) + ModCore.ModMonitor.Log("Error: Animation frame " + StartingFrame + " is outside the range of provided animations. Which has a maximum count of " + dummyList.Count); + return false; + } + } + else + { + ModCore.ModMonitor.Log("Error setting animation: " + AnimationName + " animation does not exist in list of available animations. Did you make sure to add it in?"); + return false; + } + } + + /// Sets the animation manager to an on state, meaning that this animation will update on the draw frame. + public void enableAnimation() + { + this.enabled = true; + } + + /// Sets the animation manager to an off state, meaning that this animation will no longer update on the draw frame. + public void disableAnimation() + { + this.enabled = false; + } + + public static Dictionary> parseAnimationsFromXNB(string s) + { + string[] array = s.Split('*'); + Dictionary> parsedDic = new Dictionary>(); + foreach (string v in array) + { + // Log.AsyncC(v); + string[] animationArray = v.Split(' '); + if (parsedDic.ContainsKey(animationArray[0])) + { + List animations = parseAnimationFromString(v); + foreach (var animation in animations) + { + parsedDic[animationArray[0]].Add(animation); + } + } + else + { + parsedDic.Add(animationArray[0], new List()); + List aniList = new List(); + aniList = parseAnimationFromString(v); + foreach (var ani in aniList) + { + parsedDic[animationArray[0]].Add(ani); + } + } + } + return parsedDic; + } + + public static List parseAnimationFromString(string s) + { + List ok = new List(); + string[] array2 = s.Split('>'); + foreach (string q in array2) + { + string[] array = q.Split(' '); + try + { + Animation ani = new Animation(new Rectangle(Convert.ToInt32(array[1]), Convert.ToInt32(array[2]), Convert.ToInt32(array[3]), Convert.ToInt32(array[4])), Convert.ToInt32(array[5])); + // ModCore.ModMonitor.Log(ani.sourceRectangle.ToString()); + ok.Add(ani); + } + catch { } + } + return ok; + } + /// Used to handle general drawing functionality using the animation manager. + /// We need a spritebatch to draw. + /// The texture to draw. + /// The onscreen position to draw to. + /// The source rectangle on the texture to draw. + /// The color to draw the thing passed in. + /// The rotation of the animation texture being drawn. + /// The origin of the texture. + /// The scale of the texture. + /// Effects that get applied to the sprite. + /// The dept at which to draw the texture. + public void draw(SpriteBatch spriteBatch, Texture2D texture, Vector2 Position, Rectangle? sourceRectangle, Color drawColor, float rotation, Vector2 origin, float scale, SpriteEffects spriteEffects, float LayerDepth) + { + //Log.AsyncC("Animation Manager is working!"); + spriteBatch.Draw(texture, Position, sourceRectangle, drawColor, rotation, origin, scale, spriteEffects, LayerDepth); + try + { + this.tickAnimation(); + // Log.AsyncC("Tick animation"); + } + catch (Exception err) + { + ModCore.ModMonitor.Log(err.ToString()); + } + } + + public Texture2DExtended getExtendedTexture() + { + return this.objectTexture; + } + + public void setExtendedTexture(Texture2DExtended texture) + { + this.objectTexture = texture; + } + + public void setEnabled(bool enabled) + { + this.enabled = enabled; + } + + public Texture2D getTexture() + { + return this.objectTexture.getTexture(); + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Graphics/Texture2DExtended.cs b/GeneralMods/Revitalize/Framework/Graphics/Texture2DExtended.cs new file mode 100644 index 00000000..e78447f2 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Graphics/Texture2DExtended.cs @@ -0,0 +1,78 @@ +using System.IO; +using Microsoft.Xna.Framework.Graphics; +using StardewModdingAPI; + +namespace Revitalize.Framework.Graphics +{ + public class Texture2DExtended + { + public string Name; + public Texture2D texture; + public string path; + public string modID; + public ContentSource source; + private readonly IModHelper helper; + + /// Empty/null constructor. + public Texture2DExtended() + { + this.Name = ""; + this.texture = null; + this.path = ""; + this.helper = null; + this.modID = ""; + } + + public Texture2DExtended(Texture2D Texture) + { + this.Name = ""; + this.texture = Texture; + this.path = ""; + this.helper = null; + this.modID = ""; + } + + /// Construct an instance. + /// The relative path to file on disk. See StardustCore.Utilities.getRelativePath(modname,path); + public Texture2DExtended(IModHelper helper, IManifest manifest, string path, ContentSource contentSource = ContentSource.ModFolder) + { + this.Name = Path.GetFileNameWithoutExtension(path); + this.path = path; + this.texture = helper.Content.Load(path, contentSource); + this.helper = helper; + this.modID = manifest.UniqueID; + this.source = contentSource; + } + + public Texture2DExtended(IModHelper helper, string modID, string path, ContentSource contentSource = ContentSource.ModFolder) + { + this.Name = Path.GetFileNameWithoutExtension(path); + this.path = path; + this.texture = helper.Content.Load(path, contentSource); + this.helper = helper; + this.modID = modID; + this.source = contentSource; + } + + public Texture2DExtended Copy() + { + return new Texture2DExtended(this.helper, this.modID, this.path); + } + + public IModHelper getHelper() + { + return this.helper; + } + + /// Returns the actual 2D texture held by this wrapper class. + public Texture2D getTexture() + { + return this.texture; + } + + public void setTexure(Texture2D text) + { + this.texture = text; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Graphics/TextureManager.cs b/GeneralMods/Revitalize/Framework/Graphics/TextureManager.cs new file mode 100644 index 00000000..caade4d7 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Graphics/TextureManager.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Revitalize.Framework.Graphics +{ + public class TextureManager + { + public static Dictionary TextureManagers = new Dictionary(); + + + public Dictionary textures; + + public TextureManager() + { + this.textures = new Dictionary(); + } + + public void addTexture(string name, Texture2DExtended texture) + { + this.textures.Add(name, texture); + } + + /// Returns a Texture2DExtended held by the manager. + public Texture2DExtended getTexture(string name) + { + foreach (var v in this.textures) + { + if (v.Key == name) + return v.Value.Copy(); + } + throw new Exception("Error, texture name not found!!!"); + } + + public static void addTexture(string managerName, string textureName, Texture2DExtended Texture) + { + Texture.texture.Name = managerName + '.' + textureName; + TextureManagers[managerName].addTexture(textureName, Texture); + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Illuminate/ColorExtensions.cs b/GeneralMods/Revitalize/Framework/Illuminate/ColorExtensions.cs new file mode 100644 index 00000000..e4e65c52 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Illuminate/ColorExtensions.cs @@ -0,0 +1,22 @@ +using System; +using Microsoft.Xna.Framework; + +namespace Revitalize.Framework.Illuminate +{ + public static class ColorExtensions + { + public static Color GreyScaleAverage(this Color color) + { + int value = (color.R + color.G + color.B) / 3; + return new Color(new Vector3(value)); + } + + public static Color Invert(this Color color) + { + int r = Math.Abs(255 - color.R); + int g = Math.Abs(255 - color.G); + int b = Math.Abs(255 - color.B); + return new Color(r, g, b); + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Illuminate/LightManager.cs b/GeneralMods/Revitalize/Framework/Illuminate/LightManager.cs new file mode 100644 index 00000000..c08fa902 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Illuminate/LightManager.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using Microsoft.Xna.Framework; +using StardewValley; + +namespace Revitalize.Framework.Illuminate +{ + public class LightManager + { + public Dictionary lights; + public bool lightsOn; + + public LightManager() + { + this.lights = new Dictionary(); + this.lightsOn = false; + } + + /// Add a light to the list of tracked lights. + public bool addLight(Vector2 IdKey, LightSource light, StardewValley.Object gameObject) + { + Vector2 initialPosition = gameObject.TileLocation * Game1.tileSize; + initialPosition += IdKey; + + if (this.lights.ContainsKey(IdKey)) + return false; + + light.position.Value = initialPosition; + this.lights.Add(IdKey, light); + return true; + } + + /// Turn off a single light. + public bool turnOffLight(Vector2 IdKey, GameLocation location) + { + if (!this.lights.ContainsKey(IdKey)) + return false; + + this.lights.TryGetValue(IdKey, out LightSource light); + Game1.currentLightSources.Remove(light); + location.sharedLights.Remove((int)IdKey.X * 1000000 + (int)IdKey.Y); + return true; + } + + /// Turn on a single light. + public bool turnOnLight(Vector2 IdKey, GameLocation location, StardewValley.Object gameObject) + { + if (!this.lights.ContainsKey(IdKey)) + return false; + + this.lights.TryGetValue(IdKey, out var light); + if (light == null) + throw new Exception("Light is null????"); + + Game1.currentLightSources.Add(light); + if (location == null) + throw new Exception("WHY IS LOC NULL???"); + + if (location.sharedLights == null) + throw new Exception("Locational lights is null!"); + + Game1.showRedMessage("TURN ON!"); + Game1.currentLightSources.Add(light); + location.sharedLights.Add((int)IdKey.X*10000+(int)IdKey.Y,light); + this.repositionLight(light, IdKey, gameObject); + return true; + } + + /// Add a light source to this location. + /// The game location to add the light source in. + public virtual void turnOnLights(GameLocation environment, StardewValley.Object gameObject) + { + foreach (KeyValuePair pair in this.lights) + this.turnOnLight(pair.Key, environment, gameObject); + this.repositionLights(gameObject); + } + + /// Removes a lightsource from the game location. + /// The game location to remove the light source from. + public void turnOffLights(GameLocation environment) + { + foreach (KeyValuePair pair in this.lights) + this.turnOffLight(pair.Key, environment); + } + + public void repositionLights(StardewValley.Object gameObject) + { + foreach (KeyValuePair pair in this.lights) + this.repositionLight(pair.Value, pair.Key, gameObject); + } + + public void repositionLight(LightSource light, Vector2 offset, StardewValley.Object gameObject) + { + Vector2 initialPosition = gameObject.TileLocation * Game1.tileSize; + light.position.Value = initialPosition + offset; + } + + public virtual void toggleLights(GameLocation location, StardewValley.Object gameObject) + { + if (!this.lightsOn) + { + this.turnOnLights(location, gameObject); + this.lightsOn = true; + } + else if (this.lightsOn) + { + this.turnOffLights(Game1.player.currentLocation); + this.lightsOn = false; + } + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/BasicItemInformation.cs b/GeneralMods/Revitalize/Framework/Objects/BasicItemInformation.cs new file mode 100644 index 00000000..ce4ac74c --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/BasicItemInformation.cs @@ -0,0 +1,104 @@ +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using PyTK.CustomElementHandler; +using Revitalize.Framework.Graphics.Animations; +using Revitalize.Framework.Illuminate; +using Revitalize.Framework.Utilities; +using StardewValley; + +namespace Revitalize.Framework.Objects +{ + public class BasicItemInformation : CustomObjectData + { + public string name; + public string description; + public string categoryName; + public Color categoryColor; + public int price; + public Vector2 TileLocation; + public int edibility; + public int fragility; + public bool canBeSetIndoors; + public bool canBeSetOutdoors; + public bool isLamp; + + + public AnimationManager animationManager; + public Vector2 drawPosition; + + public Color drawColor; + + public bool ignoreBoundingBox; + + public InventoryManager inventory; + + public LightManager lightManager; + + public Enums.Direction facingDirection; + + public BasicItemInformation() + { + this.name = ""; + this.description = ""; + this.categoryName = ""; + this.categoryColor = new Color(0, 0, 0); + this.price = 0; + this.TileLocation = Vector2.Zero; + this.edibility = -300; + this.canBeSetIndoors = false; + this.canBeSetOutdoors = false; + + this.animationManager = new AnimationManager(); + this.drawPosition = Vector2.Zero; + this.drawColor = Color.White; + this.inventory = new InventoryManager(); + this.lightManager = new LightManager(); + + this.facingDirection = Enums.Direction.Down; + + } + + public BasicItemInformation(string name, string description, string categoryName, Color categoryColor,int edibility, int fragility, bool isLamp, int price, Vector2 TileLocation, bool canBeSetOutdoors, bool canBeSetIndoors, string id, string data, Texture2D texture, Color color, int tileIndex, bool bigCraftable, Type type, CraftingData craftingData, AnimationManager animationManager, Color drawColor, bool ignoreBoundingBox, InventoryManager Inventory, LightManager Lights) : base(id, data, texture, color, tileIndex, bigCraftable, type, craftingData) + { + + this.name = name; + this.description = description; + this.categoryName = categoryName; + this.categoryColor = categoryColor; + this.price = price; + this.TileLocation = TileLocation; + this.edibility = edibility; + + this.canBeSetOutdoors = canBeSetOutdoors; + this.canBeSetIndoors = canBeSetIndoors; + this.fragility = fragility; + this.isLamp = isLamp; + + this.animationManager = animationManager; + if (this.animationManager.IsNull) + { + this.animationManager = new AnimationManager(new Graphics.Texture2DExtended(), new Animation(new Rectangle(0, 0, 16, 16)), false); + this.animationManager.getExtendedTexture().texture = this.texture; + } + else + this.texture = this.animationManager.getTexture(); + + this.drawPosition = Vector2.Zero; + this.drawColor = drawColor; + this.ignoreBoundingBox = ignoreBoundingBox; + this.recreateDataString(); + this.inventory = Inventory ?? new InventoryManager(); + this.lightManager = Lights ?? new LightManager(); + this.facingDirection = Enums.Direction.Down; + + } + + public void recreateDataString() + { + this.data = $"{this.name}/{this.price}/{this.edibility}/Crafting -9/{this.description}/{this.canBeSetOutdoors}/{this.canBeSetIndoors}/{this.fragility}/{this.isLamp}/{this.name}"; + } + + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/CustomObject.cs b/GeneralMods/Revitalize/Framework/Objects/CustomObject.cs new file mode 100644 index 00000000..6b0615c2 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/CustomObject.cs @@ -0,0 +1,386 @@ +using System; +using System.Collections.Generic; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using Newtonsoft.Json; +using PyTK.CustomElementHandler; +using Revitalize.Framework.Graphics.Animations; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Objects +{ + // TODO: + // -Multiple Lights + // -Events when walking over? + // -Inventories + + /// A custom object template. + public class CustomObject : PySObject + { + public string id; + + + public BasicItemInformation info; + public GameLocation location; + + + public Guid guid; + + /// The animation manager. + public AnimationManager animationManager => this.info.animationManager; + + /// The display texture for this object. + [JsonIgnore] + public Texture2D displayTexture => this.animationManager.getTexture(); + + + + /// Empty constructor. + public CustomObject() { + this.guid = Guid.NewGuid(); + } + + /// Construct an instance. + public CustomObject(BasicItemInformation info) + : base(info, Vector2.Zero) + { + this.info = info; + this.initializeBasics(); + this.guid = Guid.NewGuid(); + } + + /// Construct an instance. + public CustomObject(BasicItemInformation info, Vector2 TileLocation) + : base(info, TileLocation) + { + this.info = info; + this.initializeBasics(); + this.guid = Guid.NewGuid(); + } + + /// Sets some basic information up. + public virtual void initializeBasics() + { + this.name = this.info.name; + this.displayName = this.getDisplayNameFromStringsFile(this.id); + this.Edibility = this.info.edibility; + this.Category = -9; //For crafting. + this.displayName = this.info.name; + this.setOutdoors.Value = true; + this.setIndoors.Value = true; + this.isLamp.Value = false; + this.fragility.Value = 0; + + this.updateDrawPosition(0, 0); + + this.bigCraftable.Value = false; + + this.initNetFields(); + + + //if (this.info.ignoreBoundingBox) + // this.boundingBox.Value = new Rectangle(int.MinValue, int.MinValue, 0, 0); + } + + public override bool isPassable() + { + return this.info.ignoreBoundingBox || Revitalize.ModCore.playerInfo.sittingInfo.SittingObject==this; + } + + public override Rectangle getBoundingBox(Vector2 tileLocation) + { + //Revitalize.ModCore.log(System.Environment.StackTrace); + return this.info.ignoreBoundingBox + ? new Rectangle(int.MinValue, int.MinValue, 0, 0) + : base.getBoundingBox(tileLocation); + } + + /// Checks for interaction with the object. + public override bool checkForAction(Farmer who, bool justCheckingForActivity = false) + { + MouseState mState = Mouse.GetState(); + KeyboardState keyboardState = Game1.GetKeyboardState(); + + if (mState.RightButton == ButtonState.Pressed && (keyboardState.IsKeyDown(Keys.LeftShift) || !keyboardState.IsKeyDown(Keys.RightShift))) + { + ModCore.log("Right clicked!"); + return this.rightClicked(who); + } + + if (mState.RightButton == ButtonState.Pressed && (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))) + return this.shiftRightClicked(who); + + if (justCheckingForActivity) + return true; + ModCore.log("Left clicked!"); + return this.clicked(who); + } + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + BasicItemInformation data = (BasicItemInformation)CustomObjectData.collection[additionalSaveData["id"]]; + return new CustomObject(data, (replacement as Chest).TileLocation); + } + + /// What happens when the player right clicks the object. + public virtual bool rightClicked(Farmer who) + { + // Game1.showRedMessage("YOOO"); + //do some stuff when the right button is down + // rotate(); + if (this.heldObject.Value != null) + { + // Game1.player.addItemByMenuIfNecessary(this.heldObject); + // this.heldObject = null; + } + else + { + // this.heldObject = Game1.player.ActiveObject; + // Game1.player.removeItemFromInventory(heldObject); + } + return true; + } + + /// What happens when the player shift-right clicks this object. + public virtual bool shiftRightClicked(Farmer who) + { + ModCore.log("Shift right clicked!"); + return true; + } + + /// What happens when the player left clicks the object. + public override bool clicked(Farmer who) + { + ModCore.log("Clicky click!"); + + ModCore.log(System.Environment.StackTrace); + + return this.removeAndAddToPlayersInventory(); + //return base.clicked(who); + } + + /// What happens when a player uses a tool on this object. + public override bool performToolAction(Tool t, GameLocation location) + { + if (t.GetType() == typeof(StardewValley.Tools.Axe) || t.GetType() == typeof(StardewValley.Tools.Pickaxe)) + { + Game1.createItemDebris(this, Game1.player.getStandingPosition(), Game1.player.getDirection()); + this.location = null; + this.updateDrawPosition(0, 0); + Game1.player.currentLocation.removeObject(this.TileLocation, false); + this.updateDrawPosition(0, 0); + return false; + } + + return false; + //return base.performToolAction(t, location); + } + + /// Remove the object from the world and add it to the player's inventory if possible. + public virtual bool removeAndAddToPlayersInventory() + { + if (Game1.player.isInventoryFull()) + { + Game1.showRedMessage("Inventory full."); + return false; + } + this.location = null; + Game1.player.currentLocation.removeObject(this.TileLocation, false); + Game1.player.addItemToInventory(this); + this.updateDrawPosition(0, 0); + return true; + } + + /// Gets the category color for the object. + public override Color getCategoryColor() + { + return this.info.categoryColor; + //return data.categoryColor; + } + + /// Gets the category name for the object. + public override string getCategoryName() + { + return this.info.categoryName; + } + + /// Gets the description for the object. + public override string getDescription() + { + string text = this.info.description; + SpriteFont smallFont = Game1.smallFont; + int width = Game1.tileSize * 4 + Game1.tileSize / 4; + return Game1.parseText(text, smallFont, width); + } + + /// Places an object down. + public override bool placementAction(GameLocation location, int x, int y, Farmer who = null) + { + this.updateDrawPosition(x, y); + this.location = location; + return base.placementAction(location, x, y, who); + } + + public virtual void rotate() + { + if (this.info.facingDirection == Enums.Direction.Down) this.info.facingDirection = Enums.Direction.Right; + else if (this.info.facingDirection == Enums.Direction.Right) this.info.facingDirection = Enums.Direction.Up; + else if (this.info.facingDirection == Enums.Direction.Up) this.info.facingDirection = Enums.Direction.Left; + else if (this.info.facingDirection == Enums.Direction.Left) this.info.facingDirection = Enums.Direction.Down; + + if (this.info.animationManager.animations.ContainsKey(generateRotationalAnimationKey())) + { + this.info.animationManager.setAnimation(generateRotationalAnimationKey()); + } + else + { + //Revitalize.ModCore.log("Animation does not exist...." + generateRotationalAnimationKey()); + } + } + + + public string generateRotationalAnimationKey() + { + return (this.info.animationManager.currentAnimationName.Split('_')[0]) +"_"+ (int)this.info.facingDirection; + } + + public string generateDefaultRotationalAnimationKey() + { + return ("Default" + "_" + (int)this.info.facingDirection); + } + + /// Updates a visual draw position. + public virtual void updateDrawPosition(int x, int y) + { + this.info.drawPosition = new Vector2((int)(x / Game1.tileSize), (int)(y / Game1.tileSize)); + //this.info.drawPosition = new Vector2((float)this.boundingBox.X, (float)(this.boundingBox.Y - (this.animationManager.currentAnimation.sourceRectangle.Height * Game1.pixelZoom - this.boundingBox.Height))); + } + + /// Gets a clone of the game object. + public override Item getOne() + { + return new CustomObject((BasicItemInformation)this.data); + } + + /// What happens when the object is drawn at a tile location. + public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1f) + { + if (x <= -1) + { + spriteBatch.Draw(this.info.animationManager.getTexture(), Game1.GlobalToLocal(Game1.viewport, this.info.drawPosition), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, (float)(this.TileLocation.Y * Game1.tileSize) / 10000f)); + } + else + { + //The actual planter box being drawn. + if (this.animationManager == null) + { + if (this.animationManager.getExtendedTexture() == null) + ModCore.ModMonitor.Log("Tex Extended is null???"); + + spriteBatch.Draw(this.displayTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * Game1.tileSize), y * Game1.tileSize)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, (float)(this.TileLocation.Y * Game1.tileSize) / 10000f)); + // Log.AsyncG("ANIMATION IS NULL?!?!?!?!"); + } + + else + { + //Log.AsyncC("Animation Manager is working!"); + int addedDepth = 0; + if (this.info.ignoreBoundingBox) addedDepth++; + if (Revitalize.ModCore.playerInfo.sittingInfo.SittingObject == this) addedDepth++; + this.animationManager.draw(spriteBatch, this.displayTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * Game1.tileSize), y * Game1.tileSize)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, (float)( (this.TileLocation.Y+addedDepth) * Game1.tileSize) / 10000f)); + try + { + this.animationManager.tickAnimation(); + // Log.AsyncC("Tick animation"); + } + catch (Exception err) + { + ModCore.ModMonitor.Log(err.ToString()); + } + } + + // spriteBatch.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)((double)tileLocation.X * (double)Game1.tileSize + (((double)tileLocation.X * 11.0 + (double)tileLocation.Y * 7.0) % 10.0 - 5.0)) + (float)(Game1.tileSize / 2), (float)((double)tileLocation.Y * (double)Game1.tileSize + (((double)tileLocation.Y * 11.0 + (double)tileLocation.X * 7.0) % 10.0 - 5.0)) + (float)(Game1.tileSize / 2))), new Rectangle?(new Rectangle((int)((double)tileLocation.X * 51.0 + (double)tileLocation.Y * 77.0) % 3 * 16, 128 + this.whichForageCrop * 16, 16, 16)), Color.White, 0.0f, new Vector2(8f, 8f), (float)Game1.pixelZoom, SpriteEffects.None, (float)(((double)tileLocation.Y * (double)Game1.tileSize + (double)(Game1.tileSize / 2) + (((double)tileLocation.Y * 11.0 + (double)tileLocation.X * 7.0) % 10.0 - 5.0)) / 10000.0)); + } + } + + /// Draw the game object at a non-tile spot. Aka like debris. + public override void draw(SpriteBatch spriteBatch, int xNonTile, int yNonTile, float layerDepth, float alpha = 1f) + { + if (Game1.eventUp && Game1.CurrentEvent.isTileWalkedOn(xNonTile / 64, yNonTile / 64)) + return; + if ((int)(this.ParentSheetIndex) != 590 && (int)(this.Fragility) != 2) + spriteBatch.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(xNonTile + 32), (float)(yNonTile + 51 + 4))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White * alpha, 0.0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), 4f, SpriteEffects.None, layerDepth - 1E-06f); + SpriteBatch spriteBatch1 = spriteBatch; + Texture2D objectSpriteSheet = Game1.objectSpriteSheet; + Vector2 local = Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(xNonTile + 32 + (this.shakeTimer > 0 ? Game1.random.Next(-1, 2) : 0)), (float)(yNonTile + 32 + (this.shakeTimer > 0 ? Game1.random.Next(-1, 2) : 0)))); + Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(GameLocation.getSourceRectForObject(this.ParentSheetIndex)); + Color color = Color.White * alpha; + double num1 = 0.0; + Vector2 origin = new Vector2(8f, 8f); + Vector2 scale = this.scale; + double num2 = (double)this.scale.Y > 1.0 ? (double)this.getScale().Y : 4.0; + int num3 = (bool)(this.flipped) ? 1 : 0; + double num4 = (double)layerDepth; + + spriteBatch1.Draw(this.displayTexture, local, this.animationManager.defaultDrawFrame.sourceRectangle, this.info.drawColor * alpha, (float)num1, origin, (float)4f, (SpriteEffects)num3, (float)num4); + } + + /// What happens when the object is drawn in a menu. + public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color c, bool drawShadow) + { + if (drawStackNumber && this.maximumStackSize() > 1 && ((double)scaleSize > 0.3 && this.Stack != int.MaxValue) && this.Stack > 1) + Utility.drawTinyDigits(this.Stack, spriteBatch, location + new Vector2((float)(Game1.tileSize - Utility.getWidthOfTinyDigitString(this.Stack, 3f * scaleSize)) + 3f * scaleSize, (float)((double)Game1.tileSize - 18.0 * (double)scaleSize + 2.0)), 3f * scaleSize, 1f, Color.White); + if (drawStackNumber && this.Quality > 0) + { + float num = this.Quality < 4 ? 0.0f : (float)((Math.Cos((double)Game1.currentGameTime.TotalGameTime.Milliseconds * Math.PI / 512.0) + 1.0) * 0.0500000007450581); + spriteBatch.Draw(Game1.mouseCursors, location + new Vector2(12f, (float)(Game1.tileSize - 12) + num), new Microsoft.Xna.Framework.Rectangle?(this.Quality < 4 ? new Microsoft.Xna.Framework.Rectangle(338 + (this.Quality - 1) * 8, 400, 8, 8) : new Microsoft.Xna.Framework.Rectangle(346, 392, 8, 8)), Color.White * transparency, 0.0f, new Vector2(4f, 4f), (float)(3.0 * (double)scaleSize * (1.0 + (double)num)), SpriteEffects.None, layerDepth); + } + spriteBatch.Draw(this.displayTexture, location + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize * .75)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * transparency, 0f, new Vector2((float)(this.animationManager.currentAnimation.sourceRectangle.Width / 2), (float)(this.animationManager.currentAnimation.sourceRectangle.Height)), 3f, SpriteEffects.None, layerDepth); + } + + /// What happens when the object is drawn when held by a player. + public override void drawWhenHeld(SpriteBatch spriteBatch, Vector2 objectPosition, StardewValley.Farmer f) + { + + if (this.animationManager == null) Revitalize.ModCore.log("Animation Manager Null"); + if (this.displayTexture == null) Revitalize.ModCore.log("Display texture is null"); + if (f.ActiveObject.bigCraftable.Value) + { + spriteBatch.Draw(this.displayTexture, objectPosition, this.animationManager.currentAnimation.sourceRectangle, this.info.drawColor, 0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, Math.Max(0f, (float)(f.getStandingY() + 2) / 10000f)); + return; + } + + spriteBatch.Draw(this.displayTexture, objectPosition, this.animationManager.currentAnimation.sourceRectangle, this.info.drawColor, 0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, Math.Max(0f, (float)(f.getStandingY() + 2) / 10000f)); + if (f.ActiveObject != null && f.ActiveObject.Name.Contains("=")) + { + spriteBatch.Draw(this.displayTexture, objectPosition + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize / 2)), this.animationManager.currentAnimation.sourceRectangle, Color.White, 0f, new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize / 2)), (float)Game1.pixelZoom + Math.Abs(Game1.starCropShimmerPause) / 8f, SpriteEffects.None, Math.Max(0f, (float)(f.getStandingY() + 2) / 10000f)); + if (Math.Abs(Game1.starCropShimmerPause) <= 0.05f && Game1.random.NextDouble() < 0.97) + { + return; + } + Game1.starCropShimmerPause += 0.04f; + if (Game1.starCropShimmerPause >= 0.8f) + { + Game1.starCropShimmerPause = -0.8f; + } + } + //base.drawWhenHeld(spriteBatch, objectPosition, f); + } + + public void InitNetFields() + { + this.initNetFields(); + this.syncObject = new PySync(this); + this.NetFields.AddField(this.syncObject); + } + + + public string getDisplayNameFromStringsFile(string objectID) + { + //Load in a file that has all object names referenced here or something. + return this.info.name; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/Furniture/Bench.cs b/GeneralMods/Revitalize/Framework/Objects/Furniture/Bench.cs new file mode 100644 index 00000000..16e7357d --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/Furniture/Bench.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using PyTK.CustomElementHandler; +using StardewValley; + +namespace Revitalize.Framework.Objects.Furniture +{ + public class Bench:ChairMultiTiledObject + { + public Bench() : base() + { + + } + + public List playersSittingHere = new List(); + + public Bench(BasicItemInformation info, Vector2 TilePosition) : base(info, TilePosition) + { + + } + + + public Bench(BasicItemInformation info,Vector2 TilePosition, Dictionary Objects): base(info, TilePosition, Objects) + { + + } + + /// + /// Rotate all chair components associated with this chair object. + /// + public override void rotate() + { + + if (Revitalize.ModCore.playerInfo.sittingInfo.SittingObject == this) return; + if (this.playersSittingHere.Count > 0) + { + Game1.showRedMessage("Can't rotate furniture when people are siting on it."); + return; + } + + foreach (KeyValuePair pair in this.objects) + { + (pair.Value as ChairTileComponent).rotate(); + } + foreach (KeyValuePair pair in this.objects) + { + (pair.Value as ChairTileComponent).checkForSpecialUpSittingAnimation(); + } + + base.rotate(); + } + + public override Item getOne() + { + Dictionary objs = new Dictionary(); + foreach (var pair in this.objects) + { + objs.Add(pair.Key, (MultiTiledComponent)pair.Value); + } + + return new Bench(this.info, this.TileLocation, objs); + } + + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + Bench obj = (Bench)Revitalize.ModCore.Serializer.DeserializeGUID(additionalSaveData["GUID"]); + if (obj == null) + { + return null; + } + + Dictionary guids = new Dictionary(); + + foreach (KeyValuePair pair in obj.childrenGuids) + { + guids.Add(pair.Key, pair.Value); + } + + foreach (KeyValuePair pair in guids) + { + obj.childrenGuids.Remove(pair.Key); + //Revitalize.ModCore.log("DESERIALIZE: " + pair.Value.ToString()); + ChairTileComponent component = Revitalize.ModCore.Serializer.DeserializeGUID(pair.Value.ToString()); + component.InitNetFields(); + + obj.addComponent(pair.Key, component); + + + } + obj.InitNetFields(); + + if (!Revitalize.ModCore.ObjectGroups.ContainsKey(additionalSaveData["GUID"])) + { + Revitalize.ModCore.ObjectGroups.Add(additionalSaveData["GUID"], obj); + return obj; + } + else + { + return Revitalize.ModCore.ObjectGroups[additionalSaveData["GUID"]]; + } + } + + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/Furniture/ChairMultiTiledObject.cs b/GeneralMods/Revitalize/Framework/Objects/Furniture/ChairMultiTiledObject.cs new file mode 100644 index 00000000..74465c07 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/Furniture/ChairMultiTiledObject.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using PyTK.CustomElementHandler; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Objects.Furniture +{ + /// + /// Object which encapsulates all of the pieces that make up a chair object in-game. + /// + public class ChairMultiTiledObject:MultiTiledObject + { + + public ChairMultiTiledObject() : base() + { + + } + + public ChairMultiTiledObject(BasicItemInformation Info) : base(Info) + { + + } + + public ChairMultiTiledObject(BasicItemInformation Info, Vector2 TilePosition) : base(Info, TilePosition) + { + + } + + public ChairMultiTiledObject(BasicItemInformation Info,Vector2 TilePosition,Dictionary Objects) : base(Info, TilePosition, Objects) { + + + } + + /// + /// Rotate all chair components associated with this chair object. + /// + public override void rotate() + { + Revitalize.ModCore.log("Rotate!"); + foreach(KeyValuePair pair in this.objects) + { + (pair.Value as ChairTileComponent).rotate(); + } + foreach (KeyValuePair pair in this.objects) + { + (pair.Value as ChairTileComponent).checkForSpecialUpSittingAnimation(); + } + + base.rotate(); + } + + public override Item getOne() + { + Dictionary objs = new Dictionary(); + foreach (var pair in this.objects) + { + objs.Add(pair.Key, (MultiTiledComponent)pair.Value); + } + + return new ChairMultiTiledObject(this.info, this.TileLocation, objs); + } + + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + ChairMultiTiledObject obj = (ChairMultiTiledObject)Revitalize.ModCore.Serializer.DeserializeGUID(additionalSaveData["GUID"]); + if (obj == null) + { + return null; + } + + Dictionary guids = new Dictionary(); + + foreach (KeyValuePair pair in obj.childrenGuids) + { + guids.Add(pair.Key, pair.Value); + } + + foreach (KeyValuePair pair in guids) + { + obj.childrenGuids.Remove(pair.Key); + //Revitalize.ModCore.log("DESERIALIZE: " + pair.Value.ToString()); + ChairTileComponent component = Revitalize.ModCore.Serializer.DeserializeGUID(pair.Value.ToString()); + component.InitNetFields(); + + obj.addComponent(pair.Key, component); + + + } + obj.InitNetFields(); + + if (!Revitalize.ModCore.ObjectGroups.ContainsKey(additionalSaveData["GUID"])) + { + Revitalize.ModCore.ObjectGroups.Add(additionalSaveData["GUID"], obj); + return obj; + } + else + { + return Revitalize.ModCore.ObjectGroups[additionalSaveData["GUID"]]; + } + + + } + + + public override bool canBePlacedHere(GameLocation l, Vector2 tile) + { + return base.canBePlacedHere(l, tile); + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/Furniture/ChairTileComponent.cs b/GeneralMods/Revitalize/Framework/Objects/Furniture/ChairTileComponent.cs new file mode 100644 index 00000000..1b72aa2c --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/Furniture/ChairTileComponent.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using PyTK.CustomElementHandler; +using Revitalize.Framework.Objects.InformationFiles.Furniture; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Objects.Furniture +{ + /// + /// Chair "piece" which represents one of the objects in the game that takes up roughly one tile. + /// + public class ChairTileComponent:FurnitureTileComponent + { + public ChairInformation furnitureInfo; + + /// + /// Checks if the player can sit "on" this component. + /// + public bool CanSitHere + { + get + { + return (this.furnitureInfo as InformationFiles.Furniture.ChairInformation).canSitHere; + } + } + + public ChairTileComponent():base() + { + + } + + public ChairTileComponent(BasicItemInformation Info,ChairInformation FurnitureInfo) : base(Info) + { + this.furnitureInfo = FurnitureInfo; + } + + public ChairTileComponent(BasicItemInformation Info,Vector2 TileLocation, ChairInformation FurnitureInfo) : base(Info, TileLocation) + { + this.furnitureInfo = FurnitureInfo; + } + + + + /// + /// When the chair is right clicked ensure that all pieces associated with it are also rotated. + /// + /// + /// + public override bool rightClicked(Farmer who) + { + this.containerObject.rotate(); //Ensure that all of the chair pieces rotate at the same time. + + checkForSpecialUpSittingAnimation(); + return true; + //return base.rightClicked(who); + } + + /// + /// Used for more object interactions. + /// When the chair is shift right clicked sit on that specific chair tile if you can sit there. + /// + /// + /// + public override bool shiftRightClicked(Farmer who) + { + if (this.CanSitHere) + { + Revitalize.ModCore.playerInfo.sittingInfo.sit(this.containerObject, this.TileLocation*Game1.tileSize); + if(this.containerObject is Bench) + { + (this.containerObject as Bench).playersSittingHere.Add(Game1.player.uniqueMultiplayerID); + } + foreach(KeyValuePair pair in this.containerObject.objects) + { + (pair.Value as ChairTileComponent).checkForSpecialUpSittingAnimation(); + } + + } + return base.shiftRightClicked(who); + } + + + public override Item getOne() + { + ChairTileComponent component = new ChairTileComponent(this.info, (ChairInformation)this.furnitureInfo); + component.containerObject = this.containerObject; + component.offsetKey = this.offsetKey; + return component; + } + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + //instead of using this.offsetkey.x use get additional save data function and store offset key there + + Vector2 offsetKey = new Vector2(Convert.ToInt32(additionalSaveData["offsetKeyX"]), Convert.ToInt32(additionalSaveData["offsetKeyY"])); + ChairTileComponent self = Revitalize.ModCore.Serializer.DeserializeGUID(additionalSaveData["GUID"]); + if (self == null) + { + return null; + } + + if (!Revitalize.ModCore.ObjectGroups.ContainsKey(additionalSaveData["ParentGUID"])) + { + //Get new container + ChairMultiTiledObject obj = (ChairMultiTiledObject)Revitalize.ModCore.Serializer.DeserializeGUID(additionalSaveData["ParentGUID"]); + self.containerObject = obj; + obj.addComponent(offsetKey, self); + //Revitalize.ModCore.log("ADD IN AN OBJECT!!!!"); + Revitalize.ModCore.ObjectGroups.Add(additionalSaveData["ParentGUID"], obj); + } + else + { + self.containerObject = Revitalize.ModCore.ObjectGroups[additionalSaveData["ParentGUID"]]; + Revitalize.ModCore.ObjectGroups[additionalSaveData["GUID"]].addComponent(offsetKey, self); + //Revitalize.ModCore.log("READD AN OBJECT!!!!"); + } + + return (ICustomObject)self; + } + + public override Dictionary getAdditionalSaveData() + { + Dictionary saveData = base.getAdditionalSaveData(); + Revitalize.ModCore.Serializer.SerializeGUID(this.containerObject.childrenGuids[this.offsetKey].ToString(), this); + + return saveData; + + } + + + /// + ///Used to manage graphics for chairs that need to deal with special "layering" for transparent chair backs. Otherwise the player would be hidden. + /// + public void checkForSpecialUpSittingAnimation() + { + if (this.info.facingDirection == Enums.Direction.Up && Revitalize.ModCore.playerInfo.sittingInfo.SittingObject == this.containerObject) + { + string animationKey = "Sitting_" + (int)Enums.Direction.Up; + if (this.animationManager.animations.ContainsKey(animationKey)) + { + this.animationManager.setAnimation(animationKey); + } + } + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/Furniture/CustomFurniture.cs b/GeneralMods/Revitalize/Framework/Objects/Furniture/CustomFurniture.cs new file mode 100644 index 00000000..7ef18e8b --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/Furniture/CustomFurniture.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Revitalize.Framework.Objects.InformationFiles.Furniture; + +namespace Revitalize.Framework.Objects.Furniture +{ + public class CustomFurniture:CustomObject + { + public FurnitureInformation furnitureInfo; + + + public CustomFurniture() : base() + { + + } + + public CustomFurniture(BasicItemInformation itemInfo, FurnitureInformation furnitureInfo) : base(itemInfo) + { + this.furnitureInfo = furnitureInfo; + } + + public CustomFurniture(BasicItemInformation itemInfo, Vector2 TileLocation, FurnitureInformation furnitureInfo) : base(itemInfo, TileLocation) + { + this.furnitureInfo = furnitureInfo; + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/Furniture/FurnitureTileComponent.cs b/GeneralMods/Revitalize/Framework/Objects/Furniture/FurnitureTileComponent.cs new file mode 100644 index 00000000..7c5661c2 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/Furniture/FurnitureTileComponent.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Revitalize.Framework.Objects.InformationFiles; +using Revitalize.Framework.Objects.InformationFiles.Furniture; + +namespace Revitalize.Framework.Objects.Furniture +{ + public class FurnitureTileComponent:MultiTiledComponent + { + + + public FurnitureTileComponent():base() + { + + } + + public FurnitureTileComponent(BasicItemInformation itemInfo):base(itemInfo) + { + } + + public FurnitureTileComponent(BasicItemInformation itemInfo,Vector2 TileLocation) : base(itemInfo,TileLocation) + { + + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/GarbageTest.cs b/GeneralMods/Revitalize/Framework/Objects/GarbageTest.cs new file mode 100644 index 00000000..0da2c209 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/GarbageTest.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using PyTK.CustomElementHandler; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Objects +{ + public class GarbageTest:CustomObject + { + public GarbageTest() + { + + } + + public GarbageTest(BasicItemInformation info) : base(info) + { + + } + + public GarbageTest(BasicItemInformation info,Vector2 TileLocation) : base(info,TileLocation) + { + + } + + public override Item getOne() + { + return new GarbageTest(this.info); + } + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + CustomObjectData data = CustomObjectData.collection[additionalSaveData["id"]]; + return new GarbageTest((BasicItemInformation)data, (replacement as Chest).TileLocation); + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/InformationFiles/Furniture/ChairInformation.cs b/GeneralMods/Revitalize/Framework/Objects/InformationFiles/Furniture/ChairInformation.cs new file mode 100644 index 00000000..f1e4fe33 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/InformationFiles/Furniture/ChairInformation.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Revitalize.Framework.Objects.InformationFiles.Furniture +{ + public class ChairInformation:FurnitureInformation + { + public bool canSitHere; + + public ChairInformation():base() + { + + } + + public ChairInformation(bool CanSitHere) : base() + { + this.canSitHere = CanSitHere; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/InformationFiles/Furniture/FurnitureInformation.cs b/GeneralMods/Revitalize/Framework/Objects/InformationFiles/Furniture/FurnitureInformation.cs new file mode 100644 index 00000000..2df3b252 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/InformationFiles/Furniture/FurnitureInformation.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Revitalize.Framework.Objects.InformationFiles.Furniture +{ + public class FurnitureInformation + { + public FurnitureInformation() + { + + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/MultiTiledComponent.cs b/GeneralMods/Revitalize/Framework/Objects/MultiTiledComponent.cs new file mode 100644 index 00000000..335b121c --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/MultiTiledComponent.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using PyTK.CustomElementHandler; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Objects +{ + public class MultiTiledComponent : CustomObject,ISaveElement + { + public MultiTiledObject containerObject; + + public Vector2 offsetKey; + + public MultiTiledComponent() { } + + public MultiTiledComponent(BasicItemInformation info) : base(info) { } + + public MultiTiledComponent(BasicItemInformation info, Vector2 TileLocation,MultiTiledObject obj=null) : base(info, TileLocation) { + this.containerObject = obj; + } + + public MultiTiledComponent(BasicItemInformation info, Vector2 TileLocation,Vector2 offsetKey ,MultiTiledObject obj = null) : base(info, TileLocation) { + this.offsetKey = offsetKey; + this.containerObject = obj; + } + + public override bool isPassable() + { + return this.info.ignoreBoundingBox || Revitalize.ModCore.playerInfo.sittingInfo.SittingObject == this.containerObject; + } + + public override bool checkForAction(Farmer who, bool justCheckingForActivity = false) + { + //ModCore.log("Checking for a clicky click???"); + return base.checkForAction(who, justCheckingForActivity); + } + + public override bool clicked(Farmer who) + { + //ModCore.log("Clicked a multiTiledComponent!"); + this.containerObject.pickUp(); + return true; + //return base.clicked(who); + } + + public override bool rightClicked(Farmer who) + { + if (this.location == null) + this.location = Game1.player.currentLocation; + //this.info.lightManager.toggleLights(this.location, this); + + //ModCore.playerInfo.sittingInfo.sit(this, Vector2.Zero); + + return true; + } + + + + public override void performRemoveAction(Vector2 tileLocation, GameLocation environment) + { + this.location = null; + base.performRemoveAction(this.TileLocation, environment); + } + + public virtual void removeFromLocation(GameLocation location, Vector2 offset) + { + location.removeObject(this.TileLocation, false); + this.location = null; + //this.performRemoveAction(this.TileLocation,location); + } + + /// Places an object down. + public override bool placementAction(GameLocation location, int x, int y, Farmer who = null) + { + this.updateDrawPosition(x, y); + this.location = location; + + if (this.location == null) this.location = Game1.player.currentLocation; + this.TileLocation = new Vector2((int)(x / Game1.tileSize), (int)(y / Game1.tileSize)); + + return base.placementAction(location, x, y, who); + } + + public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color c, bool drawShadow) + { + if (drawStackNumber && this.maximumStackSize() > 1 && ((double)scaleSize > 0.3 && this.Stack != int.MaxValue) && this.Stack > 1) + Utility.drawTinyDigits(this.Stack, spriteBatch, location + new Vector2((float)(Game1.tileSize - Utility.getWidthOfTinyDigitString(this.Stack, 3f * scaleSize)) + 3f * scaleSize, (float)((double)Game1.tileSize - 18.0 * (double)scaleSize + 2.0)), 3f * scaleSize, 1f, Color.White); + if (drawStackNumber && this.Quality > 0) + { + float num = this.Quality < 4 ? 0.0f : (float)((Math.Cos((double)Game1.currentGameTime.TotalGameTime.Milliseconds * Math.PI / 512.0) + 1.0) * 0.0500000007450581); + spriteBatch.Draw(Game1.mouseCursors, location + new Vector2(12f, (float)(Game1.tileSize - 12) + num), new Microsoft.Xna.Framework.Rectangle?(this.Quality < 4 ? new Microsoft.Xna.Framework.Rectangle(338 + (this.Quality - 1) * 8, 400, 8, 8) : new Microsoft.Xna.Framework.Rectangle(346, 392, 8, 8)), Color.White * transparency, 0.0f, new Vector2(4f, 4f), (float)(3.0 * (double)scaleSize * (1.0 + (double)num)), SpriteEffects.None, layerDepth); + } + spriteBatch.Draw(this.displayTexture, location + new Vector2((float)(Game1.tileSize / 4), (float)(Game1.tileSize * .75)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * transparency, 0f, new Vector2((float)(this.animationManager.currentAnimation.sourceRectangle.Width / 2), (float)(this.animationManager.currentAnimation.sourceRectangle.Height)), scaleSize, SpriteEffects.None, layerDepth); + } + + public override Item getOne() + { + MultiTiledComponent component = new MultiTiledComponent(this.info, this.TileLocation,this.offsetKey,this.containerObject); + return component; + } + + public override object getReplacement() + { + return base.getReplacement(); + } + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + //instead of using this.offsetkey.x use get additional save data function and store offset key there + + Vector2 offsetKey = new Vector2(Convert.ToInt32(additionalSaveData["offsetKeyX"]), Convert.ToInt32(additionalSaveData["offsetKeyY"])); + MultiTiledComponent self = Revitalize.ModCore.Serializer.DeserializeGUID( additionalSaveData["GUID"]); + if (self == null) + { + return null; + } + + if (!Revitalize.ModCore.ObjectGroups.ContainsKey(additionalSaveData["ParentGUID"])) + { + //Get new container + MultiTiledObject obj = (MultiTiledObject)Revitalize.ModCore.Serializer.DeserializeGUID(additionalSaveData["ParentGUID"]); + self.containerObject = obj; + obj.addComponent(offsetKey, self); + //Revitalize.ModCore.log("ADD IN AN OBJECT!!!!"); + Revitalize.ModCore.ObjectGroups.Add(additionalSaveData["ParentGUID"], (MultiTiledObject)obj); + } + else + { + self.containerObject = Revitalize.ModCore.ObjectGroups[additionalSaveData["ParentGUID"]]; + Revitalize.ModCore.ObjectGroups[additionalSaveData["GUID"]].addComponent(offsetKey, self); + //Revitalize.ModCore.log("READD AN OBJECT!!!!"); + } + + return (ICustomObject)self; + } + + public override Dictionary getAdditionalSaveData() + { + Dictionary saveData= base.getAdditionalSaveData(); + saveData.Add("ParentID", this.containerObject.info.id); + saveData.Add("offsetKeyX", this.offsetKey.X.ToString()); + saveData.Add("offsetKeyY", this.offsetKey.Y.ToString()); + string saveLocation = ""; + if (this.location == null) + { + //Revitalize.ModCore.log("WHY IS LOCTION NULL???"); + saveLocation = ""; + } + else + { + if (!string.IsNullOrEmpty(this.location.uniqueName.Value)) saveLocation = this.location.uniqueName.Value; + else + { + saveLocation = this.location.Name; + } + } + + + saveData.Add("GameLocationName", saveLocation); + saveData.Add("Rotation", ((int)this.info.facingDirection).ToString()); + + saveData.Add("ParentGUID", this.containerObject.guid.ToString()); + saveData.Add("GUID", this.guid.ToString()); + Revitalize.ModCore.Serializer.SerializeGUID(this.containerObject.childrenGuids[this.offsetKey].ToString(),this); + + return saveData; + + } + + protected string recreateParentId(string id) + { + StringBuilder b = new StringBuilder(); + string[] splits = id.Split('.'); + for(int i = 0; i < splits.Length - 1; i++) + { + b.Append(splits[i]); + if (i == splits.Length - 2) continue; + b.Append("."); + } + return b.ToString(); + } + + /// What happens when the object is drawn at a tile location. + public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1f) + { + if (this.info == null) Revitalize.ModCore.log("info is null"); + if (this.animationManager == null) Revitalize.ModCore.log("Animation Manager Null"); + if (this.displayTexture == null) Revitalize.ModCore.log("Display texture is null"); + if (x <= -1) + { + spriteBatch.Draw(this.info.animationManager.getTexture(), Game1.GlobalToLocal(Game1.viewport, this.info.drawPosition), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, (float)(this.TileLocation.Y * Game1.tileSize) / 10000f)); + } + else + { + //The actual planter box being drawn. + if (this.animationManager == null) + { + if (this.animationManager.getExtendedTexture() == null) + ModCore.ModMonitor.Log("Tex Extended is null???"); + + spriteBatch.Draw(this.displayTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * Game1.tileSize), y * Game1.tileSize)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, (float)(this.TileLocation.Y * Game1.tileSize) / 10000f)); + // Log.AsyncG("ANIMATION IS NULL?!?!?!?!"); + } + + else + { + //Log.AsyncC("Animation Manager is working!"); + float addedDepth = 0; + + + if (Revitalize.ModCore.playerInfo.sittingInfo.SittingObject == this.containerObject && this.info.facingDirection == Enums.Direction.Up) + { + addedDepth += (this.containerObject.Height - 1) - ((int)(this.offsetKey.Y)); + if (this.info.ignoreBoundingBox) addedDepth+=1.5f; + } + else if (this.info.ignoreBoundingBox) + { + addedDepth += 1.0f; + } + this.animationManager.draw(spriteBatch, this.displayTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * Game1.tileSize), y * Game1.tileSize)), new Rectangle?(this.animationManager.currentAnimation.sourceRectangle), this.info.drawColor * alpha, 0f, Vector2.Zero, (float)Game1.pixelZoom, this.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0f, (float)((this.TileLocation.Y + addedDepth) * Game1.tileSize) / 10000f)); + try + { + this.animationManager.tickAnimation(); + // Log.AsyncC("Tick animation"); + } + catch (Exception err) + { + ModCore.ModMonitor.Log(err.ToString()); + } + } + + // spriteBatch.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, new Vector2((float)((double)tileLocation.X * (double)Game1.tileSize + (((double)tileLocation.X * 11.0 + (double)tileLocation.Y * 7.0) % 10.0 - 5.0)) + (float)(Game1.tileSize / 2), (float)((double)tileLocation.Y * (double)Game1.tileSize + (((double)tileLocation.Y * 11.0 + (double)tileLocation.X * 7.0) % 10.0 - 5.0)) + (float)(Game1.tileSize / 2))), new Rectangle?(new Rectangle((int)((double)tileLocation.X * 51.0 + (double)tileLocation.Y * 77.0) % 3 * 16, 128 + this.whichForageCrop * 16, 16, 16)), Color.White, 0.0f, new Vector2(8f, 8f), (float)Game1.pixelZoom, SpriteEffects.None, (float)(((double)tileLocation.Y * (double)Game1.tileSize + (double)(Game1.tileSize / 2) + (((double)tileLocation.Y * 11.0 + (double)tileLocation.X * 7.0) % 10.0 - 5.0)) / 10000.0)); + } + } + + + + } +} diff --git a/GeneralMods/Revitalize/Framework/Objects/MultiTiledObject.cs b/GeneralMods/Revitalize/Framework/Objects/MultiTiledObject.cs new file mode 100644 index 00000000..8cc01385 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Objects/MultiTiledObject.cs @@ -0,0 +1,314 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Newtonsoft.Json; +using PyTK.CustomElementHandler; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Objects +{ + public class MultiTiledObject : CustomObject + { + [JsonIgnore] + public Dictionary objects; + + public Dictionary childrenGuids; + + private int width; + private int height; + public int Width + { + get + { + return this.width+1; + } + } + public int Height + { + get + { + return this.height+1; + } + } + + public MultiTiledObject() + { + this.objects = new Dictionary(); + this.childrenGuids = new Dictionary(); + this.guid = Guid.NewGuid(); + } + + public MultiTiledObject(BasicItemInformation info) + : base(info) + { + this.objects = new Dictionary(); + this.childrenGuids = new Dictionary(); + this.guid = Guid.NewGuid(); + } + + public MultiTiledObject(BasicItemInformation info, Vector2 TileLocation) + : base(info, TileLocation) + { + this.objects = new Dictionary(); + this.childrenGuids = new Dictionary(); + this.guid = Guid.NewGuid(); + } + + public MultiTiledObject(BasicItemInformation info, Vector2 TileLocation, Dictionary ObjectsList) + : base(info, TileLocation) + { + this.objects = new Dictionary(); + this.childrenGuids = new Dictionary(); + foreach (var v in ObjectsList) + { + MultiTiledComponent component =(MultiTiledComponent) v.Value.getOne(); + this.addComponent(v.Key, (component as MultiTiledComponent)); + } + this.guid = Guid.NewGuid(); + + } + + public bool addComponent(Vector2 key, MultiTiledComponent obj) + { + if (this.objects.ContainsKey(key)) + return false; + + this.objects.Add(key, obj); + this.childrenGuids.Add(key, Guid.NewGuid()); + + if (key.X > this.width) this.width = (int)key.X; + if (key.Y > this.height) this.height = (int)key.Y; + (obj as MultiTiledComponent).containerObject = this; + (obj as MultiTiledComponent).offsetKey = key; + return true; + } + + public bool removeComponent(Vector2 key) + { + + + if (!this.objects.ContainsKey(key)) + return false; + + this.objects.Remove(key); + return true; + } + + public override void draw(SpriteBatch spriteBatch, int x, int y, float alpha = 1) + { + foreach (KeyValuePair pair in this.objects) + pair.Value.draw(spriteBatch, x + (int)pair.Key.X * Game1.tileSize, y + (int)pair.Key.Y * Game1.tileSize, alpha); + } + + public override void draw(SpriteBatch spriteBatch, int xNonTile, int yNonTile, float layerDepth, float alpha = 1) + { + foreach (KeyValuePair pair in this.objects) + pair.Value.draw(spriteBatch, xNonTile + (int)pair.Key.X * Game1.tileSize, yNonTile + (int)pair.Key.Y * Game1.tileSize, layerDepth, alpha); + + //base.draw(spriteBatch, xNonTile, yNonTile, layerDepth, alpha); + } + + public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber, Color c, bool drawShadow) + { + foreach (KeyValuePair pair in this.objects) + pair.Value.drawInMenu(spriteBatch, location + (pair.Key * 16), 1.0f, transparency, layerDepth, drawStackNumber, c, drawShadow); + //base.drawInMenu(spriteBatch, location, scaleSize, transparency, layerDepth, drawStackNumber, c, drawShadow); + } + + public override void drawWhenHeld(SpriteBatch spriteBatch, Vector2 objectPosition, Farmer f) + { + foreach (KeyValuePair pair in this.objects) + pair.Value.drawWhenHeld(spriteBatch, objectPosition + (pair.Key * Game1.tileSize), f); + //base.drawWhenHeld(spriteBatch, objectPosition, f); + } + + + public override void drawPlacementBounds(SpriteBatch spriteBatch, GameLocation location) + { + foreach (KeyValuePair pair in this.objects) + { + if (!this.isPlaceable()) + return; + int x = Game1.getOldMouseX() + Game1.viewport.X+ (int)((pair.Value as MultiTiledComponent).offsetKey.X*Game1.tileSize); + int y = Game1.getOldMouseY() + Game1.viewport.Y+ (int)((pair.Value as MultiTiledComponent).offsetKey.Y * Game1.tileSize); + if ((double)Game1.mouseCursorTransparency == 0.0) + { + x = ((int)Game1.player.GetGrabTile().X+ (int)((pair.Value as MultiTiledComponent).offsetKey.X)) * 64; + y = ((int)Game1.player.GetGrabTile().Y + (int)((pair.Value as MultiTiledComponent).offsetKey.Y)) * 64; + } + if (Game1.player.GetGrabTile().Equals(Game1.player.getTileLocation()) && (double)Game1.mouseCursorTransparency == 0.0) + { + Vector2 translatedVector2 = Utility.getTranslatedVector2(Game1.player.GetGrabTile(), Game1.player.FacingDirection, 1f); + translatedVector2 += (pair.Value as MultiTiledComponent).offsetKey; + x = (int)translatedVector2.X * 64; + y = (int)translatedVector2.Y * 64; + } + bool flag = Utility.playerCanPlaceItemHere(location, (Item)pair.Value, x, y, Game1.player); + spriteBatch.Draw(Game1.mouseCursors, new Vector2((float)(x / 64 * 64 - Game1.viewport.X), (float)(y / 64 * 64 - Game1.viewport.Y)), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(flag ? 194 : 210, 388, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, 0.01f); + this.draw(spriteBatch, x / 64, y / 64, 0.5f); + } + } + + + + public virtual void pickUp() + { + bool canPickUp = this.removeAndAddToPlayersInventory(); + if (canPickUp) + { + foreach (KeyValuePair pair in this.objects) + (pair.Value as MultiTiledComponent).removeFromLocation((pair.Value as MultiTiledComponent).location, pair.Key); + this.location = null; + } + else + Game1.showRedMessage("NOOOOOOOO"); + } + + public override bool removeAndAddToPlayersInventory() + { + if (Game1.player.isInventoryFull()) + { + Game1.showRedMessage("Inventory full."); + return false; + } + Game1.player.addItemToInventory(this); + return true; + } + + public override bool placementAction(GameLocation location, int x, int y, Farmer who = null) + { + foreach (KeyValuePair pair in this.objects) + { + pair.Value.placementAction(location, x + (int)pair.Key.X * Game1.tileSize, y + (int)pair.Key.Y * Game1.tileSize, who); + //ModCore.log(pair.Value.TileLocation); + } + this.location = location; + return true; + //return base.placementAction(location, x, y, who); + } + + public override bool canBePlacedHere(GameLocation l, Vector2 tile) + { + foreach (KeyValuePair pair in this.objects) + { + if (!pair.Value.canBePlacedHere(l, tile + pair.Key)) + return false; + } + return true; + + } + public override bool clicked(Farmer who) + { + bool cleanUp = this.clicked(who); + if (cleanUp) + this.pickUp(); + return cleanUp; + } + + public override bool rightClicked(Farmer who) + { + return base.rightClicked(who); + } + + public override bool shiftRightClicked(Farmer who) + { + return base.shiftRightClicked(who); + } + + public override bool checkForAction(Farmer who, bool justCheckingForActivity = false) + { + + return base.checkForAction(who, justCheckingForActivity); + } + + public override Item getOne() + { + Dictionary objs = new Dictionary(); + foreach (var pair in this.objects) + { + objs.Add(pair.Key, (MultiTiledComponent)pair.Value); + } + return new MultiTiledObject(this.info, this.TileLocation, objs); + } + + public override ICustomObject recreate(Dictionary additionalSaveData, object replacement) + { + MultiTiledObject obj = (MultiTiledObject)Revitalize.ModCore.Serializer.DeserializeGUID(additionalSaveData["GUID"]); + if (obj == null) + { + return null; + } + + Dictionary guids = new Dictionary(); + + foreach(KeyValuePair pair in obj.childrenGuids) + { + guids.Add(pair.Key, pair.Value); + } + + foreach(KeyValuePair pair in guids) + { + obj.childrenGuids.Remove(pair.Key); + //Revitalize.ModCore.log("DESERIALIZE: " + pair.Value.ToString()); + MultiTiledComponent component= Revitalize.ModCore.Serializer.DeserializeGUID(pair.Value.ToString()); + component.InitNetFields(); + + obj.addComponent(pair.Key, component); + + + } + obj.InitNetFields(); + + if (!Revitalize.ModCore.ObjectGroups.ContainsKey(additionalSaveData["GUID"])) + { + Revitalize.ModCore.ObjectGroups.Add(additionalSaveData["GUID"], obj); + return obj; + } + else + { + return Revitalize.ModCore.ObjectGroups[additionalSaveData["GUID"]]; + } + + + } + + public override Dictionary getAdditionalSaveData() + { + Dictionary saveData= base.getAdditionalSaveData(); + + Revitalize.ModCore.log("Serialize: " + this.guid.ToString()); + + saveData.Add("GUID", this.guid.ToString()); + + Revitalize.ModCore.Serializer.SerializeGUID(this.guid.ToString(), this); + return saveData; + } + + public void setAllAnimationsToDefault() + { + foreach(KeyValuePair pair in this.objects) + { + string animationKey = (pair.Value as MultiTiledComponent) .generateDefaultRotationalAnimationKey(); + if ((pair.Value as MultiTiledComponent).animationManager.animations.ContainsKey(animationKey)) + { + (pair.Value as MultiTiledComponent).animationManager.setAnimation(animationKey); + } + } + } + + public override bool canStackWith(Item other) + { + return false; + } + + public override int maximumStackSize() + { + return 1; + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Player/Managers/MagicManager.cs b/GeneralMods/Revitalize/Framework/Player/Managers/MagicManager.cs new file mode 100644 index 00000000..1ad80afe --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Player/Managers/MagicManager.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Revitalize.Framework.Player.Managers +{ + public class MagicManager + { + public int maxMagic; + public int currentMagic; + + public MagicManager() + { + this.currentMagic = 100; + this.maxMagic = 100; + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Player/Managers/SittingInfo.cs b/GeneralMods/Revitalize/Framework/Player/Managers/SittingInfo.cs new file mode 100644 index 00000000..ff818e54 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Player/Managers/SittingInfo.cs @@ -0,0 +1,149 @@ +using Microsoft.Xna.Framework; +using Revitalize.Framework.Objects; +using Revitalize.Framework.Objects.Furniture; +using StardewValley; + +namespace Revitalize.Framework.Player.Managers +{ + // TODO: + // - Make chair + // - animate player better + public class SittingInfo + { + /// If the player is currently sitting. + public bool isSitting; + + /// How long a Farmer has sat (in milliseconds) + private int elapsedTime; + + /// Gets how long the farmer has sat (in milliseconds). + public int ElapsedTime => this.elapsedTime; + + /// Keeps trck of time elapsed. + GameTime timer; + + /// How long a player has to sit to recover energy/health; + public int SittingSpan { get; } + + StardewValley.Object sittingObject; + + public StardewValley.Object SittingObject + { + get + { + return this.sittingObject; + } + } + + /// Construct an instance. + public SittingInfo() + { + this.timer = Game1.currentGameTime; + this.SittingSpan = 10000; + } + + /// Update the sitting info. + public void update() + { + if (Game1.activeClickableMenu != null) return; + + if (Game1.player.isMoving()) + { + this.isSitting = false; + this.elapsedTime = 0; + if(this.sittingObject is MultiTiledObject && (this.sittingObject.GetType()!=typeof(Bench))) + { + (this.sittingObject as MultiTiledObject).setAllAnimationsToDefault(); + this.sittingObject = null; + } + else if(this.sittingObject is Bench) + { + (this.sittingObject as Bench).playersSittingHere.Remove(Game1.player.uniqueMultiplayerID); + if((this.sittingObject as Bench).playersSittingHere.Count == 0) + { + (this.sittingObject as MultiTiledObject).setAllAnimationsToDefault(); + } + } + this.sittingObject = null; + + + } + if (this.isSitting && Game1.player.CanMove) + { + this.showSitting(); + if (this.timer == null) this.timer = Game1.currentGameTime; + this.elapsedTime += this.timer.ElapsedGameTime.Milliseconds; + } + + if (this.elapsedTime >= this.SittingSpan) + { + this.elapsedTime %= this.SittingSpan; + Game1.player.health++; + Game1.player.Stamina++; + } + + } + + /// + /// Display the farmer actually sitting. + /// + public void showSitting() + { + if (this.sittingObject == null) + { + switch (Game1.player.FacingDirection) + { + case 0: + Game1.player.FarmerSprite.setCurrentSingleFrame(113); + break; + case 1: + Game1.player.FarmerSprite.setCurrentSingleFrame(106); + break; + case 2: + Game1.player.FarmerSprite.setCurrentSingleFrame(107); + break; + case 3: + Game1.player.FarmerSprite.setCurrentSingleFrame(106); + break; + } + } + else + { + if(this.sittingObject is CustomObject) + { + Game1.player.faceDirection((int)(this.sittingObject as CustomObject).info.facingDirection); + switch ((this.sittingObject as CustomObject).info.facingDirection) + { + + case Enums.Direction.Up: + + Game1.player.FarmerSprite.setCurrentSingleFrame(113); + break; + case Enums.Direction.Right: + Game1.player.FarmerSprite.setCurrentSingleFrame(106); + break; + case Enums.Direction.Down: + Game1.player.FarmerSprite.setCurrentSingleFrame(107); + break; + case Enums.Direction.Left: + Game1.player.FarmerSprite.setCurrentSingleFrame(106,32000,false,true); + break; + } + } + } + } + + /// + /// Make the player sit. + /// + /// + /// + public void sit(StardewValley.Object obj, Vector2 offset) + { + this.isSitting = true; + Game1.player.Position = (obj.TileLocation * Game1.tileSize + offset); + Game1.player.position.Y += Game1.tileSize / 2; + this.sittingObject = obj; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Player/PlayerInfo.cs b/GeneralMods/Revitalize/Framework/Player/PlayerInfo.cs new file mode 100644 index 00000000..275e6355 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Player/PlayerInfo.cs @@ -0,0 +1,21 @@ +using Revitalize.Framework.Player.Managers; + +namespace Revitalize.Framework.Player +{ + public class PlayerInfo + { + public SittingInfo sittingInfo; + public MagicManager magicManager; + + public PlayerInfo() + { + this.sittingInfo = new SittingInfo(); + this.magicManager = new MagicManager(); + } + + public void update() + { + this.sittingInfo.update(); + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/BoundingBoxInfo.cs b/GeneralMods/Revitalize/Framework/Utilities/BoundingBoxInfo.cs new file mode 100644 index 00000000..baed3795 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/BoundingBoxInfo.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Revitalize.Framework.Objects; +using StardewValley; + +namespace Revitalize.Framework.Utilities +{ + /// + /// Deals with calculating bounding boxes on objects. + /// + public class BoundingBoxInfo + { + /// + /// The number of tiles in size for this bounding box; + /// + public Rectangle tileSize; + /// + /// The pixel offset for this bounding box dimensions. + /// + public Rectangle pixelOffsets; + + public BoundingBoxInfo() + { + + } + + /// + /// Constructor + /// + /// How big in tiles this bounding box is. + public BoundingBoxInfo(Rectangle TileSize) + { + this.tileSize = TileSize; + this.pixelOffsets = new Rectangle(0, 0, 0, 0); + } + + /// + /// Constructor. + /// + /// How big in tiles this bounding box is. + /// The offset in size and position in pixels. + public BoundingBoxInfo(Rectangle TileSize,Rectangle PixelOffsets) + { + this.tileSize = TileSize; + this.pixelOffsets = PixelOffsets; + } + + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/InventoryManager.cs b/GeneralMods/Revitalize/Framework/Utilities/InventoryManager.cs new file mode 100644 index 00000000..1265d65d --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/InventoryManager.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using StardewValley; + +namespace Revitalize.Framework.Utilities +{ + /// Handles dealing with objects. + public class InventoryManager + { + /// How many items the inventory can hold. + public int capacity; + + /// The hard uper limit for # of items to be held in case of upgrading or resizing. + public int MaxCapacity { get; private set; } + + /// How many items are currently stored in the inventory. + public int ItemCount => this.items.Count; + + /// The actual contents of the inventory. + public List items; + + /// Checks if the inventory is full or not. + public bool IsFull => this.ItemCount >= this.capacity; + + /// Checks to see if this core object actually has a valid inventory. + public bool HasInventory => this.capacity > 0; + + public InventoryManager() + { + this.capacity = 0; + this.setMaxLimit(0); + this.items = new List(); + } + + /// Construct an instance. + public InventoryManager(List items) + { + this.capacity = int.MaxValue; + this.setMaxLimit(int.MaxValue); + this.items = items; + } + + /// Construct an instance. + public InventoryManager(int capacity) + { + this.capacity = capacity; + this.MaxCapacity = int.MaxValue; + this.items = new List(); + } + + /// Construct an instance. + public InventoryManager(int capacity, int MaxCapacity) + { + this.capacity = capacity; + this.setMaxLimit(MaxCapacity); + this.items = new List(); + } + + /// Add the item to the inventory. + public bool addItem(Item item) + { + if (this.IsFull) + { + return false; + } + else + { + foreach (Item self in this.items) + { + if (self != null && self.canStackWith(item)) + { + self.addToStack(item.Stack); + return true; + } + } + this.items.Add(item); + return true; + } + } + + /// Gets a reference to the object IF it exists in the inventory. + public Item getItem(Item item) + { + foreach (Item i in this.items) + { + if (item == i) + return item; + } + return null; + } + + /// Get the item at the specific index. + public Item getItemAtIndex(int index) + { + return this.items[index]; + } + + /// Gets only one item from the stack. + public Item getSingleItemFromStack(Item item) + { + if (item.Stack == 1) + return item; + + item.Stack = item.Stack - 1; + return item.getOne(); + } + + /// Empty the inventory. + public void clear() + { + this.items.Clear(); + } + + /// Empty the inventory. + public void empty() + { + this.clear(); + } + + /// Resize how many items can be held by this object. + public void resizeCapacity(int Amount) + { + if (this.capacity + Amount < this.MaxCapacity) + this.capacity += Amount; + } + + /// Sets the upper limity of the capacity size for the inventory. + public void setMaxLimit(int amount) + { + this.MaxCapacity = amount; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/ContractResolvers/NetFieldContract.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/ContractResolvers/NetFieldContract.cs new file mode 100644 index 00000000..b17298fc --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/ContractResolvers/NetFieldContract.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Revitalize.Framework.Utilities.Serialization.ContractResolvers +{ + public class NetFieldContract : DefaultContractResolver + { + public static NetFieldContract Instance { get; } = new NetFieldContract(); + + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) + { + JsonProperty property = base.CreateProperty(member, memberSerialization); + if (member.Name == nameof(StardewValley.Item.NetFields)) + { + property.Ignored = true; + } + return property; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/ItemCoverter.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/ItemCoverter.cs new file mode 100644 index 00000000..3ad55edd --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/ItemCoverter.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; +using StardewValley; + +namespace Revitalize.Framework.Utilities.Serialization.Converters +{ + public class ItemCoverter:Newtonsoft.Json.JsonConverter + { + public static Dictionary AllTypes = new Dictionary(); + + JsonSerializerSettings settings; + public ItemCoverter() + { + this.settings = new JsonSerializerSettings() + { + Converters = new List() + { + new Framework.Utilities.Serialization.Converters.RectangleConverter(), + new Framework.Utilities.Serialization.Converters.Texture2DConverter() + }, + Formatting = Formatting.Indented, + ReferenceLoopHandling = ReferenceLoopHandling.Ignore, + NullValueHandling = NullValueHandling.Include + }; + } + + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + string convertedString = JsonConvert.SerializeObject((Item)value, this.settings); + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + writer.WriteStartObject(); + writer.WritePropertyName("Type"); + serializer.Serialize(writer, value.GetType().FullName.ToString()); + writer.WritePropertyName("Item"); + serializer.Serialize(writer, convertedString); + + writer.WriteEndObject(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + + throw new JsonSerializationException("Cant convert to item!"); + return null; + } + + JObject jo = JObject.Load(reader); + + string t = jo["Type"].Value(); + + //See if the type has already been cached and if so return it for deserialization. + if (AllTypes.ContainsKey(t)) + { + + return JsonConvert.DeserializeObject(jo["Item"].ToString(), AllTypes[t], this.settings); + } + + Assembly asm = typeof(StardewValley.Object).Assembly; + Type type = null; + + type = asm.GetType(t); + + if (type == null) + { + asm = typeof(Revitalize.ModCore).Assembly; + type = asm.GetType(t); + } + + if (type == null) + { + foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + asm = assembly; + type = asm.GetType(t); + if (t != null) break; + } + } + + if (type == null) + { + throw new Exception("Unsupported type found when Deserializing Unsure what to do so we can;t deserialize this thing!: " + t); + } + + //Cache the newly found type. + AllTypes.Add(t, type); + + return JsonConvert.DeserializeObject(jo["Item"].ToString(),type, this.settings); + /* + if (t== typeof(StardewValley.Tools.Axe).FullName.ToString()) + { + Revitalize.ModCore.log("DESERIALIZE AXE!!!"); + //return jo["Item"].Value(); + return JsonConvert.DeserializeObject(jo["Item"].ToString(),this.settings); + } + else if (t == typeof(Revitalize.Framework.Objects.MultiTiledObject).FullName.ToString()) + { + + Revitalize.ModCore.log("DESERIALIZE Multi Tile Object!!!"); + return JsonConvert.DeserializeObject(jo["Item"].ToString(), this.settings); + // return jo["Item"].Value(); + + } + else if (t == typeof(Revitalize.Framework.Objects.MultiTiledComponent).FullName.ToString()) + { + + Revitalize.ModCore.log("DESERIALIZE Multi Tile Component!!!"); + return JsonConvert.DeserializeObject(jo["Item"].ToString(), this.settings); + // return jo["Item"].Value(); + + } + + else + { + + throw new NotImplementedException("CANT DESERIALIZE: " + t.ToString()); + } + */ + + + } + + public override bool CanWrite => true; + public override bool CanRead => true; + + public override bool CanConvert(Type objectType) + { + return IsSameOrSubclass(typeof(StardewValley.Item),objectType); + } + + /// + /// https://stackoverflow.com/questions/2742276/how-do-i-check-if-a-type-is-a-subtype-or-the-type-of-an-object + /// + /// + /// + /// + public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant) + { + return potentialDescendant.IsSubclassOf(potentialBase) + || potentialDescendant == potentialBase; + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/NetFieldConverter.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/NetFieldConverter.cs new file mode 100644 index 00000000..06552ce7 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/NetFieldConverter.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace Revitalize.Framework.Utilities.Serialization.Converters +{ + + public class NetFieldConverter:JsonConverter + { + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteValue("NetFields"); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, + JsonSerializer serializer) + { + + string str = (string)reader.Value; + //string str=jsonObject.ToObject(serializer); + + return new Netcode.NetFields(); + return null; + } + + public override bool CanConvert(Type objectType) + { + return objectType == typeof(Netcode.NetFields); + } + + public override bool CanRead => true; + public override bool CanWrite => true; + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/RectangleConverter.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/RectangleConverter.cs new file mode 100644 index 00000000..f986ca35 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/RectangleConverter.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Newtonsoft.Json; + +namespace Revitalize.Framework.Utilities.Serialization.Converters +{ + public class RectangleConverter : JsonConverter + { + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + var rect = (Rectangle)value; + writer.WriteValue(rect.ToString()); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, + JsonSerializer serializer) + { + + string str = (string)reader.Value; + //string str=jsonObject.ToObject(serializer); + + + //string str = reader.ReadAsString(); + str = str.Replace("{", ""); + str = str.Replace("}", ""); + str = str.Replace("X:", ""); + str = str.Replace("Y:", ""); + str = str.Replace("Width:", ""); + str = str.Replace("Height:", ""); + + string[] values = str.Split(' '); + int x = Convert.ToInt32(values[0]); + int y = Convert.ToInt32(values[1]); + int w = Convert.ToInt32(values[2]); + int h = Convert.ToInt32(values[3]); + + + return new Rectangle(x, y, w, h); + } + + public override bool CanConvert(Type objectType) + { + return objectType == typeof(Rectangle); + } + + public override bool CanRead => true; + public override bool CanWrite => true; + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/Texture2DConverter.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/Texture2DConverter.cs new file mode 100644 index 00000000..5f73bc18 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/Texture2DConverter.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Newtonsoft.Json; +using Revitalize.Framework.Graphics; +using StardewValley; + +namespace Revitalize.Framework.Utilities.Serialization.Converters +{ + public class Texture2DConverter : JsonConverter + { + + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + var texture = (Texture2D)value; + writer.WriteValue(texture.Name); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + string textureName = reader.Value as string; + //ModCore.log(textureName); + if (string.IsNullOrEmpty(textureName)) return new Texture2D(Game1.graphics.GraphicsDevice, 2, 2); + string[] names = textureName.Split('.'); + if (names.Length == 0) return null; + + if (!TextureManager.TextureManagers.ContainsKey(names[0])) return null; + return textureName == null ? null : Revitalize.Framework.Graphics.TextureManager.TextureManagers[names[0]].getTexture(names[1]).texture; + } + + public override bool CanConvert(Type objectType) + { + return objectType == typeof(Texture2D); + } + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/Vector2Converter.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/Vector2Converter.cs new file mode 100644 index 00000000..b0f31f3c --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Converters/Vector2Converter.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Newtonsoft.Json; + +namespace Revitalize.Framework.Utilities.Serialization.Converters +{ + public class Vector2Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + var rect = (Vector2)value; + writer.WriteValue(rect.ToString()); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, + JsonSerializer serializer) + { + + string str = (string)reader.Value; + //string str=jsonObject.ToObject(serializer); + + + //string str = reader.ReadAsString(); + str = str.Replace(",", ""); + + string[] values = str.Split(' '); + double x = Convert.ToDouble(values[0]); + double y = Convert.ToDouble(values[1]); + + + return new Vector2((float)x, (float)y); + } + + public override bool CanConvert(Type objectType) + { + return objectType == typeof(Vector2); + } + + public override bool CanRead => true; + public override bool CanWrite => true; + } +} diff --git a/GeneralMods/Revitalize/Framework/Utilities/Serialization/Serialization.cs b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Serialization.cs new file mode 100644 index 00000000..dd99a092 --- /dev/null +++ b/GeneralMods/Revitalize/Framework/Utilities/Serialization/Serialization.cs @@ -0,0 +1,303 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Revitalize.Framework.Utilities.Serialization.ContractResolvers; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize.Framework.Utilities +{ + /// + /// Handles serialization of all objects in existence. + /// + /// TODO: Make JConvert that has same settings to implement a toJSon string obj + /// + public class Serializer + { + private JsonSerializer serializer; + + /// + /// All files to be cleaned up after loading. + /// + private Dictionary> filesToDelete = new Dictionary>(); + + public List itemsToRemove = new List(); + + private JsonSerializerSettings settings; + + /// + /// Constructor. + /// + public Serializer() + { + this.serializer = new JsonSerializer(); + this.serializer.Formatting = Formatting.Indented; + this.serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + this.serializer.NullValueHandling = NullValueHandling.Include; + + this.serializer.ContractResolver = new NetFieldContract(); + + this.addConverter(new Framework.Utilities.Serialization.Converters.RectangleConverter()); + this.addConverter(new Framework.Utilities.Serialization.Converters.Texture2DConverter()); + this.addConverter(new Framework.Utilities.Serialization.Converters.ItemCoverter()); + //this.addConverter(new Framework.Utilities.Serialization.Converters.NetFieldConverter()); + //this.addConverter(new Framework.Utilities.Serialization.Converters.Vector2Converter()); + + gatherAllFilesForCleanup(); + + this.settings = new JsonSerializerSettings(); + foreach(JsonConverter converter in this.serializer.Converters) + { + this.settings.Converters.Add(converter); + } + this.settings.Formatting = Formatting.Indented; + this.settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + this.settings.NullValueHandling = NullValueHandling.Include; + this.settings.ContractResolver = new NetFieldContract(); + } + + /// + /// Process all the save data for objects to be deleted by this mod. + /// + private void gatherAllFilesForCleanup() + { + this.filesToDelete.Clear(); + string[] directories = Directory.GetDirectories(Path.Combine(Revitalize.ModCore.ModHelper.DirectoryPath, "SaveData")); + foreach (string playerData in directories) + { + string objectPath = Path.Combine(playerData, "SavedObjectInformation"); + string[] objectFiles = Directory.GetFiles(objectPath); + foreach (string file in objectFiles) + { + string playerName = new DirectoryInfo(objectPath).Parent.Name; + if (this.filesToDelete.ContainsKey(playerName)){ + this.filesToDelete[playerName].Add(file); + //Revitalize.ModCore.log("Added File: " + file); + } + else + { + this.filesToDelete.Add(playerName, new List()); + //Revitalize.ModCore.log("Added Player Key: " + playerName); + this.filesToDelete[playerName].Add(file); + //Revitalize.ModCore.log("Added File: " + file); + } + + } + } + } + + /// + /// Called after load to deal with internal file cleanUp + /// + public void afterLoad() + { + deleteAllUnusedFiles(); + removeNullObjects(); + } + + public void returnToTitle() + { + gatherAllFilesForCleanup(); + } + + private void removeNullObjects() + { + List removalList = new List(); + foreach(Item I in Game1.player.items) + { + if (I == null) continue; + if (I.DisplayName.Contains("Revitalize.Framework") && (I is Chest)) + { + removalList.Add(I); + } + + } + foreach(Item I in removalList) + { + Game1.player.items.Remove(I); + } + } + + /// + /// Removes the file from all files that will be deleted. + /// + /// + /// + private void removeFileFromDeletion(string playerDirectory, string fileName) + { + if (this.filesToDelete.ContainsKey(playerDirectory)) + { + //Revitalize.ModCore.log("Removing from deletion: " + fileName); + this.filesToDelete[playerDirectory].Remove(fileName); + } + else + { + //Revitalize.ModCore.log("Found key: " + playerDirectory); + //Revitalize.ModCore.log("Found file: " + fileName); + } + } + + /// + /// Deletes unused object data. + /// + private void deleteAllUnusedFiles() + { + foreach(KeyValuePair> pair in this.filesToDelete) + { + foreach (string file in pair.Value) + { + File.Delete(file); + } + } + } + + /// + /// Adds a new converter to the json serializer. + /// + /// The type of json converter to add to the Serializer. + public void addConverter(JsonConverter converter) + { + this.serializer.Converters.Add(converter); + } + + + /// + /// Deserializes an object from a .json file. + /// + /// The type of object to deserialize into. + /// The path to the file. + /// An object of specified type T. + public T Deserialize(string p) + { + string json = ""; + foreach (string line in File.ReadLines(p)) + { + json += line; + } + using (StreamReader sw = new StreamReader(p)) + using (JsonReader reader = new JsonTextReader(sw)) + { + var obj = this.serializer.Deserialize(reader); + return obj; + } + } + + /// + /// Deserializes an object from a .json file. + /// + /// The type of object to deserialize into. + /// The path to the file. + /// An object of specified type T. + public object Deserialize(string p,Type T) + { + string json = ""; + foreach (string line in File.ReadLines(p)) + { + json += line; + } + using (StreamReader sw = new StreamReader(p)) + using (JsonReader reader = new JsonTextReader(sw)) + { + object obj = this.serializer.Deserialize(reader,T); + return obj; + } + } + + /// + /// Serializes an object to a .json file. + /// + /// + /// + public void Serialize(string path, object o) + { + using (StreamWriter sw = new StreamWriter(path)) + using (JsonWriter writer = new JsonTextWriter(sw)) + { + this.serializer.Serialize(writer, o); + } + } + + /// + /// Serialize a data structure into an file. + /// + /// + /// + public void SerializeGUID(string fileName,object obj) + { + string path = Path.Combine(Revitalize.ModCore.ModHelper.DirectoryPath, "SaveData", Game1.player.name + "_" + Game1.player.uniqueMultiplayerID, "SavedObjectInformation", fileName + ".json"); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + Serialize(path, obj); + } + + /// + /// Deserialze a file into it's proper data structure. + /// + /// The type of data structure to deserialze to. + /// The name of the file to deserialize from. + /// A data structure object deserialize from a json string in a file. + public object DeserializeGUID(string fileName,Type T) + { + string path=Path.Combine(Revitalize.ModCore.ModHelper.DirectoryPath, "SaveData", Game1.player.name + "_" + Game1.player.uniqueMultiplayerID, "SavedObjectInformation", fileName + ".json"); + removeFileFromDeletion((Game1.player.name + "_" + Game1.player.uniqueMultiplayerID), path); + return Deserialize(path, T); + } + + /// + /// Deserialze a file into it's proper data structure. + /// + /// The type of data structure to deserialze to. + /// The name of the file to deserialize from. + /// A data structure object deserialize from a json string in a file. + public T DeserializeGUID(string fileName) + { + string path = Path.Combine(Revitalize.ModCore.ModHelper.DirectoryPath, "SaveData", Game1.player.name + "_" + Game1.player.uniqueMultiplayerID, "SavedObjectInformation", fileName + ".json"); + removeFileFromDeletion((Game1.player.name + "_" + Game1.player.uniqueMultiplayerID),path); + if (File.Exists(path)) + { + + return Deserialize(path); + } + else + { + return default(T); + } + } + + /// + /// Converts objects to json form. + /// + /// + /// + public string ToJSONString(object o) + { + return JsonConvert.SerializeObject(o, this.settings); + } + + /// + /// Converts from json form to objects. + /// + /// + /// + /// + public T DeserializeFromJSONString(string info) + { + return JsonConvert.DeserializeObject(info,this.settings); + } + + /// + /// Converts from json form to objects. + /// + /// + /// + /// + public object DeserializeFromJSONString(string info, Type T) + { + return JsonConvert.DeserializeObject(info, T, this.settings); + } + + } +} diff --git a/GeneralMods/Revitalize/ModCore.cs b/GeneralMods/Revitalize/ModCore.cs new file mode 100644 index 00000000..2a2229f1 --- /dev/null +++ b/GeneralMods/Revitalize/ModCore.cs @@ -0,0 +1,325 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Xna.Framework; +using PyTK.Extensions; +using PyTK.Types; +using Revitalize.Framework; +using Revitalize.Framework.Crafting; +using Revitalize.Framework.Environment; +using Revitalize.Framework.Graphics; +using Revitalize.Framework.Graphics.Animations; +using Revitalize.Framework.Illuminate; +using Revitalize.Framework.Objects; +using Revitalize.Framework.Player; +using Revitalize.Framework.Utilities; +using StardewModdingAPI; +using StardewValley; +using StardewValley.Objects; + +namespace Revitalize +{ + // TODO: + // + // -Multiple Lights On Object + // -Illumination Colors + // Furniture: + // -rugs + // -tables + // -lamps + // -chairs (done) + // -benches + // -dressers/other storage containers + // -fun interactables + // -More crafting tables + // -Machines + // !=Energy + // -Furnace + // -Seed Maker + // -Stone Quarry + // -Materials + // -Tin/Bronze/Alluminum/Silver?Platinum/Etc + // -Crafting Menu + // -Item Grab Menu (Extendable) + // -Gift Boxes + // Magic! + // -Alchemy Bags + // -Transmutation + // -Effect Crystals + // -Spell books + // -Potions! + // -Magic Meter + // -Connected chests much like Project EE2 from MC + // + // + // + // -Bigger chests + // + // Festivals + // -Firework festival? + // Stargazing??? + // -Moon Phases+DarkerNight + // Bigger/Better Museum? + // More Crops? + // More Food? + // + // Equippables! + // -accessories that provide buffs/regen/friendship + // -braclets/rings/broaches....more crafting for these??? + // + // Music??? + // -IDK maybe add in instruments??? + // + // More buildings???? + // + // More Animals??? + // + // Readable Books? + // + // Custom NPCs for shops??? + // + // Frisbee Minigame? + // + // HorseRace Minigame/Betting? + // + // Locations: + // -Small Island Home? + // + // More crops + // + // More monsters + // -boss fights + // + // More dungeons?? + + + public class ModCore : Mod + { + public static IModHelper ModHelper; + public static IMonitor ModMonitor; + + public static Dictionary customObjects; + + public static DictionaryObjectGroups; + + public static PlayerInfo playerInfo; + + public static Serializer Serializer; + + public override void Entry(IModHelper helper) + { + ModHelper = helper; + ModMonitor = this.Monitor; + + this.createDirectories(); + this.initailizeComponents(); + + ModHelper.Events.GameLoop.SaveLoaded += this.GameLoop_SaveLoaded; + ModHelper.Events.GameLoop.TimeChanged += this.GameLoop_TimeChanged; + ModHelper.Events.GameLoop.UpdateTicked += this.GameLoop_UpdateTicked; + ModHelper.Events.GameLoop.ReturnedToTitle += this.GameLoop_ReturnedToTitle; + playerInfo = new PlayerInfo(); + + Framework.Graphics.TextureManager.TextureManagers.Add("Furniture", new TextureManager()); + TextureManager.addTexture("Furniture","Oak Chair", new Texture2DExtended(this.Helper, this.ModManifest, Path.Combine("Content","Graphics","Furniture", "Chairs", "OakChair.png"))); + + customObjects = new Dictionary(); + ObjectGroups = new Dictionary(); + + loadContent(); + Serializer = new Serializer(); + + } + + private void GameLoop_ReturnedToTitle(object sender, StardewModdingAPI.Events.ReturnedToTitleEventArgs e) + { + Serializer.returnToTitle(); + } + + private void loadContent() + { + MultiTiledComponent obj = new MultiTiledComponent(new BasicItemInformation("CoreObjectTest", "YAY FUN!", "Omegasis.Revitalize.MultiTiledComponent", Color.White, -300, 0, false, 100, Vector2.Zero, true, true, "Omegasis.TEST1", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, true, typeof(MultiTiledComponent), null, new AnimationManager(TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair"), new Animation(new Rectangle(0, 0, 16, 16))), Color.Red, true, null, null)); + MultiTiledComponent obj2 = new MultiTiledComponent(new BasicItemInformation("CoreObjectTest2", "SomeFun", "Omegasis.Revitalize.MultiTiledComponent", Color.White, -300, 0, false, 100, Vector2.Zero, true, true, "Omegasis.TEST1", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, true, typeof(MultiTiledComponent), null, new AnimationManager(TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair"), new Animation(new Rectangle(0, 16, 16, 16))), Color.Red, false, null, null)); + MultiTiledComponent obj3 = new MultiTiledComponent(new BasicItemInformation("CoreObjectTest3", "NoFun", "Omegasis.Revitalize.MultiTiledComponent", Color.White, -300, 0, false, 100, Vector2.Zero, true, true, "Omegasis.TEST1", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, true, typeof(MultiTiledComponent), null, new AnimationManager(TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair"), new Animation(new Rectangle(0, 32, 16, 16))), Color.Red, false, null, null)); + + + obj.info.lightManager.addLight(new Vector2(Game1.tileSize), new LightSource(4, new Vector2(0, 0), 2.5f, Color.Orange.Invert()), obj); + + MultiTiledObject bigObject = new MultiTiledObject(new BasicItemInformation("MultiTest", "A really big object", "Omegasis.Revitalize.MultiTiledObject", Color.Blue, -300, 0, false, 100, Vector2.Zero, true, true, "Omegasis.BigTiledTest", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, true, typeof(MultiTiledObject), null, new AnimationManager(), Color.White, false, null, null)); + bigObject.addComponent(new Vector2(0, 0), obj); + bigObject.addComponent(new Vector2(1, 0), obj2); + bigObject.addComponent(new Vector2(2, 0), obj3); + + Recipe pie = new Recipe(new Dictionary() + { + [bigObject] = 1 + }, new KeyValuePair(new Furniture(3, Vector2.Zero), 1), new StatCost(100, 50, 0, 0)); + + + + Framework.Objects.Furniture.ChairTileComponent chairTop = new Framework.Objects.Furniture.ChairTileComponent(new BasicItemInformation("Oak Chair", "A basic wooden chair", "Chairs", Color.Brown, -300, 0, false, 100, Vector2.Zero, true, true, "Omegasis.Revitalize.Furniture.Basic.OakChair", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", Framework.Graphics.TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, false, typeof(Framework.Objects.Furniture.ChairTileComponent), null, new AnimationManager(TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair"), new Animation(new Rectangle(0, 0, 16, 16)), new Dictionary>() { + { "Default_" + (int)Framework.Enums.Direction.Down , new List() + { + new Animation(new Rectangle(0,0,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Down , new List() + { + new Animation(new Rectangle(0,0,16,16)) + } + }, + { "Default_" + (int)Framework.Enums.Direction.Right , new List() + { + new Animation(new Rectangle(16,0,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Right , new List() + { + new Animation(new Rectangle(16,0,16,16)) + } + }, + { "Default_" + (int)Framework.Enums.Direction.Up , new List() + { + new Animation(new Rectangle(32,0,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Up , new List() + { + new Animation(new Rectangle(32,32,16,32)) + } + }, + { "Default_" + (int)Framework.Enums.Direction.Left , new List() + { + new Animation(new Rectangle(48,0,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Left , new List() + { + new Animation(new Rectangle(48,0,16,16)) + } + } + }, "Default_" + (int)Framework.Enums.Direction.Down), Color.White, true, new Framework.Utilities.InventoryManager(), new LightManager()), new Framework.Objects.InformationFiles.Furniture.ChairInformation(false)); + + + Framework.Objects.Furniture.ChairTileComponent chairBottom = new Framework.Objects.Furniture.ChairTileComponent(new BasicItemInformation("Oak Chair", "A basic wooden chair", "Chairs", Color.Brown, -300, 0, false, 100, Vector2.Zero, true, true, "Omegasis.Revitalize.Furniture.Basic.OakChair", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", Framework.Graphics.TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, false, typeof(Framework.Objects.Furniture.ChairTileComponent), null, new AnimationManager(TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair"), new Animation(new Rectangle(0, 16, 16, 16)), new Dictionary>() { + { "Default_" + (int)Framework.Enums.Direction.Down , new List() + { + new Animation(new Rectangle(0,16,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Down , new List() + { + new Animation(new Rectangle(0,16,16,16)) + } + }, + { "Default_" + (int)Framework.Enums.Direction.Right , new List() + { + new Animation(new Rectangle(16,16,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Right , new List() + { + new Animation(new Rectangle(16,16,16,16)) + } + }, + { "Default_" + (int)Framework.Enums.Direction.Up , new List() + { + new Animation(new Rectangle(32,16,16,16)) + } + }, + { "Sitting_" + (int)Framework.Enums.Direction.Up , new List() + { + new Animation(new Rectangle(48,32,16,32)) + } + }, + { "Default_" + (int)Framework.Enums.Direction.Left , new List() + { + new Animation(new Rectangle(48,16,16,16)) + } + }, + { "Sitting" + (int)Framework.Enums.Direction.Left , new List() + { + new Animation(new Rectangle(48,16,16,16)) + } + } + }, "Default_" + (int)Framework.Enums.Direction.Down), Color.White, false, new Framework.Utilities.InventoryManager(), new LightManager()), new Framework.Objects.InformationFiles.Furniture.ChairInformation(true)); + + + Framework.Objects.Furniture.ChairMultiTiledObject oakChair = new Framework.Objects.Furniture.ChairMultiTiledObject(new BasicItemInformation("Oak Chair", "A wood chair you can place anywhere.", "Chair", Color.White, -300, 0, true, 100, Vector2.Zero, true, true, "Omegasis.Revitalize.Furniture.OakChair", "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048", TextureManager.TextureManagers["Furniture"].getTexture("Oak Chair").texture, Color.White, 0, true, typeof(Revitalize.Framework.Objects.Furniture.ChairMultiTiledObject), null, new AnimationManager(), Color.White, false, new Framework.Utilities.InventoryManager(), new LightManager())); + oakChair.addComponent(new Vector2(0, 0), chairTop); + oakChair.addComponent(new Vector2(0, 1), chairBottom); + + customObjects.Add("Omegasis.BigTiledTest", bigObject); + customObjects.Add("Omegasis.Revitalize.Furniture.Chairs.OakChair",oakChair); + } + + private void createDirectories() + { + Directory.CreateDirectory(Path.Combine(this.Helper.DirectoryPath, "Configs")); + + Directory.CreateDirectory(Path.Combine(this.Helper.DirectoryPath, "Content")); + Directory.CreateDirectory(Path.Combine(this.Helper.DirectoryPath,"Content" ,"Graphics")); + Directory.CreateDirectory(Path.Combine(this.Helper.DirectoryPath, "Content", "Graphics","Furniture")); + Directory.CreateDirectory(Path.Combine(this.Helper.DirectoryPath, "Content", "Graphics", "Furniture","Chairs")); + } + + private void initailizeComponents() + { + DarkerNight.InitializeConfig(); + } + + private void GameLoop_UpdateTicked(object sender, StardewModdingAPI.Events.UpdateTickedEventArgs e) + { + DarkerNight.SetDarkerColor(); + playerInfo.update(); + } + + private void GameLoop_TimeChanged(object sender, StardewModdingAPI.Events.TimeChangedEventArgs e) + { + DarkerNight.CalculateDarkerNightColor(); + } + + private void GameLoop_SaveLoaded(object sender, StardewModdingAPI.Events.SaveLoadedEventArgs e) + { + Serializer.afterLoad(); + + if (Game1.IsServer || Game1.IsMultiplayer || Game1.IsClient) + { + throw new Exception("Can't run Revitalize in multiplayer due to lack of current support!"); + } + //Game1.player.addItemToInventory(customObjects["Omegasis.BigTiledTest"].getOne()); + Game1.player.addItemToInventory(getObjectFromPool("Omegasis.Revitalize.Furniture.Chairs.OakChair")); + + /* + StardewValley.Tools.Axe axe = new StardewValley.Tools.Axe(); + Serializer.Serialize(Path.Combine(this.Helper.DirectoryPath, "AXE.json"), axe); + axe =(StardewValley.Tools.Axe)Serializer.Deserialize(Path.Combine(this.Helper.DirectoryPath, "AXE.json"),typeof(StardewValley.Tools.Axe)); + //Game1.player.addItemToInventory(axe); + */ + + } + + public Item getObjectFromPool(string objName) + { + if (customObjects.ContainsKey(objName)) + { + return customObjects[objName]; + } + else + { + throw new Exception("Object Key name not found: " + objName); + } + } + + + public static void log(object message) + { + ModMonitor.Log(message.ToString()); + } + + public static string generatePlaceholderString() + { + return "2048/0/-300/Crafting -9/Play '2048 by Platonymous' at home!/true/true/0/2048"; + } + } +} diff --git a/GeneralMods/Revitalize/Properties/AssemblyInfo.cs b/GeneralMods/Revitalize/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..9463f7af --- /dev/null +++ b/GeneralMods/Revitalize/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Revitalize")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Revitalize")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("44ef6cec-fbf1-4b45-8135-81d4ebe84ddd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/GeneralMods/Revitalize/Revitalize.csproj b/GeneralMods/Revitalize/Revitalize.csproj new file mode 100644 index 00000000..e1fa1111 --- /dev/null +++ b/GeneralMods/Revitalize/Revitalize.csproj @@ -0,0 +1,93 @@ + + + + + Debug + AnyCPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD} + Library + Properties + Revitalize + Revitalize + v4.6.1 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + 12.0.1 + + + + + + $(GamePath)\Mods\PyTK\PyTK.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GeneralMods/Revitalize/manifest.json b/GeneralMods/Revitalize/manifest.json new file mode 100644 index 00000000..8ce50f03 --- /dev/null +++ b/GeneralMods/Revitalize/manifest.json @@ -0,0 +1,10 @@ +{ + "Name": "Revitalize", + "Author": "Alpha_Omegasis", + "Version": "0.0.1", + "Description": "A mod that attempts to add in a variety of new things to Stardew.", + "UniqueID": "Omegasis.Revitalize", + "EntryDll": "Revitalize.dll", + "MinimumApiVersion": "2.10.1", + "UpdateKeys": [] +} diff --git a/GeneralMods/SaveAnywhere/Framework/ModConfig.cs b/GeneralMods/SaveAnywhere/Framework/ModConfig.cs index 2fc20210..a43b4f22 100644 --- a/GeneralMods/SaveAnywhere/Framework/ModConfig.cs +++ b/GeneralMods/SaveAnywhere/Framework/ModConfig.cs @@ -1,9 +1,11 @@ -namespace Omegasis.SaveAnywhere.Framework +using StardewModdingAPI; + +namespace Omegasis.SaveAnywhere.Framework { /// The mod configuration. internal class ModConfig { /// The key which initiates a save. - public string SaveKey { get; set; } = "K"; + public SButton SaveKey { get; set; } = SButton.K; } } diff --git a/GeneralMods/SaveAnywhere/Framework/Models/CharacterType.cs b/GeneralMods/SaveAnywhere/Framework/Models/CharacterType.cs index da6e2530..39d40429 100644 --- a/GeneralMods/SaveAnywhere/Framework/Models/CharacterType.cs +++ b/GeneralMods/SaveAnywhere/Framework/Models/CharacterType.cs @@ -1,4 +1,4 @@ -namespace Omegasis.SaveAnywhere.Framework.Models +namespace Omegasis.SaveAnywhere.Framework.Models { /// The character type for an NPC. public enum CharacterType diff --git a/GeneralMods/SaveAnywhere/Framework/Models/PositionData.cs b/GeneralMods/SaveAnywhere/Framework/Models/PositionData.cs index 5708b451..17ac9cf8 100644 --- a/GeneralMods/SaveAnywhere/Framework/Models/PositionData.cs +++ b/GeneralMods/SaveAnywhere/Framework/Models/PositionData.cs @@ -1,4 +1,4 @@ -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; namespace Omegasis.SaveAnywhere.Framework.Models { diff --git a/GeneralMods/SaveAnywhere/Framework/NewSaveGameMenu.cs b/GeneralMods/SaveAnywhere/Framework/NewSaveGameMenu.cs index b3917895..6a5523c1 100644 --- a/GeneralMods/SaveAnywhere/Framework/NewSaveGameMenu.cs +++ b/GeneralMods/SaveAnywhere/Framework/NewSaveGameMenu.cs @@ -1,40 +1,34 @@ -using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; using StardewValley.BellsAndWhistles; using StardewValley.Menus; -using System; -using System.Collections.Generic; -using System.Text; namespace Omegasis.SaveAnywhere.Framework { - /// A marker subclass to detect when a custom save is in progress. - internal class NewSaveGameMenu : SaveGameMenu { - + internal class NewSaveGameMenu : SaveGameMenu + { public event EventHandler SaveComplete; private int completePause = -1; private int margin = 500; - private StringBuilder _stringBuilder = new StringBuilder(); + private readonly StringBuilder _stringBuilder = new StringBuilder(); private float _ellipsisDelay = 0.5f; private IEnumerator loader; public bool quit; public bool hasDrawn; - private SparklingText saveText; + private readonly SparklingText saveText; private int _ellipsisCount; - + public NewSaveGameMenu() { - this.saveText = new SparklingText(Game1.dialogueFont, Game1.content.LoadString("Strings\\StringsFromCSFiles:SaveGameMenu.cs.11378"), Color.LimeGreen, new Color((int)(Color.Black.R * (1.0 / 1000.0)),(int)( Color.Black.G * (1.0 / 1000.0)),(int)( Color.Black.B * (1.0 / 1000.0)),255), false, 0.1, 1500, 32, 500); + this.saveText = new SparklingText(Game1.dialogueFont, Game1.content.LoadString("Strings\\StringsFromCSFiles:SaveGameMenu.cs.11378"), Color.LimeGreen, new Color((int)(Color.Black.R * (1.0 / 1000.0)), (int)(Color.Black.G * (1.0 / 1000.0)), (int)(Color.Black.B * (1.0 / 1000.0)), 255), false, 0.1, 1500, 32, 500); } - public override void receiveRightClick(int x, int y, bool playSound = true) - { - } - - public new void complete() { Game1.playSound("money"); @@ -91,9 +85,7 @@ namespace Omegasis.SaveAnywhere.Framework if (Game1.IsMasterGame) { if (Game1.saveOnNewDay) - { this.loader = SaveGame.Save(); - } else { this.margin = -1; @@ -105,7 +97,6 @@ namespace Omegasis.SaveAnywhere.Framework NewSaveGameMenu.saveClientOptions(); this.complete(); } - } if (this.completePause < 0) return; @@ -171,8 +162,4 @@ namespace Omegasis.SaveAnywhere.Framework Game1.game1.IsSaving = false; } } - - } - - diff --git a/GeneralMods/SaveAnywhere/Framework/NewShippingMenu.cs b/GeneralMods/SaveAnywhere/Framework/NewShippingMenu.cs index 87dd59e6..d66b3681 100644 --- a/GeneralMods/SaveAnywhere/Framework/NewShippingMenu.cs +++ b/GeneralMods/SaveAnywhere/Framework/NewShippingMenu.cs @@ -1,4 +1,4 @@ -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Netcode; using StardewModdingAPI; using StardewValley; @@ -10,14 +10,12 @@ namespace Omegasis.SaveAnywhere.Framework internal class NewShippingMenu : ShippingMenu { /********* - ** Properties + ** Fields *********/ /// The private field on the shipping menu which indicates the game has already been saved, which prevents it from saving. private readonly IReflectedField SavedYet; - - /********* ** Public methods *********/ @@ -30,12 +28,7 @@ namespace Omegasis.SaveAnywhere.Framework this.SavedYet = reflection.GetField(this, "savedYet"); } - /// - /// Overrides some base functionality of the shipping menu to enable proper closing. - /// - /// - /// - /// + /// Overrides some base functionality of the shipping menu to enable proper closing. public override void receiveLeftClick(int x, int y, bool playSound = true) { if (this.okButton.containsPoint(x, y)) this.exitThisMenu(true); diff --git a/GeneralMods/SaveAnywhere/Framework/SaveManager.cs b/GeneralMods/SaveAnywhere/Framework/SaveManager.cs index 16eb42b1..a26bc946 100644 --- a/GeneralMods/SaveAnywhere/Framework/SaveManager.cs +++ b/GeneralMods/SaveAnywhere/Framework/SaveManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -15,7 +15,7 @@ namespace Omegasis.SaveAnywhere.Framework public class SaveManager { /********* - ** Properties + ** Fields *********/ /// Simplifies access to game code. private readonly IReflectionHelper Reflection; @@ -26,8 +26,8 @@ namespace Omegasis.SaveAnywhere.Framework /// SMAPI's APIs for this mod. private readonly IModHelper Helper; - /// The full path to the player data file. - private string SavePath => Path.Combine(this.Helper.DirectoryPath, "data", $"{Constants.SaveFolderName}.json"); + /// The relative path to the player data file. + private string RelativeDataPath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); /// Whether we should save at the next opportunity. private bool WaitingToSave; @@ -52,10 +52,7 @@ namespace Omegasis.SaveAnywhere.Framework } - private void empty(object o, EventArgs args) - { - - } + private void empty(object o, EventArgs args) { } /// Perform any required update logic. public void Update() @@ -63,41 +60,41 @@ namespace Omegasis.SaveAnywhere.Framework // perform passive save if (this.WaitingToSave && Game1.activeClickableMenu == null) { - currentSaveMenu = new NewSaveGameMenu(); - currentSaveMenu.SaveComplete += CurrentSaveMenu_SaveComplete; - Game1.activeClickableMenu = currentSaveMenu; + this.currentSaveMenu = new NewSaveGameMenu(); + this.currentSaveMenu.SaveComplete += this.CurrentSaveMenu_SaveComplete; + Game1.activeClickableMenu = this.currentSaveMenu; this.WaitingToSave = false; } } - /// - /// Event function for NewSaveGameMenu event SaveComplete - /// - /// - /// + /// Event function for NewSaveGameMenu event SaveComplete + /// The event sender. + /// The event arguments. private void CurrentSaveMenu_SaveComplete(object sender, EventArgs e) { - currentSaveMenu.SaveComplete -= CurrentSaveMenu_SaveComplete; - currentSaveMenu = null; + this.currentSaveMenu.SaveComplete -= this.CurrentSaveMenu_SaveComplete; + this.currentSaveMenu = null; //AfterSave.Invoke(this, EventArgs.Empty); } /// Clear saved data. public void ClearData() { - File.Delete(this.SavePath); + if (File.Exists(Path.Combine(this.Helper.DirectoryPath, this.RelativeDataPath))) + { + File.Delete(Path.Combine(this.Helper.DirectoryPath, this.RelativeDataPath)); + } this.RemoveLegacyDataForThisPlayer(); } /// Initiate a game save. public void BeginSaveData() { - // save game data Farm farm = Game1.getFarm(); if (farm.shippingBin.Any()) { - + Game1.activeClickableMenu = new NewShippingMenu(farm.shippingBin, this.Reflection); farm.shippingBin.Clear(); farm.lastItemShipped = null; @@ -105,26 +102,22 @@ namespace Omegasis.SaveAnywhere.Framework } else { - currentSaveMenu = new NewSaveGameMenu(); - currentSaveMenu.SaveComplete += CurrentSaveMenu_SaveComplete; - Game1.activeClickableMenu = currentSaveMenu; + this.currentSaveMenu = new NewSaveGameMenu(); + this.currentSaveMenu.SaveComplete += this.CurrentSaveMenu_SaveComplete; + Game1.activeClickableMenu = this.currentSaveMenu; } - - // get data + + // save data to disk PlayerData data = new PlayerData { Time = Game1.timeOfDay, Characters = this.GetPositions().ToArray(), IsCharacterSwimming = Game1.player.swimming.Value }; + this.Helper.Data.WriteJsonFile(this.RelativeDataPath, data); - // save to disk - // ReSharper disable once PossibleNullReferenceException -- not applicable - Directory.CreateDirectory(new FileInfo(this.SavePath).Directory.FullName); - this.Helper.WriteJsonFile(this.SavePath, data); - - // clear any legacy data (no longer needed as backup)1 + // clear any legacy data (no longer needed as backup) this.RemoveLegacyDataForThisPlayer(); } @@ -132,7 +125,7 @@ namespace Omegasis.SaveAnywhere.Framework public void LoadData() { // get data - PlayerData data = this.Helper.ReadJsonFile(this.SavePath); + PlayerData data = this.Helper.Data.ReadJsonFile(this.RelativeDataPath); if (data == null) return; @@ -146,23 +139,19 @@ namespace Omegasis.SaveAnywhere.Framework //AfterLoad.Invoke(this, EventArgs.Empty); } - /// - /// Checks to see if the player was swimming when the game was saved and if so, resumes the swimming animation. - /// - /// + /// Checks to see if the player was swimming when the game was saved and if so, resumes the swimming animation. public void ResumeSwimming(PlayerData data) { try { - if (data.IsCharacterSwimming == true) + if (data.IsCharacterSwimming) { Game1.player.changeIntoSwimsuit(); Game1.player.swimming.Value = true; } } - catch (Exception err) + catch { - err.ToString(); //Here to allow compatability with old save files. } } @@ -178,7 +167,8 @@ namespace Omegasis.SaveAnywhere.Framework var player = Game1.player; string name = player.Name; string map = player.currentLocation.uniqueName.Value; //Try to get a unique name for the location and if we can't we are going to default to the actual name of the map. - if (map == ""|| map==null) map = player.currentLocation.Name; //This is used to account for maps that share the same name but have a unique ID such as Coops, Barns and Sheds. + if (string.IsNullOrEmpty(map)) + map = player.currentLocation.Name; //This is used to account for maps that share the same name but have a unique ID such as Coops, Barns and Sheds. Point tile = player.getTileLocationPoint(); int facingDirection = player.facingDirection; @@ -189,9 +179,8 @@ namespace Omegasis.SaveAnywhere.Framework foreach (NPC npc in Utility.getAllCharacters()) { CharacterType? type = this.GetCharacterType(npc); - if (type == null) + if (type == null || npc?.currentLocation == null) continue; - if (npc == null || npc.currentLocation == null) continue; string name = npc.Name; string map = npc.currentLocation.Name; Point tile = npc.getTileLocationPoint(); diff --git a/GeneralMods/SaveAnywhere/SaveAnywhere.cs b/GeneralMods/SaveAnywhere/SaveAnywhere.cs index ee824935..6d6620cf 100644 --- a/GeneralMods/SaveAnywhere/SaveAnywhere.cs +++ b/GeneralMods/SaveAnywhere/SaveAnywhere.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Omegasis.SaveAnywhere.Framework; @@ -14,7 +14,7 @@ namespace Omegasis.SaveAnywhere public class SaveAnywhere : Mod { /********* - ** Properties + ** Fields *********/ /// The mod configuration. private ModConfig Config; @@ -31,20 +31,17 @@ namespace Omegasis.SaveAnywhere /// Whether we're performing a non-vanilla save (i.e. not by sleeping in bed). private bool IsCustomSaving; - - /// - /// Used to access the Mod's helper from other files associated with the mod. - /// + /// Used to access the Mod's helper from other files associated with the mod. public static IModHelper ModHelper; - /// - /// Used to access the Mod's monitor to allow for debug logging in other files associated with the mod. - /// + + /// Used to access the Mod's monitor to allow for debug logging in other files associated with the mod. public static IMonitor ModMonitor; private List monsters; private bool customMenuOpen; + /********* ** Public methods *********/ @@ -56,30 +53,25 @@ namespace Omegasis.SaveAnywhere this.SaveManager = new SaveManager(this.Helper, this.Helper.Reflection, onLoaded: () => this.ShouldResetSchedules = true); - SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; - SaveEvents.AfterSave += this.SaveEvents_AfterSave; - ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; - GameEvents.UpdateTick += this.GameEvents_UpdateTick; - TimeEvents.AfterDayStarted += this.TimeEvents_AfterDayStarted; + helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; + helper.Events.GameLoop.Saved += this.OnSaved; + helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; + helper.Events.GameLoop.DayStarted += this.OnDayStarted; + helper.Events.Input.ButtonPressed += this.OnButtonPressed; ModHelper = helper; - ModMonitor = Monitor; - customMenuOpen = false; + ModMonitor = this.Monitor; + this.customMenuOpen = false; } - /*Notes. Mods that want to support save anywhere will get the api for Save anywhere and then add their clean up code to the events that happen for Before/After Save and Loading. - Example with pseudo code. - SaveAnywhere.api.BeforeSave+=StardustCore.Objects.CleanUpBeforeSave; - We then can use function wrapping (is that what it's called?) to just handle calling the actual function that deals with clean-up code. - */ /********* ** Private methods *********/ - /// The method invoked after the player loads a save. + /// Raised after the player loads a save slot and the world is initialised. /// The event sender. - /// The event data. - private void SaveEvents_AfterLoad(object sender, EventArgs e) + /// The event arguments. + private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { // reset state this.IsCustomSaving = false; @@ -89,34 +81,31 @@ namespace Omegasis.SaveAnywhere this.SaveManager.LoadData(); } - /// The method invoked after the player finishes saving. + /// Raised after the game finishes writing data to the save file (except the initial save creation). /// The event sender. - /// The event data. - private void SaveEvents_AfterSave(object sender, EventArgs e) + /// The event arguments. + private void OnSaved(object sender, SavedEventArgs e) { // clear custom data after a normal save (to avoid restoring old state) - if (!this.IsCustomSaving) + if (!this.IsCustomSaving) this.SaveManager.ClearData(); else { - IsCustomSaving = false; + this.IsCustomSaving = false; } } - - /// The method invoked when the game updates (roughly 60 times per second). + /// Raised after the game state is updated (≈60 times per second). /// The event sender. - /// The event data. - private void GameEvents_UpdateTick(object sender, EventArgs e) + /// The event arguments. + private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { - // let save manager run background logic if (Context.IsWorldReady) { - if (Game1.player.IsMainPlayer == false) return; + if (!Game1.player.IsMainPlayer) return; this.SaveManager.Update(); } - // reset NPC schedules if (Context.IsWorldReady && this.ShouldResetSchedules) @@ -125,10 +114,10 @@ namespace Omegasis.SaveAnywhere this.ApplySchedules(); } - if (Game1.activeClickableMenu == null && this.customMenuOpen == false) return; - if(Game1.activeClickableMenu==null && this.customMenuOpen == true) + if (Game1.activeClickableMenu == null && !this.customMenuOpen) return; + if (Game1.activeClickableMenu == null && this.customMenuOpen) { - restoreMonsters(); + this.restoreMonsters(); this.customMenuOpen = false; return; } @@ -141,49 +130,36 @@ namespace Omegasis.SaveAnywhere } } - /// - /// Saves all monsters from the game world. - /// + /// Saves all monsters from the game world. private void cleanMonsters() { - monsters = new List(); + this.monsters = new List(); - foreach (var monster in Game1.player.currentLocation.characters) + foreach (var npc in Game1.player.currentLocation.characters) { try { - if (monster is Monster) - { - monsters.Add(monster as Monster); - } - } - catch (Exception err) - { - + if (npc is Monster monster) + this.monsters.Add(monster); } + catch { } } foreach (var monster in this.monsters) - { Game1.player.currentLocation.characters.Remove(monster); - } } - /// - /// Adds all saved monster back into the game world. - /// + /// Adds all saved monster back into the game world. private void restoreMonsters() { foreach (var monster in this.monsters) - { Game1.player.currentLocation.characters.Add(monster); - } } - /// The method invoked after a new day starts. + /// Raised after the game begins a new day (including when the player loads a save). /// The event sender. - /// The event data. - private void TimeEvents_AfterDayStarted(object sender, EventArgs e) + /// The event arguments. + private void OnDayStarted(object sender, DayStartedEventArgs e) { // reload NPC schedules this.ShouldResetSchedules = true; @@ -197,22 +173,20 @@ namespace Omegasis.SaveAnywhere } } - /// The method invoked when the presses a keyboard button. + /// Raised after the player presses a button on the keyboard, controller, or mouse. /// The event sender. - /// The event data. - private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) + /// The event arguments. + private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { if (!Context.IsPlayerFree) return; - - // initiate save (if valid context) - if (e.KeyPressed.ToString() == this.Config.SaveKey) + if (e.Button == this.Config.SaveKey) { - if (Game1.client==null) + if (Game1.client == null) { - cleanMonsters(); + this.cleanMonsters(); // validate: community center Junimos can't be saved if (Game1.player.currentLocation.getCharacters().OfType().Any()) @@ -221,14 +195,13 @@ namespace Omegasis.SaveAnywhere return; } - // save this.IsCustomSaving = true; this.SaveManager.BeginSaveData(); } else { - Game1.addHUDMessage(new HUDMessage("Only server hosts can save anywhere.",HUDMessage.error_type)); + Game1.addHUDMessage(new HUDMessage("Only server hosts can save anywhere.", HUDMessage.error_type)); } } } @@ -251,16 +224,14 @@ namespace Omegasis.SaveAnywhere continue; // get schedule data - string scheduleData; - if (!this.NpcSchedules.TryGetValue(npc.Name, out scheduleData) || string.IsNullOrEmpty(scheduleData)) + if (!this.NpcSchedules.TryGetValue(npc.Name, out string scheduleData) || string.IsNullOrEmpty(scheduleData)) { //this.Monitor.Log("THIS IS AWKWARD"); continue; } // get schedule script - string script; - if (!rawSchedule.TryGetValue(scheduleData, out script)) + if (!rawSchedule.TryGetValue(scheduleData, out string script)) continue; // parse entries @@ -300,10 +271,8 @@ namespace Omegasis.SaveAnywhere .Invoke(npc.currentLocation.Name, npc.getTileX(), npc.getTileY(), endMap, x, y, endFacingDir, null, null); index++; } - catch (Exception ex) + catch { - ex.ToString(); - //this.Monitor.Log($"Error pathfinding NPC {npc.name}: {ex}", LogLevel.Error); continue; } @@ -326,7 +295,7 @@ namespace Omegasis.SaveAnywhere { return Game1.content.Load>($"Characters\\schedules\\{npcName}"); } - catch (Exception) + catch { return null; } @@ -356,14 +325,14 @@ namespace Omegasis.SaveAnywhere if ((npc.Name.Equals("Penny") && (dayName.Equals("Tue") || dayName.Equals("Wed") || dayName.Equals("Fri"))) || (npc.Name.Equals("Maru") && (dayName.Equals("Tue") || dayName.Equals("Thu"))) || (npc.Name.Equals("Harvey") && (dayName.Equals("Tue") || dayName.Equals("Thu")))) { this.Helper.Reflection - .GetField(npc, "nameofTodaysSchedule") + .GetField(npc, "nameOfTodaysSchedule") .SetValue("marriageJob"); return "marriageJob"; } if (!Game1.isRaining && schedule.ContainsKey("marriage_" + Game1.shortDayNameFromDayOfSeason(Game1.dayOfMonth))) { this.Helper.Reflection - .GetField(npc, "nameofTodaysSchedule") + .GetField(npc, "nameOfTodaysSchedule") .SetValue("marriage_" + Game1.shortDayNameFromDayOfSeason(Game1.dayOfMonth)); return "marriage_" + Game1.shortDayNameFromDayOfSeason(Game1.dayOfMonth); } @@ -375,9 +344,8 @@ namespace Omegasis.SaveAnywhere if (schedule.ContainsKey(Game1.currentSeason + "_" + Game1.dayOfMonth)) return Game1.currentSeason + "_" + Game1.dayOfMonth; int i; - Friendship f; - Game1.player.friendshipData.TryGetValue(npc.Name, out f); - for (i = (Game1.player.friendshipData.ContainsKey(npc.Name) ? (f.Points/ 250) : -1); i > 0; i--) + Game1.player.friendshipData.TryGetValue(npc.Name, out Friendship f); + for (i = (Game1.player.friendshipData.ContainsKey(npc.Name) ? (f.Points / 250) : -1); i > 0; i--) { if (schedule.ContainsKey(Game1.dayOfMonth + "_" + i)) return Game1.dayOfMonth + "_" + i; @@ -394,8 +362,7 @@ namespace Omegasis.SaveAnywhere return "rain"; } List list = new List { Game1.currentSeason, Game1.shortDayNameFromDayOfSeason(Game1.dayOfMonth) }; - Friendship friendship; - Game1.player.friendshipData.TryGetValue(npc.Name, out friendship); + Game1.player.friendshipData.TryGetValue(npc.Name, out Friendship friendship); i = (Game1.player.friendshipData.ContainsKey(npc.Name) ? (friendship.Points / 250) : -1); while (i > 0) { @@ -425,8 +392,7 @@ namespace Omegasis.SaveAnywhere } list.RemoveAt(list.Count - 1); list.Add("spring"); - Friendship friendship2; - Game1.player.friendshipData.TryGetValue(npc.Name, out friendship2); + Game1.player.friendshipData.TryGetValue(npc.Name, out Friendship friendship2); i = (Game1.player.friendshipData.ContainsKey(npc.Name) ? (friendship2.Points / 250) : -1); while (i > 0) { @@ -436,9 +402,9 @@ namespace Omegasis.SaveAnywhere i--; list.RemoveAt(list.Count - 1); } - if (schedule.ContainsKey("spring")) - return "spring"; - return null; + return schedule.ContainsKey("spring") + ? "spring" + : null; } } } diff --git a/GeneralMods/SaveAnywhere/SaveAnywhere.csproj b/GeneralMods/SaveAnywhere/SaveAnywhere.csproj index a059c773..2fb9a4ca 100644 --- a/GeneralMods/SaveAnywhere/SaveAnywhere.csproj +++ b/GeneralMods/SaveAnywhere/SaveAnywhere.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ SaveAnywhere v4.5.2 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -92,19 +93,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/SaveAnywhere/manifest.json b/GeneralMods/SaveAnywhere/manifest.json index f2a0325d..ffd84748 100644 --- a/GeneralMods/SaveAnywhere/manifest.json +++ b/GeneralMods/SaveAnywhere/manifest.json @@ -1,11 +1,11 @@ { "Name": "Save Anywhere", "Author": "Alpha_Omegasis", - "Version": "3.0.0", + "Version": "2.10.0", "Description": "Lets you save almost anywhere.", "UniqueID": "Omegasis.SaveAnywhere", "EntryDll": "SaveAnywhere.dll", - "MinimumApiVersion": "2.4", + "MinimumApiVersion": "2.10.1", "Dependencies": [ - ] + ] } diff --git a/GeneralMods/SaveAnywhere/packages.config b/GeneralMods/SaveAnywhere/packages.config deleted file mode 100644 index 30506716..00000000 --- a/GeneralMods/SaveAnywhere/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/SimpleSoundManager/Framework/Sound.cs b/GeneralMods/SimpleSoundManager/Framework/Sound.cs index 3f3d5b44..0fb68e22 100644 --- a/GeneralMods/SimpleSoundManager/Framework/Sound.cs +++ b/GeneralMods/SimpleSoundManager/Framework/Sound.cs @@ -1,38 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace SimpleSoundManager.Framework { - /// - /// Interface used for common sound functionality; - /// + /// Interface used for common sound functionality; public interface Sound { - /// - /// Handles playing a sound. - /// + /// Handles playing a sound. void play(); void play(float volume); - /// - /// Handles pausing a song. - /// + + /// Handles pausing a song. void pause(); - /// - /// Handles stopping a song. - /// + + /// Handles stopping a song. void stop(); - /// - /// Handles restarting a song. - /// + + /// Handles restarting a song. void restart(); - /// - /// Handles getting a clone of the song. - /// - /// + + /// Handles getting a clone of the song. Sound clone(); string getSoundName(); diff --git a/GeneralMods/SimpleSoundManager/Framework/SoundManager.cs b/GeneralMods/SimpleSoundManager/Framework/SoundManager.cs index a9ce5a58..7d19f501 100644 --- a/GeneralMods/SimpleSoundManager/Framework/SoundManager.cs +++ b/GeneralMods/SimpleSoundManager/Framework/SoundManager.cs @@ -1,187 +1,117 @@ -using Microsoft.Xna.Framework.Audio; +using System.Collections.Generic; +using Microsoft.Xna.Framework.Audio; using StardewModdingAPI; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SimpleSoundManager.Framework { public class SoundManager { - - public Dictionary sounds; + public Dictionary sounds; public Dictionary musicBanks; public float volume; public List currentlyPlayingSounds = new List(); - /// - /// Constructor for this class. - /// + + /// Constructor for this class. public SoundManager() { this.sounds = new Dictionary(); this.musicBanks = new Dictionary(); - currentlyPlayingSounds = new List(); + this.currentlyPlayingSounds = new List(); this.volume = 1.0f; } - /// - /// Constructor for wav files. - /// - /// - /// - public void loadWavFile(string soundName,string pathToWav) + /// Constructor for wav files. + public void loadWavFile(string soundName, string pathToWav) { - WavSound wav = new WavSound(soundName,pathToWav); + WavSound wav = new WavSound(soundName, pathToWav); SimpleSoundManagerMod.ModMonitor.Log("Getting sound file:" + soundName); try { this.sounds.Add(soundName, wav); } - catch(Exception err) - { - - } + catch { } } - - /// - /// Constructor for wav files. - /// - /// - /// - /// - public void loadWavFile(IModHelper helper,string soundName,string pathToWav) + + /// Constructor for wav files. + public void loadWavFile(IModHelper helper, string soundName, string relativePath) { - WavSound wav = new WavSound(helper ,soundName,pathToWav); + WavSound wav = new WavSound(helper, soundName, relativePath); SimpleSoundManagerMod.ModMonitor.Log("Getting sound file:" + soundName); try { this.sounds.Add(soundName, wav); } - catch(Exception err) + catch { //Sound already added so no need to worry? } } - /// - /// Constructor for wav files. - /// - /// - /// - /// - public void loadWavFile(IModHelper helper,string songName,List pathToWav) + /// Constructor for wav files. + public void loadWavFile(IModHelper helper, string songName, List pathToWav) { - WavSound wav = new WavSound(helper,songName,pathToWav); + WavSound wav = new WavSound(helper, songName, pathToWav); SimpleSoundManagerMod.ModMonitor.Log("Getting sound file:" + songName); try { this.sounds.Add(songName, wav); } - catch(Exception err) - { - - } + catch { } } - /// - /// Constructor for XACT files. - /// - /// - /// - /// + /// Constructor for XACT files. public void loadXACTFile(WaveBank waveBank, ISoundBank soundBank, string songName) { XACTSound xactSound = new XACTSound(waveBank, soundBank, songName); this.sounds.Add(songName, xactSound); } - /// - /// Constructor for XACT files based on already added music packs. - /// - /// - /// + /// Constructor for XACT files based on already added music packs. public void loadXACTFile(string pairName, string songName) { - XACTMusicPair musicPair = getMusicPack(pairName); + XACTMusicPair musicPair = this.getMusicPack(pairName); if (pairName == null) - { return; - } - loadXACTFile(musicPair.waveBank, musicPair.soundBank, songName); + this.loadXACTFile(musicPair.waveBank, musicPair.soundBank, songName); } - - /// - /// Creates a music pack pair that holds .xwb and .xsb music files. - /// + /// Creates a music pack pair that holds .xwb and .xsb music files. /// The mod's helper that will handle the path of the files. /// The name of this music pack pair. /// The relative path to the .xwb file /// The relative path to the .xsb file - public void loadXACTMusicBank(IModHelper helper,string pairName,string wavName, string soundName) + public void loadXACTMusicBank(IModHelper helper, string pairName, string wavName, string soundName) { - this.musicBanks.Add(pairName,new XACTMusicPair(helper, wavName, soundName)); + this.musicBanks.Add(pairName, new XACTMusicPair(helper, wavName, soundName)); } - /// - /// Gets the music pack pair from the sound pool. - /// - /// - /// + /// Gets the music pack pair from the sound pool. public XACTMusicPair getMusicPack(string name) { - foreach(var pack in this.musicBanks) + foreach (var pack in this.musicBanks) { - if (name == pack.Key) return pack.Value; + if (name == pack.Key) + return pack.Value; } return null; } - /// - /// Gets a clone of the loaded sound. - /// - /// - /// + /// Gets a clone of the loaded sound. public Sound getSoundClone(string name) { - foreach(var sound in this.sounds) + foreach (var sound in this.sounds) { - if (sound.Key == name) return sound.Value.clone(); + if (sound.Key == name) + return sound.Value.clone(); } return null; } - /// - /// Play the sound with the given name. - /// - /// + /// Play the sound with the given name. public void playSound(string soundName) - { - SimpleSoundManagerMod.ModMonitor.Log("Trying to play sound: " + soundName); - foreach(var sound in this.sounds) - { - if (sound.Key == soundName) - { - SimpleSoundManagerMod.ModMonitor.Log("Time to play sound: " + soundName); - var s=getSoundClone(soundName); - s.play(this.volume); - this.currentlyPlayingSounds.Add(s); - break; - } - } - } - - /// - /// Play the sound with the given name and volume. - /// - /// - /// - public void playSound(string soundName,float volume=1.0f) { SimpleSoundManagerMod.ModMonitor.Log("Trying to play sound: " + soundName); foreach (var sound in this.sounds) @@ -189,7 +119,24 @@ namespace SimpleSoundManager.Framework if (sound.Key == soundName) { SimpleSoundManagerMod.ModMonitor.Log("Time to play sound: " + soundName); - var s = getSoundClone(soundName); + var s = this.getSoundClone(soundName); + s.play(this.volume); + this.currentlyPlayingSounds.Add(s); + break; + } + } + } + + /// Play the sound with the given name and volume. + public void playSound(string soundName, float volume = 1.0f) + { + SimpleSoundManagerMod.ModMonitor.Log("Trying to play sound: " + soundName); + foreach (var sound in this.sounds) + { + if (sound.Key == soundName) + { + SimpleSoundManagerMod.ModMonitor.Log("Time to play sound: " + soundName); + var s = this.getSoundClone(soundName); s.play(volume); this.currentlyPlayingSounds.Add(s); break; @@ -197,10 +144,7 @@ namespace SimpleSoundManager.Framework } } - /// - /// Stop the sound that is playing. - /// - /// + /// Stop the sound that is playing. public void stopSound(string soundName) { List removalList = new List(); @@ -212,16 +156,11 @@ namespace SimpleSoundManager.Framework removalList.Add(sound); } } - foreach(var v in removalList) - { + foreach (var v in removalList) this.currentlyPlayingSounds.Remove(v); - } } - /// - /// Pause the sound with this name? - /// - /// + /// Pause the sound with this name? public void pauseSound(string soundName) { List removalList = new List(); @@ -234,9 +173,7 @@ namespace SimpleSoundManager.Framework } } foreach (var v in removalList) - { this.currentlyPlayingSounds.Remove(v); - } } public void swapSounds(string newSong) @@ -247,29 +184,19 @@ namespace SimpleSoundManager.Framework public void update() { List removalList = new List(); - foreach(Sound song in this.currentlyPlayingSounds) + foreach (Sound song in this.currentlyPlayingSounds) { if (song.isStopped()) - { removalList.Add(song); - } } - foreach(var v in removalList) - { + foreach (var v in removalList) this.currentlyPlayingSounds.Remove(v); - } } public void stopAllSounds() { - foreach(var v in this.currentlyPlayingSounds) - { + foreach (var v in this.currentlyPlayingSounds) v.stop(); - } } - - - - } } diff --git a/GeneralMods/SimpleSoundManager/Framework/WavSound.cs b/GeneralMods/SimpleSoundManager/Framework/WavSound.cs index 6926b528..4c31fdf2 100644 --- a/GeneralMods/SimpleSoundManager/Framework/WavSound.cs +++ b/GeneralMods/SimpleSoundManager/Framework/WavSound.cs @@ -1,95 +1,70 @@ -using Microsoft.Xna.Framework.Audio; -using SimpleSoundManager.Framework; -using StardewModdingAPI; -using StardewValley; using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Microsoft.Xna.Framework.Audio; +using SimpleSoundManager.Framework; +using StardewModdingAPI; namespace SimpleSoundManager { class WavSound : Sound { - /// - /// Used to actually play the song. - /// + /// Used to actually play the song. DynamicSoundEffectInstance dynamicSound; - /// - /// Used to keep track of where in the song we are. - /// - int position; - /// - /// ??? - /// - int count; - /// - /// Used to store the info for the song. - /// - byte[] byteArray; + /// Used to keep track of where in the song we are. + int position; + + int count; + + /// Used to store the info for the song. + byte[] byteArray; public string path; public string soundName; - public bool loop; - /// - /// Get a raw disk path to the wav file. - /// - /// - public WavSound(string name,string pathToWavFile,bool Loop=false) + /// Get a raw disk path to the wav file. + public WavSound(string name, string pathToWavFile, bool loop = false) { this.path = pathToWavFile; - LoadWavFromFileToStream(); + this.LoadWavFromFileToStream(); this.soundName = name; - this.loop = Loop; + this.loop = loop; } - /// - /// A constructor that takes a mod helper and a relative path to a wav file. - /// - /// - /// - public WavSound(IModHelper modHelper,string name, string pathInModDirectory,bool Loop=false) + /// A constructor that takes a mod helper and a relative path to a wav file. + public WavSound(IModHelper modHelper, string name, string relativePath, bool loop = false) { - string path = Path.Combine(modHelper.DirectoryPath, pathInModDirectory); + string path = Path.Combine(modHelper.DirectoryPath, relativePath); this.path = path; this.soundName = name; - this.loop = Loop; + this.loop = loop; } - /// - /// Constructor that is more flexible than typing an absolute path. - /// + /// Constructor that is more flexible than typing an absolute path. /// The mod helper for the mod you wish to use to load the music files from. /// The list of folders and files that make up a complete path. - public WavSound(IModHelper modHelper,string soundName, List pathPieces,bool Loop=false) + public WavSound(IModHelper modHelper, string soundName, List pathPieces, bool loop = false) { - string s = modHelper.DirectoryPath; - foreach(var str in pathPieces) - { - s = Path.Combine(s, str); - } - this.path = s; + string dirPath = modHelper.DirectoryPath; + foreach (string str in pathPieces) + dirPath = Path.Combine(dirPath, str); + this.path = dirPath; this.soundName = soundName; - this.loop = Loop; + this.loop = loop; } - /// - /// Loads the .wav file from disk and plays it. - /// + /// Loads the .wav file from disk and plays it. public void LoadWavFromFileToStream() { // Create a new SpriteBatch, which can be used to draw textures. string file = this.path; - System.IO.Stream waveFileStream = File.OpenRead(file); //TitleContainer.OpenStream(file); + Stream waveFileStream = File.OpenRead(file); //TitleContainer.OpenStream(file); BinaryReader reader = new BinaryReader(waveFileStream); @@ -115,104 +90,83 @@ namespace SimpleSoundManager int dataID = reader.ReadInt32(); int dataSize = reader.ReadInt32(); - byteArray = reader.ReadBytes(dataSize); + this.byteArray = reader.ReadBytes(dataSize); - dynamicSound = new DynamicSoundEffectInstance(sampleRate, (AudioChannels)channels); - count = byteArray.Length;//dynamicSound.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(1000)); + this.dynamicSound = new DynamicSoundEffectInstance(sampleRate, (AudioChannels)channels); + this.count = this.byteArray.Length;//dynamicSound.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(1000)); - dynamicSound.BufferNeeded += new EventHandler(DynamicSound_BufferNeeded); - + this.dynamicSound.BufferNeeded += this.DynamicSound_BufferNeeded; } void DynamicSound_BufferNeeded(object sender, EventArgs e) { try { - dynamicSound.SubmitBuffer(byteArray, position, count); - } - catch (Exception err) - { - //SimpleSoundManagerMod.ModMonitor.Log(err.ToString()); + this.dynamicSound.SubmitBuffer(this.byteArray, this.position, this.count); } + catch { } - position += count; - if (position + count > byteArray.Length) + this.position += this.count; + if (this.position + this.count > this.byteArray.Length) { - if (loop) - { - position = 0; - } - else - { - //this.stop(); - } + if (this.loop) + this.position = 0; + //else + // this.stop(); } } - /// - /// Used to pause the current song. - /// + /// Used to pause the current song. public void pause() { - if (dynamicSound != null) dynamicSound.Pause(); + this.dynamicSound?.Pause(); } - /// - /// Used to play a song. - /// - /// + /// Used to play a song. public void play() { - if (this.isPlaying() == true) return; - LoadWavFromFileToStream(); - dynamicSound.Play(); + if (this.isPlaying()) + return; + + this.LoadWavFromFileToStream(); + this.dynamicSound.Play(); } - /// - /// Used to play a song. - /// - /// + /// Used to play a song. /// How lound the sound is when playing. 0~1.0f public void play(float volume) { - if (this.isPlaying() == true) return; - LoadWavFromFileToStream(); - dynamicSound.Volume = volume; - dynamicSound.Play(); + if (this.isPlaying()) + return; + + this.LoadWavFromFileToStream(); + this.dynamicSound.Volume = volume; + this.dynamicSound.Play(); } - /// - /// Used to resume the currently playing song. - /// + /// Used to resume the currently playing song. public void resume() { - if (dynamicSound == null) return; - dynamicSound.Resume(); + dynamicSound?.Resume(); } - /// - /// Used to stop the currently playing song. - /// + /// Used to stop the currently playing song. public void stop() { - - if (dynamicSound != null) + if (this.dynamicSound != null) { - dynamicSound.Stop(true); - dynamicSound.BufferNeeded -= new EventHandler(DynamicSound_BufferNeeded); - position = 0; - count = 0; - byteArray = new byte[0]; + this.dynamicSound.Stop(true); + this.dynamicSound.BufferNeeded -= this.DynamicSound_BufferNeeded; + this.position = 0; + this.count = 0; + this.byteArray = new byte[0]; } } - /// - /// Used to change from one playing song to another; - /// - /// + /// Used to change from one playing song to another; public void swap(string pathToNewWavFile) { this.stop(); @@ -220,42 +174,27 @@ namespace SimpleSoundManager this.play(); } - /// - /// Checks if the song is currently playing. - /// - /// + /// Checks if the song is currently playing. public bool isPlaying() { - if (this.dynamicSound == null) return false; - if (this.dynamicSound.State == SoundState.Playing) return true; - else return false; + return this.dynamicSound?.State == SoundState.Playing; } - /// - /// Checks if the song is currently paused. - /// - /// + /// Checks if the song is currently paused. public bool isPaused() { - if (this.dynamicSound == null) return false; - if (this.dynamicSound.State == SoundState.Paused) return true; - else return false; + return this.dynamicSound?.State == SoundState.Paused; } - /// - /// Checks if the song is currently stopped. - /// - /// + /// Checks if the song is currently stopped. public bool isStopped() { - if (this.dynamicSound == null) return false; - if (this.dynamicSound.State == SoundState.Stopped) return true; - else return false; + return this.dynamicSound?.State == SoundState.Stopped; } public Sound clone() { - return new WavSound(this.getSoundName(),this.path); + return new WavSound(this.getSoundName(), this.path); } public string getSoundName() @@ -268,6 +207,5 @@ namespace SimpleSoundManager this.stop(); this.play(); } - } } diff --git a/GeneralMods/SimpleSoundManager/Framework/XACTSound.cs b/GeneralMods/SimpleSoundManager/Framework/XACTSound.cs index b3bfad14..a9e6379e 100644 --- a/GeneralMods/SimpleSoundManager/Framework/XACTSound.cs +++ b/GeneralMods/SimpleSoundManager/Framework/XACTSound.cs @@ -1,11 +1,5 @@ -using Microsoft.Xna.Framework.Audio; -using StardewModdingAPI; +using Microsoft.Xna.Framework.Audio; using StardewValley; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SimpleSoundManager.Framework { @@ -14,29 +8,25 @@ namespace SimpleSoundManager.Framework public WaveBank waveBank; public ISoundBank soundBank; public string soundName; - WaveBank vanillaWaveBank; - ISoundBank vanillaSoundBank; - Cue song; + readonly WaveBank vanillaWaveBank; + readonly ISoundBank vanillaSoundBank; + readonly Cue song; - /// - /// Make a new Sound Manager to play and manage sounds in a modded wave bank. - /// + /// Make a new Sound Manager to play and manage sounds in a modded wave bank. /// The reference to the wave bank in the mod's asset folder. /// The reference to the sound bank in the mod's asset folder. - public XACTSound(WaveBank newWaveBank, ISoundBank newSoundBank,string soundName) + public XACTSound(WaveBank newWaveBank, ISoundBank newSoundBank, string soundName) { this.waveBank = newWaveBank; this.soundBank = newSoundBank; - vanillaSoundBank = Game1.soundBank; - vanillaWaveBank = Game1.waveBank; + this.vanillaSoundBank = Game1.soundBank; + this.vanillaWaveBank = Game1.waveBank; this.soundName = soundName; - song = this.soundBank.GetCue(this.soundName); + this.song = this.soundBank.GetCue(this.soundName); } - /// - /// Play a sound from the mod's wave bank. - /// + /// Play a sound from the mod's wave bank. /// The name of the sound in the mod's wave bank. This will fail if the sound doesn't exists. This is also case sensitive. public void play(string soundName) { @@ -51,89 +41,65 @@ namespace SimpleSoundManager.Framework Game1.soundBank = this.vanillaSoundBank; } - /// - /// Pauses the first instance of this sound. - /// + /// Pauses the first instance of this sound. /// public void pause(string soundName) { - if (this.song == null) return; - this.song.Pause(); + this.song?.Pause(); } - /// - /// Resume the first instance of the sound that has this name. - /// + /// Resume the first instance of the sound that has this name. public void resume(string soundName) { - if (this.song == null) return; - this.song.Resume(); + this.song?.Resume(); } - /// - /// Stop the first instance of the sound that has this name. - /// + /// Stop the first instance of the sound that has this name. /// public void stop(string soundName) { - if (this.song == null) return; - this.song.Stop(AudioStopOptions.Immediate); + this.song?.Stop(AudioStopOptions.Immediate); } - /// - /// Resumes a paused song. - /// + /// Resumes a paused song. public void resume() { - this.resume(soundName); + this.resume(this.soundName); } - /// - /// Plays this song. - /// + /// Plays this song. public void play() { this.play(this.soundName); } - /// - /// Plays this song. - /// + /// Plays this song. public void play(float volume) { this.play(this.soundName); } - /// - /// Pauses this song. - /// + /// Pauses this song. public void pause() { this.pause(this.soundName); } - /// - /// Stops this somg. - /// + /// Stops this somg. public void stop() { this.stop(this.soundName); } - /// - /// Restarts this song. - /// + /// Restarts this song. public void restart() { this.stop(); this.play(); } - /// - /// Gets a clone of this song. - /// - /// + /// Gets a clone of this song. public Sound clone() { return new XACTSound(this.waveBank, this.soundBank, this.soundName); @@ -146,11 +112,7 @@ namespace SimpleSoundManager.Framework public bool isStopped() { - if (this.song == null) return true; - if (this.song.IsStopped) return true; - return false; + return this.song == null || this.song.IsStopped; } - - } } diff --git a/GeneralMods/SimpleSoundManager/Framework/XactMusicPair.cs b/GeneralMods/SimpleSoundManager/Framework/XactMusicPair.cs index fe3a77c2..84129dc1 100644 --- a/GeneralMods/SimpleSoundManager/Framework/XactMusicPair.cs +++ b/GeneralMods/SimpleSoundManager/Framework/XactMusicPair.cs @@ -1,12 +1,7 @@ -using Microsoft.Xna.Framework.Audio; +using System.IO; +using Microsoft.Xna.Framework.Audio; using StardewModdingAPI; using StardewValley; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SimpleSoundManager { @@ -15,20 +10,17 @@ namespace SimpleSoundManager public WaveBank waveBank; public ISoundBank soundBank; - /// - /// Create a xwb and xsb music pack pair. - /// + /// Create a xwb and xsb music pack pair. /// The mod helper from the mod that will handle loading in the file. /// A relative path to the .xwb file in the mod helper's mod directory. /// A relative path to the .xsb file in the mod helper's mod directory. - public XACTMusicPair(IModHelper helper,string wavBankPath, string soundBankPath) + public XACTMusicPair(IModHelper helper, string wavBankPath, string soundBankPath) { wavBankPath = Path.Combine(helper.DirectoryPath, wavBankPath); soundBankPath = Path.Combine(helper.DirectoryPath, soundBankPath); - - waveBank = new WaveBank(Game1.audioEngine, wavBankPath); - soundBank = new SoundBankWrapper(new SoundBank(Game1.audioEngine, soundBankPath)); + this.waveBank = new WaveBank(Game1.audioEngine, wavBankPath); + this.soundBank = new SoundBankWrapper(new SoundBank(Game1.audioEngine, soundBankPath)); } } } diff --git a/GeneralMods/SimpleSoundManager/SimpleSoundManager.csproj b/GeneralMods/SimpleSoundManager/SimpleSoundManager.csproj index b5eb855e..4e840a0a 100644 --- a/GeneralMods/SimpleSoundManager/SimpleSoundManager.csproj +++ b/GeneralMods/SimpleSoundManager/SimpleSoundManager.csproj @@ -1,5 +1,5 @@  - + Debug @@ -11,8 +11,6 @@ SimpleSoundManager v4.5 512 - - true @@ -67,6 +65,9 @@ prompt MinimumRecommendedRules.ruleset + + + @@ -82,19 +83,8 @@ - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/GeneralMods/SimpleSoundManager/SimpleSoundManagerMod.cs b/GeneralMods/SimpleSoundManager/SimpleSoundManagerMod.cs index b93be9b0..1a583b3b 100644 --- a/GeneralMods/SimpleSoundManager/SimpleSoundManagerMod.cs +++ b/GeneralMods/SimpleSoundManager/SimpleSoundManagerMod.cs @@ -1,4 +1,4 @@ -using StardewModdingAPI; +using StardewModdingAPI; namespace SimpleSoundManager { @@ -7,10 +7,12 @@ namespace SimpleSoundManager internal static IModHelper ModHelper; internal static IMonitor ModMonitor; + /// The mod entry point, called after the mod is first loaded. + /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { ModHelper = helper; - ModMonitor = Monitor; + ModMonitor = this.Monitor; } } } diff --git a/GeneralMods/SimpleSoundManager/manifest.json b/GeneralMods/SimpleSoundManager/manifest.json index e5e92fab..bd16daeb 100644 --- a/GeneralMods/SimpleSoundManager/manifest.json +++ b/GeneralMods/SimpleSoundManager/manifest.json @@ -1,10 +1,10 @@ { "Name": "Simple Sound Manager", "Author": "Alpha_Omegasis", - "Version": "2.0.1", + "Version": "2.1.0", "Description": "A simple framework to play sounds from wave banks and wav files.", "UniqueID": "Omegasis.SimpleSoundManager", "EntryDll": "SimpleSoundManager.dll", - "MinimumApiVersion": "2.0", + "MinimumApiVersion": "2.10.1", "UpdateKeys": [ "Nexus:1410" ] } diff --git a/GeneralMods/SimpleSoundManager/packages.config b/GeneralMods/SimpleSoundManager/packages.config deleted file mode 100644 index af793ad3..00000000 --- a/GeneralMods/SimpleSoundManager/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/GeneralMods/StardewMods.sln b/GeneralMods/StardewMods.sln index 4e379438..5ccc93d6 100644 --- a/GeneralMods/StardewMods.sln +++ b/GeneralMods/StardewMods.sln @@ -13,8 +13,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BuildHealth", "BuildHealth\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BuyBackCollectables", "BuyBackCollectables\BuyBackCollectables.csproj", "{A19025C4-E194-4CAD-B156-4AC00BDD2AA3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomShopsRedux", "CustomShopsRedux\CustomShopsRedux.csproj", "{29F7DE68-4C76-471E-86FB-873794802ADC}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DailyQuestAnywhere", "DailyQuestAnywhere\DailyQuestAnywhere.csproj", "{AC4B84F5-31E4-4A55-B13F-A5189C552343}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fall28SnowDay", "Fall28SnowDay\Fall28SnowDay.csproj", "{1DBB583D-4A4F-4A46-8CC5-42017C93D292}" @@ -35,9 +33,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimeFreeze", "TimeFreeze\Ti EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "~metadata", "~metadata", "{90EB59CA-51F6-49CF-8DCE-A8BB62C58E17}" ProjectSection(SolutionItems) = preProject + ..\.editorconfig = ..\.editorconfig deploy.targets = deploy.targets GlobalAssemblyInfo.cs = GlobalAssemblyInfo.cs - AdditionalCropsFramework\ModularCropObject.cs = AdditionalCropsFramework\ModularCropObject.cs ..\README.md = ..\README.md EndProjectSection EndProject @@ -68,8 +66,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FarmersMarketStall", "Farme {BB737337-2D82-4245-AA46-F3B82FC6F228} = {BB737337-2D82-4245-AA46-F3B82FC6F228} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DebugSandBoxAndReferences", "DebugSandBoxAndReferences\DebugSandBoxAndReferences.csproj", "{B196EB60-5042-46B9-BEAA-3020E539CB9F}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdditionalCropsFramework", "AdditionalCropsFramework\AdditionalCropsFramework.csproj", "{C5F88D48-EA20-40CD-91E2-C8725DC11795}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedSaveBackup", "AdvancedSaveBackup\AdvancedSaveBackup.csproj", "{12984468-2B79-4B3B-B045-EE917301DEE0}" @@ -79,7 +75,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vocalization", "Vocalizatio {7B1E9A54-ED9E-47AA-BBAA-98A6E7CB527A} = {7B1E9A54-ED9E-47AA-BBAA-98A6E7CB527A} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AUnifiedSaveCore", "UnifiedSaveCore\AUnifiedSaveCore.csproj", "{ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Revitalize", "Revitalize\Revitalize.csproj", "{44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -151,18 +147,6 @@ Global {A19025C4-E194-4CAD-B156-4AC00BDD2AA3}.x86|Any CPU.Build.0 = x86|Any CPU {A19025C4-E194-4CAD-B156-4AC00BDD2AA3}.x86|x86.ActiveCfg = x86|x86 {A19025C4-E194-4CAD-B156-4AC00BDD2AA3}.x86|x86.Build.0 = x86|x86 - {29F7DE68-4C76-471E-86FB-873794802ADC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {29F7DE68-4C76-471E-86FB-873794802ADC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {29F7DE68-4C76-471E-86FB-873794802ADC}.Debug|x86.ActiveCfg = Debug|x86 - {29F7DE68-4C76-471E-86FB-873794802ADC}.Debug|x86.Build.0 = Debug|x86 - {29F7DE68-4C76-471E-86FB-873794802ADC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {29F7DE68-4C76-471E-86FB-873794802ADC}.Release|Any CPU.Build.0 = Release|Any CPU - {29F7DE68-4C76-471E-86FB-873794802ADC}.Release|x86.ActiveCfg = Release|x86 - {29F7DE68-4C76-471E-86FB-873794802ADC}.Release|x86.Build.0 = Release|x86 - {29F7DE68-4C76-471E-86FB-873794802ADC}.x86|Any CPU.ActiveCfg = x86|Any CPU - {29F7DE68-4C76-471E-86FB-873794802ADC}.x86|Any CPU.Build.0 = x86|Any CPU - {29F7DE68-4C76-471E-86FB-873794802ADC}.x86|x86.ActiveCfg = x86|x86 - {29F7DE68-4C76-471E-86FB-873794802ADC}.x86|x86.Build.0 = x86|x86 {AC4B84F5-31E4-4A55-B13F-A5189C552343}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AC4B84F5-31E4-4A55-B13F-A5189C552343}.Debug|Any CPU.Build.0 = Debug|Any CPU {AC4B84F5-31E4-4A55-B13F-A5189C552343}.Debug|x86.ActiveCfg = Debug|x86 @@ -355,18 +339,6 @@ Global {0E37BE57-6B3C-4C79-A134-D16283D5306D}.x86|Any CPU.Build.0 = x86|Any CPU {0E37BE57-6B3C-4C79-A134-D16283D5306D}.x86|x86.ActiveCfg = x86|x86 {0E37BE57-6B3C-4C79-A134-D16283D5306D}.x86|x86.Build.0 = x86|x86 - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Debug|x86.ActiveCfg = Debug|x86 - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Debug|x86.Build.0 = Debug|x86 - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Release|Any CPU.Build.0 = Release|Any CPU - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Release|x86.ActiveCfg = Release|x86 - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.Release|x86.Build.0 = Release|x86 - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.x86|Any CPU.ActiveCfg = x86|Any CPU - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.x86|Any CPU.Build.0 = x86|Any CPU - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.x86|x86.ActiveCfg = x86|x86 - {B196EB60-5042-46B9-BEAA-3020E539CB9F}.x86|x86.Build.0 = x86|x86 {C5F88D48-EA20-40CD-91E2-C8725DC11795}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C5F88D48-EA20-40CD-91E2-C8725DC11795}.Debug|Any CPU.Build.0 = Debug|Any CPU {C5F88D48-EA20-40CD-91E2-C8725DC11795}.Debug|x86.ActiveCfg = Debug|x86 @@ -403,18 +375,18 @@ Global {1651701C-DB36-43C7-B66D-2700171DD9A9}.x86|Any CPU.Build.0 = Release|Any CPU {1651701C-DB36-43C7-B66D-2700171DD9A9}.x86|x86.ActiveCfg = Release|Any CPU {1651701C-DB36-43C7-B66D-2700171DD9A9}.x86|x86.Build.0 = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Debug|x86.ActiveCfg = Debug|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Debug|x86.Build.0 = Debug|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Release|Any CPU.Build.0 = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Release|x86.ActiveCfg = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.Release|x86.Build.0 = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.x86|Any CPU.ActiveCfg = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.x86|Any CPU.Build.0 = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.x86|x86.ActiveCfg = Release|Any CPU - {ACAF0BAE-6495-4F1B-8B1F-E34BF7CCF51A}.x86|x86.Build.0 = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Debug|x86.ActiveCfg = Debug|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Debug|x86.Build.0 = Debug|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Release|Any CPU.Build.0 = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Release|x86.ActiveCfg = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.Release|x86.Build.0 = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.x86|Any CPU.ActiveCfg = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.x86|Any CPU.Build.0 = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.x86|x86.ActiveCfg = Release|Any CPU + {44EF6CEC-FBF1-4B45-8135-81D4EBE84DDD}.x86|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Config.cs b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Config.cs index 1e1c81ba..76413128 100644 --- a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Config.cs +++ b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Config.cs @@ -1,44 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using StardewModdingAPI; namespace StardewSymphonyRemastered { - /// - /// A class that handles all of the config files for this mod. - /// + /// A class that handles all of the config files for this mod. public class Config { - /// - /// Whether or not to display debug log information on the SMAPI console for this mod. - /// - public bool EnableDebugLog { get; set; }=false; + /// Whether to show debug logs in the SMAPI console. + public bool EnableDebugLog { get; set; } = false; - /// - /// The minimum delay between songs in terms of milliseconds. - /// - public int MinimumDelayBetweenSongsInMilliseconds { get; set; }=5000; + /// The minimum delay between songs in milliseconds. + public int MinimumDelayBetweenSongsInMilliseconds { get; set; } = 5000; - /// - /// The maximum delay between songs in terms of milliseconds. - /// - public int MaximumDelayBetweenSongsInMilliseconds { get; set; }=60000; + /// The maximum delay between songs in milliseconds. + public int MaximumDelayBetweenSongsInMilliseconds { get; set; } = 60000; - /// - /// The key binding to open up the menu music. - /// - public string KeyBinding { get; set; }="L"; - - /// - /// Used to write a .json file for every possible option for a music pack. Use at your own risk! - /// - public bool writeAllConfigMusicOptions { get; set; } = false; + /// The key binding to open the menu music. + public SButton KeyBinding { get; set; } = SButton.L; - /// - /// Used to completely disable the Stardew Valley OST. - /// - public bool disableStardewMusic { get; set; } = false; + /// Whether to write a JSON file for every possible option for a music pack. Use at your own risk! + public bool WriteAllConfigMusicOptions { get; set; } = false; + + /// Whether to completely disable the Stardew Valley OST. + public bool DisableStardewMusic { get; set; } = false; } } diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/MusicPackInformation.json b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/MusicPackInformation.json deleted file mode 100644 index c82b910e..00000000 --- a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/MusicPackInformation.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "Omegas's Music Data Example", - "author": "Omegasis", - "description": "Just a simple example of how metadata is formated for music packs. Feel free to copy and edit this one!", - "versionInfo": "1.0.0 CoolExample", - "pathToMusicPackIcon": "Icon", - "Icon": null -} \ No newline at end of file diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/Songs/SongsGoHere.txt b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/Songs/SongsGoHere.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/readme.txt b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/readme.txt deleted file mode 100644 index 4d4fbb8f..00000000 --- a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/WAV/readme.txt +++ /dev/null @@ -1 +0,0 @@ -Place the .wav song files in the Songs folder, modify the MusicPackInformation.json as desired, and then run! \ No newline at end of file diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/XACT/MusicPackInformation.json b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/XACT/MusicPackInformation.json deleted file mode 100644 index d18bc584..00000000 --- a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/XACT/MusicPackInformation.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "Omegas's Music Data Example", - "author": "Omegasis", - "description": "Just a simple example of how metadata is formated for music packs. Feel free to copy and edit this one!", - "versionInfo": "1.0.0 CoolExample", - "pathToMusicPackIcon": "Icon.png", - "Icon": null -} \ No newline at end of file diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/XACT/readme.txt b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/XACT/readme.txt deleted file mode 100644 index 3942c582..00000000 --- a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Content/Music/Templates/XACT/readme.txt +++ /dev/null @@ -1,3 +0,0 @@ -Place the Wave Bank.xwb file and Sound Bank.xsb file you created in XACT in a similar directory in Content/Music/XACT/SoundPackName. -Modify MusicPackInformation.json as desire! -Run the mod! \ No newline at end of file diff --git a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Framework/Menus/MusicManagerMenu.cs b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Framework/Menus/MusicManagerMenu.cs index e4118a5f..23f70ec6 100644 --- a/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Framework/Menus/MusicManagerMenu.cs +++ b/GeneralMods/StardewSymphonyRemastered/StardewSymphonyRemastered/Framework/Menus/MusicManagerMenu.cs @@ -1,8 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; using StardewValley; using StardewValley.Locations; using StardustCore.Animations; @@ -11,18 +12,13 @@ using StardustCore.UIUtilities.MenuComponents; using StardustCore.UIUtilities.MenuComponents.Delegates; using StardustCore.UIUtilities.MenuComponents.Delegates.Functionality; using StardustCore.UIUtilities.SpriteFonts; -using StardustCore.UIUtilities.SpriteFonts.Components; namespace StardewSymphonyRemastered.Framework.Menus { - /// - /// Interface for the menu for selection music. - /// + /// Interface for the menu for selection music. public class MusicManagerMenu : IClickableMenuExtended { - /// - /// The different displays for this menu. - /// + /// The different displays for this menu. public enum DrawMode { AlbumSelection, @@ -47,7 +43,7 @@ namespace StardewSymphonyRemastered.Framework.Menus SeasonSelection, } - public List