Compare commits

...

2 Commits

Author SHA1 Message Date
cabee86ee0 Resource: afegida pantalla de progres de càrrega
Screen: Afegit objecte de text propi per a la clase
2025-06-10 22:08:17 +02:00
02b111e4fd Resource: treballant en la visualització de la càrrega de recursos 2025-06-10 18:42:14 +02:00
7 changed files with 332 additions and 193 deletions

View File

@@ -52,7 +52,7 @@ bool Asset::check() const
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES");
// Comprueba la lista de ficheros clasificándolos por tipo // Comprueba la lista de ficheros clasificándolos por tipo
for (int type = 0; type < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type) for (int type = 0; type < static_cast<int>(AssetType::COUNT); ++type)
{ {
// Comprueba si hay ficheros de ese tipo // Comprueba si hay ficheros de ese tipo
bool any = false; bool any = false;
@@ -131,8 +131,6 @@ std::string Asset::getTypeName(AssetType type) const
return "ANIMATION"; return "ANIMATION";
case AssetType::PALETTE: case AssetType::PALETTE:
return "PALETTE"; return "PALETTE";
case AssetType::ITEM:
return "ITEM";
default: default:
return "ERROR"; return "ERROR";
} }

View File

@@ -15,10 +15,10 @@ enum class AssetType : int
FONT, FONT,
LANG, LANG,
DATA, DATA,
DEMODATA,
ANIMATION, ANIMATION,
PALETTE, PALETTE,
ITEM, COUNT,
MAX_ASSET_TYPE,
}; };
// Clase Asset: gestor de recursos (singleton) // Clase Asset: gestor de recursos (singleton)

View File

@@ -103,12 +103,6 @@ void Director::init()
Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones
Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones
#ifdef DEBUG
// Configuración adicional en modo depuración
Screen::get()->initDebugInfo();
Screen::get()->setDebugInfoEnabled(true);
#endif
} }
// Cierra todo y libera recursos del sistema y de los singletons // Cierra todo y libera recursos del sistema y de los singletons
@@ -287,8 +281,8 @@ void Director::setFileList()
Asset::get()->add(system_folder_ + "/score.bin", AssetType::DATA, false, true); Asset::get()->add(system_folder_ + "/score.bin", AssetType::DATA, false, true);
Asset::get()->add(prefix + "/data/config/param_320x240.txt", AssetType::DATA); Asset::get()->add(prefix + "/data/config/param_320x240.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/param_320x256.txt", AssetType::DATA); Asset::get()->add(prefix + "/data/config/param_320x256.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/demo1.bin", AssetType::DATA); Asset::get()->add(prefix + "/data/config/demo1.bin", AssetType::DEMODATA);
Asset::get()->add(prefix + "/data/config/demo2.bin", AssetType::DATA); Asset::get()->add(prefix + "/data/config/demo2.bin", AssetType::DEMODATA);
Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", AssetType::DATA); Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", AssetType::DATA);
// Musicas // Musicas

View File

@@ -1,14 +1,16 @@
#include "resource.h" #include "resource.h"
#include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError #include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError
#include <algorithm> // Para find_if #include <SDL3/SDL.h>
#include <stdexcept> // Para runtime_error #include <algorithm> // Para find_if
#include "asset.h" // Para Asset, AssetType #include <array>
#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic #include <stdexcept> // Para runtime_error
#include "lang.h" // Para getText #include "asset.h" // Para Asset, AssetType
#include "screen.h" // Para Screen #include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic
#include "text.h" // Para Text, loadTextFile #include "lang.h" // Para getText
struct JA_Music_t; // lines 11-11 #include "screen.h" // Para Screen
struct JA_Sound_t; // lines 12-12 #include "text.h" // Para Text, loadTextFile
struct JA_Music_t; // lines 11-11
struct JA_Sound_t; // lines 12-12
// Singleton // Singleton
Resource *Resource::instance_ = nullptr; Resource *Resource::instance_ = nullptr;
@@ -23,7 +25,7 @@ void Resource::destroy() { delete Resource::instance_; }
Resource *Resource::get() { return Resource::instance_; } Resource *Resource::get() { return Resource::instance_; }
// Constructor // Constructor
Resource::Resource() { load(); } Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
// Vacia todos los vectores de recursos // Vacia todos los vectores de recursos
void Resource::clear() void Resource::clear()
@@ -37,30 +39,43 @@ void Resource::clear()
demos_.clear(); demos_.clear();
} }
// Carga todos los recursos // Carga todos los recursos del juego y muestra el progreso de carga
void Resource::load() void Resource::load()
{ {
// Calcula el total de recursos a cargar
calculateTotal();
// Muerstra la ventana y desactiva el sincronismo vertical
auto screen = Screen::get();
auto vsync = screen->getVSync();
screen->show();
screen->setVSync(false);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** LOADING RESOURCES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** LOADING RESOURCES");
loadSounds(); loadSounds(); // Carga sonidos
loadMusics(); loadMusics(); // Carga músicas
loadTextures(); loadTextures(); // Carga texturas
loadTextFiles(); loadTextFiles(); // Carga ficheros de texto
loadAnimations(); loadAnimations(); // Carga animaciones
loadDemoData(); loadDemoData(); // Carga datos de demo
addPalettes(); addPalettes(); // Añade paletas a las texturas
createText(); createText(); // Crea objetos de texto
createTextures(); createTextures(); // Crea texturas a partir de texto
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** RESOURCES LOADED"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** RESOURCES LOADED");
// Restablece el sincronismo vertical a su valor original
screen->setVSync(vsync);
SDL_Delay(1000);
} }
// Recarga todos los recursos // Recarga todos los recursos (limpia y vuelve a cargar)
void Resource::reload() void Resource::reload()
{ {
clear(); clear();
load(); load();
} }
// Recarga las texturas // Recarga solo las texturas y paletas
void Resource::reloadTextures() void Resource::reloadTextures()
{ {
loadTextures(); loadTextures();
@@ -68,7 +83,7 @@ void Resource::reloadTextures()
createTextures(); createTextures();
} }
// Obtiene el sonido a partir de un nombre // Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
JA_Sound_t *Resource::getSound(const std::string &name) JA_Sound_t *Resource::getSound(const std::string &name)
{ {
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s)
@@ -83,7 +98,7 @@ JA_Sound_t *Resource::getSound(const std::string &name)
throw std::runtime_error("Sonido no encontrado: " + name); throw std::runtime_error("Sonido no encontrado: " + name);
} }
// Obtiene la música a partir de un nombre // Obtiene la música a partir de un nombre. Lanza excepción si no existe.
JA_Music_t *Resource::getMusic(const std::string &name) JA_Music_t *Resource::getMusic(const std::string &name)
{ {
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m)
@@ -98,7 +113,7 @@ JA_Music_t *Resource::getMusic(const std::string &name)
throw std::runtime_error("Música no encontrada: " + name); throw std::runtime_error("Música no encontrada: " + name);
} }
// Obtiene la textura a partir de un nombre // Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Texture> Resource::getTexture(const std::string &name) std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
{ {
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t)
@@ -113,7 +128,7 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
throw std::runtime_error("Imagen no encontrada: " + name); throw std::runtime_error("Imagen no encontrada: " + name);
} }
// Obtiene el fichero de texto a partir de un nombre // Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
{ {
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t)
@@ -128,7 +143,7 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
throw std::runtime_error("TextFile no encontrado: " + name); throw std::runtime_error("TextFile no encontrado: " + name);
} }
// Obtiene el objeto de texto a partir de un nombre // Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Text> Resource::getText(const std::string &name) std::shared_ptr<Text> Resource::getText(const std::string &name)
{ {
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t)
@@ -143,7 +158,7 @@ std::shared_ptr<Text> Resource::getText(const std::string &name)
throw std::runtime_error("Text no encontrado: " + name); throw std::runtime_error("Text no encontrado: " + name);
} }
// Obtiene la animación a partir de un nombre // Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
AnimationsFileBuffer &Resource::getAnimation(const std::string &name) AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
{ {
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a)
@@ -158,13 +173,13 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
throw std::runtime_error("Animación no encontrada: " + name); throw std::runtime_error("Animación no encontrada: " + name);
} }
// Obtiene el fichero con los datos para el modo demostración a partir de un çindice // Obtiene el fichero con los datos para el modo demostración a partir de un índice
DemoData &Resource::getDemoData(int index) DemoData &Resource::getDemoData(int index)
{ {
return demos_.at(index); return demos_.at(index);
} }
// Carga los sonidos // Carga los sonidos del juego
void Resource::loadSounds() void Resource::loadSounds()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> SOUND FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> SOUND FILES");
@@ -174,12 +189,13 @@ void Resource::loadSounds()
for (const auto &l : list) for (const auto &l : list)
{ {
auto name = getFileName(l); auto name = getFileName(l);
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str()))); sounds_.emplace_back(Resource::ResourceSound(name, JA_LoadSound(l.c_str())));
printWithDots("Sound : ", name, "[ LOADED ]"); printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress(name);
} }
} }
// Carga las músicas // Carga las músicas del juego
void Resource::loadMusics() void Resource::loadMusics()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> MUSIC FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> MUSIC FILES");
@@ -189,12 +205,13 @@ void Resource::loadMusics()
for (const auto &l : list) for (const auto &l : list)
{ {
auto name = getFileName(l); auto name = getFileName(l);
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str()))); musics_.emplace_back(Resource::ResourceMusic(name, JA_LoadMusic(l.c_str())));
printWithDots("Music : ", name, "[ LOADED ]"); printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress(name);
} }
} }
// Carga las texturas // Carga las texturas del juego
void Resource::loadTextures() void Resource::loadTextures()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXTURES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXTURES");
@@ -204,11 +221,12 @@ void Resource::loadTextures()
for (const auto &l : list) for (const auto &l : list)
{ {
auto name = getFileName(l); auto name = getFileName(l);
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l))); textures_.emplace_back(Resource::ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
updateLoadingProgress(name);
} }
} }
// Carga los ficheros de texto // Carga los ficheros de texto del juego
void Resource::loadTextFiles() void Resource::loadTextFiles()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXT FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXT FILES");
@@ -218,11 +236,12 @@ void Resource::loadTextFiles()
for (const auto &l : list) for (const auto &l : list)
{ {
auto name = getFileName(l); auto name = getFileName(l);
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l))); text_files_.emplace_back(Resource::ResourceTextFile(name, loadTextFile(l)));
updateLoadingProgress(name);
} }
} }
// Carga las animaciones // Carga las animaciones del juego
void Resource::loadAnimations() void Resource::loadAnimations()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> ANIMATIONS"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> ANIMATIONS");
@@ -232,7 +251,8 @@ void Resource::loadAnimations()
for (const auto &l : list) for (const auto &l : list)
{ {
auto name = getFileName(l); auto name = getFileName(l);
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); animations_.emplace_back(Resource::ResourceAnimation(name, loadAnimationsFromFile(l)));
updateLoadingProgress(name);
} }
} }
@@ -240,30 +260,36 @@ void Resource::loadAnimations()
void Resource::loadDemoData() void Resource::loadDemoData()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES");
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo1.bin")));
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo2.bin"))); constexpr std::array<const char *, 2> demo_files = {"demo1.bin", "demo2.bin"};
for (const auto &file : demo_files)
{
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get(file)));
updateLoadingProgress(file);
}
} }
// Añade paletas a las texturas // Añade paletas de colores a las texturas principales
void Resource::addPalettes() void Resource::addPalettes()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> PALETTES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> PALETTES");
// Jugador 1 // Paletas para el jugador 1
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif"));
// Jugador 2 // Paletas para el jugador 2
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_1_coffee_palette.gif")); getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_1_coffee_palette.gif"));
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_2_coffee_palette.gif")); getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_2_coffee_palette.gif"));
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_invencible_palette.gif")); getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_invencible_palette.gif"));
// Fuentes // Paleta para la fuente SMB2
getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal")); getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal"));
} }
// Crea texturas // Crea texturas a partir de textos para mostrar puntuaciones y mensajes
void Resource::createTextures() void Resource::createTextures()
{ {
struct NameAndText struct NameAndText
@@ -277,7 +303,7 @@ void Resource::createTextures()
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
// Tamaño normal // Texturas de tamaño normal
std::vector<NameAndText> strings = { std::vector<NameAndText> strings = {
{"game_text_1000_points", "1.000"}, {"game_text_1000_points", "1.000"},
{"game_text_2500_points", "2.500"}, {"game_text_2500_points", "2.500"},
@@ -290,11 +316,11 @@ void Resource::createTextures()
auto text = getText("04b_25"); auto text = getText("04b_25");
for (const auto &s : strings) for (const auto &s : strings)
{ {
textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2))); textures_.emplace_back(Resource::ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
printWithDots("Texture : ", s.name, "[ DONE ]"); printWithDots("Texture : ", s.name, "[ DONE ]");
} }
// Tamaño doble // Texturas de tamaño doble
std::vector<NameAndText> strings2X = { std::vector<NameAndText> strings2X = {
{"game_text_100000_points", "100.000"}, {"game_text_100000_points", "100.000"},
{"game_text_get_ready", lang::getText("[GAME_TEXT] 7")}, {"game_text_get_ready", lang::getText("[GAME_TEXT] 7")},
@@ -305,11 +331,12 @@ void Resource::createTextures()
auto text2 = getText("04b_25_2x"); auto text2 = getText("04b_25_2x");
for (const auto &s : strings2X) for (const auto &s : strings2X)
{ {
textures_.emplace_back(ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4))); textures_.emplace_back(Resource::ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4)));
printWithDots("Texture : ", s.name, "[ DONE ]"); printWithDots("Texture : ", s.name, "[ DONE ]");
} }
} }
// Crea los objetos de texto a partir de los archivos de textura y texto
void Resource::createText() void Resource::createText()
{ {
struct ResourceInfo struct ResourceInfo
@@ -339,14 +366,14 @@ void Resource::createText()
for (const auto &resource : resources) for (const auto &resource : resources)
{ {
texts_.emplace_back(ResourceText(resource.key, std::make_shared<Text>( texts_.emplace_back(Resource::ResourceText(resource.key, std::make_shared<Text>(
getTexture(resource.textureFile), getTexture(resource.textureFile),
getTextFile(resource.textFile)))); getTextFile(resource.textFile))));
printWithDots("Text : ", resource.key, "[ DONE ]"); printWithDots("Text : ", resource.key, "[ DONE ]");
} }
} }
// Vacía el vector de sonidos // Vacía el vector de sonidos y libera la memoria asociada
void Resource::clearSounds() void Resource::clearSounds()
{ {
for (auto &sound : sounds_) for (auto &sound : sounds_)
@@ -360,7 +387,7 @@ void Resource::clearSounds()
sounds_.clear(); sounds_.clear();
} }
// Vacía el vector de músicas // Vacía el vector de músicas y libera la memoria asociada
void Resource::clearMusics() void Resource::clearMusics()
{ {
for (auto &music : musics_) for (auto &music : musics_)
@@ -372,4 +399,87 @@ void Resource::clearMusics()
} }
} }
musics_.clear(); musics_.clear();
}
// Calcula el número total de recursos a cargar y reinicia el contador de carga
void Resource::calculateTotal()
{
const std::array<AssetType, 6> ASSET_TYPES = {
AssetType::SOUND,
AssetType::MUSIC,
AssetType::BITMAP,
AssetType::FONT,
AssetType::ANIMATION,
AssetType::DEMODATA};
size_t total = 0;
for (const auto &asset_type : ASSET_TYPES)
{
auto list = Asset::get()->getListByType(asset_type);
total += list.size();
std::string log = std::to_string(list.size()) + " - " + std::to_string(total);
SDL_Log("%s", log.c_str());
}
loading_count_ = ResourceCount(total);
}
// Muestra el progreso de carga en pantalla (barra y texto)
void Resource::renderProgress()
{
auto screen = Screen::get();
auto renderer = screen->getRenderer();
screen->update();
constexpr float X_PADDING = 10.0f;
constexpr float Y_PADDING = 10.0f;
constexpr float BAR_HEIGHT = 10.0f;
const float BAR_Y_POSITION = param.game.height - BAR_HEIGHT - Y_PADDING;
screen->start();
screen->clean();
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
const float wired_bar_width = param.game.width - (X_PADDING * 2);
SDL_FRect rect_wired = {X_PADDING, BAR_Y_POSITION, wired_bar_width, X_PADDING};
SDL_RenderRect(renderer, &rect_wired);
const float full_bar_width = wired_bar_width * loading_count_.getPercentage();
SDL_FRect rect_full = {X_PADDING, BAR_Y_POSITION, full_bar_width, X_PADDING};
SDL_RenderFillRect(renderer, &rect_full);
loading_text_->write(X_PADDING, BAR_Y_POSITION - 9, "Loading : " + loading_resource_name_);
screen->render();
}
// Comprueba los eventos durante la carga (permite salir con ESC o cerrar ventana)
void Resource::checkEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_EVENT_QUIT:
exit(0);
break;
case SDL_EVENT_KEY_DOWN:
if (event.key.key == SDLK_ESCAPE)
{
exit(0);
}
break;
}
}
}
// Actualiza el progreso de carga, muestra la barra y procesa eventos
void Resource::updateLoadingProgress(std::string name)
{
loading_resource_name_ = name;
loading_count_.add(1);
renderProgress();
checkEvents();
} }

View File

@@ -1,77 +1,13 @@
#pragma once #pragma once
#include <memory> // Para shared_ptr #include <memory>
#include <string> // Para string #include <string>
#include <vector> // Para vector #include <vector>
#include "animated_sprite.h" // Para AnimationsFileBuffer #include "animated_sprite.h"
#include "text.h" // Para TextFile, Text #include "text.h"
#include "texture.h" // Para Texture #include "texture.h"
#include "utils.h" // Para DemoData #include "utils.h"
#include "jail_audio.h"
struct JA_Music_t;
struct JA_Sound_t;
// --- Estructuras para recursos individuales ---
// Sonido
struct ResourceSound
{
std::string name; // Nombre del sonido
JA_Sound_t *sound; // Objeto con el sonido
ResourceSound(const std::string &name, JA_Sound_t *sound)
: name(name), sound(sound) {}
};
// Música
struct ResourceMusic
{
std::string name; // Nombre de la música
JA_Music_t *music; // Objeto con la música
ResourceMusic(const std::string &name, JA_Music_t *music)
: name(name), music(music) {}
};
// Textura
struct ResourceTexture
{
std::string name; // Nombre de la textura
std::shared_ptr<Texture> texture; // Objeto con la textura
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
: name(name), texture(texture) {}
};
// Fichero de texto (fuente)
struct ResourceTextFile
{
std::string name; // Nombre del fichero
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
: name(name), text_file(text_file) {}
};
// Objeto de texto
struct ResourceText
{
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto
ResourceText(const std::string &name, std::shared_ptr<Text> text)
: name(name), text(text) {}
};
// Animación
struct ResourceAnimation
{
std::string name; // Nombre del fichero
AnimationsFileBuffer animation; // Objeto con las animaciones
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
: name(name), animation(animation) {}
};
// --- Clase Resource: gestiona todos los recursos del juego (singleton) --- // --- Clase Resource: gestiona todos los recursos del juego (singleton) ---
class Resource class Resource
@@ -91,13 +27,84 @@ public:
AnimationsFileBuffer &getAnimation(const std::string &name); // Obtiene la animación por nombre AnimationsFileBuffer &getAnimation(const std::string &name); // Obtiene la animación por nombre
DemoData &getDemoData(int index); // Obtiene los datos de demo por índice DemoData &getDemoData(int index); // Obtiene los datos de demo por índice
// --- Recarga de recursos --- // --- Métodos de recarga de recursos ---
void reload(); // Recarga todos los recursos void reload(); // Recarga todos los recursos
void reloadTextures(); // Recarga solo las texturas void reloadTextures(); // Recarga solo las texturas
private: private:
// --- Singleton --- // --- Estructuras para recursos individuales ---
static Resource *instance_; struct ResourceSound
{
std::string name; // Nombre del sonido
JA_Sound_t *sound; // Objeto con el sonido
ResourceSound(const std::string &name, JA_Sound_t *sound)
: name(name), sound(sound) {}
};
struct ResourceMusic
{
std::string name; // Nombre de la música
JA_Music_t *music; // Objeto con la música
ResourceMusic(const std::string &name, JA_Music_t *music)
: name(name), music(music) {}
};
struct ResourceTexture
{
std::string name; // Nombre de la textura
std::shared_ptr<Texture> texture; // Objeto con la textura
ResourceTexture(const std::string &name, std::shared_ptr<Texture> texture)
: name(name), texture(texture) {}
};
struct ResourceTextFile
{
std::string name; // Nombre del fichero
std::shared_ptr<TextFile> text_file; // Objeto con los descriptores de la fuente de texto
ResourceTextFile(const std::string &name, std::shared_ptr<TextFile> text_file)
: name(name), text_file(text_file) {}
};
struct ResourceText
{
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto de texto
ResourceText(const std::string &name, std::shared_ptr<Text> text)
: name(name), text(text) {}
};
struct ResourceAnimation
{
std::string name; // Nombre de la animación
AnimationsFileBuffer animation; // Objeto con las animaciones
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
: name(name), animation(animation) {}
};
// --- Estructura para el progreso de carga ---
struct ResourceCount
{
size_t total; // Número total de recursos
size_t loaded; // Número de recursos cargados
ResourceCount() : total(0), loaded(0) {}
ResourceCount(size_t total) : total(total), loaded(0) {}
void add(size_t amount) { loaded += amount; }
float getPercentage() const
{
return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0f;
}
};
// --- Instancia singleton ---
static Resource *instance_; // Instancia única de Resource
// --- Vectores de recursos --- // --- Vectores de recursos ---
std::vector<ResourceSound> sounds_; // Vector con los sonidos std::vector<ResourceSound> sounds_; // Vector con los sonidos
@@ -108,6 +115,11 @@ private:
std::vector<ResourceAnimation> animations_; // Vector con las animaciones std::vector<ResourceAnimation> animations_; // Vector con las animaciones
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
// --- Progreso de carga ---
ResourceCount loading_count_; // Contador de recursos cargados
std::shared_ptr<Text> loading_text_; // Texto para escribir en pantalla
std::string loading_resource_name_; // Nombre del recurso que se está cargando
// --- Métodos internos de carga y gestión --- // --- Métodos internos de carga y gestión ---
void loadSounds(); // Carga los sonidos void loadSounds(); // Carga los sonidos
void loadMusics(); // Carga las músicas void loadMusics(); // Carga las músicas
@@ -123,6 +135,12 @@ private:
void clearSounds(); // Vacía el vector de sonidos void clearSounds(); // Vacía el vector de sonidos
void clearMusics(); // Vacía el vector de músicas void clearMusics(); // Vacía el vector de músicas
// --- Métodos internos para gestionar el progreso ---
void calculateTotal(); // Calcula el número de recursos para cargar
void renderProgress(); // Muestra el progreso de carga
void checkEvents(); // Comprueba los eventos durante la carga
void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
// --- Constructores y destructor privados (singleton) --- // --- Constructores y destructor privados (singleton) ---
Resource(); // Constructor privado Resource(); // Constructor privado
~Resource() = default; // Destructor privado ~Resource() = default; // Destructor privado

View File

@@ -35,7 +35,12 @@ Screen *Screen::get() { return Screen::instance_; }
// Constructor // Constructor
Screen::Screen() Screen::Screen()
: src_rect_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}), : window_(nullptr),
renderer_(nullptr),
game_canvas_(nullptr),
service_menu_(nullptr),
notifier_(nullptr),
src_rect_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
dst_rect_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}) dst_rect_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)})
{ {
// Arranca SDL VIDEO, crea la ventana y el renderizador // Arranca SDL VIDEO, crea la ventana y el renderizador
@@ -48,18 +53,22 @@ Screen::Screen()
// Inicializa variables // Inicializa variables
adjustRenderLogicalSize(); adjustRenderLogicalSize();
// Muestra la ventana
show();
// Inicializa los shaders // Inicializa los shaders
initShaders(); // Se ha de ejecutar con la ventana visible initShaders();
// Crea el objeto de texto
createText();
#ifdef DEBUG
debug_info_.text = text_;
setDebugInfoEnabled(true);
#endif
} }
// Destructor // Destructor
Screen::~Screen() Screen::~Screen()
{ {
SDL_DestroyTexture(game_canvas_); SDL_DestroyTexture(game_canvas_);
SDL_DestroyRenderer(renderer_); SDL_DestroyRenderer(renderer_);
SDL_DestroyWindow(window_); SDL_DestroyWindow(window_);
} }
@@ -173,8 +182,10 @@ void Screen::update()
fps_.calculate(SDL_GetTicks()); fps_.calculate(SDL_GetTicks());
shake_effect_.update(src_rect_, dst_rect_); shake_effect_.update(src_rect_, dst_rect_);
flash_effect_.update(); flash_effect_.update();
serviceMenu_->update(); if (service_menu_)
notifier_->update(); service_menu_->update();
if (notifier_)
notifier_->update();
Mouse::updateCursorVisibility(); Mouse::updateCursorVisibility();
} }
@@ -232,18 +243,19 @@ void Screen::renderInfo()
// Carga el contenido del archivo GLSL // Carga el contenido del archivo GLSL
void Screen::loadShaders() void Screen::loadShaders()
{ {
const std::string GLSL_FILE = param.game.game_area.rect.h == 256 ? "crtpi_256.glsl" : "crtpi_240.glsl"; if (shader_source_.empty())
std::ifstream f(Asset::get()->get(GLSL_FILE).c_str()); {
shader_source_ = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); const std::string GLSL_FILE = param.game.game_area.rect.h == 256 ? "crtpi_256.glsl" : "crtpi_240.glsl";
std::ifstream f(Asset::get()->get(GLSL_FILE).c_str());
shader_source_ = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
}
} }
// Inicializa los shaders // Inicializa los shaders
void Screen::initShaders() void Screen::initShaders()
{ {
if (shader_source_.empty()) show(); // Se ha de ejecutar con la ventana visible
{ loadShaders();
loadShaders();
}
shader::init(window_, game_canvas_, shader_source_); shader::init(window_, game_canvas_, shader_source_);
} }
@@ -279,8 +291,10 @@ void Screen::renderOverlays()
renderShake(); renderShake();
renderFlash(); renderFlash();
renderAttenuate(); renderAttenuate();
serviceMenu_->render(); if (service_menu_)
notifier_->render(); service_menu_->render();
if (notifier_)
notifier_->render();
#ifdef DEBUG #ifdef DEBUG
renderInfo(); renderInfo();
#endif #endif
@@ -392,24 +406,31 @@ void Screen::getDisplayInfo()
} }
} }
// Activa / desactiva el escalado entero // Alterna entre activar y desactivar el escalado entero
void Screen::toggleIntegerScale() void Screen::toggleIntegerScale()
{ {
options.video.integer_scale = !options.video.integer_scale; options.video.integer_scale = !options.video.integer_scale;
SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX); SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
} }
// Activa / desactiva el vsync // Alterna entre activar y desactivar el V-Sync
void Screen::toggleVSync() void Screen::toggleVSync()
{ {
options.video.v_sync = !options.video.v_sync; options.video.v_sync = !options.video.v_sync;
SDL_SetRenderVSync(renderer_, options.video.v_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED); SDL_SetRenderVSync(renderer_, options.video.v_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED);
} }
// Establece el estado del V-Sync
void Screen::setVSync(bool enabled)
{
options.video.v_sync = enabled;
SDL_SetRenderVSync(renderer_, enabled ? 1 : SDL_RENDERER_VSYNC_DISABLED);
}
// Obtiene los punteros a los singletones // Obtiene los punteros a los singletones
void Screen::getSingletons() void Screen::getSingletons()
{ {
serviceMenu_ = ServiceMenu::get(); service_menu_ = ServiceMenu::get();
notifier_ = Notifier::get(); notifier_ = Notifier::get();
} }
@@ -420,4 +441,11 @@ void Screen::applySettings()
SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX); SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
adjustWindowSize(); adjustWindowSize();
setFullscreenMode(); setFullscreenMode();
}
// Crea el objeto de texto
void Screen::createText()
{
auto texture = std::make_shared<Texture>(getRenderer(), Asset::get()->get("aseprite.png"));
text_ = std::make_unique<Text>(texture, Asset::get()->get("aseprite.txt"));
} }

View File

@@ -10,11 +10,7 @@
#include "options.h" // Para Options, VideoOptions, options #include "options.h" // Para Options, VideoOptions, options
#include "param.h" // Para Param, ParamGame, param #include "param.h" // Para Param, ParamGame, param
#include "utils.h" // Para Color #include "utils.h" // Para Color
#ifdef DEBUG
#include "text.h" #include "text.h"
#include "resource.h"
#endif
class Notifier; class Notifier;
class ServiceMenu; class ServiceMenu;
@@ -45,22 +41,24 @@ public:
// --- Efectos visuales --- // --- Efectos visuales ---
void shake() { shake_effect_.enable(src_rect_, dst_rect_); } // Agita la pantalla void shake() { shake_effect_.enable(src_rect_, dst_rect_); } // Agita la pantalla
void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); } // Pone la pantalla de color void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); } // Pone la pantalla de color
void toggleShaders() { options.video.shaders = !options.video.shaders; } // Activa/desactiva los shaders void toggleShaders() { options.video.shaders = !options.video.shaders; } // Alterna entre activar y desactivar los shaders
void toggleIntegerScale(); // Activa/desactiva el escalado entero void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
void toggleVSync(); // Activa/desactiva el vsync void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
void setVSync(bool enabled); // Establece el estado del V-Sync
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
// --- Getters --- // --- Getters ---
SDL_Renderer *getRenderer() { return renderer_; } // Obtiene el renderizador SDL_Renderer *getRenderer() { return renderer_; } // Obtiene el renderizador
void show() { SDL_ShowWindow(window_); } // Muestra la ventana void show() { SDL_ShowWindow(window_); } // Muestra la ventana
void hide() { SDL_HideWindow(window_); } // Oculta la ventana void hide() { SDL_HideWindow(window_); } // Oculta la ventana
void getSingletons(); // Obtiene los punteros a los singletones void getSingletons(); // Obtiene los punteros a los singletones
bool getVSync() const { return options.video.v_sync; } // Obtiene el valor de V-Sync
std::shared_ptr<Text> getText() const { return text_; } // Obtiene el puntero al texto de Screen
#ifdef DEBUG #ifdef DEBUG
// --- Debug --- // --- Debug ---
void toggleDebugInfo() { debug_info_.show = !debug_info_.show; } void toggleDebugInfo() { debug_info_.show = !debug_info_.show; }
void setDebugInfoEnabled(bool value) { debug_info_.show = value; } void setDebugInfoEnabled(bool value) { debug_info_.show = value; }
void initDebugInfo() { debug_info_.init(); }
#endif #endif
private: private:
@@ -165,32 +163,21 @@ private:
#ifdef DEBUG #ifdef DEBUG
struct Debug struct Debug
{ {
std::shared_ptr<Text> text = nullptr; std::shared_ptr<Text> text;
bool show = false; bool show = false;
void init()
{
if (Resource::get())
{
text = Resource::get()->getText("aseprite");
if (!text)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to retrieve debug_.text object!");
return;
}
}
}
}; };
#endif #endif
// --- Singleton --- // --- Singleton ---
static Screen *instance_; static Screen *instance_;
// --- Objetos y punteros --- // --- Objetos y punteros ---
SDL_Window *window_; // Ventana de la aplicación SDL_Window *window_; // Ventana de la aplicación
SDL_Renderer *renderer_; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
ServiceMenu *serviceMenu_; // Objeto para mostrar el menú de servicio ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio
Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla
// --- Variables de estado --- // --- Variables de estado ---
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
@@ -204,6 +191,9 @@ private:
Debug debug_info_; // Información de debug Debug debug_info_; // Información de debug
#endif #endif
// --- Texto ---
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
// --- Métodos internos --- // --- Métodos internos ---
bool initSDL(); // Arranca SDL VIDEO y crea la ventana bool initSDL(); // Arranca SDL VIDEO y crea la ventana
void renderFlash(); // Dibuja el efecto de flash en la pantalla void renderFlash(); // Dibuja el efecto de flash en la pantalla
@@ -217,6 +207,7 @@ private:
void getDisplayInfo(); // Obtiene información sobre la pantalla void getDisplayInfo(); // Obtiene información sobre la pantalla
void renderOverlays(); // Renderiza todos los overlays y efectos void renderOverlays(); // Renderiza todos los overlays y efectos
void renderAttenuate(); // Atenúa la pantalla void renderAttenuate(); // Atenúa la pantalla
void createText(); // Crea el objeto de texto
// --- Constructores y destructor --- // --- Constructores y destructor ---
Screen(); Screen();