summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <github@jplamondonw.com>2017-07-08 12:54:06 -0400
committerJesse Plamondon-Willard <github@jplamondonw.com>2017-07-08 12:54:06 -0400
commit1edd98aef027faa768f56cf0b3591e64e20ba096 (patch)
treeaec210e2b44c9654f29572dd084206a4598896e1 /src
parent36930ffd7d363d6afd7f8cac4918c7d1c1c3e339 (diff)
parent8743c4115aa142113d791f2d2cd9ba811dcada2c (diff)
downloadSMAPI-1edd98aef027faa768f56cf0b3591e64e20ba096.tar.gz
SMAPI-1edd98aef027faa768f56cf0b3591e64e20ba096.tar.bz2
SMAPI-1edd98aef027faa768f56cf0b3591e64e20ba096.zip
Merge branch 'develop' into stable
Diffstat (limited to 'src')
-rw-r--r--src/.editorconfig1
-rw-r--r--src/GlobalAssemblyInfo.cs4
-rw-r--r--src/StardewModdingAPI.AssemblyRewriters/Finders/PropertyFinder.cs83
-rw-r--r--src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj1
-rw-r--r--src/StardewModdingAPI.Installer/InteractiveInstaller.cs1
-rw-r--r--src/StardewModdingAPI.Installer/readme.txt33
-rw-r--r--src/StardewModdingAPI.Tests/Core/ModResolverTests.cs (renamed from src/StardewModdingAPI.Tests/ModResolverTests.cs)181
-rw-r--r--src/StardewModdingAPI.Tests/Core/TranslationTests.cs (renamed from src/StardewModdingAPI.Tests/TranslationTests.cs)9
-rw-r--r--src/StardewModdingAPI.Tests/Sample.cs (renamed from src/StardewModdingAPI.Tests/Framework/Sample.cs)2
-rw-r--r--src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj8
-rw-r--r--src/StardewModdingAPI.Tests/Utilities/SDateTests.cs253
-rw-r--r--src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs255
-rw-r--r--src/StardewModdingAPI.sln3
-rw-r--r--src/StardewModdingAPI/Command.cs10
-rw-r--r--src/StardewModdingAPI/Config.cs6
-rw-r--r--src/StardewModdingAPI/Constants.cs33
-rw-r--r--src/StardewModdingAPI/Events/ContentEvents.cs65
-rw-r--r--src/StardewModdingAPI/Events/EventArgsCommand.cs4
-rw-r--r--src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs2
-rw-r--r--src/StardewModdingAPI/Events/EventArgsInput.cs126
-rw-r--r--src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs4
-rw-r--r--src/StardewModdingAPI/Events/EventArgsNewDay.cs4
-rw-r--r--src/StardewModdingAPI/Events/EventArgsStringChanged.cs4
-rw-r--r--src/StardewModdingAPI/Events/GameEvents.cs30
-rw-r--r--src/StardewModdingAPI/Events/InputEvents.cs45
-rw-r--r--src/StardewModdingAPI/Events/PlayerEvents.cs10
-rw-r--r--src/StardewModdingAPI/Events/TimeEvents.cs19
-rw-r--r--src/StardewModdingAPI/Framework/Content/AssetData.cs44
-rw-r--r--src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs (renamed from src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs)4
-rw-r--r--src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs (renamed from src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs)4
-rw-r--r--src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs (renamed from src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs)19
-rw-r--r--src/StardewModdingAPI/Framework/Content/AssetInfo.cs (renamed from src/StardewModdingAPI/Framework/Content/ContentEventData.cs)41
-rw-r--r--src/StardewModdingAPI/Framework/CursorPosition.cs37
-rw-r--r--src/StardewModdingAPI/Framework/DeprecationManager.cs13
-rw-r--r--src/StardewModdingAPI/Framework/Exceptions/SParseException.cs17
-rw-r--r--src/StardewModdingAPI/Framework/InternalExtensions.cs5
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs23
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs (renamed from src/StardewModdingAPI/Framework/CommandHelper.cs)9
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs (renamed from src/StardewModdingAPI/Framework/ContentHelper.cs)26
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs (renamed from src/StardewModdingAPI/Framework/ModHelper.cs)42
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs48
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs160
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs (renamed from src/StardewModdingAPI/Framework/TranslationHelper.cs)8
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs27
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs124
-rw-r--r--src/StardewModdingAPI/Framework/ModRegistry.cs6
-rw-r--r--src/StardewModdingAPI/Framework/Models/DisabledMod.cs22
-rw-r--r--src/StardewModdingAPI/Framework/Models/Manifest.cs5
-rw-r--r--src/StardewModdingAPI/Framework/Models/ManifestDependency.cs21
-rw-r--r--src/StardewModdingAPI/Framework/Models/SConfig.cs3
-rw-r--r--src/StardewModdingAPI/Framework/Monitor.cs32
-rw-r--r--src/StardewModdingAPI/Framework/Reflection/Reflector.cs (renamed from src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs)44
-rw-r--r--src/StardewModdingAPI/Framework/SContentManager.cs248
-rw-r--r--src/StardewModdingAPI/Framework/SGame.cs357
-rw-r--r--src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs19
-rw-r--r--src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs41
-rw-r--r--src/StardewModdingAPI/IAssetData.cs47
-rw-r--r--src/StardewModdingAPI/IAssetDataForDictionary.cs (renamed from src/StardewModdingAPI/IContentEventHelperForDictionary.cs)2
-rw-r--r--src/StardewModdingAPI/IAssetDataForImage.cs (renamed from src/StardewModdingAPI/IContentEventHelperForImage.cs)2
-rw-r--r--src/StardewModdingAPI/IAssetEditor.cs17
-rw-r--r--src/StardewModdingAPI/IAssetInfo.cs28
-rw-r--r--src/StardewModdingAPI/IAssetLoader.cs17
-rw-r--r--src/StardewModdingAPI/ICommandHelper.cs2
-rw-r--r--src/StardewModdingAPI/IContentEventData.cs38
-rw-r--r--src/StardewModdingAPI/IContentEventHelper.cs26
-rw-r--r--src/StardewModdingAPI/IContentHelper.cs2
-rw-r--r--src/StardewModdingAPI/ICursorPosition.cs19
-rw-r--r--src/StardewModdingAPI/IManifest.cs2
-rw-r--r--src/StardewModdingAPI/IManifestDependency.cs8
-rw-r--r--src/StardewModdingAPI/IModLinked.cs12
-rw-r--r--src/StardewModdingAPI/IModRegistry.cs4
-rw-r--r--src/StardewModdingAPI/IReflectionHelper.cs4
-rw-r--r--src/StardewModdingAPI/ITranslationHelper.cs2
-rw-r--r--src/StardewModdingAPI/Log.cs6
-rw-r--r--src/StardewModdingAPI/Mod.cs17
-rw-r--r--src/StardewModdingAPI/Program.cs335
-rw-r--r--src/StardewModdingAPI/SemanticVersion.cs32
-rw-r--r--src/StardewModdingAPI/StardewModdingAPI.config.json25
-rw-r--r--src/StardewModdingAPI/StardewModdingAPI.csproj45
-rw-r--r--src/StardewModdingAPI/Utilities/SButton.cs659
-rw-r--r--src/StardewModdingAPI/Utilities/SDate.cs222
-rw-r--r--src/TrainerMod/Framework/Commands/ArgumentParser.cs159
-rw-r--r--src/TrainerMod/Framework/Commands/ITrainerCommand.cs34
-rw-r--r--src/TrainerMod/Framework/Commands/Other/DebugCommand.cs33
-rw-r--r--src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs26
-rw-r--r--src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs26
-rw-r--r--src/TrainerMod/Framework/Commands/Player/AddCommand.cs81
-rw-r--r--src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs53
-rw-r--r--src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs76
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs76
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs72
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs38
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs63
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs38
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs38
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs72
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs52
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs31
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs72
-rw-r--r--src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs92
-rw-r--r--src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs28
-rw-r--r--src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs27
-rw-r--r--src/TrainerMod/Framework/Commands/TrainerCommand.cs103
-rw-r--r--src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs28
-rw-r--r--src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs67
-rw-r--r--src/TrainerMod/Framework/Commands/World/SetDayCommand.cs39
-rw-r--r--src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs33
-rw-r--r--src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs46
-rw-r--r--src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs40
-rw-r--r--src/TrainerMod/Framework/Commands/World/SetYearCommand.cs39
-rw-r--r--src/TrainerMod/Framework/ItemData/ItemType.cs39
-rw-r--r--src/TrainerMod/Framework/ItemData/SearchableItem.cs41
-rw-r--r--src/TrainerMod/Framework/ItemRepository.cs179
-rw-r--r--src/TrainerMod/ItemData/ISearchItem.cs21
-rw-r--r--src/TrainerMod/ItemData/ItemType.cs15
-rw-r--r--src/TrainerMod/ItemData/SearchableObject.cs48
-rw-r--r--src/TrainerMod/ItemData/SearchableRing.cs48
-rw-r--r--src/TrainerMod/ItemData/SearchableWeapon.cs48
-rw-r--r--src/TrainerMod/TrainerMod.cs851
-rw-r--r--src/TrainerMod/TrainerMod.csproj37
-rw-r--r--src/TrainerMod/manifest.json4
-rw-r--r--src/crossplatform.targets2
122 files changed, 5381 insertions, 1752 deletions
diff --git a/src/.editorconfig b/src/.editorconfig
index 132fe6cb..4271803d 100644
--- a/src/.editorconfig
+++ b/src/.editorconfig
@@ -10,6 +10,7 @@ indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
+charset = utf-8
[*.json]
indent_size = 2
diff --git a/src/GlobalAssemblyInfo.cs b/src/GlobalAssemblyInfo.cs
index cb174d48..d2f2597f 100644
--- a/src/GlobalAssemblyInfo.cs
+++ b/src/GlobalAssemblyInfo.cs
@@ -2,5 +2,5 @@
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
-[assembly: AssemblyVersion("1.14.1.0")]
-[assembly: AssemblyFileVersion("1.14.1.0")] \ No newline at end of file
+[assembly: AssemblyVersion("1.15.0.0")]
+[assembly: AssemblyFileVersion("1.15.0.0")] \ No newline at end of file
diff --git a/src/StardewModdingAPI.AssemblyRewriters/Finders/PropertyFinder.cs b/src/StardewModdingAPI.AssemblyRewriters/Finders/PropertyFinder.cs
new file mode 100644
index 00000000..441f15f2
--- /dev/null
+++ b/src/StardewModdingAPI.AssemblyRewriters/Finders/PropertyFinder.cs
@@ -0,0 +1,83 @@
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+
+namespace StardewModdingAPI.AssemblyRewriters.Finders
+{
+ /// <summary>Finds incompatible CIL instructions that reference a given property and throws an <see cref="IncompatibleInstructionException"/>.</summary>
+ public class PropertyFinder : IInstructionRewriter
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The full type name for which to find references.</summary>
+ private readonly string FullTypeName;
+
+ /// <summary>The property name for which to find references.</summary>
+ private readonly string PropertyName;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>A brief noun phrase indicating what the instruction finder matches.</summary>
+ public string NounPhrase { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="fullTypeName">The full type name for which to find references.</param>
+ /// <param name="propertyName">The property name for which to find references.</param>
+ /// <param name="nounPhrase">A brief noun phrase indicating what the instruction finder matches (or <c>null</c> to generate one).</param>
+ public PropertyFinder(string fullTypeName, string propertyName, string nounPhrase = null)
+ {
+ this.FullTypeName = fullTypeName;
+ this.PropertyName = propertyName;
+ this.NounPhrase = nounPhrase ?? $"{fullTypeName}.{propertyName} property";
+ }
+
+ /// <summary>Rewrite a method definition for compatibility.</summary>
+ /// <param name="module">The module being rewritten.</param>
+ /// <param name="method">The method definition to rewrite.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ /// <returns>Returns whether the instruction was rewritten.</returns>
+ /// <exception cref="IncompatibleInstructionException">The CIL instruction is not compatible, and can't be rewritten.</exception>
+ public virtual bool Rewrite(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ return false;
+ }
+
+ /// <summary>Rewrite a CIL instruction for compatibility.</summary>
+ /// <param name="module">The module being rewritten.</param>
+ /// <param name="cil">The CIL rewriter.</param>
+ /// <param name="instruction">The instruction to rewrite.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ /// <returns>Returns whether the instruction was rewritten.</returns>
+ /// <exception cref="IncompatibleInstructionException">The CIL instruction is not compatible, and can't be rewritten.</exception>
+ public virtual bool Rewrite(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ if (!this.IsMatch(instruction))
+ return false;
+
+ throw new IncompatibleInstructionException(this.NounPhrase);
+ }
+
+
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Get whether a CIL instruction matches.</summary>
+ /// <param name="instruction">The IL instruction.</param>
+ protected bool IsMatch(Instruction instruction)
+ {
+ MethodReference methodRef = RewriteHelper.AsMethodReference(instruction);
+ return
+ methodRef != null
+ && methodRef.DeclaringType.FullName == this.FullTypeName
+ && (methodRef.Name == "get_" + this.PropertyName || methodRef.Name == "set_" + this.PropertyName);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj b/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj
index e25b201e..7a12a8e9 100644
--- a/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj
+++ b/src/StardewModdingAPI.AssemblyRewriters/StardewModdingAPI.AssemblyRewriters.csproj
@@ -49,6 +49,7 @@
<Link>Properties\GlobalAssemblyInfo.cs</Link>
</Compile>
<Compile Include="Finders\EventFinder.cs" />
+ <Compile Include="Finders\PropertyFinder.cs" />
<Compile Include="Finders\FieldFinder.cs" />
<Compile Include="Finders\MethodFinder.cs" />
<Compile Include="Finders\TypeFinder.cs" />
diff --git a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs
index efad0a3e..78d3d10e 100644
--- a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs
+++ b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs
@@ -82,6 +82,7 @@ namespace StardewModdingApi.Installer
yield return GetInstallPath("StardewModdingAPI.config.json");
yield return GetInstallPath("StardewModdingAPI.data.json");
yield return GetInstallPath("StardewModdingAPI.AssemblyRewriters.dll");
+ yield return GetInstallPath("System.ValueTuple.dll");
yield return GetInstallPath("steam_appid.txt");
// Linux/Mac only
diff --git a/src/StardewModdingAPI.Installer/readme.txt b/src/StardewModdingAPI.Installer/readme.txt
index cf6090c4..eb27ac52 100644
--- a/src/StardewModdingAPI.Installer/readme.txt
+++ b/src/StardewModdingAPI.Installer/readme.txt
@@ -13,7 +13,32 @@
SMAPI lets you run Stardew Valley with mods. Don't forget to download mods separately.
-Need help? See:
- - Install guide: http://canimod.com/for-players/install-smapi
- - Troubleshooting: http://canimod.com/for-players/faqs#troubleshooting
- - Ask for help: https://discord.gg/kH55QXP
+
+Install guide
+--------------------------------
+See http://stardewvalleywiki.com/Modding:Installing_SMAPI.
+
+
+Need help?
+--------------------------------
+- FAQs: http://stardewvalleywiki.com/Modding:Player_FAQs
+- Ask for help: https://discord.gg/kH55QXP
+
+
+Manual install
+--------------------------------
+THIS IS NOT RECOMMENDED FOR MOST PLAYERS. See instructions above instead.
+If you really want to install SMAPI manually, here's how.
+
+1. Download the latest version of SMAPI: https://github.com/Pathoschild/SMAPI/releases.
+2. Unzip the .zip file somewhere (not in your game folder).
+3. Copy the files from the "internal/Windows" folder (on Windows) or "internal/Mono" folder (on
+ Linux/Mac) into your game folder. The `StardewModdingAPI.exe` file should be right next to the
+ game's executable.
+4.
+ - Windows only: if you use Steam, see the install guide above to enable achievements and
+ overlay. Otherwise, just run StardewModdingAPI.exe in your game folder to play with mods.
+
+ - Linux/Mac only: rename the "StardewValley" file (no extension) to "StardewValley-original", and
+ "StardewModdingAPI" (no extension) to "StardewValley". Now just launch the game as usual to
+ play with mods.
diff --git a/src/StardewModdingAPI.Tests/ModResolverTests.cs b/src/StardewModdingAPI.Tests/Core/ModResolverTests.cs
index 23aeba64..b451465e 100644
--- a/src/StardewModdingAPI.Tests/ModResolverTests.cs
+++ b/src/StardewModdingAPI.Tests/Core/ModResolverTests.cs
@@ -9,9 +9,8 @@ using StardewModdingAPI.Framework;
using StardewModdingAPI.Framework.Models;
using StardewModdingAPI.Framework.ModLoading;
using StardewModdingAPI.Framework.Serialisation;
-using StardewModdingAPI.Tests.Framework;
-namespace StardewModdingAPI.Tests
+namespace StardewModdingAPI.Tests.Core
{
/// <summary>Unit tests for <see cref="ModResolver"/>.</summary>
[TestFixture]
@@ -31,7 +30,7 @@ namespace StardewModdingAPI.Tests
Directory.CreateDirectory(rootFolder);
// act
- IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0]).ToArray();
+ IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0], new DisabledMod[0]).ToArray();
// assert
Assert.AreEqual(0, mods.Length, 0, $"Expected to find zero manifests, found {mods.Length} instead.");
@@ -46,7 +45,7 @@ namespace StardewModdingAPI.Tests
Directory.CreateDirectory(modFolder);
// act
- IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0]).ToArray();
+ IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0], new DisabledMod[0]).ToArray();
IModMetadata mod = mods.FirstOrDefault();
// assert
@@ -85,7 +84,7 @@ namespace StardewModdingAPI.Tests
File.WriteAllText(filename, JsonConvert.SerializeObject(original));
// act
- IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0]).ToArray();
+ IModMetadata[] mods = new ModResolver().ReadManifests(rootFolder, new JsonHelper(), new ModCompatibility[0], new DisabledMod[0]).ToArray();
IModMetadata mod = mods.FirstOrDefault();
// assert
@@ -101,7 +100,7 @@ namespace StardewModdingAPI.Tests
Assert.AreEqual(original[nameof(IManifest.Author)], mod.Manifest.Author, "The manifest's author doesn't match.");
Assert.AreEqual(original[nameof(IManifest.Description)], mod.Manifest.Description, "The manifest's description doesn't match.");
Assert.AreEqual(original[nameof(IManifest.EntryDll)], mod.Manifest.EntryDll, "The manifest's entry DLL doesn't match.");
- Assert.AreEqual(original[nameof(IManifest.MinimumApiVersion)], mod.Manifest.MinimumApiVersion, "The manifest's minimum API version doesn't match.");
+ Assert.AreEqual(original[nameof(IManifest.MinimumApiVersion)], mod.Manifest.MinimumApiVersion?.ToString(), "The manifest's minimum API version doesn't match.");
Assert.AreEqual(original[nameof(IManifest.Version)]?.ToString(), mod.Manifest.Version?.ToString(), "The manifest's version doesn't match.");
Assert.IsNotNull(mod.Manifest.ExtraFields, "The extra fields should not be null.");
@@ -160,7 +159,7 @@ namespace StardewModdingAPI.Tests
Mock<IModMetadata> mock = new Mock<IModMetadata>(MockBehavior.Strict);
mock.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
mock.Setup(p => p.Compatibility).Returns(() => null);
- mock.Setup(p => p.Manifest).Returns(this.GetRandomManifest(m => m.MinimumApiVersion = "1.1"));
+ mock.Setup(p => p.Manifest).Returns(this.GetManifest(m => m.MinimumApiVersion = new SemanticVersion("1.1")));
mock.Setup(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>())).Returns(() => mock.Object);
// act
@@ -177,7 +176,7 @@ namespace StardewModdingAPI.Tests
Mock<IModMetadata> mock = new Mock<IModMetadata>(MockBehavior.Strict);
mock.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
mock.Setup(p => p.Compatibility).Returns(() => null);
- mock.Setup(p => p.Manifest).Returns(this.GetRandomManifest());
+ mock.Setup(p => p.Manifest).Returns(this.GetManifest());
mock.Setup(p => p.DirectoryPath).Returns(Path.GetTempPath());
mock.Setup(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>())).Returns(() => mock.Object);
@@ -192,7 +191,7 @@ namespace StardewModdingAPI.Tests
public void ValidateManifests_Valid_Passes()
{
// set up manifest
- IManifest manifest = this.GetRandomManifest();
+ IManifest manifest = this.GetManifest();
// create DLL
string modFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
@@ -231,9 +230,9 @@ namespace StardewModdingAPI.Tests
{
// arrange
// A B C
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B");
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C");
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B");
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C");
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modA.Object, modB.Object, modC.Object }).ToArray();
@@ -267,9 +266,9 @@ namespace StardewModdingAPI.Tests
// ▲ ▲
// │ │
// └─ C ─┘
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod A", "Mod B" });
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod A", "Mod B" });
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object }).ToArray();
@@ -286,10 +285,10 @@ namespace StardewModdingAPI.Tests
{
// arrange
// A ◀── B ◀── C ◀── D
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B" });
- Mock<IModMetadata> modD = this.GetMetadataForDependencyTest("Mod D", dependencies: new[] { "Mod C" });
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B" });
+ Mock<IModMetadata> modD = this.GetMetadata("Mod D", dependencies: new[] { "Mod C" });
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object }).ToArray();
@@ -310,12 +309,12 @@ namespace StardewModdingAPI.Tests
// ▲ ▲
// │ │
// E ◀── F
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B" });
- Mock<IModMetadata> modD = this.GetMetadataForDependencyTest("Mod D", dependencies: new[] { "Mod C" });
- Mock<IModMetadata> modE = this.GetMetadataForDependencyTest("Mod E", dependencies: new[] { "Mod B" });
- Mock<IModMetadata> modF = this.GetMetadataForDependencyTest("Mod F", dependencies: new[] { "Mod C", "Mod E" });
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B" });
+ Mock<IModMetadata> modD = this.GetMetadata("Mod D", dependencies: new[] { "Mod C" });
+ Mock<IModMetadata> modE = this.GetMetadata("Mod E", dependencies: new[] { "Mod B" });
+ Mock<IModMetadata> modF = this.GetMetadata("Mod F", dependencies: new[] { "Mod C", "Mod E" });
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object, modF.Object, modE.Object }).ToArray();
@@ -338,11 +337,11 @@ namespace StardewModdingAPI.Tests
// ▲ │
// │ ▼
// └──── E
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B", "Mod D" }, allowStatusChange: true);
- Mock<IModMetadata> modD = this.GetMetadataForDependencyTest("Mod D", dependencies: new[] { "Mod E" }, allowStatusChange: true);
- Mock<IModMetadata> modE = this.GetMetadataForDependencyTest("Mod E", dependencies: new[] { "Mod C" }, allowStatusChange: true);
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B", "Mod D" }, allowStatusChange: true);
+ Mock<IModMetadata> modD = this.GetMetadata("Mod D", dependencies: new[] { "Mod E" }, allowStatusChange: true);
+ Mock<IModMetadata> modE = this.GetMetadata("Mod E", dependencies: new[] { "Mod C" }, allowStatusChange: true);
// act
IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modC.Object, modA.Object, modB.Object, modD.Object, modE.Object }).ToArray();
@@ -361,9 +360,9 @@ namespace StardewModdingAPI.Tests
{
// arrange
// A ◀── B ◀── C D (failed)
- Mock<IModMetadata> modA = this.GetMetadataForDependencyTest("Mod A");
- Mock<IModMetadata> modB = this.GetMetadataForDependencyTest("Mod B", dependencies: new[] { "Mod A" });
- Mock<IModMetadata> modC = this.GetMetadataForDependencyTest("Mod C", dependencies: new[] { "Mod B" }, allowStatusChange: true);
+ Mock<IModMetadata> modA = this.GetMetadata("Mod A");
+ Mock<IModMetadata> modB = this.GetMetadata("Mod B", dependencies: new[] { "Mod A" });
+ Mock<IModMetadata> modC = this.GetMetadata("Mod C", dependencies: new[] { "Mod B" }, allowStatusChange: true);
Mock<IModMetadata> modD = new Mock<IModMetadata>(MockBehavior.Strict);
modD.Setup(p => p.Manifest).Returns<IManifest>(null);
modD.Setup(p => p.Status).Returns(ModMetadataStatus.Failed);
@@ -379,12 +378,80 @@ namespace StardewModdingAPI.Tests
Assert.AreSame(modC.Object, mods[3], "The load order is incorrect: mod C should be fourth since it needs mod B, and is needed by mod D.");
}
+ [Test(Description = "Assert that dependencies are failed if they don't meet the minimum version.")]
+ public void ProcessDependencies_WithMinVersions_FailsIfNotMet()
+ {
+ // arrange
+ // A 1.0 ◀── B (need A 1.1)
+ Mock<IModMetadata> modA = this.GetMetadata(this.GetManifest("Mod A", "1.0"));
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.1")), allowStatusChange: true);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modA.Object, modB.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(2, mods.Length, 0, "Expected to get the same number of mods input.");
+ modB.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<string>()), Times.Once, "Mod B unexpectedly didn't fail even though it needs a newer version of Mod A.");
+ }
+
+ [Test(Description = "Assert that dependencies are accepted if they meet the minimum version.")]
+ public void ProcessDependencies_WithMinVersions_SucceedsIfMet()
+ {
+ // arrange
+ // A 1.0 ◀── B (need A 1.0-beta)
+ Mock<IModMetadata> modA = this.GetMetadata(this.GetManifest("Mod A", "1.0"));
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.0-beta")), allowStatusChange: false);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modA.Object, modB.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(2, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modA.Object, mods[0], "The load order is incorrect: mod A should be first since it's needed by mod B.");
+ Assert.AreSame(modB.Object, mods[1], "The load order is incorrect: mod B should be second since it needs mod A.");
+ }
+
+#if SMAPI_2_0
+ [Test(Description = "Assert that optional dependencies are sorted correctly if present.")]
+ public void ProcessDependencies_IfOptional()
+ {
+ // arrange
+ // A ◀── B
+ Mock<IModMetadata> modA = this.GetMetadata(this.GetManifest("Mod A", "1.0"));
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.0", required: false)), allowStatusChange: false);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modB.Object, modA.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(2, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modA.Object, mods[0], "The load order is incorrect: mod A should be first since it's needed by mod B.");
+ Assert.AreSame(modB.Object, mods[1], "The load order is incorrect: mod B should be second since it needs mod A.");
+ }
+
+ [Test(Description = "Assert that optional dependencies are accepted if they're missing.")]
+ public void ProcessDependencies_IfOptional_SucceedsIfMissing()
+ {
+ // arrange
+ // A ◀── B where A doesn't exist
+ Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest("Mod B", "1.0", new ManifestDependency("Mod A", "1.0", required: false)), allowStatusChange: false);
+
+ // act
+ IModMetadata[] mods = new ModResolver().ProcessDependencies(new[] { modB.Object }).ToArray();
+
+ // assert
+ Assert.AreEqual(1, mods.Length, 0, "Expected to get the same number of mods input.");
+ Assert.AreSame(modB.Object, mods[0], "The load order is incorrect: mod B should be first since it's the only mod.");
+ }
+#endif
+
+
/*********
** Private methods
*********/
/// <summary>Get a randomised basic manifest.</summary>
/// <param name="adjust">Adjust the generated manifest.</param>
- private Manifest GetRandomManifest(Action<Manifest> adjust = null)
+ private Manifest GetManifest(Action<Manifest> adjust = null)
{
Manifest manifest = new Manifest
{
@@ -401,26 +468,50 @@ namespace StardewModdingAPI.Tests
/// <summary>Get a randomised basic manifest.</summary>
/// <param name="uniqueID">The mod's name and unique ID.</param>
+ /// <param name="version">The mod version.</param>
/// <param name="dependencies">The dependencies this mod requires.</param>
+ private IManifest GetManifest(string uniqueID, string version, params IManifestDependency[] dependencies)
+ {
+ return this.GetManifest(manifest =>
+ {
+ manifest.Name = uniqueID;
+ manifest.UniqueID = uniqueID;
+ manifest.Version = new SemanticVersion(version);
+ manifest.Dependencies = dependencies;
+ });
+ }
+
+ /// <summary>Get a randomised basic manifest.</summary>
+ /// <param name="uniqueID">The mod's name and unique ID.</param>
+ private Mock<IModMetadata> GetMetadata(string uniqueID)
+ {
+ return this.GetMetadata(this.GetManifest(uniqueID, "1.0"));
+ }
+
+ /// <summary>Get a randomised basic manifest.</summary>
+ /// <param name="uniqueID">The mod's name and unique ID.</param>
+ /// <param name="dependencies">The dependencies this mod requires.</param>
+ /// <param name="allowStatusChange">Whether the code being tested is allowed to change the mod status.</param>
+ private Mock<IModMetadata> GetMetadata(string uniqueID, string[] dependencies, bool allowStatusChange = false)
+ {
+ IManifest manifest = this.GetManifest(uniqueID, "1.0", dependencies?.Select(dependencyID => (IManifestDependency)new ManifestDependency(dependencyID, null)).ToArray());
+ return this.GetMetadata(manifest, allowStatusChange);
+ }
+
+ /// <summary>Get a randomised basic manifest.</summary>
+ /// <param name="manifest">The mod manifest.</param>
/// <param name="allowStatusChange">Whether the code being tested is allowed to change the mod status.</param>
- private Mock<IModMetadata> GetMetadataForDependencyTest(string uniqueID, string[] dependencies = null, bool allowStatusChange = false)
+ private Mock<IModMetadata> GetMetadata(IManifest manifest, bool allowStatusChange = false)
{
Mock<IModMetadata> mod = new Mock<IModMetadata>(MockBehavior.Strict);
mod.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
- mod.Setup(p => p.DisplayName).Returns(uniqueID);
- mod.Setup(p => p.Manifest).Returns(
- this.GetRandomManifest(manifest =>
- {
- manifest.Name = uniqueID;
- manifest.UniqueID = uniqueID;
- manifest.Dependencies = dependencies?.Select(dependencyID => (IManifestDependency)new ManifestDependency(dependencyID)).ToArray();
- })
- );
+ mod.Setup(p => p.DisplayName).Returns(manifest.UniqueID);
+ mod.Setup(p => p.Manifest).Returns(manifest);
if (allowStatusChange)
{
mod
.Setup(p => p.SetStatus(It.IsAny<ModMetadataStatus>(), It.IsAny<string>()))
- .Callback<ModMetadataStatus, string>((status, message) => Console.WriteLine($"<{uniqueID} changed status: [{status}] {message}"))
+ .Callback<ModMetadataStatus, string>((status, message) => Console.WriteLine($"<{manifest.UniqueID} changed status: [{status}] {message}"))
.Returns(mod.Object);
}
return mod;
diff --git a/src/StardewModdingAPI.Tests/TranslationTests.cs b/src/StardewModdingAPI.Tests/Core/TranslationTests.cs
index 157a08a2..8511e765 100644
--- a/src/StardewModdingAPI.Tests/TranslationTests.cs
+++ b/src/StardewModdingAPI.Tests/Core/TranslationTests.cs
@@ -3,9 +3,10 @@ using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using StardewModdingAPI.Framework;
+using StardewModdingAPI.Framework.ModHelpers;
using StardewValley;
-namespace StardewModdingAPI.Tests
+namespace StardewModdingAPI.Tests.Core
{
/// <summary>Unit tests for <see cref="TranslationHelper"/> and <see cref="Translation"/>.</summary>
[TestFixture]
@@ -31,7 +32,7 @@ namespace StardewModdingAPI.Tests
var data = new Dictionary<string, IDictionary<string, string>>();
// act
- ITranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ ITranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
Translation translation = helper.Get("key");
Translation[] translationList = helper.GetTranslations()?.ToArray();
@@ -54,7 +55,7 @@ namespace StardewModdingAPI.Tests
// act
var actual = new Dictionary<string, Translation[]>();
- TranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ TranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
foreach (string locale in expected.Keys)
{
this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en);
@@ -78,7 +79,7 @@ namespace StardewModdingAPI.Tests
// act
var actual = new Dictionary<string, Translation[]>();
- TranslationHelper helper = new TranslationHelper("ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
+ TranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data);
foreach (string locale in expected.Keys)
{
this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en);
diff --git a/src/StardewModdingAPI.Tests/Framework/Sample.cs b/src/StardewModdingAPI.Tests/Sample.cs
index 10006f1e..99835d92 100644
--- a/src/StardewModdingAPI.Tests/Framework/Sample.cs
+++ b/src/StardewModdingAPI.Tests/Sample.cs
@@ -1,6 +1,6 @@
using System;
-namespace StardewModdingAPI.Tests.Framework
+namespace StardewModdingAPI.Tests
{
/// <summary>Provides sample values for unit testing.</summary>
internal static class Sample
diff --git a/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj b/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
index 3818ec9c..9bfd7567 100644
--- a/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
+++ b/src/StardewModdingAPI.Tests/StardewModdingAPI.Tests.csproj
@@ -48,10 +48,12 @@
<Compile Include="..\GlobalAssemblyInfo.cs">
<Link>Properties\GlobalAssemblyInfo.cs</Link>
</Compile>
- <Compile Include="TranslationTests.cs" />
- <Compile Include="ModResolverTests.cs" />
+ <Compile Include="Utilities\SemanticVersionTests.cs" />
+ <Compile Include="Utilities\SDateTests.cs" />
+ <Compile Include="Core\TranslationTests.cs" />
+ <Compile Include="Core\ModResolverTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Framework\Sample.cs" />
+ <Compile Include="Sample.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
diff --git a/src/StardewModdingAPI.Tests/Utilities/SDateTests.cs b/src/StardewModdingAPI.Tests/Utilities/SDateTests.cs
new file mode 100644
index 00000000..714756e0
--- /dev/null
+++ b/src/StardewModdingAPI.Tests/Utilities/SDateTests.cs
@@ -0,0 +1,253 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Text.RegularExpressions;
+using NUnit.Framework;
+using StardewModdingAPI.Utilities;
+
+namespace StardewModdingAPI.Tests.Utilities
+{
+ /// <summary>Unit tests for <see cref="SDate"/>.</summary>
+ [TestFixture]
+ internal class SDateTests
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>All valid seasons.</summary>
+ private static readonly string[] ValidSeasons = { "spring", "summer", "fall", "winter" };
+
+ /// <summary>All valid days of a month.</summary>
+ private static readonly int[] ValidDays = Enumerable.Range(1, 28).ToArray();
+
+ /// <summary>Sample relative dates for test cases.</summary>
+ private static class Dates
+ {
+ /// <summary>The base date to which other dates are relative.</summary>
+ public const string Now = "02 summer Y2";
+
+ /// <summary>The day before <see cref="Now"/>.</summary>
+ public const string PrevDay = "01 summer Y2";
+
+ /// <summary>The month before <see cref="Now"/>.</summary>
+ public const string PrevMonth = "02 spring Y2";
+
+ /// <summary>The year before <see cref="Now"/>.</summary>
+ public const string PrevYear = "02 summer Y1";
+
+ /// <summary>The day after <see cref="Now"/>.</summary>
+ public const string NextDay = "03 summer Y2";
+
+ /// <summary>The month after <see cref="Now"/>.</summary>
+ public const string NextMonth = "02 fall Y2";
+
+ /// <summary>The year after <see cref="Now"/>.</summary>
+ public const string NextYear = "02 summer Y3";
+ }
+
+
+ /*********
+ ** Unit tests
+ *********/
+ /****
+ ** Constructor
+ ****/
+ [Test(Description = "Assert that the constructor sets the expected values for all valid dates.")]
+ public void Constructor_SetsExpectedValues([ValueSource(nameof(SDateTests.ValidSeasons))] string season, [ValueSource(nameof(SDateTests.ValidDays))] int day, [Values(1, 2, 100)] int year)
+ {
+ // act
+ SDate date = new SDate(day, season, year);
+
+ // assert
+ Assert.AreEqual(day, date.Day);
+ Assert.AreEqual(season, date.Season);
+ Assert.AreEqual(year, date.Year);
+ }
+
+ [Test(Description = "Assert that the constructor throws an exception if the values are invalid.")]
+ [TestCase(01, "Spring", 1)] // seasons are case-sensitive
+ [TestCase(01, "springs", 1)] // invalid season name
+ [TestCase(-1, "spring", 1)] // day < 0
+ [TestCase(29, "spring", 1)] // day > 28
+ [TestCase(01, "spring", -1)] // year < 1
+ [TestCase(01, "spring", 0)] // year < 1
+ [SuppressMessage("ReSharper", "AssignmentIsFullyDiscarded", Justification = "Deliberate for unit test.")]
+ public void Constructor_RejectsInvalidValues(int day, string season, int year)
+ {
+ // act & assert
+ Assert.Throws<ArgumentException>(() => _ = new SDate(day, season, year), "Constructing the invalid date didn't throw the expected exception.");
+ }
+
+ /****
+ ** ToString
+ ****/
+ [Test(Description = "Assert that ToString returns the expected string.")]
+ [TestCase("14 spring Y1", ExpectedResult = "14 spring Y1")]
+ [TestCase("01 summer Y16", ExpectedResult = "01 summer Y16")]
+ [TestCase("28 fall Y10", ExpectedResult = "28 fall Y10")]
+ [TestCase("01 winter Y1", ExpectedResult = "01 winter Y1")]
+ public string ToString(string dateStr)
+ {
+ return this.GetDate(dateStr).ToString();
+ }
+
+ /****
+ ** AddDays
+ ****/
+ [Test(Description = "Assert that AddDays returns the expected date.")]
+ [TestCase("01 spring Y1", 15, ExpectedResult = "16 spring Y1")] // day transition
+ [TestCase("01 spring Y1", 28, ExpectedResult = "01 summer Y1")] // season transition
+ [TestCase("01 spring Y1", 28 * 4, ExpectedResult = "01 spring Y2")] // year transition
+ [TestCase("01 spring Y1", 28 * 7 + 17, ExpectedResult = "18 winter Y2")] // year transition
+ [TestCase("15 spring Y1", -14, ExpectedResult = "01 spring Y1")] // negative day transition
+ [TestCase("15 summer Y1", -28, ExpectedResult = "15 spring Y1")] // negative season transition
+ [TestCase("15 summer Y2", -28 * 4, ExpectedResult = "15 summer Y1")] // negative year transition
+ [TestCase("01 spring Y3", -(28 * 7 + 17), ExpectedResult = "12 spring Y1")] // negative year transition
+ public string AddDays(string dateStr, int addDays)
+ {
+ return this.GetDate(dateStr).AddDays(addDays).ToString();
+ }
+
+ /****
+ ** GetHashCode
+ ****/
+ [Test(Description = "Assert that GetHashCode returns a unique ordered value for every date.")]
+ public void GetHashCode_ReturnsUniqueOrderedValue()
+ {
+ IDictionary<int, SDate> hashes = new Dictionary<int, SDate>();
+ int lastHash = int.MinValue;
+ for (int year = 1; year <= 4; year++)
+ {
+ foreach (string season in SDateTests.ValidSeasons)
+ {
+ foreach (int day in SDateTests.ValidDays)
+ {
+ SDate date = new SDate(day, season, year);
+ int hash = date.GetHashCode();
+ if (hashes.TryGetValue(hash, out SDate otherDate))
+ Assert.Fail($"Received identical hash code {hash} for dates {otherDate} and {date}.");
+ if (hash < lastHash)
+ Assert.Fail($"Received smaller hash code for date {date} ({hash}) relative to {hashes[lastHash]} ({lastHash}).");
+
+ lastHash = hash;
+ hashes[hash] = date;
+ }
+ }
+ }
+ }
+
+ [Test(Description = "Assert that the == operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = false)]
+ public bool Operators_Equals(string now, string other)
+ {
+ return this.GetDate(now) == this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the != operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = true)]
+ public bool Operators_NotEquals(string now, string other)
+ {
+ return this.GetDate(now) != this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the < operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = true)]
+ public bool Operators_LessThan(string now, string other)
+ {
+ return this.GetDate(now) < this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the <= operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = true)]
+ public bool Operators_LessThanOrEqual(string now, string other)
+ {
+ return this.GetDate(now) <= this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the > operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = false)]
+ public bool Operators_MoreThan(string now, string other)
+ {
+ return this.GetDate(now) > this.GetDate(other);
+ }
+
+ [Test(Description = "Assert that the > operator returns the expected values. We only need a few test cases, since it's based on GetHashCode which is tested more thoroughly.")]
+ [TestCase(Dates.Now, null, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.PrevDay, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevMonth, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.PrevYear, ExpectedResult = true)]
+ [TestCase(Dates.Now, Dates.Now, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextDay, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextMonth, ExpectedResult = false)]
+ [TestCase(Dates.Now, Dates.NextYear, ExpectedResult = false)]
+ public bool Operators_MoreThanOrEqual(string now, string other)
+ {
+ return this.GetDate(now) > this.GetDate(other);
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Convert a string date into a game date, to make unit tests easier to read.</summary>
+ /// <param name="dateStr">The date string like "dd MMMM yy".</param>
+ private SDate GetDate(string dateStr)
+ {
+ if (dateStr == null)
+ return null;
+
+ void Fail(string reason) => throw new AssertionException($"Couldn't parse date '{dateStr}' because {reason}.");
+
+ // parse
+ Match match = Regex.Match(dateStr, @"^(?<day>\d+) (?<season>\w+) Y(?<year>\d+)$");
+ if (!match.Success)
+ Fail("it doesn't match expected pattern (should be like 28 spring Y1)");
+
+ // extract parts
+ string season = match.Groups["season"].Value;
+ if (!int.TryParse(match.Groups["day"].Value, out int day))
+ Fail($"'{match.Groups["day"].Value}' couldn't be parsed as a day.");
+ if (!int.TryParse(match.Groups["year"].Value, out int year))
+ Fail($"'{match.Groups["year"].Value}' couldn't be parsed as a year.");
+
+ // build date
+ return new SDate(day, season, year);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs b/src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs
new file mode 100644
index 00000000..95d0d74f
--- /dev/null
+++ b/src/StardewModdingAPI.Tests/Utilities/SemanticVersionTests.cs
@@ -0,0 +1,255 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using NUnit.Framework;
+
+namespace StardewModdingAPI.Tests.Utilities
+{
+ /// <summary>Unit tests for <see cref="SemanticVersion"/>.</summary>
+ [TestFixture]
+ internal class SemanticVersionTests
+ {
+ /*********
+ ** Unit tests
+ *********/
+ /****
+ ** Constructor
+ ****/
+ [Test(Description = "Assert that the constructor sets the expected values for all valid versions.")]
+ [TestCase("1.0", ExpectedResult = "1.0")]
+ [TestCase("1.0.0", ExpectedResult = "1.0")]
+ [TestCase("3000.4000.5000", ExpectedResult = "3000.4000.5000")]
+ [TestCase("1.2-some-tag.4", ExpectedResult = "1.2-some-tag.4")]
+ [TestCase("1.2.3-some-tag.4", ExpectedResult = "1.2.3-some-tag.4")]
+ [TestCase("1.2.3-some-tag.4 ", ExpectedResult = "1.2.3-some-tag.4")]
+ public string Constructor_FromString(string input)
+ {
+ return new SemanticVersion(input).ToString();
+ }
+
+ [Test(Description = "Assert that the constructor sets the expected values for all valid versions.")]
+ [TestCase(1, 0, 0, null, ExpectedResult = "1.0")]
+ [TestCase(3000, 4000, 5000, null, ExpectedResult = "3000.4000.5000")]
+ [TestCase(1, 2, 3, "", ExpectedResult = "1.2.3")]
+ [TestCase(1, 2, 3, " ", ExpectedResult = "1.2.3")]
+ [TestCase(1, 2, 3, "some-tag.4", ExpectedResult = "1.2.3-some-tag.4")]
+ [TestCase(1, 2, 3, "some-tag.4 ", ExpectedResult = "1.2.3-some-tag.4")]
+ public string Constructor_FromParts(int major, int minor, int patch, string tag)
+ {
+ // act
+ ISemanticVersion version = new SemanticVersion(major, minor, patch, tag);
+
+ // assert
+ Assert.AreEqual(major, version.MajorVersion, "The major version doesn't match the given value.");
+ Assert.AreEqual(minor, version.MinorVersion, "The minor version doesn't match the given value.");
+ Assert.AreEqual(patch, version.PatchVersion, "The patch version doesn't match the given value.");
+ Assert.AreEqual(string.IsNullOrWhiteSpace(tag) ? null : tag.Trim(), version.Build, "The tag doesn't match the given value.");
+ return version.ToString();
+ }
+
+ [Test(Description = "Assert that the constructor throws the expected exception for invalid versions.")]
+ [TestCase(null)]
+ [TestCase("")]
+ [TestCase(" ")]
+ [TestCase("1")]
+ [TestCase("01.0")]
+ [TestCase("1.05")]
+ [TestCase("1.5.06")] // leading zeros specifically prohibited by spec
+ [TestCase("1.2.3.4")]
+ [TestCase("1.apple")]
+ [TestCase("1.2.apple")]
+ [TestCase("1.2.3.apple")]
+ [TestCase("1..2..3")]
+ [TestCase("1.2.3-")]
+ [TestCase("1.2.3-some-tag...")]
+ [TestCase("1.2.3-some-tag...4")]
+ [TestCase("apple")]
+ [TestCase("-apple")]
+ [TestCase("-5")]
+ public void Constructor_FromString_WithInvalidValues(string input)
+ {
+ if (input == null)
+ this.AssertAndLogException<ArgumentNullException>(() => new SemanticVersion(input));
+ else
+ this.AssertAndLogException<FormatException>(() => new SemanticVersion(input));
+ }
+
+ /****
+ ** CompareTo
+ ****/
+ [Test(Description = "Assert that version.CompareTo returns the expected value.")]
+ // equal
+ [TestCase("0.5.7", "0.5.7", ExpectedResult = 0)]
+ [TestCase("1.0", "1.0", ExpectedResult = 0)]
+ [TestCase("1.0-beta", "1.0-beta", ExpectedResult = 0)]
+ [TestCase("1.0-beta.10", "1.0-beta.10", ExpectedResult = 0)]
+ [TestCase("1.0-beta", "1.0-beta ", ExpectedResult = 0)]
+
+ // less than
+ [TestCase("0.5.7", "0.5.8", ExpectedResult = -1)]
+ [TestCase("1.0", "1.1", ExpectedResult = -1)]
+ [TestCase("1.0-beta", "1.0", ExpectedResult = -1)]
+ [TestCase("1.0-beta", "1.0-beta.2", ExpectedResult = -1)]
+ [TestCase("1.0-beta.1", "1.0-beta.2", ExpectedResult = -1)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", ExpectedResult = -1)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", ExpectedResult = -1)]
+
+ // more than
+ [TestCase("0.5.8", "0.5.7", ExpectedResult = 1)]
+ [TestCase("1.1", "1.0", ExpectedResult = 1)]
+ [TestCase("1.0", "1.0-beta", ExpectedResult = 1)]
+ [TestCase("1.0-beta.2", "1.0-beta", ExpectedResult = 1)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", ExpectedResult = 1)]
+ [TestCase("1.0-beta.10", "1.0-beta.2", ExpectedResult = 1)]
+ [TestCase("1.0-beta-10", "1.0-beta-2", ExpectedResult = 1)]
+ public int CompareTo(string versionStrA, string versionStrB)
+ {
+ ISemanticVersion versionA = new SemanticVersion(versionStrA);
+ ISemanticVersion versionB = new SemanticVersion(versionStrB);
+ return versionA.CompareTo(versionB);
+ }
+
+ /****
+ ** IsOlderThan
+ ****/
+ [Test(Description = "Assert that version.IsOlderThan returns the expected value.")]
+ // keep test cases in sync with CompareTo for simplicity.
+ // equal
+ [TestCase("0.5.7", "0.5.7", ExpectedResult = false)]
+ [TestCase("1.0", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.10", "1.0-beta.10", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta ", ExpectedResult = false)]
+
+ // less than
+ [TestCase("0.5.7", "0.5.8", ExpectedResult = true)]
+ [TestCase("1.0", "1.1", ExpectedResult = true)]
+ [TestCase("1.0-beta", "1.0", ExpectedResult = true)]
+ [TestCase("1.0-beta", "1.0-beta.2", ExpectedResult = true)]
+ [TestCase("1.0-beta.1", "1.0-beta.2", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", ExpectedResult = true)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", ExpectedResult = true)]
+
+ // more than
+ [TestCase("0.5.8", "0.5.7", ExpectedResult = false)]
+ [TestCase("1.1", "1.0", ExpectedResult = false)]
+ [TestCase("1.0", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", ExpectedResult = false)]
+ [TestCase("1.0-beta.10", "1.0-beta.2", ExpectedResult = false)]
+ [TestCase("1.0-beta-10", "1.0-beta-2", ExpectedResult = false)]
+ public bool IsOlderThan(string versionStrA, string versionStrB)
+ {
+ ISemanticVersion versionA = new SemanticVersion(versionStrA);
+ ISemanticVersion versionB = new SemanticVersion(versionStrB);
+ return versionA.IsOlderThan(versionB);
+ }
+
+ /****
+ ** IsNewerThan
+ ****/
+ [Test(Description = "Assert that version.IsNewerThan returns the expected value.")]
+ // keep test cases in sync with CompareTo for simplicity.
+ // equal
+ [TestCase("0.5.7", "0.5.7", ExpectedResult = false)]
+ [TestCase("1.0", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta", ExpectedResult = false)]
+ [TestCase("1.0-beta.10", "1.0-beta.10", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta ", ExpectedResult = false)]
+
+ // less than
+ [TestCase("0.5.7", "0.5.8", ExpectedResult = false)]
+ [TestCase("1.0", "1.1", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta", "1.0-beta.2", ExpectedResult = false)]
+ [TestCase("1.0-beta.1", "1.0-beta.2", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", ExpectedResult = false)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", ExpectedResult = false)]
+
+ // more than
+ [TestCase("0.5.8", "0.5.7", ExpectedResult = true)]
+ [TestCase("1.1", "1.0", ExpectedResult = true)]
+ [TestCase("1.0", "1.0-beta", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", ExpectedResult = true)]
+ [TestCase("1.0-beta.10", "1.0-beta.2", ExpectedResult = true)]
+ [TestCase("1.0-beta-10", "1.0-beta-2", ExpectedResult = true)]
+ public bool IsNewerThan(string versionStrA, string versionStrB)
+ {
+ ISemanticVersion versionA = new SemanticVersion(versionStrA);
+ ISemanticVersion versionB = new SemanticVersion(versionStrB);
+ return versionA.IsNewerThan(versionB);
+ }
+
+ /****
+ ** IsBetween
+ ****/
+ [Test(Description = "Assert that version.IsNewerThan returns the expected value.")]
+ // is between
+ [TestCase("0.5.7-beta.3", "0.5.7-beta.3", "0.5.7-beta.3", ExpectedResult = true)]
+ [TestCase("1.0", "1.0", "1.1", ExpectedResult = true)]
+ [TestCase("1.0", "1.0-beta", "1.1", ExpectedResult = true)]
+ [TestCase("1.0", "0.5", "1.1", ExpectedResult = true)]
+ [TestCase("1.0-beta.2", "1.0-beta.1", "1.0-beta.3", ExpectedResult = true)]
+ [TestCase("1.0-beta-2", "1.0-beta-1", "1.0-beta-3", ExpectedResult = true)]
+
+ // is not between
+ [TestCase("1.0-beta", "1.0", "1.1", ExpectedResult = false)]
+ [TestCase("1.0", "1.1", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.1", "1.0", ExpectedResult = false)]
+ [TestCase("1.0-beta.2", "1.0-beta.10", "1.0-beta.3", ExpectedResult = false)]
+ [TestCase("1.0-beta-2", "1.0-beta-10", "1.0-beta-3", ExpectedResult = false)]
+ public bool IsBetween(string versionStr, string lowerStr, string upperStr)
+ {
+ ISemanticVersion lower = new SemanticVersion(lowerStr);
+ ISemanticVersion upper = new SemanticVersion(upperStr);
+ ISemanticVersion version = new SemanticVersion(versionStr);
+ return version.IsBetween(lower, upper);
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Assert that the expected exception type is thrown, and log the action output and thrown exception.</summary>
+ /// <typeparam name="T">The expected exception type.</typeparam>
+ /// <param name="action">The action which may throw the exception.</param>
+ /// <param name="message">The message to log if the expected exception isn't thrown.</param>
+ [SuppressMessage("ReSharper", "UnusedParameter.Local", Justification = "The message argument is deliberately only used in precondition checks since this is an assertion method.")]
+ private void AssertAndLogException<T>(Func<object> action, string message = null)
+ where T : Exception
+ {
+ this.AssertAndLogException<T>(() =>
+ {
+ object result = action();
+ TestContext.WriteLine($"Func result: {result}");
+ });
+ }
+
+ /// <summary>Assert that the expected exception type is thrown, and log the thrown exception.</summary>
+ /// <typeparam name="T">The expected exception type.</typeparam>
+ /// <param name="action">The action which may throw the exception.</param>
+ /// <param name="message">The message to log if the expected exception isn't thrown.</param>
+ [SuppressMessage("ReSharper", "UnusedParameter.Local", Justification = "The message argument is deliberately only used in precondition checks since this is an assertion method.")]
+ private void AssertAndLogException<T>(Action action, string message = null)
+ where T : Exception
+ {
+ try
+ {
+ action();
+ }
+ catch (T ex)
+ {
+ TestContext.WriteLine($"Exception thrown:\n{ex}");
+ return;
+ }
+ catch (Exception ex) when (!(ex is AssertionException))
+ {
+ TestContext.WriteLine($"Exception thrown:\n{ex}");
+ Assert.Fail(message ?? $"Didn't throw the expected exception; expected {typeof(T).FullName}, got {ex.GetType().FullName}.");
+ }
+
+ // no exception thrown
+ Assert.Fail(message ?? "Didn't throw an exception.");
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.sln b/src/StardewModdingAPI.sln
index edc299f4..4d27e51b 100644
--- a/src/StardewModdingAPI.sln
+++ b/src/StardewModdingAPI.sln
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
-VisualStudioVersion = 15.0.26430.4
+VisualStudioVersion = 15.0.26430.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainerMod", "TrainerMod\TrainerMod.csproj", "{28480467-1A48-46A7-99F8-236D95225359}"
EndProject
@@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "metadata", "metadata", "{86
.editorconfig = .editorconfig
..\.gitattributes = ..\.gitattributes
..\.gitignore = ..\.gitignore
+ ..\CONTRIBUTING.md = ..\CONTRIBUTING.md
crossplatform.targets = crossplatform.targets
GlobalAssemblyInfo.cs = GlobalAssemblyInfo.cs
..\LICENSE = ..\LICENSE
diff --git a/src/StardewModdingAPI/Command.cs b/src/StardewModdingAPI/Command.cs
index e2d08538..689bb18b 100644
--- a/src/StardewModdingAPI/Command.cs
+++ b/src/StardewModdingAPI/Command.cs
@@ -1,4 +1,5 @@
-using System;
+#if !SMAPI_2_0
+using System;
using System.Collections.Generic;
using StardewModdingAPI.Events;
using StardewModdingAPI.Framework;
@@ -94,7 +95,7 @@ namespace StardewModdingAPI
/// <param name="monitor">Encapsulates monitoring and logging.</param>
public static void CallCommand(string input, IMonitor monitor)
{
- Command.DeprecationManager.Warn("Command.CallCommand", "1.9", DeprecationLevel.Info);
+ Command.DeprecationManager.Warn("Command.CallCommand", "1.9", DeprecationLevel.PendingRemoval);
Command.CommandManager.Trigger(input);
}
@@ -107,7 +108,7 @@ namespace StardewModdingAPI
name = name?.Trim().ToLower();
// raise deprecation warning
- Command.DeprecationManager.Warn("Command.RegisterCommand", "1.9", DeprecationLevel.Info);
+ Command.DeprecationManager.Warn("Command.RegisterCommand", "1.9", DeprecationLevel.PendingRemoval);
// validate
if (Command.LegacyCommands.ContainsKey(name))
@@ -130,7 +131,7 @@ namespace StardewModdingAPI
/// <param name="name">The command name to find.</param>
public static Command FindCommand(string name)
{
- Command.DeprecationManager.Warn("Command.FindCommand", "1.9", DeprecationLevel.Info);
+ Command.DeprecationManager.Warn("Command.FindCommand", "1.9", DeprecationLevel.PendingRemoval);
if (name == null)
return null;
@@ -155,3 +156,4 @@ namespace StardewModdingAPI
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Config.cs b/src/StardewModdingAPI/Config.cs
index 9f4bfad2..e166f414 100644
--- a/src/StardewModdingAPI/Config.cs
+++ b/src/StardewModdingAPI/Config.cs
@@ -1,4 +1,5 @@
-using System;
+#if !SMAPI_2_0
+using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
@@ -125,7 +126,7 @@ namespace StardewModdingAPI
/// <summary>Construct an instance.</summary>
protected Config()
{
- Config.DeprecationManager.Warn("the Config class", "1.0", DeprecationLevel.Info);
+ Config.DeprecationManager.Warn("the Config class", "1.0", DeprecationLevel.PendingRemoval);
Config.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.BaseConfigPath)}", "1.0"); // typically used to construct config, avoid redundant warnings
}
}
@@ -184,3 +185,4 @@ namespace StardewModdingAPI
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Constants.cs b/src/StardewModdingAPI/Constants.cs
index bd489b29..586cadeb 100644
--- a/src/StardewModdingAPI/Constants.cs
+++ b/src/StardewModdingAPI/Constants.cs
@@ -33,7 +33,12 @@ namespace StardewModdingAPI
** Public
****/
/// <summary>SMAPI's current semantic version.</summary>
- public static ISemanticVersion ApiVersion { get; } = new SemanticVersion(1, 14, 1); // alpha-{DateTime.UtcNow:yyyyMMddHHmm}
+ public static ISemanticVersion ApiVersion { get; } =
+#if SMAPI_2_0
+ new SemanticVersion(2, 0, 0, $"alpha-{DateTime.UtcNow:yyyyMMddHHmm}");
+#else
+ new SemanticVersion(1, 15, 0); // alpha-{DateTime.UtcNow:yyyyMMddHHmm}
+#endif
/// <summary>The minimum supported version of Stardew Valley.</summary>
public static ISemanticVersion MinimumGameVersion { get; } = new SemanticVersion("1.2.30");
@@ -169,6 +174,32 @@ namespace StardewModdingAPI
new EventFinder("StardewModdingAPI.Events.GraphicsEvents", "OnPreRenderHudEventNoCheck"),
new EventFinder("StardewModdingAPI.Events.GraphicsEvents", "OnPreRenderGuiEventNoCheck"),
+ // APIs removed in SMAPI 2.0
+#if SMAPI_2_0
+ new TypeFinder("StardewModdingAPI.Command"),
+ new TypeFinder("StardewModdingAPI.Config"),
+ new TypeFinder("StardewModdingAPI.Log"),
+ new TypeFinder("StardewModdingAPI.Events.EventArgsCommand"),
+ new TypeFinder("StardewModdingAPI.Events.EventArgsFarmerChanged"),
+ new TypeFinder("StardewModdingAPI.Events.EventArgsLoadedGameChanged"),
+ new TypeFinder("StardewModdingAPI.Events.EventArgsNewDay"),
+ new TypeFinder("StardewModdingAPI.Events.EventArgsStringChanged"),
+ new PropertyFinder("StardewModdingAPI.Mod", "PathOnDisk"),
+ new PropertyFinder("StardewModdingAPI.Mod", "BaseConfigPath"),
+ new PropertyFinder("StardewModdingAPI.Mod", "PerSaveConfigFolder"),
+ new PropertyFinder("StardewModdingAPI.Mod", "PerSaveConfigPath"),
+ new EventFinder("StardewModdingAPI.Events.GameEvents", "Initialize"),
+ new EventFinder("StardewModdingAPI.Events.GameEvents", "LoadContent"),
+ new EventFinder("StardewModdingAPI.Events.GameEvents", "GameLoaded"),
+ new EventFinder("StardewModdingAPI.Events.GameEvents", "FirstUpdateTick"),
+ new EventFinder("StardewModdingAPI.Events.PlayerEvents", "LoadedGame"),
+ new EventFinder("StardewModdingAPI.Events.PlayerEvents", "FarmerChanged"),
+ new EventFinder("StardewModdingAPI.Events.TimeEvents", "DayOfMonthChanged"),
+ new EventFinder("StardewModdingAPI.Events.TimeEvents", "YearOfGameChanged"),
+ new EventFinder("StardewModdingAPI.Events.TimeEvents", "SeasonOfYearChanged"),
+ new EventFinder("StardewModdingAPI.Events.TimeEvents", "OnNewDay"),
+#endif
+
/****
** Rewriters change CIL as needed to fix incompatible code
****/
diff --git a/src/StardewModdingAPI/Events/ContentEvents.cs b/src/StardewModdingAPI/Events/ContentEvents.cs
index 8fa9ae3c..4b4e2ad0 100644
--- a/src/StardewModdingAPI/Events/ContentEvents.cs
+++ b/src/StardewModdingAPI/Events/ContentEvents.cs
@@ -1,6 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
using StardewModdingAPI.Framework;
namespace StardewModdingAPI.Events
@@ -8,21 +6,6 @@ namespace StardewModdingAPI.Events
/// <summary>Events raised when the game loads content.</summary>
public static class ContentEvents
{
- /*********
- ** Properties
- *********/
- /// <summary>Tracks the installed mods.</summary>
- private static ModRegistry ModRegistry;
-
- /// <summary>Encapsulates monitoring and logging.</summary>
- private static IMonitor Monitor;
-
- /// <summary>The mods using the experimental API for which a warning has been raised.</summary>
- private static readonly HashSet<string> WarnedMods = new HashSet<string>();
-
- /// <summary>The backing field for <see cref="AfterAssetLoaded"/>.</summary>
- [SuppressMessage("ReSharper", "InconsistentNaming")]
- private static event EventHandler<IContentEventHelper> _AfterAssetLoaded;
/*********
** Events
@@ -30,35 +13,10 @@ namespace StardewModdingAPI.Events
/// <summary>Raised after the content language changes.</summary>
public static event EventHandler<EventArgsValueChanged<string>> AfterLocaleChanged;
- /// <summary>Raised when an XNB file is being read into the cache. Mods can change the data here before it's cached.</summary>
-#if EXPERIMENTAL
- public
-#else
- internal
-#endif
- static event EventHandler<IContentEventHelper> AfterAssetLoaded
- {
- add
- {
- ContentEvents.RaiseContentExperimentalWarning();
- ContentEvents._AfterAssetLoaded += value;
- }
- remove => ContentEvents._AfterAssetLoaded -= value;
- }
-
/*********
** Internal methods
*********/
- /// <summary>Injects types required for backwards compatibility.</summary>
- /// <param name="modRegistry">Tracks the installed mods.</param>
- /// <param name="monitor">Encapsulates monitoring and logging.</param>
- internal static void Shim(ModRegistry modRegistry, IMonitor monitor)
- {
- ContentEvents.ModRegistry = modRegistry;
- ContentEvents.Monitor = monitor;
- }
-
/// <summary>Raise an <see cref="AfterLocaleChanged"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="oldLocale">The previous locale.</param>
@@ -67,28 +25,5 @@ namespace StardewModdingAPI.Events
{
monitor.SafelyRaiseGenericEvent($"{nameof(ContentEvents)}.{nameof(ContentEvents.AfterLocaleChanged)}", ContentEvents.AfterLocaleChanged?.GetInvocationList(), null, new EventArgsValueChanged<string>(oldLocale, newLocale));
}
-
- /// <summary>Raise an <see cref="AfterAssetLoaded"/> event.</summary>
- /// <param name="monitor">Encapsulates monitoring and logging.</param>
- /// <param name="contentHelper">Encapsulates access and changes to content being read from a data file.</param>
- internal static void InvokeAfterAssetLoaded(IMonitor monitor, IContentEventHelper contentHelper)
- {
- monitor.SafelyRaiseGenericEvent($"{nameof(ContentEvents)}.{nameof(ContentEvents.AfterAssetLoaded)}", ContentEvents._AfterAssetLoaded?.GetInvocationList(), null, contentHelper);
- }
-
-
- /*********
- ** Private methods
- *********/
- /// <summary>Raise an 'experimental API' warning for a mod using the content API.</summary>
- private static void RaiseContentExperimentalWarning()
- {
- string modName = ContentEvents.ModRegistry.GetModFromStack() ?? "An unknown mod";
- if (!ContentEvents.WarnedMods.Contains(modName))
- {
- ContentEvents.WarnedMods.Add(modName);
- ContentEvents.Monitor.Log($"{modName} used the undocumented and experimental content API, which may change or be removed without warning.", LogLevel.Warn);
- }
- }
}
}
diff --git a/src/StardewModdingAPI/Events/EventArgsCommand.cs b/src/StardewModdingAPI/Events/EventArgsCommand.cs
index 88a9e5a3..f0435904 100644
--- a/src/StardewModdingAPI/Events/EventArgsCommand.cs
+++ b/src/StardewModdingAPI/Events/EventArgsCommand.cs
@@ -1,4 +1,5 @@
-using System;
+#if !SMAPI_2_0
+using System;
namespace StardewModdingAPI.Events
{
@@ -24,3 +25,4 @@ namespace StardewModdingAPI.Events
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs b/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs
index 699d90be..c34fc4ab 100644
--- a/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs
+++ b/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs
@@ -1,3 +1,4 @@
+#if !SMAPI_2_0
using System;
using SFarmer = StardewValley.Farmer;
@@ -29,3 +30,4 @@ namespace StardewModdingAPI.Events
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Events/EventArgsInput.cs b/src/StardewModdingAPI/Events/EventArgsInput.cs
new file mode 100644
index 00000000..e5eb7372
--- /dev/null
+++ b/src/StardewModdingAPI/Events/EventArgsInput.cs
@@ -0,0 +1,126 @@
+#if SMAPI_2_0
+using System;
+using System.Linq;
+using Microsoft.Xna.Framework;
+using Microsoft.Xna.Framework.Input;
+using StardewModdingAPI.Utilities;
+using StardewValley;
+
+namespace StardewModdingAPI.Events
+{
+ /// <summary>Event arguments when a button is pressed or released.</summary>
+ public class EventArgsInput : EventArgs
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The button on the controller, keyboard, or mouse.</summary>
+ public SButton Button { get; }
+
+ /// <summary>The current cursor position.</summary>
+ public ICursorPosition Cursor { get; set; }
+
+ /// <summary>Whether the input is considered a 'click' by the game for enabling action.</summary>
+ public bool IsClick { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="button">The button on the controller, keyboard, or mouse.</param>
+ /// <param name="cursor">The cursor position.</param>
+ /// <param name="isClick">Whether the input is considered a 'click' by the game for enabling action.</param>
+ public EventArgsInput(SButton button, ICursorPosition cursor, bool isClick)
+ {
+ this.Button = button;
+ this.Cursor = cursor;
+ this.IsClick = isClick;
+ }
+
+ /// <summary>Prevent the game from handling the vurrent button press. This doesn't prevent other mods from receiving the event.</summary>
+ public void SuppressButton()
+ {
+ this.SuppressButton(this.Button);
+ }
+
+ /// <summary>Prevent the game from handling a button press. This doesn't prevent other mods from receiving the event.</summary>
+ /// <param name="button">The button to suppress.</param>
+ public void SuppressButton(SButton button)
+ {
+ // keyboard
+ if (this.Button.TryGetKeyboard(out Keys key))
+ Game1.oldKBState = new KeyboardState(Game1.oldKBState.GetPressedKeys().Except(new[] { key }).ToArray());
+
+ // controller
+ else if (this.Button.TryGetController(out Buttons controllerButton))
+ {
+ var newState = GamePad.GetState(PlayerIndex.One);
+ var thumbsticks = Game1.oldPadState.ThumbSticks;
+ var triggers = Game1.oldPadState.Triggers;
+ var buttons = Game1.oldPadState.Buttons;
+ var dpad = Game1.oldPadState.DPad;
+
+ switch (controllerButton)
+ {
+ // d-pad
+ case Buttons.DPadDown:
+ dpad = new GamePadDPad(dpad.Up, newState.DPad.Down, dpad.Left, dpad.Right);
+ break;
+ case Buttons.DPadLeft:
+ dpad = new GamePadDPad(dpad.Up, dpad.Down, newState.DPad.Left, dpad.Right);
+ break;
+ case Buttons.DPadRight:
+ dpad = new GamePadDPad(dpad.Up, dpad.Down, dpad.Left, newState.DPad.Right);
+ break;
+ case Buttons.DPadUp:
+ dpad = new GamePadDPad(newState.DPad.Up, dpad.Down, dpad.Left, dpad.Right);
+ break;
+
+ // trigger
+ case Buttons.LeftTrigger:
+ triggers = new GamePadTriggers(newState.Triggers.Left, triggers.Right);
+ break;
+ case Buttons.RightTrigger:
+ triggers = new GamePadTriggers(triggers.Left, newState.Triggers.Right);
+ break;
+
+ // thumbstick
+ case Buttons.LeftThumbstickDown:
+ case Buttons.LeftThumbstickLeft:
+ case Buttons.LeftThumbstickRight:
+ case Buttons.LeftThumbstickUp:
+ thumbsticks = new GamePadThumbSticks(newState.ThumbSticks.Left, thumbsticks.Right);
+ break;
+ case Buttons.RightThumbstickDown:
+ case Buttons.RightThumbstickLeft:
+ case Buttons.RightThumbstickRight:
+ case Buttons.RightThumbstickUp:
+ thumbsticks = new GamePadThumbSticks(newState.ThumbSticks.Right, thumbsticks.Left);
+ break;
+
+ // buttons
+ default:
+ var mask =
+ (buttons.A == ButtonState.Pressed ? Buttons.A : 0)
+ | (buttons.B == ButtonState.Pressed ? Buttons.B : 0)
+ | (buttons.Back == ButtonState.Pressed ? Buttons.Back : 0)
+ | (buttons.BigButton == ButtonState.Pressed ? Buttons.BigButton : 0)
+ | (buttons.LeftShoulder == ButtonState.Pressed ? Buttons.LeftShoulder : 0)
+ | (buttons.LeftStick == ButtonState.Pressed ? Buttons.LeftStick : 0)
+ | (buttons.RightShoulder == ButtonState.Pressed ? Buttons.RightShoulder : 0)
+ | (buttons.RightStick == ButtonState.Pressed ? Buttons.RightStick : 0)
+ | (buttons.Start == ButtonState.Pressed ? Buttons.Start : 0)
+ | (buttons.X == ButtonState.Pressed ? Buttons.X : 0)
+ | (buttons.Y == ButtonState.Pressed ? Buttons.Y : 0);
+ mask = mask ^ controllerButton;
+ buttons = new GamePadButtons(mask);
+ break;
+ }
+
+ Game1.oldPadState = new GamePadState(thumbsticks, triggers, buttons, dpad);
+ }
+ }
+ }
+}
+#endif
diff --git a/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs b/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs
index 51d64016..d6fc4594 100644
--- a/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs
+++ b/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs
@@ -1,4 +1,5 @@
-using System;
+#if !SMAPI_2_0
+using System;
namespace StardewModdingAPI.Events
{
@@ -23,3 +24,4 @@ namespace StardewModdingAPI.Events
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Events/EventArgsNewDay.cs b/src/StardewModdingAPI/Events/EventArgsNewDay.cs
index aba837e4..5bd2ba66 100644
--- a/src/StardewModdingAPI/Events/EventArgsNewDay.cs
+++ b/src/StardewModdingAPI/Events/EventArgsNewDay.cs
@@ -1,4 +1,5 @@
-using System;
+#if !SMAPI_2_0
+using System;
namespace StardewModdingAPI.Events
{
@@ -33,3 +34,4 @@ namespace StardewModdingAPI.Events
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Events/EventArgsStringChanged.cs b/src/StardewModdingAPI/Events/EventArgsStringChanged.cs
index 85b6fab5..1498cb71 100644
--- a/src/StardewModdingAPI/Events/EventArgsStringChanged.cs
+++ b/src/StardewModdingAPI/Events/EventArgsStringChanged.cs
@@ -1,4 +1,5 @@
-using System;
+#if !SMAPI_2_0
+using System;
namespace StardewModdingAPI.Events
{
@@ -27,3 +28,4 @@ namespace StardewModdingAPI.Events
}
}
}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Events/GameEvents.cs b/src/StardewModdingAPI/Events/GameEvents.cs
index 8e3cf662..557b451f 100644
--- a/src/StardewModdingAPI/Events/GameEvents.cs
+++ b/src/StardewModdingAPI/Events/GameEvents.cs
@@ -11,6 +11,7 @@ namespace StardewModdingAPI.Events
/*********
** Properties
*********/
+#if !SMAPI_2_0
/// <summary>Manages deprecation warnings.</summary>
private static DeprecationManager DeprecationManager;
@@ -29,6 +30,7 @@ namespace StardewModdingAPI.Events
/// <summary>The backing field for <see cref="FirstUpdateTick"/>.</summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
private static event EventHandler _FirstUpdateTick;
+#endif
/*********
@@ -40,13 +42,14 @@ namespace StardewModdingAPI.Events
/// <summary>Raised during launch after configuring Stardew Valley, loading it into memory, and opening the game window. The window is still blank by this point.</summary>
internal static event EventHandler GameLoadedInternal;
+#if !SMAPI_2_0
/// <summary>Raised during launch after configuring XNA or MonoGame. The game window hasn't been opened by this point. Called after <see cref="Microsoft.Xna.Framework.Game.Initialize"/>.</summary>
[Obsolete("The " + nameof(Mod) + "." + nameof(Mod.Entry) + " method is now called after the " + nameof(GameEvents.Initialize) + " event, so any contained logic can be done directly in " + nameof(Mod.Entry) + ".")]
public static event EventHandler Initialize
{
add
{
- GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.Initialize)}", "1.10", DeprecationLevel.Info);
+ GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.Initialize)}", "1.10", DeprecationLevel.PendingRemoval);
GameEvents._Initialize += value;
}
remove => GameEvents._Initialize -= value;
@@ -58,7 +61,7 @@ namespace StardewModdingAPI.Events
{
add
{
- GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.LoadContent)}", "1.10", DeprecationLevel.Info);
+ GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.LoadContent)}", "1.10", DeprecationLevel.PendingRemoval);
GameEvents._LoadContent += value;
}
remove => GameEvents._LoadContent -= value;
@@ -70,7 +73,7 @@ namespace StardewModdingAPI.Events
{
add
{
- GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoaded)}", "1.12", DeprecationLevel.Info);
+ GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoaded)}", "1.12", DeprecationLevel.PendingRemoval);
GameEvents._GameLoaded += value;
}
remove => GameEvents._GameLoaded -= value;
@@ -82,11 +85,12 @@ namespace StardewModdingAPI.Events
{
add
{
- GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", "1.12", DeprecationLevel.Info);
+ GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", "1.12", DeprecationLevel.PendingRemoval);
GameEvents._FirstUpdateTick += value;
}
remove => GameEvents._FirstUpdateTick -= value;
}
+#endif
/// <summary>Raised when the game updates its state (≈60 times per second).</summary>
public static event EventHandler UpdateTick;
@@ -113,42 +117,52 @@ namespace StardewModdingAPI.Events
/*********
** Internal methods
*********/
+#if !SMAPI_2_0
/// <summary>Injects types required for backwards compatibility.</summary>
/// <param name="deprecationManager">Manages deprecation warnings.</param>
internal static void Shim(DeprecationManager deprecationManager)
{
GameEvents.DeprecationManager = deprecationManager;
}
+#endif
- /// <summary>Raise an <see cref="Initialize"/> event.</summary>
- /// <param name="monitor">Encapsulates logging and monitoring.</param>
- internal static void InvokeInitialize(IMonitor monitor)
+ /// <summary>Raise an <see cref="InitializeInternal"/> event.</summary>
+ /// <param name="monitor">Encapsulates logging and monitoring.</param>
+ internal static void InvokeInitialize(IMonitor monitor)
{
monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.InitializeInternal)}", GameEvents.InitializeInternal?.GetInvocationList());
+#if !SMAPI_2_0
monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.Initialize)}", GameEvents._Initialize?.GetInvocationList());
+#endif
}
+#if !SMAPI_2_0
/// <summary>Raise a <see cref="LoadContent"/> event.</summary>
/// <param name="monitor">Encapsulates logging and monitoring.</param>
internal static void InvokeLoadContent(IMonitor monitor)
{
monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.LoadContent)}", GameEvents._LoadContent?.GetInvocationList());
}
+#endif
- /// <summary>Raise a <see cref="GameLoaded"/> event.</summary>
+ /// <summary>Raise a <see cref="GameLoadedInternal"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
internal static void InvokeGameLoaded(IMonitor monitor)
{
monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoadedInternal)}", GameEvents.GameLoadedInternal?.GetInvocationList());
+#if !SMAPI_2_0
monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoaded)}", GameEvents._GameLoaded?.GetInvocationList());
+#endif
}
+#if !SMAPI_2_0
/// <summary>Raise a <see cref="FirstUpdateTick"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
internal static void InvokeFirstUpdateTick(IMonitor monitor)
{
monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", GameEvents._FirstUpdateTick?.GetInvocationList());
}
+#endif
/// <summary>Raise an <see cref="UpdateTick"/> event.</summary>
/// <param name="monitor">Encapsulates logging and monitoring.</param>
diff --git a/src/StardewModdingAPI/Events/InputEvents.cs b/src/StardewModdingAPI/Events/InputEvents.cs
new file mode 100644
index 00000000..285487af
--- /dev/null
+++ b/src/StardewModdingAPI/Events/InputEvents.cs
@@ -0,0 +1,45 @@
+#if SMAPI_2_0
+using System;
+using StardewModdingAPI.Framework;
+using StardewModdingAPI.Utilities;
+
+namespace StardewModdingAPI.Events
+{
+ /// <summary>Events raised when the player uses a controller, keyboard, or mouse button.</summary>
+ public static class InputEvents
+ {
+ /*********
+ ** Events
+ *********/
+ /// <summary>Raised when the player presses a button on the keyboard, controller, or mouse.</summary>
+ public static event EventHandler<EventArgsInput> ButtonPressed;
+
+ /// <summary>Raised when the player releases a keyboard key on the keyboard, controller, or mouse.</summary>
+ public static event EventHandler<EventArgsInput> ButtonReleased;
+
+
+ /*********
+ ** Internal methods
+ *********/
+ /// <summary>Raise a <see cref="ButtonPressed"/> event.</summary>
+ /// <param name="monitor">Encapsulates monitoring and logging.</param>
+ /// <param name="button">The button on the controller, keyboard, or mouse.</param>
+ /// <param name="cursor">The cursor position.</param>
+ /// <param name="isClick">Whether the input is considered a 'click' by the game for enabling action.</param>
+ internal static void InvokeButtonPressed(IMonitor monitor, SButton button, ICursorPosition cursor, bool isClick)
+ {
+ monitor.SafelyRaiseGenericEvent($"{nameof(InputEvents)}.{nameof(InputEvents.ButtonPressed)}", InputEvents.ButtonPressed?.GetInvocationList(), null, new EventArgsInput(button, cursor, isClick));
+ }
+
+ /// <summary>Raise a <see cref="ButtonReleased"/> event.</summary>
+ /// <param name="monitor">Encapsulates monitoring and logging.</param>
+ /// <param name="button">The button on the controller, keyboard, or mouse.</param>
+ /// <param name="cursor">The cursor position.</param>
+ /// <param name="isClick">Whether the input is considered a 'click' by the game for enabling action.</param>
+ internal static void InvokeButtonReleased(IMonitor monitor, SButton button, ICursorPosition cursor, bool isClick)
+ {
+ monitor.SafelyRaiseGenericEvent($"{nameof(InputEvents)}.{nameof(InputEvents.ButtonReleased)}", InputEvents.ButtonReleased?.GetInvocationList(), null, new EventArgsInput(button, cursor, isClick));
+ }
+ }
+}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Events/PlayerEvents.cs b/src/StardewModdingAPI/Events/PlayerEvents.cs
index 37649fee..acbdc562 100644
--- a/src/StardewModdingAPI/Events/PlayerEvents.cs
+++ b/src/StardewModdingAPI/Events/PlayerEvents.cs
@@ -15,6 +15,7 @@ namespace StardewModdingAPI.Events
/*********
** Properties
*********/
+#if !SMAPI_2_0
/// <summary>Manages deprecation warnings.</summary>
private static DeprecationManager DeprecationManager;
@@ -25,18 +26,20 @@ namespace StardewModdingAPI.Events
/// <summary>The backing field for <see cref="FarmerChanged"/>.</summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
private static event EventHandler<EventArgsFarmerChanged> _FarmerChanged;
+#endif
/*********
** Events
*********/
+#if !SMAPI_2_0
/// <summary>Raised after the player loads a saved game.</summary>
[Obsolete("Use " + nameof(SaveEvents) + "." + nameof(SaveEvents.AfterLoad) + " instead")]
public static event EventHandler<EventArgsLoadedGameChanged> LoadedGame
{
add
{
- PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}", "1.6", DeprecationLevel.Info);
+ PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}", "1.6", DeprecationLevel.PendingRemoval);
PlayerEvents._LoadedGame += value;
}
remove => PlayerEvents._LoadedGame -= value;
@@ -48,11 +51,12 @@ namespace StardewModdingAPI.Events
{
add
{
- PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", "1.6", DeprecationLevel.Info);
+ PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", "1.6", DeprecationLevel.PendingRemoval);
PlayerEvents._FarmerChanged += value;
}
remove => PlayerEvents._FarmerChanged -= value;
}
+#endif
/// <summary>Raised after the player's inventory changes in any way (added or removed item, sorted, etc).</summary>
public static event EventHandler<EventArgsInventoryChanged> InventoryChanged;
@@ -64,6 +68,7 @@ namespace StardewModdingAPI.Events
/*********
** Internal methods
*********/
+#if !SMAPI_2_0
/// <summary>Injects types required for backwards compatibility.</summary>
/// <param name="deprecationManager">Manages deprecation warnings.</param>
internal static void Shim(DeprecationManager deprecationManager)
@@ -87,6 +92,7 @@ namespace StardewModdingAPI.Events
{
monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", PlayerEvents._FarmerChanged?.GetInvocationList(), null, new EventArgsFarmerChanged(priorFarmer, newFarmer));
}
+#endif
/// <summary>Raise an <see cref="InventoryChanged"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
diff --git a/src/StardewModdingAPI/Events/TimeEvents.cs b/src/StardewModdingAPI/Events/TimeEvents.cs
index 5dadf567..f0fdb4f2 100644
--- a/src/StardewModdingAPI/Events/TimeEvents.cs
+++ b/src/StardewModdingAPI/Events/TimeEvents.cs
@@ -11,6 +11,7 @@ namespace StardewModdingAPI.Events
/*********
** Properties
*********/
+#if !SMAPI_2_0
/// <summary>Manages deprecation warnings.</summary>
private static DeprecationManager DeprecationManager;
@@ -29,6 +30,8 @@ namespace StardewModdingAPI.Events
/// <summary>The backing field for <see cref="YearOfGameChanged"/>.</summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
private static event EventHandler<EventArgsIntChanged> _YearOfGameChanged;
+#endif
+
/*********
** Events
@@ -39,13 +42,14 @@ namespace StardewModdingAPI.Events
/// <summary>Raised after the in-game clock changes.</summary>
public static event EventHandler<EventArgsIntChanged> TimeOfDayChanged;
+#if !SMAPI_2_0
/// <summary>Raised after the day-of-month value changes, including when loading a save. This may happen before save; in most cases you should use <see cref="AfterDayStarted"/> instead.</summary>
[Obsolete("Use " + nameof(TimeEvents) + "." + nameof(TimeEvents.AfterDayStarted) + " or " + nameof(SaveEvents) + " instead")]
public static event EventHandler<EventArgsIntChanged> DayOfMonthChanged
{
add
{
- TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.DayOfMonthChanged)}", "1.14", DeprecationLevel.Info);
+ TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.DayOfMonthChanged)}", "1.14", DeprecationLevel.PendingRemoval);
TimeEvents._DayOfMonthChanged += value;
}
remove => TimeEvents._DayOfMonthChanged -= value;
@@ -57,7 +61,7 @@ namespace StardewModdingAPI.Events
{
add
{
- TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.YearOfGameChanged)}", "1.14", DeprecationLevel.Info);
+ TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.YearOfGameChanged)}", "1.14", DeprecationLevel.PendingRemoval);
TimeEvents._YearOfGameChanged += value;
}
remove => TimeEvents._YearOfGameChanged -= value;
@@ -69,7 +73,7 @@ namespace StardewModdingAPI.Events
{
add
{
- TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.SeasonOfYearChanged)}", "1.14", DeprecationLevel.Info);
+ TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.SeasonOfYearChanged)}", "1.14", DeprecationLevel.PendingRemoval);
TimeEvents._SeasonOfYearChanged += value;
}
remove => TimeEvents._SeasonOfYearChanged -= value;
@@ -81,22 +85,25 @@ namespace StardewModdingAPI.Events
{
add
{
- TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", "1.6", DeprecationLevel.Info);
+ TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", "1.6", DeprecationLevel.PendingRemoval);
TimeEvents._OnNewDay += value;
}
remove => TimeEvents._OnNewDay -= value;
}
+#endif
/*********
** Internal methods
*********/
+#if !SMAPI_2_0
/// <summary>Injects types required for backwards compatibility.</summary>
/// <param name="deprecationManager">Manages deprecation warnings.</param>
internal static void Shim(DeprecationManager deprecationManager)
{
TimeEvents.DeprecationManager = deprecationManager;
}
+#endif
/// <summary>Raise an <see cref="AfterDayStarted"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
@@ -105,7 +112,7 @@ namespace StardewModdingAPI.Events
monitor.SafelyRaisePlainEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.AfterDayStarted)}", TimeEvents.AfterDayStarted?.GetInvocationList(), null, EventArgs.Empty);
}
- /// <summary>Raise a <see cref="InvokeDayOfMonthChanged"/> event.</summary>
+ /// <summary>Raise a <see cref="TimeOfDayChanged"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="priorTime">The previous time in military time format (e.g. 6:00pm is 1800).</param>
/// <param name="newTime">The current time in military time format (e.g. 6:10pm is 1810).</param>
@@ -114,6 +121,7 @@ namespace StardewModdingAPI.Events
monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.TimeOfDayChanged)}", TimeEvents.TimeOfDayChanged?.GetInvocationList(), null, new EventArgsIntChanged(priorTime, newTime));
}
+#if !SMAPI_2_0
/// <summary>Raise a <see cref="DayOfMonthChanged"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="priorDay">The previous day value.</param>
@@ -150,5 +158,6 @@ namespace StardewModdingAPI.Events
{
monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", TimeEvents._OnNewDay?.GetInvocationList(), null, new EventArgsNewDay(priorDay, newDay, isTransitioning));
}
+#endif
}
}
diff --git a/src/StardewModdingAPI/Framework/Content/AssetData.cs b/src/StardewModdingAPI/Framework/Content/AssetData.cs
new file mode 100644
index 00000000..1ab9eebd
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/Content/AssetData.cs
@@ -0,0 +1,44 @@
+using System;
+
+namespace StardewModdingAPI.Framework.Content
+{
+ /// <summary>Base implementation for a content helper which encapsulates access and changes to content being read from a data file.</summary>
+ /// <typeparam name="TValue">The interface value type.</typeparam>
+ internal class AssetData<TValue> : AssetInfo, IAssetData<TValue>
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The content data being read.</summary>
+ public TValue Data { get; protected set; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="locale">The content's locale code, if the content is localised.</param>
+ /// <param name="assetName">The normalised asset name being read.</param>
+ /// <param name="data">The content data being read.</param>
+ /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
+ public AssetData(string locale, string assetName, TValue data, Func<string, string> getNormalisedPath)
+ : base(locale, assetName, data.GetType(), getNormalisedPath)
+ {
+ this.Data = data;
+ }
+
+ /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary>
+ /// <param name="value">The new content value.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception>
+ /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception>
+ public void ReplaceWith(TValue value)
+ {
+ if (value == null)
+ throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value.");
+ if (!this.DataType.IsInstanceOfType(value))
+ throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.DataType)} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors.");
+
+ this.Data = value;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs
index 26f059e4..e9b29b12 100644
--- a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs
+++ b/src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs
@@ -5,7 +5,7 @@ using System.Linq;
namespace StardewModdingAPI.Framework.Content
{
/// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary>
- internal class ContentEventHelperForDictionary<TKey, TValue> : ContentEventData<IDictionary<TKey, TValue>>, IContentEventHelperForDictionary<TKey, TValue>
+ internal class AssetDataForDictionary<TKey, TValue> : AssetData<IDictionary<TKey, TValue>>, IAssetDataForDictionary<TKey, TValue>
{
/*********
** Public methods
@@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content
/// <param name="assetName">The normalised asset name being read.</param>
/// <param name="data">The content data being read.</param>
/// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
- public ContentEventHelperForDictionary(string locale, string assetName, IDictionary<TKey, TValue> data, Func<string, string> getNormalisedPath)
+ public AssetDataForDictionary(string locale, string assetName, IDictionary<TKey, TValue> data, Func<string, string> getNormalisedPath)
: base(locale, assetName, data, getNormalisedPath) { }
/// <summary>Add or replace an entry in the dictionary.</summary>
diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs
index da30590b..45c5588b 100644
--- a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs
+++ b/src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs
@@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics;
namespace StardewModdingAPI.Framework.Content
{
/// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary>
- internal class ContentEventHelperForImage : ContentEventData<Texture2D>, IContentEventHelperForImage
+ internal class AssetDataForImage : AssetData<Texture2D>, IAssetDataForImage
{
/*********
** Public methods
@@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content
/// <param name="assetName">The normalised asset name being read.</param>
/// <param name="data">The content data being read.</param>
/// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
- public ContentEventHelperForImage(string locale, string assetName, Texture2D data, Func<string, string> getNormalisedPath)
+ public AssetDataForImage(string locale, string assetName, Texture2D data, Func<string, string> getNormalisedPath)
: base(locale, assetName, data, getNormalisedPath) { }
/// <summary>Overwrite part of the image.</summary>
diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs
index 9bf1ea17..f30003e4 100644
--- a/src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs
+++ b/src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs
@@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics;
namespace StardewModdingAPI.Framework.Content
{
/// <summary>Encapsulates access and changes to content being read from a data file.</summary>
- internal class ContentEventHelper : ContentEventData<object>, IContentEventHelper
+ internal class AssetDataForObject : AssetData<object>, IAssetData
{
/*********
** Public methods
@@ -15,23 +15,30 @@ namespace StardewModdingAPI.Framework.Content
/// <param name="assetName">The normalised asset name being read.</param>
/// <param name="data">The content data being read.</param>
/// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
- public ContentEventHelper(string locale, string assetName, object data, Func<string, string> getNormalisedPath)
+ public AssetDataForObject(string locale, string assetName, object data, Func<string, string> getNormalisedPath)
: base(locale, assetName, data, getNormalisedPath) { }
+ /// <summary>Construct an instance.</summary>
+ /// <param name="info">The asset metadata.</param>
+ /// <param name="data">The content data being read.</param>
+ /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
+ public AssetDataForObject(IAssetInfo info, object data, Func<string, string> getNormalisedPath)
+ : this(info.Locale, info.AssetName, data, getNormalisedPath) { }
+
/// <summary>Get a helper to manipulate the data as a dictionary.</summary>
/// <typeparam name="TKey">The expected dictionary key.</typeparam>
/// <typeparam name="TValue">The expected dictionary balue.</typeparam>
/// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception>
- public IContentEventHelperForDictionary<TKey, TValue> AsDictionary<TKey, TValue>()
+ public IAssetDataForDictionary<TKey, TValue> AsDictionary<TKey, TValue>()
{
- return new ContentEventHelperForDictionary<TKey, TValue>(this.Locale, this.AssetName, this.GetData<IDictionary<TKey, TValue>>(), this.GetNormalisedPath);
+ return new AssetDataForDictionary<TKey, TValue>(this.Locale, this.AssetName, this.GetData<IDictionary<TKey, TValue>>(), this.GetNormalisedPath);
}
/// <summary>Get a helper to manipulate the data as an image.</summary>
/// <exception cref="InvalidOperationException">The content being read isn't an image.</exception>
- public IContentEventHelperForImage AsImage()
+ public IAssetDataForImage AsImage()
{
- return new ContentEventHelperForImage(this.Locale, this.AssetName, this.GetData<Texture2D>(), this.GetNormalisedPath);
+ return new AssetDataForImage(this.Locale, this.AssetName, this.GetData<Texture2D>(), this.GetNormalisedPath);
}
/// <summary>Get the data as a given type.</summary>
diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventData.cs b/src/StardewModdingAPI/Framework/Content/AssetInfo.cs
index 1a1779d4..d580dc06 100644
--- a/src/StardewModdingAPI/Framework/Content/ContentEventData.cs
+++ b/src/StardewModdingAPI/Framework/Content/AssetInfo.cs
@@ -4,9 +4,7 @@ using Microsoft.Xna.Framework.Graphics;
namespace StardewModdingAPI.Framework.Content
{
- /// <summary>Base implementation for a content helper which encapsulates access and changes to content being read from a data file.</summary>
- /// <typeparam name="TValue">The interface value type.</typeparam>
- internal class ContentEventData<TValue> : EventArgs, IContentEventData<TValue>
+ internal class AssetInfo : IAssetInfo
{
/*********
** Properties
@@ -21,12 +19,9 @@ namespace StardewModdingAPI.Framework.Content
/// <summary>The content's locale code, if the content is localised.</summary>
public string Locale { get; }
- /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="IsAssetName"/> to compare with a known path.</summary>
+ /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="AssetNameEquals"/> to compare with a known path.</summary>
public string AssetName { get; }
- /// <summary>The content data being read.</summary>
- public TValue Data { get; protected set; }
-
/// <summary>The content data type.</summary>
public Type DataType { get; }
@@ -37,48 +32,24 @@ namespace StardewModdingAPI.Framework.Content
/// <summary>Construct an instance.</summary>
/// <param name="locale">The content's locale code, if the content is localised.</param>
/// <param name="assetName">The normalised asset name being read.</param>
- /// <param name="data">The content data being read.</param>
- /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
- public ContentEventData(string locale, string assetName, TValue data, Func<string, string> getNormalisedPath)
- : this(locale, assetName, data, data.GetType(), getNormalisedPath) { }
-
- /// <summary>Construct an instance.</summary>
- /// <param name="locale">The content's locale code, if the content is localised.</param>
- /// <param name="assetName">The normalised asset name being read.</param>
- /// <param name="data">The content data being read.</param>
- /// <param name="dataType">The content data type being read.</param>
+ /// <param name="type">The content type being read.</param>
/// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param>
- public ContentEventData(string locale, string assetName, TValue data, Type dataType, Func<string, string> getNormalisedPath)
+ public AssetInfo(string locale, string assetName, Type type, Func<string, string> getNormalisedPath)
{
this.Locale = locale;
this.AssetName = assetName;
- this.Data = data;
- this.DataType = dataType;
+ this.DataType = type;
this.GetNormalisedPath = getNormalisedPath;
}
/// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary>
/// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param>
- public bool IsAssetName(string path)
+ public bool AssetNameEquals(string path)
{
path = this.GetNormalisedPath(path);
return this.AssetName.Equals(path, StringComparison.InvariantCultureIgnoreCase);
}
- /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary>
- /// <param name="value">The new content value.</param>
- /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception>
- /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception>
- public void ReplaceWith(TValue value)
- {
- if (value == null)
- throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value.");
- if (!this.DataType.IsInstanceOfType(value))
- throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.DataType)} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors.");
-
- this.Data = value;
- }
-
/*********
** Protected methods
diff --git a/src/StardewModdingAPI/Framework/CursorPosition.cs b/src/StardewModdingAPI/Framework/CursorPosition.cs
new file mode 100644
index 00000000..4f256da5
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/CursorPosition.cs
@@ -0,0 +1,37 @@
+#if SMAPI_2_0
+using Microsoft.Xna.Framework;
+
+namespace StardewModdingAPI.Framework
+{
+ /// <summary>Defines a position on a given map at different reference points.</summary>
+ internal class CursorPosition : ICursorPosition
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The pixel position relative to the top-left corner of the visible screen.</summary>
+ public Vector2 ScreenPixels { get; }
+
+ /// <summary>The tile position under the cursor relative to the top-left corner of the map.</summary>
+ public Vector2 Tile { get; }
+
+ /// <summary>The tile position that the game considers under the cursor for purposes of clicking actions. This may be different than <see cref="Tile"/> if that's too far from the player.</summary>
+ public Vector2 GrabTile { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="screenPixels">The pixel position relative to the top-left corner of the visible screen.</param>
+ /// <param name="tile">The tile position relative to the top-left corner of the map.</param>
+ /// <param name="grabTile">The tile position that the game considers under the cursor for purposes of clicking actions.</param>
+ public CursorPosition(Vector2 screenPixels, Vector2 tile, Vector2 grabTile)
+ {
+ this.ScreenPixels = screenPixels;
+ this.Tile = tile;
+ this.GrabTile = grabTile;
+ }
+ }
+}
+#endif
diff --git a/src/StardewModdingAPI/Framework/DeprecationManager.cs b/src/StardewModdingAPI/Framework/DeprecationManager.cs
index 6b95960b..153d8829 100644
--- a/src/StardewModdingAPI/Framework/DeprecationManager.cs
+++ b/src/StardewModdingAPI/Framework/DeprecationManager.cs
@@ -52,13 +52,12 @@ namespace StardewModdingAPI.Framework
if (!this.MarkWarned(source ?? "<unknown>", nounPhrase, version))
return;
+ // show SMAPI 2.0 meta-warning
+ if(this.MarkWarned("SMAPI", "SMAPI 2.0 meta-warning", "2.0"))
+ this.Monitor.Log("Some mods may stop working in SMAPI 2.0 (but they'll work fine for now). Try updating mods with 'deprecated code' warnings; if that doesn't remove the warnings, let the mod authors know about this message or see http://community.playstarbound.com/threads/135000 for details.", LogLevel.Warn);
+
// build message
- string message = source != null
- ? $"{source} used {nounPhrase}, which is deprecated since SMAPI {version}."
- : $"An unknown mod used {nounPhrase}, which is deprecated since SMAPI {version}.";
- message += severity != DeprecationLevel.PendingRemoval
- ? " This will break in a future version of SMAPI."
- : " It will be removed soon, so the mod will break if it's not updated.";
+ string message = $"{source ?? "An unknown mod"} uses deprecated code ({nounPhrase}).";
if (source == null)
message += $"{Environment.NewLine}{Environment.StackTrace}";
@@ -70,7 +69,7 @@ namespace StardewModdingAPI.Framework
break;
case DeprecationLevel.Info:
- this.Monitor.Log(message, LogLevel.Warn);
+ this.Monitor.Log(message, LogLevel.Debug);
break;
case DeprecationLevel.PendingRemoval:
diff --git a/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs b/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs
new file mode 100644
index 00000000..f7133ee7
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs
@@ -0,0 +1,17 @@
+using System;
+
+namespace StardewModdingAPI.Framework.Exceptions
+{
+ /// <summary>A format exception which provides a user-facing error message.</summary>
+ internal class SParseException : FormatException
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="message">The error message.</param>
+ /// <param name="ex">The underlying exception, if any.</param>
+ public SParseException(string message, Exception ex = null)
+ : base(message, ex) { }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs
index b99d3798..2842bc83 100644
--- a/src/StardewModdingAPI/Framework/InternalExtensions.cs
+++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Xna.Framework.Graphics;
+using StardewModdingAPI.Framework.Reflection;
using StardewValley;
namespace StardewModdingAPI.Framework
@@ -99,7 +100,7 @@ namespace StardewModdingAPI.Framework
/// <summary>Get whether the sprite batch is between a begin and end pair.</summary>
/// <param name="spriteBatch">The sprite batch to check.</param>
/// <param name="reflection">The reflection helper with which to access private fields.</param>
- public static bool IsOpen(this SpriteBatch spriteBatch, IReflectionHelper reflection)
+ public static bool IsOpen(this SpriteBatch spriteBatch, Reflector reflection)
{
// get field name
const string fieldName =
@@ -110,7 +111,7 @@ namespace StardewModdingAPI.Framework
#endif
// get result
- return reflection.GetPrivateValue<bool>(Game1.spriteBatch, fieldName);
+ return reflection.GetPrivateField<bool>(Game1.spriteBatch, fieldName).GetValue();
}
}
}
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs
new file mode 100644
index 00000000..16032da1
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs
@@ -0,0 +1,23 @@
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>The common base class for mod helpers.</summary>
+ internal abstract class BaseHelper : IModLinked
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The unique ID of the mod for which the helper was created.</summary>
+ public string ModID { get; }
+
+
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
+ protected BaseHelper(string modID)
+ {
+ this.ModID = modID;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/CommandHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs
index 86734fc5..bdedb07c 100644
--- a/src/StardewModdingAPI/Framework/CommandHelper.cs
+++ b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs
@@ -1,9 +1,9 @@
using System;
-namespace StardewModdingAPI.Framework
+namespace StardewModdingAPI.Framework.ModHelpers
{
/// <summary>Provides an API for managing console commands.</summary>
- internal class CommandHelper : ICommandHelper
+ internal class CommandHelper : BaseHelper, ICommandHelper
{
/*********
** Accessors
@@ -15,14 +15,15 @@ namespace StardewModdingAPI.Framework
private readonly CommandManager CommandManager;
-
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
/// <param name="modName">The friendly mod name for this instance.</param>
/// <param name="commandManager">Manages console commands.</param>
- public CommandHelper(string modName, CommandManager commandManager)
+ public CommandHelper(string modID, string modName, CommandManager commandManager)
+ : base(modID)
{
this.ModName = modName;
this.CommandManager = commandManager;
diff --git a/src/StardewModdingAPI/Framework/ContentHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs
index 7fd5e803..5f72176e 100644
--- a/src/StardewModdingAPI/Framework/ContentHelper.cs
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
@@ -11,10 +13,10 @@ using xTile;
using xTile.Format;
using xTile.Tiles;
-namespace StardewModdingAPI.Framework
+namespace StardewModdingAPI.Framework.ModHelpers
{
/// <summary>Provides an API for loading content assets.</summary>
- internal class ContentHelper : IContentHelper
+ internal class ContentHelper : BaseHelper, IContentHelper
{
/*********
** Properties
@@ -33,13 +35,31 @@ namespace StardewModdingAPI.Framework
/*********
+ ** Accessors
+ *********/
+ /// <summary>The observable implementation of <see cref="AssetEditors"/>.</summary>
+ internal ObservableCollection<IAssetEditor> ObservableAssetEditors { get; } = new ObservableCollection<IAssetEditor>();
+
+ /// <summary>The observable implementation of <see cref="AssetLoaders"/>.</summary>
+ internal ObservableCollection<IAssetLoader> ObservableAssetLoaders { get; } = new ObservableCollection<IAssetLoader>();
+
+ /// <summary>Interceptors which provide the initial versions of matching content assets.</summary>
+ internal IList<IAssetLoader> AssetLoaders => this.ObservableAssetLoaders;
+
+ /// <summary>Interceptors which edit matching content assets after they're loaded.</summary>
+ internal IList<IAssetEditor> AssetEditors => this.ObservableAssetEditors;
+
+
+ /*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="contentManager">SMAPI's underlying content manager.</param>
/// <param name="modFolderPath">The absolute path to the mod folder.</param>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
/// <param name="modName">The friendly mod name for use in errors.</param>
- public ContentHelper(SContentManager contentManager, string modFolderPath, string modName)
+ public ContentHelper(SContentManager contentManager, string modFolderPath, string modID, string modName)
+ : base(modID)
{
this.ContentManager = contentManager;
this.ModFolderPath = modFolderPath;
diff --git a/src/StardewModdingAPI/Framework/ModHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs
index 5a8ce459..665b9cf4 100644
--- a/src/StardewModdingAPI/Framework/ModHelper.cs
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs
@@ -2,10 +2,10 @@
using System.IO;
using StardewModdingAPI.Framework.Serialisation;
-namespace StardewModdingAPI.Framework
+namespace StardewModdingAPI.Framework.ModHelpers
{
/// <summary>Provides simplified APIs for writing mods.</summary>
- internal class ModHelper : IModHelper, IDisposable
+ internal class ModHelper : BaseHelper, IModHelper, IDisposable
{
/*********
** Properties
@@ -23,16 +23,16 @@ namespace StardewModdingAPI.Framework
/// <summary>An API for loading content assets.</summary>
public IContentHelper Content { get; }
- /// <summary>Simplifies access to private game code.</summary>
+ /// <summary>An API for accessing private game code.</summary>
public IReflectionHelper Reflection { get; }
- /// <summary>Metadata about loaded mods.</summary>
+ /// <summary>an API for fetching metadata about loaded mods.</summary>
public IModRegistry ModRegistry { get; }
/// <summary>An API for managing console commands.</summary>
public ICommandHelper ConsoleCommands { get; }
- /// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> &lt; <c>pt.json</c> &lt; <c>default.json</c>).</summary>
+ /// <summary>An API for reading translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> &lt; <c>pt.json</c> &lt; <c>default.json</c>).</summary>
public ITranslationHelper Translation { get; }
@@ -40,35 +40,33 @@ namespace StardewModdingAPI.Framework
** Public methods
*********/
/// <summary>Construct an instance.</summary>
- /// <param name="displayName">The mod's display name.</param>
+ /// <param name="modID">The mod's unique ID.</param>
/// <param name="modDirectory">The full path to the mod's folder.</param>
/// <param name="jsonHelper">Encapsulate SMAPI's JSON parsing.</param>
- /// <param name="modRegistry">Metadata about loaded mods.</param>
- /// <param name="commandManager">Manages console commands.</param>
- /// <param name="contentManager">The content manager which loads content assets.</param>
- /// <param name="reflection">Simplifies access to private game code.</param>
+ /// <param name="contentHelper">An API for loading content assets.</param>
+ /// <param name="commandHelper">An API for managing console commands.</param>
+ /// <param name="modRegistry">an API for fetching metadata about loaded mods.</param>
+ /// <param name="reflectionHelper">An API for accessing private game code.</param>
+ /// <param name="translationHelper">An API for reading translations stored in the mod's <c>i18n</c> folder.</param>
/// <exception cref="ArgumentNullException">An argument is null or empty.</exception>
/// <exception cref="InvalidOperationException">The <paramref name="modDirectory"/> path does not exist on disk.</exception>
- public ModHelper(string displayName, string modDirectory, JsonHelper jsonHelper, IModRegistry modRegistry, CommandManager commandManager, SContentManager contentManager, IReflectionHelper reflection)
+ public ModHelper(string modID, string modDirectory, JsonHelper jsonHelper, IContentHelper contentHelper, ICommandHelper commandHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, ITranslationHelper translationHelper)
+ : base(modID)
{
- // validate
+ // validate directory
if (string.IsNullOrWhiteSpace(modDirectory))
throw new ArgumentNullException(nameof(modDirectory));
- if (jsonHelper == null)
- throw new ArgumentNullException(nameof(jsonHelper));
- if (modRegistry == null)
- throw new ArgumentNullException(nameof(modRegistry));
if (!Directory.Exists(modDirectory))
throw new InvalidOperationException("The specified mod directory does not exist.");
// initialise
this.DirectoryPath = modDirectory;
- this.JsonHelper = jsonHelper;
- this.Content = new ContentHelper(contentManager, modDirectory, displayName);
- this.ModRegistry = modRegistry;
- this.ConsoleCommands = new CommandHelper(displayName, commandManager);
- this.Reflection = reflection;
- this.Translation = new TranslationHelper(displayName, contentManager.GetLocale(), contentManager.GetCurrentLanguage());
+ this.JsonHelper = jsonHelper ?? throw new ArgumentNullException(nameof(jsonHelper));
+ this.Content = contentHelper ?? throw new ArgumentNullException(nameof(contentHelper));
+ this.ModRegistry = modRegistry ?? throw new ArgumentNullException(nameof(modRegistry));
+ this.ConsoleCommands = commandHelper ?? throw new ArgumentNullException(nameof(commandHelper));
+ this.Reflection = reflectionHelper ?? throw new ArgumentNullException(nameof(reflectionHelper));
+ this.Translation = translationHelper ?? throw new ArgumentNullException(nameof(translationHelper));
}
/****
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs
new file mode 100644
index 00000000..9e824694
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs
@@ -0,0 +1,48 @@
+using System.Collections.Generic;
+
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>Provides metadata about installed mods.</summary>
+ internal class ModRegistryHelper : BaseHelper, IModRegistry
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The underlying mod registry.</summary>
+ private readonly ModRegistry Registry;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
+ /// <param name="registry">The underlying mod registry.</param>
+ public ModRegistryHelper(string modID, ModRegistry registry)
+ : base(modID)
+ {
+ this.Registry = registry;
+ }
+
+ /// <summary>Get metadata for all loaded mods.</summary>
+ public IEnumerable<IManifest> GetAll()
+ {
+ return this.Registry.GetAll();
+ }
+
+ /// <summary>Get metadata for a loaded mod.</summary>
+ /// <param name="uniqueID">The mod's unique ID.</param>
+ /// <returns>Returns the matching mod's metadata, or <c>null</c> if not found.</returns>
+ public IManifest Get(string uniqueID)
+ {
+ return this.Registry.Get(uniqueID);
+ }
+
+ /// <summary>Get whether a mod has been loaded.</summary>
+ /// <param name="uniqueID">The mod's unique ID.</param>
+ public bool IsLoaded(string uniqueID)
+ {
+ return this.Registry.IsLoaded(uniqueID);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs
new file mode 100644
index 00000000..9411a97a
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs
@@ -0,0 +1,160 @@
+using System;
+using StardewModdingAPI.Framework.Reflection;
+
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>Provides helper methods for accessing private game code.</summary>
+ /// <remarks>This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage).</remarks>
+ internal class ReflectionHelper : BaseHelper, IReflectionHelper
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The underlying reflection helper.</summary>
+ private readonly Reflector Reflector;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
+ /// <param name="reflector">The underlying reflection helper.</param>
+ public ReflectionHelper(string modID, Reflector reflector)
+ : base(modID)
+ {
+ this.Reflector = reflector;
+ }
+
+ /****
+ ** Fields
+ ****/
+ /// <summary>Get a private instance field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="obj">The object which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ /// <returns>Returns the field wrapper, or <c>null</c> if the field doesn't exist and <paramref name="required"/> is <c>false</c>.</returns>
+ public IPrivateField<TValue> GetPrivateField<TValue>(object obj, string name, bool required = true)
+ {
+ return this.Reflector.GetPrivateField<TValue>(obj, name, required);
+ }
+
+ /// <summary>Get a private static field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="type">The type which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateField<TValue> GetPrivateField<TValue>(Type type, string name, bool required = true)
+ {
+ return this.Reflector.GetPrivateField<TValue>(type, name, required);
+ }
+
+ /****
+ ** Properties
+ ****/
+ /// <summary>Get a private instance property.</summary>
+ /// <typeparam name="TValue">The property type.</typeparam>
+ /// <param name="obj">The object which has the property.</param>
+ /// <param name="name">The property name.</param>
+ /// <param name="required">Whether to throw an exception if the private property is not found.</param>
+ public IPrivateProperty<TValue> GetPrivateProperty<TValue>(object obj, string name, bool required = true)
+ {
+ return this.Reflector.GetPrivateProperty<TValue>(obj, name, required);
+ }
+
+ /// <summary>Get a private static property.</summary>
+ /// <typeparam name="TValue">The property type.</typeparam>
+ /// <param name="type">The type which has the property.</param>
+ /// <param name="name">The property name.</param>
+ /// <param name="required">Whether to throw an exception if the private property is not found.</param>
+ public IPrivateProperty<TValue> GetPrivateProperty<TValue>(Type type, string name, bool required = true)
+ {
+ return this.Reflector.GetPrivateProperty<TValue>(type, name, required);
+ }
+
+ /****
+ ** Field values
+ ** (shorthand since this is the most common case)
+ ****/
+ /// <summary>Get the value of a private instance field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="obj">The object which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns>
+ /// <remarks>
+ /// This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.
+ /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(object,string,bool)" /> instead.
+ /// </remarks>
+ public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true)
+ {
+ IPrivateField<TValue> field = this.GetPrivateField<TValue>(obj, name, required);
+ return field != null
+ ? field.GetValue()
+ : default(TValue);
+ }
+
+ /// <summary>Get the value of a private static field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="type">The type which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns>
+ /// <remarks>
+ /// This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.
+ /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(Type,string,bool)" /> instead.
+ /// </remarks>
+ public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true)
+ {
+ IPrivateField<TValue> field = this.GetPrivateField<TValue>(type, name, required);
+ return field != null
+ ? field.GetValue()
+ : default(TValue);
+ }
+
+ /****
+ ** Methods
+ ****/
+ /// <summary>Get a private instance method.</summary>
+ /// <param name="obj">The object which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(object obj, string name, bool required = true)
+ {
+ return this.Reflector.GetPrivateMethod(obj, name, required);
+ }
+
+ /// <summary>Get a private static method.</summary>
+ /// <param name="type">The type which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(Type type, string name, bool required = true)
+ {
+ return this.Reflector.GetPrivateMethod(type, name, required);
+ }
+
+ /****
+ ** Methods by signature
+ ****/
+ /// <summary>Get a private instance method.</summary>
+ /// <param name="obj">The object which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="argumentTypes">The argument types of the method signature to find.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(object obj, string name, Type[] argumentTypes, bool required = true)
+ {
+ return this.Reflector.GetPrivateMethod(obj, name, argumentTypes, required);
+ }
+
+ /// <summary>Get a private static method.</summary>
+ /// <param name="type">The type which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="argumentTypes">The argument types of the method signature to find.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(Type type, string name, Type[] argumentTypes, bool required = true)
+ {
+ return this.Reflector.GetPrivateMethod(type, name, argumentTypes, required);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/TranslationHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs
index fe387789..bbe3a81a 100644
--- a/src/StardewModdingAPI/Framework/TranslationHelper.cs
+++ b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs
@@ -3,10 +3,10 @@ using System.Collections.Generic;
using System.Linq;
using StardewValley;
-namespace StardewModdingAPI.Framework
+namespace StardewModdingAPI.Framework.ModHelpers
{
/// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> &lt; <c>pt.json</c> &lt; <c>default.json</c>).</summary>
- internal class TranslationHelper : ITranslationHelper
+ internal class TranslationHelper : BaseHelper, ITranslationHelper
{
/*********
** Properties
@@ -35,10 +35,12 @@ namespace StardewModdingAPI.Framework
** Public methods
*********/
/// <summary>Construct an instance.</summary>
+ /// <param name="modID">The unique ID of the relevant mod.</param>
/// <param name="modName">The name of the relevant mod for error messages.</param>
/// <param name="locale">The initial locale.</param>
/// <param name="languageCode">The game's current language code.</param>
- public TranslationHelper(string modName, string locale, LocalizedContentManager.LanguageCode languageCode)
+ public TranslationHelper(string modID, string modName, string locale, LocalizedContentManager.LanguageCode languageCode)
+ : base(modID)
{
// save data
this.ModName = modName;
diff --git a/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs
index 42bd7bfb..406d49e1 100644
--- a/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs
+++ b/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs
@@ -71,13 +71,15 @@ namespace StardewModdingAPI.Framework.ModLoading
}
// rewrite & load assemblies in leaf-to-root order
+ bool oneAssembly = assemblies.Length == 1;
Assembly lastAssembly = null;
foreach (AssemblyParseResult assembly in assemblies)
{
- bool changed = this.RewriteAssembly(assembly.Definition, assumeCompatible);
+ bool changed = this.RewriteAssembly(assembly.Definition, assumeCompatible, logPrefix: " ");
if (changed)
{
- this.Monitor.Log($"Loading {assembly.File.Name} (rewritten in memory)...", LogLevel.Trace);
+ if (!oneAssembly)
+ this.Monitor.Log($" Loading {assembly.File.Name}.dll (rewritten in memory)...", LogLevel.Trace);
using (MemoryStream outStream = new MemoryStream())
{
assembly.Definition.Write(outStream);
@@ -87,7 +89,8 @@ namespace StardewModdingAPI.Framework.ModLoading
}
else
{
- this.Monitor.Log($"Loading {assembly.File.Name}...", LogLevel.Trace);
+ if (!oneAssembly)
+ this.Monitor.Log($" Loading {assembly.File.Name}.dll...", LogLevel.Trace);
lastAssembly = Assembly.UnsafeLoadFrom(assembly.File.FullName);
}
}
@@ -161,12 +164,14 @@ namespace StardewModdingAPI.Framework.ModLoading
/// <summary>Rewrite the types referenced by an assembly.</summary>
/// <param name="assembly">The assembly to rewrite.</param>
/// <param name="assumeCompatible">Assume the mod is compatible, even if incompatible code is detected.</param>
+ /// <param name="logPrefix">A string to prefix to log messages.</param>
/// <returns>Returns whether the assembly was modified.</returns>
/// <exception cref="IncompatibleInstructionException">An incompatible CIL instruction was found while rewriting the assembly.</exception>
- private bool RewriteAssembly(AssemblyDefinition assembly, bool assumeCompatible)
+ private bool RewriteAssembly(AssemblyDefinition assembly, bool assumeCompatible, string logPrefix)
{
ModuleDefinition module = assembly.MainModule;
HashSet<string> loggedMessages = new HashSet<string>();
+ string filename = $"{assembly.Name.Name}.dll";
// swap assembly references if needed (e.g. XNA => MonoGame)
bool platformChanged = false;
@@ -175,7 +180,7 @@ namespace StardewModdingAPI.Framework.ModLoading
// remove old assembly reference
if (this.AssemblyMap.RemoveNames.Any(name => module.AssemblyReferences[i].Name == name))
{
- this.LogOnce(this.Monitor, loggedMessages, $"Rewriting {assembly.Name.Name} for OS...");
+ this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewriting {filename} for OS...");
platformChanged = true;
module.AssemblyReferences.RemoveAt(i);
i--;
@@ -205,15 +210,15 @@ namespace StardewModdingAPI.Framework.ModLoading
{
if (rewriter.Rewrite(module, method, this.AssemblyMap, platformChanged))
{
- this.LogOnce(this.Monitor, loggedMessages, $"Rewrote {assembly.Name.Name} to fix {rewriter.NounPhrase}...");
+ this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewrote {filename} to fix {rewriter.NounPhrase}...");
anyRewritten = true;
}
}
catch (IncompatibleInstructionException)
{
if (!assumeCompatible)
- throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}.");
- this.LogOnce(this.Monitor, loggedMessages, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn);
+ throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}.");
+ this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn);
}
}
@@ -227,15 +232,15 @@ namespace StardewModdingAPI.Framework.ModLoading
{
if (rewriter.Rewrite(module, cil, instruction, this.AssemblyMap, platformChanged))
{
- this.LogOnce(this.Monitor, loggedMessages, $"Rewrote {assembly.Name.Name} to fix {rewriter.NounPhrase}...");
+ this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewrote {filename} to fix {rewriter.NounPhrase}...");
anyRewritten = true;
}
}
catch (IncompatibleInstructionException)
{
if (!assumeCompatible)
- throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}.");
- this.LogOnce(this.Monitor, loggedMessages, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn);
+ throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}.");
+ this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn);
}
}
}
diff --git a/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs b/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs
index f5139ce5..38dddce7 100644
--- a/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs
+++ b/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using StardewModdingAPI.Framework.Exceptions;
using StardewModdingAPI.Framework.Models;
using StardewModdingAPI.Framework.Serialisation;
@@ -17,10 +18,13 @@ namespace StardewModdingAPI.Framework.ModLoading
/// <param name="rootPath">The root path to search for mods.</param>
/// <param name="jsonHelper">The JSON helper with which to read manifests.</param>
/// <param name="compatibilityRecords">Metadata about mods that SMAPI should assume is compatible or broken, regardless of whether it detects incompatible code.</param>
+ /// <param name="disabledMods">Metadata about mods that SMAPI should consider obsolete and not load.</param>
/// <returns>Returns the manifests by relative folder.</returns>
- public IEnumerable<IModMetadata> ReadManifests(string rootPath, JsonHelper jsonHelper, IEnumerable<ModCompatibility> compatibilityRecords)
+ public IEnumerable<IModMetadata> ReadManifests(string rootPath, JsonHelper jsonHelper, IEnumerable<ModCompatibility> compatibilityRecords, IEnumerable<DisabledMod> disabledMods)
{
compatibilityRecords = compatibilityRecords.ToArray();
+ disabledMods = disabledMods.ToArray();
+
foreach (DirectoryInfo modDir in this.GetModFolders(rootPath))
{
// read file
@@ -42,25 +46,38 @@ namespace StardewModdingAPI.Framework.ModLoading
else if (string.IsNullOrWhiteSpace(manifest.EntryDll))
error = "its manifest doesn't set an entry DLL.";
}
+ catch (SParseException ex)
+ {
+ error = $"parsing its manifest failed: {ex.Message}";
+ }
catch (Exception ex)
{
error = $"parsing its manifest failed:\n{ex.GetLogSummary()}";
}
- // get compatibility record
+ // validate metadata
ModCompatibility compatibility = null;
if (manifest != null)
{
+ // get unique key for lookups
string key = !string.IsNullOrWhiteSpace(manifest.UniqueID) ? manifest.UniqueID : manifest.EntryDll;
+
+ // check if mod should be disabled
+ DisabledMod disabledMod = disabledMods.FirstOrDefault(mod => mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase));
+ if (disabledMod != null)
+ error = $"it's obsolete: {disabledMod.ReasonPhrase}";
+
+ // get compatibility record
compatibility = (
from mod in compatibilityRecords
where
- mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase)
- && (mod.LowerSemanticVersion == null || !manifest.Version.IsOlderThan(mod.LowerSemanticVersion))
- && !manifest.Version.IsNewerThan(mod.UpperSemanticVersion)
+ mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase)
+ && (mod.LowerSemanticVersion == null || !manifest.Version.IsOlderThan(mod.LowerSemanticVersion))
+ && !manifest.Version.IsNewerThan(mod.UpperSemanticVersion)
select mod
).FirstOrDefault();
}
+
// build metadata
string displayName = !string.IsNullOrWhiteSpace(manifest?.Name)
? manifest.Name
@@ -92,7 +109,7 @@ namespace StardewModdingAPI.Framework.ModLoading
bool hasOfficialUrl = !string.IsNullOrWhiteSpace(mod.Compatibility.UpdateUrl);
bool hasUnofficialUrl = !string.IsNullOrWhiteSpace(mod.Compatibility.UnofficialUpdateUrl);
- string reasonPhrase = compatibility.ReasonPhrase ?? "it's not compatible with the latest version of the game";
+ string reasonPhrase = compatibility.ReasonPhrase ?? "it's not compatible with the latest version of the game or SMAPI";
string error = $"{reasonPhrase}. Please check for a version newer than {compatibility.UpperVersionLabel ?? compatibility.UpperVersion} here:";
if (hasOfficialUrl)
error += !hasUnofficialUrl ? $" {compatibility.UpdateUrl}" : $"{Environment.NewLine}- official mod: {compatibility.UpdateUrl}";
@@ -105,24 +122,36 @@ namespace StardewModdingAPI.Framework.ModLoading
}
// validate SMAPI version
- if (!string.IsNullOrWhiteSpace(mod.Manifest.MinimumApiVersion))
+ if (mod.Manifest.MinimumApiVersion?.IsNewerThan(apiVersion) == true)
{
- if (!SemanticVersion.TryParse(mod.Manifest.MinimumApiVersion, out ISemanticVersion minVersion))
- {
- mod.SetStatus(ModMetadataStatus.Failed, $"it has an invalid minimum SMAPI version '{mod.Manifest.MinimumApiVersion}'. This should be a semantic version number like {apiVersion}.");
- continue;
- }
- if (minVersion.IsNewerThan(apiVersion))
- {
- mod.SetStatus(ModMetadataStatus.Failed, $"it needs SMAPI {minVersion} or later. Please update SMAPI to the latest version to use this mod.");
- continue;
- }
+ mod.SetStatus(ModMetadataStatus.Failed, $"it needs SMAPI {mod.Manifest.MinimumApiVersion} or later. Please update SMAPI to the latest version to use this mod.");
+ continue;
}
// validate DLL path
string assemblyPath = Path.Combine(mod.DirectoryPath, mod.Manifest.EntryDll);
if (!File.Exists(assemblyPath))
+ {
mod.SetStatus(ModMetadataStatus.Failed, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist.");
+ continue;
+ }
+
+ // validate required fields
+#if SMAPI_2_0
+ {
+ List<string> missingFields = new List<string>(3);
+
+ if (string.IsNullOrWhiteSpace(mod.Manifest.Name))
+ missingFields.Add(nameof(IManifest.Name));
+ if (mod.Manifest.Version == null || mod.Manifest.Version.ToString() == "0.0")
+ missingFields.Add(nameof(IManifest.Version));
+ if (string.IsNullOrWhiteSpace(mod.Manifest.UniqueID))
+ missingFields.Add(nameof(IManifest.UniqueID));
+
+ if (missingFields.Any())
+ mod.SetStatus(ModMetadataStatus.Failed, $"its manifest is missing required fields ({string.Join(", ", missingFields)}).");
+ }
+#endif
}
}
@@ -193,20 +222,51 @@ namespace StardewModdingAPI.Framework.ModLoading
return states[mod] = ModDependencyStatus.Sorted;
}
+ // get dependencies
+ var dependencies =
+ (
+ from entry in mod.Manifest.Dependencies
+ let dependencyMod = mods.FirstOrDefault(m => string.Equals(m.Manifest?.UniqueID, entry.UniqueID, StringComparison.InvariantCultureIgnoreCase))
+ orderby entry.UniqueID
+ select new
+ {
+ ID = entry.UniqueID,
+ MinVersion = entry.MinimumVersion,
+ Mod = dependencyMod,
+ IsRequired =
+#if SMAPI_2_0
+ entry.IsRequired
+#else
+ true
+#endif
+ }
+ )
+ .ToArray();
+
// missing required dependencies, mark failed
{
- string[] missingModIDs =
+ string[] failedIDs = (from entry in dependencies where entry.IsRequired && entry.Mod == null select entry.ID).ToArray();
+ if (failedIDs.Any())
+ {
+ sortedMods.Push(mod);
+ mod.SetStatus(ModMetadataStatus.Failed, $"it requires mods which aren't installed ({string.Join(", ", failedIDs)}).");
+ return states[mod] = ModDependencyStatus.Failed;
+ }
+ }
+
+ // dependency min version not met, mark failed
+ {
+ string[] failedLabels =
(
- from dependency in mod.Manifest.Dependencies
- where mods.All(m => m.Manifest?.UniqueID != dependency.UniqueID)
- orderby dependency.UniqueID
- select dependency.UniqueID
+ from entry in dependencies
+ where entry.Mod != null && entry.MinVersion != null && entry.MinVersion.IsNewerThan(entry.Mod.Manifest.Version)
+ select $"{entry.Mod.DisplayName} (needs {entry.MinVersion} or later)"
)
.ToArray();
- if (missingModIDs.Any())
+ if (failedLabels.Any())
{
sortedMods.Push(mod);
- mod.SetStatus(ModMetadataStatus.Failed, $"it requires mods which aren't installed ({string.Join(", ", missingModIDs)}).");
+ mod.SetStatus(ModMetadataStatus.Failed, $"it needs newer versions of some mods: {string.Join(", ", failedLabels)}.");
return states[mod] = ModDependencyStatus.Failed;
}
}
@@ -215,20 +275,16 @@ namespace StardewModdingAPI.Framework.ModLoading
{
states[mod] = ModDependencyStatus.Checking;
- // get mods to load first
- IModMetadata[] modsToLoadFirst =
- (
- from other in mods
- where mod.Manifest.Dependencies.Any(required => required.UniqueID == other.Manifest?.UniqueID)
- select other
- )
- .ToArray();
-
// recursively sort dependencies
- foreach (IModMetadata requiredMod in modsToLoadFirst)
+ foreach (var dependency in dependencies)
{
+ IModMetadata requiredMod = dependency.Mod;
var subchain = new List<IModMetadata>(currentChain) { mod };
+ // ignore missing optional dependency
+ if (!dependency.IsRequired && requiredMod == null)
+ continue;
+
// detect dependency loop
if (states[requiredMod] == ModDependencyStatus.Checking)
{
diff --git a/src/StardewModdingAPI/Framework/ModRegistry.cs b/src/StardewModdingAPI/Framework/ModRegistry.cs
index f9d3cfbf..a427bdb7 100644
--- a/src/StardewModdingAPI/Framework/ModRegistry.cs
+++ b/src/StardewModdingAPI/Framework/ModRegistry.cs
@@ -7,7 +7,7 @@ using System.Reflection;
namespace StardewModdingAPI.Framework
{
/// <summary>Tracks the installed mods.</summary>
- internal class ModRegistry : IModRegistry
+ internal class ModRegistry
{
/*********
** Properties
@@ -23,7 +23,7 @@ namespace StardewModdingAPI.Framework
** Public methods
*********/
/****
- ** IModRegistry
+ ** Basic metadata
****/
/// <summary>Get metadata for all loaded mods.</summary>
public IEnumerable<IManifest> GetAll()
@@ -47,7 +47,7 @@ namespace StardewModdingAPI.Framework
}
/****
- ** Internal methods
+ ** Mod data
****/
/// <summary>Register a mod as a possible source of deprecation warnings.</summary>
/// <param name="metadata">The mod metadata.</param>
diff --git a/src/StardewModdingAPI/Framework/Models/DisabledMod.cs b/src/StardewModdingAPI/Framework/Models/DisabledMod.cs
new file mode 100644
index 00000000..170fa760
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/Models/DisabledMod.cs
@@ -0,0 +1,22 @@
+namespace StardewModdingAPI.Framework.Models
+{
+ /// <summary>Metadata about for a mod that should never be loaded.</summary>
+ internal class DisabledMod
+ {
+ /*********
+ ** Accessors
+ *********/
+ /****
+ ** From config
+ ****/
+ /// <summary>The unique mod IDs.</summary>
+ public string[] ID { get; set; }
+
+ /// <summary>The mod name.</summary>
+ public string Name { get; set; }
+
+ /// <summary>The reason phrase to show in the warning, or <c>null</c> to use the default value.</summary>
+ /// <example>"this mod is no longer supported or used"</example>
+ public string ReasonPhrase { get; set; }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/Models/Manifest.cs b/src/StardewModdingAPI/Framework/Models/Manifest.cs
index be781585..08b88025 100644
--- a/src/StardewModdingAPI/Framework/Models/Manifest.cs
+++ b/src/StardewModdingAPI/Framework/Models/Manifest.cs
@@ -25,7 +25,8 @@ namespace StardewModdingAPI.Framework.Models
public ISemanticVersion Version { get; set; }
/// <summary>The minimum SMAPI version required by this mod, if any.</summary>
- public string MinimumApiVersion { get; set; }
+ [JsonConverter(typeof(ManifestFieldConverter))]
+ public ISemanticVersion MinimumApiVersion { get; set; }
/// <summary>The name of the DLL in the directory that has the <see cref="Mod.Entry"/> method.</summary>
public string EntryDll { get; set; }
@@ -37,9 +38,11 @@ namespace StardewModdingAPI.Framework.Models
/// <summary>The unique mod ID.</summary>
public string UniqueID { get; set; }
+#if !SMAPI_2_0
/// <summary>Whether the mod uses per-save config files.</summary>
[Obsolete("Use " + nameof(Mod) + "." + nameof(Mod.Helper) + "." + nameof(IModHelper.ReadConfig) + " instead")]
public bool PerSaveConfigs { get; set; }
+#endif
/// <summary>Any manifest fields which didn't match a valid field.</summary>
[JsonExtensionData]
diff --git a/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs b/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs
index 2f580c1d..25d92a29 100644
--- a/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs
+++ b/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs
@@ -9,15 +9,34 @@
/// <summary>The unique mod ID to require.</summary>
public string UniqueID { get; set; }
+ /// <summary>The minimum required version (if any).</summary>
+ public ISemanticVersion MinimumVersion { get; set; }
+
+#if SMAPI_2_0
+ /// <summary>Whether the dependency must be installed to use the mod.</summary>
+ public bool IsRequired { get; set; }
+#endif
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="uniqueID">The unique mod ID to require.</param>
- public ManifestDependency(string uniqueID)
+ /// <param name="minimumVersion">The minimum required version (if any).</param>
+ /// <param name="required">Whether the dependency must be installed to use the mod.</param>
+ public ManifestDependency(string uniqueID, string minimumVersion
+#if SMAPI_2_0
+ , bool required = true
+#endif
+ )
{
this.UniqueID = uniqueID;
+ this.MinimumVersion = !string.IsNullOrWhiteSpace(minimumVersion)
+ ? new SemanticVersion(minimumVersion)
+ : null;
+#if SMAPI_2_0
+ this.IsRequired = required;
+#endif
}
}
}
diff --git a/src/StardewModdingAPI/Framework/Models/SConfig.cs b/src/StardewModdingAPI/Framework/Models/SConfig.cs
index c3f0816e..b2ca4113 100644
--- a/src/StardewModdingAPI/Framework/Models/SConfig.cs
+++ b/src/StardewModdingAPI/Framework/Models/SConfig.cs
@@ -17,5 +17,8 @@
/// <summary>A list of mod versions which should be considered compatible or incompatible regardless of whether SMAPI detects incompatible code.</summary>
public ModCompatibility[] ModCompatibility { get; set; }
+
+ /// <summary>A list of mods which should be considered obsolete and not loaded.</summary>
+ public DisabledMod[] DisabledMods { get; set; }
}
}
diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs
index 925efc33..6359b454 100644
--- a/src/StardewModdingAPI/Framework/Monitor.cs
+++ b/src/StardewModdingAPI/Framework/Monitor.cs
@@ -45,6 +45,11 @@ namespace StardewModdingAPI.Framework
/// <summary>Whether SMAPI is aborting. Mods don't need to worry about this unless they have background tasks.</summary>
public bool IsExiting => this.ExitTokenSource.IsCancellationRequested;
+#if SMAPI_2_0
+ /// <summary>Whether to show the full log stamps (with time/level/logger) in the console. If false, shows a simplified stamp with only the logger.</summary>
+ internal bool ShowFullStampInConsole { get; set; }
+#endif
+
/// <summary>Whether to show trace messages in the console.</summary>
internal bool ShowTraceInConsole { get; set; }
@@ -92,6 +97,18 @@ namespace StardewModdingAPI.Framework
this.ExitTokenSource.Cancel();
}
+#if SMAPI_2_0
+ /// <summary>Write a newline to the console and log file.</summary>
+ internal void Newline()
+ {
+ if (this.WriteToConsole)
+ this.ConsoleManager.ExclusiveWriteWithoutInterception(Console.WriteLine);
+ if (this.WriteToFile)
+ this.LogFile.WriteLine("");
+ }
+#endif
+
+#if !SMAPI_2_0
/// <summary>Log a message for the player or developer, using the specified console color.</summary>
/// <param name="source">The name of the mod logging the message.</param>
/// <param name="message">The message to log.</param>
@@ -102,6 +119,7 @@ namespace StardewModdingAPI.Framework
{
this.LogImpl(source, message, level, color);
}
+#endif
/*********
@@ -124,7 +142,13 @@ namespace StardewModdingAPI.Framework
{
// generate message
string levelStr = level.ToString().ToUpper().PadRight(Monitor.MaxLevelLength);
- message = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}";
+
+ string fullMessage = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}";
+#if SMAPI_2_0
+ string consoleMessage = this.ShowFullStampInConsole ? fullMessage : $"[{source}] {message}";
+#else
+ string consoleMessage = fullMessage;
+#endif
// write to console
if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace))
@@ -136,17 +160,17 @@ namespace StardewModdingAPI.Framework
if (background.HasValue)
Console.BackgroundColor = background.Value;
Console.ForegroundColor = color;
- Console.WriteLine(message);
+ Console.WriteLine(consoleMessage);
Console.ResetColor();
}
else
- Console.WriteLine(message);
+ Console.WriteLine(consoleMessage);
});
}
// write to log file
if (this.WriteToFile)
- this.LogFile.WriteLine(message);
+ this.LogFile.WriteLine(fullMessage);
}
}
}
diff --git a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/Reflection/Reflector.cs
index 7a5789dc..5c2d90fa 100644
--- a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs
+++ b/src/StardewModdingAPI/Framework/Reflection/Reflector.cs
@@ -7,13 +7,13 @@ namespace StardewModdingAPI.Framework.Reflection
{
/// <summary>Provides helper methods for accessing private game code.</summary>
/// <remarks>This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage).</remarks>
- internal class ReflectionHelper : IReflectionHelper
+ internal class Reflector
{
/*********
** Properties
*********/
/// <summary>The cached fields and methods found via reflection.</summary>
- private readonly MemoryCache Cache = new MemoryCache(typeof(ReflectionHelper).FullName);
+ private readonly MemoryCache Cache = new MemoryCache(typeof(Reflector).FullName);
/// <summary>The sliding cache expiration time.</summary>
private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5);
@@ -94,46 +94,6 @@ namespace StardewModdingAPI.Framework.Reflection
}
/****
- ** Field values
- ** (shorthand since this is the most common case)
- ****/
- /// <summary>Get the value of a private instance field.</summary>
- /// <typeparam name="TValue">The field type.</typeparam>
- /// <param name="obj">The object which has the field.</param>
- /// <param name="name">The field name.</param>
- /// <param name="required">Whether to throw an exception if the private field is not found.</param>
- /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns>
- /// <remarks>
- /// This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.
- /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(object,string,bool)" /> instead.
- /// </remarks>
- public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true)
- {
- IPrivateField<TValue> field = this.GetPrivateField<TValue>(obj, name, required);
- return field != null
- ? field.GetValue()
- : default(TValue);
- }
-
- /// <summary>Get the value of a private static field.</summary>
- /// <typeparam name="TValue">The field type.</typeparam>
- /// <param name="type">The type which has the field.</param>
- /// <param name="name">The field name.</param>
- /// <param name="required">Whether to throw an exception if the private field is not found.</param>
- /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns>
- /// <remarks>
- /// This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.
- /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(Type,string,bool)" /> instead.
- /// </remarks>
- public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true)
- {
- IPrivateField<TValue> field = this.GetPrivateField<TValue>(type, name, required);
- return field != null
- ? field.GetValue()
- : default(TValue);
- }
-
- /****
** Methods
****/
/// <summary>Get a private instance method.</summary>
diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs
index acd3e108..669b0e7a 100644
--- a/src/StardewModdingAPI/Framework/SContentManager.cs
+++ b/src/StardewModdingAPI/Framework/SContentManager.cs
@@ -3,14 +3,16 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
+using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI.AssemblyRewriters;
-using StardewModdingAPI.Events;
using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.Reflection;
using StardewValley;
+using StardewValley.BellsAndWhistles;
+using StardewValley.Objects;
+using StardewValley.Projectiles;
namespace StardewModdingAPI.Framework
{
@@ -42,6 +44,12 @@ namespace StardewModdingAPI.Framework
/*********
** Accessors
*********/
+ /// <summary>Interceptors which provide the initial versions of matching assets.</summary>
+ internal IDictionary<IModMetadata, IList<IAssetLoader>> Loaders { get; } = new Dictionary<IModMetadata, IList<IAssetLoader>>();
+
+ /// <summary>Interceptors which edit matching assets after they're loaded.</summary>
+ internal IDictionary<IModMetadata, IList<IAssetEditor>> Editors { get; } = new Dictionary<IModMetadata, IList<IAssetEditor>>();
+
/// <summary>The absolute path to the <see cref="ContentManager.RootDirectory"/>.</summary>
public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory);
@@ -52,22 +60,19 @@ namespace StardewModdingAPI.Framework
/// <summary>Construct an instance.</summary>
/// <param name="serviceProvider">The service provider to use to locate services.</param>
/// <param name="rootDirectory">The root directory to search for content.</param>
- /// <param name="monitor">Encapsulates monitoring and logging.</param>
- public SContentManager(IServiceProvider serviceProvider, string rootDirectory, IMonitor monitor)
- : this(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, null, monitor) { }
-
- /// <summary>Construct an instance.</summary>
- /// <param name="serviceProvider">The service provider to use to locate services.</param>
- /// <param name="rootDirectory">The root directory to search for content.</param>
/// <param name="currentCulture">The current culture for which to localise content.</param>
/// <param name="languageCodeOverride">The current language code for which to localise content.</param>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor)
: base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride)
{
+ // validate
+ if (monitor == null)
+ throw new ArgumentNullException(nameof(monitor));
+
// initialise
+ var reflection = new Reflector();
this.Monitor = monitor;
- IReflectionHelper reflection = new ReflectionHelper();
// get underlying fields for interception
this.Cache = reflection.GetPrivateField<Dictionary<string, object>>(this, "loadedAssets").GetValue();
@@ -117,22 +122,24 @@ namespace StardewModdingAPI.Framework
/// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param>
public override T Load<T>(string assetName)
{
- // get normalised metadata
assetName = this.NormaliseAssetName(assetName);
- string cacheLocale = this.GetCacheLocale(assetName);
// skip if already loaded
if (this.IsNormalisedKeyLoaded(assetName))
return base.Load<T>(assetName);
- // load data
- T data = base.Load<T>(assetName);
+ // load asset
+ T data;
+ {
+ IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, typeof(T), this.NormaliseAssetName);
+ IAssetData asset = this.ApplyLoader<T>(info) ?? new AssetDataForObject(info, base.Load<T>(assetName), this.NormaliseAssetName);
+ asset = this.ApplyEditors<T>(info, asset);
+ data = (T)asset.Data;
+ }
- // let mods intercept content
- IContentEventHelper helper = new ContentEventHelper(cacheLocale, assetName, data, this.NormaliseAssetName);
- ContentEvents.InvokeAfterAssetLoaded(this.Monitor, helper);
- this.Cache[assetName] = helper.Data;
- return (T)helper.Data;
+ // update cache & return data
+ this.Cache[assetName] = data;
+ return data;
}
/// <summary>Inject an asset into the cache.</summary>
@@ -142,6 +149,7 @@ namespace StardewModdingAPI.Framework
public void Inject<T>(string assetName, T value)
{
assetName = this.NormaliseAssetName(assetName);
+
this.Cache[assetName] = value;
}
@@ -151,6 +159,57 @@ namespace StardewModdingAPI.Framework
return this.GetKeyLocale.Invoke<string>();
}
+ /// <summary>Reset the asset cache and reload the game's static assets.</summary>
+ /// <remarks>This implementation is derived from <see cref="Game1.LoadContent"/>.</remarks>
+ public void Reset()
+ {
+ this.Monitor.Log("Resetting asset cache...", LogLevel.Trace);
+ this.Cache.Clear();
+
+ // from Game1.LoadContent
+ Game1.daybg = this.Load<Texture2D>("LooseSprites\\daybg");
+ Game1.nightbg = this.Load<Texture2D>("LooseSprites\\nightbg");
+ Game1.menuTexture = this.Load<Texture2D>("Maps\\MenuTiles");
+ Game1.lantern = this.Load<Texture2D>("LooseSprites\\Lighting\\lantern");
+ Game1.windowLight = this.Load<Texture2D>("LooseSprites\\Lighting\\windowLight");
+ Game1.sconceLight = this.Load<Texture2D>("LooseSprites\\Lighting\\sconceLight");
+ Game1.cauldronLight = this.Load<Texture2D>("LooseSprites\\Lighting\\greenLight");
+ Game1.indoorWindowLight = this.Load<Texture2D>("LooseSprites\\Lighting\\indoorWindowLight");
+ Game1.shadowTexture = this.Load<Texture2D>("LooseSprites\\shadow");
+ Game1.mouseCursors = this.Load<Texture2D>("LooseSprites\\Cursors");
+ Game1.controllerMaps = this.Load<Texture2D>("LooseSprites\\ControllerMaps");
+ Game1.animations = this.Load<Texture2D>("TileSheets\\animations");
+ Game1.achievements = this.Load<Dictionary<int, string>>("Data\\Achievements");
+ Game1.NPCGiftTastes = this.Load<Dictionary<string, string>>("Data\\NPCGiftTastes");
+ Game1.dialogueFont = this.Load<SpriteFont>("Fonts\\SpriteFont1");
+ Game1.smallFont = this.Load<SpriteFont>("Fonts\\SmallFont");
+ Game1.tinyFont = this.Load<SpriteFont>("Fonts\\tinyFont");
+ Game1.tinyFontBorder = this.Load<SpriteFont>("Fonts\\tinyFontBorder");
+ Game1.objectSpriteSheet = this.Load<Texture2D>("Maps\\springobjects");
+ Game1.cropSpriteSheet = this.Load<Texture2D>("TileSheets\\crops");
+ Game1.emoteSpriteSheet = this.Load<Texture2D>("TileSheets\\emotes");
+ Game1.debrisSpriteSheet = this.Load<Texture2D>("TileSheets\\debris");
+ Game1.bigCraftableSpriteSheet = this.Load<Texture2D>("TileSheets\\Craftables");
+ Game1.rainTexture = this.Load<Texture2D>("TileSheets\\rain");
+ Game1.buffsIcons = this.Load<Texture2D>("TileSheets\\BuffsIcons");
+ Game1.objectInformation = this.Load<Dictionary<int, string>>("Data\\ObjectInformation");
+ Game1.bigCraftablesInformation = this.Load<Dictionary<int, string>>("Data\\BigCraftablesInformation");
+ FarmerRenderer.hairStylesTexture = this.Load<Texture2D>("Characters\\Farmer\\hairstyles");
+ FarmerRenderer.shirtsTexture = this.Load<Texture2D>("Characters\\Farmer\\shirts");
+ FarmerRenderer.hatsTexture = this.Load<Texture2D>("Characters\\Farmer\\hats");
+ FarmerRenderer.accessoriesTexture = this.Load<Texture2D>("Characters\\Farmer\\accessories");
+ Furniture.furnitureTexture = this.Load<Texture2D>("TileSheets\\furniture");
+ SpriteText.spriteTexture = this.Load<Texture2D>("LooseSprites\\font_bold");
+ SpriteText.coloredTexture = this.Load<Texture2D>("LooseSprites\\font_colored");
+ Tool.weaponsTexture = this.Load<Texture2D>("TileSheets\\weapons");
+ Projectile.projectileSheet = this.Load<Texture2D>("TileSheets\\Projectiles");
+
+ // from Farmer constructor
+ if (Game1.player != null)
+ Game1.player.FarmerRenderer = new FarmerRenderer(this.Load<Texture2D>("Characters\\Farmer\\farmer_" + (Game1.player.isMale ? "" : "girl_") + "base"));
+ }
+
+
/*********
** Private methods
*********/
@@ -162,14 +221,151 @@ namespace StardewModdingAPI.Framework
|| this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke<string>()}"); // translated asset
}
- /// <summary>Get the locale for which the asset name was saved, if any.</summary>
- /// <param name="normalisedAssetName">The normalised asset name.</param>
- private string GetCacheLocale(string normalisedAssetName)
+ /// <summary>Load the initial asset from the registered <see cref="Loaders"/>.</summary>
+ /// <param name="info">The basic asset metadata.</param>
+ /// <returns>Returns the loaded asset metadata, or <c>null</c> if no loader matched.</returns>
+ private IAssetData ApplyLoader<T>(IAssetInfo info)
+ {
+ // find matching loaders
+ var loaders = this.GetInterceptors(this.Loaders)
+ .Where(entry =>
+ {
+ try
+ {
+ return entry.Value.CanLoad<T>(info);
+ }
+ catch (Exception ex)
+ {
+ this.Monitor.Log($"{entry.Key.DisplayName} crashed when checking whether it could load asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error);
+ return false;
+ }
+ })
+ .ToArray();
+
+ // validate loaders
+ if (!loaders.Any())
+ return null;
+ if (loaders.Length > 1)
+ {
+ string[] loaderNames = loaders.Select(p => p.Key.DisplayName).ToArray();
+ this.Monitor.Log($"Multiple mods want to provide the '{info.AssetName}' asset ({string.Join(", ", loaderNames)}), but an asset can't be loaded multiple times. SMAPI will use the default asset instead; uninstall one of the mods to fix this. (Message for modders: you should usually use {typeof(IAssetEditor)} instead to avoid conflicts.)", LogLevel.Warn);
+ return null;
+ }
+
+ // fetch asset from loader
+ IModMetadata mod = loaders[0].Key;
+ IAssetLoader loader = loaders[0].Value;
+ T data;
+ try
+ {
+ data = loader.Load<T>(info);
+ this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace);
+ }
+ catch (Exception ex)
+ {
+ this.Monitor.Log($"{mod.DisplayName} crashed when loading asset '{info.AssetName}'. SMAPI will use the default asset instead. Error details:\n{ex.GetLogSummary()}", LogLevel.Error);
+ return null;
+ }
+
+ // validate asset
+ if (data == null)
+ {
+ this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Error);
+ return null;
+ }
+
+ // return matched asset
+ return new AssetDataForObject(info, data, this.NormaliseAssetName);
+ }
+
+ /// <summary>Apply any <see cref="Editors"/> to a loaded asset.</summary>
+ /// <typeparam name="T">The asset type.</typeparam>
+ /// <param name="info">The basic asset metadata.</param>
+ /// <param name="asset">The loaded asset.</param>
+ private IAssetData ApplyEditors<T>(IAssetInfo info, IAssetData asset)
{
- string locale = this.GetKeyLocale.Invoke<string>();
- return this.Cache.ContainsKey($"{normalisedAssetName}.{locale}")
- ? locale
- : null;
+ IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.NormaliseAssetName);
+
+ // edit asset
+ foreach (var entry in this.GetInterceptors(this.Editors))
+ {
+ // check for match
+ IModMetadata mod = entry.Key;
+ IAssetEditor editor = entry.Value;
+ try
+ {
+ if (!editor.CanEdit<T>(info))
+ continue;
+ }
+ catch (Exception ex)
+ {
+ this.Monitor.Log($"{mod.DisplayName} crashed when checking whether it could edit asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error);
+ continue;
+ }
+
+ // try edit
+ object prevAsset = asset.Data;
+ try
+ {
+ editor.Edit<T>(asset);
+ this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace);
+ }
+ catch (Exception ex)
+ {
+ this.Monitor.Log($"{mod.DisplayName} crashed when editing asset '{info.AssetName}', which may cause errors in-game. Error details:\n{ex.GetLogSummary()}", LogLevel.Error);
+ }
+
+ // validate edit
+ if (asset.Data == null)
+ {
+ this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Warn);
+ asset = GetNewData(prevAsset);
+ }
+ else if (!(asset.Data is T))
+ {
+ this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{asset.AssetName}' to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn);
+ asset = GetNewData(prevAsset);
+ }
+ }
+
+ // return result
+ return asset;
+ }
+
+ /// <summary>Get all registered interceptors from a list.</summary>
+ private IEnumerable<KeyValuePair<IModMetadata, T>> GetInterceptors<T>(IDictionary<IModMetadata, IList<T>> entries)
+ {
+ foreach (var entry in entries)
+ {
+ IModMetadata metadata = entry.Key;
+ IList<T> interceptors = entry.Value;
+
+ // special case if mod is an interceptor
+ if (metadata.Mod is T modAsInterceptor)
+ yield return new KeyValuePair<IModMetadata, T>(metadata, modAsInterceptor);
+
+ // registered editors
+ foreach (T interceptor in interceptors)
+ yield return new KeyValuePair<IModMetadata, T>(metadata, interceptor);
+ }
+ }
+
+ /// <summary>Dispose all game resources.</summary>
+ /// <param name="disposing">Whether the content manager is disposing (rather than finalising).</param>
+ protected override void Dispose(bool disposing)
+ {
+ if (!disposing)
+ return;
+
+ // Clear cache & reload all assets. While that may seem perverse during disposal, it's
+ // necessary due to limitations in the way SMAPI currently intercepts content assets.
+ //
+ // The game uses multiple content managers while SMAPI needs one and only one. The game
+ // only disposes some of its content managers when returning to title, which means SMAPI
+ // can't know which assets are meant to be disposed. Here we remove current assets from
+ // the cache, but don't dispose them to avoid crashing any code that still references
+ // them. The garbage collector will eventually clean up any unused assets.
+ this.Reset();
}
}
}
diff --git a/src/StardewModdingAPI/Framework/SGame.cs b/src/StardewModdingAPI/Framework/SGame.cs
index 602a522b..c7784c60 100644
--- a/src/StardewModdingAPI/Framework/SGame.cs
+++ b/src/StardewModdingAPI/Framework/SGame.cs
@@ -4,11 +4,14 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
+using System.Threading;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using StardewModdingAPI.Events;
+using StardewModdingAPI.Framework.Reflection;
+using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.BellsAndWhistles;
using StardewValley.Locations;
@@ -29,6 +32,12 @@ namespace StardewModdingAPI.Framework
/****
** SMAPI state
****/
+ /// <summary>Encapsulates monitoring and logging.</summary>
+ private readonly IMonitor Monitor;
+
+ /// <summary>SMAPI's content manager.</summary>
+ private readonly SContentManager SContentManager;
+
/// <summary>The maximum number of consecutive attempts SMAPI should make to recover from a draw error.</summary>
private readonly Countdown DrawCrashTimer = new Countdown(60); // 60 ticks = roughly one second
@@ -48,18 +57,19 @@ namespace StardewModdingAPI.Framework
/// <summary>Whether the game's zoom level is at 100% (i.e. nothing should be scaled).</summary>
public bool ZoomLevelIsOne => Game1.options.zoomLevel.Equals(1.0f);
- /// <summary>Encapsulates monitoring and logging.</summary>
- private readonly IMonitor Monitor;
/****
** Game state
****/
- /// <summary>Arrays of pressed controller buttons indexed by <see cref="PlayerIndex"/>.</summary>
- private Buttons[] PreviousPressedButtons = new Buttons[0];
+ /// <summary>A record of the buttons pressed as of the previous tick.</summary>
+ private SButton[] PreviousPressedButtons = new SButton[0];
/// <summary>A record of the keyboard state (i.e. the up/down state for each button) as of the previous tick.</summary>
private KeyboardState PreviousKeyState;
+ /// <summary>A record of the controller state (i.e. the up/down state for each button) as of the previous tick.</summary>
+ private GamePadState PreviousControllerState;
+
/// <summary>A record of the mouse state (i.e. the cursor position, scroll amount, and the up/down state for each button) as of the previous tick.</summary>
private MouseState PreviousMouseState;
@@ -108,6 +118,7 @@ namespace StardewModdingAPI.Framework
/// <summary>The time of day (in 24-hour military format) at last check.</summary>
private int PreviousTime;
+#if !SMAPI_2_0
/// <summary>The day of month (1–28) at last check.</summary>
private int PreviousDay;
@@ -122,6 +133,7 @@ namespace StardewModdingAPI.Framework
/// <summary>The player character at last check.</summary>
private SFarmer PreviousFarmer;
+#endif
/// <summary>The previous content locale.</summary>
private LocalizedContentManager.LanguageCode? PreviousLocale;
@@ -139,7 +151,7 @@ namespace StardewModdingAPI.Framework
** Private wrappers
****/
/// <summary>Simplifies access to private game code.</summary>
- private static IReflectionHelper Reflection;
+ private static Reflector Reflection;
// ReSharper disable ArrangeStaticMemberQualifier, ArrangeThisQualifier, InconsistentNaming
/// <summary>Used to access private fields and methods.</summary>
@@ -173,23 +185,22 @@ namespace StardewModdingAPI.Framework
/// <summary>Construct an instance.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="reflection">Simplifies access to private game code.</param>
- internal SGame(IMonitor monitor, IReflectionHelper reflection)
+ internal SGame(IMonitor monitor, Reflector reflection)
{
+ // initialise
this.Monitor = monitor;
this.FirstUpdate = true;
SGame.Instance = this;
SGame.Reflection = reflection;
- Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; // required by Stardew Valley
+ // set XNA option required by Stardew Valley
+ Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;
- // The game uses the default content manager instead of Game1.CreateContentManager in
- // several cases (See http://community.playstarbound.com/threads/130058/page-27#post-3159274).
- // The workaround is...
- // 1. Override the default content manager.
- // 2. Since Game1.content isn't initialised yet, and we need one main instance to
- // support custom map tilesheets, detect when Game1.content is being initialised
- // and use the same instance.
- this.Content = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, this.Monitor);
+ // override content manager
+ this.Monitor?.Log("Overriding content manager...", LogLevel.Trace);
+ this.SContentManager = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor);
+ this.Content = this.SContentManager;
+ Game1.content = this.SContentManager;
}
/****
@@ -200,13 +211,19 @@ namespace StardewModdingAPI.Framework
/// <param name="rootDirectory">The root directory to search for content.</param>
protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory)
{
- // When Game1.content is being initialised, use SMAPI's main content manager instance.
- // See comment in SGame constructor.
- if (Game1.content == null && this.Content is SContentManager mainContentManager)
- return mainContentManager;
+ // return default if SMAPI's content manager isn't initialised yet
+ if (this.SContentManager == null)
+ {
+ this.Monitor?.Log("SMAPI's content manager isn't initialised; skipping content manager interception.", LogLevel.Trace);
+ return base.CreateContentManager(serviceProvider, rootDirectory);
+ }
- // build new instance
- return new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, this.Monitor);
+ // return single instance if valid
+ if (serviceProvider != this.Content.ServiceProvider)
+ throw new InvalidOperationException("SMAPI uses a single content manager internally. You can't get a new content manager with a different service provider.");
+ if (rootDirectory != this.Content.RootDirectory)
+ throw new InvalidOperationException($"SMAPI uses a single content manager internally. You can't get a new content manager with a different root directory (current is {this.Content.RootDirectory}, requested {rootDirectory}).");
+ return this.SContentManager;
}
/// <summary>The method called when the game is updating its state. This happens roughly 60 times per second.</summary>
@@ -275,7 +292,9 @@ namespace StardewModdingAPI.Framework
if (this.FirstUpdate)
{
GameEvents.InvokeInitialize(this.Monitor);
+#if !SMAPI_2_0
GameEvents.InvokeLoadContent(this.Monitor);
+#endif
GameEvents.InvokeGameLoaded(this.Monitor);
}
@@ -305,7 +324,9 @@ namespace StardewModdingAPI.Framework
Context.IsWorldReady = true;
SaveEvents.InvokeAfterLoad(this.Monitor);
+#if !SMAPI_2_0
PlayerEvents.InvokeLoadedGame(this.Monitor, new EventArgsLoadedGameChanged(Game1.hasLoadedGame));
+#endif
TimeEvents.InvokeAfterDayStarted(this.Monitor);
}
this.AfterLoadTimer--;
@@ -334,53 +355,96 @@ namespace StardewModdingAPI.Framework
if (Game1.game1.IsActive)
{
// get latest state
- KeyboardState keyState = Keyboard.GetState();
- MouseState mouseState = Mouse.GetState();
- Point mousePosition = new Point(Game1.getMouseX(), Game1.getMouseY());
+ KeyboardState keyState;
+ GamePadState controllerState;
+ MouseState mouseState;
+ Point mousePosition;
+ try
+ {
+ keyState = Keyboard.GetState();
+ controllerState = GamePad.GetState(PlayerIndex.One);
+ mouseState = Mouse.GetState();
+ mousePosition = new Point(Game1.getMouseX(), Game1.getMouseY());
+ }
+ catch (InvalidOperationException) // GetState() may crash for some players if window doesn't have focus but game1.IsActive == true
+ {
+ keyState = this.PreviousKeyState;
+ controllerState = this.PreviousControllerState;
+ mouseState = this.PreviousMouseState;
+ mousePosition = this.PreviousMousePosition;
+ }
// analyse state
- Keys[] currentlyPressedKeys = keyState.GetPressedKeys();
- Keys[] previousPressedKeys = this.PreviousKeyState.GetPressedKeys();
- Keys[] framePressedKeys = currentlyPressedKeys.Except(previousPressedKeys).ToArray();
- Keys[] frameReleasedKeys = previousPressedKeys.Except(currentlyPressedKeys).ToArray();
-
- // raise key pressed
- foreach (Keys key in framePressedKeys)
- ControlEvents.InvokeKeyPressed(this.Monitor, key);
-
- // raise key released
- foreach (Keys key in frameReleasedKeys)
- ControlEvents.InvokeKeyReleased(this.Monitor, key);
+ SButton[] currentlyPressedKeys = this.GetPressedButtons(keyState, mouseState, controllerState).ToArray();
+ SButton[] previousPressedKeys = this.PreviousPressedButtons;
+ SButton[] framePressedKeys = currentlyPressedKeys.Except(previousPressedKeys).ToArray();
+ SButton[] frameReleasedKeys = previousPressedKeys.Except(currentlyPressedKeys).ToArray();
+ bool isClick = framePressedKeys.Contains(SButton.MouseLeft) || (framePressedKeys.Contains(SButton.ControllerA) && !currentlyPressedKeys.Contains(SButton.ControllerX));
+
+ // get cursor position
+#if SMAPI_2_0
+ ICursorPosition cursor;
+ {
+ // cursor position
+ Vector2 screenPixels = new Vector2(Game1.getMouseX(), Game1.getMouseY());
+ Vector2 tile = new Vector2((Game1.viewport.X + screenPixels.X) / Game1.tileSize, (Game1.viewport.Y + screenPixels.Y) / Game1.tileSize);
+ Vector2 grabTile = (Game1.mouseCursorTransparency > 0 && Utility.tileWithinRadiusOfPlayer((int)tile.X, (int)tile.Y, 1, Game1.player)) // derived from Game1.pressActionButton
+ ? tile
+ : Game1.player.GetGrabTile();
+ cursor = new CursorPosition(screenPixels, tile, grabTile);
+ }
+#endif
- // raise controller button pressed
- foreach (Buttons button in this.GetFramePressedButtons())
+ // raise button pressed
+ foreach (SButton button in framePressedKeys)
{
- if (button == Buttons.LeftTrigger || button == Buttons.RightTrigger)
+#if SMAPI_2_0
+ InputEvents.InvokeButtonPressed(this.Monitor, button, cursor, isClick);
+#endif
+
+ // legacy events
+ if (button.TryGetKeyboard(out Keys key))
{
- var triggers = GamePad.GetState(PlayerIndex.One).Triggers;
- ControlEvents.InvokeTriggerPressed(this.Monitor, button, button == Buttons.LeftTrigger ? triggers.Left : triggers.Right);
+ if (key != Keys.None)
+ ControlEvents.InvokeKeyPressed(this.Monitor, key);
+ }
+ else if (button.TryGetController(out Buttons controllerButton))
+ {
+ if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger)
+ ControlEvents.InvokeTriggerPressed(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? controllerState.Triggers.Left : controllerState.Triggers.Right);
+ else
+ ControlEvents.InvokeButtonPressed(this.Monitor, controllerButton);
}
- else
- ControlEvents.InvokeButtonPressed(this.Monitor, button);
}
- // raise controller button released
- foreach (Buttons button in this.GetFrameReleasedButtons())
+ // raise button released
+ foreach (SButton button in frameReleasedKeys)
{
- if (button == Buttons.LeftTrigger || button == Buttons.RightTrigger)
+#if SMAPI_2_0
+ bool wasClick =
+ (button == SButton.MouseLeft && previousPressedKeys.Contains(SButton.MouseLeft)) // released left click
+ || (button == SButton.ControllerA && previousPressedKeys.Contains(SButton.ControllerA) && !previousPressedKeys.Contains(SButton.ControllerX));
+ InputEvents.InvokeButtonReleased(this.Monitor, button, cursor, wasClick);
+#endif
+
+ // legacy events
+ if (button.TryGetKeyboard(out Keys key))
{
- var triggers = GamePad.GetState(PlayerIndex.One).Triggers;
- ControlEvents.InvokeTriggerReleased(this.Monitor, button, button == Buttons.LeftTrigger ? triggers.Left : triggers.Right);
+ if (key != Keys.None)
+ ControlEvents.InvokeKeyReleased(this.Monitor, key);
+ }
+ else if (button.TryGetController(out Buttons controllerButton))
+ {
+ if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger)
+ ControlEvents.InvokeTriggerReleased(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? controllerState.Triggers.Left : controllerState.Triggers.Right);
+ else
+ ControlEvents.InvokeButtonReleased(this.Monitor, controllerButton);
}
- else
- ControlEvents.InvokeButtonReleased(this.Monitor, button);
}
- // raise keyboard state changed
+ // raise legacy state-changed events
if (keyState != this.PreviousKeyState)
ControlEvents.InvokeKeyboardChanged(this.Monitor, this.PreviousKeyState, keyState);
-
- // raise mouse state changed
if (mouseState != this.PreviousMouseState)
ControlEvents.InvokeMouseChanged(this.Monitor, this.PreviousMouseState, mouseState, this.PreviousMousePosition, mousePosition);
@@ -388,7 +452,8 @@ namespace StardewModdingAPI.Framework
this.PreviousMouseState = mouseState;
this.PreviousMousePosition = mousePosition;
this.PreviousKeyState = keyState;
- this.PreviousPressedButtons = this.GetButtonsDown();
+ this.PreviousControllerState = controllerState;
+ this.PreviousPressedButtons = currentlyPressedKeys;
}
/*********
@@ -438,9 +503,11 @@ namespace StardewModdingAPI.Framework
if (this.GetHash(Game1.locations) != this.PreviousGameLocations)
LocationEvents.InvokeLocationsChanged(this.Monitor, Game1.locations);
+#if !SMAPI_2_0
// raise player changed
if (Game1.player != this.PreviousFarmer)
PlayerEvents.InvokeFarmerChanged(this.Monitor, this.PreviousFarmer, Game1.player);
+#endif
// raise events that shouldn't be triggered on initial load
if (Game1.uniqueIDForThisGame == this.PreviousSaveID)
@@ -471,12 +538,14 @@ namespace StardewModdingAPI.Framework
// raise time changed
if (Game1.timeOfDay != this.PreviousTime)
TimeEvents.InvokeTimeOfDayChanged(this.Monitor, this.PreviousTime, Game1.timeOfDay);
+#if !SMAPI_2_0
if (Game1.dayOfMonth != this.PreviousDay)
TimeEvents.InvokeDayOfMonthChanged(this.Monitor, this.PreviousDay, Game1.dayOfMonth);
if (Game1.currentSeason != this.PreviousSeason)
TimeEvents.InvokeSeasonOfYearChanged(this.Monitor, this.PreviousSeason, Game1.currentSeason);
if (Game1.year != this.PreviousYear)
TimeEvents.InvokeYearOfGameChanged(this.Monitor, this.PreviousYear, Game1.year);
+#endif
// raise mine level changed
if (Game1.mine != null && Game1.mine.mineLevel != this.PreviousMineLevel)
@@ -486,7 +555,6 @@ namespace StardewModdingAPI.Framework
// update state
this.PreviousGameLocations = this.GetHash(Game1.locations);
this.PreviousGameLocation = Game1.currentLocation;
- this.PreviousFarmer = Game1.player;
this.PreviousCombatLevel = Game1.player.combatLevel;
this.PreviousFarmingLevel = Game1.player.farmingLevel;
this.PreviousFishingLevel = Game1.player.fishingLevel;
@@ -496,21 +564,26 @@ namespace StardewModdingAPI.Framework
this.PreviousItems = Game1.player.items.Where(n => n != null).ToDictionary(n => n, n => n.Stack);
this.PreviousLocationObjects = this.GetHash(Game1.currentLocation.objects);
this.PreviousTime = Game1.timeOfDay;
+ this.PreviousMineLevel = Game1.mine?.mineLevel ?? 0;
+ this.PreviousSaveID = Game1.uniqueIDForThisGame;
+#if !SMAPI_2_0
+ this.PreviousFarmer = Game1.player;
this.PreviousDay = Game1.dayOfMonth;
this.PreviousSeason = Game1.currentSeason;
this.PreviousYear = Game1.year;
- this.PreviousMineLevel = Game1.mine?.mineLevel ?? 0;
- this.PreviousSaveID = Game1.uniqueIDForThisGame;
+#endif
}
/*********
** Game day transition event (obsolete)
*********/
+#if !SMAPI_2_0
if (Game1.newDay != this.PreviousIsNewDay)
{
TimeEvents.InvokeOnNewDay(this.Monitor, this.PreviousDay, Game1.dayOfMonth, Game1.newDay);
this.PreviousIsNewDay = Game1.newDay;
}
+#endif
/*********
** Game update
@@ -530,7 +603,9 @@ namespace StardewModdingAPI.Framework
GameEvents.InvokeUpdateTick(this.Monitor);
if (this.FirstUpdate)
{
+#if !SMAPI_2_0
GameEvents.InvokeFirstUpdateTick(this.Monitor);
+#endif
this.FirstUpdate = false;
}
if (this.CurrentUpdateTick % 2 == 0)
@@ -1270,120 +1345,66 @@ namespace StardewModdingAPI.Framework
this.PreviousSaveID = 0;
}
- /// <summary>Get the controller buttons which are currently pressed.</summary>
- private Buttons[] GetButtonsDown()
- {
- var state = GamePad.GetState(PlayerIndex.One);
- var buttons = new List<Buttons>();
- if (state.IsConnected)
- {
- if (state.Buttons.A == ButtonState.Pressed) buttons.Add(Buttons.A);
- if (state.Buttons.B == ButtonState.Pressed) buttons.Add(Buttons.B);
- if (state.Buttons.Back == ButtonState.Pressed) buttons.Add(Buttons.Back);
- if (state.Buttons.BigButton == ButtonState.Pressed) buttons.Add(Buttons.BigButton);
- if (state.Buttons.LeftShoulder == ButtonState.Pressed) buttons.Add(Buttons.LeftShoulder);
- if (state.Buttons.LeftStick == ButtonState.Pressed) buttons.Add(Buttons.LeftStick);
- if (state.Buttons.RightShoulder == ButtonState.Pressed) buttons.Add(Buttons.RightShoulder);
- if (state.Buttons.RightStick == ButtonState.Pressed) buttons.Add(Buttons.RightStick);
- if (state.Buttons.Start == ButtonState.Pressed) buttons.Add(Buttons.Start);
- if (state.Buttons.X == ButtonState.Pressed) buttons.Add(Buttons.X);
- if (state.Buttons.Y == ButtonState.Pressed) buttons.Add(Buttons.Y);
- if (state.DPad.Up == ButtonState.Pressed) buttons.Add(Buttons.DPadUp);
- if (state.DPad.Down == ButtonState.Pressed) buttons.Add(Buttons.DPadDown);
- if (state.DPad.Left == ButtonState.Pressed) buttons.Add(Buttons.DPadLeft);
- if (state.DPad.Right == ButtonState.Pressed) buttons.Add(Buttons.DPadRight);
- if (state.Triggers.Left > 0.2f) buttons.Add(Buttons.LeftTrigger);
- if (state.Triggers.Right > 0.2f) buttons.Add(Buttons.RightTrigger);
- }
- return buttons.ToArray();
- }
-
- /// <summary>Get the controller buttons which were pressed after the last update.</summary>
- private Buttons[] GetFramePressedButtons()
+ /// <summary>Get the buttons pressed in the given stats.</summary>
+ /// <param name="keyboard">The keyboard state.</param>
+ /// <param name="mouse">The mouse state.</param>
+ /// <param name="controller">The controller state.</param>
+ private IEnumerable<SButton> GetPressedButtons(KeyboardState keyboard, MouseState mouse, GamePadState controller)
{
- var state = GamePad.GetState(PlayerIndex.One);
- var buttons = new List<Buttons>();
- if (state.IsConnected)
+ // keyboard
+ foreach (Keys key in keyboard.GetPressedKeys())
+ yield return key.ToSButton();
+
+ // mouse
+ if (mouse.LeftButton == ButtonState.Pressed)
+ yield return SButton.MouseLeft;
+ if (mouse.RightButton == ButtonState.Pressed)
+ yield return SButton.MouseRight;
+ if (mouse.MiddleButton == ButtonState.Pressed)
+ yield return SButton.MouseMiddle;
+ if (mouse.XButton1 == ButtonState.Pressed)
+ yield return SButton.MouseX1;
+ if (mouse.XButton2 == ButtonState.Pressed)
+ yield return SButton.MouseX2;
+
+ // controller
+ if (controller.IsConnected)
{
- if (this.WasButtonJustPressed(Buttons.A, state.Buttons.A)) buttons.Add(Buttons.A);
- if (this.WasButtonJustPressed(Buttons.B, state.Buttons.B)) buttons.Add(Buttons.B);
- if (this.WasButtonJustPressed(Buttons.Back, state.Buttons.Back)) buttons.Add(Buttons.Back);
- if (this.WasButtonJustPressed(Buttons.BigButton, state.Buttons.BigButton)) buttons.Add(Buttons.BigButton);
- if (this.WasButtonJustPressed(Buttons.LeftShoulder, state.Buttons.LeftShoulder)) buttons.Add(Buttons.LeftShoulder);
- if (this.WasButtonJustPressed(Buttons.LeftStick, state.Buttons.LeftStick)) buttons.Add(Buttons.LeftStick);
- if (this.WasButtonJustPressed(Buttons.RightShoulder, state.Buttons.RightShoulder)) buttons.Add(Buttons.RightShoulder);
- if (this.WasButtonJustPressed(Buttons.RightStick, state.Buttons.RightStick)) buttons.Add(Buttons.RightStick);
- if (this.WasButtonJustPressed(Buttons.Start, state.Buttons.Start)) buttons.Add(Buttons.Start);
- if (this.WasButtonJustPressed(Buttons.X, state.Buttons.X)) buttons.Add(Buttons.X);
- if (this.WasButtonJustPressed(Buttons.Y, state.Buttons.Y)) buttons.Add(Buttons.Y);
- if (this.WasButtonJustPressed(Buttons.DPadUp, state.DPad.Up)) buttons.Add(Buttons.DPadUp);
- if (this.WasButtonJustPressed(Buttons.DPadDown, state.DPad.Down)) buttons.Add(Buttons.DPadDown);
- if (this.WasButtonJustPressed(Buttons.DPadLeft, state.DPad.Left)) buttons.Add(Buttons.DPadLeft);
- if (this.WasButtonJustPressed(Buttons.DPadRight, state.DPad.Right)) buttons.Add(Buttons.DPadRight);
- if (this.WasButtonJustPressed(Buttons.LeftTrigger, state.Triggers.Left)) buttons.Add(Buttons.LeftTrigger);
- if (this.WasButtonJustPressed(Buttons.RightTrigger, state.Triggers.Right)) buttons.Add(Buttons.RightTrigger);
+ if (controller.Buttons.A == ButtonState.Pressed)
+ yield return SButton.ControllerA;
+ if (controller.Buttons.B == ButtonState.Pressed)
+ yield return SButton.ControllerB;
+ if (controller.Buttons.Back == ButtonState.Pressed)
+ yield return SButton.ControllerBack;
+ if (controller.Buttons.BigButton == ButtonState.Pressed)
+ yield return SButton.BigButton;
+ if (controller.Buttons.LeftShoulder == ButtonState.Pressed)
+ yield return SButton.LeftShoulder;
+ if (controller.Buttons.LeftStick == ButtonState.Pressed)
+ yield return SButton.LeftStick;
+ if (controller.Buttons.RightShoulder == ButtonState.Pressed)
+ yield return SButton.RightShoulder;
+ if (controller.Buttons.RightStick == ButtonState.Pressed)
+ yield return SButton.RightStick;
+ if (controller.Buttons.Start == ButtonState.Pressed)
+ yield return SButton.ControllerStart;
+ if (controller.Buttons.X == ButtonState.Pressed)
+ yield return SButton.ControllerX;
+ if (controller.Buttons.Y == ButtonState.Pressed)
+ yield return SButton.ControllerY;
+ if (controller.DPad.Up == ButtonState.Pressed)
+ yield return SButton.DPadUp;
+ if (controller.DPad.Down == ButtonState.Pressed)
+ yield return SButton.DPadDown;
+ if (controller.DPad.Left == ButtonState.Pressed)
+ yield return SButton.DPadLeft;
+ if (controller.DPad.Right == ButtonState.Pressed)
+ yield return SButton.DPadRight;
+ if (controller.Triggers.Left > 0.2f)
+ yield return SButton.LeftTrigger;
+ if (controller.Triggers.Right > 0.2f)
+ yield return SButton.RightTrigger;
}
- return buttons.ToArray();
- }
-
- /// <summary>Get the controller buttons which were released after the last update.</summary>
- private Buttons[] GetFrameReleasedButtons()
- {
- var state = GamePad.GetState(PlayerIndex.One);
- var buttons = new List<Buttons>();
- if (state.IsConnected)
- {
- if (this.WasButtonJustReleased(Buttons.A, state.Buttons.A)) buttons.Add(Buttons.A);
- if (this.WasButtonJustReleased(Buttons.B, state.Buttons.B)) buttons.Add(Buttons.B);
- if (this.WasButtonJustReleased(Buttons.Back, state.Buttons.Back)) buttons.Add(Buttons.Back);
- if (this.WasButtonJustReleased(Buttons.BigButton, state.Buttons.BigButton)) buttons.Add(Buttons.BigButton);
- if (this.WasButtonJustReleased(Buttons.LeftShoulder, state.Buttons.LeftShoulder)) buttons.Add(Buttons.LeftShoulder);
- if (this.WasButtonJustReleased(Buttons.LeftStick, state.Buttons.LeftStick)) buttons.Add(Buttons.LeftStick);
- if (this.WasButtonJustReleased(Buttons.RightShoulder, state.Buttons.RightShoulder)) buttons.Add(Buttons.RightShoulder);
- if (this.WasButtonJustReleased(Buttons.RightStick, state.Buttons.RightStick)) buttons.Add(Buttons.RightStick);
- if (this.WasButtonJustReleased(Buttons.Start, state.Buttons.Start)) buttons.Add(Buttons.Start);
- if (this.WasButtonJustReleased(Buttons.X, state.Buttons.X)) buttons.Add(Buttons.X);
- if (this.WasButtonJustReleased(Buttons.Y, state.Buttons.Y)) buttons.Add(Buttons.Y);
- if (this.WasButtonJustReleased(Buttons.DPadUp, state.DPad.Up)) buttons.Add(Buttons.DPadUp);
- if (this.WasButtonJustReleased(Buttons.DPadDown, state.DPad.Down)) buttons.Add(Buttons.DPadDown);
- if (this.WasButtonJustReleased(Buttons.DPadLeft, state.DPad.Left)) buttons.Add(Buttons.DPadLeft);
- if (this.WasButtonJustReleased(Buttons.DPadRight, state.DPad.Right)) buttons.Add(Buttons.DPadRight);
- if (this.WasButtonJustReleased(Buttons.LeftTrigger, state.Triggers.Left)) buttons.Add(Buttons.LeftTrigger);
- if (this.WasButtonJustReleased(Buttons.RightTrigger, state.Triggers.Right)) buttons.Add(Buttons.RightTrigger);
- }
- return buttons.ToArray();
- }
-
- /// <summary>Get whether a controller button was pressed since the last check.</summary>
- /// <param name="button">The controller button to check.</param>
- /// <param name="buttonState">The last known state.</param>
- private bool WasButtonJustPressed(Buttons button, ButtonState buttonState)
- {
- return buttonState == ButtonState.Pressed && !this.PreviousPressedButtons.Contains(button);
- }
-
- /// <summary>Get whether a controller button was released since the last check.</summary>
- /// <param name="button">The controller button to check.</param>
- /// <param name="buttonState">The last known state.</param>
- private bool WasButtonJustReleased(Buttons button, ButtonState buttonState)
- {
- return buttonState == ButtonState.Released && this.PreviousPressedButtons.Contains(button);
- }
-
- /// <summary>Get whether an analogue controller button was pressed since the last check.</summary>
- /// <param name="button">The controller button to check.</param>
- /// <param name="value">The last known value.</param>
- private bool WasButtonJustPressed(Buttons button, float value)
- {
- return this.WasButtonJustPressed(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released);
- }
-
- /// <summary>Get whether an analogue controller button was released since the last check.</summary>
- /// <param name="button">The controller button to check.</param>
- /// <param name="value">The last known value.</param>
- private bool WasButtonJustReleased(Buttons button, float value)
- {
- return this.WasButtonJustReleased(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released);
}
/// <summary>Get the player inventory changes between two states.</summary>
diff --git a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs
index 64d8738e..3193aa3c 100644
--- a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs
+++ b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework.Input;
using Newtonsoft.Json;
+using StardewModdingAPI.Utilities;
namespace StardewModdingAPI.Framework.Serialisation
{
@@ -19,7 +20,7 @@ namespace StardewModdingAPI.Framework.Serialisation
ObjectCreationHandling = ObjectCreationHandling.Replace, // avoid issue where default ICollection<T> values are duplicated each time the config is loaded
Converters = new List<JsonConverter>
{
- new SelectiveStringEnumConverter(typeof(Buttons), typeof(Keys))
+ new SelectiveStringEnumConverter(typeof(Buttons), typeof(Keys), typeof(SButton))
}
};
@@ -51,7 +52,21 @@ namespace StardewModdingAPI.Framework.Serialisation
}
// deserialise model
- return JsonConvert.DeserializeObject<TModel>(json, this.JsonSettings);
+ try
+ {
+ return JsonConvert.DeserializeObject<TModel>(json, this.JsonSettings);
+ }
+ catch (JsonReaderException ex)
+ {
+ string message = $"The file at {fullPath} doesn't seem to be valid JSON.";
+
+ string text = File.ReadAllText(fullPath);
+ if (text.Contains("“") || text.Contains("”"))
+ message += " Found curly quotes in the text; note that only straight quotes are allowed in JSON.";
+
+ message += $"\nTechnical details: {ex.Message}";
+ throw new JsonReaderException(message);
+ }
}
/// <summary>Save to a JSON file.</summary>
diff --git a/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs b/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs
index 6b5a6aaa..5be0f0b6 100644
--- a/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs
+++ b/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
+using StardewModdingAPI.Framework.Exceptions;
using StardewModdingAPI.Framework.Models;
namespace StardewModdingAPI.Framework.Serialisation
@@ -36,12 +37,32 @@ namespace StardewModdingAPI.Framework.Serialisation
// semantic version
if (objectType == typeof(ISemanticVersion))
{
- JObject obj = JObject.Load(reader);
- int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion));
- int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion));
- int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion));
- string build = obj.Value<string>(nameof(ISemanticVersion.Build));
- return new SemanticVersion(major, minor, patch, build);
+ JToken token = JToken.Load(reader);
+ switch (token.Type)
+ {
+ case JTokenType.Object:
+ {
+ JObject obj = (JObject)token;
+ int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion));
+ int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion));
+ int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion));
+ string build = obj.Value<string>(nameof(ISemanticVersion.Build));
+ return new SemanticVersion(major, minor, patch, build);
+ }
+
+ case JTokenType.String:
+ {
+ string str = token.Value<string>();
+ if (string.IsNullOrWhiteSpace(str))
+ return null;
+ if (!SemanticVersion.TryParse(str, out ISemanticVersion version))
+ throw new SParseException($"Can't parse semantic version from invalid value '{str}', should be formatted like 1.2, 1.2.30, or 1.2.30-beta.");
+ return version;
+ }
+
+ default:
+ throw new SParseException($"Can't parse semantic version from {token.Type}, must be an object or string.");
+ }
}
// manifest dependency
@@ -51,7 +72,13 @@ namespace StardewModdingAPI.Framework.Serialisation
foreach (JObject obj in JArray.Load(reader).Children<JObject>())
{
string uniqueID = obj.Value<string>(nameof(IManifestDependency.UniqueID));
- result.Add(new ManifestDependency(uniqueID));
+ string minVersion = obj.Value<string>(nameof(IManifestDependency.MinimumVersion));
+#if SMAPI_2_0
+ bool required = obj.Value<bool?>(nameof(IManifestDependency.IsRequired)) ?? true;
+ result.Add(new ManifestDependency(uniqueID, minVersion, required));
+#else
+ result.Add(new ManifestDependency(uniqueID, minVersion));
+#endif
}
return result.ToArray();
}
diff --git a/src/StardewModdingAPI/IAssetData.cs b/src/StardewModdingAPI/IAssetData.cs
new file mode 100644
index 00000000..c3021144
--- /dev/null
+++ b/src/StardewModdingAPI/IAssetData.cs
@@ -0,0 +1,47 @@
+using System;
+
+namespace StardewModdingAPI
+{
+ /// <summary>Generic metadata and methods for a content asset being loaded.</summary>
+ /// <typeparam name="TValue">The expected data type.</typeparam>
+ public interface IAssetData<TValue> : IAssetInfo
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The content data being read.</summary>
+ TValue Data { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary>
+ /// <param name="value">The new content value.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception>
+ /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception>
+ void ReplaceWith(TValue value);
+ }
+
+ /// <summary>Generic metadata and methods for a content asset being loaded.</summary>
+ public interface IAssetData : IAssetData<object>
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get a helper to manipulate the data as a dictionary.</summary>
+ /// <typeparam name="TKey">The expected dictionary key.</typeparam>
+ /// <typeparam name="TValue">The expected dictionary value.</typeparam>
+ /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception>
+ IAssetDataForDictionary<TKey, TValue> AsDictionary<TKey, TValue>();
+
+ /// <summary>Get a helper to manipulate the data as an image.</summary>
+ /// <exception cref="InvalidOperationException">The content being read isn't an image.</exception>
+ IAssetDataForImage AsImage();
+
+ /// <summary>Get the data as a given type.</summary>
+ /// <typeparam name="TData">The expected data type.</typeparam>
+ /// <exception cref="InvalidCastException">The data can't be converted to <typeparamref name="TData"/>.</exception>
+ TData GetData<TData>();
+ }
+}
diff --git a/src/StardewModdingAPI/IContentEventHelperForDictionary.cs b/src/StardewModdingAPI/IAssetDataForDictionary.cs
index 2f9d5a65..53c24346 100644
--- a/src/StardewModdingAPI/IContentEventHelperForDictionary.cs
+++ b/src/StardewModdingAPI/IAssetDataForDictionary.cs
@@ -4,7 +4,7 @@ using System.Collections.Generic;
namespace StardewModdingAPI
{
/// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary>
- public interface IContentEventHelperForDictionary<TKey, TValue> : IContentEventData<IDictionary<TKey, TValue>>
+ public interface IAssetDataForDictionary<TKey, TValue> : IAssetData<IDictionary<TKey, TValue>>
{
/*********
** Public methods
diff --git a/src/StardewModdingAPI/IContentEventHelperForImage.cs b/src/StardewModdingAPI/IAssetDataForImage.cs
index 1158c868..4584a20e 100644
--- a/src/StardewModdingAPI/IContentEventHelperForImage.cs
+++ b/src/StardewModdingAPI/IAssetDataForImage.cs
@@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics;
namespace StardewModdingAPI
{
/// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary>
- public interface IContentEventHelperForImage : IContentEventData<Texture2D>
+ public interface IAssetDataForImage : IAssetData<Texture2D>
{
/*********
** Public methods
diff --git a/src/StardewModdingAPI/IAssetEditor.cs b/src/StardewModdingAPI/IAssetEditor.cs
new file mode 100644
index 00000000..d2c6f295
--- /dev/null
+++ b/src/StardewModdingAPI/IAssetEditor.cs
@@ -0,0 +1,17 @@
+namespace StardewModdingAPI
+{
+ /// <summary>Edits matching content assets.</summary>
+ public interface IAssetEditor
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get whether this instance can edit the given asset.</summary>
+ /// <param name="asset">Basic metadata about the asset being loaded.</param>
+ bool CanEdit<T>(IAssetInfo asset);
+
+ /// <summary>Edit a matched asset.</summary>
+ /// <param name="asset">A helper which encapsulates metadata about an asset and enables changes to it.</param>
+ void Edit<T>(IAssetData asset);
+ }
+}
diff --git a/src/StardewModdingAPI/IAssetInfo.cs b/src/StardewModdingAPI/IAssetInfo.cs
new file mode 100644
index 00000000..5dd58e2e
--- /dev/null
+++ b/src/StardewModdingAPI/IAssetInfo.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace StardewModdingAPI
+{
+ /// <summary>Basic metadata for a content asset.</summary>
+ public interface IAssetInfo
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The content's locale code, if the content is localised.</summary>
+ string Locale { get; }
+
+ /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="AssetNameEquals"/> to compare with a known path.</summary>
+ string AssetName { get; }
+
+ /// <summary>The content data type.</summary>
+ Type DataType { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary>
+ /// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param>
+ bool AssetNameEquals(string path);
+ }
+}
diff --git a/src/StardewModdingAPI/IAssetLoader.cs b/src/StardewModdingAPI/IAssetLoader.cs
new file mode 100644
index 00000000..ad97b941
--- /dev/null
+++ b/src/StardewModdingAPI/IAssetLoader.cs
@@ -0,0 +1,17 @@
+namespace StardewModdingAPI
+{
+ /// <summary>Provides the initial version for matching assets loaded by the game. SMAPI will raise an error if two mods try to load the same asset; in most cases you should use <see cref="IAssetEditor"/> instead.</summary>
+ public interface IAssetLoader
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get whether this instance can load the initial version of the given asset.</summary>
+ /// <param name="asset">Basic metadata about the asset being loaded.</param>
+ bool CanLoad<T>(IAssetInfo asset);
+
+ /// <summary>Load a matched asset.</summary>
+ /// <param name="asset">Basic metadata about the asset being loaded.</param>
+ T Load<T>(IAssetInfo asset);
+ }
+}
diff --git a/src/StardewModdingAPI/ICommandHelper.cs b/src/StardewModdingAPI/ICommandHelper.cs
index 3a51ffb4..fb562e32 100644
--- a/src/StardewModdingAPI/ICommandHelper.cs
+++ b/src/StardewModdingAPI/ICommandHelper.cs
@@ -3,7 +3,7 @@
namespace StardewModdingAPI
{
/// <summary>Provides an API for managing console commands.</summary>
- public interface ICommandHelper
+ public interface ICommandHelper : IModLinked
{
/*********
** Public methods
diff --git a/src/StardewModdingAPI/IContentEventData.cs b/src/StardewModdingAPI/IContentEventData.cs
deleted file mode 100644
index 7e2d4df1..00000000
--- a/src/StardewModdingAPI/IContentEventData.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System;
-
-namespace StardewModdingAPI
-{
- /// <summary>Generic metadata and methods for a content asset being loaded.</summary>
- /// <typeparam name="TValue">The expected data type.</typeparam>
- public interface IContentEventData<TValue>
- {
- /*********
- ** Accessors
- *********/
- /// <summary>The content's locale code, if the content is localised.</summary>
- string Locale { get; }
-
- /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="IsAssetName"/> to compare with a known path.</summary>
- string AssetName { get; }
-
- /// <summary>The content data being read.</summary>
- TValue Data { get; }
-
- /// <summary>The content data type.</summary>
- Type DataType { get; }
-
-
- /*********
- ** Public methods
- *********/
- /// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary>
- /// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param>
- bool IsAssetName(string path);
-
- /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary>
- /// <param name="value">The new content value.</param>
- /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception>
- /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception>
- void ReplaceWith(TValue value);
- }
-}
diff --git a/src/StardewModdingAPI/IContentEventHelper.cs b/src/StardewModdingAPI/IContentEventHelper.cs
deleted file mode 100644
index 421a1e06..00000000
--- a/src/StardewModdingAPI/IContentEventHelper.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-
-namespace StardewModdingAPI
-{
- /// <summary>Encapsulates access and changes to content being read from a data file.</summary>
- public interface IContentEventHelper : IContentEventData<object>
- {
- /*********
- ** Public methods
- *********/
- /// <summary>Get a helper to manipulate the data as a dictionary.</summary>
- /// <typeparam name="TKey">The expected dictionary key.</typeparam>
- /// <typeparam name="TValue">The expected dictionary balue.</typeparam>
- /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception>
- IContentEventHelperForDictionary<TKey, TValue> AsDictionary<TKey, TValue>();
-
- /// <summary>Get a helper to manipulate the data as an image.</summary>
- /// <exception cref="InvalidOperationException">The content being read isn't an image.</exception>
- IContentEventHelperForImage AsImage();
-
- /// <summary>Get the data as a given type.</summary>
- /// <typeparam name="TData">The expected data type.</typeparam>
- /// <exception cref="InvalidCastException">The data can't be converted to <typeparamref name="TData"/>.</exception>
- TData GetData<TData>();
- }
-}
diff --git a/src/StardewModdingAPI/IContentHelper.cs b/src/StardewModdingAPI/IContentHelper.cs
index 1d520135..32a9ff19 100644
--- a/src/StardewModdingAPI/IContentHelper.cs
+++ b/src/StardewModdingAPI/IContentHelper.cs
@@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics;
namespace StardewModdingAPI
{
/// <summary>Provides an API for loading content assets.</summary>
- public interface IContentHelper
+ public interface IContentHelper : IModLinked
{
/// <summary>Load content from the game folder or mod folder (if not already cached), and return it. When loading a <c>.png</c> file, this must be called outside the game's draw loop.</summary>
/// <typeparam name="T">The expected data type. The main supported types are <see cref="Texture2D"/> and dictionaries; other types may be supported by the game's content pipeline.</typeparam>
diff --git a/src/StardewModdingAPI/ICursorPosition.cs b/src/StardewModdingAPI/ICursorPosition.cs
new file mode 100644
index 00000000..d03cda71
--- /dev/null
+++ b/src/StardewModdingAPI/ICursorPosition.cs
@@ -0,0 +1,19 @@
+#if SMAPI_2_0
+using Microsoft.Xna.Framework;
+
+namespace StardewModdingAPI
+{
+ /// <summary>Represents a cursor position in the different coordinate systems.</summary>
+ public interface ICursorPosition
+ {
+ /// <summary>The pixel position relative to the top-left corner of the visible screen.</summary>
+ Vector2 ScreenPixels { get; }
+
+ /// <summary>The tile position under the cursor relative to the top-left corner of the map.</summary>
+ Vector2 Tile { get; }
+
+ /// <summary>The tile position that the game considers under the cursor for purposes of clicking actions. This may be different than <see cref="Tile"/> if that's too far from the player.</summary>
+ Vector2 GrabTile { get; }
+ }
+}
+#endif
diff --git a/src/StardewModdingAPI/IManifest.cs b/src/StardewModdingAPI/IManifest.cs
index 9533aadb..407db1ce 100644
--- a/src/StardewModdingAPI/IManifest.cs
+++ b/src/StardewModdingAPI/IManifest.cs
@@ -21,7 +21,7 @@ namespace StardewModdingAPI
ISemanticVersion Version { get; }
/// <summary>The minimum SMAPI version required by this mod, if any.</summary>
- string MinimumApiVersion { get; }
+ ISemanticVersion MinimumApiVersion { get; }
/// <summary>The unique mod ID.</summary>
string UniqueID { get; }
diff --git a/src/StardewModdingAPI/IManifestDependency.cs b/src/StardewModdingAPI/IManifestDependency.cs
index 7bd2e8b6..027c1d59 100644
--- a/src/StardewModdingAPI/IManifestDependency.cs
+++ b/src/StardewModdingAPI/IManifestDependency.cs
@@ -8,5 +8,13 @@
*********/
/// <summary>The unique mod ID to require.</summary>
string UniqueID { get; }
+
+ /// <summary>The minimum required version (if any).</summary>
+ ISemanticVersion MinimumVersion { get; }
+
+#if SMAPI_2_0
+ /// <summary>Whether the dependency must be installed to use the mod.</summary>
+ bool IsRequired { get; }
+#endif
}
}
diff --git a/src/StardewModdingAPI/IModLinked.cs b/src/StardewModdingAPI/IModLinked.cs
new file mode 100644
index 00000000..172ee30c
--- /dev/null
+++ b/src/StardewModdingAPI/IModLinked.cs
@@ -0,0 +1,12 @@
+namespace StardewModdingAPI
+{
+ /// <summary>An instance linked to a mod.</summary>
+ public interface IModLinked
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The unique ID of the mod for which the instance was created.</summary>
+ string ModID { get; }
+ }
+}
diff --git a/src/StardewModdingAPI/IModRegistry.cs b/src/StardewModdingAPI/IModRegistry.cs
index 676c9734..5ef3fd65 100644
--- a/src/StardewModdingAPI/IModRegistry.cs
+++ b/src/StardewModdingAPI/IModRegistry.cs
@@ -2,8 +2,8 @@
namespace StardewModdingAPI
{
- /// <summary>Provides metadata about loaded mods.</summary>
- public interface IModRegistry
+ /// <summary>Provides an API for fetching metadata about loaded mods.</summary>
+ public interface IModRegistry : IModLinked
{
/// <summary>Get metadata for all loaded mods.</summary>
IEnumerable<IManifest> GetAll();
diff --git a/src/StardewModdingAPI/IReflectionHelper.cs b/src/StardewModdingAPI/IReflectionHelper.cs
index 77943c6c..fb2c7861 100644
--- a/src/StardewModdingAPI/IReflectionHelper.cs
+++ b/src/StardewModdingAPI/IReflectionHelper.cs
@@ -2,8 +2,8 @@
namespace StardewModdingAPI
{
- /// <summary>Simplifies access to private game code.</summary>
- public interface IReflectionHelper
+ /// <summary>Provides an API for accessing private game code.</summary>
+ public interface IReflectionHelper : IModLinked
{
/*********
** Public methods
diff --git a/src/StardewModdingAPI/ITranslationHelper.cs b/src/StardewModdingAPI/ITranslationHelper.cs
index dac83025..c4b72444 100644
--- a/src/StardewModdingAPI/ITranslationHelper.cs
+++ b/src/StardewModdingAPI/ITranslationHelper.cs
@@ -4,7 +4,7 @@ using StardewValley;
namespace StardewModdingAPI
{
/// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> &lt; <c>pt.json</c> &lt; <c>default.json</c>).</summary>
- public interface ITranslationHelper
+ public interface ITranslationHelper : IModLinked
{
/*********
** Accessors
diff --git a/src/StardewModdingAPI/Log.cs b/src/StardewModdingAPI/Log.cs
index d58cebfe..46f1caae 100644
--- a/src/StardewModdingAPI/Log.cs
+++ b/src/StardewModdingAPI/Log.cs
@@ -1,3 +1,4 @@
+#if !SMAPI_2_0
using System;
using System.Threading;
using StardewModdingAPI.Framework;
@@ -306,7 +307,7 @@ namespace StardewModdingAPI
/// <summary>Raise a deprecation warning.</summary>
private static void WarnDeprecated()
{
- Log.DeprecationManager.Warn($"the {nameof(Log)} class", "1.1", DeprecationLevel.Info);
+ Log.DeprecationManager.Warn($"the {nameof(Log)} class", "1.1", DeprecationLevel.PendingRemoval);
}
/// <summary>Get the name of the mod logging a message from the stack.</summary>
@@ -315,4 +316,5 @@ namespace StardewModdingAPI
return Log.ModRegistry.GetModFromStack() ?? "<unknown mod>";
}
}
-} \ No newline at end of file
+}
+#endif \ No newline at end of file
diff --git a/src/StardewModdingAPI/Mod.cs b/src/StardewModdingAPI/Mod.cs
index 171088cf..cb36c596 100644
--- a/src/StardewModdingAPI/Mod.cs
+++ b/src/StardewModdingAPI/Mod.cs
@@ -11,11 +11,14 @@ namespace StardewModdingAPI
/*********
** Properties
*********/
+#if !SMAPI_2_0
/// <summary>Manages deprecation warnings.</summary>
private static DeprecationManager DeprecationManager;
+
/// <summary>The backing field for <see cref="Mod.PathOnDisk"/>.</summary>
private string _pathOnDisk;
+#endif
/*********
@@ -30,13 +33,14 @@ namespace StardewModdingAPI
/// <summary>The mod's manifest.</summary>
public IManifest ModManifest { get; internal set; }
+#if !SMAPI_2_0
/// <summary>The full path to the mod's directory on the disk.</summary>
[Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.DirectoryPath) + " instead")]
public string PathOnDisk
{
get
{
- Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0", DeprecationLevel.Info);
+ Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0", DeprecationLevel.PendingRemoval);
return this._pathOnDisk;
}
internal set { this._pathOnDisk = value; }
@@ -48,7 +52,7 @@ namespace StardewModdingAPI
{
get
{
- Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.BaseConfigPath)}", "1.0", DeprecationLevel.Info);
+ Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.BaseConfigPath)}", "1.0", DeprecationLevel.PendingRemoval);
Mod.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0"); // avoid redundant warnings
return Path.Combine(this.PathOnDisk, "config.json");
}
@@ -64,16 +68,18 @@ namespace StardewModdingAPI
{
get
{
- Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigPath)}", "1.0", DeprecationLevel.Info);
+ Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigPath)}", "1.0", DeprecationLevel.PendingRemoval);
Mod.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigFolder)}", "1.0"); // avoid redundant warnings
return Context.IsSaveLoaded ? Path.Combine(this.PerSaveConfigFolder, $"{Constants.SaveFolderName}.json") : "";
}
}
+#endif
/*********
** Public methods
*********/
+#if !SMAPI_2_0
/// <summary>Injects types required for backwards compatibility.</summary>
/// <param name="deprecationManager">Manages deprecation warnings.</param>
internal static void Shim(DeprecationManager deprecationManager)
@@ -84,6 +90,7 @@ namespace StardewModdingAPI
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
[Obsolete("This overload is obsolete since SMAPI 1.0.")]
public virtual void Entry(params object[] objects) { }
+#endif
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
@@ -101,11 +108,12 @@ namespace StardewModdingAPI
/*********
** Private methods
*********/
+#if !SMAPI_2_0
/// <summary>Get the full path to the per-save configuration file for the current save (if <see cref="Manifest.PerSaveConfigs"/> is <c>true</c>).</summary>
[Obsolete]
private string GetPerSaveConfigFolder()
{
- Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigFolder)}", "1.0", DeprecationLevel.Info);
+ Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigFolder)}", "1.0", DeprecationLevel.PendingRemoval);
Mod.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0"); // avoid redundant warnings
if (!((Manifest)this.ModManifest).PerSaveConfigs)
@@ -115,6 +123,7 @@ namespace StardewModdingAPI
}
return Path.Combine(this.PathOnDisk, "psconfigs");
}
+#endif
/// <summary>Release or reset unmanaged resources when the game exits. There's no guarantee this will be called on every exit.</summary>
/// <param name="disposing">Whether the instance is being disposed explicitly rather than finalised. If this is false, the instance shouldn't dispose other objects since they may already be finalised.</param>
diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs
index d75d5193..97e18322 100644
--- a/src/StardewModdingAPI/Program.cs
+++ b/src/StardewModdingAPI/Program.cs
@@ -4,6 +4,8 @@ using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
+using System.Runtime.ExceptionServices;
+using System.Security;
using System.Threading;
#if SMAPI_FOR_WINDOWS
using System.Management;
@@ -15,6 +17,7 @@ using StardewModdingAPI.Events;
using StardewModdingAPI.Framework;
using StardewModdingAPI.Framework.Logging;
using StardewModdingAPI.Framework.Models;
+using StardewModdingAPI.Framework.ModHelpers;
using StardewModdingAPI.Framework.ModLoading;
using StardewModdingAPI.Framework.Reflection;
using StardewModdingAPI.Framework.Serialisation;
@@ -43,7 +46,7 @@ namespace StardewModdingAPI
private readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
/// <summary>Simplifies access to private game code.</summary>
- private readonly IReflectionHelper Reflection = new ReflectionHelper();
+ private readonly Reflector Reflection = new Reflector();
/// <summary>The underlying game instance.</summary>
private SGame GameInstance;
@@ -115,6 +118,7 @@ namespace StardewModdingAPI
}
/// <summary>Launch SMAPI.</summary>
+ [HandleProcessCorruptedStateExceptions, SecurityCritical] // let try..catch handle corrupted state exceptions
public void RunInteractively()
{
// initialise SMAPI
@@ -123,7 +127,9 @@ namespace StardewModdingAPI
// init logging
this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} on {this.GetFriendlyPlatformName()}", LogLevel.Info);
this.Monitor.Log($"Mods go here: {Constants.ModPath}");
+#if !SMAPI_2_0
this.Monitor.Log("Preparing SMAPI...");
+#endif
// validate paths
this.VerifyPath(Constants.ModPath);
@@ -207,7 +213,11 @@ namespace StardewModdingAPI
}
// start game
+#if SMAPI_2_0
+ this.Monitor.Log("Starting game...", LogLevel.Trace);
+#else
this.Monitor.Log("Starting game...");
+#endif
try
{
this.IsGameRunning = true;
@@ -224,6 +234,7 @@ namespace StardewModdingAPI
}
}
+#if !SMAPI_2_0
/// <summary>Get a monitor for legacy code which doesn't have one passed in.</summary>
[Obsolete("This method should only be used when needed for backwards compatibility.")]
internal IMonitor GetLegacyMonitorForMod()
@@ -231,6 +242,7 @@ namespace StardewModdingAPI
string modName = this.ModRegistry.GetModFromStack() ?? "unknown";
return this.GetSecondaryMonitor(modName);
}
+#endif
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
@@ -321,17 +333,18 @@ namespace StardewModdingAPI
this.DeprecationManager = new DeprecationManager(this.Monitor, this.ModRegistry);
this.CommandManager = new CommandManager();
+#if !SMAPI_2_0
// inject compatibility shims
#pragma warning disable 618
Command.Shim(this.CommandManager, this.DeprecationManager, this.ModRegistry);
Config.Shim(this.DeprecationManager);
Log.Shim(this.DeprecationManager, this.GetSecondaryMonitor("legacy mod"), this.ModRegistry);
Mod.Shim(this.DeprecationManager);
- ContentEvents.Shim(this.ModRegistry, this.Monitor);
GameEvents.Shim(this.DeprecationManager);
PlayerEvents.Shim(this.DeprecationManager);
TimeEvents.Shim(this.DeprecationManager);
#pragma warning restore 618
+#endif
// redirect direct console output
{
@@ -344,6 +357,9 @@ namespace StardewModdingAPI
if (this.Settings.DeveloperMode)
{
this.Monitor.ShowTraceInConsole = true;
+#if SMAPI_2_0
+ this.Monitor.ShowFullStampInConsole = true;
+#endif
this.Monitor.Log($"You configured SMAPI to run in developer mode. The console may be much more verbose. You can disable developer mode by installing the non-developer version of SMAPI, or by editing {Constants.ApiConfigPath}.", LogLevel.Info);
}
if (!this.Settings.CheckForUpdates)
@@ -355,19 +371,23 @@ namespace StardewModdingAPI
// validate XNB integrity
if (!this.ValidateContentIntegrity())
- this.Monitor.Log("SMAPI found problems in the game's XNB files which may cause errors or crashes while you're playing. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Warn);
+ this.Monitor.Log("SMAPI found problems in your game's content files which are likely to cause errors or crashes. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Error);
// load mods
- int modsLoaded;
{
+#if SMAPI_2_0
+ this.Monitor.Log("Loading mod metadata...", LogLevel.Trace);
+#else
this.Monitor.Log("Loading mod metadata...");
+#endif
ModResolver resolver = new ModResolver();
// load manifests
- IModMetadata[] mods = resolver.ReadManifests(Constants.ModPath, new JsonHelper(), this.Settings.ModCompatibility).ToArray();
+ IModMetadata[] mods = resolver.ReadManifests(Constants.ModPath, new JsonHelper(), this.Settings.ModCompatibility, this.Settings.DisabledMods).ToArray();
resolver.ValidateManifests(mods, Constants.ApiVersion);
// check for deprecated metadata
+#if !SMAPI_2_0
IList<Action> deprecationWarnings = new List<Action>();
foreach (IModMetadata mod in mods.Where(m => m.Status != ModMetadataStatus.Failed))
{
@@ -389,7 +409,7 @@ namespace StardewModdingAPI
// per-save directories
if ((mod.Manifest as Manifest)?.PerSaveConfigs == true)
{
- deprecationWarnings.Add(() => this.DeprecationManager.Warn(mod.DisplayName, $"{nameof(Manifest)}.{nameof(Manifest.PerSaveConfigs)}", "1.0", DeprecationLevel.Info));
+ deprecationWarnings.Add(() => this.DeprecationManager.Warn(mod.DisplayName, $"{nameof(Manifest)}.{nameof(Manifest.PerSaveConfigs)}", "1.0", DeprecationLevel.PendingRemoval));
try
{
string psDir = Path.Combine(mod.DirectoryPath, "psconfigs");
@@ -403,14 +423,19 @@ namespace StardewModdingAPI
}
}
}
+#endif
// process dependencies
mods = resolver.ProcessDependencies(mods).ToArray();
// load mods
- modsLoaded = this.LoadMods(mods, new JsonHelper(), this.ContentManager, deprecationWarnings);
+#if SMAPI_2_0
+ this.LoadMods(mods, new JsonHelper(), this.ContentManager);
+#else
+ this.LoadMods(mods, new JsonHelper(), this.ContentManager, deprecationWarnings);
foreach (Action warning in deprecationWarnings)
warning();
+#endif
}
if (this.Monitor.IsExiting)
{
@@ -419,6 +444,7 @@ namespace StardewModdingAPI
}
// update window titles
+ int modsLoaded = this.ModRegistry.GetMods().Count();
this.GameInstance.Window.Title = $"Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} - running SMAPI {Constants.ApiVersion} with {modsLoaded} mods";
Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} with {modsLoaded} mods";
@@ -443,7 +469,9 @@ namespace StardewModdingAPI
private void RunConsoleLoop()
{
// prepare console
+#if !SMAPI_2_0
this.Monitor.Log("Starting console...");
+#endif
this.Monitor.Log("Type 'help' for help, or 'help <cmd>' for a command's usage", LogLevel.Info);
this.CommandManager.Add("SMAPI", "help", "Lists command documentation.\n\nUsage: help\nLists all available commands.\n\nUsage: help <cmd>\n- cmd: The name of a command whose documentation to display.", this.HandleCommand);
this.CommandManager.Add("SMAPI", "reload_i18n", "Reloads translation files for all mods.\n\nUsage: reload_i18n", this.HandleCommand);
@@ -483,20 +511,21 @@ namespace StardewModdingAPI
/// <returns>Returns whether all integrity checks passed.</returns>
private bool ValidateContentIntegrity()
{
- this.Monitor.Log("Detecting common issues...");
+ this.Monitor.Log("Detecting common issues...", LogLevel.Trace);
bool issuesFound = false;
-
// object format (commonly broken by outdated files)
{
- void LogIssue(int id, string issue) => this.Monitor.Log($"Detected issue: item #{id} in Content\\Data\\ObjectInformation is invalid ({issue}).", LogLevel.Warn);
+ // detect issues
+ bool hasObjectIssues = false;
+ void LogIssue(int id, string issue) => this.Monitor.Log($@"Detected issue: item #{id} in Content\Data\ObjectInformation.xnb is invalid ({issue}).", LogLevel.Trace);
foreach (KeyValuePair<int, string> entry in Game1.objectInformation)
{
// must not be empty
if (string.IsNullOrWhiteSpace(entry.Value))
{
LogIssue(entry.Key, "entry is empty");
- issuesFound = true;
+ hasObjectIssues = true;
continue;
}
@@ -505,7 +534,7 @@ namespace StardewModdingAPI
if (fields.Length < SObject.objectInfoDescriptionIndex + 1)
{
LogIssue(entry.Key, "too few fields for an object");
- issuesFound = true;
+ hasObjectIssues = true;
continue;
}
@@ -516,11 +545,18 @@ namespace StardewModdingAPI
if (fields.Length < SObject.objectInfoBuffDurationIndex + 1)
{
LogIssue(entry.Key, "too few fields for a cooking item");
- issuesFound = true;
+ hasObjectIssues = true;
}
break;
}
}
+
+ // log error
+ if (hasObjectIssues)
+ {
+ issuesFound = true;
+ this.Monitor.Log(@"Your Content\Data\ObjectInformation.xnb file seems to be broken or outdated.", LogLevel.Warn);
+ }
}
return !issuesFound;
@@ -567,125 +603,221 @@ namespace StardewModdingAPI
/// <param name="mods">The mods to load.</param>
/// <param name="jsonHelper">The JSON helper with which to read mods' JSON files.</param>
/// <param name="contentManager">The content manager to use for mod content.</param>
+#if !SMAPI_2_0
/// <param name="deprecationWarnings">A list to populate with any deprecation warnings.</param>
- /// <returns>Returns the number of mods successfully loaded.</returns>
- private int LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager, IList<Action> deprecationWarnings)
+ private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager, IList<Action> deprecationWarnings)
+#else
+ private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager)
+#endif
{
+#if SMAPI_2_0
+ this.Monitor.Log("Loading mods...", LogLevel.Trace);
+#else
this.Monitor.Log("Loading mods...");
- void LogSkip(IModMetadata mod, string reasonPhrase, LogLevel level = LogLevel.Error) => this.Monitor.Log($"Skipped {mod.DisplayName} because {reasonPhrase}", level);
-
+#endif
// load mod assemblies
- int modsLoaded = 0;
- AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.TargetPlatform, this.Monitor);
- AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => modAssemblyLoader.ResolveAssembly(e.Name);
- foreach (IModMetadata metadata in mods)
+ IDictionary<IModMetadata, string> skippedMods = new Dictionary<IModMetadata, string>();
{
- // validate status
- if (metadata.Status == ModMetadataStatus.Failed)
- {
- LogSkip(metadata, metadata.Error);
- continue;
- }
-
- // get basic info
- IManifest manifest = metadata.Manifest;
- string assemblyPath = Path.Combine(metadata.DirectoryPath, metadata.Manifest.EntryDll);
+ void TrackSkip(IModMetadata mod, string reasonPhrase) => skippedMods[mod] = reasonPhrase;
- // preprocess & load mod assembly
- Assembly modAssembly;
- try
- {
- modAssembly = modAssemblyLoader.Load(assemblyPath, assumeCompatible: metadata.Compatibility?.Compatibility == ModCompatibilityType.AssumeCompatible);
- }
- catch (IncompatibleInstructionException ex)
- {
- LogSkip(metadata, $"it's not compatible with the latest version of the game (detected {ex.NounPhrase}). Please check for a newer version of the mod (you have v{manifest.Version}).");
- continue;
- }
- catch (Exception ex)
+ AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.TargetPlatform, this.Monitor);
+ AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => modAssemblyLoader.ResolveAssembly(e.Name);
+ foreach (IModMetadata metadata in mods)
{
- LogSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded:\n{ex.GetLogSummary()}");
- continue;
- }
+ // get basic info
+ IManifest manifest = metadata.Manifest;
+ string assemblyPath = metadata.Manifest?.EntryDll != null
+ ? Path.Combine(metadata.DirectoryPath, metadata.Manifest.EntryDll)
+ : null;
+ this.Monitor.Log(assemblyPath != null
+ ? $"Loading {metadata.DisplayName} from {assemblyPath.Replace(Constants.ModPath, "").TrimStart(Path.DirectorySeparatorChar)}..."
+ : $"Loading {metadata.DisplayName}...", LogLevel.Trace);
+
+ // validate status
+ if (metadata.Status == ModMetadataStatus.Failed)
+ {
+ this.Monitor.Log($" Failed: {metadata.Error}", LogLevel.Trace);
+ TrackSkip(metadata, metadata.Error);
+ continue;
+ }
- // validate assembly
- try
- {
- int modEntries = modAssembly.DefinedTypes.Count(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract);
- if (modEntries == 0)
+ // preprocess & load mod assembly
+ Assembly modAssembly;
+ try
{
- LogSkip(metadata, $"its DLL has no '{nameof(Mod)}' subclass.");
+ modAssembly = modAssemblyLoader.Load(assemblyPath, assumeCompatible: metadata.Compatibility?.Compatibility == ModCompatibilityType.AssumeCompatible);
+ }
+ catch (IncompatibleInstructionException ex)
+ {
+ TrackSkip(metadata, $"it's not compatible with the latest version of the game or SMAPI (detected {ex.NounPhrase}). Please check for a newer version of the mod.");
continue;
}
- if (modEntries > 1)
+ catch (Exception ex)
{
- LogSkip(metadata, $"its DLL contains multiple '{nameof(Mod)}' subclasses.");
+ TrackSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded:\n{ex.GetLogSummary()}");
continue;
}
- }
- catch (Exception ex)
- {
- LogSkip(metadata, $"its DLL couldn't be loaded:\n{ex.GetLogSummary()}");
- continue;
- }
- // initialise mod
- try
- {
- // get implementation
- TypeInfo modEntryType = modAssembly.DefinedTypes.First(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract);
- Mod mod = (Mod)modAssembly.CreateInstance(modEntryType.ToString());
- if (mod == null)
+ // validate assembly
+ try
{
- LogSkip(metadata, "its entry class couldn't be instantiated.");
+ int modEntries = modAssembly.DefinedTypes.Count(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract);
+ if (modEntries == 0)
+ {
+ TrackSkip(metadata, $"its DLL has no '{nameof(Mod)}' subclass.");
+ continue;
+ }
+ if (modEntries > 1)
+ {
+ TrackSkip(metadata, $"its DLL contains multiple '{nameof(Mod)}' subclasses.");
+ continue;
+ }
+ }
+ catch (Exception ex)
+ {
+ TrackSkip(metadata, $"its DLL couldn't be loaded:\n{ex.GetLogSummary()}");
continue;
}
- // inject data
- mod.ModManifest = manifest;
- mod.Helper = new ModHelper(metadata.DisplayName, metadata.DirectoryPath, jsonHelper, this.ModRegistry, this.CommandManager, contentManager, this.Reflection);
- mod.Monitor = this.GetSecondaryMonitor(metadata.DisplayName);
- mod.PathOnDisk = metadata.DirectoryPath;
-
- // track mod
- metadata.SetMod(mod);
- this.ModRegistry.Add(metadata);
- modsLoaded++;
- this.Monitor.Log($"Loaded {metadata.DisplayName} by {manifest.Author}, v{manifest.Version} | {manifest.Description}", LogLevel.Info);
+ // initialise mod
+ try
+ {
+ // get implementation
+ TypeInfo modEntryType = modAssembly.DefinedTypes.First(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract);
+ Mod mod = (Mod)modAssembly.CreateInstance(modEntryType.ToString());
+ if (mod == null)
+ {
+ TrackSkip(metadata, "its entry class couldn't be instantiated.");
+ continue;
+ }
+
+#if !SMAPI_2_0
+ // prevent mods from using SMAPI 2.0 content interception before release
+ // ReSharper disable SuspiciousTypeConversion.Global
+ if (mod is IAssetEditor || mod is IAssetLoader)
+ {
+ TrackSkip(metadata, $"its entry class implements {nameof(IAssetEditor)} or {nameof(IAssetLoader)}. These are part of a prototype API that isn't available for mods to use yet.");
+ }
+ // ReSharper restore SuspiciousTypeConversion.Global
+#endif
+
+ // inject data
+ {
+ ICommandHelper commandHelper = new CommandHelper(manifest.UniqueID, metadata.DisplayName, this.CommandManager);
+ IContentHelper contentHelper = new ContentHelper(contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName);
+ IReflectionHelper reflectionHelper = new ReflectionHelper(manifest.UniqueID, this.Reflection);
+ IModRegistry modRegistryHelper = new ModRegistryHelper(manifest.UniqueID, this.ModRegistry);
+ ITranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentManager.GetLocale(), contentManager.GetCurrentLanguage());
+
+ mod.ModManifest = manifest;
+ mod.Helper = new ModHelper(manifest.UniqueID, metadata.DirectoryPath, jsonHelper, contentHelper, commandHelper, modRegistryHelper, reflectionHelper, translationHelper);
+ mod.Monitor = this.GetSecondaryMonitor(metadata.DisplayName);
+#if !SMAPI_2_0
+ mod.PathOnDisk = metadata.DirectoryPath;
+#endif
+ }
+
+ // track mod
+ metadata.SetMod(mod);
+ this.ModRegistry.Add(metadata);
+ }
+ catch (Exception ex)
+ {
+ TrackSkip(metadata, $"initialisation failed:\n{ex.GetLogSummary()}");
+ }
}
- catch (Exception ex)
+ }
+ IModMetadata[] loadedMods = this.ModRegistry.GetMods().ToArray();
+
+ // log skipped mods
+#if SMAPI_2_0
+ this.Monitor.Newline();
+#endif
+ if (skippedMods.Any())
+ {
+ this.Monitor.Log($"Skipped {skippedMods.Count} mods:", LogLevel.Error);
+ foreach (var pair in skippedMods.OrderBy(p => p.Key.DisplayName))
{
- LogSkip(metadata, $"initialisation failed:\n{ex.GetLogSummary()}");
+ IModMetadata mod = pair.Key;
+ string reason = pair.Value;
+
+ if (mod.Manifest?.Version != null)
+ this.Monitor.Log($" {mod.DisplayName} {mod.Manifest.Version} because {reason}", LogLevel.Error);
+ else
+ this.Monitor.Log($" {mod.DisplayName} because {reason}", LogLevel.Error);
}
+#if SMAPI_2_0
+ this.Monitor.Newline();
+#endif
}
+ // log loaded mods
+ this.Monitor.Log($"Loaded {loadedMods.Length} mods" + (loadedMods.Length > 0 ? ":" : "."), LogLevel.Info);
+ foreach (IModMetadata metadata in loadedMods.OrderBy(p => p.DisplayName))
+ {
+ IManifest manifest = metadata.Manifest;
+ this.Monitor.Log(
+ $" {metadata.DisplayName} {manifest.Version}"
+ + (!string.IsNullOrWhiteSpace(manifest.Author) ? $" by {manifest.Author}" : "")
+ + (!string.IsNullOrWhiteSpace(manifest.Description) ? $" | {manifest.Description}" : ""),
+ LogLevel.Info
+ );
+ }
+#if SMAPI_2_0
+ this.Monitor.Newline();
+#endif
+
// initialise translations
this.ReloadTranslations();
// initialise loaded mods
- foreach (IModMetadata metadata in this.ModRegistry.GetMods())
+ foreach (IModMetadata metadata in loadedMods)
{
+ // add interceptors
+ if (metadata.Mod.Helper.Content is ContentHelper helper)
+ {
+ this.ContentManager.Editors[metadata] = helper.ObservableAssetEditors;
+ this.ContentManager.Loaders[metadata] = helper.ObservableAssetLoaders;
+ }
+
+ // call entry method
try
{
IMod mod = metadata.Mod;
-
- // call entry methods
- (mod as Mod)?.Entry(); // deprecated since 1.0
mod.Entry(mod.Helper);
+#if !SMAPI_2_0
+ (mod as Mod)?.Entry(); // deprecated since 1.0
// raise deprecation warning for old Entry() methods
if (this.DeprecationManager.IsVirtualMethodImplemented(mod.GetType(), typeof(Mod), nameof(Mod.Entry), new[] { typeof(object[]) }))
- deprecationWarnings.Add(() => this.DeprecationManager.Warn(metadata.DisplayName, $"{nameof(Mod)}.{nameof(Mod.Entry)}(object[]) instead of {nameof(Mod)}.{nameof(Mod.Entry)}({nameof(IModHelper)})", "1.0", DeprecationLevel.Info));
+ deprecationWarnings.Add(() => this.DeprecationManager.Warn(metadata.DisplayName, $"{nameof(Mod)}.{nameof(Mod.Entry)}(object[]) instead of {nameof(Mod)}.{nameof(Mod.Entry)}({nameof(IModHelper)})", "1.0", DeprecationLevel.PendingRemoval));
+#endif
}
catch (Exception ex)
{
- this.Monitor.Log($"The {metadata.DisplayName} mod failed on entry initialisation. It will still be loaded, but may not function correctly.\n{ex.GetLogSummary()}", LogLevel.Warn);
+ this.Monitor.Log($"{metadata.DisplayName} failed on entry and might not work correctly. Technical details:\n{ex.GetLogSummary()}", LogLevel.Error);
}
}
- // print result
- this.Monitor.Log($"Loaded {modsLoaded} mods.");
- return modsLoaded;
+ // reset cache when needed
+ // only register listeners after Entry to avoid repeatedly reloading assets during load
+ foreach (IModMetadata metadata in loadedMods)
+ {
+ if (metadata.Mod.Helper.Content is ContentHelper helper)
+ {
+ helper.ObservableAssetEditors.CollectionChanged += (sender, e) =>
+ {
+ if (e.NewItems.Count > 0)
+ this.ContentManager.Reset();
+ };
+ helper.ObservableAssetLoaders.CollectionChanged += (sender, e) =>
+ {
+ if (e.NewItems.Count > 0)
+ this.ContentManager.Reset();
+ };
+ }
+ }
+ this.ContentManager.Reset();
}
/// <summary>Reload translations for all mods.</summary>
@@ -737,8 +869,22 @@ namespace StardewModdingAPI
}
else
{
+#if SMAPI_2_0
+ string message = "The following commands are registered:\n";
+ IGrouping<string, string>[] groups = (from command in this.CommandManager.GetAll() orderby command.ModName, command.Name group command.Name by command.ModName).ToArray();
+ foreach (var group in groups)
+ {
+ string modName = group.Key;
+ string[] commandNames = group.ToArray();
+ message += $"{modName}:\n {string.Join("\n ", commandNames)}\n\n";
+ }
+ message += "For more information about a command, type 'help command_name'.";
+
+ this.Monitor.Log(message, LogLevel.Info);
+#else
this.Monitor.Log("The following commands are registered: " + string.Join(", ", this.CommandManager.GetAll().Select(p => p.Name)) + ".", LogLevel.Info);
this.Monitor.Log("For more information about a command, type 'help command_name'.", LogLevel.Info);
+#endif
}
break;
@@ -783,7 +929,14 @@ namespace StardewModdingAPI
/// <param name="name">The name of the module which will log messages with this instance.</param>
private Monitor GetSecondaryMonitor(string name)
{
- return new Monitor(name, this.ConsoleManager, this.LogFile, this.CancellationTokenSource) { WriteToConsole = this.Monitor.WriteToConsole, ShowTraceInConsole = this.Settings.DeveloperMode };
+ return new Monitor(name, this.ConsoleManager, this.LogFile, this.CancellationTokenSource)
+ {
+ WriteToConsole = this.Monitor.WriteToConsole,
+ ShowTraceInConsole = this.Settings.DeveloperMode,
+#if SMAPI_2_0
+ ShowFullStampInConsole = this.Settings.DeveloperMode
+#endif
+ };
}
/// <summary>Get a human-readable name for the current platform.</summary>
diff --git a/src/StardewModdingAPI/SemanticVersion.cs b/src/StardewModdingAPI/SemanticVersion.cs
index a2adb657..4b27c819 100644
--- a/src/StardewModdingAPI/SemanticVersion.cs
+++ b/src/StardewModdingAPI/SemanticVersion.cs
@@ -10,8 +10,14 @@ namespace StardewModdingAPI
** Properties
*********/
/// <summary>A regular expression matching a semantic version string.</summary>
- /// <remarks>Derived from https://github.com/maxhauser/semver.</remarks>
- private static readonly Regex Regex = new Regex(@"^(?<major>\d+)(\.(?<minor>\d+))?(\.(?<patch>\d+))?(?<build>.*)$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
+ /// <remarks>
+ /// This pattern is derived from the BNF documentation in the <a href="https://github.com/mojombo/semver">semver repo</a>,
+ /// with three important deviations intended to support Stardew Valley mod conventions:
+ /// - allows short-form "x.y" versions;
+ /// - allows hyphens in prerelease tags as synonyms for dots (like "-unofficial-update.3");
+ /// - doesn't allow '+build' suffixes.
+ /// </remarks>
+ private static readonly Regex Regex = new Regex(@"^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)(\.(?<patch>0|[1-9]\d*))?(?:-(?<prerelease>([a-z0-9]+[\-\.]?)+))?$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture);
/*********
@@ -48,17 +54,22 @@ namespace StardewModdingAPI
/// <summary>Construct an instance.</summary>
/// <param name="version">The semantic version string.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="version"/> is null.</exception>
/// <exception cref="FormatException">The <paramref name="version"/> is not a valid semantic version.</exception>
public SemanticVersion(string version)
{
- var match = SemanticVersion.Regex.Match(version);
+ // parse
+ if (version == null)
+ throw new ArgumentNullException(nameof(version), "The input version string can't be null.");
+ var match = SemanticVersion.Regex.Match(version.Trim());
if (!match.Success)
- throw new FormatException($"The input '{version}' is not a valid semantic version.");
+ throw new FormatException($"The input '{version}' isn't a valid semantic version.");
+ // initialise
this.MajorVersion = int.Parse(match.Groups["major"].Value);
this.MinorVersion = match.Groups["minor"].Success ? int.Parse(match.Groups["minor"].Value) : 0;
this.PatchVersion = match.Groups["patch"].Success ? int.Parse(match.Groups["patch"].Value) : 0;
- this.Build = match.Groups["build"].Success ? this.GetNormalisedTag(match.Groups["build"].Value) : null;
+ this.Build = match.Groups["prerelease"].Success ? this.GetNormalisedTag(match.Groups["prerelease"].Value) : null;
}
/// <summary>Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version.</summary>
@@ -93,8 +104,8 @@ namespace StardewModdingAPI
return curOlder;
// compare two pre-release tag values
- string[] curParts = this.Build.Split('.');
- string[] otherParts = other.Build.Split('.');
+ string[] curParts = this.Build.Split('.', '-');
+ string[] otherParts = other.Build.Split('.', '-');
for (int i = 0; i < curParts.Length; i++)
{
// longer prerelease tag supercedes if otherwise equal
@@ -200,6 +211,7 @@ namespace StardewModdingAPI
}
}
+
/*********
** Private methods
*********/
@@ -207,11 +219,9 @@ namespace StardewModdingAPI
/// <param name="tag">The tag to normalise.</param>
private string GetNormalisedTag(string tag)
{
- tag = tag?.Trim().Trim('-', '.');
- if (string.IsNullOrWhiteSpace(tag))
+ tag = tag?.Trim();
+ if (string.IsNullOrWhiteSpace(tag) || tag == "0") // '0' from incorrect examples in old SMAPI documentation
return null;
- if (tag == "0")
- return null; // from incorrect examples in old SMAPI documentation
return tag;
}
}
diff --git a/src/StardewModdingAPI/StardewModdingAPI.config.json b/src/StardewModdingAPI/StardewModdingAPI.config.json
index f62db90c..4e871636 100644
--- a/src/StardewModdingAPI/StardewModdingAPI.config.json
+++ b/src/StardewModdingAPI/StardewModdingAPI.config.json
@@ -27,6 +27,23 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha
"VerboseLogging": false,
/**
+ * A list of mods SMAPI should consider obsolete and not load. Changing this field is not
+ * recommended and may destabilise your game.
+ */
+ "DisabledMods": [
+ {
+ "Name": "Modder Serialization Utility",
+ "ID": [ "SerializerUtils-0-1" ],
+ "ReasonPhrase": "it's no longer used by any mods, and is no longer maintained."
+ },
+ {
+ "Name": "StarDustCore",
+ "ID": [ "StarDustCore" ],
+ "ReasonPhrase": "it was only used by earlier versions of Save Anywhere (which no longer uses it), and is no longer maintained."
+ }
+ ],
+
+ /**
* A list of mod versions SMAPI should consider compatible or broken regardless of whether it
* detects incompatible code. Each record can be set to `AssumeCompatible` or `AssumeBroken`.
* Changing this field is not recommended and may destabilise your game.
@@ -316,14 +333,6 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha
"Notes": "Needs update for SDV 1.2."
},
{
- "Name": "StarDustCore",
- "ID": [ "StarDustCore" ],
- "UpperVersion": "1.0",
- "Compatibility": "AssumeBroken",
- "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/683",
- "Notes": "Obsolete (originally needed by Save Anywhere); broken in SDV 1.2."
- },
- {
"Name": "Teleporter",
"ID": [ "Teleporter" ],
"UpperVersion": "1.0.2",
diff --git a/src/StardewModdingAPI/StardewModdingAPI.csproj b/src/StardewModdingAPI/StardewModdingAPI.csproj
index ae454a35..f778660d 100644
--- a/src/StardewModdingAPI/StardewModdingAPI.csproj
+++ b/src/StardewModdingAPI/StardewModdingAPI.csproj
@@ -93,7 +93,10 @@
<Compile Include="Command.cs" />
<Compile Include="ContentSource.cs" />
<Compile Include="Events\ContentEvents.cs" />
+ <Compile Include="Events\EventArgsInput.cs" />
<Compile Include="Events\EventArgsValueChanged.cs" />
+ <Compile Include="Events\InputEvents.cs" />
+ <Compile Include="Framework\Content\AssetInfo.cs" />
<Compile Include="Framework\Exceptions\SContentLoadException.cs" />
<Compile Include="Framework\Command.cs" />
<Compile Include="Config.cs" />
@@ -124,6 +127,14 @@
<Compile Include="Events\GraphicsEvents.cs" />
<Compile Include="Framework\Countdown.cs" />
<Compile Include="Framework\IModMetadata.cs" />
+ <Compile Include="Framework\Models\DisabledMod.cs" />
+ <Compile Include="Framework\ModHelpers\BaseHelper.cs" />
+ <Compile Include="Framework\ModHelpers\CommandHelper.cs" />
+ <Compile Include="Framework\ModHelpers\ContentHelper.cs" />
+ <Compile Include="Framework\ModHelpers\ModHelper.cs" />
+ <Compile Include="Framework\ModHelpers\ModRegistryHelper.cs" />
+ <Compile Include="Framework\ModHelpers\ReflectionHelper.cs" />
+ <Compile Include="Framework\ModHelpers\TranslationHelper.cs" />
<Compile Include="Framework\ModLoading\InvalidModStateException.cs" />
<Compile Include="Framework\ModLoading\ModDependencyStatus.cs" />
<Compile Include="Framework\ModLoading\ModMetadataStatus.cs" />
@@ -131,15 +142,13 @@
<Compile Include="Framework\ModLoading\AssemblyDefinitionResolver.cs" />
<Compile Include="Framework\ModLoading\AssemblyParseResult.cs" />
<Compile Include="Framework\CommandManager.cs" />
- <Compile Include="Framework\ContentHelper.cs" />
- <Compile Include="Framework\Content\ContentEventData.cs" />
- <Compile Include="Framework\Content\ContentEventHelper.cs" />
- <Compile Include="Framework\Content\ContentEventHelperForDictionary.cs" />
- <Compile Include="Framework\Content\ContentEventHelperForImage.cs" />
+ <Compile Include="Framework\Content\AssetData.cs" />
+ <Compile Include="Framework\Content\AssetDataForObject.cs" />
+ <Compile Include="Framework\Content\AssetDataForDictionary.cs" />
+ <Compile Include="Framework\Content\AssetDataForImage.cs" />
<Compile Include="Context.cs" />
<Compile Include="Framework\Logging\ConsoleInterceptionManager.cs" />
<Compile Include="Framework\Logging\InterceptingTextWriter.cs" />
- <Compile Include="Framework\CommandHelper.cs" />
<Compile Include="Framework\Models\ManifestDependency.cs" />
<Compile Include="Framework\Models\ModCompatibilityType.cs" />
<Compile Include="Framework\Models\SConfig.cs" />
@@ -147,15 +156,17 @@
<Compile Include="Framework\Reflection\PrivateProperty.cs" />
<Compile Include="Framework\RequestExitDelegate.cs" />
<Compile Include="Framework\SContentManager.cs" />
+ <Compile Include="Framework\Exceptions\SParseException.cs" />
<Compile Include="Framework\Serialisation\JsonHelper.cs" />
<Compile Include="Framework\Serialisation\SelectiveStringEnumConverter.cs" />
<Compile Include="Framework\Serialisation\ManifestFieldConverter.cs" />
- <Compile Include="Framework\TranslationHelper.cs" />
+ <Compile Include="IAssetEditor.cs" />
+ <Compile Include="IAssetInfo.cs" />
+ <Compile Include="IAssetLoader.cs" />
<Compile Include="ICommandHelper.cs" />
- <Compile Include="IContentEventData.cs" />
- <Compile Include="IContentEventHelper.cs" />
- <Compile Include="IContentEventHelperForDictionary.cs" />
- <Compile Include="IContentEventHelperForImage.cs" />
+ <Compile Include="IAssetData.cs" />
+ <Compile Include="IAssetDataForDictionary.cs" />
+ <Compile Include="IAssetDataForImage.cs" />
<Compile Include="IContentHelper.cs" />
<Compile Include="IManifestDependency.cs" />
<Compile Include="IModRegistry.cs" />
@@ -173,10 +184,11 @@
<Compile Include="Framework\Reflection\CacheEntry.cs" />
<Compile Include="Framework\Reflection\PrivateField.cs" />
<Compile Include="Framework\Reflection\PrivateMethod.cs" />
- <Compile Include="Framework\Reflection\ReflectionHelper.cs" />
+ <Compile Include="Framework\Reflection\Reflector.cs" />
<Compile Include="IManifest.cs" />
<Compile Include="IMod.cs" />
<Compile Include="IModHelper.cs" />
+ <Compile Include="IModLinked.cs" />
<Compile Include="Framework\Logging\LogFileManager.cs" />
<Compile Include="IPrivateProperty.cs" />
<Compile Include="ISemanticVersion.cs" />
@@ -192,7 +204,6 @@
<Compile Include="Framework\Monitor.cs" />
<Compile Include="Framework\Models\Manifest.cs" />
<Compile Include="Mod.cs" />
- <Compile Include="Framework\ModHelper.cs" />
<Compile Include="PatchMode.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
@@ -202,6 +213,10 @@
<Compile Include="IReflectionHelper.cs" />
<Compile Include="SemanticVersion.cs" />
<Compile Include="Translation.cs" />
+ <Compile Include="ICursorPosition.cs" />
+ <Compile Include="Utilities\SDate.cs" />
+ <Compile Include="Utilities\SButton.cs" />
+ <Compile Include="Framework\CursorPosition.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config">
@@ -269,8 +284,8 @@
<StartProgram>$(GamePath)\StardewModdingAPI.exe</StartProgram>
<StartWorkingDirectory>$(GamePath)</StartWorkingDirectory>
</PropertyGroup>
-
+
<!-- Somehow this makes Visual Studio for Mac recognise the previous section. -->
<!-- Nobody knows why. -->
<PropertyGroup Condition="'$(RunConfiguration)' == 'Default'" />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/StardewModdingAPI/Utilities/SButton.cs b/src/StardewModdingAPI/Utilities/SButton.cs
new file mode 100644
index 00000000..f4fccfff
--- /dev/null
+++ b/src/StardewModdingAPI/Utilities/SButton.cs
@@ -0,0 +1,659 @@
+using System;
+using Microsoft.Xna.Framework.Input;
+
+namespace StardewModdingAPI.Utilities
+{
+ /// <summary>A unified button constant which includes all controller, keyboard, and mouse buttons.</summary>
+ /// <remarks>Derived from <see cref="Keys"/>, <see cref="Buttons"/>, and <see cref="System.Windows.Forms.MouseButtons"/>.</remarks>
+#if SMAPI_2_0
+ public
+#else
+ internal
+#endif
+ enum SButton
+ {
+ /// <summary>No valid key.</summary>
+ None = 0,
+
+ /*********
+ ** Mouse
+ *********/
+ /// <summary>The left mouse button.</summary>
+ MouseLeft = 1000,
+
+ /// <summary>The right mouse button.</summary>
+ MouseRight = 1001,
+
+ /// <summary>The middle mouse button.</summary>
+ MouseMiddle = 1002,
+
+ /// <summary>The first mouse XButton.</summary>
+ MouseX1 = 1003,
+
+ /// <summary>The second mouse XButton.</summary>
+ MouseX2 = 1004,
+
+ /*********
+ ** Controller
+ *********/
+ /// <summary>The 'A' button on a controller.</summary>
+ ControllerA = SButtonExtensions.ControllerOffset + Buttons.A,
+
+ /// <summary>The 'B' button on a controller.</summary>
+ ControllerB = SButtonExtensions.ControllerOffset + Buttons.B,
+
+ /// <summary>The 'X' button on a controller.</summary>
+ ControllerX = SButtonExtensions.ControllerOffset + Buttons.X,
+
+ /// <summary>The 'Y' button on a controller.</summary>
+ ControllerY = SButtonExtensions.ControllerOffset + Buttons.Y,
+
+ /// <summary>The back button on a controller.</summary>
+ ControllerBack = SButtonExtensions.ControllerOffset + Buttons.Back,
+
+ /// <summary>The start button on a controller.</summary>
+ ControllerStart = SButtonExtensions.ControllerOffset + Buttons.Start,
+
+ /// <summary>The up button on the directional pad of a controller.</summary>
+ DPadUp = SButtonExtensions.ControllerOffset + Buttons.DPadUp,
+
+ /// <summary>The down button on the directional pad of a controller.</summary>
+ DPadDown = SButtonExtensions.ControllerOffset + Buttons.DPadDown,
+
+ /// <summary>The left button on the directional pad of a controller.</summary>
+ DPadLeft = SButtonExtensions.ControllerOffset + Buttons.DPadLeft,
+
+ /// <summary>The right button on the directional pad of a controller.</summary>
+ DPadRight = SButtonExtensions.ControllerOffset + Buttons.DPadRight,
+
+ /// <summary>The left bumper (shoulder) button on a controller.</summary>
+ LeftShoulder = SButtonExtensions.ControllerOffset + Buttons.LeftShoulder,
+
+ /// <summary>The right bumper (shoulder) button on a controller.</summary>
+ RightShoulder = SButtonExtensions.ControllerOffset + Buttons.RightShoulder,
+
+ /// <summary>The left trigger on a controller.</summary>
+ LeftTrigger = SButtonExtensions.ControllerOffset + Buttons.LeftTrigger,
+
+ /// <summary>The right trigger on a controller.</summary>
+ RightTrigger = SButtonExtensions.ControllerOffset + Buttons.RightTrigger,
+
+ /// <summary>The left analog stick on a controller (when pressed).</summary>
+ LeftStick = SButtonExtensions.ControllerOffset + Buttons.LeftStick,
+
+ /// <summary>The right analog stick on a controller (when pressed).</summary>
+ RightStick = SButtonExtensions.ControllerOffset + Buttons.RightStick,
+
+ /// <summary>The 'big button' on a controller.</summary>
+ BigButton = SButtonExtensions.ControllerOffset + Buttons.BigButton,
+
+ /// <summary>The left analog stick on a controller (when pushed left).</summary>
+ LeftThumbstickLeft = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickLeft,
+
+ /// <summary>The left analog stick on a controller (when pushed right).</summary>
+ LeftThumbstickRight = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickRight,
+
+ /// <summary>The left analog stick on a controller (when pushed down).</summary>
+ LeftThumbstickDown = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickDown,
+
+ /// <summary>The left analog stick on a controller (when pushed up).</summary>
+ LeftThumbstickUp = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickUp,
+
+ /// <summary>The right analog stick on a controller (when pushed left).</summary>
+ RightThumbstickLeft = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickLeft,
+
+ /// <summary>The right analog stick on a controller (when pushed right).</summary>
+ RightThumbstickRight = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickRight,
+
+ /// <summary>The right analog stick on a controller (when pushed down).</summary>
+ RightThumbstickDown = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickDown,
+
+ /// <summary>The right analog stick on a controller (when pushed up).</summary>
+ RightThumbstickUp = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickUp,
+
+ /*********
+ ** Keyboard
+ *********/
+ /// <summary>The A button on a keyboard.</summary>
+ A = Keys.A,
+
+ /// <summary>The Add button on a keyboard.</summary>
+ Add = Keys.Add,
+
+ /// <summary>The Applications button on a keyboard.</summary>
+ Apps = Keys.Apps,
+
+ /// <summary>The Attn button on a keyboard.</summary>
+ Attn = Keys.Attn,
+
+ /// <summary>The B button on a keyboard.</summary>
+ B = Keys.B,
+
+ /// <summary>The Backspace button on a keyboard.</summary>
+ Back = Keys.Back,
+
+ /// <summary>The Browser Back button on a keyboard in Windows 2000/XP.</summary>
+ BrowserBack = Keys.BrowserBack,
+
+ /// <summary>The Browser Favorites button on a keyboard in Windows 2000/XP.</summary>
+ BrowserFavorites = Keys.BrowserFavorites,
+
+ /// <summary>The Browser Favorites button on a keyboard in Windows 2000/XP.</summary>
+ BrowserForward = Keys.BrowserForward,
+
+ /// <summary>The Browser Home button on a keyboard in Windows 2000/XP.</summary>
+ BrowserHome = Keys.BrowserHome,
+
+ /// <summary>The Browser Refresh button on a keyboard in Windows 2000/XP.</summary>
+ BrowserRefresh = Keys.BrowserRefresh,
+
+ /// <summary>The Browser Search button on a keyboard in Windows 2000/XP.</summary>
+ BrowserSearch = Keys.BrowserSearch,
+
+ /// <summary>The Browser Stop button on a keyboard in Windows 2000/XP.</summary>
+ BrowserStop = Keys.BrowserStop,
+
+ /// <summary>The C button on a keyboard.</summary>
+ C = Keys.C,
+
+ /// <summary>The Caps Lock button on a keyboard.</summary>
+ CapsLock = Keys.CapsLock,
+
+ /// <summary>The Green ChatPad button on a keyboard.</summary>
+ ChatPadGreen = Keys.ChatPadGreen,
+
+ /// <summary>The Orange ChatPad button on a keyboard.</summary>
+ ChatPadOrange = Keys.ChatPadOrange,
+
+ /// <summary>The CrSel button on a keyboard.</summary>
+ Crsel = Keys.Crsel,
+
+ /// <summary>The D button on a keyboard.</summary>
+ D = Keys.D,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D0 = Keys.D0,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D1 = Keys.D1,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D2 = Keys.D2,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D3 = Keys.D3,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D4 = Keys.D4,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D5 = Keys.D5,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D6 = Keys.D6,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D7 = Keys.D7,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D8 = Keys.D8,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ D9 = Keys.D9,
+
+ /// <summary>The Decimal button on a keyboard.</summary>
+ Decimal = Keys.Decimal,
+
+ /// <summary>The Delete button on a keyboard.</summary>
+ Delete = Keys.Delete,
+
+ /// <summary>The Divide button on a keyboard.</summary>
+ Divide = Keys.Divide,
+
+ /// <summary>The Down arrow button on a keyboard.</summary>
+ Down = Keys.Down,
+
+ /// <summary>The E button on a keyboard.</summary>
+ E = Keys.E,
+
+ /// <summary>The End button on a keyboard.</summary>
+ End = Keys.End,
+
+ /// <summary>The Enter button on a keyboard.</summary>
+ Enter = Keys.Enter,
+
+ /// <summary>The Erase EOF button on a keyboard.</summary>
+ EraseEof = Keys.EraseEof,
+
+ /// <summary>The Escape button on a keyboard.</summary>
+ Escape = Keys.Escape,
+
+ /// <summary>The Execute button on a keyboard.</summary>
+ Execute = Keys.Execute,
+
+ /// <summary>The ExSel button on a keyboard.</summary>
+ Exsel = Keys.Exsel,
+
+ /// <summary>The F button on a keyboard.</summary>
+ F = Keys.F,
+
+ /// <summary>The F1 button on a keyboard.</summary>
+ F1 = Keys.F1,
+
+ /// <summary>The F10 button on a keyboard.</summary>
+ F10 = Keys.F10,
+
+ /// <summary>The F11 button on a keyboard.</summary>
+ F11 = Keys.F11,
+
+ /// <summary>The F12 button on a keyboard.</summary>
+ F12 = Keys.F12,
+
+ /// <summary>The F13 button on a keyboard.</summary>
+ F13 = Keys.F13,
+
+ /// <summary>The F14 button on a keyboard.</summary>
+ F14 = Keys.F14,
+
+ /// <summary>The F15 button on a keyboard.</summary>
+ F15 = Keys.F15,
+
+ /// <summary>The F16 button on a keyboard.</summary>
+ F16 = Keys.F16,
+
+ /// <summary>The F17 button on a keyboard.</summary>
+ F17 = Keys.F17,
+
+ /// <summary>The F18 button on a keyboard.</summary>
+ F18 = Keys.F18,
+
+ /// <summary>The F19 button on a keyboard.</summary>
+ F19 = Keys.F19,
+
+ /// <summary>The F2 button on a keyboard.</summary>
+ F2 = Keys.F2,
+
+ /// <summary>The F20 button on a keyboard.</summary>
+ F20 = Keys.F20,
+
+ /// <summary>The F21 button on a keyboard.</summary>
+ F21 = Keys.F21,
+
+ /// <summary>The F22 button on a keyboard.</summary>
+ F22 = Keys.F22,
+
+ /// <summary>The F23 button on a keyboard.</summary>
+ F23 = Keys.F23,
+
+ /// <summary>The F24 button on a keyboard.</summary>
+ F24 = Keys.F24,
+
+ /// <summary>The F3 button on a keyboard.</summary>
+ F3 = Keys.F3,
+
+ /// <summary>The F4 button on a keyboard.</summary>
+ F4 = Keys.F4,
+
+ /// <summary>The F5 button on a keyboard.</summary>
+ F5 = Keys.F5,
+
+ /// <summary>The F6 button on a keyboard.</summary>
+ F6 = Keys.F6,
+
+ /// <summary>The F7 button on a keyboard.</summary>
+ F7 = Keys.F7,
+
+ /// <summary>The F8 button on a keyboard.</summary>
+ F8 = Keys.F8,
+
+ /// <summary>The F9 button on a keyboard.</summary>
+ F9 = Keys.F9,
+
+ /// <summary>The G button on a keyboard.</summary>
+ G = Keys.G,
+
+ /// <summary>The H button on a keyboard.</summary>
+ H = Keys.H,
+
+ /// <summary>The Help button on a keyboard.</summary>
+ Help = Keys.Help,
+
+ /// <summary>The Home button on a keyboard.</summary>
+ Home = Keys.Home,
+
+ /// <summary>The I button on a keyboard.</summary>
+ I = Keys.I,
+
+ /// <summary>The IME Convert button on a keyboard.</summary>
+ ImeConvert = Keys.ImeConvert,
+
+ /// <summary>The IME NoConvert button on a keyboard.</summary>
+ ImeNoConvert = Keys.ImeNoConvert,
+
+ /// <summary>The INS button on a keyboard.</summary>
+ Insert = Keys.Insert,
+
+ /// <summary>The J button on a keyboard.</summary>
+ J = Keys.J,
+
+ /// <summary>The K button on a keyboard.</summary>
+ K = Keys.K,
+
+ /// <summary>The Kana button on a Japanese keyboard.</summary>
+ Kana = Keys.Kana,
+
+ /// <summary>The Kanji button on a Japanese keyboard.</summary>
+ Kanji = Keys.Kanji,
+
+ /// <summary>The L button on a keyboard.</summary>
+ L = Keys.L,
+
+ /// <summary>The Start Applications 1 button on a keyboard in Windows 2000/XP.</summary>
+ LaunchApplication1 = Keys.LaunchApplication1,
+
+ /// <summary>The Start Applications 2 button on a keyboard in Windows 2000/XP.</summary>
+ LaunchApplication2 = Keys.LaunchApplication2,
+
+ /// <summary>The Start Mail button on a keyboard in Windows 2000/XP.</summary>
+ LaunchMail = Keys.LaunchMail,
+
+ /// <summary>The Left arrow button on a keyboard.</summary>
+ Left = Keys.Left,
+
+ /// <summary>The Left Alt button on a keyboard.</summary>
+ LeftAlt = Keys.LeftAlt,
+
+ /// <summary>The Left Control button on a keyboard.</summary>
+ LeftControl = Keys.LeftControl,
+
+ /// <summary>The Left Shift button on a keyboard.</summary>
+ LeftShift = Keys.LeftShift,
+
+ /// <summary>The Left Windows button on a keyboard.</summary>
+ LeftWindows = Keys.LeftWindows,
+
+ /// <summary>The M button on a keyboard.</summary>
+ M = Keys.M,
+
+ /// <summary>The MediaNextTrack button on a keyboard in Windows 2000/XP.</summary>
+ MediaNextTrack = Keys.MediaNextTrack,
+
+ /// <summary>The MediaPlayPause button on a keyboard in Windows 2000/XP.</summary>
+ MediaPlayPause = Keys.MediaPlayPause,
+
+ /// <summary>The MediaPreviousTrack button on a keyboard in Windows 2000/XP.</summary>
+ MediaPreviousTrack = Keys.MediaPreviousTrack,
+
+ /// <summary>The MediaStop button on a keyboard in Windows 2000/XP.</summary>
+ MediaStop = Keys.MediaStop,
+
+ /// <summary>The Multiply button on a keyboard.</summary>
+ Multiply = Keys.Multiply,
+
+ /// <summary>The N button on a keyboard.</summary>
+ N = Keys.N,
+
+ /// <summary>The Num Lock button on a keyboard.</summary>
+ NumLock = Keys.NumLock,
+
+ /// <summary>The Numeric keypad 0 button on a keyboard.</summary>
+ NumPad0 = Keys.NumPad0,
+
+ /// <summary>The Numeric keypad 1 button on a keyboard.</summary>
+ NumPad1 = Keys.NumPad1,
+
+ /// <summary>The Numeric keypad 2 button on a keyboard.</summary>
+ NumPad2 = Keys.NumPad2,
+
+ /// <summary>The Numeric keypad 3 button on a keyboard.</summary>
+ NumPad3 = Keys.NumPad3,
+
+ /// <summary>The Numeric keypad 4 button on a keyboard.</summary>
+ NumPad4 = Keys.NumPad4,
+
+ /// <summary>The Numeric keypad 5 button on a keyboard.</summary>
+ NumPad5 = Keys.NumPad5,
+
+ /// <summary>The Numeric keypad 6 button on a keyboard.</summary>
+ NumPad6 = Keys.NumPad6,
+
+ /// <summary>The Numeric keypad 7 button on a keyboard.</summary>
+ NumPad7 = Keys.NumPad7,
+
+ /// <summary>The Numeric keypad 8 button on a keyboard.</summary>
+ NumPad8 = Keys.NumPad8,
+
+ /// <summary>The Numeric keypad 9 button on a keyboard.</summary>
+ NumPad9 = Keys.NumPad9,
+
+ /// <summary>The O button on a keyboard.</summary>
+ O = Keys.O,
+
+ /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary>
+ Oem8 = Keys.Oem8,
+
+ /// <summary>The OEM Auto button on a keyboard.</summary>
+ OemAuto = Keys.OemAuto,
+
+ /// <summary>The OEM Angle Bracket or Backslash button on the RT 102 keyboard in Windows 2000/XP.</summary>
+ OemBackslash = Keys.OemBackslash,
+
+ /// <summary>The Clear button on a keyboard.</summary>
+ OemClear = Keys.OemClear,
+
+ /// <summary>The OEM Close Bracket button on a US standard keyboard in Windows 2000/XP.</summary>
+ OemCloseBrackets = Keys.OemCloseBrackets,
+
+ /// <summary>The ',' button on a keyboard in any country/region in Windows 2000/XP.</summary>
+ OemComma = Keys.OemComma,
+
+ /// <summary>The OEM Copy button on a keyboard.</summary>
+ OemCopy = Keys.OemCopy,
+
+ /// <summary>The OEM Enlarge Window button on a keyboard.</summary>
+ OemEnlW = Keys.OemEnlW,
+
+ /// <summary>The '-' button on a keyboard in any country/region in Windows 2000/XP.</summary>
+ OemMinus = Keys.OemMinus,
+
+ /// <summary>The OEM Open Bracket button on a US standard keyboard in Windows 2000/XP.</summary>
+ OemOpenBrackets = Keys.OemOpenBrackets,
+
+ /// <summary>The '.' button on a keyboard in any country/region.</summary>
+ OemPeriod = Keys.OemPeriod,
+
+ /// <summary>The OEM Pipe button on a US standard keyboard.</summary>
+ OemPipe = Keys.OemPipe,
+
+ /// <summary>The '+' button on a keyboard in Windows 2000/XP.</summary>
+ OemPlus = Keys.OemPlus,
+
+ /// <summary>The OEM Question Mark button on a US standard keyboard.</summary>
+ OemQuestion = Keys.OemQuestion,
+
+ /// <summary>The OEM Single/Double Quote button on a US standard keyboard.</summary>
+ OemQuotes = Keys.OemQuotes,
+
+ /// <summary>The OEM Semicolon button on a US standard keyboard.</summary>
+ OemSemicolon = Keys.OemSemicolon,
+
+ /// <summary>The OEM Tilde button on a US standard keyboard.</summary>
+ OemTilde = Keys.OemTilde,
+
+ /// <summary>The P button on a keyboard.</summary>
+ P = Keys.P,
+
+ /// <summary>The PA1 button on a keyboard.</summary>
+ Pa1 = Keys.Pa1,
+
+ /// <summary>The Page Down button on a keyboard.</summary>
+ PageDown = Keys.PageDown,
+
+ /// <summary>The Page Up button on a keyboard.</summary>
+ PageUp = Keys.PageUp,
+
+ /// <summary>The Pause button on a keyboard.</summary>
+ Pause = Keys.Pause,
+
+ /// <summary>The Play button on a keyboard.</summary>
+ Play = Keys.Play,
+
+ /// <summary>The Print button on a keyboard.</summary>
+ Print = Keys.Print,
+
+ /// <summary>The Print Screen button on a keyboard.</summary>
+ PrintScreen = Keys.PrintScreen,
+
+ /// <summary>The IME Process button on a keyboard in Windows 95/98/ME/NT 4.0/2000/XP.</summary>
+ ProcessKey = Keys.ProcessKey,
+
+ /// <summary>The Q button on a keyboard.</summary>
+ Q = Keys.Q,
+
+ /// <summary>The R button on a keyboard.</summary>
+ R = Keys.R,
+
+ /// <summary>The Right Arrow button on a keyboard.</summary>
+ Right = Keys.Right,
+
+ /// <summary>The Right Alt button on a keyboard.</summary>
+ RightAlt = Keys.RightAlt,
+
+ /// <summary>The Right Control button on a keyboard.</summary>
+ RightControl = Keys.RightControl,
+
+ /// <summary>The Right Shift button on a keyboard.</summary>
+ RightShift = Keys.RightShift,
+
+ /// <summary>The Right Windows button on a keyboard.</summary>
+ RightWindows = Keys.RightWindows,
+
+ /// <summary>The S button on a keyboard.</summary>
+ S = Keys.S,
+
+ /// <summary>The Scroll Lock button on a keyboard.</summary>
+ Scroll = Keys.Scroll,
+
+ /// <summary>The Select button on a keyboard.</summary>
+ Select = Keys.Select,
+
+ /// <summary>The Select Media button on a keyboard in Windows 2000/XP.</summary>
+ SelectMedia = Keys.SelectMedia,
+
+ /// <summary>The Separator button on a keyboard.</summary>
+ Separator = Keys.Separator,
+
+ /// <summary>The Computer Sleep button on a keyboard.</summary>
+ Sleep = Keys.Sleep,
+
+ /// <summary>The Space bar on a keyboard.</summary>
+ Space = Keys.Space,
+
+ /// <summary>The Subtract button on a keyboard.</summary>
+ Subtract = Keys.Subtract,
+
+ /// <summary>The T button on a keyboard.</summary>
+ T = Keys.T,
+
+ /// <summary>The Tab button on a keyboard.</summary>
+ Tab = Keys.Tab,
+
+ /// <summary>The U button on a keyboard.</summary>
+ U = Keys.U,
+
+ /// <summary>The Up Arrow button on a keyboard.</summary>
+ Up = Keys.Up,
+
+ /// <summary>The V button on a keyboard.</summary>
+ V = Keys.V,
+
+ /// <summary>The Volume Down button on a keyboard in Windows 2000/XP.</summary>
+ VolumeDown = Keys.VolumeDown,
+
+ /// <summary>The Volume Mute button on a keyboard in Windows 2000/XP.</summary>
+ VolumeMute = Keys.VolumeMute,
+
+ /// <summary>The Volume Up button on a keyboard in Windows 2000/XP.</summary>
+ VolumeUp = Keys.VolumeUp,
+
+ /// <summary>The W button on a keyboard.</summary>
+ W = Keys.W,
+
+ /// <summary>The X button on a keyboard.</summary>
+ X = Keys.X,
+
+ /// <summary>The Y button on a keyboard.</summary>
+ Y = Keys.Y,
+
+ /// <summary>The Z button on a keyboard.</summary>
+ Z = Keys.Z,
+
+ /// <summary>The Zoom button on a keyboard.</summary>
+ Zoom = Keys.Zoom
+ }
+
+ /// <summary>Provides extension methods for <see cref="SButton"/>.</summary>
+#if SMAPI_2_0
+ public
+#else
+ internal
+#endif
+ static class SButtonExtensions
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The offset added to <see cref="Buttons"/> values when converting them to <see cref="SButton"/> to avoid collisions with <see cref="Keys"/> values.</summary>
+ internal const int ControllerOffset = 2000;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get the <see cref="SButton"/> equivalent for the given button.</summary>
+ /// <param name="key">The keyboard button to convert.</param>
+ internal static SButton ToSButton(this Keys key)
+ {
+ return (SButton)key;
+ }
+
+ /// <summary>Get the <see cref="SButton"/> equivalent for the given button.</summary>
+ /// <param name="key">The controller button to convert.</param>
+ internal static SButton ToSButton(this Buttons key)
+ {
+ return (SButton)(SButtonExtensions.ControllerOffset + key);
+ }
+
+ /// <summary>Get the <see cref="Keys"/> equivalent for the given button.</summary>
+ /// <param name="input">The button to convert.</param>
+ /// <param name="key">The keyboard equivalent.</param>
+ /// <returns>Returns whether the value was converted successfully.</returns>
+ public static bool TryGetKeyboard(this SButton input, out Keys key)
+ {
+ if (Enum.IsDefined(typeof(Keys), (int)input))
+ {
+ key = (Keys)input;
+ return true;
+ }
+
+ key = Keys.None;
+ return false;
+ }
+
+ /// <summary>Get the <see cref="Buttons"/> equivalent for the given button.</summary>
+ /// <param name="input">The button to convert.</param>
+ /// <param name="button">The controller equivalent.</param>
+ /// <returns>Returns whether the value was converted successfully.</returns>
+ public static bool TryGetController(this SButton input, out Buttons button)
+ {
+ if (Enum.IsDefined(typeof(Keys), (int)input - SButtonExtensions.ControllerOffset))
+ {
+ button = (Buttons)(input - SButtonExtensions.ControllerOffset);
+ return true;
+ }
+
+ button = 0;
+ return false;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Utilities/SDate.cs b/src/StardewModdingAPI/Utilities/SDate.cs
new file mode 100644
index 00000000..e0613491
--- /dev/null
+++ b/src/StardewModdingAPI/Utilities/SDate.cs
@@ -0,0 +1,222 @@
+using System;
+using System.Linq;
+using StardewValley;
+
+namespace StardewModdingAPI.Utilities
+{
+ /// <summary>Represents a Stardew Valley date.</summary>
+ public class SDate : IEquatable<SDate>
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The internal season names in order.</summary>
+ private readonly string[] Seasons = { "spring", "summer", "fall", "winter" };
+
+ /// <summary>The number of seasons in a year.</summary>
+ private int SeasonsInYear => this.Seasons.Length;
+
+ /// <summary>The number of days in a season.</summary>
+ private readonly int DaysInSeason = 28;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The day of month.</summary>
+ public int Day { get; }
+
+ /// <summary>The season name.</summary>
+ public string Season { get; }
+
+ /// <summary>The year.</summary>
+ public int Year { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="day">The day of month.</param>
+ /// <param name="season">The season name.</param>
+ /// <exception cref="ArgumentException">One of the arguments has an invalid value (like day 35).</exception>
+ public SDate(int day, string season)
+ : this(day, season, Game1.year) { }
+
+ /// <summary>Construct an instance.</summary>
+ /// <param name="day">The day of month.</param>
+ /// <param name="season">The season name.</param>
+ /// <param name="year">The year.</param>
+ /// <exception cref="ArgumentException">One of the arguments has an invalid value (like day 35).</exception>
+ public SDate(int day, string season, int year)
+ {
+ // validate
+ if (season == null)
+ throw new ArgumentNullException(nameof(season));
+ if (!this.Seasons.Contains(season))
+ throw new ArgumentException($"Unknown season '{season}', must be one of [{string.Join(", ", this.Seasons)}].");
+ if (day < 1 || day > this.DaysInSeason)
+ throw new ArgumentException($"Invalid day '{day}', must be a value from 1 to {this.DaysInSeason}.");
+ if (year < 1)
+ throw new ArgumentException($"Invalid year '{year}', must be at least 1.");
+
+ // initialise
+ this.Day = day;
+ this.Season = season;
+ this.Year = year;
+ }
+
+ /// <summary>Get the current in-game date.</summary>
+ public static SDate Now()
+ {
+ return new SDate(Game1.dayOfMonth, Game1.currentSeason, Game1.year);
+ }
+
+ /// <summary>Get a new date with the given number of days added.</summary>
+ /// <param name="offset">The number of days to add.</param>
+ /// <returns>Returns the resulting date.</returns>
+ /// <exception cref="ArithmeticException">The offset would result in an invalid date (like year 0).</exception>
+ public SDate AddDays(int offset)
+ {
+ // simple case
+ int day = this.Day + offset;
+ string season = this.Season;
+ int year = this.Year;
+
+ // handle season transition
+ if (day > this.DaysInSeason || day < 1)
+ {
+ // get season index
+ int curSeasonIndex = this.GetSeasonIndex();
+
+ // get season offset
+ int seasonOffset = day / this.DaysInSeason;
+ if (day < 1)
+ seasonOffset -= 1;
+
+ // get new date
+ day = this.GetWrappedIndex(day, this.DaysInSeason);
+ season = this.Seasons[this.GetWrappedIndex(curSeasonIndex + seasonOffset, this.Seasons.Length)];
+ year += seasonOffset / this.Seasons.Length;
+ }
+
+ // validate
+ if (year < 1)
+ throw new ArithmeticException($"Adding {offset} days to {this} would result in invalid date {day:00} {season} {year}.");
+
+ // return new date
+ return new SDate(day, season, year);
+ }
+
+ /// <summary>Get a string representation of the date. This is mainly intended for debugging or console messages.</summary>
+ public override string ToString()
+ {
+ return $"{this.Day:00} {this.Season} Y{this.Year}";
+ }
+
+ /****
+ ** IEquatable
+ ****/
+ /// <summary>Get whether this instance is equal to another.</summary>
+ /// <param name="other">The other value to compare.</param>
+ public bool Equals(SDate other)
+ {
+ return this == other;
+ }
+
+ /// <summary>Get whether this instance is equal to another.</summary>
+ /// <param name="obj">The other value to compare.</param>
+ public override bool Equals(object obj)
+ {
+ return obj is SDate other && this == other;
+ }
+
+ /// <summary>Get a hash code which uniquely identifies a date.</summary>
+ public override int GetHashCode()
+ {
+ // return the number of days since 01 spring Y1
+ int yearIndex = this.Year - 1;
+ return
+ yearIndex * this.DaysInSeason * this.SeasonsInYear
+ + this.GetSeasonIndex() * this.DaysInSeason
+ + this.Day;
+ }
+
+ /****
+ ** Operators
+ ****/
+ /// <summary>Get whether one date is equal to another.</summary>
+ /// <param name="date">The base date to compare.</param>
+ /// <param name="other">The other date to compare.</param>
+ /// <returns>The equality of the dates</returns>
+ public static bool operator ==(SDate date, SDate other)
+ {
+ return date?.GetHashCode() == other?.GetHashCode();
+ }
+
+ /// <summary>Get whether one date is not equal to another.</summary>
+ /// <param name="date">The base date to compare.</param>
+ /// <param name="other">The other date to compare.</param>
+ public static bool operator !=(SDate date, SDate other)
+ {
+ return date?.GetHashCode() != other?.GetHashCode();
+ }
+
+ /// <summary>Get whether one date is more than another.</summary>
+ /// <param name="date">The base date to compare.</param>
+ /// <param name="other">The other date to compare.</param>
+ public static bool operator >(SDate date, SDate other)
+ {
+ return date?.GetHashCode() > other?.GetHashCode();
+ }
+
+ /// <summary>Get whether one date is more than or equal to another.</summary>
+ /// <param name="date">The base date to compare.</param>
+ /// <param name="other">The other date to compare.</param>
+ public static bool operator >=(SDate date, SDate other)
+ {
+ return date?.GetHashCode() >= other?.GetHashCode();
+ }
+
+ /// <summary>Get whether one date is less than or equal to another.</summary>
+ /// <param name="date">The base date to compare.</param>
+ /// <param name="other">The other date to compare.</param>
+ public static bool operator <=(SDate date, SDate other)
+ {
+ return date?.GetHashCode() <= other?.GetHashCode();
+ }
+
+ /// <summary>Get whether one date is less than another.</summary>
+ /// <param name="date">The base date to compare.</param>
+ /// <param name="other">The other date to compare.</param>
+ public static bool operator <(SDate date, SDate other)
+ {
+ return date?.GetHashCode() < other?.GetHashCode();
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Get the current season index.</summary>
+ /// <exception cref="InvalidOperationException">The current season wasn't recognised.</exception>
+ private int GetSeasonIndex()
+ {
+ int index = Array.IndexOf(this.Seasons, this.Season);
+ if (index == -1)
+ throw new InvalidOperationException($"The current season '{this.Season}' wasn't recognised.");
+ return index;
+ }
+
+ /// <summary>Get the real index in an array which should be treated as a two-way loop.</summary>
+ /// <param name="index">The index in the looped array.</param>
+ /// <param name="length">The number of elements in the array.</param>
+ private int GetWrappedIndex(int index, int length)
+ {
+ int wrapped = index % length;
+ if (wrapped < 0)
+ wrapped += length;
+ return wrapped;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/ArgumentParser.cs b/src/TrainerMod/Framework/Commands/ArgumentParser.cs
new file mode 100644
index 00000000..6bcd3ff8
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/ArgumentParser.cs
@@ -0,0 +1,159 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using StardewModdingAPI;
+
+namespace TrainerMod.Framework.Commands
+{
+ /// <summary>Provides methods for parsing command-line arguments.</summary>
+ internal class ArgumentParser : IReadOnlyList<string>
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The command name for errors.</summary>
+ private readonly string CommandName;
+
+ /// <summary>The arguments to parse.</summary>
+ private readonly string[] Args;
+
+ /// <summary>Writes messages to the console and log file.</summary>
+ private readonly IMonitor Monitor;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Get the number of arguments.</summary>
+ public int Count => this.Args.Length;
+
+ /// <summary>Get the argument at the specified index in the list.</summary>
+ /// <param name="index">The zero-based index of the element to get.</param>
+ public string this[int index] => this.Args[index];
+
+ /// <summary>A method which parses a string argument into the given value.</summary>
+ /// <typeparam name="T">The expected argument type.</typeparam>
+ /// <param name="input">The argument to parse.</param>
+ /// <param name="output">The parsed value.</param>
+ /// <returns>Returns whether the argument was successfully parsed.</returns>
+ public delegate bool ParseDelegate<T>(string input, out T output);
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="commandName">The command name for errors.</param>
+ /// <param name="args">The arguments to parse.</param>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ public ArgumentParser(string commandName, string[] args, IMonitor monitor)
+ {
+ this.CommandName = commandName;
+ this.Args = args;
+ this.Monitor = monitor;
+ }
+
+ /// <summary>Try to read a string argument.</summary>
+ /// <param name="index">The argument index.</param>
+ /// <param name="name">The argument name for error messages.</param>
+ /// <param name="value">The parsed value.</param>
+ /// <param name="required">Whether to show an error if the argument is missing.</param>
+ /// <param name="oneOf">Require that the argument match one of the given values (case-insensitive).</param>
+ public bool TryGet(int index, string name, out string value, bool required = true, string[] oneOf = null)
+ {
+ value = null;
+
+ // validate
+ if (this.Args.Length < index + 1)
+ {
+ if (required)
+ this.LogError($"Argument {index} ({name}) is required.");
+ return false;
+ }
+ if (oneOf?.Any() == true && !oneOf.Contains(this.Args[index], StringComparer.InvariantCultureIgnoreCase))
+ {
+ this.LogError($"Argument {index} ({name}) must be one of {string.Join(", ", oneOf)}.");
+ return false;
+ }
+
+ // get value
+ value = this.Args[index];
+ return true;
+ }
+
+ /// <summary>Try to read an integer argument.</summary>
+ /// <param name="index">The argument index.</param>
+ /// <param name="name">The argument name for error messages.</param>
+ /// <param name="value">The parsed value.</param>
+ /// <param name="required">Whether to show an error if the argument is missing.</param>
+ /// <param name="min">The minimum value allowed.</param>
+ /// <param name="max">The maximum value allowed.</param>
+ public bool TryGetInt(int index, string name, out int value, bool required = true, int? min = null, int? max = null)
+ {
+ value = 0;
+
+ // get argument
+ if (!this.TryGet(index, name, out string raw, required))
+ return false;
+
+ // parse
+ if (!int.TryParse(raw, out value))
+ {
+ this.LogIntFormatError(index, name, min, max);
+ return false;
+ }
+
+ // validate
+ if ((min.HasValue && value < min) || (max.HasValue && value > max))
+ {
+ this.LogIntFormatError(index, name, min, max);
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>Returns an enumerator that iterates through the collection.</summary>
+ /// <returns>An enumerator that can be used to iterate through the collection.</returns>
+ public IEnumerator<string> GetEnumerator()
+ {
+ return ((IEnumerable<string>)this.Args).GetEnumerator();
+ }
+
+ /// <summary>Returns an enumerator that iterates through a collection.</summary>
+ /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return this.GetEnumerator();
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Log a usage error.</summary>
+ /// <param name="message">The message describing the error.</param>
+ private void LogError(string message)
+ {
+ this.Monitor.Log($"{message} Type 'help {this.CommandName}' for usage.", LogLevel.Error);
+ }
+
+ /// <summary>Print an error for an invalid int argument.</summary>
+ /// <param name="index">The argument index.</param>
+ /// <param name="name">The argument name for error messages.</param>
+ /// <param name="min">The minimum value allowed.</param>
+ /// <param name="max">The maximum value allowed.</param>
+ private void LogIntFormatError(int index, string name, int? min, int? max)
+ {
+ if (min.HasValue && max.HasValue)
+ this.LogError($"Argument {index} ({name}) must be an integer between {min} and {max}.");
+ else if (min.HasValue)
+ this.LogError($"Argument {index} ({name}) must be an integer and at least {min}.");
+ else if (max.HasValue)
+ this.LogError($"Argument {index} ({name}) must be an integer and at most {max}.");
+ else
+ this.LogError($"Argument {index} ({name}) must be an integer.");
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/ITrainerCommand.cs b/src/TrainerMod/Framework/Commands/ITrainerCommand.cs
new file mode 100644
index 00000000..3d97e799
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/ITrainerCommand.cs
@@ -0,0 +1,34 @@
+using StardewModdingAPI;
+
+namespace TrainerMod.Framework.Commands
+{
+ /// <summary>A TrainerMod command to register.</summary>
+ internal interface ITrainerCommand
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The command name the user must type.</summary>
+ string Name { get; }
+
+ /// <summary>The command description.</summary>
+ string Description { get; }
+
+ /// <summary>Whether the command needs to perform logic when the game updates.</summary>
+ bool NeedsUpdate { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ void Handle(IMonitor monitor, string command, ArgumentParser args);
+
+ /// <summary>Perform any logic needed on update tick.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ void Update(IMonitor monitor);
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs b/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs
new file mode 100644
index 00000000..8c6e9f3b
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs
@@ -0,0 +1,33 @@
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Other
+{
+ /// <summary>A command which sends a debug command to the game.</summary>
+ internal class DebugCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public DebugCommand()
+ : base("debug", "Run one of the game's debug commands; for example, 'debug warp FarmHouse 1 1' warps the player to the farmhouse.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // submit command
+ string debugCommand = string.Join(" ", args);
+ string oldOutput = Game1.debugOutput;
+ Game1.game1.parseDebugInput(debugCommand);
+
+ // show result
+ monitor.Log(Game1.debugOutput != oldOutput
+ ? $"> {Game1.debugOutput}"
+ : "Sent debug command to the game, but there was no output.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs b/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs
new file mode 100644
index 00000000..367a70c6
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs
@@ -0,0 +1,26 @@
+using System.Diagnostics;
+using StardewModdingAPI;
+
+namespace TrainerMod.Framework.Commands.Other
+{
+ /// <summary>A command which shows the data files.</summary>
+ internal class ShowDataFilesCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public ShowDataFilesCommand()
+ : base("show_data_files", "Opens the folder containing the save and log files.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ Process.Start(Constants.DataPath);
+ monitor.Log($"OK, opening {Constants.DataPath}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs b/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs
new file mode 100644
index 00000000..67fa83a3
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs
@@ -0,0 +1,26 @@
+using System.Diagnostics;
+using StardewModdingAPI;
+
+namespace TrainerMod.Framework.Commands.Other
+{
+ /// <summary>A command which shows the game files.</summary>
+ internal class ShowGameFilesCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public ShowGameFilesCommand()
+ : base("show_game_files", "Opens the game folder.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ Process.Start(Constants.ExecutionPath);
+ monitor.Log($"OK, opening {Constants.ExecutionPath}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/AddCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddCommand.cs
new file mode 100644
index 00000000..47840202
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/AddCommand.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+using TrainerMod.Framework.ItemData;
+using Object = StardewValley.Object;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which adds an item to the player inventory.</summary>
+ internal class AddCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Provides methods for searching and constructing items.</summary>
+ private readonly ItemRepository Items = new ItemRepository();
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public AddCommand()
+ : base("player_add", AddCommand.GetDescription())
+ { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // read arguments
+ if (!args.TryGet(0, "item type", out string rawType, oneOf: Enum.GetNames(typeof(ItemType))))
+ return;
+ if (!args.TryGetInt(1, "item ID", out int id, min: 0))
+ return;
+ if (!args.TryGetInt(2, "count", out int count, min: 1, required: false))
+ count = 1;
+ if (!args.TryGetInt(3, "quality", out int quality, min: Object.lowQuality, max: Object.bestQuality, required: false))
+ quality = Object.lowQuality;
+ ItemType type = (ItemType)Enum.Parse(typeof(ItemType), rawType, ignoreCase: true);
+
+ // find matching item
+ SearchableItem match = this.Items.GetAll().FirstOrDefault(p => p.Type == type && p.ID == id);
+ if (match == null)
+ {
+ monitor.Log($"There's no {type} item with ID {id}.", LogLevel.Error);
+ return;
+ }
+
+ // apply count & quality
+ match.Item.Stack = count;
+ if (match.Item is Object obj)
+ obj.quality = quality;
+
+ // add to inventory
+ Game1.player.addItemByMenuIfNecessary(match.Item);
+ monitor.Log($"OK, added {match.Name} ({match.Type} #{match.ID}) to your inventory.", LogLevel.Info);
+ }
+
+ /*********
+ ** Private methods
+ *********/
+ private static string GetDescription()
+ {
+ string[] typeValues = Enum.GetNames(typeof(ItemType));
+ return "Gives the player an item.\n"
+ + "\n"
+ + "Usage: player_add <type> <item> [count] [quality]\n"
+ + $"- type: the item type (one of {string.Join(", ", typeValues)}).\n"
+ + "- item: the item ID (use the 'list_items' command to see a list).\n"
+ + "- count (optional): how many of the item to give.\n"
+ + $"- quality (optional): one of {Object.lowQuality} (normal), {Object.medQuality} (silver), {Object.highQuality} (gold), or {Object.bestQuality} (iridium).\n"
+ + "\n"
+ + "This example adds the galaxy sword to your inventory:\n"
+ + " player_add weapon 4";
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs
new file mode 100644
index 00000000..5f14edbb
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs
@@ -0,0 +1,53 @@
+using System.Linq;
+using StardewModdingAPI;
+using TrainerMod.Framework.ItemData;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which list item types.</summary>
+ internal class ListItemTypesCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Provides methods for searching and constructing items.</summary>
+ private readonly ItemRepository Items = new ItemRepository();
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public ListItemTypesCommand()
+ : base("list_item_types", "Lists item types you can filter in other commands.\n\nUsage: list_item_types") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!Context.IsWorldReady)
+ {
+ monitor.Log("You need to load a save to use this command.", LogLevel.Error);
+ return;
+ }
+
+ // handle
+ ItemType[] matches =
+ (
+ from item in this.Items.GetAll()
+ orderby item.Type.ToString()
+ select item.Type
+ )
+ .Distinct()
+ .ToArray();
+ string summary = "Searching...\n";
+ if (matches.Any())
+ monitor.Log(summary + this.GetTableString(matches, new[] { "type" }, val => new[] { val.ToString() }), LogLevel.Info);
+ else
+ monitor.Log(summary + "No item types found.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs
new file mode 100644
index 00000000..7f4f454c
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs
@@ -0,0 +1,76 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using StardewModdingAPI;
+using TrainerMod.Framework.ItemData;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which list items available to spawn.</summary>
+ internal class ListItemsCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Provides methods for searching and constructing items.</summary>
+ private readonly ItemRepository Items = new ItemRepository();
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public ListItemsCommand()
+ : base("list_items", "Lists and searches items in the game data.\n\nUsage: list_items [search]\n- search (optional): an arbitrary search string to filter by.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!Context.IsWorldReady)
+ {
+ monitor.Log("You need to load a save to use this command.", LogLevel.Error);
+ return;
+ }
+
+ // handle
+ SearchableItem[] matches =
+ (
+ from item in this.GetItems(args.ToArray())
+ orderby item.Type.ToString(), item.Name
+ select item
+ )
+ .ToArray();
+ string summary = "Searching...\n";
+ if (matches.Any())
+ monitor.Log(summary + this.GetTableString(matches, new[] { "type", "name", "id" }, val => new[] { val.Type.ToString(), val.Name, val.ID.ToString() }), LogLevel.Info);
+ else
+ monitor.Log(summary + "No items found", LogLevel.Info);
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Get all items which can be searched and added to the player's inventory through the console.</summary>
+ /// <param name="searchWords">The search string to find.</param>
+ private IEnumerable<SearchableItem> GetItems(string[] searchWords)
+ {
+ // normalise search term
+ searchWords = searchWords?.Where(word => !string.IsNullOrWhiteSpace(word)).ToArray();
+ if (searchWords?.Any() == false)
+ searchWords = null;
+
+ // find matches
+ return (
+ from item in this.Items.GetAll()
+ let term = $"{item.ID}|{item.Type}|{item.Name}|{item.DisplayName}"
+ where searchWords == null || searchWords.All(word => term.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) != -1)
+ select item
+ );
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs
new file mode 100644
index 00000000..28ace0df
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs
@@ -0,0 +1,76 @@
+using Microsoft.Xna.Framework;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the color of a player feature.</summary>
+ internal class SetColorCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetColorCommand()
+ : base("player_changecolor", "Sets the color of a player feature.\n\nUsage: player_changecolor <target> <color>\n- target: what to change (one of 'hair', 'eyes', or 'pants').\n- color: a color value in RGB format, like (255,255,255).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // parse arguments
+ if (!args.TryGet(0, "target", out string target, oneOf: new[] { "hair", "eyes", "pants" }))
+ return;
+ if (!args.TryGet(1, "color", out string rawColor))
+ return;
+
+ // parse color
+ if (!this.TryParseColor(rawColor, out Color color))
+ {
+ this.LogUsageError(monitor, "Argument 1 (color) must be an RBG value like '255,150,0'.");
+ return;
+ }
+
+ // handle
+ switch (target)
+ {
+ case "hair":
+ Game1.player.hairstyleColor = color;
+ monitor.Log("OK, your hair color is updated.", LogLevel.Info);
+ break;
+
+ case "eyes":
+ Game1.player.changeEyeColor(color);
+ monitor.Log("OK, your eye color is updated.", LogLevel.Info);
+ break;
+
+ case "pants":
+ Game1.player.pantsColor = color;
+ monitor.Log("OK, your pants color is updated.", LogLevel.Info);
+ break;
+ }
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Try to parse a color from a string.</summary>
+ /// <param name="input">The input string.</param>
+ /// <param name="color">The color to set.</param>
+ private bool TryParseColor(string input, out Color color)
+ {
+ string[] colorHexes = input.Split(new[] { ',' }, 3);
+ if (int.TryParse(colorHexes[0], out int r) && int.TryParse(colorHexes[1], out int g) && int.TryParse(colorHexes[2], out int b))
+ {
+ color = new Color(r, g, b);
+ return true;
+ }
+
+ color = Color.Transparent;
+ return false;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs
new file mode 100644
index 00000000..f64e9035
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs
@@ -0,0 +1,72 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's current health.</summary>
+ internal class SetHealthCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Whether to keep the player's health at its maximum.</summary>
+ private bool InfiniteHealth;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Whether the command needs to perform logic when the game updates.</summary>
+ public override bool NeedsUpdate => this.InfiniteHealth;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetHealthCommand()
+ : base("player_sethealth", "Sets the player's health.\n\nUsage: player_sethealth [value]\n- value: an integer amount, or 'inf' for infinite health.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // no-argument mode
+ if (!args.Any())
+ {
+ monitor.Log($"You currently have {(this.InfiniteHealth ? "infinite" : Game1.player.health.ToString())} health. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // handle
+ string amountStr = args[0];
+ if (amountStr == "inf")
+ {
+ this.InfiniteHealth = true;
+ monitor.Log("OK, you now have infinite health.", LogLevel.Info);
+ }
+ else
+ {
+ this.InfiniteHealth = false;
+ if (int.TryParse(amountStr, out int amount))
+ {
+ Game1.player.health = amount;
+ monitor.Log($"OK, you now have {Game1.player.health} health.", LogLevel.Info);
+ }
+ else
+ this.LogArgumentNotInt(monitor);
+ }
+ }
+
+ /// <summary>Perform any logic needed on update tick.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ public override void Update(IMonitor monitor)
+ {
+ if (this.InfiniteHealth)
+ Game1.player.health = Game1.player.maxHealth;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs
new file mode 100644
index 00000000..59b28a3c
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs
@@ -0,0 +1,38 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's current immunity.</summary>
+ internal class SetImmunityCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetImmunityCommand()
+ : base("player_setimmunity", "Sets the player's immunity.\n\nUsage: player_setimmunity [value]\n- value: an integer amount.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!args.Any())
+ {
+ monitor.Log($"You currently have {Game1.player.immunity} immunity. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // handle
+ if (args.TryGetInt(0, "amount", out int amount, min: 0))
+ {
+ Game1.player.immunity = amount;
+ monitor.Log($"OK, you now have {Game1.player.immunity} immunity.", LogLevel.Info);
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs
new file mode 100644
index 00000000..b223aa9f
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs
@@ -0,0 +1,63 @@
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's current level for a skill.</summary>
+ internal class SetLevelCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetLevelCommand()
+ : base("player_setlevel", "Sets the player's specified skill to the specified value.\n\nUsage: player_setlevel <skill> <value>\n- skill: the skill to set (one of 'luck', 'mining', 'combat', 'farming', 'fishing', or 'foraging').\n- value: the target level (a number from 1 to 10).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!args.TryGet(0, "skill", out string skill, oneOf: new[] { "luck", "mining", "combat", "farming", "fishing", "foraging" }))
+ return;
+ if (!args.TryGetInt(1, "level", out int level, min: 0, max: 10))
+ return;
+
+ // handle
+ switch (skill)
+ {
+ case "luck":
+ Game1.player.LuckLevel = level;
+ monitor.Log($"OK, your luck skill is now {Game1.player.LuckLevel}.", LogLevel.Info);
+ break;
+
+ case "mining":
+ Game1.player.MiningLevel = level;
+ monitor.Log($"OK, your mining skill is now {Game1.player.MiningLevel}.", LogLevel.Info);
+ break;
+
+ case "combat":
+ Game1.player.CombatLevel = level;
+ monitor.Log($"OK, your combat skill is now {Game1.player.CombatLevel}.", LogLevel.Info);
+ break;
+
+ case "farming":
+ Game1.player.FarmingLevel = level;
+ monitor.Log($"OK, your farming skill is now {Game1.player.FarmingLevel}.", LogLevel.Info);
+ break;
+
+ case "fishing":
+ Game1.player.FishingLevel = level;
+ monitor.Log($"OK, your fishing skill is now {Game1.player.FishingLevel}.", LogLevel.Info);
+ break;
+
+ case "foraging":
+ Game1.player.ForagingLevel = level;
+ monitor.Log($"OK, your foraging skill is now {Game1.player.ForagingLevel}.", LogLevel.Info);
+ break;
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs
new file mode 100644
index 00000000..4b9d87dc
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs
@@ -0,0 +1,38 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's maximum health.</summary>
+ internal class SetMaxHealthCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetMaxHealthCommand()
+ : base("player_setmaxhealth", "Sets the player's max health.\n\nUsage: player_setmaxhealth [value]\n- value: an integer amount.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!args.Any())
+ {
+ monitor.Log($"You currently have {Game1.player.maxHealth} max health. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // handle
+ if (args.TryGetInt(0, "amount", out int amount, min: 1))
+ {
+ Game1.player.maxHealth = amount;
+ monitor.Log($"OK, you now have {Game1.player.maxHealth} max health.", LogLevel.Info);
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs
new file mode 100644
index 00000000..3997bb1b
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs
@@ -0,0 +1,38 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's maximum stamina.</summary>
+ internal class SetMaxStaminaCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetMaxStaminaCommand()
+ : base("player_setmaxstamina", "Sets the player's max stamina.\n\nUsage: player_setmaxstamina [value]\n- value: an integer amount.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!args.Any())
+ {
+ monitor.Log($"You currently have {Game1.player.MaxStamina} max stamina. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // handle
+ if (args.TryGetInt(0, "amount", out int amount, min: 1))
+ {
+ Game1.player.MaxStamina = amount;
+ monitor.Log($"OK, you now have {Game1.player.MaxStamina} max stamina.", LogLevel.Info);
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs
new file mode 100644
index 00000000..55e069a4
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs
@@ -0,0 +1,72 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's current money.</summary>
+ internal class SetMoneyCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Whether to keep the player's money at a set value.</summary>
+ private bool InfiniteMoney;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Whether the command needs to perform logic when the game updates.</summary>
+ public override bool NeedsUpdate => this.InfiniteMoney;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetMoneyCommand()
+ : base("player_setmoney", "Sets the player's money.\n\nUsage: player_setmoney <value>\n- value: an integer amount, or 'inf' for infinite money.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!args.Any())
+ {
+ monitor.Log($"You currently have {(this.InfiniteMoney ? "infinite" : Game1.player.Money.ToString())} gold. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // handle
+ string amountStr = args[0];
+ if (amountStr == "inf")
+ {
+ this.InfiniteMoney = true;
+ monitor.Log("OK, you now have infinite money.", LogLevel.Info);
+ }
+ else
+ {
+ this.InfiniteMoney = false;
+ if (int.TryParse(amountStr, out int amount))
+ {
+ Game1.player.Money = amount;
+ monitor.Log($"OK, you now have {Game1.player.Money} gold.", LogLevel.Info);
+ }
+ else
+ this.LogArgumentNotInt(monitor);
+ }
+ }
+
+ /// <summary>Perform any logic needed on update tick.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ public override void Update(IMonitor monitor)
+ {
+ if (this.InfiniteMoney)
+ Game1.player.money = 999999;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs
new file mode 100644
index 00000000..3fd4475c
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs
@@ -0,0 +1,52 @@
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's name.</summary>
+ internal class SetNameCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetNameCommand()
+ : base("player_setname", "Sets the player's name.\n\nUsage: player_setname <target> <name>\n- target: what to rename (one of 'player' or 'farm').\n- name: the new name to set.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // parse arguments
+ if (!args.TryGet(0, "target", out string target, oneOf: new[] { "player", "farm" }))
+ return;
+ args.TryGet(1, "name", out string name, required: false);
+
+ // handle
+ switch (target)
+ {
+ case "player":
+ if (!string.IsNullOrWhiteSpace(name))
+ {
+ Game1.player.Name = args[1];
+ monitor.Log($"OK, your name is now {Game1.player.Name}.", LogLevel.Info);
+ }
+ else
+ monitor.Log($"Your name is currently '{Game1.player.Name}'. Type 'help player_setname' for usage.", LogLevel.Info);
+ break;
+
+ case "farm":
+ if (!string.IsNullOrWhiteSpace(name))
+ {
+ Game1.player.farmName = args[1];
+ monitor.Log($"OK, your farm's name is now {Game1.player.farmName}.", LogLevel.Info);
+ }
+ else
+ monitor.Log($"Your farm's name is currently '{Game1.player.farmName}'. Type 'help player_setname' for usage.", LogLevel.Info);
+ break;
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs
new file mode 100644
index 00000000..40b87b62
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs
@@ -0,0 +1,31 @@
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's current added speed.</summary>
+ internal class SetSpeedCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetSpeedCommand()
+ : base("player_setspeed", "Sets the player's added speed to the specified value.\n\nUsage: player_setspeed <value>\n- value: an integer amount (0 is normal).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // parse arguments
+ if (!args.TryGetInt(0, "added speed", out int amount, min: 0))
+ return;
+
+ // handle
+ Game1.player.addedSpeed = amount;
+ monitor.Log($"OK, your added speed is now {Game1.player.addedSpeed}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs
new file mode 100644
index 00000000..d44d1370
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs
@@ -0,0 +1,72 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits the player's current stamina.</summary>
+ internal class SetStaminaCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Whether to keep the player's stamina at its maximum.</summary>
+ private bool InfiniteStamina;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Whether the command needs to perform logic when the game updates.</summary>
+ public override bool NeedsUpdate => this.InfiniteStamina;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetStaminaCommand()
+ : base("player_setstamina", "Sets the player's stamina.\n\nUsage: player_setstamina [value]\n- value: an integer amount, or 'inf' for infinite stamina.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // validate
+ if (!args.Any())
+ {
+ monitor.Log($"You currently have {(this.InfiniteStamina ? "infinite" : Game1.player.Stamina.ToString())} stamina. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // handle
+ string amountStr = args[0];
+ if (amountStr == "inf")
+ {
+ this.InfiniteStamina = true;
+ monitor.Log("OK, you now have infinite stamina.", LogLevel.Info);
+ }
+ else
+ {
+ this.InfiniteStamina = false;
+ if (int.TryParse(amountStr, out int amount))
+ {
+ Game1.player.Stamina = amount;
+ monitor.Log($"OK, you now have {Game1.player.Stamina} stamina.", LogLevel.Info);
+ }
+ else
+ this.LogArgumentNotInt(monitor);
+ }
+ }
+
+ /// <summary>Perform any logic needed on update tick.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ public override void Update(IMonitor monitor)
+ {
+ if (this.InfiniteStamina)
+ Game1.player.stamina = Game1.player.MaxStamina;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs
new file mode 100644
index 00000000..96e34af2
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs
@@ -0,0 +1,92 @@
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Player
+{
+ /// <summary>A command which edits a player style.</summary>
+ internal class SetStyleCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetStyleCommand()
+ : base("player_changestyle", "Sets the style of a player feature.\n\nUsage: player_changecolor <target> <value>.\n- target: what to change (one of 'hair', 'shirt', 'skin', 'acc', 'shoe', 'swim', or 'gender').\n- value: the integer style ID.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // parse arguments
+ if (!args.TryGet(0, "target", out string target, oneOf: new[] { "hair", "shirt", "acc", "skin", "shoe", "swim", "gender" }))
+ return;
+ if (!args.TryGetInt(1, "style ID", out int styleID))
+ return;
+
+ // handle
+ switch (target)
+ {
+ case "hair":
+ Game1.player.changeHairStyle(styleID);
+ monitor.Log("OK, your hair style is updated.", LogLevel.Info);
+ break;
+
+ case "shirt":
+ Game1.player.changeShirt(styleID);
+ monitor.Log("OK, your shirt style is updated.", LogLevel.Info);
+ break;
+
+ case "acc":
+ Game1.player.changeAccessory(styleID);
+ monitor.Log("OK, your accessory style is updated.", LogLevel.Info);
+ break;
+
+ case "skin":
+ Game1.player.changeSkinColor(styleID);
+ monitor.Log("OK, your skin color is updated.", LogLevel.Info);
+ break;
+
+ case "shoe":
+ Game1.player.changeShoeColor(styleID);
+ monitor.Log("OK, your shoe style is updated.", LogLevel.Info);
+ break;
+
+ case "swim":
+ switch (styleID)
+ {
+ case 0:
+ Game1.player.changeOutOfSwimSuit();
+ monitor.Log("OK, you're no longer in your swimming suit.", LogLevel.Info);
+ break;
+ case 1:
+ Game1.player.changeIntoSwimsuit();
+ monitor.Log("OK, you're now in your swimming suit.", LogLevel.Info);
+ break;
+ default:
+ this.LogUsageError(monitor, "The swim value should be 0 (no swimming suit) or 1 (swimming suit).");
+ break;
+ }
+ break;
+
+ case "gender":
+ switch (styleID)
+ {
+ case 0:
+ Game1.player.changeGender(true);
+ monitor.Log("OK, you're now male.", LogLevel.Info);
+ break;
+ case 1:
+ Game1.player.changeGender(false);
+ monitor.Log("OK, you're now female.", LogLevel.Info);
+ break;
+ default:
+ this.LogUsageError(monitor, "The gender value should be 0 (male) or 1 (female).");
+ break;
+ }
+ break;
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs b/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs
new file mode 100644
index 00000000..121ad9a6
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs
@@ -0,0 +1,28 @@
+using StardewModdingAPI;
+using StardewValley;
+using StardewValley.Menus;
+
+namespace TrainerMod.Framework.Commands.Saves
+{
+ /// <summary>A command which shows the load screen.</summary>
+ internal class LoadCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public LoadCommand()
+ : base("load", "Shows the load screen.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ monitor.Log("Triggering load menu...", LogLevel.Info);
+ Game1.hasLoadedGame = false;
+ Game1.activeClickableMenu = new LoadGameMenu();
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs b/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs
new file mode 100644
index 00000000..5f6941e9
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs
@@ -0,0 +1,27 @@
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.Saves
+{
+ /// <summary>A command which saves the game.</summary>
+ internal class SaveCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SaveCommand()
+ : base("save", "Saves the game? Doesn't seem to work.") { }
+
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ monitor.Log("Saving the game...", LogLevel.Info);
+ SaveGame.Save();
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/TrainerCommand.cs b/src/TrainerMod/Framework/Commands/TrainerCommand.cs
new file mode 100644
index 00000000..abe9ee41
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/TrainerCommand.cs
@@ -0,0 +1,103 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using StardewModdingAPI;
+
+namespace TrainerMod.Framework.Commands
+{
+ /// <summary>The base implementation for a trainer command.</summary>
+ internal abstract class TrainerCommand : ITrainerCommand
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The command name the user must type.</summary>
+ public string Name { get; }
+
+ /// <summary>The command description.</summary>
+ public string Description { get; }
+
+ /// <summary>Whether the command needs to perform logic when the game updates.</summary>
+ public virtual bool NeedsUpdate { get; } = false;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public abstract void Handle(IMonitor monitor, string command, ArgumentParser args);
+
+ /// <summary>Perform any logic needed on update tick.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ public virtual void Update(IMonitor monitor) { }
+
+
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="name">The command name the user must type.</param>
+ /// <param name="description">The command description.</param>
+ protected TrainerCommand(string name, string description)
+ {
+ this.Name = name;
+ this.Description = description;
+ }
+
+ /// <summary>Log an error indicating incorrect usage.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="error">A sentence explaining the problem.</param>
+ protected void LogUsageError(IMonitor monitor, string error)
+ {
+ monitor.Log($"{error} Type 'help {this.Name}' for usage.", LogLevel.Error);
+ }
+
+ /// <summary>Log an error indicating a value must be an integer.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ protected void LogArgumentNotInt(IMonitor monitor)
+ {
+ this.LogUsageError(monitor, "The value must be a whole number.");
+ }
+
+ /// <summary>Get an ASCII table to show tabular data in the console.</summary>
+ /// <typeparam name="T">The data type.</typeparam>
+ /// <param name="data">The data to display.</param>
+ /// <param name="header">The table header.</param>
+ /// <param name="getRow">Returns a set of fields for a data value.</param>
+ protected string GetTableString<T>(IEnumerable<T> data, string[] header, Func<T, string[]> getRow)
+ {
+ // get table data
+ int[] widths = header.Select(p => p.Length).ToArray();
+ string[][] rows = data
+ .Select(item =>
+ {
+ string[] fields = getRow(item);
+ if (fields.Length != widths.Length)
+ throw new InvalidOperationException($"Expected {widths.Length} columns, but found {fields.Length}: {string.Join(", ", fields)}");
+
+ for (int i = 0; i < fields.Length; i++)
+ widths[i] = Math.Max(widths[i], fields[i].Length);
+
+ return fields;
+ })
+ .ToArray();
+
+ // render fields
+ List<string[]> lines = new List<string[]>(rows.Length + 2)
+ {
+ header,
+ header.Select((value, i) => "".PadRight(widths[i], '-')).ToArray()
+ };
+ lines.AddRange(rows);
+
+ return string.Join(
+ Environment.NewLine,
+ lines.Select(line => string.Join(" | ", line.Select((field, i) => field.PadRight(widths[i], ' ')).ToArray())
+ )
+ );
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs b/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs
new file mode 100644
index 00000000..4e62cf77
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs
@@ -0,0 +1,28 @@
+using StardewModdingAPI;
+using StardewValley;
+using StardewValley.Locations;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which moves the player to the next mine level.</summary>
+ internal class DownMineLevelCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public DownMineLevelCommand()
+ : base("world_downminelevel", "Goes down one mine level.") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ int level = (Game1.currentLocation as MineShaft)?.mineLevel ?? 0;
+ monitor.Log($"OK, warping you to mine level {level + 1}.", LogLevel.Info);
+ Game1.enterMine(false, level + 1, "");
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs b/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs
new file mode 100644
index 00000000..13d08398
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs
@@ -0,0 +1,67 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which freezes the current time.</summary>
+ internal class FreezeTimeCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The time of day at which to freeze time.</summary>
+ internal static int FrozenTime;
+
+ /// <summary>Whether to freeze time.</summary>
+ private bool FreezeTime;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Whether the command needs to perform logic when the game updates.</summary>
+ public override bool NeedsUpdate => this.FreezeTime;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public FreezeTimeCommand()
+ : base("world_freezetime", "Freezes or resumes time.\n\nUsage: world_freezetime [value]\n- value: one of 0 (resume), 1 (freeze), or blank (toggle).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ if (args.Any())
+ {
+ // parse arguments
+ if (!args.TryGetInt(0, "value", out int value, min: 0, max: 1))
+ return;
+
+ // handle
+ this.FreezeTime = value == 1;
+ FreezeTimeCommand.FrozenTime = Game1.timeOfDay;
+ monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info);
+ }
+ else
+ {
+ this.FreezeTime = !this.FreezeTime;
+ FreezeTimeCommand.FrozenTime = Game1.timeOfDay;
+ monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info);
+ }
+ }
+
+ /// <summary>Perform any logic needed on update tick.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ public override void Update(IMonitor monitor)
+ {
+ if (this.FreezeTime)
+ Game1.timeOfDay = FreezeTimeCommand.FrozenTime;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs b/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs
new file mode 100644
index 00000000..54267384
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs
@@ -0,0 +1,39 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which sets the current day.</summary>
+ internal class SetDayCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetDayCommand()
+ : base("world_setday", "Sets the day to the specified value.\n\nUsage: world_setday <value>.\n- value: the target day (a number from 1 to 28).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // no-argument mode
+ if (!args.Any())
+ {
+ monitor.Log($"The current date is {Game1.currentSeason} {Game1.dayOfMonth}. Specify a value to change the day.", LogLevel.Info);
+ return;
+ }
+
+ // parse arguments
+ if (!args.TryGetInt(0, "day", out int day, min: 1, max: 28))
+ return;
+
+ // handle
+ Game1.dayOfMonth = day;
+ monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs b/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs
new file mode 100644
index 00000000..225ec091
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs
@@ -0,0 +1,33 @@
+using System;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which moves the player to the given mine level.</summary>
+ internal class SetMineLevelCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetMineLevelCommand()
+ : base("world_setminelevel", "Sets the mine level?\n\nUsage: world_setminelevel <value>\n- value: The target level (a number starting at 1).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // parse arguments
+ if (!args.TryGetInt(0, "mine level", out int level, min: 1))
+ return;
+
+ // handle
+ level = Math.Max(1, level);
+ monitor.Log($"OK, warping you to mine level {level}.", LogLevel.Info);
+ Game1.enterMine(true, level, "");
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs b/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs
new file mode 100644
index 00000000..96c3d920
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs
@@ -0,0 +1,46 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which sets the current season.</summary>
+ internal class SetSeasonCommand : TrainerCommand
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The valid season names.</summary>
+ private readonly string[] ValidSeasons = { "winter", "spring", "summer", "fall" };
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetSeasonCommand()
+ : base("world_setseason", "Sets the season to the specified value.\n\nUsage: world_setseason <season>\n- season: the target season (one of 'spring', 'summer', 'fall', 'winter').") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // no-argument mode
+ if (!args.Any())
+ {
+ monitor.Log($"The current season is {Game1.currentSeason}. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // parse arguments
+ if (!args.TryGet(0, "season", out string season, oneOf: this.ValidSeasons))
+ return;
+
+ // handle
+ Game1.currentSeason = season;
+ monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs b/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs
new file mode 100644
index 00000000..c827ea5e
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs
@@ -0,0 +1,40 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which sets the current time.</summary>
+ internal class SetTimeCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetTimeCommand()
+ : base("world_settime", "Sets the time to the specified value.\n\nUsage: world_settime <value>\n- value: the target time in military time (like 0600 for 6am and 1800 for 6pm).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // no-argument mode
+ if (!args.Any())
+ {
+ monitor.Log($"The current time is {Game1.timeOfDay}. Specify a value to change it.", LogLevel.Info);
+ return;
+ }
+
+ // parse arguments
+ if (!args.TryGetInt(0, "time", out int time, min: 600, max: 2600))
+ return;
+
+ // handle
+ Game1.timeOfDay = time;
+ FreezeTimeCommand.FrozenTime = Game1.timeOfDay;
+ monitor.Log($"OK, the time is now {Game1.timeOfDay.ToString().PadLeft(4, '0')}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs b/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs
new file mode 100644
index 00000000..760fc170
--- /dev/null
+++ b/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs
@@ -0,0 +1,39 @@
+using System.Linq;
+using StardewModdingAPI;
+using StardewValley;
+
+namespace TrainerMod.Framework.Commands.World
+{
+ /// <summary>A command which sets the current year.</summary>
+ internal class SetYearCommand : TrainerCommand
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SetYearCommand()
+ : base("world_setyear", "Sets the year to the specified value.\n\nUsage: world_setyear <year>\n- year: the target year (a number starting from 1).") { }
+
+ /// <summary>Handle the command.</summary>
+ /// <param name="monitor">Writes messages to the console and log file.</param>
+ /// <param name="command">The command name.</param>
+ /// <param name="args">The command arguments.</param>
+ public override void Handle(IMonitor monitor, string command, ArgumentParser args)
+ {
+ // no-argument mode
+ if (!args.Any())
+ {
+ monitor.Log($"The current year is {Game1.year}. Specify a value to change the year.", LogLevel.Info);
+ return;
+ }
+
+ // parse arguments
+ if (!args.TryGetInt(0, "year", out int year, min: 1))
+ return;
+
+ // handle
+ Game1.year = year;
+ monitor.Log($"OK, the year is now {Game1.year}.", LogLevel.Info);
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/ItemData/ItemType.cs b/src/TrainerMod/Framework/ItemData/ItemType.cs
new file mode 100644
index 00000000..423455e9
--- /dev/null
+++ b/src/TrainerMod/Framework/ItemData/ItemType.cs
@@ -0,0 +1,39 @@
+namespace TrainerMod.Framework.ItemData
+{
+ /// <summary>An item type that can be searched and added to the player through the console.</summary>
+ internal enum ItemType
+ {
+ /// <summary>A big craftable object in <see cref="StardewValley.Game1.bigCraftablesInformation"/></summary>
+ BigCraftable,
+
+ /// <summary>A <see cref="Boots"/> item.</summary>
+ Boots,
+
+ /// <summary>A fish item.</summary>
+ Fish,
+
+ /// <summary>A <see cref="Wallpaper"/> flooring item.</summary>
+ Flooring,
+
+ /// <summary>A <see cref="Furniture"/> item.</summary>
+ Furniture,
+
+ /// <summary>A <see cref="Hat"/> item.</summary>
+ Hat,
+
+ /// <summary>Any object in <see cref="StardewValley.Game1.objectInformation"/> (except rings).</summary>
+ Object,
+
+ /// <summary>A <see cref="Ring"/> item.</summary>
+ Ring,
+
+ /// <summary>A <see cref="Tool"/> tool.</summary>
+ Tool,
+
+ /// <summary>A <see cref="Wallpaper"/> wall item.</summary>
+ Wallpaper,
+
+ /// <summary>A <see cref="StardewValley.Tools.MeleeWeapon"/> or <see cref="StardewValley.Tools.Slingshot"/> item.</summary>
+ Weapon
+ }
+}
diff --git a/src/TrainerMod/Framework/ItemData/SearchableItem.cs b/src/TrainerMod/Framework/ItemData/SearchableItem.cs
new file mode 100644
index 00000000..146da1a8
--- /dev/null
+++ b/src/TrainerMod/Framework/ItemData/SearchableItem.cs
@@ -0,0 +1,41 @@
+using StardewValley;
+
+namespace TrainerMod.Framework.ItemData
+{
+ /// <summary>A game item with metadata.</summary>
+ internal class SearchableItem
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The item type.</summary>
+ public ItemType Type { get; }
+
+ /// <summary>The item instance.</summary>
+ public Item Item { get; }
+
+ /// <summary>The item's unique ID for its type.</summary>
+ public int ID { get; }
+
+ /// <summary>The item's default name.</summary>
+ public string Name => this.Item.Name;
+
+ /// <summary>The item's display name for the current language.</summary>
+ public string DisplayName => this.Item.DisplayName;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="type">The item type.</param>
+ /// <param name="id">The unique ID (if different from the item's parent sheet index).</param>
+ /// <param name="item">The item instance.</param>
+ public SearchableItem(ItemType type, int id, Item item)
+ {
+ this.Type = type;
+ this.ID = id;
+ this.Item = item;
+ }
+ }
+}
diff --git a/src/TrainerMod/Framework/ItemRepository.cs b/src/TrainerMod/Framework/ItemRepository.cs
new file mode 100644
index 00000000..96d3159e
--- /dev/null
+++ b/src/TrainerMod/Framework/ItemRepository.cs
@@ -0,0 +1,179 @@
+using System.Collections.Generic;
+using Microsoft.Xna.Framework;
+using StardewValley;
+using StardewValley.Objects;
+using StardewValley.Tools;
+using TrainerMod.Framework.ItemData;
+using SObject = StardewValley.Object;
+
+namespace TrainerMod.Framework
+{
+ /// <summary>Provides methods for searching and constructing items.</summary>
+ internal class ItemRepository
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The custom ID offset for items don't have a unique ID in the game.</summary>
+ private readonly int CustomIDOffset = 1000;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get all spawnable items.</summary>
+ public IEnumerable<SearchableItem> GetAll()
+ {
+ // get tools
+ for (int quality = Tool.stone; quality <= Tool.iridium; quality++)
+ {
+ yield return new SearchableItem(ItemType.Tool, ToolFactory.axe, ToolFactory.getToolFromDescription(ToolFactory.axe, quality));
+ yield return new SearchableItem(ItemType.Tool, ToolFactory.hoe, ToolFactory.getToolFromDescription(ToolFactory.hoe, quality));
+ yield return new SearchableItem(ItemType.Tool, ToolFactory.pickAxe, ToolFactory.getToolFromDescription(ToolFactory.pickAxe, quality));
+ yield return new SearchableItem(ItemType.Tool, ToolFactory.wateringCan, ToolFactory.getToolFromDescription(ToolFactory.wateringCan, quality));
+ if (quality != Tool.iridium)
+ yield return new SearchableItem(ItemType.Tool, ToolFactory.fishingRod, ToolFactory.getToolFromDescription(ToolFactory.fishingRod, quality));
+ }
+ yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset, new MilkPail()); // these don't have any sort of ID, so we'll just assign some arbitrary ones
+ yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 1, new Shears());
+ yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 2, new Pan());
+
+ // wallpapers
+ for (int id = 0; id < 112; id++)
+ yield return new SearchableItem(ItemType.Wallpaper, id, new Wallpaper(id));
+
+ // flooring
+ for (int id = 0; id < 40; id++)
+ yield return new SearchableItem(ItemType.Flooring, id, new Wallpaper(id, isFloor: true));
+
+ // equipment
+ foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\Boots").Keys)
+ yield return new SearchableItem(ItemType.Boots, id, new Boots(id));
+ foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\hats").Keys)
+ yield return new SearchableItem(ItemType.Hat, id, new Hat(id));
+ foreach (int id in Game1.objectInformation.Keys)
+ {
+ if (id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange)
+ yield return new SearchableItem(ItemType.Ring, id, new Ring(id));
+ }
+
+ // weapons
+ foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\weapons").Keys)
+ {
+ Item weapon = (id >= 32 && id <= 34)
+ ? (Item)new Slingshot(id)
+ : new MeleeWeapon(id);
+ yield return new SearchableItem(ItemType.Weapon, id, weapon);
+ }
+
+ // furniture
+ foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\Furniture").Keys)
+ {
+ if (id == 1466 || id == 1468)
+ yield return new SearchableItem(ItemType.Furniture, id, new TV(id, Vector2.Zero));
+ else
+ yield return new SearchableItem(ItemType.Furniture, id, new Furniture(id, Vector2.Zero));
+ }
+
+ // fish
+ foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\Fish").Keys)
+ yield return new SearchableItem(ItemType.Fish, id, new SObject(id, 999));
+
+ // craftables
+ foreach (int id in Game1.bigCraftablesInformation.Keys)
+ yield return new SearchableItem(ItemType.BigCraftable, id, new SObject(Vector2.Zero, id));
+
+ // objects
+ foreach (int id in Game1.objectInformation.Keys)
+ {
+ if (id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange)
+ continue; // handled separated
+
+ SObject item = new SObject(id, 1);
+ yield return new SearchableItem(ItemType.Object, id, item);
+
+ // fruit products
+ if (item.category == SObject.FruitsCategory)
+ {
+ yield return new SearchableItem(ItemType.Object, this.CustomIDOffset + id, new SObject(348, 1)
+ {
+ name = $"{item.Name} Wine",
+ price = item.price * 3,
+ preserve = SObject.PreserveType.Wine,
+ preservedParentSheetIndex = item.parentSheetIndex
+ });
+ yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 2 + id, new SObject(344, 1)
+ {
+ name = $"{item.Name} Jelly",
+ price = 50 + item.Price * 2,
+ preserve = SObject.PreserveType.Jelly,
+ preservedParentSheetIndex = item.parentSheetIndex
+ });
+ }
+
+ // vegetable products
+ else if (item.category == SObject.VegetableCategory)
+ {
+ yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 3 + id, new SObject(350, 1)
+ {
+ name = $"{item.Name} Juice",
+ price = (int)(item.price * 2.25d),
+ preserve = SObject.PreserveType.Juice,
+ preservedParentSheetIndex = item.parentSheetIndex
+ });
+ yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 4 + id, new SObject(342, 1)
+ {
+ name = $"Pickled {item.Name}",
+ price = 50 + item.Price * 2,
+ preserve = SObject.PreserveType.Pickle,
+ preservedParentSheetIndex = item.parentSheetIndex
+ });
+ }
+
+ // flower honey
+ else if (item.category == SObject.flowersCategory)
+ {
+ // get honey type
+ SObject.HoneyType? type = null;
+ switch (item.parentSheetIndex)
+ {
+ case 376:
+ type = SObject.HoneyType.Poppy;
+ break;
+ case 591:
+ type = SObject.HoneyType.Tulip;
+ break;
+ case 593:
+ type = SObject.HoneyType.SummerSpangle;
+ break;
+ case 595:
+ type = SObject.HoneyType.FairyRose;
+ break;
+ case 597:
+ type = SObject.HoneyType.BlueJazz;
+ break;
+ case 421: // sunflower standing in for all other flowers
+ type = SObject.HoneyType.Wild;
+ break;
+ }
+
+ // yield honey
+ if (type != null)
+ {
+ SObject honey = new SObject(Vector2.Zero, 340, item.Name + " Honey", false, true, false, false)
+ {
+ name = "Wild Honey",
+ honeyType = type
+ };
+ if (type != SObject.HoneyType.Wild)
+ {
+ honey.name = $"{item.Name} Honey";
+ honey.price += item.price * 2;
+ }
+ yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 5 + id, honey);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/TrainerMod/ItemData/ISearchItem.cs b/src/TrainerMod/ItemData/ISearchItem.cs
deleted file mode 100644
index b2f7c2b8..00000000
--- a/src/TrainerMod/ItemData/ISearchItem.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace TrainerMod.ItemData
-{
- /// <summary>An item that can be searched and added to the player's inventory through the console.</summary>
- internal interface ISearchItem
- {
- /*********
- ** Accessors
- *********/
- /// <summary>Whether the item is valid.</summary>
- bool IsValid { get; }
-
- /// <summary>The item ID.</summary>
- int ID { get; }
-
- /// <summary>The item name.</summary>
- string Name { get; }
-
- /// <summary>The item type.</summary>
- ItemType Type { get; }
- }
-} \ No newline at end of file
diff --git a/src/TrainerMod/ItemData/ItemType.cs b/src/TrainerMod/ItemData/ItemType.cs
deleted file mode 100644
index 2e049aa1..00000000
--- a/src/TrainerMod/ItemData/ItemType.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace TrainerMod.ItemData
-{
- /// <summary>An item type that can be searched and added to the player through the console.</summary>
- internal enum ItemType
- {
- /// <summary>Any object in <see cref="StardewValley.Game1.objectInformation"/> (except rings).</summary>
- Object,
-
- /// <summary>A ring in <see cref="StardewValley.Game1.objectInformation"/>.</summary>
- Ring,
-
- /// <summary>A weapon from <c>Data\weapons</c>.</summary>
- Weapon
- }
-}
diff --git a/src/TrainerMod/ItemData/SearchableObject.cs b/src/TrainerMod/ItemData/SearchableObject.cs
deleted file mode 100644
index 30362f54..00000000
--- a/src/TrainerMod/ItemData/SearchableObject.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using StardewValley;
-
-namespace TrainerMod.ItemData
-{
- /// <summary>An object that can be searched and added to the player's inventory through the console.</summary>
- internal class SearchableObject : ISearchItem
- {
- /*********
- ** Properties
- *********/
- /// <summary>The underlying item.</summary>
- private readonly Item Item;
-
-
- /*********
- ** Accessors
- *********/
- /// <summary>Whether the item is valid.</summary>
- public bool IsValid => this.Item != null && this.Item.Name != "Broken Item";
-
- /// <summary>The item ID.</summary>
- public int ID => this.Item.parentSheetIndex;
-
- /// <summary>The item name.</summary>
- public string Name => this.Item.Name;
-
- /// <summary>The item type.</summary>
- public ItemType Type => ItemType.Object;
-
-
- /*********
- ** Accessors
- *********/
- /// <summary>Construct an instance.</summary>
- /// <param name="id">The item ID.</param>
- public SearchableObject(int id)
- {
- try
- {
- this.Item = new Object(id, 1);
- }
- catch
- {
- // invalid
- }
- }
- }
-} \ No newline at end of file
diff --git a/src/TrainerMod/ItemData/SearchableRing.cs b/src/TrainerMod/ItemData/SearchableRing.cs
deleted file mode 100644
index 7751e6aa..00000000
--- a/src/TrainerMod/ItemData/SearchableRing.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using StardewValley.Objects;
-
-namespace TrainerMod.ItemData
-{
- /// <summary>A ring that can be searched and added to the player's inventory through the console.</summary>
- internal class SearchableRing : ISearchItem
- {
- /*********
- ** Properties
- *********/
- /// <summary>The underlying item.</summary>
- private readonly Ring Ring;
-
-
- /*********
- ** Accessors
- *********/
- /// <summary>Whether the item is valid.</summary>
- public bool IsValid => this.Ring != null;
-
- /// <summary>The item ID.</summary>
- public int ID => this.Ring.parentSheetIndex;
-
- /// <summary>The item name.</summary>
- public string Name => this.Ring.Name;
-
- /// <summary>The item type.</summary>
- public ItemType Type => ItemType.Ring;
-
-
- /*********
- ** Accessors
- *********/
- /// <summary>Construct an instance.</summary>
- /// <param name="id">The ring ID.</param>
- public SearchableRing(int id)
- {
- try
- {
- this.Ring = new Ring(id);
- }
- catch
- {
- // invalid
- }
- }
- }
-} \ No newline at end of file
diff --git a/src/TrainerMod/ItemData/SearchableWeapon.cs b/src/TrainerMod/ItemData/SearchableWeapon.cs
deleted file mode 100644
index cc9ef459..00000000
--- a/src/TrainerMod/ItemData/SearchableWeapon.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using StardewValley.Tools;
-
-namespace TrainerMod.ItemData
-{
- /// <summary>A weapon that can be searched and added to the player's inventory through the console.</summary>
- internal class SearchableWeapon : ISearchItem
- {
- /*********
- ** Properties
- *********/
- /// <summary>The underlying item.</summary>
- private readonly MeleeWeapon Weapon;
-
-
- /*********
- ** Accessors
- *********/
- /// <summary>Whether the item is valid.</summary>
- public bool IsValid => this.Weapon != null;
-
- /// <summary>The item ID.</summary>
- public int ID => this.Weapon.initialParentTileIndex;
-
- /// <summary>The item name.</summary>
- public string Name => this.Weapon.Name;
-
- /// <summary>The item type.</summary>
- public ItemType Type => ItemType.Weapon;
-
-
- /*********
- ** Accessors
- *********/
- /// <summary>Construct an instance.</summary>
- /// <param name="id">The weapon ID.</param>
- public SearchableWeapon(int id)
- {
- try
- {
- this.Weapon = new MeleeWeapon(id);
- }
- catch
- {
- // invalid
- }
- }
- }
-} \ No newline at end of file
diff --git a/src/TrainerMod/TrainerMod.cs b/src/TrainerMod/TrainerMod.cs
index 9a3a8d0b..5db02cd6 100644
--- a/src/TrainerMod/TrainerMod.cs
+++ b/src/TrainerMod/TrainerMod.cs
@@ -1,17 +1,9 @@
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.Linq;
-using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
-using StardewValley;
-using StardewValley.Locations;
-using StardewValley.Menus;
-using StardewValley.Objects;
-using StardewValley.Tools;
-using TrainerMod.ItemData;
-using Object = StardewValley.Object;
+using TrainerMod.Framework.Commands;
namespace TrainerMod
{
@@ -21,20 +13,8 @@ namespace TrainerMod
/*********
** Properties
*********/
- /// <summary>The time of day at which to freeze time.</summary>
- private int FrozenTime;
-
- /// <summary>Whether to keep the player's health at its maximum.</summary>
- private bool InfiniteHealth;
-
- /// <summary>Whether to keep the player's stamina at its maximum.</summary>
- private bool InfiniteStamina;
-
- /// <summary>Whether to keep the player's money at a set value.</summary>
- private bool InfiniteMoney;
-
- /// <summary>Whether to freeze time.</summary>
- private bool FreezeTime;
+ /// <summary>The commands to handle.</summary>
+ private ITrainerCommand[] Commands;
/*********
@@ -44,829 +24,52 @@ namespace TrainerMod
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper)
{
- this.RegisterCommands(helper);
- GameEvents.UpdateTick += this.ReceiveUpdateTick;
+ // register commands
+ this.Commands = this.ScanForCommands().ToArray();
+ foreach (ITrainerCommand command in this.Commands)
+ helper.ConsoleCommands.Add(command.Name, command.Description, (name, args) => this.HandleCommand(command, name, args));
+
+ // hook events
+ GameEvents.UpdateTick += this.GameEvents_UpdateTick;
}
/*********
** Private methods
*********/
- /****
- ** Implementation
- ****/
/// <summary>The method invoked when the game updates its state.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
- private void ReceiveUpdateTick(object sender, EventArgs e)
+ private void GameEvents_UpdateTick(object sender, EventArgs e)
{
- if (Game1.player == null)
+ if (!Context.IsWorldReady)
return;
- if (this.InfiniteHealth)
- Game1.player.health = Game1.player.maxHealth;
- if (this.InfiniteStamina)
- Game1.player.stamina = Game1.player.MaxStamina;
- if (this.InfiniteMoney)
- Game1.player.money = 999999;
- if (this.FreezeTime)
- Game1.timeOfDay = this.FrozenTime;
- }
-
- /****
- ** Command definitions
- ****/
- /// <summary>Register all trainer commands.</summary>
- /// <param name="helper">Provides simplified APIs for writing mods.</param>
- private void RegisterCommands(IModHelper helper)
- {
- helper.ConsoleCommands
- .Add("save", "Saves the game? Doesn't seem to work.", this.HandleCommand)
- .Add("load", "Shows the load screen.", this.HandleCommand)
- .Add("player_setname", "Sets the player's name.\n\nUsage: player_setname <target> <name>\n- target: what to rename (one of 'player' or 'farm').\n- name: the new name to set.", this.HandleCommand)
- .Add("player_setmoney", "Sets the player's money.\n\nUsage: player_setmoney <value>\n- value: an integer amount, or 'inf' for infinite money.", this.HandleCommand)
- .Add("player_setstamina", "Sets the player's stamina.\n\nUsage: player_setstamina [value]\n- value: an integer amount, or 'inf' for infinite stamina.", this.HandleCommand)
- .Add("player_setmaxstamina", "Sets the player's max stamina.\n\nUsage: player_setmaxstamina [value]\n- value: an integer amount.", this.HandleCommand)
- .Add("player_sethealth", "Sets the player's health.\n\nUsage: player_sethealth [value]\n- value: an integer amount, or 'inf' for infinite health.", this.HandleCommand)
- .Add("player_setmaxhealth", "Sets the player's max health.\n\nUsage: player_setmaxhealth [value]\n- value: an integer amount.", this.HandleCommand)
- .Add("player_setimmunity", "Sets the player's immunity.\n\nUsage: player_setimmunity [value]\n- value: an integer amount.", this.HandleCommand)
-
- .Add("player_setlevel", "Sets the player's specified skill to the specified value.\n\nUsage: player_setlevel <skill> <value>\n- skill: the skill to set (one of 'luck', 'mining', 'combat', 'farming', 'fishing', or 'foraging').\n- value: the target level (a number from 1 to 10).", this.HandleCommand)
- .Add("player_setspeed", "Sets the player's speed to the specified value?\n\nUsage: player_setspeed <value>\n- value: an integer amount (0 is normal).", this.HandleCommand)
- .Add("player_changecolor", "Sets the color of a player feature.\n\nUsage: player_changecolor <target> <color>\n- target: what to change (one of 'hair', 'eyes', or 'pants').\n- color: a color value in RGB format, like (255,255,255).", this.HandleCommand)
- .Add("player_changestyle", "Sets the style of a player feature.\n\nUsage: player_changecolor <target> <value>.\n- target: what to change (one of 'hair', 'shirt', 'skin', 'acc', 'shoe', 'swim', or 'gender').\n- value: the integer style ID.", this.HandleCommand)
-
- .Add("player_additem", $"Gives the player an item.\n\nUsage: player_additem <item> [count] [quality]\n- item: the item ID (use the 'list_items' command to see a list).\n- count (optional): how many of the item to give.\n- quality (optional): one of {Object.lowQuality} (normal), {Object.medQuality} (silver), {Object.highQuality} (gold), or {Object.bestQuality} (iridium).", this.HandleCommand)
- .Add("player_addweapon", "Gives the player a weapon.\n\nUsage: player_addweapon <item>\n- item: the weapon ID (use the 'list_items' command to see a list).", this.HandleCommand)
- .Add("player_addring", "Gives the player a ring.\n\nUsage: player_addring <item>\n- item: the ring ID (use the 'list_items' command to see a list).", this.HandleCommand)
-
- .Add("list_items", "Lists and searches items in the game data.\n\nUsage: list_items [search]\n- search (optional): an arbitrary search string to filter by.", this.HandleCommand)
-
- .Add("world_freezetime", "Freezes or resumes time.\n\nUsage: world_freezetime [value]\n- value: one of 0 (resume), 1 (freeze), or blank (toggle).", this.HandleCommand)
- .Add("world_settime", "Sets the time to the specified value.\n\nUsage: world_settime <value>\n- value: the target time in military time (like 0600 for 6am and 1800 for 6pm)", this.HandleCommand)
- .Add("world_setday", "Sets the day to the specified value.\n\nUsage: world_setday <value>.\n- value: the target day (a number from 1 to 28).", this.HandleCommand)
- .Add("world_setseason", "Sets the season to the specified value.\n\nUsage: world_setseason <season>\n- season: the target season (one of 'spring', 'summer', 'fall', 'winter').", this.HandleCommand)
- .Add("world_setyear", "Sets the year to the specified value.\n\nUsage: world_setyear <year>\n- year: the target year (a number starting from 1).", this.HandleCommand)
- .Add("world_downminelevel", "Goes down one mine level?", this.HandleCommand)
- .Add("world_setminelevel", "Sets the mine level?\n\nUsage: world_setminelevel <value>\n- value: The target level (a number between 1 and 120).", this.HandleCommand)
-
- .Add("show_game_files", "Opens the game folder.", this.HandleCommand)
- .Add("show_data_files", "Opens the folder containing the save and log files.", this.HandleCommand)
-
- .Add("debug", "Run one of the game's debug commands; for example, 'debug warp FarmHouse 1 1' warps the player to the farmhouse.", this.HandleCommand);
+ foreach (ITrainerCommand command in this.Commands)
+ {
+ if (command.NeedsUpdate)
+ command.Update(this.Monitor);
+ }
}
/// <summary>Handle a TrainerMod command.</summary>
- /// <param name="command">The command name.</param>
+ /// <param name="command">The command to invoke.</param>
+ /// <param name="commandName">The command name specified by the user.</param>
/// <param name="args">The command arguments.</param>
- private void HandleCommand(string command, string[] args)
+ private void HandleCommand(ITrainerCommand command, string commandName, string[] args)
{
- switch (command)
- {
- case "debug":
- // submit command
- string debugCommand = string.Join(" ", args);
- string oldOutput = Game1.debugOutput;
- Game1.game1.parseDebugInput(debugCommand);
-
- // show result
- this.Monitor.Log(Game1.debugOutput != oldOutput
- ? $"> {Game1.debugOutput}"
- : "Sent debug command to the game, but there was no output.", LogLevel.Info);
- break;
-
- case "save":
- this.Monitor.Log("Saving the game...", LogLevel.Info);
- SaveGame.Save();
- break;
-
- case "load":
- this.Monitor.Log("Triggering load menu...", LogLevel.Info);
- Game1.hasLoadedGame = false;
- Game1.activeClickableMenu = new LoadGameMenu();
- break;
-
- case "player_setname":
- if (args.Length > 1)
- {
- string target = args[0];
- string[] validTargets = { "player", "farm" };
- if (validTargets.Contains(target))
- {
- switch (target)
- {
- case "player":
- Game1.player.Name = args[1];
- this.Monitor.Log($"OK, your player's name is now {Game1.player.Name}.", LogLevel.Info);
- break;
- case "farm":
- Game1.player.farmName = args[1];
- this.Monitor.Log($"OK, your farm's name is now {Game1.player.Name}.", LogLevel.Info);
- break;
- }
- }
- else
- this.LogArgumentsInvalid(command);
- }
- else
- this.Monitor.Log($"Your name is currently '{Game1.player.Name}'. Type 'help player_setname' for usage.", LogLevel.Info);
- break;
-
- case "player_setmoney":
- if (args.Any())
- {
- string amountStr = args[0];
- if (amountStr == "inf")
- {
- this.InfiniteMoney = true;
- this.Monitor.Log("OK, you now have infinite money.", LogLevel.Info);
- }
- else
- {
- this.InfiniteMoney = false;
- int amount;
- if (int.TryParse(amountStr, out amount))
- {
- Game1.player.Money = amount;
- this.Monitor.Log($"OK, you now have {Game1.player.Money} gold.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- }
- else
- this.Monitor.Log($"You currently have {(this.InfiniteMoney ? "infinite" : Game1.player.Money.ToString())} gold. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_setstamina":
- if (args.Any())
- {
- string amountStr = args[0];
- if (amountStr == "inf")
- {
- this.InfiniteStamina = true;
- this.Monitor.Log("OK, you now have infinite stamina.", LogLevel.Info);
- }
- else
- {
- this.InfiniteStamina = false;
- int amount;
- if (int.TryParse(amountStr, out amount))
- {
- Game1.player.Stamina = amount;
- this.Monitor.Log($"OK, you now have {Game1.player.Stamina} stamina.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- }
- else
- this.Monitor.Log($"You currently have {(this.InfiniteStamina ? "infinite" : Game1.player.Stamina.ToString())} stamina. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_setmaxstamina":
- if (args.Any())
- {
- int amount;
- if (int.TryParse(args[0], out amount))
- {
- Game1.player.MaxStamina = amount;
- this.Monitor.Log($"OK, you now have {Game1.player.MaxStamina} max stamina.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"You currently have {Game1.player.MaxStamina} max stamina. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_setlevel":
- if (args.Length > 1)
- {
- string skill = args[0];
- string[] skills = { "luck", "mining", "combat", "farming", "fishing", "foraging" };
- if (skills.Contains(skill))
- {
- int level;
- if (int.TryParse(args[1], out level))
- {
- switch (skill)
- {
- case "luck":
- Game1.player.LuckLevel = level;
- this.Monitor.Log($"OK, your luck skill is now {Game1.player.LuckLevel}.", LogLevel.Info);
- break;
- case "mining":
- Game1.player.MiningLevel = level;
- this.Monitor.Log($"OK, your mining skill is now {Game1.player.MiningLevel}.", LogLevel.Info);
- break;
- case "combat":
- Game1.player.CombatLevel = level;
- this.Monitor.Log($"OK, your combat skill is now {Game1.player.CombatLevel}.", LogLevel.Info);
- break;
- case "farming":
- Game1.player.FarmingLevel = level;
- this.Monitor.Log($"OK, your farming skill is now {Game1.player.FarmingLevel}.", LogLevel.Info);
- break;
- case "fishing":
- Game1.player.FishingLevel = level;
- this.Monitor.Log($"OK, your fishing skill is now {Game1.player.FishingLevel}.", LogLevel.Info);
- break;
- case "foraging":
- Game1.player.ForagingLevel = level;
- this.Monitor.Log($"OK, your foraging skill is now {Game1.player.ForagingLevel}.", LogLevel.Info);
- break;
- }
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.LogUsageError("That isn't a valid skill.", command);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "player_setspeed":
- if (args.Any())
- {
- int addedSpeed;
- if (int.TryParse(args[0], out addedSpeed))
- {
- Game1.player.addedSpeed = addedSpeed;
- this.Monitor.Log($"OK, your added speed is now {Game1.player.addedSpeed}.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"You currently have {Game1.player.addedSpeed} added speed. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_changecolor":
- if (args.Length > 1)
- {
- string target = args[0];
- string[] validTargets = { "hair", "eyes", "pants" };
- if (validTargets.Contains(target))
- {
- string[] colorHexes = args[1].Split(new[] { ',' }, 3);
- int r, g, b;
- if (int.TryParse(colorHexes[0], out r) && int.TryParse(colorHexes[1], out g) && int.TryParse(colorHexes[2], out b))
- {
- Color color = new Color(r, g, b);
- switch (target)
- {
- case "hair":
- Game1.player.hairstyleColor = color;
- this.Monitor.Log("OK, your hair color is updated.", LogLevel.Info);
- break;
- case "eyes":
- Game1.player.changeEyeColor(color);
- this.Monitor.Log("OK, your eye color is updated.", LogLevel.Info);
- break;
- case "pants":
- Game1.player.pantsColor = color;
- this.Monitor.Log("OK, your pants color is updated.", LogLevel.Info);
- break;
- }
- }
- else
- this.LogUsageError("The color should be an RBG value like '255,150,0'.", command);
- }
- else
- this.LogArgumentsInvalid(command);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "player_changestyle":
- if (args.Length > 1)
- {
- string target = args[0];
- string[] validTargets = { "hair", "shirt", "skin", "acc", "shoe", "swim", "gender" };
- if (validTargets.Contains(target))
- {
- int styleID;
- if (int.TryParse(args[1], out styleID))
- {
- switch (target)
- {
- case "hair":
- Game1.player.changeHairStyle(styleID);
- this.Monitor.Log("OK, your hair style is updated.", LogLevel.Info);
- break;
- case "shirt":
- Game1.player.changeShirt(styleID);
- this.Monitor.Log("OK, your shirt style is updated.", LogLevel.Info);
- break;
- case "acc":
- Game1.player.changeAccessory(styleID);
- this.Monitor.Log("OK, your accessory style is updated.", LogLevel.Info);
- break;
- case "skin":
- Game1.player.changeSkinColor(styleID);
- this.Monitor.Log("OK, your skin color is updated.", LogLevel.Info);
- break;
- case "shoe":
- Game1.player.changeShoeColor(styleID);
- this.Monitor.Log("OK, your shoe style is updated.", LogLevel.Info);
- break;
- case "swim":
- switch (styleID)
- {
- case 0:
- Game1.player.changeOutOfSwimSuit();
- this.Monitor.Log("OK, you're no longer in your swimming suit.", LogLevel.Info);
- break;
- case 1:
- Game1.player.changeIntoSwimsuit();
- this.Monitor.Log("OK, you're now in your swimming suit.", LogLevel.Info);
- break;
- default:
- this.LogUsageError("The swim value should be 0 (no swimming suit) or 1 (swimming suit).", command);
- break;
- }
- break;
- case "gender":
- switch (styleID)
- {
- case 0:
- Game1.player.changeGender(true);
- this.Monitor.Log("OK, you're now male.", LogLevel.Info);
- break;
- case 1:
- Game1.player.changeGender(false);
- this.Monitor.Log("OK, you're now female.", LogLevel.Info);
- break;
- default:
- this.LogUsageError("The gender value should be 0 (male) or 1 (female).", command);
- break;
- }
- break;
- }
- }
- else
- this.LogArgumentsInvalid(command);
- }
- else
- this.LogArgumentsInvalid(command);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "world_freezetime":
- if (args.Any())
- {
- int value;
- if (int.TryParse(args[0], out value))
- {
- if (value == 0 || value == 1)
- {
- this.FreezeTime = value == 1;
- this.FrozenTime = this.FreezeTime ? Game1.timeOfDay : 0;
- this.Monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info);
- }
- else
- this.LogUsageError("The value should be 0 (not frozen), 1 (frozen), or empty (toggle).", command);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- {
- this.FreezeTime = !this.FreezeTime;
- this.FrozenTime = this.FreezeTime ? Game1.timeOfDay : 0;
- this.Monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info);
- }
- break;
-
- case "world_settime":
- if (args.Any())
- {
- int time;
- if (int.TryParse(args[0], out time))
- {
- if (time <= 2600 && time >= 600)
- {
- Game1.timeOfDay = time;
- this.FrozenTime = this.FreezeTime ? Game1.timeOfDay : 0;
- this.Monitor.Log($"OK, the time is now {Game1.timeOfDay.ToString().PadLeft(4, '0')}.", LogLevel.Info);
- }
- else
- this.LogUsageError("That isn't a valid time.", command);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"The current time is {Game1.timeOfDay}. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "world_setday":
- if (args.Any())
- {
- int day;
- if (int.TryParse(args[0], out day))
- {
- if (day <= 28 && day > 0)
- {
- Game1.dayOfMonth = day;
- this.Monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info);
- }
- else
- this.LogUsageError("That isn't a valid day.", command);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"The current date is {Game1.currentSeason} {Game1.dayOfMonth}. Specify a value to change the day.", LogLevel.Info);
- break;
-
- case "world_setseason":
- if (args.Any())
- {
- string season = args[0];
- string[] validSeasons = { "winter", "spring", "summer", "fall" };
- if (validSeasons.Contains(season))
- {
- Game1.currentSeason = season;
- this.Monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info);
- }
- else
- this.LogUsageError("That isn't a valid season name.", command);
- }
- else
- this.Monitor.Log($"The current season is {Game1.currentSeason}. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "world_setyear":
- if (args.Any())
- {
- int year;
- if (int.TryParse(args[0], out year))
- {
- if (year >= 1)
- {
- Game1.year = year;
- this.Monitor.Log($"OK, the year is now {Game1.year}.", LogLevel.Info);
- }
- else
- this.LogUsageError("That isn't a valid year.", command);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"The current year is {Game1.year}. Specify a value to change the year.", LogLevel.Info);
- break;
-
- case "player_sethealth":
- if (args.Any())
- {
- string amountStr = args[0];
-
- if (amountStr == "inf")
- {
- this.InfiniteHealth = true;
- this.Monitor.Log("OK, you now have infinite health.", LogLevel.Info);
- }
- else
- {
- this.InfiniteHealth = false;
- int amount;
- if (int.TryParse(amountStr, out amount))
- {
- Game1.player.health = amount;
- this.Monitor.Log($"OK, you now have {Game1.player.health} health.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- }
- else
- this.Monitor.Log($"You currently have {(this.InfiniteHealth ? "infinite" : Game1.player.health.ToString())} health. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_setmaxhealth":
- if (args.Any())
- {
- int maxHealth;
- if (int.TryParse(args[0], out maxHealth))
- {
- Game1.player.maxHealth = maxHealth;
- this.Monitor.Log($"OK, you now have {Game1.player.maxHealth} max health.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"You currently have {Game1.player.maxHealth} max health. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_setimmunity":
- if (args.Any())
- {
- int amount;
- if (int.TryParse(args[0], out amount))
- {
- Game1.player.immunity = amount;
- this.Monitor.Log($"OK, you now have {Game1.player.immunity} immunity.", LogLevel.Info);
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.Monitor.Log($"You currently have {Game1.player.immunity} immunity. Specify a value to change it.", LogLevel.Info);
- break;
-
- case "player_additem":
- if (args.Any())
- {
- int itemID;
- if (int.TryParse(args[0], out itemID))
- {
- int count = 1;
- int quality = 0;
- if (args.Length > 1)
- {
- if (!int.TryParse(args[1], out count))
- {
- this.LogUsageError("The optional count is invalid.", command);
- return;
- }
-
- if (args.Length > 2 && !int.TryParse(args[2], out quality))
- {
- this.LogUsageError("The optional quality is invalid.", command);
- return;
- }
- }
-
- var item = new Object(itemID, count) { quality = quality };
- if (item.Name == "Error Item")
- this.Monitor.Log("There is no such item ID.", LogLevel.Error);
- else
- {
- Game1.player.addItemByMenuIfNecessary(item);
- this.Monitor.Log($"OK, added {item.Name} to your inventory.", LogLevel.Info);
- }
- }
- else
- this.LogUsageError("The item ID must be an integer.", command);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "player_addweapon":
- if (args.Any())
- {
- int weaponID;
- if (int.TryParse(args[0], out weaponID))
- {
- // get raw weapon data
- string data;
- if (!Game1.content.Load<Dictionary<int, string>>("Data\\weapons").TryGetValue(weaponID, out data))
- {
- this.Monitor.Log("There is no such weapon ID.", LogLevel.Error);
- return;
- }
-
- // get raw weapon type
- int type;
- {
- string[] fields = data.Split('/');
- string typeStr = fields.Length > 8 ? fields[8] : null;
- if (!int.TryParse(typeStr, out type))
- {
- this.Monitor.Log("Could not parse the data for the weapon with that ID.", LogLevel.Error);
- return;
- }
- }
-
- // get weapon
- Tool weapon;
- switch (type)
- {
- case MeleeWeapon.stabbingSword:
- case MeleeWeapon.dagger:
- case MeleeWeapon.club:
- case MeleeWeapon.defenseSword:
- weapon = new MeleeWeapon(weaponID);
- break;
-
- case 4:
- weapon = new Slingshot(weaponID);
- break;
-
- default:
- this.Monitor.Log($"The specified weapon has unknown type '{type}' in the game data.", LogLevel.Error);
- return;
- }
-
- // validate
- if (weapon.Name == null)
- {
- this.Monitor.Log("That weapon doesn't seem to be valid.", LogLevel.Error);
- return;
- }
-
- // add weapon
- Game1.player.addItemByMenuIfNecessary(weapon);
- this.Monitor.Log($"OK, added {weapon.Name} to your inventory.", LogLevel.Info);
- }
- else
- this.LogUsageError("The weapon ID must be an integer.", command);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "player_addring":
- if (args.Any())
- {
- int ringID;
- if (int.TryParse(args[0], out ringID))
- {
- if (ringID < Ring.ringLowerIndexRange || ringID > Ring.ringUpperIndexRange)
- this.Monitor.Log($"There is no such ring ID (must be between {Ring.ringLowerIndexRange} and {Ring.ringUpperIndexRange}).", LogLevel.Error);
- else
- {
- Ring ring = new Ring(ringID);
- Game1.player.addItemByMenuIfNecessary(ring);
- this.Monitor.Log($"OK, added {ring.Name} to your inventory.", LogLevel.Info);
- }
- }
- else
- this.Monitor.Log("<item> is invalid", LogLevel.Error);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "list_items":
- {
- var matches = this.GetItems(args).ToArray();
-
- // show matches
- string summary = "Searching...\n";
- if (matches.Any())
- this.Monitor.Log(summary + this.GetTableString(matches, new[] { "type", "id", "name" }, val => new[] { val.Type.ToString(), val.ID.ToString(), val.Name }), LogLevel.Info);
- else
- this.Monitor.Log(summary + "No items found", LogLevel.Info);
- }
- break;
-
- case "world_downminelevel":
- {
- int level = (Game1.currentLocation as MineShaft)?.mineLevel ?? 0;
- this.Monitor.Log($"OK, warping you to mine level {level + 1}.", LogLevel.Info);
- Game1.enterMine(false, level + 1, "");
- break;
- }
-
- case "world_setminelevel":
- if (args.Any())
- {
- int level;
- if (int.TryParse(args[0], out level))
- {
- level = Math.Max(1, level);
- this.Monitor.Log($"OK, warping you to mine level {level}.", LogLevel.Info);
- Game1.enterMine(true, level, "");
- }
- else
- this.LogArgumentNotInt(command);
- }
- else
- this.LogArgumentsInvalid(command);
- break;
-
- case "show_game_files":
- Process.Start(Constants.ExecutionPath);
- this.Monitor.Log($"OK, opening {Constants.ExecutionPath}.", LogLevel.Info);
- break;
-
- case "show_data_files":
- Process.Start(Constants.DataPath);
- this.Monitor.Log($"OK, opening {Constants.DataPath}.", LogLevel.Info);
- break;
-
- default:
- throw new NotImplementedException($"TrainerMod received unknown command '{command}'.");
- }
+ ArgumentParser argParser = new ArgumentParser(commandName, args, this.Monitor);
+ command.Handle(this.Monitor, commandName, argParser);
}
- /****
- ** Helpers
- ****/
- /// <summary>Get all items which can be searched and added to the player's inventory through the console.</summary>
- /// <param name="searchWords">The search string to find.</param>
- private IEnumerable<ISearchItem> GetItems(string[] searchWords)
+ /// <summary>Find all commands in the assembly.</summary>
+ private IEnumerable<ITrainerCommand> ScanForCommands()
{
- // normalise search term
- searchWords = searchWords?.Where(word => !string.IsNullOrWhiteSpace(word)).ToArray();
- if (searchWords?.Any() == false)
- searchWords = null;
-
- // find matches
return (
- from item in this.GetItems()
- let term = $"{item.ID}|{item.Type}|{item.Name}"
- where searchWords == null || searchWords.All(word => term.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) != -1)
- select item
- );
- }
-
- /// <summary>Get all items which can be searched and added to the player's inventory through the console.</summary>
- private IEnumerable<ISearchItem> GetItems()
- {
- // objects
- foreach (int id in Game1.objectInformation.Keys)
- {
- ISearchItem obj = id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange
- ? new SearchableRing(id)
- : (ISearchItem)new SearchableObject(id);
- if (obj.IsValid)
- yield return obj;
- }
-
- // weapons
- foreach (int id in Game1.content.Load<Dictionary<int, string>>("Data\\weapons").Keys)
- {
- ISearchItem weapon = new SearchableWeapon(id);
- if (weapon.IsValid)
- yield return weapon;
- }
- }
-
- /// <summary>Get an ASCII table for a set of tabular data.</summary>
- /// <typeparam name="T">The data type.</typeparam>
- /// <param name="data">The data to display.</param>
- /// <param name="header">The table header.</param>
- /// <param name="getRow">Returns a set of fields for a data value.</param>
- private string GetTableString<T>(IEnumerable<T> data, string[] header, Func<T, string[]> getRow)
- {
- // get table data
- int[] widths = header.Select(p => p.Length).ToArray();
- string[][] rows = data
- .Select(item =>
- {
- string[] fields = getRow(item);
- if (fields.Length != widths.Length)
- throw new InvalidOperationException($"Expected {widths.Length} columns, but found {fields.Length}: {string.Join(", ", fields)}");
-
- for (int i = 0; i < fields.Length; i++)
- widths[i] = Math.Max(widths[i], fields[i].Length);
-
- return fields;
- })
- .ToArray();
-
- // render fields
- List<string[]> lines = new List<string[]>(rows.Length + 2)
- {
- header,
- header.Select((value, i) => "".PadRight(widths[i], '-')).ToArray()
- };
- lines.AddRange(rows);
-
- return string.Join(
- Environment.NewLine,
- lines.Select(line => string.Join(" | ",
- line.Select((field, i) => field.PadRight(widths[i], ' ')).ToArray())
- )
+ from type in this.GetType().Assembly.GetTypes()
+ where !type.IsAbstract && typeof(ITrainerCommand).IsAssignableFrom(type)
+ select (ITrainerCommand)Activator.CreateInstance(type)
);
}
-
- /****
- ** Logging
- ****/
- /// <summary>Log an error indicating incorrect usage.</summary>
- /// <param name="error">A sentence explaining the problem.</param>
- /// <param name="command">The name of the command.</param>
- private void LogUsageError(string error, string command)
- {
- this.Monitor.Log($"{error} Type 'help {command}' for usage.", LogLevel.Error);
- }
-
- /// <summary>Log an error indicating a value must be an integer.</summary>
- /// <param name="command">The name of the command.</param>
- private void LogArgumentNotInt(string command)
- {
- this.LogUsageError("The value must be a whole number.", command);
- }
-
- /// <summary>Log an error indicating a value is invalid.</summary>
- /// <param name="command">The name of the command.</param>
- private void LogArgumentsInvalid(string command)
- {
- this.LogUsageError("The arguments are invalid.", command);
- }
}
}
diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj
index 46d8bef9..99a15c8f 100644
--- a/src/TrainerMod/TrainerMod.csproj
+++ b/src/TrainerMod/TrainerMod.csproj
@@ -51,11 +51,38 @@
<Compile Include="..\GlobalAssemblyInfo.cs">
<Link>Properties\GlobalAssemblyInfo.cs</Link>
</Compile>
- <Compile Include="ItemData\ISearchItem.cs" />
- <Compile Include="ItemData\ItemType.cs" />
- <Compile Include="ItemData\SearchableObject.cs" />
- <Compile Include="ItemData\SearchableRing.cs" />
- <Compile Include="ItemData\SearchableWeapon.cs" />
+ <Compile Include="Framework\Commands\ArgumentParser.cs" />
+ <Compile Include="Framework\Commands\Other\ShowDataFilesCommand.cs" />
+ <Compile Include="Framework\Commands\Other\ShowGameFilesCommand.cs" />
+ <Compile Include="Framework\Commands\Other\DebugCommand.cs" />
+ <Compile Include="Framework\Commands\Player\ListItemTypesCommand.cs" />
+ <Compile Include="Framework\Commands\Player\ListItemsCommand.cs" />
+ <Compile Include="Framework\Commands\Player\AddCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetStyleCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetColorCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetSpeedCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetLevelCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetMaxHealthCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetMaxStaminaCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetHealthCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetImmunityCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetStaminaCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetNameCommand.cs" />
+ <Compile Include="Framework\Commands\Player\SetMoneyCommand.cs" />
+ <Compile Include="Framework\Commands\Saves\LoadCommand.cs" />
+ <Compile Include="Framework\Commands\Saves\SaveCommand.cs" />
+ <Compile Include="Framework\Commands\TrainerCommand.cs" />
+ <Compile Include="Framework\Commands\World\SetMineLevelCommand.cs" />
+ <Compile Include="Framework\Commands\World\DownMineLevelCommand.cs" />
+ <Compile Include="Framework\Commands\World\SetYearCommand.cs" />
+ <Compile Include="Framework\Commands\World\SetSeasonCommand.cs" />
+ <Compile Include="Framework\Commands\World\SetDayCommand.cs" />
+ <Compile Include="Framework\Commands\World\SetTimeCommand.cs" />
+ <Compile Include="Framework\Commands\World\FreezeTimeCommand.cs" />
+ <Compile Include="Framework\ItemData\ItemType.cs" />
+ <Compile Include="Framework\Commands\ITrainerCommand.cs" />
+ <Compile Include="Framework\ItemData\SearchableItem.cs" />
+ <Compile Include="Framework\ItemRepository.cs" />
<Compile Include="TrainerMod.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
diff --git a/src/TrainerMod/manifest.json b/src/TrainerMod/manifest.json
index 40eb3237..f1665a45 100644
--- a/src/TrainerMod/manifest.json
+++ b/src/TrainerMod/manifest.json
@@ -3,8 +3,8 @@
"Author": "SMAPI",
"Version": {
"MajorVersion": 1,
- "MinorVersion": 14,
- "PatchVersion": 1,
+ "MinorVersion": 15,
+ "PatchVersion": 0,
"Build": null
},
"Description": "Adds SMAPI console commands that let you manipulate the game.",
diff --git a/src/crossplatform.targets b/src/crossplatform.targets
index 31d4722d..929aac6c 100644
--- a/src/crossplatform.targets
+++ b/src/crossplatform.targets
@@ -1,4 +1,6 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Condition="$(OS) != 'Windows_NT' AND Exists('$(HOME)\stardewvalley.targets')" Project="$(HOME)\stardewvalley.targets" />
+ <Import Condition="$(OS) == 'Windows_NT' AND Exists('$(USERPROFILE)\stardewvalley.targets')" Project="$(USERPROFILE)\stardewvalley.targets" />
<PropertyGroup>
<!-- Linux paths -->
<GamePath Condition="!Exists('$(GamePath)')">$(HOME)/GOG Games/Stardew Valley/game</GamePath>