87 lines
3.1 KiB
C#
Executable File
87 lines
3.1 KiB
C#
Executable File
using System.IO;
|
|
|
|
namespace DaggerFramework
|
|
{
|
|
public static class ResourceManager
|
|
{
|
|
public static string ResourceRoot { get; set; } = "Resources/";
|
|
public static T Load<T>(string relativePath) where T : Resource
|
|
{
|
|
var path = GlobalizePath(relativePath);
|
|
var loader = GetAssociatedResourceLoader<T>();
|
|
var res = loader.Load(path);
|
|
res.Path = path;
|
|
return res as T;
|
|
}
|
|
|
|
public static T Load<T>(string name, string relativePath) where T : Resource
|
|
{
|
|
T res = null;
|
|
if (TryGetResourceFromCache<T>(name, out res)) return res as T;
|
|
|
|
res = Load<T>(relativePath);
|
|
AddResourceToCache(name, res);
|
|
return res as T;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Loads a list of resources from a folder. Their names will be derived from the actual file name, excluding the extension.
|
|
/// </summary>
|
|
/// <typeparam name="T">Resource type for all of the resources.</typeparam>
|
|
/// <param name="localPath">Path to the folder, relative to the ResourceRoot.</param>
|
|
/// <returns></returns>
|
|
public static void LoadFolder<T>(string relativePath) where T : Resource
|
|
{
|
|
var files = Directory.GetFiles(GlobalizePath(relativePath));
|
|
foreach (var file in files)
|
|
{
|
|
var resName = Path.GetFileNameWithoutExtension(file);
|
|
var resRelativePath = Path.GetRelativePath(ResourceRoot, file);
|
|
|
|
Load<T>(resName, resRelativePath);
|
|
}
|
|
}
|
|
|
|
public static T Get<T>(string name) where T : Resource
|
|
{
|
|
T res = null;
|
|
if (TryGetResourceFromCache<T>(name, out res)) return res as T;
|
|
return res;
|
|
}
|
|
|
|
public static string GlobalizePath(string relativePath)
|
|
{
|
|
return Path.Join(ResourceRoot, relativePath);
|
|
}
|
|
|
|
private static void AddResourceToCache(string name, Resource resource)
|
|
{
|
|
_resourceCache.Add(name, resource);
|
|
}
|
|
|
|
private static bool TryGetResourceFromCache<T>(string name, out T resource) where T : Resource
|
|
{
|
|
resource = null;
|
|
if (!_resourceCache.ContainsKey(name)) return false;
|
|
resource = _resourceCache[name] as T;
|
|
return true;
|
|
}
|
|
|
|
private static ResourceLoader GetAssociatedResourceLoader<T>() where T : Resource
|
|
{
|
|
return _resourceLoaderAssociations[typeof(T)];
|
|
}
|
|
|
|
private static KeyValuePair<Type, ResourceLoader> CreateResourceAssociation(Type type, ResourceLoader loader)
|
|
{
|
|
return new KeyValuePair<Type, ResourceLoader>(type, loader);
|
|
}
|
|
|
|
private static Dictionary<string, Resource> _resourceCache = new Dictionary<string, Resource>();
|
|
private static readonly Dictionary<Type, ResourceLoader> _resourceLoaderAssociations = new Dictionary<Type, ResourceLoader>()
|
|
{
|
|
{typeof(Texture2d), new Texture2dLoader()},
|
|
{typeof(Sound), new SoundLoader()}
|
|
};
|
|
}
|
|
} |