using System.Collections.Generic; using System.Linq; using Godot; using KeepersCompound.LGS; namespace KeepersCompound.TMV; public partial class TextureLoader { private readonly List _textureCache = new(); private readonly Dictionary _idMap = new(); private readonly Dictionary _idPathMap = new(); private readonly Dictionary _pathMap = new(); public TextureLoader() { LoadDefaultTextures(); } private void LoadDefaultTextures() { _textureCache.Add(ResourceLoader.Load("res://project/jorge.png")); _textureCache.Add(ResourceLoader.Load("res://project/sky.png")); _idMap.Add(0, 0); _idMap.Add(249, 1); } public bool Register(int id, string path) { return _idPathMap.TryAdd(id, path); } private bool Load(int id, string path) { var loaded = false; var campaignResources = Context.Instance.CampaignResources; var texPath = campaignResources.GetResourcePath(ResourceType.Texture, path); if (texPath != null) { var texture = LoadTexture(texPath); if (texture != null) { _textureCache.Add(texture); loaded = true; } } var index = loaded ? _textureCache.Count - 1 : 0; _idMap.TryAdd(id, index); _pathMap.TryAdd(path, index); return loaded; } public static ImageTexture LoadTexture(string path) { var ext = path.GetExtension().ToLower(); string[] validExtensions = { "png", "tga", "pcx", "gif" }; if (validExtensions.Contains(ext)) { var image = ext switch { "pcx" => LoadPcx(path), "gif" => LoadGif(path), _ => Image.LoadFromFile(path), }; image.GenerateMipmaps(); return ImageTexture.CreateFromImage(image); } return null; } // TODO: We should report load failures public Texture2D Get(int id) { if (_idMap.TryGetValue(id, out int value)) { return _textureCache[value]; } if (_idPathMap.TryGetValue(id, out var path) && Load(id, path)) { return _textureCache[_idMap[id]]; } return _textureCache[0]; } // TODO: Load by path :) public Texture2D Get(string path) { if (!_pathMap.ContainsKey(path)) { return _textureCache[0]; } return _textureCache[_pathMap[path]]; } }