unificats els resources en un namespace

This commit is contained in:
2025-11-11 10:04:57 +01:00
parent 1821b84e73
commit 54fc6d2902
35 changed files with 356 additions and 341 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -5,9 +5,9 @@
#include <algorithm> // Para clamp
#include <iostream> // 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<int>(group));
JA_PlaySound(Resource::Cache::get()->getSound(name), 0, static_cast<int>(group));
}
}

View File

@@ -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<Uint8>(PaletteColor::YELLOW);
// FPS
@@ -397,7 +397,7 @@ auto Screen::getBorderSurface() -> std::shared_ptr<Surface> { return border_surf
auto loadData(const std::string& filepath) -> std::vector<uint8_t> {
// 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<Surface>(Asset::get()->get("aseprite.gif"));
auto surface = std::make_shared<Surface>(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<Text>(surface, Asset::get()->get("aseprite.txt"));
text_ = std::make_shared<Text>(surface, Resource::List::get()->get("aseprite.txt"));
}

View File

@@ -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<Uint8> buffer = Jdd::ResourceHelper::loadFile(file_path);
std::vector<Uint8> buffer = Resource::Helper::loadFile(file_path);
if (buffer.empty()) {
std::cerr << "Error opening file: " << file_path << '\n';
throw std::runtime_error("Error opening file");

View File

@@ -8,14 +8,14 @@
#include <utility>
#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<Surface>& 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") {

View File

@@ -28,7 +28,7 @@ auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile> {
}
// 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));

View File

@@ -1,4 +1,4 @@
#include "core/resources/resource.hpp"
#include "core/resources/resource_cache.hpp"
#include <SDL3/SDL.h>
@@ -8,40 +8,42 @@
#include <stdexcept> // Para runtime_error
#include <utility>
#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<Uint8>(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<Surface> {
auto Cache::getSurface(const std::string& name) -> std::shared_ptr<Surface> {
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<Surface> {
}
// 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<TextFile> {
auto Cache::getTextFile(const std::string& name) -> std::shared_ptr<TextFile> {
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<TextFile>
}
// Obtiene el objeto de texto a partir de un nombre
auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> {
auto Cache::getText(const std::string& name) -> std::shared_ptr<Text> {
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<Text> {
}
// 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<int>& {
auto Cache::getTileMap(const std::string& name) -> std::vector<int>& {
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<int>& {
}
// Obtiene la habitación a partir de un nombre
auto Resource::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
auto Cache::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
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<Room::Data> {
}
// Obtiene todas las habitaciones
auto Resource::getRooms() -> std::vector<ResourceRoom>& {
auto Cache::getRooms() -> std::vector<ResourceRoom>& {
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<Uint32>(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<Uint32>(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::Type> 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<List::Type> 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();
}
}
} // namespace Resource

View File

@@ -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<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> 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();
};
};
} // namespace Resource

View File

@@ -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<uint8_t> {
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<uint8_t> {
}
// 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

View File

@@ -8,7 +8,7 @@
#include <string>
#include <vector>
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

View File

@@ -1,4 +1,4 @@
#include "core/resources/asset.hpp"
#include "core/resources/resource_list.hpp"
#include <SDL3/SDL.h> // 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<uint8_t> {
auto List::loadData(const std::string& filename) const -> std::vector<uint8_t> {
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<uint8_t>
}
// 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<std::string> {
auto List::getListByType(Type type) const -> std::vector<std::string> {
std::vector<std::string> list;
for (const auto& [filename, item] : file_list_) {
@@ -311,7 +313,7 @@ auto Asset::getListByType(Type type) const -> std::vector<std::string> {
}
// 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

View File

@@ -6,8 +6,10 @@
#include <utility> // Para move
#include <vector> // 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

View File

@@ -7,19 +7,19 @@
#include <fstream>
#include <iostream>
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<ResourcePack>();
std::cout << "Loader: Loading pack file: " << pack_file << '\n';
resource_pack_ = std::make_unique<Pack>();
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<uint8_t> {
auto Loader::loadResource(const std::string& filename) -> std::vector<uint8_t> {
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<ui
if (!data.empty()) {
return data;
}
std::cerr << "ResourceLoader: Failed to extract from pack: " << filename
std::cerr << "Loader: Failed to extract from pack: " << filename
<< '\n';
}
}
@@ -76,12 +76,12 @@ auto ResourceLoader::loadResource(const std::string& filename) -> std::vector<ui
return loadFromFilesystem(filename);
}
std::cerr << "ResourceLoader: Resource not found: " << filename << '\n';
std::cerr << "Loader: Resource not found: " << filename << '\n';
return {};
}
// Check if a resource exists
auto ResourceLoader::resourceExists(const std::string& filename) -> 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<uint8_t> {
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<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(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

View File

@@ -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<uint8_t>;
@@ -59,11 +59,11 @@ class ResourceLoader {
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
// Member data
std::unique_ptr<ResourcePack> resource_pack_;
std::unique_ptr<Pack> resource_pack_;
bool fallback_to_files_{true};
bool initialized_{false};
};
} // namespace Jdd
} // namespace Resource
#endif // RESOURCE_LOADER_HPP

View File

@@ -10,10 +10,10 @@
#include <fstream>
#include <iostream>
namespace Jdd {
namespace Resource {
// Calculate CRC32 checksum for data verification
auto ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t {
auto Pack::calculateChecksum(const std::vector<uint8_t>& 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<uint8_t>& data) -> uint32
}
// XOR encryption (symmetric - same function for encrypt/decrypt)
void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
void Pack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
if (key.empty()) {
return;
}
@@ -31,13 +31,13 @@ void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& ke
}
}
void ResourcePack::decryptData(std::vector<uint8_t>& data, const std::string& key) {
void Pack::decryptData(std::vector<uint8_t>& 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<uint8_t> {
auto Pack::readFile(const std::string& filepath) -> std::vector<uint8_t> {
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<uint8_t>
}
// 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<uint8_t> {
auto Pack::getResource(const std::string& filename) -> std::vector<uint8_t> {
auto it = resources_.find(filename);
if (it == resources_.end()) {
return {};
@@ -258,12 +258,12 @@ auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8
}
// Check if a resource exists
auto ResourcePack::hasResource(const std::string& filename) const -> 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<std::string> {
auto Pack::getResourceList() const -> std::vector<std::string> {
std::vector<std::string> list;
list.reserve(resources_.size());
for (const auto& [name, entry] : resources_) {
@@ -274,7 +274,7 @@ auto ResourcePack::getResourceList() const -> std::vector<std::string> {
}
// 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

View File

@@ -11,7 +11,7 @@
#include <unordered_map>
#include <vector>
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

View File

@@ -3,9 +3,9 @@
#include <algorithm> // Para max
#include <memory> // 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;

View File

@@ -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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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

View File

@@ -5,13 +5,13 @@
#include <cstdlib> // 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<SurfaceAnimatedSprite>(/*Resource::get()->getSurface(enemy.surface_path), */ Resource::get()->getAnimations(enemy.animation_path))),
: sprite_(std::make_shared<SurfaceAnimatedSprite>(/*Resource::Cache::get()->getSurface(enemy.surface_path), */ Resource::Cache::get()->getAnimations(enemy.animation_path))),
color_string_(enemy.color),
x1_(enemy.x1),
x2_(enemy.x2),

View File

@@ -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<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
: sprite_(std::make_shared<SurfaceSprite>(Resource::Cache::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
time_accumulator_(static_cast<float>(item.counter) * COLOR_CHANGE_INTERVAL),
is_paused_(false) {
// Inicia variables

View File

@@ -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<SurfaceAnimatedSprite>(animations);
sprite_->setWidth(WIDTH);
sprite_->setHeight(HEIGHT);

View File

@@ -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<SurfaceAnimatedSprite>(animations);
sprite_->setWidth(WIDTH);

View File

@@ -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<Scoreboard::Data> 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

View File

@@ -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> 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<SurfaceAnimatedSprite>(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);

View File

@@ -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<Surface>(Options::game.width, Options::game.height)),
cover_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
shining_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getAnimations("shine.ani"))),
shining_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::Cache::get()->getAnimations("shine.ani"))),
delta_timer_(std::make_unique<DeltaTimer>()) {
// 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<Uint8>(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();

View File

@@ -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();

View File

@@ -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<Uint8>(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<Uint8>(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<SurfaceAnimatedSprite>(Resource::get()->getAnimations(file + ".ani")));
sprites_.emplace_back(std::make_shared<SurfaceAnimatedSprite>(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<int>(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<std::string> 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) {

View File

@@ -5,26 +5,26 @@
#include <utility>
#include <vector> // 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<Scoreboard::Data>(0, 9, 0, true, 0, SDL_GetTicks(), Options::cheats.jail_is_open == Options::Cheat::State::ENABLED)),
scoreboard_(std::make_shared<Scoreboard>(board_)),
room_tracker_(std::make_shared<RoomTracker>()),
stats_(std::make_shared<Stats>(Asset::get()->get("stats.csv"), Asset::get()->get("stats_buffer.csv"))),
stats_(std::make_shared<Stats>(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>(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_ptr<Room
// Crea la textura para poner el nombre de la habitación
void Game::createRoomNameTexture() {
auto text = Resource::get()->getText("smb2");
auto text = Resource::Cache::get()->getText("smb2");
room_name_surface_ = std::make_shared<Surface>(Options::game.width, text->getCharacterSize() * 2);
// Establece el destino de la textura

View File

@@ -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<SurfaceAnimatedSprite>(Resource::get()->getAnimations("player_game_over.ani"))),
tv_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getAnimations("tv.ani"))),
: player_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::Cache::get()->getAnimations("player_game_over.ani"))),
tv_sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::Cache::get()->getAnimations("tv.ani"))),
delta_timer_(std::make_shared<DeltaTimer>()) {
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<Uint8>(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_);

View File

@@ -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<SurfaceSprite>(mono_loading_screen_surface_, 0, 0, mono_loading_screen_surface_->getWidth(), mono_loading_screen_surface_->getHeight())),
color_loading_screen_sprite_(std::make_unique<SurfaceSprite>(color_loading_screen_surface_, 0, 0, color_loading_screen_surface_->getWidth(), color_loading_screen_surface_->getHeight())),
program_sprite_(std::make_unique<SurfaceSprite>(Resource::get()->getSurface("program_jaildoc.gif"))),
program_sprite_(std::make_unique<SurfaceSprite>(Resource::Cache::get()->getSurface("program_jaildoc.gif"))),
screen_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
delta_timer_(std::make_unique<DeltaTimer>()) {
// 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<Uint8>(PaletteColor::RED) : static_cast<Uint8>(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<int>(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) {

View File

@@ -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<SurfaceSprite>(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<DeltaTimer>()) {
// Configura variables

View File

@@ -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<SurfaceSprite>(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<SurfaceSprite>(loading_screen_surface_, 0, 0, loading_screen_surface_->getWidth(), loading_screen_surface_->getHeight())),
title_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
delta_timer_(std::make_unique<DeltaTimer>()),
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

View File

@@ -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<DeltaTimer>()),
bg_color_(Options::notifications.color),
has_icons_(!icon_file.empty()) {}

View File

@@ -11,8 +11,8 @@
#include <unordered_map> // Para unordered_map, operator==, _Node_const_iter...
#include <utility> // 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<std::string>& 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));
}
}