using System.IO; namespace DaggerFramework { public static class ResourceManager { public static string ResourceRoot { get; set; } = "Resources/"; public static T Load(string relativePath) where T : Resource { var path = GlobalizePath(relativePath); var loader = GetAssociatedResourceLoader(); var res = loader.Load(path); res.Path = path; return res as T; } public static T Load(string name, string relativePath) where T : Resource { T res = null; if (TryGetResourceFromCache(name, out res)) return res as T; res = Load(relativePath); AddResourceToCache(name, res); return res as T; } /// /// Loads a list of resources from a folder. Their names will be derived from the actual file name, excluding the extension. /// /// Resource type for all of the resources. /// Path to the folder, relative to the ResourceRoot. /// public static void LoadFolder(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(resName, resRelativePath); } } public static T Get(string name) where T : Resource { T res = null; if (TryGetResourceFromCache(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(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() where T : Resource { return _resourceLoaderAssociations[typeof(T)]; } private static KeyValuePair CreateResourceAssociation(Type type, ResourceLoader loader) { return new KeyValuePair(type, loader); } private static Dictionary _resourceCache = new Dictionary(); private static readonly Dictionary _resourceLoaderAssociations = new Dictionary() { {typeof(Texture2d), new Texture2dLoader()}, {typeof(Sound), new SoundLoader()} }; } }