diff options
author | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-04-29 22:44:57 -0400 |
---|---|---|
committer | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-04-29 22:44:57 -0400 |
commit | 3cfe14d27946518c1cd631607f878f7d2f4a2cdb (patch) | |
tree | eee1aa3ee88ede4769cd38e8b3982fd8b2a6f7c9 /src/StardewModdingAPI | |
parent | f52edf9e0b267e79f88c492e7d7e34f63744f21c (diff) | |
download | SMAPI-3cfe14d27946518c1cd631607f878f7d2f4a2cdb.tar.gz SMAPI-3cfe14d27946518c1cd631607f878f7d2f4a2cdb.tar.bz2 SMAPI-3cfe14d27946518c1cd631607f878f7d2f4a2cdb.zip |
add contentHelper.GetActualAssetKey(..) to support custom map tilesheets (#257)
Diffstat (limited to 'src/StardewModdingAPI')
-rw-r--r-- | src/StardewModdingAPI/Framework/ContentHelper.cs | 65 | ||||
-rw-r--r-- | src/StardewModdingAPI/Framework/SContentManager.cs | 42 | ||||
-rw-r--r-- | src/StardewModdingAPI/IContentHelper.cs | 6 |
3 files changed, 72 insertions, 41 deletions
diff --git a/src/StardewModdingAPI/Framework/ContentHelper.cs b/src/StardewModdingAPI/Framework/ContentHelper.cs index 04317a84..4d116b54 100644 --- a/src/StardewModdingAPI/Framework/ContentHelper.cs +++ b/src/StardewModdingAPI/Framework/ContentHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.Xna.Framework; @@ -21,7 +22,7 @@ namespace StardewModdingAPI.Framework private readonly string ModFolderPath; /// <summary>The path to the mod's folder, relative to the game's content folder (e.g. "../Mods/ModName").</summary> - private readonly string RelativeContentFolder; + private readonly string ModFolderPathFromContent; /// <summary>The friendly mod name for use in errors.</summary> private readonly string ModName; @@ -39,7 +40,7 @@ namespace StardewModdingAPI.Framework this.ContentManager = contentManager; this.ModFolderPath = modFolderPath; this.ModName = modName; - this.RelativeContentFolder = this.GetRelativePath(contentManager.FullRootDirectory, modFolderPath); + this.ModFolderPathFromContent = this.GetRelativePath(contentManager.FullRootDirectory, modFolderPath); } /// <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> @@ -50,13 +51,7 @@ namespace StardewModdingAPI.Framework /// <exception cref="ContentLoadException">The content asset couldn't be loaded (e.g. because it doesn't exist).</exception> public T Load<T>(string key, ContentSource source) { - // validate - if (string.IsNullOrWhiteSpace(key)) - throw new ArgumentException("The asset key or local path is empty."); - if (key.Intersect(Path.GetInvalidPathChars()).Any()) - throw new ArgumentException("The asset key or local path contains invalid characters."); - - // load content + this.AssertValidAssetKeyFormat(key); try { switch (source) @@ -72,16 +67,14 @@ namespace StardewModdingAPI.Framework if (!file.Exists) throw new ContentLoadException($"There is no file at path '{file.FullName}'."); - // get content-relative path - string contentPath = Path.Combine(this.RelativeContentFolder, key); - if (contentPath.EndsWith(".xnb")) - contentPath = contentPath.Substring(0, contentPath.Length - 4); + // get underlying asset key + string actualKey = this.GetActualAssetKey(key, source); // load content switch (file.Extension.ToLower()) { case ".xnb": - return this.ContentManager.Load<T>(contentPath); + return this.ContentManager.Load<T>(actualKey); case ".png": // validate @@ -89,15 +82,15 @@ namespace StardewModdingAPI.Framework throw new ContentLoadException($"Can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); // try cache - if (this.ContentManager.IsLoaded(contentPath)) - return this.ContentManager.Load<T>(contentPath); + if (this.ContentManager.IsLoaded(actualKey)) + return this.ContentManager.Load<T>(actualKey); // fetch & cache using (FileStream stream = File.OpenRead(file.FullName)) { - var texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); + Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); texture = this.PremultiplyTransparency(texture); - this.ContentManager.Inject(contentPath, texture); + this.ContentManager.Inject(actualKey, texture); return (T)(object)texture; } @@ -115,10 +108,44 @@ namespace StardewModdingAPI.Framework } } + /// <summary>Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists.</summary> + /// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to an XNB file relative to the mod folder.</param> + /// <param name="source">Where to search for a matching content asset.</param> + /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception> + public string GetActualAssetKey(string key, ContentSource source) + { + switch (source) + { + case ContentSource.GameContent: + return this.ContentManager.NormaliseAssetName(key); + + case ContentSource.ModFolder: + string contentPath = Path.Combine(this.ModFolderPathFromContent, key); + if (contentPath.EndsWith(".xnb")) + contentPath = contentPath.Substring(0, contentPath.Length - 4); + return this.ContentManager.NormaliseAssetName(contentPath); + + default: + throw new NotSupportedException($"Unknown content source '{source}'."); + } + } + /********* ** Private methods *********/ + /// <summary>Assert that the given key has a valid format.</summary> + /// <param name="key">The asset key to check.</param> + /// <exception cref="ArgumentException">The asset key is empty or contains invalid characters.</exception> + [SuppressMessage("ReSharper", "UnusedParameter.Local", Justification = "Parameter is only used for assertion checks by design.")] + private void AssertValidAssetKeyFormat(string key) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException("The asset key or local path is empty."); + if (key.Intersect(Path.GetInvalidPathChars()).Any()) + throw new ArgumentException("The asset key or local path contains invalid characters."); + } + /// <summary>Get a directory path relative to a given root.</summary> /// <param name="rootPath">The root path from which the path should be relative.</param> /// <param name="targetPath">The target file path.</param> @@ -184,7 +211,7 @@ namespace StardewModdingAPI.Framework //Game1.graphics.GraphicsDevice.Viewport = originalViewport; // store data from render target because the RenderTarget2D is volatile - var data = new Color[texture.Width * texture.Height]; + Color[] data = new Color[texture.Width * texture.Height]; renderTarget.GetData(data); // unset texture from graphic device and set modified data back to it diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index e363e6b4..99814c94 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -83,6 +83,26 @@ namespace StardewModdingAPI.Framework this.NormaliseAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load<T> logic } + /// <summary>Normalise an asset name so it's consistent with the underlying cache.</summary> + /// <param name="assetName">The asset key.</param> + public string NormaliseAssetName(string assetName) + { + // ensure name format is consistent + string[] parts = assetName.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); + assetName = string.Join(SContentManager.PreferredPathSeparator, parts); + + // apply platform normalisation logic + return this.NormaliseAssetNameForPlatform(assetName); + } + + /// <summary>Get whether the content manager has already loaded and cached the given asset.</summary> + /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> + public bool IsLoaded(string assetName) + { + assetName = this.NormaliseAssetName(assetName); + return this.IsNormalisedKeyLoaded(assetName); + } + /// <summary>Load an asset that has been processed by the content pipeline.</summary> /// <typeparam name="T">The type of asset to load.</typeparam> /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> @@ -116,31 +136,9 @@ namespace StardewModdingAPI.Framework this.Cache[assetName] = value; } - /// <summary>Get whether the content manager has already loaded and cached the given asset.</summary> - /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> - public bool IsLoaded(string assetName) - { - assetName = this.NormaliseAssetName(assetName); - return this.IsNormalisedKeyLoaded(assetName); - - } - - /********* ** Private methods *********/ - /// <summary>Normalise an asset name so it's consistent with the underlying cache.</summary> - /// <param name="assetName">The asset key.</param> - private string NormaliseAssetName(string assetName) - { - // ensure name format is consistent - string[] parts = assetName.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); - assetName = string.Join(SContentManager.PreferredPathSeparator, parts); - - // apply platform normalisation logic - return this.NormaliseAssetNameForPlatform(assetName); - } - /// <summary>Get whether an asset has already been loaded.</summary> /// <param name="normalisedAssetName">The normalised asset name.</param> private bool IsNormalisedKeyLoaded(string normalisedAssetName) diff --git a/src/StardewModdingAPI/IContentHelper.cs b/src/StardewModdingAPI/IContentHelper.cs index b878dfe5..7cde413b 100644 --- a/src/StardewModdingAPI/IContentHelper.cs +++ b/src/StardewModdingAPI/IContentHelper.cs @@ -14,5 +14,11 @@ namespace StardewModdingAPI /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception> /// <exception cref="ContentLoadException">The content asset couldn't be loaded (e.g. because it doesn't exist).</exception> T Load<T>(string key, ContentSource source); + + /// <summary>Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists.</summary> + /// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to an XNB file relative to the mod folder.</param> + /// <param name="source">Where to search for a matching content asset.</param> + /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception> + string GetActualAssetKey(string key, ContentSource source); } } |