diff --git a/CLAUDE.md b/CLAUDE.md index 6e6fdfad..3849866c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -645,7 +645,7 @@ Achievements trigger notifications on unlock. Available types: `DATA`, `BITMAP`, `ANIMATION`, `MUSIC`, `SOUND`, `FONT`, `ROOM`, `TILEMAP`, `PALETTE` 3. Optional flags can be added: `TYPE|${PREFIX}/path/file.ext|optional,absolute` 4. Resource loads automatically during `Resource::init()` -5. Access via: `Resource::get()->getSurface("name")` +5. Access via: `Resource::Cache::get()->getSurface("name")` **Note:** No recompilation needed when adding/removing/modifying assets in `config/assets.txt` @@ -788,7 +788,7 @@ Binary 256-color palette format (256 × 4 bytes RGBA). ### For Asset Management - `config/assets.txt` - Asset configuration file (text-based, no recompilation needed) - `Asset::loadFromFile()` - Loads assets from config file -- `Asset::get()` - Retrieves asset path (O(1) lookup with unordered_map) +- `Resource::List::get()` - Retrieves asset path (O(1) lookup with unordered_map) - `Resource::load()` - Asset loading - `Director::setFileList()` - Calls `Asset::loadFromFile()` with PREFIX and system_folder diff --git a/CMakeLists.txt b/CMakeLists.txt index 37d07945..ee31c959 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,8 +56,8 @@ set(APP_SOURCES source/core/rendering/texture.cpp # Core - Resources - source/core/resources/asset.cpp - source/core/resources/resource.cpp + source/core/resources/resource_list.cpp + source/core/resources/resource_cache.cpp source/core/resources/resource_pack.cpp source/core/resources/resource_loader.cpp source/core/resources/resource_helper.cpp diff --git a/source/core/audio/audio.cpp b/source/core/audio/audio.cpp index 54b6d988..c1dfac0f 100644 --- a/source/core/audio/audio.cpp +++ b/source/core/audio/audio.cpp @@ -5,9 +5,9 @@ #include // Para clamp #include // Para std::cout -#include "core/resources/resource.hpp" // Para Resource -#include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM... -#include "game/options.hpp" // Para AudioOptions, audio, MusicOptions +#include "core/resources/resource_cache.hpp" // Para Resource +#include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM... +#include "game/options.hpp" // Para AudioOptions, audio, MusicOptions // Singleton Audio* Audio::instance = nullptr; @@ -44,7 +44,7 @@ void Audio::playMusic(const std::string& name, const int loop) { } // Intentar obtener recurso; si falla, no tocar estado - auto* resource = Resource::get()->getMusic(name); + auto* resource = Resource::Cache::get()->getMusic(name); if (resource == nullptr) { // manejo de error opcional return; @@ -91,7 +91,7 @@ void Audio::stopMusic() { // Reproduce un sonido por nombre void Audio::playSound(const std::string& name, Group group) const { if (sound_enabled_) { - JA_PlaySound(Resource::get()->getSound(name), 0, static_cast(group)); + JA_PlaySound(Resource::Cache::get()->getSound(name), 0, static_cast(group)); } } diff --git a/source/core/rendering/screen.cpp b/source/core/rendering/screen.cpp index a3b741de..594e9204 100644 --- a/source/core/rendering/screen.cpp +++ b/source/core/rendering/screen.cpp @@ -13,9 +13,9 @@ #include "core/rendering/opengl/opengl_shader.hpp" // Para OpenGLShader #include "core/rendering/surface.hpp" // Para Surface, readPalFile #include "core/rendering/text.hpp" // Para Text -#include "core/resources/asset.hpp" // Para Asset, AssetType -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/resources/resource_helper.hpp" // Para ResourceHelper +#include "core/resources/resource_list.hpp" // Para Asset, AssetType #include "game/options.hpp" // Para Options, options, OptionsVideo, Border #include "game/ui/notifier.hpp" // Para Notifier @@ -41,7 +41,7 @@ auto Screen::get() -> Screen* { Screen::Screen() : window_width_(0), window_height_(0), - palettes_(Asset::get()->getListByType(Asset::Type::PALETTE)) { + palettes_(Resource::List::get()->getListByType(Resource::List::Type::PALETTE)) { // Arranca SDL VIDEO, crea la ventana y el renderizador initSDLVideo(); if (Options::video.fullscreen) { @@ -274,8 +274,8 @@ void Screen::previousPalette() { // Establece la paleta void Screen::setPalete() { - game_surface_->loadPalette(Resource::get()->getPalette(palettes_.at(current_palette_))); - border_surface_->loadPalette(Resource::get()->getPalette(palettes_.at(current_palette_))); + game_surface_->loadPalette(Resource::Cache::get()->getPalette(palettes_.at(current_palette_))); + border_surface_->loadPalette(Resource::Cache::get()->getPalette(palettes_.at(current_palette_))); Options::video.palette = palettes_.at(current_palette_); @@ -341,8 +341,8 @@ auto Screen::findPalette(const std::string& name) -> size_t { // Muestra información por pantalla void Screen::renderInfo() { - if (show_debug_info_ && (Resource::get() != nullptr)) { - auto text = Resource::get()->getText("smb2"); + if (show_debug_info_ && (Resource::Cache::get() != nullptr)) { + auto text = Resource::Cache::get()->getText("smb2"); auto color = static_cast(PaletteColor::YELLOW); // FPS @@ -397,7 +397,7 @@ auto Screen::getBorderSurface() -> std::shared_ptr { return border_surf auto loadData(const std::string& filepath) -> std::vector { // Load using ResourceHelper (supports both filesystem and pack) - return Jdd::ResourceHelper::loadFile(filepath); + return Resource::Helper::loadFile(filepath); } // Carga el contenido de los archivos GLSL @@ -406,12 +406,12 @@ void Screen::loadShaders() { // Detectar si necesitamos OpenGL ES (Raspberry Pi) // Intentar cargar versión ES primero si existe std::string vertex_file = "crtpi_vertex_es.glsl"; - auto data = loadData(Asset::get()->get(vertex_file)); + auto data = loadData(Resource::List::get()->get(vertex_file)); if (data.empty()) { // Si no existe versión ES, usar versión Desktop vertex_file = "crtpi_vertex.glsl"; - data = loadData(Asset::get()->get(vertex_file)); + data = loadData(Resource::List::get()->get(vertex_file)); std::cout << "Usando shaders OpenGL Desktop 3.3\n"; } else { std::cout << "Usando shaders OpenGL ES 3.0 (Raspberry Pi)\n"; @@ -424,12 +424,12 @@ void Screen::loadShaders() { if (fragment_shader_source_.empty()) { // Intentar cargar versión ES primero si existe std::string fragment_file = "crtpi_fragment_es.glsl"; - auto data = loadData(Asset::get()->get(fragment_file)); + auto data = loadData(Resource::List::get()->get(fragment_file)); if (data.empty()) { // Si no existe versión ES, usar versión Desktop fragment_file = "crtpi_fragment.glsl"; - data = loadData(Asset::get()->get(fragment_file)); + data = loadData(Resource::List::get()->get(fragment_file)); } if (!data.empty()) { @@ -582,8 +582,8 @@ auto Screen::initSDLVideo() -> bool { // Crea el objeto de texto void Screen::createText() { // Carga la surface de la fuente directamente del archivo - auto surface = std::make_shared(Asset::get()->get("aseprite.gif")); + auto surface = std::make_shared(Resource::List::get()->get("aseprite.gif")); // Crea el objeto de texto (el constructor de Text carga el archivo text_file internamente) - text_ = std::make_shared(surface, Asset::get()->get("aseprite.txt")); + text_ = std::make_shared(surface, Resource::List::get()->get("aseprite.txt")); } \ No newline at end of file diff --git a/source/core/rendering/surface.cpp b/source/core/rendering/surface.cpp index 9e0f63c8..27dff12c 100644 --- a/source/core/rendering/surface.cpp +++ b/source/core/rendering/surface.cpp @@ -21,7 +21,7 @@ // Carga una paleta desde un archivo .gif auto loadPalette(const std::string& file_path) -> Palette { // Load file using ResourceHelper (supports both filesystem and pack) - auto buffer = Jdd::ResourceHelper::loadFile(file_path); + auto buffer = Resource::Helper::loadFile(file_path); if (buffer.empty()) { throw std::runtime_error("Error opening file: " + file_path); } @@ -48,7 +48,7 @@ auto readPalFile(const std::string& file_path) -> Palette { palette.fill(0); // Inicializar todo con 0 (transparente por defecto) // Load file using ResourceHelper (supports both filesystem and pack) - auto file_data = Jdd::ResourceHelper::loadFile(file_path); + auto file_data = Resource::Helper::loadFile(file_path); if (file_data.empty()) { throw std::runtime_error("No se pudo abrir el archivo .pal: " + file_path); } @@ -106,7 +106,7 @@ Surface::Surface(const std::string& file_path) // Carga una superficie desde un archivo auto Surface::loadSurface(const std::string& file_path) -> SurfaceData { // Load file using ResourceHelper (supports both filesystem and pack) - std::vector buffer = Jdd::ResourceHelper::loadFile(file_path); + std::vector buffer = Resource::Helper::loadFile(file_path); if (buffer.empty()) { std::cerr << "Error opening file: " << file_path << '\n'; throw std::runtime_error("Error opening file"); diff --git a/source/core/rendering/surface_animated_sprite.cpp b/source/core/rendering/surface_animated_sprite.cpp index 55fd2f16..1af6b919 100644 --- a/source/core/rendering/surface_animated_sprite.cpp +++ b/source/core/rendering/surface_animated_sprite.cpp @@ -8,14 +8,14 @@ #include #include "core/rendering/surface.hpp" // Para Surface -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/resources/resource_helper.hpp" // Para ResourceHelper #include "utils/utils.hpp" // Para printWithDots // Carga las animaciones en un vector(Animations) desde un fichero auto loadAnimationsFromFile(const std::string& file_path) -> Animations { // Load file using ResourceHelper (supports both filesystem and pack) - auto file_data = Jdd::ResourceHelper::loadFile(file_path); + auto file_data = Resource::Helper::loadFile(file_path); if (file_data.empty()) { std::cerr << "Error: Fichero no encontrado " << file_path << '\n'; throw std::runtime_error("Fichero no encontrado: " + file_path); @@ -192,7 +192,7 @@ auto parseGlobalParameter(const std::string& line, std::shared_ptr& sur if (key == "tileSetFile") { std::string value = line.substr(pos + 1); - surface = Resource::get()->getSurface(value); + surface = Resource::Cache::get()->getSurface(value); return true; } if (key == "frame_width") { diff --git a/source/core/rendering/text.cpp b/source/core/rendering/text.cpp index 8c4b5781..9726247d 100644 --- a/source/core/rendering/text.cpp +++ b/source/core/rendering/text.cpp @@ -28,7 +28,7 @@ auto loadTextFile(const std::string& file_path) -> std::shared_ptr { } // Load file using ResourceHelper (supports both filesystem and pack) - auto file_data = Jdd::ResourceHelper::loadFile(file_path); + auto file_data = Resource::Helper::loadFile(file_path); if (file_data.empty()) { std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n'; throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); diff --git a/source/core/resources/resource.cpp b/source/core/resources/resource_cache.cpp similarity index 76% rename from source/core/resources/resource.cpp rename to source/core/resources/resource_cache.cpp index a7266023..30a7d5b8 100644 --- a/source/core/resources/resource.cpp +++ b/source/core/resources/resource_cache.cpp @@ -1,4 +1,4 @@ -#include "core/resources/resource.hpp" +#include "core/resources/resource_cache.hpp" #include @@ -8,40 +8,42 @@ #include // Para runtime_error #include -#include "core/rendering/screen.hpp" // Para Screen -#include "core/rendering/text.hpp" // Para Text, loadTextFile -#include "core/resources/asset.hpp" // Para AssetType, Asset -#include "core/resources/resource_helper.hpp" // Para ResourceHelper -#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa... -#include "game/defaults.hpp" // Para GameDefaults::VERSION -#include "game/gameplay/room.hpp" // Para RoomData, loadRoomFile, loadRoomTileFile -#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 +#include "core/rendering/screen.hpp" // Para Screen +#include "core/rendering/text.hpp" // Para Text, loadTextFile +#include "core/resources/resource_list.hpp" // Para List, List::Type +#include "core/resources/resource_helper.hpp" // Para Helper +#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa... +#include "game/defaults.hpp" // Para GameDefaults::VERSION +#include "game/gameplay/room.hpp" // Para RoomData, loadRoomFile, loadRoomTileFile +#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 -Resource* Resource::resource = nullptr; +Cache* Cache::cache = nullptr; -// [SINGLETON] Crearemos el objeto screen con esta función estática -void Resource::init() { Resource::resource = new Resource(); } +// [SINGLETON] Crearemos el objeto cache con esta función estática +void Cache::init() { Cache::cache = new Cache(); } -// [SINGLETON] Destruiremos el objeto screen con esta función estática -void Resource::destroy() { delete Resource::resource; } +// [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 screen y podemos trabajar con él -auto Resource::get() -> Resource* { return Resource::resource; } +// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él +auto Cache::get() -> Cache* { return Cache::cache; } // Constructor -Resource::Resource() +Cache::Cache() : loading_text_(Screen::get()->getText()) { load(); } // Vacia todos los vectores de recursos -void Resource::clear() { +void Cache::clear() { clearSounds(); clearMusics(); surfaces_.clear(); @@ -52,7 +54,7 @@ void Resource::clear() { } // Carga todos los recursos -void Resource::load() { +void Cache::load() { calculateTotal(); Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); std::cout << "** LOADING RESOURCES" << '\n'; @@ -69,13 +71,13 @@ void Resource::load() { } // Recarga todos los recursos -void Resource::reload() { +void Cache::reload() { clear(); load(); } // Obtiene el sonido a partir de un nombre -auto Resource::getSound(const std::string& name) -> JA_Sound_t* { +auto Cache::getSound(const std::string& name) -> JA_Sound_t* { auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; }); if (it != sounds_.end()) { @@ -87,7 +89,7 @@ auto Resource::getSound(const std::string& name) -> JA_Sound_t* { } // Obtiene la música a partir de un nombre -auto Resource::getMusic(const std::string& name) -> JA_Music_t* { +auto Cache::getMusic(const std::string& name) -> JA_Music_t* { auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; }); if (it != musics_.end()) { @@ -99,7 +101,7 @@ auto Resource::getMusic(const std::string& name) -> JA_Music_t* { } // Obtiene la surface a partir de un nombre -auto Resource::getSurface(const std::string& name) -> std::shared_ptr { +auto Cache::getSurface(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) { return t.name == name; }); if (it != surfaces_.end()) { @@ -111,7 +113,7 @@ auto Resource::getSurface(const std::string& name) -> std::shared_ptr { } // Obtiene la paleta a partir de un nombre -auto Resource::getPalette(const std::string& name) -> Palette { +auto Cache::getPalette(const std::string& name) -> Palette { auto it = std::ranges::find_if(palettes_, [&name](const auto& t) { return t.name == name; }); if (it != palettes_.end()) { @@ -123,7 +125,7 @@ auto Resource::getPalette(const std::string& name) -> Palette { } // Obtiene el fichero de texto a partir de un nombre -auto Resource::getTextFile(const std::string& name) -> std::shared_ptr { +auto Cache::getTextFile(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; }); if (it != text_files_.end()) { @@ -135,7 +137,7 @@ auto Resource::getTextFile(const std::string& name) -> std::shared_ptr } // Obtiene el objeto de texto a partir de un nombre -auto Resource::getText(const std::string& name) -> std::shared_ptr { +auto Cache::getText(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(texts_, [&name](const auto& t) { return t.name == name; }); if (it != texts_.end()) { @@ -147,7 +149,7 @@ auto Resource::getText(const std::string& name) -> std::shared_ptr { } // Obtiene la animación a partir de un nombre -auto Resource::getAnimations(const std::string& name) -> Animations& { +auto Cache::getAnimations(const std::string& name) -> Animations& { auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; }); if (it != animations_.end()) { @@ -159,7 +161,7 @@ auto Resource::getAnimations(const std::string& name) -> Animations& { } // Obtiene el mapa de tiles a partir de un nombre -auto Resource::getTileMap(const std::string& name) -> std::vector& { +auto Cache::getTileMap(const std::string& name) -> std::vector& { auto it = std::ranges::find_if(tile_maps_, [&name](const auto& t) { return t.name == name; }); if (it != tile_maps_.end()) { @@ -171,7 +173,7 @@ auto Resource::getTileMap(const std::string& name) -> std::vector& { } // Obtiene la habitación a partir de un nombre -auto Resource::getRoom(const std::string& name) -> std::shared_ptr { +auto Cache::getRoom(const std::string& name) -> std::shared_ptr { auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; }); if (it != rooms_.end()) { @@ -183,14 +185,14 @@ auto Resource::getRoom(const std::string& name) -> std::shared_ptr { } // Obtiene todas las habitaciones -auto Resource::getRooms() -> std::vector& { +auto Cache::getRooms() -> std::vector& { return rooms_; } // Carga los sonidos -void Resource::loadSounds() { +void Cache::loadSounds() { std::cout << "\n>> SOUND FILES" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::SOUND); + auto list = List::get()->getListByType(List::Type::SOUND); sounds_.clear(); for (const auto& l : list) { @@ -198,7 +200,7 @@ void Resource::loadSounds() { JA_Sound_t* sound = nullptr; // Try loading from resource pack first - auto audio_data = Jdd::ResourceHelper::loadFile(l); + auto audio_data = Helper::loadFile(l); if (!audio_data.empty()) { sound = JA_LoadSound(audio_data.data(), static_cast(audio_data.size())); } @@ -215,9 +217,9 @@ void Resource::loadSounds() { } // Carga las musicas -void Resource::loadMusics() { +void Cache::loadMusics() { std::cout << "\n>> MUSIC FILES" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::MUSIC); + auto list = List::get()->getListByType(List::Type::MUSIC); musics_.clear(); for (const auto& l : list) { @@ -225,7 +227,7 @@ void Resource::loadMusics() { JA_Music_t* music = nullptr; // Try loading from resource pack first - auto audio_data = Jdd::ResourceHelper::loadFile(l); + auto audio_data = Helper::loadFile(l); if (!audio_data.empty()) { music = JA_LoadMusic(audio_data.data(), static_cast(audio_data.size())); } @@ -242,9 +244,9 @@ void Resource::loadMusics() { } // Carga las texturas -void Resource::loadSurfaces() { +void Cache::loadSurfaces() { std::cout << "\n>> SURFACES" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::BITMAP); + auto list = List::get()->getListByType(List::Type::BITMAP); surfaces_.clear(); for (const auto& l : list) { @@ -265,9 +267,9 @@ void Resource::loadSurfaces() { } // Carga las paletas -void Resource::loadPalettes() { +void Cache::loadPalettes() { std::cout << "\n>> PALETTES" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::PALETTE); + auto list = List::get()->getListByType(List::Type::PALETTE); palettes_.clear(); for (const auto& l : list) { @@ -278,9 +280,9 @@ void Resource::loadPalettes() { } // Carga los ficheros de texto -void Resource::loadTextFiles() { +void Cache::loadTextFiles() { std::cout << "\n>> TEXT FILES" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::FONT); + auto list = List::get()->getListByType(List::Type::FONT); text_files_.clear(); for (const auto& l : list) { @@ -291,9 +293,9 @@ void Resource::loadTextFiles() { } // Carga las animaciones -void Resource::loadAnimations() { +void Cache::loadAnimations() { std::cout << "\n>> ANIMATIONS" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::ANIMATION); + auto list = List::get()->getListByType(List::Type::ANIMATION); animations_.clear(); for (const auto& l : list) { @@ -304,9 +306,9 @@ void Resource::loadAnimations() { } // Carga los mapas de tiles -void Resource::loadTileMaps() { +void Cache::loadTileMaps() { std::cout << "\n>> TILE MAPS" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::TILEMAP); + auto list = List::get()->getListByType(List::Type::TILEMAP); tile_maps_.clear(); for (const auto& l : list) { @@ -318,9 +320,9 @@ void Resource::loadTileMaps() { } // Carga las habitaciones -void Resource::loadRooms() { +void Cache::loadRooms() { std::cout << "\n>> ROOMS" << '\n'; - auto list = Asset::get()->getListByType(Asset::Type::ROOM); + auto list = List::get()->getListByType(List::Type::ROOM); rooms_.clear(); for (const auto& l : list) { @@ -331,7 +333,7 @@ void Resource::loadRooms() { } } -void Resource::createText() { +void Cache::createText() { struct ResourceInfo { std::string key; // Identificador del recurso std::string texture_file; // Nombre del archivo de textura @@ -360,7 +362,7 @@ void Resource::createText() { } // Vacía el vector de sonidos -void Resource::clearSounds() { +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) { @@ -372,7 +374,7 @@ void Resource::clearSounds() { } // Vacía el vector de musicas -void Resource::clearMusics() { +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) { @@ -384,20 +386,20 @@ void Resource::clearMusics() { } // Calcula el numero de recursos para cargar -void Resource::calculateTotal() { - std::vector asset_types = { - Asset::Type::SOUND, - Asset::Type::MUSIC, - Asset::Type::BITMAP, - Asset::Type::PALETTE, - Asset::Type::FONT, - Asset::Type::ANIMATION, - Asset::Type::TILEMAP, - Asset::Type::ROOM}; +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::TILEMAP, + List::Type::ROOM}; size_t total = 0; for (const auto& asset_type : asset_types) { - auto list = Asset::get()->getListByType(asset_type); + auto list = List::get()->getListByType(asset_type); total += list.size(); } @@ -405,7 +407,7 @@ void Resource::calculateTotal() { } // Muestra el progreso de carga -void Resource::renderProgress() { +void Cache::renderProgress() { constexpr float X_PADDING = 60.0F; constexpr float Y_PADDING = 10.0F; constexpr float BAR_HEIGHT = 5.0F; @@ -451,7 +453,7 @@ void Resource::renderProgress() { } // Comprueba los eventos de la pantalla de carga -void Resource::checkEvents() { +void Cache::checkEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { @@ -468,10 +470,12 @@ void Resource::checkEvents() { } // Actualiza el progreso de carga -void Resource::updateLoadingProgress(int steps) { +void Cache::updateLoadingProgress(int steps) { count_.add(1); if (count_.loaded % steps == 0 || count_.loaded == count_.total) { renderProgress(); } checkEvents(); -} \ No newline at end of file +} + +} // namespace Resource diff --git a/source/core/resources/resource.hpp b/source/core/resources/resource_cache.hpp similarity index 94% rename from source/core/resources/resource.hpp rename to source/core/resources/resource_cache.hpp index 7ebd9016..a0a69831 100644 --- a/source/core/resources/resource.hpp +++ b/source/core/resources/resource_cache.hpp @@ -137,10 +137,12 @@ struct ResourceCount { } }; -class Resource { +namespace Resource { + +class Cache { private: - // [SINGLETON] Objeto resource privado para Don Melitón - static Resource* resource; + // [SINGLETON] Objeto cache privado para Don Melitón + static Cache* cache; std::vector sounds_; // Vector con los sonidos std::vector musics_; // Vector con las musicas @@ -206,23 +208,23 @@ class Resource { // Actualiza el progreso de carga void updateLoadingProgress(int steps = 5); - // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera + // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos cache desde fuera // Constructor - Resource(); + Cache(); // Destructor - ~Resource() = default; + ~Cache() = default; public: - // [SINGLETON] Crearemos el objeto resource con esta función estática + // [SINGLETON] Crearemos el objeto cache con esta función estática static void init(); - // [SINGLETON] Destruiremos el objeto resource con esta función estática + // [SINGLETON] Destruiremos el objeto cache con esta función estática static void destroy(); - // [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él - static auto get() -> Resource*; + // [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él + static auto get() -> Cache*; // Obtiene el sonido a partir de un nombre auto getSound(const std::string& name) -> JA_Sound_t*; @@ -256,4 +258,6 @@ class Resource { // Recarga todos los recursos void reload(); -}; \ No newline at end of file +}; + +} // namespace Resource diff --git a/source/core/resources/resource_helper.cpp b/source/core/resources/resource_helper.cpp index 771bd1b4..da71b7c9 100644 --- a/source/core/resources/resource_helper.cpp +++ b/source/core/resources/resource_helper.cpp @@ -10,7 +10,7 @@ #include "resource_loader.hpp" -namespace Jdd::ResourceHelper { +namespace Resource::Helper { static bool resource_system_initialized = false; @@ -26,7 +26,7 @@ auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback std::cout << "ResourceHelper: Fallback enabled: " << (enable_fallback ? "Yes" : "No") << '\n'; - bool success = ResourceLoader::get().initialize(pack_file, enable_fallback); + bool success = Loader::get().initialize(pack_file, enable_fallback); if (success) { resource_system_initialized = true; std::cout << "ResourceHelper: Initialization successful\n"; @@ -40,7 +40,7 @@ auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback // Shutdown the resource system void shutdownResourceSystem() { if (resource_system_initialized) { - ResourceLoader::get().shutdown(); + Loader::get().shutdown(); resource_system_initialized = false; std::cout << "ResourceHelper: Shutdown complete\n"; } @@ -68,7 +68,7 @@ auto loadFile(const std::string& filepath) -> std::vector { std::string pack_path = getPackPath(filepath); // Try to load from pack - auto data = ResourceLoader::get().loadResource(pack_path); + auto data = Loader::get().loadResource(pack_path); if (!data.empty()) { return data; } @@ -79,7 +79,7 @@ auto loadFile(const std::string& filepath) -> std::vector { } // Load from filesystem - return ResourceLoader::get().loadResource(filepath); + return Loader::get().loadResource(filepath); } // Check if a file exists @@ -91,7 +91,7 @@ auto fileExists(const std::string& filepath) -> bool { // Check pack if appropriate if (shouldUseResourcePack(filepath)) { std::string pack_path = getPackPath(filepath); - if (ResourceLoader::get().resourceExists(pack_path)) { + if (Loader::get().resourceExists(pack_path)) { return true; } } @@ -150,7 +150,7 @@ auto shouldUseResourcePack(const std::string& filepath) -> bool { std::ranges::replace(path, '\\', '/'); // Don't use pack for most config files (except config/assets.txt which is loaded - // directly via ResourceLoader::loadAssetsConfig() in release builds) + // directly via Loader::loadAssetsConfig() in release builds) if (path.find("config/") != std::string::npos) { return false; } @@ -177,7 +177,7 @@ auto isPackLoaded() -> bool { if (!resource_system_initialized) { return false; } - return ResourceLoader::get().isPackLoaded(); + return Loader::get().isPackLoaded(); } -} // namespace Jdd::ResourceHelper +} // namespace Resource::Helper diff --git a/source/core/resources/resource_helper.hpp b/source/core/resources/resource_helper.hpp index bb5ba4aa..2e337c13 100644 --- a/source/core/resources/resource_helper.hpp +++ b/source/core/resources/resource_helper.hpp @@ -8,7 +8,7 @@ #include #include -namespace Jdd::ResourceHelper { +namespace Resource::Helper { // Initialize the resource system // pack_file: Path to resources.pack @@ -36,6 +36,6 @@ auto shouldUseResourcePack(const std::string& filepath) -> bool; // Check if pack is loaded auto isPackLoaded() -> bool; -} // namespace Jdd::ResourceHelper +} // namespace Resource::Helper #endif // RESOURCE_HELPER_HPP diff --git a/source/core/resources/asset.cpp b/source/core/resources/resource_list.cpp similarity index 86% rename from source/core/resources/asset.cpp rename to source/core/resources/resource_list.cpp index 66a761b1..4d57e325 100644 --- a/source/core/resources/asset.cpp +++ b/source/core/resources/resource_list.cpp @@ -1,4 +1,4 @@ -#include "core/resources/asset.hpp" +#include "core/resources/resource_list.hpp" #include // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError @@ -13,23 +13,25 @@ #include "utils/utils.hpp" // Para getFileName, printWithDots +namespace Resource { + // Singleton -Asset* Asset::instance = nullptr; +List* List::instance = nullptr; -void Asset::init(const std::string& executable_path) { - Asset::instance = new Asset(executable_path); +void List::init(const std::string& executable_path) { + List::instance = new List(executable_path); } -void Asset::destroy() { - delete Asset::instance; +void List::destroy() { + delete List::instance; } -auto Asset::get() -> Asset* { - return Asset::instance; +auto List::get() -> List* { + return List::instance; } // Añade un elemento al mapa (función auxiliar) -void Asset::addToMap(const std::string& file_path, Type type, bool required, bool absolute) { +void List::addToMap(const std::string& file_path, Type type, bool required, bool absolute) { std::string full_path = absolute ? file_path : executable_path_ + file_path; std::string filename = getFileName(full_path); @@ -44,12 +46,12 @@ void Asset::addToMap(const std::string& file_path, Type type, bool required, boo } // Añade un elemento a la lista -void Asset::add(const std::string& file_path, Type type, bool required, bool absolute) { +void List::add(const std::string& file_path, Type type, bool required, bool absolute) { addToMap(file_path, type, required, absolute); } // Carga recursos desde un archivo de configuración con soporte para variables -void Asset::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) { +void List::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) { std::ifstream file(config_file_path); if (!file.is_open()) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, @@ -68,7 +70,7 @@ void Asset::loadFromFile(const std::string& config_file_path, const std::string& } // Carga recursos desde un string de configuración (para release con pack) -void Asset::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) { +void List::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) { std::istringstream stream(config_content); std::string line; int line_number = 0; @@ -136,7 +138,7 @@ void Asset::loadFromString(const std::string& config_content, const std::string& } // Devuelve la ruta completa a un fichero (búsqueda O(1)) -auto Asset::get(const std::string& filename) const -> std::string { +auto List::get(const std::string& filename) const -> std::string { auto it = file_list_.find(filename); if (it != file_list_.end()) { return it->second.file; @@ -147,7 +149,7 @@ auto Asset::get(const std::string& filename) const -> std::string { } // Carga datos del archivo -auto Asset::loadData(const std::string& filename) const -> std::vector { +auto List::loadData(const std::string& filename) const -> std::vector { auto it = file_list_.find(filename); if (it != file_list_.end()) { std::ifstream file(it->second.file, std::ios::binary); @@ -176,12 +178,12 @@ auto Asset::loadData(const std::string& filename) const -> std::vector } // Verifica si un recurso existe -auto Asset::exists(const std::string& filename) const -> bool { +auto List::exists(const std::string& filename) const -> bool { return file_list_.find(filename) != file_list_.end(); } // Comprueba que existen todos los elementos -auto Asset::check() const -> bool { +auto List::check() const -> bool { bool success = true; std::cout << "\n** CHECKING FILES" << '\n'; @@ -223,7 +225,7 @@ auto Asset::check() const -> bool { } // Comprueba que existe un fichero -auto Asset::checkFile(const std::string& path) -> bool { +auto List::checkFile(const std::string& path) -> bool { std::ifstream file(path); bool success = file.good(); file.close(); @@ -236,7 +238,7 @@ auto Asset::checkFile(const std::string& path) -> bool { } // Parsea string a Type -auto Asset::parseAssetType(const std::string& type_str) -> Type { +auto List::parseAssetType(const std::string& type_str) -> Type { if (type_str == "DATA") { return Type::DATA; } @@ -269,7 +271,7 @@ auto Asset::parseAssetType(const std::string& type_str) -> Type { } // Devuelve el nombre del tipo de recurso -auto Asset::getTypeName(Type type) -> std::string { +auto List::getTypeName(Type type) -> std::string { switch (type) { case Type::DATA: return "DATA"; @@ -295,7 +297,7 @@ auto Asset::getTypeName(Type type) -> std::string { } // Devuelve la lista de recursos de un tipo -auto Asset::getListByType(Type type) const -> std::vector { +auto List::getListByType(Type type) const -> std::vector { std::vector list; for (const auto& [filename, item] : file_list_) { @@ -311,7 +313,7 @@ auto Asset::getListByType(Type type) const -> std::vector { } // Reemplaza variables en las rutas -auto Asset::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string { +auto List::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string { std::string result = path; // Reemplazar ${PREFIX} @@ -332,7 +334,7 @@ auto Asset::replaceVariables(const std::string& path, const std::string& prefix, } // Parsea las opciones de una línea de configuración -auto Asset::parseOptions(const std::string& options, bool& required, bool& absolute) -> void { +auto List::parseOptions(const std::string& options, bool& required, bool& absolute) -> void { if (options.empty()) { return; } @@ -352,3 +354,5 @@ auto Asset::parseOptions(const std::string& options, bool& required, bool& absol } } } + +} // namespace Resource diff --git a/source/core/resources/asset.hpp b/source/core/resources/resource_list.hpp similarity index 89% rename from source/core/resources/asset.hpp rename to source/core/resources/resource_list.hpp index 583a100d..a966d33c 100644 --- a/source/core/resources/asset.hpp +++ b/source/core/resources/resource_list.hpp @@ -6,8 +6,10 @@ #include // Para move #include // Para vector -// --- Clase Asset: gestor optimizado de recursos (singleton) --- -class Asset { +namespace Resource { + +// --- Clase List: gestor optimizado de recursos (singleton) --- +class List { public: // --- Enums --- enum class Type : int { @@ -26,9 +28,9 @@ class Asset { // --- Métodos de singleton --- static void init(const std::string& executable_path); static void destroy(); - static auto get() -> Asset*; - Asset(const Asset&) = delete; - auto operator=(const Asset&) -> Asset& = delete; + static auto get() -> List*; + List(const List&) = delete; + auto operator=(const List&) -> List& = delete; // --- Métodos para la gestión de recursos --- void add(const std::string& file_path, Type type, bool required = true, bool absolute = false); @@ -66,10 +68,12 @@ class Asset { static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones // --- Constructores y destructor privados (singleton) --- - explicit Asset(std::string executable_path) // Constructor privado + explicit List(std::string executable_path) // Constructor privado : executable_path_(std::move(executable_path)) {} - ~Asset() = default; // Destructor privado + ~List() = default; // Destructor privado // --- Instancia singleton --- - static Asset* instance; // Instancia única de Asset + static List* instance; // Instancia única de List }; + +} // namespace Resource diff --git a/source/core/resources/resource_loader.cpp b/source/core/resources/resource_loader.cpp index f4fb4113..d8ed8364 100644 --- a/source/core/resources/resource_loader.cpp +++ b/source/core/resources/resource_loader.cpp @@ -7,19 +7,19 @@ #include #include -namespace Jdd { +namespace Resource { // Get singleton instance -auto ResourceLoader::get() -> ResourceLoader& { - static ResourceLoader instance_; +auto Loader::get() -> Loader& { + static Loader instance_; return instance_; } // Initialize with a pack file -auto ResourceLoader::initialize(const std::string& pack_file, bool enable_fallback) +auto Loader::initialize(const std::string& pack_file, bool enable_fallback) -> bool { if (initialized_) { - std::cout << "ResourceLoader: Already initialized\n"; + std::cout << "Loader: Already initialized\n"; return true; } @@ -27,35 +27,35 @@ auto ResourceLoader::initialize(const std::string& pack_file, bool enable_fallba // Try to load the pack file if (!pack_file.empty() && fileExistsOnFilesystem(pack_file)) { - std::cout << "ResourceLoader: Loading pack file: " << pack_file << '\n'; - resource_pack_ = std::make_unique(); + std::cout << "Loader: Loading pack file: " << pack_file << '\n'; + resource_pack_ = std::make_unique(); if (resource_pack_->loadPack(pack_file)) { - std::cout << "ResourceLoader: Pack loaded successfully\n"; + std::cout << "Loader: Pack loaded successfully\n"; initialized_ = true; return true; } - std::cerr << "ResourceLoader: Failed to load pack file\n"; + std::cerr << "Loader: Failed to load pack file\n"; resource_pack_.reset(); } else { - std::cout << "ResourceLoader: Pack file not found: " << pack_file << '\n'; + std::cout << "Loader: Pack file not found: " << pack_file << '\n'; } // If pack loading failed and fallback is disabled, fail if (!fallback_to_files_) { - std::cerr << "ResourceLoader: Pack required but not found (fallback disabled)\n"; + std::cerr << "Loader: Pack required but not found (fallback disabled)\n"; return false; } // Otherwise, fallback to filesystem - std::cout << "ResourceLoader: Using filesystem fallback\n"; + std::cout << "Loader: Using filesystem fallback\n"; initialized_ = true; return true; } // Load a resource -auto ResourceLoader::loadResource(const std::string& filename) -> std::vector { +auto Loader::loadResource(const std::string& filename) -> std::vector { if (!initialized_) { - std::cerr << "ResourceLoader: Not initialized\n"; + std::cerr << "Loader: Not initialized\n"; return {}; } @@ -66,7 +66,7 @@ auto ResourceLoader::loadResource(const std::string& filename) -> std::vector std::vector bool { +auto Loader::resourceExists(const std::string& filename) -> bool { if (!initialized_) { return false; } @@ -102,12 +102,12 @@ auto ResourceLoader::resourceExists(const std::string& filename) -> bool { } // Check if pack is loaded -auto ResourceLoader::isPackLoaded() const -> bool { +auto Loader::isPackLoaded() const -> bool { return resource_pack_ && resource_pack_->isLoaded(); } // Get pack statistics -auto ResourceLoader::getPackResourceCount() const -> size_t { +auto Loader::getPackResourceCount() const -> size_t { if (resource_pack_ && resource_pack_->isLoaded()) { return resource_pack_->getResourceCount(); } @@ -115,14 +115,14 @@ auto ResourceLoader::getPackResourceCount() const -> size_t { } // Cleanup -void ResourceLoader::shutdown() { +void Loader::shutdown() { resource_pack_.reset(); initialized_ = false; - std::cout << "ResourceLoader: Shutdown complete\n"; + std::cout << "Loader: Shutdown complete\n"; } // Load from filesystem -auto ResourceLoader::loadFromFilesystem(const std::string& filepath) +auto Loader::loadFromFilesystem(const std::string& filepath) -> std::vector { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { @@ -134,7 +134,7 @@ auto ResourceLoader::loadFromFilesystem(const std::string& filepath) std::vector data(file_size); if (!file.read(reinterpret_cast(data.data()), file_size)) { - std::cerr << "ResourceLoader: Failed to read file: " << filepath << '\n'; + std::cerr << "Loader: Failed to read file: " << filepath << '\n'; return {}; } @@ -142,14 +142,14 @@ auto ResourceLoader::loadFromFilesystem(const std::string& filepath) } // Check if file exists on filesystem -auto ResourceLoader::fileExistsOnFilesystem(const std::string& filepath) -> bool { +auto Loader::fileExistsOnFilesystem(const std::string& filepath) -> bool { return std::filesystem::exists(filepath); } // Validate pack integrity -auto ResourceLoader::validatePack() const -> bool { +auto Loader::validatePack() const -> bool { if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) { - std::cerr << "ResourceLoader: Cannot validate - pack not loaded\n"; + std::cerr << "Loader: Cannot validate - pack not loaded\n"; return false; } @@ -157,20 +157,20 @@ auto ResourceLoader::validatePack() const -> bool { uint32_t checksum = resource_pack_->calculatePackChecksum(); if (checksum == 0) { - std::cerr << "ResourceLoader: Pack checksum is zero (invalid)\n"; + std::cerr << "Loader: Pack checksum is zero (invalid)\n"; return false; } - std::cout << "ResourceLoader: Pack checksum: 0x" << std::hex << checksum << std::dec + std::cout << "Loader: Pack checksum: 0x" << std::hex << checksum << std::dec << '\n'; - std::cout << "ResourceLoader: Pack validation successful\n"; + std::cout << "Loader: Pack validation successful\n"; return true; } // Load assets.txt from pack -auto ResourceLoader::loadAssetsConfig() const -> std::string { +auto Loader::loadAssetsConfig() const -> std::string { if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) { - std::cerr << "ResourceLoader: Cannot load assets config - pack not loaded\n"; + std::cerr << "Loader: Cannot load assets config - pack not loaded\n"; return ""; } @@ -178,22 +178,22 @@ auto ResourceLoader::loadAssetsConfig() const -> std::string { std::string config_path = "config/assets.txt"; if (!resource_pack_->hasResource(config_path)) { - std::cerr << "ResourceLoader: assets.txt not found in pack: " << config_path << '\n'; + std::cerr << "Loader: assets.txt not found in pack: " << config_path << '\n'; return ""; } auto data = resource_pack_->getResource(config_path); if (data.empty()) { - std::cerr << "ResourceLoader: Failed to load assets.txt from pack\n"; + std::cerr << "Loader: Failed to load assets.txt from pack\n"; return ""; } // Convert bytes to string std::string config_content(data.begin(), data.end()); - std::cout << "ResourceLoader: Loaded assets.txt from pack (" << data.size() + std::cout << "Loader: Loaded assets.txt from pack (" << data.size() << " bytes)\n"; return config_content; } -} // namespace Jdd +} // namespace Resource diff --git a/source/core/resources/resource_loader.hpp b/source/core/resources/resource_loader.hpp index 80bc4d14..b61c4e4e 100644 --- a/source/core/resources/resource_loader.hpp +++ b/source/core/resources/resource_loader.hpp @@ -10,13 +10,13 @@ #include "resource_pack.hpp" -namespace Jdd { +namespace Resource { // Singleton class for loading resources from pack or filesystem -class ResourceLoader { +class Loader { public: // Get singleton instance - static auto get() -> ResourceLoader&; + static auto get() -> Loader&; // Initialize with a pack file (optional) auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool; @@ -43,14 +43,14 @@ class ResourceLoader { void shutdown(); // Disable copy/move - ResourceLoader(const ResourceLoader&) = delete; - auto operator=(const ResourceLoader&) -> ResourceLoader& = delete; - ResourceLoader(ResourceLoader&&) = delete; - auto operator=(ResourceLoader&&) -> ResourceLoader& = delete; + Loader(const Loader&) = delete; + auto operator=(const Loader&) -> Loader& = delete; + Loader(Loader&&) = delete; + auto operator=(Loader&&) -> Loader& = delete; private: - ResourceLoader() = default; - ~ResourceLoader() = default; + Loader() = default; + ~Loader() = default; // Load from filesystem static auto loadFromFilesystem(const std::string& filepath) -> std::vector; @@ -59,11 +59,11 @@ class ResourceLoader { static auto fileExistsOnFilesystem(const std::string& filepath) -> bool; // Member data - std::unique_ptr resource_pack_; + std::unique_ptr resource_pack_; bool fallback_to_files_{true}; bool initialized_{false}; }; -} // namespace Jdd +} // namespace Resource #endif // RESOURCE_LOADER_HPP diff --git a/source/core/resources/resource_pack.cpp b/source/core/resources/resource_pack.cpp index 0f06f71b..93e85073 100644 --- a/source/core/resources/resource_pack.cpp +++ b/source/core/resources/resource_pack.cpp @@ -10,10 +10,10 @@ #include #include -namespace Jdd { +namespace Resource { // Calculate CRC32 checksum for data verification -auto ResourcePack::calculateChecksum(const std::vector& data) -> uint32_t { +auto Pack::calculateChecksum(const std::vector& data) -> uint32_t { uint32_t checksum = 0x12345678; for (unsigned char byte : data) { checksum = ((checksum << 5) + checksum) + byte; @@ -22,7 +22,7 @@ auto ResourcePack::calculateChecksum(const std::vector& data) -> uint32 } // XOR encryption (symmetric - same function for encrypt/decrypt) -void ResourcePack::encryptData(std::vector& data, const std::string& key) { +void Pack::encryptData(std::vector& data, const std::string& key) { if (key.empty()) { return; } @@ -31,13 +31,13 @@ void ResourcePack::encryptData(std::vector& data, const std::string& ke } } -void ResourcePack::decryptData(std::vector& data, const std::string& key) { +void Pack::decryptData(std::vector& data, const std::string& key) { // XOR is symmetric encryptData(data, key); } // Read entire file into memory -auto ResourcePack::readFile(const std::string& filepath) -> std::vector { +auto Pack::readFile(const std::string& filepath) -> std::vector { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "ResourcePack: Failed to open file: " << filepath << '\n'; @@ -57,7 +57,7 @@ auto ResourcePack::readFile(const std::string& filepath) -> std::vector } // Add a single file to the pack -auto ResourcePack::addFile(const std::string& filepath, const std::string& pack_name) +auto Pack::addFile(const std::string& filepath, const std::string& pack_name) -> bool { auto file_data = readFile(filepath); if (file_data.empty()) { @@ -80,7 +80,7 @@ auto ResourcePack::addFile(const std::string& filepath, const std::string& pack_ } // Add all files from a directory recursively -auto ResourcePack::addDirectory(const std::string& dir_path, +auto Pack::addDirectory(const std::string& dir_path, const std::string& base_path) -> bool { namespace fs = std::filesystem; @@ -117,7 +117,7 @@ auto ResourcePack::addDirectory(const std::string& dir_path, } // Save the pack to a file -auto ResourcePack::savePack(const std::string& pack_file) -> bool { +auto Pack::savePack(const std::string& pack_file) -> bool { std::ofstream file(pack_file, std::ios::binary); if (!file) { std::cerr << "ResourcePack: Failed to create pack file: " << pack_file << '\n'; @@ -162,7 +162,7 @@ auto ResourcePack::savePack(const std::string& pack_file) -> bool { } // Load a pack from a file -auto ResourcePack::loadPack(const std::string& pack_file) -> bool { +auto Pack::loadPack(const std::string& pack_file) -> bool { std::ifstream file(pack_file, std::ios::binary); if (!file) { std::cerr << "ResourcePack: Failed to open pack file: " << pack_file << '\n'; @@ -229,7 +229,7 @@ auto ResourcePack::loadPack(const std::string& pack_file) -> bool { } // Get a resource by name -auto ResourcePack::getResource(const std::string& filename) -> std::vector { +auto Pack::getResource(const std::string& filename) -> std::vector { auto it = resources_.find(filename); if (it == resources_.end()) { return {}; @@ -258,12 +258,12 @@ auto ResourcePack::getResource(const std::string& filename) -> std::vector bool { +auto Pack::hasResource(const std::string& filename) const -> bool { return resources_.find(filename) != resources_.end(); } // Get list of all resources -auto ResourcePack::getResourceList() const -> std::vector { +auto Pack::getResourceList() const -> std::vector { std::vector list; list.reserve(resources_.size()); for (const auto& [name, entry] : resources_) { @@ -274,7 +274,7 @@ auto ResourcePack::getResourceList() const -> std::vector { } // Calculate overall pack checksum for validation -auto ResourcePack::calculatePackChecksum() const -> uint32_t { +auto Pack::calculatePackChecksum() const -> uint32_t { if (!loaded_ || data_.empty()) { return 0; } @@ -300,4 +300,4 @@ auto ResourcePack::calculatePackChecksum() const -> uint32_t { return global_checksum; } -} // namespace Jdd +} // namespace Resource diff --git a/source/core/resources/resource_pack.hpp b/source/core/resources/resource_pack.hpp index 62face3f..85fc87dd 100644 --- a/source/core/resources/resource_pack.hpp +++ b/source/core/resources/resource_pack.hpp @@ -11,7 +11,7 @@ #include #include -namespace Jdd { +namespace Resource { // Entry metadata for each resource in the pack struct ResourceEntry { @@ -25,16 +25,16 @@ struct ResourceEntry { // Header: "JDDI" (4 bytes) + Version (4 bytes) // Metadata: Count + array of ResourceEntry // Data: Encrypted data block -class ResourcePack { +class Pack { public: - ResourcePack() = default; - ~ResourcePack() = default; + Pack() = default; + ~Pack() = default; // Disable copy/move - ResourcePack(const ResourcePack&) = delete; - auto operator=(const ResourcePack&) -> ResourcePack& = delete; - ResourcePack(ResourcePack&&) = delete; - auto operator=(ResourcePack&&) -> ResourcePack& = delete; + Pack(const Pack&) = delete; + auto operator=(const Pack&) -> Pack& = delete; + Pack(Pack&&) = delete; + auto operator=(Pack&&) -> Pack& = delete; // Add a single file to the pack auto addFile(const std::string& filepath, const std::string& pack_name) -> bool; @@ -89,6 +89,6 @@ class ResourcePack { bool loaded_{false}; }; -} // namespace Jdd +} // namespace Resource #endif // RESOURCE_PACK_HPP diff --git a/source/core/system/debug.cpp b/source/core/system/debug.cpp index 10425f1a..0ac6256b 100644 --- a/source/core/system/debug.cpp +++ b/source/core/system/debug.cpp @@ -3,9 +3,9 @@ #include // Para max #include // Para __shared_ptr_access, shared_ptr -#include "core/rendering/text.hpp" // Para Text -#include "core/resources/resource.hpp" // Para Resource -#include "utils/utils.hpp" // Para Color +#include "core/rendering/text.hpp" // Para Text +#include "core/resources/resource_cache.hpp" // Para Resource +#include "utils/utils.hpp" // Para Color // [SINGLETON] Debug* Debug::debug = nullptr; @@ -27,7 +27,7 @@ auto Debug::get() -> Debug* { // Dibuja en pantalla void Debug::render() { - auto text = Resource::get()->getText("aseprite"); + auto text = Resource::Cache::get()->getText("aseprite"); int y = y_; int w = 0; diff --git a/source/core/system/director.cpp b/source/core/system/director.cpp index 5c3cb047..19dfd4b2 100644 --- a/source/core/system/director.cpp +++ b/source/core/system/director.cpp @@ -14,9 +14,9 @@ #include "core/audio/audio.hpp" // Para Audio #include "core/input/input.hpp" // Para Input, InputAction #include "core/rendering/screen.hpp" // Para Screen -#include "core/resources/asset.hpp" // Para Asset, AssetType -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/resources/resource_helper.hpp" // Para ResourceHelper +#include "core/resources/resource_list.hpp" // Para Asset, AssetType #include "core/resources/resource_loader.hpp" // Para ResourceLoader #include "core/system/debug.hpp" // Para Debug #include "game/gameplay/cheevos.hpp" // Para Cheevos @@ -69,7 +69,7 @@ Director::Director(std::vector const& args) { // 1. Initialize resource pack system (required, no fallback) std::cout << "Initializing resource pack: " << pack_path << '\n'; - if (!jdd::ResourceHelper::initializeResourceSystem(pack_path, false)) { + if (!Resource::Helper::initializeResourceSystem(pack_path, false)) { std::cerr << "ERROR: Failed to load resources.pack (required in release builds)\n"; exit(EXIT_FAILURE); } @@ -92,8 +92,8 @@ Director::Director(std::vector const& args) { // 4. Initialize Asset system with config from pack // NOTE: In release, don't use executable_path or PREFIX - paths in pack are relative // Pass empty string to avoid issues when running from different directories - Asset::init(""); // Empty executable_path in release - Asset::get()->loadFromString(assets_config, "", system_folder_); // Empty PREFIX for pack + Resource::List::init(""); // Empty executable_path in release + Resource::List::get()->loadFromString(assets_config, "", system_folder_); // Empty PREFIX for pack std::cout << "Asset system initialized from pack\n"; #else @@ -103,7 +103,7 @@ Director::Director(std::vector const& args) { std::cout << "\n** DEVELOPMENT MODE: Filesystem-first initialization\n"; // 1. Initialize Asset system from filesystem - Asset::init(executable_path_); + Resource::List::init(executable_path_); // 2. Load and verify assets from disk if (!setFileList()) { @@ -112,12 +112,12 @@ Director::Director(std::vector const& args) { // 3. Initialize resource pack system (optional, with fallback) std::cout << "Initializing resource pack (development mode): " << pack_path << '\n'; - Jdd::ResourceHelper::initializeResourceSystem(pack_path, true); + Resource::Helper::initializeResourceSystem(pack_path, true); #endif // Carga las opciones desde un fichero - Options::loadFromFile(Asset::get()->get("config.txt")); + Options::loadFromFile(Resource::List::get()->get("config.txt")); // Inicializa JailAudio Audio::init(); @@ -126,7 +126,7 @@ Director::Director(std::vector const& args) { Screen::init(); // Initialize resources (works for both release and development) - Resource::init(); + Resource::Cache::init(); Notifier::init("", "8bithud"); Screen::get()->setNotificationsEnabled(true); @@ -134,10 +134,10 @@ Director::Director(std::vector const& args) { #ifdef RELEASE_BUILD // In release, construct the path manually (not from Asset which has empty executable_path) std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt"; - Input::init(gamecontroller_db, Asset::get()->get("controllers.json")); + Input::init(gamecontroller_db, Resource::List::get()->get("controllers.json")); #else // In development, use Asset as normal - Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles + Input::init(Resource::List::get()->get("gamecontrollerdb.txt"), Resource::List::get()->get("controllers.json")); // Carga configuración de controles #endif // Aplica las teclas configuradas desde Options @@ -150,24 +150,24 @@ Director::Director(std::vector const& args) { std::string cheevos_path = system_folder_ + "/cheevos.bin"; Cheevos::init(cheevos_path); #else - Cheevos::init(Asset::get()->get("cheevos.bin")); + Cheevos::init(Resource::List::get()->get("cheevos.bin")); #endif } Director::~Director() { // Guarda las opciones a un fichero - Options::saveToFile(Asset::get()->get("config.txt")); + Options::saveToFile(Resource::List::get()->get("config.txt")); // Destruye los singletones Cheevos::destroy(); Debug::destroy(); Input::destroy(); Notifier::destroy(); - Resource::destroy(); - Jdd::ResourceHelper::shutdownResourceSystem(); // Shutdown resource pack system + Resource::Cache::destroy(); + Resource::Helper::shutdownResourceSystem(); // Shutdown resource pack system Audio::destroy(); Screen::destroy(); - Asset::destroy(); + Resource::List::destroy(); SDL_Quit(); @@ -264,10 +264,10 @@ auto Director::setFileList() -> bool { std::string config_path = executable_path_ + PREFIX + "/config/assets.txt"; // Cargar todos los assets desde el archivo de configuración - Asset::get()->loadFromFile(config_path, PREFIX, system_folder_); + Resource::List::get()->loadFromFile(config_path, PREFIX, system_folder_); // Verificar que todos los assets requeridos existen - return Asset::get()->check(); + return Resource::List::get()->check(); } // Ejecuta la seccion de juego con el logo diff --git a/source/game/entities/enemy.cpp b/source/game/entities/enemy.cpp index 50b87adc..21b99e22 100644 --- a/source/game/entities/enemy.cpp +++ b/source/game/entities/enemy.cpp @@ -5,13 +5,13 @@ #include // Para rand #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "utils/utils.hpp" // Para stringToColor // Constructor Enemy::Enemy(const Data& enemy) // [DOC:29/10/2025] la surface ara se pillarà del .ANI - : sprite_(std::make_shared(/*Resource::get()->getSurface(enemy.surface_path), */ Resource::get()->getAnimations(enemy.animation_path))), + : sprite_(std::make_shared(/*Resource::Cache::get()->getSurface(enemy.surface_path), */ Resource::Cache::get()->getAnimations(enemy.animation_path))), color_string_(enemy.color), x1_(enemy.x1), x2_(enemy.x2), diff --git a/source/game/entities/item.cpp b/source/game/entities/item.cpp index 108fd52d..e7c61909 100644 --- a/source/game/entities/item.cpp +++ b/source/game/entities/item.cpp @@ -1,11 +1,11 @@ #include "game/entities/item.hpp" #include "core/rendering/surface_sprite.hpp" // Para SSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource // Constructor Item::Item(const Data& item) - : sprite_(std::make_shared(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)), + : sprite_(std::make_shared(Resource::Cache::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)), time_accumulator_(static_cast(item.counter) * COLOR_CHANGE_INTERVAL), is_paused_(false) { // Inicia variables diff --git a/source/game/entities/player.cpp b/source/game/entities/player.cpp index 8f1fa509..c0b3af2e 100644 --- a/source/game/entities/player.cpp +++ b/source/game/entities/player.cpp @@ -9,7 +9,7 @@ #include "core/audio/audio.hpp" // Para Audio #include "core/input/input.hpp" // Para Input, InputAction #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "game/gameplay/room.hpp" // Para Room, TileType #include "game/options.hpp" // Para Cheat, Options, options #include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT @@ -196,7 +196,7 @@ void Player::handleState(float delta_time) { } else if (state_ == State::STANDING) { // Si no tiene suelo debajo y no está en rampa descendente -> FALLING if (!isOnFloor() && !isOnConveyorBelt() && !isOnDownSlope()) { - transitionToState(State::FALLING); // setState() establece vx_=0, vy_=MAX_VY + transitionToState(State::FALLING); // setState() establece vx_=0, vy_=MAX_VY } } else if (state_ == State::JUMPING) { playJumpSound(delta_time); @@ -545,10 +545,10 @@ void Player::updateFeet() { void Player::initSounds() { for (int i = 0; i < 24; ++i) { std::string sound_file = "jump" + std::to_string(i + 1) + ".wav"; - jumping_sound_[i] = Resource::get()->getSound(sound_file); + jumping_sound_[i] = Resource::Cache::get()->getSound(sound_file); if (i >= 10) { // i+1 >= 11 - falling_sound_[i - 10] = Resource::get()->getSound(sound_file); + falling_sound_[i - 10] = Resource::Cache::get()->getSound(sound_file); } } } @@ -649,7 +649,7 @@ void Player::applySpawnValues(const SpawnData& spawn) { // Inicializa el sprite del jugador void Player::initSprite(const std::string& animations_path) { - auto animations = Resource::get()->getAnimations(animations_path); + auto animations = Resource::Cache::get()->getAnimations(animations_path); sprite_ = std::make_unique(animations); sprite_->setWidth(WIDTH); sprite_->setHeight(HEIGHT); diff --git a/source/game/entities/player.cpp.bak b/source/game/entities/player.cpp.bak index cd23f374..6dba9902 100644 --- a/source/game/entities/player.cpp.bak +++ b/source/game/entities/player.cpp.bak @@ -9,7 +9,7 @@ #include "core/audio/audio.hpp" // Para Audio #include "core/input/input.hpp" // Para Input, InputAction #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "game/gameplay/room.hpp" // Para Room, TileType #include "game/options.hpp" // Para Cheat, Options, options #include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT @@ -585,10 +585,10 @@ void Player::initSounds() { for (int i = 1; i <= 24; ++i) { std::string sound_file = "jump" + std::to_string(i) + ".wav"; - jumping_sound_.push_back(Resource::get()->getSound(sound_file)); + jumping_sound_.push_back(Resource::Cache::get()->getSound(sound_file)); if (i >= 11) { - falling_sound_.push_back(Resource::get()->getSound(sound_file)); + falling_sound_.push_back(Resource::Cache::get()->getSound(sound_file)); } } } @@ -607,7 +607,7 @@ void Player::applySpawnValues(const SpawnData& spawn) { // Inicializa el sprite del jugador void Player::initSprite(const std::string& animations_path) { - auto animations = Resource::get()->getAnimations(animations_path); + auto animations = Resource::Cache::get()->getAnimations(animations_path); sprite_ = std::make_unique(animations); sprite_->setWidth(WIDTH); diff --git a/source/game/gameplay/room.cpp b/source/game/gameplay/room.cpp index 6b26d87a..c774e3c6 100644 --- a/source/game/gameplay/room.cpp +++ b/source/game/gameplay/room.cpp @@ -11,7 +11,7 @@ #include "core/rendering/screen.hpp" // Para Screen #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_sprite.hpp" // Para SSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/resources/resource_helper.hpp" // Para ResourceHelper #include "core/system/debug.hpp" // Para Debug #include "game/gameplay/item_tracker.hpp" // Para ItemTracker @@ -23,7 +23,7 @@ // Constructor Room::Room(const std::string& room_path, std::shared_ptr data) : data_(std::move(std::move(data))) { - auto room = Resource::get()->getRoom(room_path); + auto room = Resource::Cache::get()->getRoom(room_path); initializeRoom(*room); openTheJail(); // Abre la Jail si se da el caso @@ -49,8 +49,8 @@ void Room::initializeRoom(const Data& room) { tile_set_file_ = room.tile_set_file; tile_map_file_ = room.tile_map_file; conveyor_belt_direction_ = room.conveyor_belt_direction; - tile_map_ = Resource::get()->getTileMap(room.tile_map_file); - surface_ = Resource::get()->getSurface(room.tile_set_file); + tile_map_ = Resource::Cache::get()->getTileMap(room.tile_map_file); + surface_ = Resource::Cache::get()->getSurface(room.tile_set_file); tile_set_width_ = surface_->getWidth() / TILE_SIZE; is_paused_ = false; time_accumulator_ = 0.0F; @@ -930,7 +930,7 @@ auto Room::loadRoomTileFile(const std::string& file_path, bool verbose) -> std:: const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1); // Load file using ResourceHelper (supports both filesystem and pack) - auto file_data = Jdd::ResourceHelper::loadFile(file_path); + auto file_data = Resource::Helper::loadFile(file_path); if (!file_data.empty()) { // Convert bytes to string and parse @@ -992,7 +992,7 @@ auto Room::loadRoomFile(const std::string& file_path, bool verbose) -> Data { room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of('.')); // Load file using ResourceHelper (supports both filesystem and pack) - auto file_data = Jdd::ResourceHelper::loadFile(file_path); + auto file_data = Resource::Helper::loadFile(file_path); if (!file_data.empty()) { // Convert bytes to string and parse diff --git a/source/game/gameplay/scoreboard.cpp b/source/game/gameplay/scoreboard.cpp index 6e540d4e..2e61c3d1 100644 --- a/source/game/gameplay/scoreboard.cpp +++ b/source/game/gameplay/scoreboard.cpp @@ -8,21 +8,21 @@ #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite #include "core/rendering/text.hpp" // Para Text -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "game/options.hpp" // Para Options, options, Cheat, OptionsGame #include "utils/defines.hpp" // Para BLOCK #include "utils/utils.hpp" // Para stringToColor // Constructor Scoreboard::Scoreboard(std::shared_ptr data) - : item_surface_(Resource::get()->getSurface("items.gif")), + : item_surface_(Resource::Cache::get()->getSurface("items.gif")), data_(std::move(std::move(data))) { const float SURFACE_WIDTH = Options::game.width; constexpr float SURFACE_HEIGHT = 6.0F * TILE_SIZE; // Reserva memoria para los objetos - // auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif"); - auto player_animations = Resource::get()->getAnimations(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani"); + // auto player_texture = Resource::Cache::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif"); + auto player_animations = Resource::Cache::get()->getAnimations(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani"); player_sprite_ = std::make_shared(player_animations); player_sprite_->setCurrentAnimation("walk_menu"); @@ -154,7 +154,7 @@ void Scoreboard::fillTexture() { } // Escribe los textos - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); const std::string TIME_TEXT = std::to_string((clock_.minutes % 100) / 10) + std::to_string(clock_.minutes % 10) + clock_.separator + std::to_string((clock_.seconds % 60) / 10) + std::to_string(clock_.seconds % 10); const std::string ITEMS_TEXT = std::to_string(data_->items / 100) + std::to_string((data_->items % 100) / 10) + std::to_string(data_->items % 10); text->writeColored(TILE_SIZE, LINE1, "Items collected ", data_->color); diff --git a/source/game/scenes/credits.cpp b/source/game/scenes/credits.cpp index 22ae2233..7aaf9cfa 100644 --- a/source/game/scenes/credits.cpp +++ b/source/game/scenes/credits.cpp @@ -11,7 +11,7 @@ #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite #include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/system/global_events.hpp" // Para check #include "game/options.hpp" // Para Options, options, OptionsGame, Sectio... #include "game/scene_manager.hpp" // Para SceneManager @@ -23,7 +23,7 @@ Credits::Credits() : text_surface_(std::make_shared(Options::game.width, Options::game.height)), cover_surface_(std::make_shared(Options::game.width, Options::game.height)), - shining_sprite_(std::make_shared(Resource::get()->getAnimations("shine.ani"))), + shining_sprite_(std::make_shared(Resource::Cache::get()->getAnimations("shine.ani"))), delta_timer_(std::make_unique()) { // Configura la escena SceneManager::current = SceneManager::Scene::CREDITS; @@ -111,7 +111,7 @@ void Credits::fillTexture() { Screen::get()->setRendererSurface(text_surface_); text_surface_->clear(static_cast(PaletteColor::BLACK)); - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); // Escribe el texto en la textura const int SIZE = text->getCharacterSize(); diff --git a/source/game/scenes/ending.cpp b/source/game/scenes/ending.cpp index cc45d37c..d9550a7a 100644 --- a/source/game/scenes/ending.cpp +++ b/source/game/scenes/ending.cpp @@ -11,7 +11,7 @@ #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_sprite.hpp" // Para SSprite #include "core/rendering/text.hpp" // Para Text, TEXT_STROKE -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/system/global_events.hpp" // Para check #include "game/options.hpp" // Para Options, options, OptionsGame, SectionS... #include "game/scene_manager.hpp" // Para SceneManager @@ -209,7 +209,7 @@ void Ending::iniTexts() { sprite_texts_.clear(); for (const auto& txt : texts) { - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); const float WIDTH = text->lenght(txt.caption, 1) + 2 + 2; const float HEIGHT = text->getCharacterSize() + 2 + 2; @@ -284,7 +284,7 @@ void Ending::iniPics() { EndingSurface sp; // Crea la texture - sp.image_surface = Resource::get()->getSurface(pic.caption); + sp.image_surface = Resource::Cache::get()->getSurface(pic.caption); sp.image_surface->setTransparentColor(); const float WIDTH = sp.image_surface->getWidth(); const float HEIGHT = sp.image_surface->getHeight(); diff --git a/source/game/scenes/ending2.cpp b/source/game/scenes/ending2.cpp index 0ae0634f..5e775b63 100644 --- a/source/game/scenes/ending2.cpp +++ b/source/game/scenes/ending2.cpp @@ -12,7 +12,7 @@ #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite #include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite #include "core/rendering/text.hpp" // Para Text -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/system/global_events.hpp" // Para check #include "game/options.hpp" // Para Options, options, OptionsGame, Sectio... #include "game/scene_manager.hpp" // Para SceneManager @@ -34,13 +34,12 @@ Ending2::Ending2() colors_.push_back(stringToColor(color)); } - - Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK));// Cambia el color del borde - iniSpriteList();// Inicializa la lista de sprites - loadSprites();// Carga todos los sprites desde una lista - placeSprites();// Coloca los sprites en su sito - createSpriteTexts();// Crea los sprites con las texturas con los textos - createTexts();// Crea los sprites con las texturas con los textos del final + Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); // Cambia el color del borde + iniSpriteList(); // Inicializa la lista de sprites + loadSprites(); // Carga todos los sprites desde una lista + placeSprites(); // Coloca los sprites en su sito + createSpriteTexts(); // Crea los sprites con las texturas con los textos + createTexts(); // Crea los sprites con las texturas con los textos del final } // Actualiza el objeto @@ -288,7 +287,7 @@ void Ending2::loadSprites() { // Carga los sprites for (const auto& file : sprite_list_) { - sprites_.emplace_back(std::make_shared(Resource::get()->getAnimations(file + ".ani"))); + sprites_.emplace_back(std::make_shared(Resource::Cache::get()->getAnimations(file + ".ani"))); sprite_max_width_ = std::max(sprites_.back()->getWidth(), sprite_max_width_); sprite_max_height_ = std::max(sprites_.back()->getHeight(), sprite_max_height_); } @@ -358,7 +357,7 @@ void Ending2::renderTexts() { void Ending2::placeSprites() { for (int i = 0; i < static_cast(sprites_.size()); ++i) { const float X = i % 2 == 0 ? FIRST_COL : SECOND_COL; - const float Y = ((i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT + Resource::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE)) + Options::game.height + INITIAL_Y_OFFSET; + const float Y = ((i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT + Resource::Cache::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE)) + Options::game.height + INITIAL_Y_OFFSET; const float W = sprites_.at(i)->getWidth(); const float H = sprites_.at(i)->getHeight(); const float DX = -(W / 2); @@ -379,7 +378,7 @@ void Ending2::placeSprites() { void Ending2::createSpriteTexts() { // Crea los sprites de texto a partir de la lista for (size_t i = 0; i < sprite_list_.size(); ++i) { - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); // Procesa y ajusta el texto del sprite actual std::string txt = sprite_list_[i]; @@ -420,7 +419,7 @@ void Ending2::createTexts() { std::vector list; list.emplace_back("STARRING"); - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); // Crea los sprites de texto a partir de la lista for (size_t i = 0; i < list.size(); ++i) { diff --git a/source/game/scenes/game.cpp b/source/game/scenes/game.cpp index c6575ba6..05365c66 100644 --- a/source/game/scenes/game.cpp +++ b/source/game/scenes/game.cpp @@ -5,26 +5,26 @@ #include #include // Para vector -#include "core/audio/audio.hpp" // Para Audio -#include "core/input/global_inputs.hpp" // Para check -#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT -#include "core/rendering/screen.hpp" // Para Screen -#include "core/rendering/surface.hpp" // Para Surface -#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "core/resources/asset.hpp" // Para Asset -#include "core/resources/resource.hpp" // Para ResourceRoom, Resource -#include "core/system/global_events.hpp" // Para check -#include "game/gameplay/cheevos.hpp" // Para Cheevos -#include "game/gameplay/item_tracker.hpp" // Para ItemTracker -#include "game/gameplay/room.hpp" // Para Room, RoomData -#include "game/gameplay/room_tracker.hpp" // Para RoomTracker -#include "game/gameplay/scoreboard.hpp" // Para Scoreboard::Data, Scoreboard -#include "game/gameplay/stats.hpp" // Para Stats -#include "game/options.hpp" // Para Options, options, Cheat, SectionState -#include "game/scene_manager.hpp" // Para SceneManager -#include "game/ui/notifier.hpp" // Para Notifier, NotificationText, CHEEVO_NO... -#include "utils/defines.hpp" // Para TILE_SIZE, PLAY_AREA_HEIGHT, RoomBorder::BOTTOM -#include "utils/utils.hpp" // Para PaletteColor, stringToColor +#include "core/audio/audio.hpp" // Para Audio +#include "core/input/global_inputs.hpp" // Para check +#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT +#include "core/rendering/screen.hpp" // Para Screen +#include "core/rendering/surface.hpp" // Para Surface +#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR +#include "core/resources/resource_cache.hpp" // Para ResourceRoom, Resource +#include "core/resources/resource_list.hpp" // Para Asset +#include "core/system/global_events.hpp" // Para check +#include "game/gameplay/cheevos.hpp" // Para Cheevos +#include "game/gameplay/item_tracker.hpp" // Para ItemTracker +#include "game/gameplay/room.hpp" // Para Room, RoomData +#include "game/gameplay/room_tracker.hpp" // Para RoomTracker +#include "game/gameplay/scoreboard.hpp" // Para Scoreboard::Data, Scoreboard +#include "game/gameplay/stats.hpp" // Para Stats +#include "game/options.hpp" // Para Options, options, Cheat, SectionState +#include "game/scene_manager.hpp" // Para SceneManager +#include "game/ui/notifier.hpp" // Para Notifier, NotificationText, CHEEVO_NO... +#include "utils/defines.hpp" // Para TILE_SIZE, PLAY_AREA_HEIGHT, RoomBorder::BOTTOM +#include "utils/utils.hpp" // Para PaletteColor, stringToColor #ifdef _DEBUG #include "core/system/debug.hpp" // Para Debug @@ -35,7 +35,7 @@ Game::Game(Mode mode) : board_(std::make_shared(0, 9, 0, true, 0, SDL_GetTicks(), Options::cheats.jail_is_open == Options::Cheat::State::ENABLED)), scoreboard_(std::make_shared(board_)), room_tracker_(std::make_shared()), - stats_(std::make_shared(Asset::get()->get("stats.csv"), Asset::get()->get("stats_buffer.csv"))), + stats_(std::make_shared(Resource::List::get()->get("stats.csv"), Resource::List::get()->get("stats_buffer.csv"))), mode_(mode), #ifdef _DEBUG current_room_("03.room"), @@ -229,7 +229,7 @@ void Game::handleDebugEvents(const SDL_Event& event) { break; case SDL_SCANCODE_R: - Resource::get()->reload(); + Resource::Cache::get()->reload(); break; case SDL_SCANCODE_W: @@ -273,7 +273,7 @@ auto Game::changeRoom(const std::string& room_path) -> bool { } // Verifica que exista el fichero que se va a cargar - if (!Asset::get()->get(room_path).empty()) { + if (!Resource::List::get()->get(room_path).empty()) { // Crea un objeto habitación nuevo a partir del fichero room_ = std::make_shared(room_path, board_); @@ -441,7 +441,7 @@ auto Game::checkEndGame() -> bool { // Obtiene la cantidad total de items que hay en el mapeado del juego auto Game::getTotalItems() -> int { int items = 0; - auto rooms = Resource::get()->getRooms(); + auto rooms = Resource::Cache::get()->getRooms(); for (const auto& room : rooms) { items += room.room->items.size(); @@ -486,7 +486,7 @@ void Game::checkRestoringJail(float delta_time) { // Inicializa el diccionario de las estadísticas void Game::initStats() { - auto list = Resource::get()->getRooms(); + auto list = Resource::Cache::get()->getRooms(); for (const auto& room : list) { stats_->addDictionary(room.room->number, room.room->name); @@ -505,7 +505,7 @@ void Game::fillRoomNameTexture() { room_name_surface_->clear(stringToColor("white")); // Escribe el texto en la textura - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, text->getCharacterSize() / 2, room_->getName(), 1, room_->getBGColor()); // Deja el renderizador por defecto @@ -580,7 +580,7 @@ void Game::initPlayer(const Player::SpawnData& spawn_point, std::shared_ptrgetText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); room_name_surface_ = std::make_shared(Options::game.width, text->getCharacterSize() * 2); // Establece el destino de la textura diff --git a/source/game/scenes/game_over.cpp b/source/game/scenes/game_over.cpp index cd204ad7..59e134e0 100644 --- a/source/game/scenes/game_over.cpp +++ b/source/game/scenes/game_over.cpp @@ -11,7 +11,7 @@ #include "core/rendering/screen.hpp" // Para Screen #include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite #include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/system/global_events.hpp" // Para check #include "game/options.hpp" // Para Options, options, OptionsStats, Secti... #include "game/scene_manager.hpp" // Para SceneManager @@ -21,8 +21,8 @@ // Constructor GameOver::GameOver() - : player_sprite_(std::make_shared(Resource::get()->getAnimations("player_game_over.ani"))), - tv_sprite_(std::make_shared(Resource::get()->getAnimations("tv.ani"))), + : player_sprite_(std::make_shared(Resource::Cache::get()->getAnimations("player_game_over.ani"))), + tv_sprite_(std::make_shared(Resource::Cache::get()->getAnimations("tv.ani"))), delta_timer_(std::make_shared()) { SceneManager::current = SceneManager::Scene::GAME_OVER; SceneManager::options = SceneManager::Options::NONE; @@ -65,7 +65,7 @@ void GameOver::render() { Screen::get()->start(); Screen::get()->clearSurface(static_cast(PaletteColor::BLACK)); - auto text = Resource::get()->getText("smb2"); + auto text = Resource::Cache::get()->getText("smb2"); // Escribe el texto de GAME OVER text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, TEXT_Y, "G A M E O V E R", 1, color_); diff --git a/source/game/scenes/loading_screen.cpp b/source/game/scenes/loading_screen.cpp index 64ad567f..0f48fe99 100644 --- a/source/game/scenes/loading_screen.cpp +++ b/source/game/scenes/loading_screen.cpp @@ -11,7 +11,7 @@ #include "core/rendering/screen.hpp" // Para Screen #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_sprite.hpp" // Para SSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/system/global_events.hpp" // Para check #include "game/options.hpp" // Para Options, options, SectionState, Options... #include "game/scene_manager.hpp" // Para SceneManager @@ -20,11 +20,11 @@ // Constructor LoadingScreen::LoadingScreen() - : mono_loading_screen_surface_(Resource::get()->getSurface("loading_screen_bn.gif")), - color_loading_screen_surface_(Resource::get()->getSurface("loading_screen_color.gif")), + : mono_loading_screen_surface_(Resource::Cache::get()->getSurface("loading_screen_bn.gif")), + color_loading_screen_surface_(Resource::Cache::get()->getSurface("loading_screen_color.gif")), mono_loading_screen_sprite_(std::make_unique(mono_loading_screen_surface_, 0, 0, mono_loading_screen_surface_->getWidth(), mono_loading_screen_surface_->getHeight())), color_loading_screen_sprite_(std::make_unique(color_loading_screen_surface_, 0, 0, color_loading_screen_surface_->getWidth(), color_loading_screen_surface_->getHeight())), - program_sprite_(std::make_unique(Resource::get()->getSurface("program_jaildoc.gif"))), + program_sprite_(std::make_unique(Resource::Cache::get()->getSurface("program_jaildoc.gif"))), screen_surface_(std::make_shared(Options::game.width, Options::game.height)), delta_timer_(std::make_unique()) { // Configura la superficie donde se van a pintar los sprites @@ -312,7 +312,7 @@ void LoadingScreen::renderHeaderBorder() const { const auto COLOR = carrier_.toggle ? static_cast(PaletteColor::RED) : static_cast(PaletteColor::CYAN); const int WIDTH = Options::game.width + (Options::video.border.width * 2); const int HEIGHT = Options::game.height + (Options::video.border.height * 2); - + // Primera linea (con el color y tamaño de la portadora) int row = 0; const int FIRST_ROW_HEIGHT = static_cast(carrier_.offset); @@ -320,7 +320,7 @@ void LoadingScreen::renderHeaderBorder() const { border->drawLine(0, i, WIDTH, i, COLOR); } row += FIRST_ROW_HEIGHT; - + // Resto de lineas (siguen a la portadora) bool draw_enabled = false; while (row < HEIGHT) { diff --git a/source/game/scenes/logo.cpp b/source/game/scenes/logo.cpp index 7b389e3b..d42cd681 100644 --- a/source/game/scenes/logo.cpp +++ b/source/game/scenes/logo.cpp @@ -12,7 +12,7 @@ #include "core/rendering/screen.hpp" // Para Screen #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_sprite.hpp" // Para SSprite -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "core/system/global_events.hpp" // Para check #include "game/options.hpp" // Para Options, SectionState, options, Section #include "game/scene_manager.hpp" // Para SceneManager @@ -22,8 +22,8 @@ // Constructor Logo::Logo() - : jailgames_surface_(Resource::get()->getSurface("jailgames.gif")), - since_1998_surface_(Resource::get()->getSurface("since_1998.gif")), + : jailgames_surface_(Resource::Cache::get()->getSurface("jailgames.gif")), + since_1998_surface_(Resource::Cache::get()->getSurface("since_1998.gif")), since_1998_sprite_(std::make_shared(since_1998_surface_, (256 - since_1998_surface_->getWidth()) / 2, 83 + jailgames_surface_->getHeight() + 5, since_1998_surface_->getWidth(), since_1998_surface_->getHeight())), delta_timer_(std::make_unique()) { // Configura variables diff --git a/source/game/scenes/title.cpp b/source/game/scenes/title.cpp index 350a82de..720c65b2 100644 --- a/source/game/scenes/title.cpp +++ b/source/game/scenes/title.cpp @@ -11,8 +11,8 @@ #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_sprite.hpp" // Para SSprite #include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "core/resources/asset.hpp" // Para Asset -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource +#include "core/resources/resource_list.hpp" // Para Asset #include "core/system/global_events.hpp" // Para check #include "game/gameplay/cheevos.hpp" // Para Cheevos, Achievement #include "game/options.hpp" // Para Options, options, SectionState, Section @@ -22,14 +22,14 @@ // Constructor Title::Title() - : game_logo_surface_(Resource::get()->getSurface("title_logo.gif")), + : game_logo_surface_(Resource::Cache::get()->getSurface("title_logo.gif")), game_logo_sprite_(std::make_unique(game_logo_surface_, 29, 9, game_logo_surface_->getWidth(), game_logo_surface_->getHeight())), - loading_screen_surface_(Resource::get()->getSurface("loading_screen_color.gif")), + loading_screen_surface_(Resource::Cache::get()->getSurface("loading_screen_color.gif")), loading_screen_sprite_(std::make_unique(loading_screen_surface_, 0, 0, loading_screen_surface_->getWidth(), loading_screen_surface_->getHeight())), title_surface_(std::make_shared(Options::game.width, Options::game.height)), delta_timer_(std::make_unique()), - marquee_text_(Resource::get()->getText("gauntlet")), - menu_text_(Resource::get()->getText("gauntlet")) { + marquee_text_(Resource::Cache::get()->getText("gauntlet")), + menu_text_(Resource::Cache::get()->getText("gauntlet")) { // Inicializa arrays con valores por defecto temp_keys_.fill(SDL_SCANCODE_UNKNOWN); temp_buttons_.fill(-1); @@ -437,7 +437,7 @@ void Title::createCheevosTexture() { // Crea la textura con el listado de logros const auto CHEEVOS_LIST = Cheevos::get()->list(); - const auto TEXT = Resource::get()->getText("subatomic"); + const auto TEXT = Resource::Cache::get()->getText("subatomic"); constexpr int CHEEVOS_TEXTURE_WIDTH = 200; constexpr int CHEEVOS_TEXTURE_VIEW_HEIGHT = MENU_ZONE_HEIGHT; constexpr int CHEEVOS_PADDING = 10; @@ -653,7 +653,7 @@ void Title::applyKeyboardRemap() { Input::get()->applyKeyboardBindingsFromOptions(); // Guardar a archivo de configuracion - Options::saveToFile(Asset::get()->get("config.txt")); + Options::saveToFile(Resource::List::get()->get("config.txt")); } // Dibuja la pantalla de redefinir teclado @@ -836,7 +836,7 @@ void Title::applyJoystickRemap() { Input::get()->applyGamepadBindingsFromOptions(); // Guardar a archivo de configuracion - Options::saveToFile(Asset::get()->get("config.txt")); + Options::saveToFile(Resource::List::get()->get("config.txt")); } // Retorna el nombre amigable del botón del gamepad diff --git a/source/game/ui/notifier.cpp b/source/game/ui/notifier.cpp index e2b82079..56a0a60c 100644 --- a/source/game/ui/notifier.cpp +++ b/source/game/ui/notifier.cpp @@ -13,7 +13,7 @@ #include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface_sprite.hpp" // Para SSprite #include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR -#include "core/resources/resource.hpp" // Para Resource +#include "core/resources/resource_cache.hpp" // Para Resource #include "game/options.hpp" // Para Options, options, NotificationPosition #include "utils/delta_timer.hpp" // Para DeltaTimer #include "utils/utils.hpp" // Para PaletteColor @@ -38,8 +38,8 @@ auto Notifier::get() -> Notifier* { // Constructor Notifier::Notifier(const std::string& icon_file, const std::string& text) - : icon_surface_(!icon_file.empty() ? Resource::get()->getSurface(icon_file) : nullptr), - text_(Resource::get()->getText(text)), + : icon_surface_(!icon_file.empty() ? Resource::Cache::get()->getSurface(icon_file) : nullptr), + text_(Resource::Cache::get()->getText(text)), delta_timer_(std::make_unique()), bg_color_(Options::notifications.color), has_icons_(!icon_file.empty()) {} diff --git a/source/utils/utils.cpp b/source/utils/utils.cpp index 5e44b8e9..5809b0f7 100644 --- a/source/utils/utils.cpp +++ b/source/utils/utils.cpp @@ -11,8 +11,8 @@ #include // Para unordered_map, operator==, _Node_const_iter... #include // Para pair -#include "core/resources/resource.hpp" // Para Resource -#include "external/jail_audio.h" // Para JA_GetMusicState, JA_Music_state, JA_PlayMusic +#include "core/resources/resource_cache.hpp" // Para Resource +#include "external/jail_audio.h" // Para JA_GetMusicState, JA_Music_state, JA_PlayMusic // Calcula el cuadrado de la distancia entre dos puntos auto distanceSquared(int x1, int y1, int x2, int y2) -> double { @@ -429,7 +429,7 @@ auto stringInVector(const std::vector& vec, const std::string& str) void playMusic(const std::string& music_path) { // Si la música no está sonando if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) { - JA_PlayMusic(Resource::get()->getMusic(music_path)); + JA_PlayMusic(Resource::Cache::get()->getMusic(music_path)); } }