using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.ContentManagers;
using StardewModdingAPI.Framework.Exceptions;
using StardewValley;
using xTile;
namespace StardewModdingAPI.Framework.ModHelpers
{
/// Provides an API for loading content assets.
internal class ContentHelper : BaseHelper, IContentHelper
{
/*********
** Fields
*********/
/// SMAPI's core content logic.
private readonly ContentCoordinator ContentCore;
/// A content manager for this mod which manages files from the game's Content folder.
private readonly IContentManager GameContentManager;
/// A content manager for this mod which manages files from the mod's folder.
private readonly ModContentManager ModContentManager;
/// The friendly mod name for use in errors.
private readonly string ModName;
/// Encapsulates monitoring and logging.
private readonly IMonitor Monitor;
/*********
** Accessors
*********/
/// The game's current locale code (like pt-BR).
public string CurrentLocale => this.GameContentManager.GetLocale();
/// The game's current locale as an enum value.
public LocalizedContentManager.LanguageCode CurrentLocaleConstant => this.GameContentManager.Language;
/// The observable implementation of .
internal ObservableCollection ObservableAssetEditors { get; } = new ObservableCollection();
/// The observable implementation of .
internal ObservableCollection ObservableAssetLoaders { get; } = new ObservableCollection();
/// Interceptors which provide the initial versions of matching content assets.
public IList AssetLoaders => this.ObservableAssetLoaders;
/// Interceptors which edit matching content assets after they're loaded.
public IList AssetEditors => this.ObservableAssetEditors;
/*********
** Public methods
*********/
/// Construct an instance.
/// SMAPI's core content logic.
/// The absolute path to the mod folder.
/// The unique ID of the relevant mod.
/// The friendly mod name for use in errors.
/// Encapsulates monitoring and logging.
public ContentHelper(ContentCoordinator contentCore, string modFolderPath, string modID, string modName, IMonitor monitor)
: base(modID)
{
string managedAssetPrefix = contentCore.GetManagedAssetPrefix(modID);
this.ContentCore = contentCore;
this.GameContentManager = contentCore.CreateGameContentManager(managedAssetPrefix + ".content");
this.ModContentManager = contentCore.CreateModContentManager(managedAssetPrefix, modName, modFolderPath, this.GameContentManager);
this.ModName = modName;
this.Monitor = monitor;
}
/// Load content from the game folder or mod folder (if not already cached), and return it. When loading a .png file, this must be called outside the game's draw loop.
/// The expected data type. The main supported types are , , and dictionaries; other types may be supported by the game's content pipeline.
/// The asset key to fetch (if the is ), or the local path to a content file relative to the mod folder.
/// Where to search for a matching content asset.
/// The is empty or contains invalid characters.
/// The content asset couldn't be loaded (e.g. because it doesn't exist).
public T Load(string key, ContentSource source = ContentSource.ModFolder)
{
try
{
this.AssertAndNormalizeAssetName(key);
switch (source)
{
case ContentSource.GameContent:
return this.GameContentManager.Load(key, this.CurrentLocaleConstant, useCache: false);
case ContentSource.ModFolder:
return this.ModContentManager.Load(key, Constants.DefaultLanguage, useCache: false);
default:
throw new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}: unknown content source '{source}'.");
}
}
catch (Exception ex) when (!(ex is SContentLoadException))
{
throw new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}.", ex);
}
}
/// Normalize an asset name so it's consistent with those generated by the game. This is mainly useful for string comparisons like on generated asset names, and isn't necessary when passing asset names into other content helper methods.
/// The asset key.
[Pure]
public string NormalizeAssetName(string assetName)
{
return this.ModContentManager.AssertAndNormalizeAssetName(assetName);
}
/// 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.
/// The asset key to fetch (if the is ), or the local path to a content file relative to the mod folder.
/// Where to search for a matching content asset.
/// The is empty or contains invalid characters.
public string GetActualAssetKey(string key, ContentSource source = ContentSource.ModFolder)
{
switch (source)
{
case ContentSource.GameContent:
return this.GameContentManager.AssertAndNormalizeAssetName(key);
case ContentSource.ModFolder:
return this.ModContentManager.GetInternalAssetKey(key);
default:
throw new NotSupportedException($"Unknown content source '{source}'.");
}
}
/// Remove an asset from the content cache so it's reloaded on the next request. This will reload core game assets if needed, but references to the former asset will still show the previous content.
/// The asset key to invalidate in the content folder.
/// The is empty or contains invalid characters.
/// Returns whether the given asset key was cached.
public bool InvalidateCache(string key)
{
string actualKey = this.GetActualAssetKey(key, ContentSource.GameContent);
this.Monitor.Log($"Requested cache invalidation for '{actualKey}'.", LogLevel.Trace);
return this.ContentCore.InvalidateCache(asset => asset.AssetNameEquals(actualKey)).Any();
}
/// Remove all assets of the given type from the cache so they're reloaded on the next request. This can be a very expensive operation and should only be used in very specific cases. This will reload core game assets if needed, but references to the former assets will still show the previous content.
/// The asset type to remove from the cache.
/// Returns whether any assets were invalidated.
public bool InvalidateCache()
{
this.Monitor.Log($"Requested cache invalidation for all assets of type {typeof(T)}. This is an expensive operation and should be avoided if possible.", LogLevel.Trace);
return this.ContentCore.InvalidateCache((key, type) => typeof(T).IsAssignableFrom(type)).Any();
}
/// Remove matching assets from the content cache so they're reloaded on the next request. This will reload core game assets if needed, but references to the former asset will still show the previous content.
/// A predicate matching the assets to invalidate.
/// Returns whether any cache entries were invalidated.
public bool InvalidateCache(Func predicate)
{
this.Monitor.Log("Requested cache invalidation for all assets matching a predicate.", LogLevel.Trace);
return this.ContentCore.InvalidateCache(predicate).Any();
}
/// Get a patch helper for arbitrary data.
/// The data type.
/// The asset data.
/// The asset name. This is only used for tracking purposes and has no effect on the patch helper.
public IAssetData GetPatchHelper(T data, string assetName = null)
{
if (data == null)
throw new ArgumentNullException(nameof(data), "Can't get a patch helper for a null value.");
assetName ??= $"temp/{Guid.NewGuid():N}";
return new AssetDataForObject(this.CurrentLocale, assetName, data, this.NormalizeAssetName);
}
/*********
** Private methods
*********/
/// Assert that the given key has a valid format.
/// The asset key to check.
/// The asset key is empty or contains invalid characters.
[SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")]
private void AssertAndNormalizeAssetName(string key)
{
this.ModContentManager.AssertAndNormalizeAssetName(key);
if (Path.IsPathRooted(key))
throw new ArgumentException("The asset key must not be an absolute path.");
}
}
}