Skip to content

Cache ModContentManagers loading of images #980

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/SMAPI/Framework/ContentManagers/ModContentManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
Expand Down Expand Up @@ -45,6 +46,8 @@ internal sealed class ModContentManager : BaseContentManager
/// <summary>If a map tilesheet's image source has no file extensions, the file extensions to check for in the local mod folder.</summary>
private static readonly string[] LocalTilesheetExtensions = [".png", ".xnb"];

private readonly Dictionary<string, RawTextureData> TextureCache = [];


/*********
** Public methods
Expand Down Expand Up @@ -220,6 +223,12 @@ private T LoadImageFile<T>(IAssetName assetName, FileInfo file)
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "The 'forRawData' parameter is only added for mods which may intercept this method.")]
private IRawTextureData LoadRawImageData(FileInfo file, bool forRawData)
{
if (this.TextureCache.TryGetValue(file.FullName, out var cacheResult))
{
var cacheColors = cacheResult.Data;
return new RawTextureData(cacheResult.Width, cacheResult.Height, cacheColors);
}

// load raw data
int width;
int height;
Expand All @@ -238,13 +247,19 @@ private IRawTextureData LoadRawImageData(FileInfo file, bool forRawData)

// convert to XNA pixel format
var pixels = GC.AllocateUninitializedArray<Color>(rawPixels.Length);
var pixelCache = GC.AllocateUninitializedArray<Color>(rawPixels.Length);
for (int i = 0; i < pixels.Length; i++)
{
SKPMColor pixel = rawPixels[i];
pixels[i] = pixel.Alpha == 0
? Color.Transparent
: new Color(r: pixel.Red, g: pixel.Green, b: pixel.Blue, alpha: pixel.Alpha);

pixelCache[i] = pixel.Alpha == 0
? Color.Transparent
: new Color(r: pixel.Red, g: pixel.Green, b: pixel.Blue, alpha: pixel.Alpha);
}
this.TextureCache.Add(file.FullName, new RawTextureData(width, height, pixelCache));

return new RawTextureData(width, height, pixels);
}
Expand Down