using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI.AssemblyRewriters;
using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.Reflection;
using StardewValley;
using StardewValley.BellsAndWhistles;
using StardewValley.Objects;
using StardewValley.Projectiles;
namespace StardewModdingAPI.Framework
{
/// SMAPI's implementation of the game's content manager which lets it raise content events.
internal class SContentManager : LocalizedContentManager
{
/*********
** Properties
*********/
/// The possible directory separator characters in an asset key.
private static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray();
/// The preferred directory separator chaeacter in an asset key.
private static readonly string PreferredPathSeparator = Path.DirectorySeparatorChar.ToString();
/// Encapsulates monitoring and logging.
private readonly IMonitor Monitor;
/// The underlying content manager's asset cache.
private readonly IDictionary Cache;
/// Applies platform-specific asset key normalisation so it's consistent with the underlying cache.
private readonly Func NormaliseAssetNameForPlatform;
/// The private method which generates the locale portion of an asset name.
private readonly IPrivateMethod GetKeyLocale;
/*********
** Accessors
*********/
/// Interceptors which provide the initial versions of matching assets.
internal IDictionary> Loaders { get; } = new Dictionary>();
/// Interceptors which edit matching assets after they're loaded.
internal IDictionary> Editors { get; } = new Dictionary>();
/// The absolute path to the .
public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory);
/*********
** Public methods
*********/
/// Construct an instance.
/// The service provider to use to locate services.
/// The root directory to search for content.
/// The current culture for which to localise content.
/// The current language code for which to localise content.
/// Encapsulates monitoring and logging.
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;
// get underlying fields for interception
this.Cache = reflection.GetPrivateField>(this, "loadedAssets").GetValue();
this.GetKeyLocale = reflection.GetPrivateMethod(this, "languageCode");
// get asset key normalisation logic
if (Constants.TargetPlatform == Platform.Windows)
{
IPrivateMethod method = reflection.GetPrivateMethod(typeof(TitleContainer), "GetCleanPath");
this.NormaliseAssetNameForPlatform = path => method.Invoke(path);
}
else
this.NormaliseAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic
}
/// Normalise path separators in a file path. For asset keys, see instead.
/// The file path to normalise.
public string NormalisePathSeparators(string path)
{
string[] parts = path.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries);
string normalised = string.Join(SContentManager.PreferredPathSeparator, parts);
if (path.StartsWith(SContentManager.PreferredPathSeparator))
normalised = SContentManager.PreferredPathSeparator + normalised; // keep root slash
return normalised;
}
/// Normalise an asset name so it's consistent with the underlying cache.
/// The asset key.
public string NormaliseAssetName(string assetName)
{
assetName = this.NormalisePathSeparators(assetName);
if (assetName.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase))
return assetName.Substring(0, assetName.Length - 4);
return this.NormaliseAssetNameForPlatform(assetName);
}
/// Get whether the content manager has already loaded and cached the given asset.
/// The asset path relative to the loader root directory, not including the .xnb extension.
public bool IsLoaded(string assetName)
{
assetName = this.NormaliseAssetName(assetName);
return this.IsNormalisedKeyLoaded(assetName);
}
/// Load an asset that has been processed by the content pipeline.
/// The type of asset to load.
/// The asset path relative to the loader root directory, not including the .xnb extension.
public override T Load(string assetName)
{
assetName = this.NormaliseAssetName(assetName);
// skip if already loaded
if (this.IsNormalisedKeyLoaded(assetName))
return base.Load(assetName);
// load asset
T data;
{
IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, typeof(T), this.NormaliseAssetName);
IAssetData asset = this.ApplyLoader(info) ?? new AssetDataForObject(info, base.Load(assetName), this.NormaliseAssetName);
asset = this.ApplyEditors(info, asset);
data = (T)asset.Data;
}
// update cache & return data
this.Cache[assetName] = data;
return data;
}
/// Inject an asset into the cache.
/// The type of asset to inject.
/// The asset path relative to the loader root directory, not including the .xnb extension.
/// The asset value.
public void Inject(string assetName, T value)
{
assetName = this.NormaliseAssetName(assetName);
this.Cache[assetName] = value;
}
/// Get the current content locale.
public string GetLocale()
{
return this.GetKeyLocale.Invoke();
}
/// Reset the asset cache and reload the game's static assets.
/// This implementation is derived from .
public void Reset()
{
this.Monitor.Log("Resetting asset cache...", LogLevel.Trace);
this.Cache.Clear();
// from Game1.LoadContent
Game1.daybg = this.Load("LooseSprites\\daybg");
Game1.nightbg = this.Load("LooseSprites\\nightbg");
Game1.menuTexture = this.Load("Maps\\MenuTiles");
Game1.lantern = this.Load("LooseSprites\\Lighting\\lantern");
Game1.windowLight = this.Load("LooseSprites\\Lighting\\windowLight");
Game1.sconceLight = this.Load("LooseSprites\\Lighting\\sconceLight");
Game1.cauldronLight = this.Load("LooseSprites\\Lighting\\greenLight");
Game1.indoorWindowLight = this.Load("LooseSprites\\Lighting\\indoorWindowLight");
Game1.shadowTexture = this.Load("LooseSprites\\shadow");
Game1.mouseCursors = this.Load("LooseSprites\\Cursors");
Game1.controllerMaps = this.Load("LooseSprites\\ControllerMaps");
Game1.animations = this.Load("TileSheets\\animations");
Game1.achievements = this.Load>("Data\\Achievements");
Game1.NPCGiftTastes = this.Load>("Data\\NPCGiftTastes");
Game1.dialogueFont = this.Load("Fonts\\SpriteFont1");
Game1.smallFont = this.Load("Fonts\\SmallFont");
Game1.tinyFont = this.Load("Fonts\\tinyFont");
Game1.tinyFontBorder = this.Load("Fonts\\tinyFontBorder");
Game1.objectSpriteSheet = this.Load("Maps\\springobjects");
Game1.cropSpriteSheet = this.Load("TileSheets\\crops");
Game1.emoteSpriteSheet = this.Load("TileSheets\\emotes");
Game1.debrisSpriteSheet = this.Load("TileSheets\\debris");
Game1.bigCraftableSpriteSheet = this.Load("TileSheets\\Craftables");
Game1.rainTexture = this.Load("TileSheets\\rain");
Game1.buffsIcons = this.Load("TileSheets\\BuffsIcons");
Game1.objectInformation = this.Load>("Data\\ObjectInformation");
Game1.bigCraftablesInformation = this.Load>("Data\\BigCraftablesInformation");
FarmerRenderer.hairStylesTexture = this.Load("Characters\\Farmer\\hairstyles");
FarmerRenderer.shirtsTexture = this.Load("Characters\\Farmer\\shirts");
FarmerRenderer.hatsTexture = this.Load("Characters\\Farmer\\hats");
FarmerRenderer.accessoriesTexture = this.Load("Characters\\Farmer\\accessories");
Furniture.furnitureTexture = this.Load("TileSheets\\furniture");
SpriteText.spriteTexture = this.Load("LooseSprites\\font_bold");
SpriteText.coloredTexture = this.Load("LooseSprites\\font_colored");
Tool.weaponsTexture = this.Load("TileSheets\\weapons");
Projectile.projectileSheet = this.Load("TileSheets\\Projectiles");
// from Farmer constructor
if (Game1.player != null)
Game1.player.FarmerRenderer = new FarmerRenderer(this.Load("Characters\\Farmer\\farmer_" + (Game1.player.isMale ? "" : "girl_") + "base"));
}
/*********
** Private methods
*********/
/// Get whether an asset has already been loaded.
/// The normalised asset name.
private bool IsNormalisedKeyLoaded(string normalisedAssetName)
{
return this.Cache.ContainsKey(normalisedAssetName)
|| this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke()}"); // translated asset
}
/// Load the initial asset from the registered .
/// The basic asset metadata.
/// Returns the loaded asset metadata, or null if no loader matched.
private IAssetData ApplyLoader(IAssetInfo info)
{
// find matching loaders
var loaders = this.GetInterceptors(this.Loaders)
.Where(entry =>
{
try
{
return entry.Value.CanLoad(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(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);
}
/// Apply any to a loaded asset.
/// The asset type.
/// The basic asset metadata.
/// The loaded asset.
private IAssetData ApplyEditors(IAssetInfo info, IAssetData asset)
{
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(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(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;
}
/// Get all registered interceptors from a list.
private IEnumerable> GetInterceptors(IDictionary> entries)
{
foreach (var entry in entries)
{
IModMetadata metadata = entry.Key;
IList interceptors = entry.Value;
// special case if mod is an interceptor
if (metadata.Mod is T modAsInterceptor)
yield return new KeyValuePair(metadata, modAsInterceptor);
// registered editors
foreach (T interceptor in interceptors)
yield return new KeyValuePair(metadata, interceptor);
}
}
/// Dispose all game resources.
/// Whether the content manager is disposing (rather than finalising).
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();
}
}
}