#include "core/resources/resource_cache.hpp" #include #include // Para find_if #include // Para exit, size_t #include // Para ifstream, istreambuf_iterator #include // Para basic_ostream, operator<<, endl, cout #include // Para runtime_error #include #include "core/audio/jail_audio.hpp" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa... #include "core/rendering/screen.hpp" // Para Screen #include "core/rendering/text.hpp" // Para Text, loadTextFile #include "core/resources/resource_helper.hpp" // Para Helper #include "core/resources/resource_list.hpp" // Para List, List::Type #include "game/defaults.hpp" // Para Defaults namespace #include "game/gameplay/room.hpp" // Para RoomData, loadRoomFile, loadRoomTileFile #include "game/gameplay/room_loader.hpp" // Para RoomLoader::loadFromString #include "game/options.hpp" // Para Options, OptionsGame, options #include "utils/defines.hpp" // Para WINDOW_CAPTION #include "utils/utils.hpp" // Para getFileName, printWithDots, PaletteColor #include "version.h" // Para Version::GIT_HASH struct JA_Music_t; // lines 17-17 struct JA_Sound_t; // lines 18-18 namespace Resource { // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado Cache* Cache::cache = nullptr; // [SINGLETON] Crearemos el objeto cache con esta función estática void Cache::init(LoadingMode mode) { Cache::cache = new Cache(mode); } // [SINGLETON] Destruiremos el objeto cache con esta función estática void Cache::destroy() { delete Cache::cache; } // [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él auto Cache::get() -> Cache* { return Cache::cache; } // Constructor Cache::Cache(LoadingMode mode) : loading_mode_(mode), loading_text_(Screen::get()->getText()) { load(); } // Vacia todos los vectores de recursos void Cache::clear() { clearSounds(); clearMusics(); surfaces_.clear(); palettes_.clear(); text_files_.clear(); texts_.clear(); animations_.clear(); } // Carga todos los recursos void Cache::load() { // Nota: el overlay de debug (RenderInfo) se inicializa después de esta carga, // por lo que updateZoomFactor() se llamará correctamente en RenderInfo::init(). if (loading_mode_ == LoadingMode::EAGER) { calculateTotal(); Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); std::cout << "\n** LOADING RESOURCES" << '\n'; loadSounds(); loadMusics(); loadSurfaces(); loadPalettes(); loadTextFiles(); loadAnimations(); loadRooms(); createText(); std::cout << "\n** RESOURCES LOADED" << '\n'; } else { std::cout << "\n** LAZY LOADING MODE **\n"; initLazyStubs(); createText(); // Carga fuentes bajo demanda a través de los getters lazy std::cout << "\n** RESOURCE STUBS READY" << '\n'; } } // Recarga todos los recursos void Cache::reload() { clear(); load(); } // Obtiene el sonido a partir de un nombre auto Cache::getSound(const std::string& name) -> JA_Sound_t* { auto it = std::ranges::find_if(sounds_, [&name](const auto& s) -> bool { return s.name == name; }); if (it != sounds_.end()) { if (loading_mode_ == LoadingMode::LAZY && it->sound == nullptr) { loadSoundByName(name); } return it->sound; } std::cerr << "Error: Sonido no encontrado " << name << '\n'; throw std::runtime_error("Sonido no encontrado: " + name); } // Obtiene la música a partir de un nombre auto Cache::getMusic(const std::string& name) -> JA_Music_t* { auto it = std::ranges::find_if(musics_, [&name](const auto& m) -> bool { return m.name == name; }); if (it != musics_.end()) { if (loading_mode_ == LoadingMode::LAZY && it->music == nullptr) { loadMusicByName(name); } return it->music; } std::cerr << "Error: Música no encontrada " << name << '\n'; throw std::runtime_error("Música no encontrada: " + name); } // Obtiene la surface a partir de un nombre auto Cache::getSurface(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != surfaces_.end()) { if (loading_mode_ == LoadingMode::LAZY && it->surface == nullptr) { loadSurfaceByName(name); } return it->surface; } std::cerr << "Error: Imagen no encontrada " << name << '\n'; throw std::runtime_error("Imagen no encontrada: " + name); } // Obtiene la paleta a partir de un nombre auto Cache::getPalette(const std::string& name) -> Palette { auto it = std::ranges::find_if(palettes_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != palettes_.end()) { if (loading_mode_ == LoadingMode::LAZY && !it->loaded) { loadPaletteByName(name); } return it->palette; } std::cerr << "Error: Paleta no encontrada " << name << '\n'; throw std::runtime_error("Paleta no encontrada: " + name); } // Obtiene el fichero de texto a partir de un nombre auto Cache::getTextFile(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(text_files_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != text_files_.end()) { if (loading_mode_ == LoadingMode::LAZY && it->text_file == nullptr) { loadTextFileByName(name); } return it->text_file; } std::cerr << "Error: TextFile no encontrado " << name << '\n'; throw std::runtime_error("TextFile no encontrado: " + name); } // Obtiene el objeto de texto a partir de un nombre auto Cache::getText(const std::string& name) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) auto it = std::ranges::find_if(texts_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != texts_.end()) { return it->text; } std::cerr << "Error: Text no encontrado " << name << '\n'; throw std::runtime_error("Texto no encontrado: " + name); } // Obtiene los datos de animación parseados a partir de un nombre auto Cache::getAnimationData(const std::string& name) -> const AnimationResource& { auto it = std::ranges::find_if(animations_, [&name](const auto& a) -> bool { return a.name == name; }); if (it != animations_.end()) { if (loading_mode_ == LoadingMode::LAZY && it->yaml_data.empty()) { loadAnimationByName(name); } return *it; } std::cerr << "Error: Animación no encontrada " << name << '\n'; throw std::runtime_error("Animación no encontrada: " + name); } // Obtiene la habitación a partir de un nombre auto Cache::getRoom(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(rooms_, [&name](const auto& r) -> bool { return r.name == name; }); if (it != rooms_.end()) { if (loading_mode_ == LoadingMode::LAZY && it->room == nullptr) { loadRoomByName(name); } return it->room; } std::cerr << "Error: Habitación no encontrada " << name << '\n'; throw std::runtime_error("Habitación no encontrada: " + name); } #ifdef _DEBUG // Recarga una habitación desde disco (para el editor de mapas) // Lee directamente del filesystem (no del resource pack) para obtener los cambios del editor void Cache::reloadRoom(const std::string& name) { auto file_path = List::get()->get(name); if (file_path.empty()) { std::cerr << "reloadRoom: Cannot resolve path for " << name << '\n'; return; } // Leer directamente del filesystem (evita el resource pack que tiene datos antiguos) std::ifstream file(file_path); if (!file.is_open()) { std::cerr << "reloadRoom: Cannot open " << file_path << '\n'; return; } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); // Parsear y actualizar el cache auto it = std::ranges::find_if(rooms_, [&name](const auto& r) -> bool { return r.name == name; }); if (it != rooms_.end()) { *(it->room) = RoomLoader::loadFromString(content, name); std::cout << "reloadRoom: " << name << " reloaded from filesystem\n"; } } #endif // Obtiene todas las habitaciones auto Cache::getRooms() -> std::vector& { if (loading_mode_ == LoadingMode::LAZY) { for (auto& r : rooms_) { if (r.room == nullptr) { loadRoomByName(r.name); } } } return rooms_; } // Helper para lanzar errores de carga con formato consistente [[noreturn]] void Cache::throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e) { // NOLINT(readability-convert-member-functions-to-static) std::cerr << "\n[ ERROR ] Failed to load " << asset_type << ": " << getFileName(file_path) << '\n'; std::cerr << "[ ERROR ] Path: " << file_path << '\n'; std::cerr << "[ ERROR ] Reason: " << e.what() << '\n'; std::cerr << "[ ERROR ] Check config/assets.yaml configuration\n"; throw; } // Carga los sonidos void Cache::loadSounds() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> SOUND FILES" << '\n'; auto list = List::get()->getListByType(List::Type::SOUND); sounds_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); JA_Sound_t* sound = nullptr; // Try loading from resource pack first auto audio_data = Helper::loadFile(l); if (!audio_data.empty()) { sound = JA_LoadSound(audio_data.data(), static_cast(audio_data.size())); } // Fallback to file path if memory loading failed if (sound == nullptr) { sound = JA_LoadSound(l.c_str()); } if (sound == nullptr) { throw std::runtime_error("Failed to decode audio file"); } sounds_.emplace_back(SoundResource{.name = name, .sound = sound}); printWithDots("Sound : ", name, "[ LOADED ]"); updateLoadingProgress(); } catch (const std::exception& e) { throwLoadError("SOUND", l, e); } } } // Carga las musicas void Cache::loadMusics() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> MUSIC FILES" << '\n'; auto list = List::get()->getListByType(List::Type::MUSIC); musics_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); JA_Music_t* music = nullptr; // Try loading from resource pack first auto audio_data = Helper::loadFile(l); if (!audio_data.empty()) { music = JA_LoadMusic(audio_data.data(), static_cast(audio_data.size())); } // Fallback to file path if memory loading failed if (music == nullptr) { music = JA_LoadMusic(l.c_str()); } if (music == nullptr) { throw std::runtime_error("Failed to decode music file"); } musics_.emplace_back(MusicResource{.name = name, .music = music}); printWithDots("Music : ", name, "[ LOADED ]"); updateLoadingProgress(1); } catch (const std::exception& e) { throwLoadError("MUSIC", l, e); } } } // Carga las texturas void Cache::loadSurfaces() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> SURFACES" << '\n'; auto list = List::get()->getListByType(List::Type::BITMAP); surfaces_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); surfaces_.emplace_back(SurfaceResource{.name = name, .surface = std::make_shared(l)}); surfaces_.back().surface->setTransparentColor(0); updateLoadingProgress(); } catch (const std::exception& e) { throwLoadError("BITMAP", l, e); } } // Reconfigura el color transparente de algunas surfaces getSurface("loading_screen_color.gif")->setTransparentColor(); getSurface("ending1.gif")->setTransparentColor(); getSurface("ending2.gif")->setTransparentColor(); getSurface("ending3.gif")->setTransparentColor(); getSurface("ending4.gif")->setTransparentColor(); getSurface("ending5.gif")->setTransparentColor(); getSurface("standard.gif")->setTransparentColor(16); } // Carga las paletas void Cache::loadPalettes() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> PALETTES" << '\n'; auto list = List::get()->getListByType(List::Type::PALETTE); palettes_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); palettes_.emplace_back(ResourcePalette{.name = name, .palette = readPalFile(l)}); updateLoadingProgress(); } catch (const std::exception& e) { throwLoadError("PALETTE", l, e); } } } // Carga los ficheros de texto void Cache::loadTextFiles() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> TEXT FILES" << '\n'; auto list = List::get()->getListByType(List::Type::FONT); text_files_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); text_files_.emplace_back(TextFileResource{.name = name, .text_file = Text::loadTextFile(l)}); updateLoadingProgress(); } catch (const std::exception& e) { throwLoadError("FONT", l, e); } } } // Carga las animaciones void Cache::loadAnimations() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> ANIMATIONS" << '\n'; auto list = List::get()->getListByType(List::Type::ANIMATION); animations_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); // Cargar bytes del archivo YAML sin parsear (carga lazy) auto yaml_bytes = Helper::loadFile(l); if (yaml_bytes.empty()) { throw std::runtime_error("File is empty or could not be loaded"); } animations_.emplace_back(AnimationResource{.name = name, .yaml_data = yaml_bytes}); printWithDots("Animation : ", name, "[ LOADED ]"); updateLoadingProgress(); } catch (const std::exception& e) { throwLoadError("ANIMATION", l, e); } } } // Carga las habitaciones desde archivos YAML void Cache::loadRooms() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> ROOMS" << '\n'; auto list = List::get()->getListByType(List::Type::ROOM); rooms_.clear(); for (const auto& l : list) { try { auto name = getFileName(l); rooms_.emplace_back(RoomResource{.name = name, .room = std::make_shared(Room::loadYAML(l))}); printWithDots("Room : ", name, "[ LOADED ]"); updateLoadingProgress(); } catch (const std::exception& e) { throwLoadError("ROOM", l, e); } } } void Cache::createText() { // NOLINT(readability-convert-member-functions-to-static) struct ResourceInfo { std::string key; // Identificador del recurso std::string texture_file; // Nombre del archivo de textura std::string text_file; // Nombre del archivo de texto }; std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n'; std::vector resources = { {.key = "aseprite", .texture_file = "aseprite.gif", .text_file = "aseprite.fnt"}, {.key = "gauntlet", .texture_file = "gauntlet.gif", .text_file = "gauntlet.fnt"}, {.key = "smb2", .texture_file = "smb2.gif", .text_file = "smb2.fnt"}, {.key = "subatomic", .texture_file = "subatomic.gif", .text_file = "subatomic.fnt"}, {.key = "8bithud", .texture_file = "8bithud.gif", .text_file = "8bithud.fnt"}}; for (const auto& res_info : resources) { texts_.emplace_back(TextResource{.name = res_info.key, .text = std::make_shared(getSurface(res_info.texture_file), getTextFile(res_info.text_file))}); printWithDots("Text : ", res_info.key, "[ DONE ]"); } } // Vacía el vector de sonidos void Cache::clearSounds() { // Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t for (auto& sound : sounds_) { if (sound.sound != nullptr) { JA_DeleteSound(sound.sound); sound.sound = nullptr; } } sounds_.clear(); // Limpia el vector después de liberar todos los recursos } // Vacía el vector de musicas void Cache::clearMusics() { // Itera sobre el vector y libera los recursos asociados a cada JA_Music_t for (auto& music : musics_) { if (music.music != nullptr) { JA_DeleteMusic(music.music); music.music = nullptr; } } musics_.clear(); // Limpia el vector después de liberar todos los recursos } // Calcula el numero de recursos para cargar void Cache::calculateTotal() { std::vector asset_types = { List::Type::SOUND, List::Type::MUSIC, List::Type::BITMAP, List::Type::PALETTE, List::Type::FONT, List::Type::ANIMATION, List::Type::ROOM}; int total = 0; for (const auto& asset_type : asset_types) { auto list = List::get()->getListByType(asset_type); total += list.size(); } count_ = ResourceCount{.total = total, .loaded = 0}; } // Muestra el progreso de carga void Cache::renderProgress() { constexpr float X_PADDING = 60.0F; constexpr float Y_PADDING = 10.0F; constexpr float BAR_HEIGHT = 5.0F; const float BAR_POSITION = Options::game.height - BAR_HEIGHT - Y_PADDING; Screen::get()->start(); Screen::get()->clearSurface(static_cast(PaletteColor::BLACK)); auto surface = Screen::get()->getRendererSurface(); const auto LOADING_TEXT_COLOR = static_cast(PaletteColor::BRIGHT_WHITE); const auto BAR_COLOR = static_cast(PaletteColor::WHITE); const int TEXT_HEIGHT = loading_text_->getCharacterSize(); const int CENTER_X = Options::game.width / 2; const int CENTER_Y = Options::game.height / 2; // Draw APP_NAME centered above center const std::string APP_NAME = spaceBetweenLetters(Version::APP_NAME); loading_text_->writeColored( CENTER_X - (loading_text_->length(APP_NAME) / 2), CENTER_Y - TEXT_HEIGHT, APP_NAME, LOADING_TEXT_COLOR); // Draw VERSION centered below center const std::string VERSION_TEXT = "ver. " + std::string(Texts::VERSION) + " (" + std::string(Version::GIT_HASH) + ")"; loading_text_->writeColored( CENTER_X - (loading_text_->length(VERSION_TEXT) / 2), CENTER_Y + TEXT_HEIGHT, VERSION_TEXT, LOADING_TEXT_COLOR); // Draw progress bar border const float WIRED_BAR_WIDTH = Options::game.width - (X_PADDING * 2); SDL_FRect rect_wired = {.x = X_PADDING, .y = BAR_POSITION, .w = WIRED_BAR_WIDTH, .h = BAR_HEIGHT}; surface->drawRectBorder(&rect_wired, BAR_COLOR); // Draw progress bar fill const float FULL_BAR_WIDTH = WIRED_BAR_WIDTH * count_.getPercentage(); SDL_FRect rect_full = {.x = X_PADDING, .y = BAR_POSITION, .w = FULL_BAR_WIDTH, .h = BAR_HEIGHT}; surface->fillRect(&rect_full, BAR_COLOR); Screen::get()->render(); } // Comprueba los eventos de la pantalla de carga void Cache::checkEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_EVENT_QUIT: exit(0); break; case SDL_EVENT_KEY_DOWN: if (event.key.key == SDLK_ESCAPE) { exit(0); } break; } } } // Actualiza el progreso de carga void Cache::updateLoadingProgress(int steps) { count_.add(1); if (count_.loaded % steps == 0 || count_.loaded == count_.total) { renderProgress(); } checkEvents(); } // --- Modo lazy: stubs y cargadores bajo demanda --------------------------- // Rellena los vectores de recursos con entradas name-only (sin contenido) void Cache::initLazyStubs() { sounds_.clear(); musics_.clear(); surfaces_.clear(); palettes_.clear(); text_files_.clear(); animations_.clear(); rooms_.clear(); for (const auto& l : List::get()->getListByType(List::Type::SOUND)) { sounds_.emplace_back(SoundResource{.name = getFileName(l), .sound = nullptr}); } for (const auto& l : List::get()->getListByType(List::Type::MUSIC)) { musics_.emplace_back(MusicResource{.name = getFileName(l), .music = nullptr}); } for (const auto& l : List::get()->getListByType(List::Type::BITMAP)) { surfaces_.emplace_back(SurfaceResource{.name = getFileName(l), .surface = nullptr}); } for (const auto& l : List::get()->getListByType(List::Type::PALETTE)) { palettes_.emplace_back(ResourcePalette{.name = getFileName(l)}); } for (const auto& l : List::get()->getListByType(List::Type::FONT)) { text_files_.emplace_back(TextFileResource{.name = getFileName(l), .text_file = nullptr}); } for (const auto& l : List::get()->getListByType(List::Type::ANIMATION)) { animations_.emplace_back(AnimationResource{.name = getFileName(l), .yaml_data = {}}); } for (const auto& l : List::get()->getListByType(List::Type::ROOM)) { rooms_.emplace_back(RoomResource{.name = getFileName(l), .room = nullptr}); } } void Cache::loadSoundByName(const std::string& name) { auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; }); if (it == sounds_.end()) { return; } auto path = List::get()->get(name); try { auto bytes = Helper::loadFile(path); JA_Sound_t* sound = nullptr; if (!bytes.empty()) { sound = JA_LoadSound(bytes.data(), static_cast(bytes.size())); } if (sound == nullptr) { sound = JA_LoadSound(path.c_str()); } if (sound == nullptr) { throw std::runtime_error("Failed to decode audio file"); } it->sound = sound; std::cout << "[lazy] Sound loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("SOUND", path, e); } } void Cache::loadMusicByName(const std::string& name) { auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; }); if (it == musics_.end()) { return; } auto path = List::get()->get(name); try { auto bytes = Helper::loadFile(path); JA_Music_t* music = nullptr; if (!bytes.empty()) { music = JA_LoadMusic(bytes.data(), static_cast(bytes.size())); } if (music == nullptr) { music = JA_LoadMusic(path.c_str()); } if (music == nullptr) { throw std::runtime_error("Failed to decode music file"); } it->music = music; std::cout << "[lazy] Music loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("MUSIC", path, e); } } void Cache::loadSurfaceByName(const std::string& name) { auto it = std::ranges::find_if(surfaces_, [&name](const auto& s) { return s.name == name; }); if (it == surfaces_.end()) { return; } auto path = List::get()->get(name); try { it->surface = std::make_shared(path); it->surface->setTransparentColor(0); // Superficies con color transparente específico (replica el ajuste de loadSurfaces) if (name == "loading_screen_color.gif" || name == "ending1.gif" || name == "ending2.gif" || name == "ending3.gif" || name == "ending4.gif" || name == "ending5.gif") { it->surface->setTransparentColor(); } else if (name == "standard.gif") { it->surface->setTransparentColor(16); } std::cout << "[lazy] Surface loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("BITMAP", path, e); } } void Cache::loadPaletteByName(const std::string& name) { auto it = std::ranges::find_if(palettes_, [&name](const auto& p) { return p.name == name; }); if (it == palettes_.end()) { return; } auto path = List::get()->get(name); try { it->palette = readPalFile(path); it->loaded = true; std::cout << "[lazy] Palette loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("PALETTE", path, e); } } void Cache::loadTextFileByName(const std::string& name) { auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; }); if (it == text_files_.end()) { return; } auto path = List::get()->get(name); try { it->text_file = Text::loadTextFile(path); std::cout << "[lazy] TextFile loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("FONT", path, e); } } void Cache::loadAnimationByName(const std::string& name) { auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; }); if (it == animations_.end()) { return; } auto path = List::get()->get(name); try { auto bytes = Helper::loadFile(path); if (bytes.empty()) { throw std::runtime_error("File is empty or could not be loaded"); } it->yaml_data = bytes; std::cout << "[lazy] Animation loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("ANIMATION", path, e); } } void Cache::loadRoomByName(const std::string& name) { auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; }); if (it == rooms_.end()) { return; } auto path = List::get()->get(name); try { it->room = std::make_shared(Room::loadYAML(path)); std::cout << "[lazy] Room loaded: " << name << '\n'; } catch (const std::exception& e) { throwLoadError("ROOM", path, e); } } } // namespace Resource