using System.Collections.Generic; using System.IO; using System.Linq; using Godot; namespace KeepersCompound.TMV; public partial class TextureLoader { private readonly string _rootPath; // TODO: Load from installation resources private readonly string _fmPath; private readonly Dictionary _fmTexturePaths = new(); private readonly List _textureCache = new(); private readonly Dictionary _idMap = new(); private readonly Dictionary _pathMap = new(); public TextureLoader(string rootPath, string fmPath) { _rootPath = rootPath; _fmPath = fmPath; LoadDefaultTexture(); RegisterFmTexturePaths(); } private void LoadDefaultTexture() { // TODO: This should be a resource loaded from RES const string path = "user://textures/jorge.png"; var texture = ImageTexture.CreateFromImage(Image.LoadFromFile(path)); _textureCache.Add(texture); } private void RegisterFmTexturePaths() { // TODO: Load DDS BMP PCX GIF CEL string[] validExtensions = { "png", "tga" }; var famOptions = new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive }; var textureOptions = new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, RecurseSubdirectories = true, }; foreach (var dirPath in Directory.EnumerateDirectories(_fmPath, "fam", famOptions)) { foreach (var path in Directory.EnumerateFiles(dirPath, "*", textureOptions)) { if (validExtensions.Contains(path.GetExtension().ToLower())) { // TODO: This only adds the first one found rather than the highest priority var key = path.TrimPrefix(_fmPath).GetBaseName().ToLower(); _fmTexturePaths.TryAdd(key, path); } } } } public bool Load(int id, string path) { var userTexturesPath = ProjectSettings.GlobalizePath($"user://textures{path}.PCX"); var loaded = false; if (_fmTexturePaths.TryGetValue(path.ToLower(), out var filePath)) { _textureCache.Add(LoadTexture(filePath)); loaded = true; } else if (File.Exists(userTexturesPath)) { _textureCache.Add(LoadTexture(userTexturesPath)); loaded = true; } var index = loaded ? _textureCache.Count - 1 : 0; _idMap.TryAdd(id, index); _pathMap.TryAdd(path, index); return loaded; } private static ImageTexture LoadTexture(string path) { var ext = path.GetExtension().ToLower(); var texture = ext switch { "pcx" => LoadPcx(path), _ => ImageTexture.CreateFromImage(Image.LoadFromFile(path)), }; return texture; } public ImageTexture Get(int id) { if (!_idMap.ContainsKey(id)) { return _textureCache[0]; } return _textureCache[_idMap[id]]; } public ImageTexture Get(string path) { if (!_pathMap.ContainsKey(path)) { return _textureCache[0]; } return _textureCache[_pathMap[path]]; } }