Compare commits

...

4 Commits

19 changed files with 863 additions and 442 deletions

View File

@@ -197,9 +197,9 @@ void AnimatedSprite::processConfigLine(const std::string& line, AnimationConfig&
// Actualiza los cálculos basados en las dimensiones del frame // Actualiza los cálculos basados en las dimensiones del frame
void AnimatedSprite::updateFrameCalculations(AnimationConfig& config) { void AnimatedSprite::updateFrameCalculations(AnimationConfig& config) {
config.frames_per_row = texture_->getWidth() / config.frame_width; config.frames_per_row = getTexture()->getWidth() / config.frame_width;
const int WIDTH = texture_->getWidth() / config.frame_width; const int WIDTH = getTexture()->getWidth() / config.frame_width;
const int HEIGHT = texture_->getHeight() / config.frame_height; const int HEIGHT = getTexture()->getHeight() / config.frame_height;
config.max_tiles = WIDTH * HEIGHT; config.max_tiles = WIDTH * HEIGHT;
} }

View File

@@ -1,10 +1,11 @@
#include "asset.h" #include "asset.h"
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <fstream>
#include <sstream>
#include <algorithm> #include <algorithm>
#include <filesystem> #include <filesystem>
#include <fstream>
#include <sstream>
#include "utils.h" #include "utils.h"
@@ -31,7 +32,8 @@ void Asset::addToMap(const std::string &file_path, Type type, bool required, boo
// Verificar si ya existe el archivo // Verificar si ya existe el archivo
if (file_list_.find(filename) != file_list_.end()) { if (file_list_.find(filename) != file_list_.end()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset '%s' already exists, overwriting", filename.c_str()); "Warning: Asset '%s' already exists, overwriting",
filename.c_str());
} }
file_list_.emplace(filename, Item{std::move(full_path), type, required}); file_list_.emplace(filename, Item{std::move(full_path), type, required});
@@ -48,7 +50,8 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string
std::ifstream file(config_file_path); std::ifstream file(config_file_path);
if (!file.is_open()) { if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error: Cannot open config file: %s", config_file_path.c_str()); "Error: Cannot open config file: %s",
config_file_path.c_str());
return; return;
} }
@@ -82,7 +85,8 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string
// Verificar que tenemos al menos tipo y ruta // Verificar que tenemos al menos tipo y ruta
if (parts.size() < 2) { if (parts.size() < 2) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Malformed line %d in config file (insufficient fields)", line_number); "Warning: Malformed line %d in config file (insufficient fields)",
line_number);
continue; continue;
} }
@@ -110,12 +114,15 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string
} catch (const std::exception &e) { } catch (const std::exception &e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error parsing line %d in config file: %s", line_number, e.what()); "Error parsing line %d in config file: %s",
line_number,
e.what());
} }
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Loaded %d assets from config file", static_cast<int>(file_list_.size())); "Loaded %d assets from config file",
static_cast<int>(file_list_.size()));
file.close(); file.close();
} }
@@ -157,7 +164,8 @@ auto Asset::check() const -> bool {
if (by_type.find(asset_type) != by_type.end()) { if (by_type.find(asset_type) != by_type.end()) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"\n>> %s FILES", getTypeName(asset_type).c_str()); "\n>> %s FILES",
getTypeName(asset_type).c_str());
bool type_success = true; bool type_success = true;
for (const auto *item : by_type[asset_type]) { for (const auto *item : by_type[asset_type]) {
@@ -191,7 +199,8 @@ auto Asset::checkFile(const std::string &path) -> bool {
if (!success) { if (!success) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Checking file: %s [ ERROR ]", getFileName(path).c_str()); "Checking file: %s [ ERROR ]",
getFileName(path).c_str());
} }
return success; return success;
@@ -233,16 +242,26 @@ auto Asset::parseAssetType(const std::string &type_str) -> Type {
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
auto Asset::getTypeName(Type type) -> std::string { auto Asset::getTypeName(Type type) -> std::string {
switch (type) { switch (type) {
case Type::BITMAP: return "BITMAP"; case Type::BITMAP:
case Type::MUSIC: return "MUSIC"; return "BITMAP";
case Type::SOUND: return "SOUND"; case Type::MUSIC:
case Type::FONT: return "FONT"; return "MUSIC";
case Type::LANG: return "LANG"; case Type::SOUND:
case Type::DATA: return "DATA"; return "SOUND";
case Type::DEMODATA: return "DEMODATA"; case Type::FONT:
case Type::ANIMATION: return "ANIMATION"; return "FONT";
case Type::PALETTE: return "PALETTE"; case Type::LANG:
default: return "ERROR"; return "LANG";
case Type::DATA:
return "DATA";
case Type::DEMODATA:
return "DEMODATA";
case Type::ANIMATION:
return "ANIMATION";
case Type::PALETTE:
return "PALETTE";
default:
return "ERROR";
} }
} }

View File

@@ -2,8 +2,8 @@
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <vector>
#include <utility> #include <utility>
#include <vector>
// Clase Asset: gestor optimizado de recursos (singleton) // Clase Asset: gestor optimizado de recursos (singleton)
class Asset { class Asset {

View File

@@ -46,7 +46,7 @@ Director::Director(int argc, std::span<char *> argv) {
Section::name = Section::Name::GAME; Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P; Section::options = Section::Options::GAME_PLAY_1P;
#elif _DEBUG #elif _DEBUG
Section::name = Section::Name::TITLE; Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P; Section::options = Section::Options::GAME_PLAY_1P;
#else // NORMAL GAME #else // NORMAL GAME
Section::name = Section::Name::LOGO; Section::name = Section::Name::LOGO;
@@ -98,9 +98,11 @@ void Director::init() {
Lang::setLanguage(Options::settings.language); // Carga el archivo de idioma Lang::setLanguage(Options::settings.language); // Carga el archivo de idioma
Screen::init(); // Inicializa la pantalla y el sistema de renderizado Screen::init(); // Inicializa la pantalla y el sistema de renderizado
Audio::init(); // Activa el sistema de audio Audio::init(); // Activa el sistema de audio
Resource::init(); // Inicializa el sistema de gestión de recursos #ifdef _DEBUG
// bindInputs(); // Asigna los controles a la entrada del sistema Resource::init(Resource::LoadingMode::PRELOAD); // Inicializa el sistema de gestión de recursos
#else
Resource::init(Resource::LoadingMode::PRELOAD); // Inicializa el sistema de gestión de recursos
#endif
ServiceMenu::init(); // Inicializa el menú de servicio ServiceMenu::init(); // Inicializa el menú de servicio
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

View File

@@ -72,7 +72,7 @@ void MovingSprite::update() {
} }
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void MovingSprite::render() { texture_->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_); } void MovingSprite::render() { getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_); }
// Establece la rotacion // Establece la rotacion
void MovingSprite::rotate() { void MovingSprite::rotate() {

View File

@@ -22,7 +22,7 @@
// Constructor // Constructor
Player::Player(const Config &config) Player::Player(const Config &config)
: player_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(0), config.animations.at(0))), : player_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(0), config.animations.at(0))),
power_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(1), config.animations.at(1))), power_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(4), config.animations.at(1))),
enter_name_(std::make_unique<EnterName>()), enter_name_(std::make_unique<EnterName>()),
hi_score_table_(*config.hi_score_table), hi_score_table_(*config.hi_score_table),
glowing_entry_(*config.glowing_entry), glowing_entry_(*config.glowing_entry),
@@ -32,7 +32,10 @@ Player::Player(const Config &config)
default_pos_y_(config.y), default_pos_y_(config.y),
demo_(config.demo) { demo_(config.demo) {
// Configura objetos // Configura objetos
player_sprite_->getTexture()->setPalette(coffees_); player_sprite_->addTexture(config.texture.at(1));
player_sprite_->addTexture(config.texture.at(2));
player_sprite_->addTexture(config.texture.at(3));
player_sprite_->setActiveTexture(coffees_);
power_sprite_->getTexture()->setAlpha(224); power_sprite_->getTexture()->setAlpha(224);
power_up_x_offset_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2; power_up_x_offset_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2;
power_sprite_->setPosY(default_pos_y_ - (power_sprite_->getHeight() - player_sprite_->getHeight())); power_sprite_->setPosY(default_pos_y_ - (power_sprite_->getHeight() - player_sprite_->getHeight()));
@@ -460,26 +463,21 @@ void Player::setAnimation() {
player_sprite_->setFlip(flipMode); player_sprite_->setFlip(flipMode);
break; break;
} }
case State::WAITING: case State::WAITING:
player_sprite_->setCurrentAnimation("hello"); player_sprite_->setCurrentAnimation("hello");
break; break;
case State::ROLLING: case State::ROLLING:
case State::CONTINUE_TIME_OUT: case State::CONTINUE_TIME_OUT:
player_sprite_->setCurrentAnimation("rolling"); player_sprite_->setCurrentAnimation("rolling");
break; break;
case State::LYING_ON_THE_FLOOR_FOREVER: case State::LYING_ON_THE_FLOOR_FOREVER:
case State::ENTERING_NAME: case State::ENTERING_NAME:
case State::CONTINUE: case State::CONTINUE:
player_sprite_->setCurrentAnimation("dead"); player_sprite_->setCurrentAnimation("dead");
break; break;
case State::CELEBRATING: case State::CELEBRATING:
player_sprite_->setCurrentAnimation("celebration"); player_sprite_->setCurrentAnimation("celebration");
break; break;
default: default:
break; break;
} }
@@ -782,10 +780,10 @@ void Player::updateInvulnerable() {
if (invulnerable_) { if (invulnerable_) {
if (invulnerable_counter_ > 0) { if (invulnerable_counter_ > 0) {
--invulnerable_counter_; --invulnerable_counter_;
invulnerable_counter_ % 8 > 3 ? player_sprite_->getTexture()->setPalette(coffees_) : player_sprite_->getTexture()->setPalette(3); invulnerable_counter_ % 8 > 3 ? player_sprite_->setActiveTexture(coffees_) : player_sprite_->setActiveTexture(3);
} else { } else {
setInvulnerable(false); setInvulnerable(false);
player_sprite_->getTexture()->setPalette(coffees_); player_sprite_->setActiveTexture(coffees_);
} }
} }
} }
@@ -812,7 +810,7 @@ void Player::giveExtraHit() {
extra_hit_ = true; extra_hit_ = true;
if (coffees_ < 2) { if (coffees_ < 2) {
coffees_++; coffees_++;
player_sprite_->getTexture()->setPalette(coffees_); player_sprite_->setActiveTexture(coffees_);
} }
} }
@@ -821,7 +819,7 @@ void Player::removeExtraHit() {
if (coffees_ > 0) { if (coffees_ > 0) {
coffees_--; coffees_--;
setInvulnerable(true); setInvulnerable(true);
player_sprite_->getTexture()->setPalette(coffees_); player_sprite_->setActiveTexture(coffees_);
} }
extra_hit_ = coffees_ != 0; extra_hit_ = coffees_ != 0;

View File

@@ -5,6 +5,7 @@
#include <algorithm> // Para find_if, max #include <algorithm> // Para find_if, max
#include <array> // Para array #include <array> // Para array
#include <cstdlib> // Para exit #include <cstdlib> // Para exit
#include <iostream> // Para printWithDots
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <utility> // Para move #include <utility> // Para move
@@ -21,23 +22,372 @@
struct JA_Music_t; // lines 11-11 struct JA_Music_t; // lines 11-11
struct JA_Sound_t; // lines 12-12 struct JA_Sound_t; // lines 12-12
// Declaraciones de funciones que necesitas implementar en otros archivos
extern AnimationsFileBuffer loadAnimationsFromFile(const std::string &filename);
extern DemoData loadDemoDataFromFile(const std::string &filename);
// Singleton // Singleton
Resource *Resource::instance = nullptr; Resource *Resource::instance = nullptr;
// Inicializa la instancia única del singleton // Inicializa la instancia única del singleton con modo de carga
void Resource::init() { Resource::instance = new Resource(); } void Resource::init(LoadingMode mode) {
Resource::instance = new Resource(mode);
}
// Libera la instancia // Libera la instancia
void Resource::destroy() { delete Resource::instance; } void Resource::destroy() {
delete Resource::instance;
Resource::instance = nullptr;
}
// Obtiene la instancia // Obtiene la instancia
auto Resource::get() -> Resource * { return Resource::instance; } auto Resource::get() -> Resource * { return Resource::instance; }
// Constructor // Constructor con modo de carga
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); } Resource::Resource(LoadingMode mode)
: loading_mode_(mode), loading_text_(nullptr) {
if (loading_mode_ == LoadingMode::PRELOAD) {
loading_text_ = Screen::get()->getText();
load();
} else {
// En modo lazy, cargamos lo mínimo indispensable
initResourceLists();
loadEssentialResources();
}
}
// Destructor // Destructor
Resource::~Resource() { clear(); } Resource::~Resource() {
clear();
}
// Carga los recursos esenciales que siempre se necesitan (modo lazy)
void Resource::loadEssentialResources() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading essential resources for lazy mode");
// Cargar recursos de texto básicos que se usan para crear texturas
loadTextFilesQuiet(); // <- VERSIÓN SILENCIOSA
loadEssentialTextures(); // Ya es silenciosa
createText(); // Crear objetos de texto
createTextTextures(); // Crear texturas generadas (game_text_xxx)
createPlayerTextures(); // Crea las texturas de jugadores con todas sus variantes de paleta
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Essential resources loaded");
}
// Carga los ficheros de texto del juego (versión silenciosa)
void Resource::loadTextFilesQuiet() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXT FILES (quiet load)");
auto list = Asset::get()->getListByType(Asset::Type::FONT);
for (const auto &l : list) {
auto name = getFileName(l);
// Buscar en nuestra lista y cargar directamente
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
if (it != text_files_.end()) {
it->text_file = Text::loadFile(l);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Text file loaded: %s", name.c_str());
}
}
}
// Carga solo las texturas esenciales (fuentes)
void Resource::loadEssentialTextures() {
const std::vector<std::string> essential_textures = {
"04b_25.png",
"04b_25_2x.png",
"04b_25_metal.png",
"04b_25_grey.png",
"04b_25_flat.png",
"04b_25_reversed.png",
"04b_25_flat_2x.png",
"04b_25_reversed_2x.png",
"8bithud.png",
"aseprite.png",
"smb2.png",
"smb2_grad.png"};
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
for (const auto &file : texture_list) {
auto name = getFileName(file);
// Solo cargar texturas esenciales
if (std::find(essential_textures.begin(), essential_textures.end(), name) != essential_textures.end()) {
// Buscar en nuestra lista y cargar
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
if (it != textures_.end()) {
it->texture = std::make_shared<Texture>(Screen::get()->getRenderer(), file);
}
}
}
}
// Inicializa las listas de recursos sin cargar el contenido (modo lazy)
void Resource::initResourceLists() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Initializing resource lists for lazy loading");
// Inicializa lista de sonidos
auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND);
sounds_.clear();
for (const auto &file : sound_list) {
sounds_.emplace_back(getFileName(file));
}
// Inicializa lista de músicas
auto music_list = Asset::get()->getListByType(Asset::Type::MUSIC);
musics_.clear();
for (const auto &file : music_list) {
musics_.emplace_back(getFileName(file));
}
// Inicializa lista de texturas
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
textures_.clear();
for (const auto &file : texture_list) {
textures_.emplace_back(getFileName(file));
}
// Inicializa lista de ficheros de texto
auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
text_files_.clear();
for (const auto &file : text_file_list) {
text_files_.emplace_back(getFileName(file));
}
// Inicializa lista de animaciones
auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
animations_.clear();
for (const auto &file : animation_list) {
animations_.emplace_back(getFileName(file));
}
// Los demos se cargan directamente sin mostrar progreso (son pocos y pequeños)
loadDemoDataQuiet();
// Inicializa lista de objetos de texto (sin cargar el contenido)
const std::vector<std::string> text_objects = {
"04b_25",
"04b_25_2x",
"04b_25_metal",
"04b_25_grey",
"04b_25_flat",
"04b_25_reversed",
"04b_25_flat_2x",
"04b_25_reversed_2x",
"8bithud",
"aseprite",
"smb2",
"smb2_grad"};
texts_.clear();
for (const auto &text_name : text_objects) {
texts_.emplace_back(text_name); // Constructor con nullptr por defecto
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Resource lists initialized for lazy loading");
}
// Obtiene el sonido a partir de un nombre (con carga perezosa)
auto Resource::getSound(const std::string &name) -> JA_Sound_t * {
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) { return s.name == name; });
if (it != sounds_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora
if (loading_mode_ == LoadingMode::LAZY_LOAD && it->sound == nullptr) {
it->sound = loadSoundLazy(name);
}
return it->sound;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Sonido no encontrado %s", name.c_str());
throw std::runtime_error("Sonido no encontrado: " + name);
}
// Obtiene la música a partir de un nombre (con carga perezosa)
auto Resource::getMusic(const std::string &name) -> JA_Music_t * {
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) { return m.name == name; });
if (it != musics_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora
if (loading_mode_ == LoadingMode::LAZY_LOAD && it->music == nullptr) {
it->music = loadMusicLazy(name);
}
return it->music;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Música no encontrada %s", name.c_str());
throw std::runtime_error("Música no encontrada: " + name);
}
// Obtiene la textura a partir de un nombre (con carga perezosa)
auto Resource::getTexture(const std::string &name) -> std::shared_ptr<Texture> {
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
if (it != textures_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora
if (loading_mode_ == LoadingMode::LAZY_LOAD && it->texture == nullptr) {
it->texture = loadTextureLazy(name);
}
return it->texture;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Imagen no encontrada %s", name.c_str());
throw std::runtime_error("Imagen no encontrada: " + name);
}
// Obtiene el fichero de texto a partir de un nombre (con carga perezosa)
auto Resource::getTextFile(const std::string &name) -> std::shared_ptr<Text::File> {
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
if (it != text_files_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora
if (loading_mode_ == LoadingMode::LAZY_LOAD && it->text_file == nullptr) {
it->text_file = loadTextFileLazy(name);
}
return it->text_file;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: TextFile no encontrado %s", name.c_str());
throw std::runtime_error("TextFile no encontrado: " + name);
}
// Obtiene el objeto de texto a partir de un nombre (con carga perezosa)
auto Resource::getText(const std::string &name) -> std::shared_ptr<Text> {
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) { return t.name == name; });
if (it != texts_.end()) {
// Si está en modo lazy y no se ha cargado aún, lo carga ahora
if (loading_mode_ == LoadingMode::LAZY_LOAD && it->text == nullptr) {
it->text = loadTextLazy(name);
}
return it->text;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Text no encontrado %s", name.c_str());
throw std::runtime_error("Text no encontrado: " + name);
}
// Obtiene la animación a partir de un nombre (con carga perezosa)
auto Resource::getAnimation(const std::string &name) -> AnimationsFileBuffer & {
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; });
if (it != animations_.end()) {
// Si está en modo lazy y no se ha cargado aún (vector vacío), lo carga ahora
if (loading_mode_ == LoadingMode::LAZY_LOAD && it->animation.empty()) {
it->animation = loadAnimationLazy(name);
}
return it->animation;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Animación no encontrada %s", name.c_str());
throw std::runtime_error("Animación no encontrada: " + name);
}
// Obtiene el fichero con los datos para el modo demostración a partir de un índice
auto Resource::getDemoData(int index) -> DemoData & {
return demos_.at(index);
}
// --- Métodos de carga perezosa ---
auto Resource::loadSoundLazy(const std::string &name) -> JA_Sound_t * {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading sound lazily: %s", name.c_str());
#ifndef NO_AUDIO
auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND);
for (const auto &file : sound_list) {
if (getFileName(file) == name) {
return JA_LoadSound(file.c_str());
}
}
#endif
return nullptr;
}
auto Resource::loadMusicLazy(const std::string &name) -> JA_Music_t * {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading music lazily: %s", name.c_str());
#ifndef NO_AUDIO
auto music_list = Asset::get()->getListByType(Asset::Type::MUSIC);
for (const auto &file : music_list) {
if (getFileName(file) == name) {
return JA_LoadMusic(file.c_str());
}
}
#endif
return nullptr;
}
auto Resource::loadTextureLazy(const std::string &name) -> std::shared_ptr<Texture> {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading texture lazily: %s", name.c_str());
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
for (const auto &file : texture_list) {
if (getFileName(file) == name) {
return std::make_shared<Texture>(Screen::get()->getRenderer(), file);
}
}
return nullptr;
}
auto Resource::loadTextFileLazy(const std::string &name) -> std::shared_ptr<Text::File> {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading text file lazily: %s", name.c_str());
auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
for (const auto &file : text_file_list) {
if (getFileName(file) == name) {
return Text::loadFile(file);
}
}
return nullptr;
}
auto Resource::loadTextLazy(const std::string &name) -> std::shared_ptr<Text> {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading text object lazily: %s", name.c_str());
// Mapeo de objetos de texto a sus recursos
struct TextMapping {
std::string key;
std::string texture_file;
std::string text_file;
};
const std::vector<TextMapping> text_mappings = {
{"04b_25", "04b_25.png", "04b_25.txt"},
{"04b_25_2x", "04b_25_2x.png", "04b_25_2x.txt"},
{"04b_25_metal", "04b_25_metal.png", "04b_25.txt"},
{"04b_25_grey", "04b_25_grey.png", "04b_25.txt"},
{"04b_25_flat", "04b_25_flat.png", "04b_25.txt"},
{"04b_25_reversed", "04b_25_reversed.png", "04b_25.txt"},
{"04b_25_flat_2x", "04b_25_flat_2x.png", "04b_25_2x.txt"},
{"04b_25_reversed_2x", "04b_25_reversed_2x.png", "04b_25_2x.txt"},
{"8bithud", "8bithud.png", "8bithud.txt"},
{"aseprite", "aseprite.png", "aseprite.txt"},
{"smb2", "smb2.png", "smb2.txt"},
{"smb2_grad", "smb2_grad.png", "smb2.txt"}};
for (const auto &mapping : text_mappings) {
if (mapping.key == name) {
// Cargar las dependencias automáticamente
auto texture = getTexture(mapping.texture_file); // Esto cargará la textura si no está cargada
auto text_file = getTextFile(mapping.text_file); // Esto cargará el archivo de texto si no está cargado
if (texture && text_file) {
return std::make_shared<Text>(texture, text_file);
}
}
}
return nullptr;
}
auto Resource::loadAnimationLazy(const std::string &name) -> AnimationsFileBuffer {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading animation lazily: %s", name.c_str());
auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
for (const auto &file : animation_list) {
if (getFileName(file) == name) {
return loadAnimationsFromFile(file);
}
}
// Si no se encuentra, retorna vector vacío
return AnimationsFileBuffer{};
}
// Vacia todos los vectores de recursos // Vacia todos los vectores de recursos
void Resource::clear() { void Resource::clear() {
@@ -72,9 +422,9 @@ void Resource::load() {
loadTextFiles(); // Carga ficheros de texto loadTextFiles(); // Carga ficheros de texto
loadAnimations(); // Carga animaciones loadAnimations(); // Carga animaciones
loadDemoData(); // Carga datos de demo loadDemoData(); // Carga datos de demo
addPalettes(); // Añade paletas a las texturas
createText(); // Crea objetos de texto createText(); // Crea objetos de texto
createTextures(); // Crea texturas a partir de texto createTextTextures(); // Crea texturas a partir de texto
createPlayerTextures(); // Crea las texturas de jugadores con todas sus variantes de paleta
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 // Restablece el sincronismo vertical a su valor original
@@ -84,91 +434,11 @@ void Resource::load() {
// Recarga todos los recursos (limpia y vuelve a cargar) // Recarga todos los recursos (limpia y vuelve a cargar)
void Resource::reload() { void Resource::reload() {
clear(); clear();
if (loading_mode_ == LoadingMode::PRELOAD) {
load(); load();
} else {
initResourceLists();
} }
// Recarga solo las texturas y paletas
void Resource::reloadTextures() {
loadTextures();
addPalettes();
createTextures();
}
// Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
auto Resource::getSound(const std::string &name) -> JA_Sound_t * {
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) { return s.name == name; });
if (it != sounds_.end()) {
return it->sound;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Sonido no encontrado %s", name.c_str());
throw std::runtime_error("Sonido no encontrado: " + name);
}
// Obtiene la música a partir de un nombre. Lanza excepción si no existe.
auto Resource::getMusic(const std::string &name) -> JA_Music_t * {
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) { return m.name == name; });
if (it != musics_.end()) {
return it->music;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Música no encontrada %s", name.c_str());
throw std::runtime_error("Música no encontrada: " + name);
}
// Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
auto Resource::getTexture(const std::string &name) -> std::shared_ptr<Texture> {
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
if (it != textures_.end()) {
return it->texture;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Imagen no encontrada %s", name.c_str());
throw std::runtime_error("Imagen no encontrada: " + name);
}
// Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
auto Resource::getTextFile(const std::string &name) -> std::shared_ptr<Text::File> {
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
if (it != text_files_.end()) {
return it->text_file;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: TextFile no encontrado %s", name.c_str());
throw std::runtime_error("TextFile no encontrado: " + name);
}
// Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
auto Resource::getText(const std::string &name) -> std::shared_ptr<Text> {
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) { return t.name == name; });
if (it != texts_.end()) {
return it->text;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Text no encontrado %s", name.c_str());
throw std::runtime_error("Text no encontrado: " + name);
}
// Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
auto Resource::getAnimation(const std::string &name) -> AnimationsFileBuffer & {
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; });
if (it != animations_.end()) {
return it->animation;
}
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Animación no encontrada %s", name.c_str());
throw std::runtime_error("Animación no encontrada: " + name);
}
// Obtiene el fichero con los datos para el modo demostración a partir de un índice
auto Resource::getDemoData(int index) -> DemoData & {
return demos_.at(index);
} }
// Carga los sonidos del juego // Carga los sonidos del juego
@@ -182,6 +452,8 @@ void Resource::loadSounds() {
updateLoadingProgress(name); updateLoadingProgress(name);
#ifndef NO_AUDIO #ifndef NO_AUDIO
sounds_.emplace_back(name, JA_LoadSound(l.c_str())); sounds_.emplace_back(name, JA_LoadSound(l.c_str()));
#else
sounds_.emplace_back(name, nullptr);
#endif #endif
printWithDots("Sound : ", name, "[ LOADED ]"); printWithDots("Sound : ", name, "[ LOADED ]");
} }
@@ -198,6 +470,8 @@ void Resource::loadMusics() {
updateLoadingProgress(name); updateLoadingProgress(name);
#ifndef NO_AUDIO #ifndef NO_AUDIO
musics_.emplace_back(name, JA_LoadMusic(l.c_str())); musics_.emplace_back(name, JA_LoadMusic(l.c_str()));
#else
musics_.emplace_back(name, nullptr);
#endif #endif
printWithDots("Music : ", name, "[ LOADED ]"); printWithDots("Music : ", name, "[ LOADED ]");
} }
@@ -254,23 +528,61 @@ void Resource::loadDemoData() {
} }
} }
// Añade paletas de colores a las texturas principales // Crea las texturas de jugadores con todas sus variantes de paleta
void Resource::addPalettes() { void Resource::createPlayerTextures() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> PALETTES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING PLAYER TEXTURES");
// Paletas para el jugador 1 // Configuración de jugadores y sus paletas
getTexture("player1.gif")->addPaletteFromPalFile(Asset::get()->get("player1_coffee1.pal")); struct PlayerConfig {
getTexture("player1.gif")->addPaletteFromPalFile(Asset::get()->get("player1_coffee2.pal")); std::string base_texture;
getTexture("player1.gif")->addPaletteFromPalFile(Asset::get()->get("player1_invencible.pal")); std::vector<std::string> palette_files;
std::string name_prefix;
};
// Paletas para el jugador 2 std::vector<PlayerConfig> players = {
getTexture("player2.gif")->addPaletteFromPalFile(Asset::get()->get("player2_coffee1.pal")); {"player1.gif", {"player1_coffee1.pal", "player1_coffee2.pal", "player1_invencible.pal"}, "player1"},
getTexture("player2.gif")->addPaletteFromPalFile(Asset::get()->get("player2_coffee2.pal")); {"player2.gif", {"player2_coffee1.pal", "player2_coffee2.pal", "player2_invencible.pal"}, "player2"}};
getTexture("player2.gif")->addPaletteFromPalFile(Asset::get()->get("player2_invencible.pal"));
for (const auto &player : players) {
// Encontrar el archivo original de la textura
std::string texture_file_path;
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
for (const auto &file : texture_list) {
if (getFileName(file) == player.base_texture) {
texture_file_path = file;
break;
}
}
// Crear variante con paleta original (pal0) - usar la textura ya cargada
auto base_texture = getTexture(player.base_texture);
std::string pal0_name = player.name_prefix + "_pal0";
textures_.emplace_back(pal0_name, base_texture);
printWithDots("Player Texture : ", pal0_name, "[ DONE ]");
// Crear variantes con paletas adicionales - CADA UNA DESDE EL ARCHIVO
for (size_t i = 0; i < player.palette_files.size(); ++i) {
// Crear textura completamente nueva desde el archivo
auto texture_copy = std::make_shared<Texture>(Screen::get()->getRenderer(), texture_file_path);
// Añadir todas las paletas
texture_copy->addPaletteFromPalFile(Asset::get()->get(player.palette_files[0]));
texture_copy->addPaletteFromPalFile(Asset::get()->get(player.palette_files[1]));
texture_copy->addPaletteFromPalFile(Asset::get()->get(player.palette_files[2]));
// Cambiar a la paleta específica (índice i+1 porque 0 es la original)
texture_copy->setPalette(i + 1);
// Guardar con nombre específico
std::string variant_name = player.name_prefix + "_pal" + std::to_string(i + 1);
textures_.emplace_back(variant_name, texture_copy);
printWithDots("Player Texture : ", variant_name, "[ DONE ]");
}
}
} }
// Crea texturas a partir de textos para mostrar puntuaciones y mensajes // Crea texturas a partir de textos para mostrar puntuaciones y mensajes
void Resource::createTextures() { void Resource::createTextTextures() {
struct NameAndText { struct NameAndText {
std::string name; std::string name;
std::string text; std::string text;
@@ -441,13 +753,16 @@ void Resource::checkEvents() {
} }
} }
// Actualiza el progreso de carga, muestra la barra y procesa eventos // Carga los datos para el modo demostración (sin mostrar progreso)
void Resource::updateLoadingProgress(std::string name) { void Resource::loadDemoDataQuiet() {
loading_resource_name_ = name; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES (quiet load)");
loading_count_.increase();
updateProgressBar(); constexpr std::array<const char *, 2> DEMO_FILES = {"demo1.bin", "demo2.bin"};
renderProgress();
checkEvents(); for (const auto &file : DEMO_FILES) {
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get(file)));
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Demo file loaded: %s", file);
}
} }
// Inicializa los rectangulos que definen la barra de progreso // Inicializa los rectangulos que definen la barra de progreso
@@ -464,6 +779,15 @@ void Resource::initProgressBar() {
loading_full_rect_ = {X_PADDING, BAR_Y_POSITION, FULL_BAR_WIDTH, BAR_HEIGHT}; loading_full_rect_ = {X_PADDING, BAR_Y_POSITION, FULL_BAR_WIDTH, BAR_HEIGHT};
} }
// Actualiza el progreso de carga, muestra la barra y procesa eventos
void Resource::updateLoadingProgress(std::string name) {
loading_resource_name_ = name;
loading_count_.increase();
updateProgressBar();
renderProgress();
checkEvents();
}
// Actualiza la barra de estado // Actualiza la barra de estado
void Resource::updateProgressBar() { void Resource::updateProgressBar() {
loading_full_rect_.w = loading_wired_rect_.w * loading_count_.getPercentage(); loading_full_rect_.w = loading_wired_rect_.w * loading_count_.getPercentage();

View File

@@ -19,8 +19,14 @@ struct JA_Sound_t;
// --- Clase Resource: gestiona todos los recursos del juego (singleton) --- // --- Clase Resource: gestiona todos los recursos del juego (singleton) ---
class Resource { class Resource {
public: public:
// --- Enum para el modo de carga ---
enum class LoadingMode {
PRELOAD, // Carga todos los recursos al inicio
LAZY_LOAD // Carga los recursos bajo demanda
};
// --- Métodos de singleton --- // --- Métodos de singleton ---
static void init(); // Inicializa el objeto Resource static void init(LoadingMode mode = LoadingMode::PRELOAD); // Inicializa el objeto Resource con modo de carga
static void destroy(); // Libera el objeto Resource static void destroy(); // Libera el objeto Resource
static auto get() -> Resource *; // Obtiene el puntero al objeto Resource static auto get() -> Resource *; // Obtiene el puntero al objeto Resource
@@ -35,7 +41,9 @@ class Resource {
// --- Métodos de 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
// --- Método para obtener el modo de carga actual ---
auto getLoadingMode() const -> LoadingMode { return loading_mode_; }
private: private:
// --- Estructuras para recursos individuales --- // --- Estructuras para recursos individuales ---
@@ -43,7 +51,7 @@ class Resource {
std::string name; // Nombre del sonido std::string name; // Nombre del sonido
JA_Sound_t *sound; // Objeto con el sonido JA_Sound_t *sound; // Objeto con el sonido
ResourceSound(std::string name, JA_Sound_t *sound) ResourceSound(std::string name, JA_Sound_t *sound = nullptr)
: name(std::move(name)), sound(sound) {} : name(std::move(name)), sound(sound) {}
}; };
@@ -51,7 +59,7 @@ class Resource {
std::string name; // Nombre de la música std::string name; // Nombre de la música
JA_Music_t *music; // Objeto con la música JA_Music_t *music; // Objeto con la música
ResourceMusic(std::string name, JA_Music_t *music) ResourceMusic(std::string name, JA_Music_t *music = nullptr)
: name(std::move(name)), music(music) {} : name(std::move(name)), music(music) {}
}; };
@@ -59,7 +67,7 @@ class Resource {
std::string name; // Nombre de la textura std::string name; // Nombre de la textura
std::shared_ptr<Texture> texture; // Objeto con la textura std::shared_ptr<Texture> texture; // Objeto con la textura
ResourceTexture(std::string name, std::shared_ptr<Texture> texture) ResourceTexture(std::string name, std::shared_ptr<Texture> texture = nullptr)
: name(std::move(name)), texture(std::move(texture)) {} : name(std::move(name)), texture(std::move(texture)) {}
}; };
@@ -67,7 +75,7 @@ class Resource {
std::string name; // Nombre del fichero std::string name; // Nombre del fichero
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto
ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file) ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file = nullptr)
: name(std::move(name)), text_file(std::move(text_file)) {} : name(std::move(name)), text_file(std::move(text_file)) {}
}; };
@@ -75,7 +83,7 @@ class Resource {
std::string name; // Nombre del objeto std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto de texto std::shared_ptr<Text> text; // Objeto de texto
ResourceText(std::string name, std::shared_ptr<Text> text) ResourceText(std::string name, std::shared_ptr<Text> text = nullptr)
: name(std::move(name)), text(std::move(text)) {} : name(std::move(name)), text(std::move(text)) {}
}; };
@@ -83,7 +91,7 @@ class Resource {
std::string name; // Nombre de la animación std::string name; // Nombre de la animación
AnimationsFileBuffer animation; // Objeto con las animaciones AnimationsFileBuffer animation; // Objeto con las animaciones
ResourceAnimation(std::string name, AnimationsFileBuffer animation) ResourceAnimation(std::string name, AnimationsFileBuffer animation = {})
: name(std::move(name)), animation(std::move(animation)) {} : name(std::move(name)), animation(std::move(animation)) {}
}; };
@@ -102,6 +110,9 @@ class Resource {
} }
}; };
// --- Modo de carga ---
LoadingMode loading_mode_;
// --- Vectores de recursos --- // --- Vectores de recursos ---
std::vector<ResourceSound> sounds_; // Vector con los sonidos std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las músicas std::vector<ResourceMusic> musics_; // Vector con las músicas
@@ -125,14 +136,28 @@ class Resource {
void loadTextFiles(); // Carga los ficheros de texto void loadTextFiles(); // Carga los ficheros de texto
void loadAnimations(); // Carga las animaciones void loadAnimations(); // Carga las animaciones
void loadDemoData(); // Carga los datos para el modo demostración void loadDemoData(); // Carga los datos para el modo demostración
void addPalettes(); // Añade paletas a las texturas void loadDemoDataQuiet(); // Carga los datos de demo sin mostrar progreso (para modo lazy)
void createTextures(); // Crea las texturas a partir de los datos cargados void loadEssentialResources(); // Carga recursos esenciales en modo lazy
void loadEssentialTextures(); // Carga solo las texturas esenciales (fuentes)
void loadTextFilesQuiet(); // Carga ficheros de texto sin mostrar progreso (para modo lazy)
// void addPalettes(); // Añade paletas a las texturas
void createPlayerTextures(); // Crea las texturas de jugadores con todas sus variantes de paleta
void createTextTextures(); // Crea las texturas a partir de los datos cargados
void createText(); // Crea los objetos de texto void createText(); // Crea los objetos de texto
void clear(); // Vacía todos los vectores de recursos void clear(); // Vacía todos los vectores de recursos
void load(); // Carga todos los recursos void load(); // Carga todos los recursos
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 para carga perezosa ---
void initResourceLists(); // Inicializa las listas de recursos sin cargar el contenido
auto loadSoundLazy(const std::string &name) -> JA_Sound_t *; // Carga un sonido específico bajo demanda
auto loadMusicLazy(const std::string &name) -> JA_Music_t *; // Carga una música específica bajo demanda
auto loadTextureLazy(const std::string &name) -> std::shared_ptr<Texture>; // Carga una textura específica bajo demanda
auto loadTextFileLazy(const std::string &name) -> std::shared_ptr<Text::File>; // Carga un fichero de texto específico bajo demanda
auto loadTextLazy(const std::string &name) -> std::shared_ptr<Text>; // Carga un objeto de texto específico bajo demanda
auto loadAnimationLazy(const std::string &name) -> AnimationsFileBuffer; // Carga una animación específica bajo demanda
// --- Métodos internos para gestionar el progreso --- // --- Métodos internos para gestionar el progreso ---
void calculateTotalResources(); // Calcula el número de recursos para cargar void calculateTotalResources(); // Calcula el número de recursos para cargar
void renderProgress(); // Muestra el progreso de carga void renderProgress(); // Muestra el progreso de carga
@@ -142,7 +167,7 @@ class Resource {
void updateProgressBar(); // Actualiza la barra de estado void updateProgressBar(); // Actualiza la barra de estado
// --- Constructores y destructor privados (singleton) --- // --- Constructores y destructor privados (singleton) ---
Resource(); // Constructor privado explicit Resource(LoadingMode mode); // Constructor privado con modo de carga
~Resource(); // Destructor privado ~Resource(); // Destructor privado
// --- Instancia singleton --- // --- Instancia singleton ---

View File

@@ -331,13 +331,19 @@ void Credits::initPlayers() {
// Texturas - Player1 // Texturas - Player1
std::vector<std::shared_ptr<Texture>> player1_textures; std::vector<std::shared_ptr<Texture>> player1_textures;
player1_textures.emplace_back(Resource::get()->getTexture("player1.gif")); player1_textures.emplace_back(Resource::get()->getTexture("player1_pal0"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal1"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal2"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal3"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png")); player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png"));
player_textures.push_back(player1_textures); player_textures.push_back(player1_textures);
// Texturas - Player2 // Texturas - Player2
std::vector<std::shared_ptr<Texture>> player2_textures; std::vector<std::shared_ptr<Texture>> player2_textures;
player2_textures.emplace_back(Resource::get()->getTexture("player2.gif")); player2_textures.emplace_back(Resource::get()->getTexture("player2_pal0"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal1"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal2"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal3"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png")); player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png"));
player_textures.push_back(player2_textures); player_textures.push_back(player2_textures);

View File

@@ -124,6 +124,7 @@ Game::~Game() {
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO;
Audio::get()->stopMusic(); Audio::get()->stopMusic();
} }
ServiceMenu::get()->setStateChangeCallback(nullptr);
#ifdef RECORDING #ifdef RECORDING
saveDemoFile(Asset::get()->get("demo1.bin"), demo_.data.at(0)); saveDemoFile(Asset::get()->get("demo1.bin"), demo_.data.at(0));
@@ -162,13 +163,19 @@ void Game::setResources() {
player_textures_.clear(); player_textures_.clear();
// Texturas - Player1 // Texturas - Player1
std::vector<std::shared_ptr<Texture>> player1_textures; std::vector<std::shared_ptr<Texture>> player1_textures;
player1_textures.emplace_back(Resource::get()->getTexture("player1.gif")); player1_textures.emplace_back(Resource::get()->getTexture("player1_pal0"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal1"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal2"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal3"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png")); player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png"));
player_textures_.push_back(player1_textures); player_textures_.push_back(player1_textures);
// Texturas - Player2 // Texturas - Player2
std::vector<std::shared_ptr<Texture>> player2_textures; std::vector<std::shared_ptr<Texture>> player2_textures;
player2_textures.emplace_back(Resource::get()->getTexture("player2.gif")); player2_textures.emplace_back(Resource::get()->getTexture("player2_pal0"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal1"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal2"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal3"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png")); player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png"));
player_textures_.push_back(player2_textures); player_textures_.push_back(player2_textures);

View File

@@ -488,13 +488,19 @@ void Title::initPlayers() {
// Texturas - Player1 // Texturas - Player1
std::vector<std::shared_ptr<Texture>> player1_textures; std::vector<std::shared_ptr<Texture>> player1_textures;
player1_textures.emplace_back(Resource::get()->getTexture("player1.gif")); player1_textures.emplace_back(Resource::get()->getTexture("player1_pal0"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal1"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal2"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_pal3"));
player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png")); player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png"));
player_textures.push_back(player1_textures); player_textures.push_back(player1_textures);
// Texturas - Player2 // Texturas - Player2
std::vector<std::shared_ptr<Texture>> player2_textures; std::vector<std::shared_ptr<Texture>> player2_textures;
player2_textures.emplace_back(Resource::get()->getTexture("player2.gif")); player2_textures.emplace_back(Resource::get()->getTexture("player2_pal0"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal1"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal2"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_pal3"));
player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png")); player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png"));
player_textures.push_back(player2_textures); player_textures.push_back(player2_textures);

View File

@@ -1,28 +1,29 @@
#include "sprite.h" #include "sprite.h"
#include <utility> // Para move #include <utility> // Para move
#include <vector> // Para vector
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height) Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
: texture_(std::move(texture)), : textures_{texture},
pos_((SDL_FRect){pos_x, pos_y, width, height}), pos_((SDL_FRect){pos_x, pos_y, width, height}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect) Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: texture_(std::move(texture)), : textures_{texture},
pos_(rect), pos_(rect),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(std::move(texture)), : textures_{texture},
pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}), pos_(SDL_FRect{0, 0, static_cast<float>(textures_.at(texture_index_)->getWidth()), static_cast<float>(textures_.at(texture_index_)->getHeight())}),
sprite_clip_(pos_) {} sprite_clip_(pos_) {}
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void Sprite::render() { void Sprite::render() {
texture_->render(pos_.x, pos_.y, &sprite_clip_, zoom_, zoom_); textures_.at(texture_index_)->render(pos_.x, pos_.y, &sprite_clip_, zoom_, zoom_);
} }
// Establece la posición del objeto // Establece la posición del objeto
@@ -42,3 +43,12 @@ void Sprite::clear() {
pos_ = {0, 0, 0, 0}; pos_ = {0, 0, 0, 0};
sprite_clip_ = {0, 0, 0, 0}; sprite_clip_ = {0, 0, 0, 0};
} }
// Cambia la textura activa por índice
bool Sprite::setActiveTexture(size_t index) {
if (index < textures_.size()) {
texture_index_ = index;
return true;
}
return false; // Índice fuera de rango
}

View File

@@ -3,6 +3,7 @@
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint #include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <vector> // Para vector
class Texture; class Texture;
@@ -49,12 +50,21 @@ class Sprite {
void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; } void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; }
// --- Textura --- // --- Textura ---
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return texture_; } [[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return textures_.at(texture_index_); }
void setTexture(std::shared_ptr<Texture> texture) { texture_ = texture; } void setTexture(std::shared_ptr<Texture> texture) { textures_.at(texture_index_) = texture; }
void addTexture(std::shared_ptr<Texture> texture) { textures_.push_back(texture); }
bool setActiveTexture(size_t index); // Cambia la textura activa por índice
size_t getActiveTextureIndex() const { return texture_index_; } // Obtiene el índice de la textura activa
size_t getTextureCount() const { return textures_.size(); } // Obtiene el número total de texturas
protected: protected:
std::shared_ptr<Texture>& getTextureRef() {
return textures_.at(texture_index_);
}
// --- Variables internas --- // --- Variables internas ---
std::shared_ptr<Texture> texture_; // Textura donde están todos los dibujos del sprite size_t texture_index_ = 0;
std::vector<std::shared_ptr<Texture>> textures_; // Lista de texturas
SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite
SDL_FRect sprite_clip_; // Rectángulo de origen de la textura que se dibujará en pantalla SDL_FRect sprite_clip_; // Rectángulo de origen de la textura que se dibujará en pantalla
double zoom_ = 1.0F; // Zoom aplicado a la textura double zoom_ = 1.0F; // Zoom aplicado a la textura

View File

@@ -13,25 +13,33 @@
// --- Implementación de las estructuras de animación --- // --- Implementación de las estructuras de animación ---
void MenuRenderer::ResizeAnimation::start(float from_w, float from_h, float to_w, float to_h) { void MenuRenderer::ResizeAnimation::start(float from_w, float from_h, float to_w, float to_h) {
start_width = from_w; start_height = from_h; start_width = from_w;
target_width = to_w; target_height = to_h; start_height = from_h;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F; elapsed = 0.0F;
active = true; active = true;
} }
void MenuRenderer::ResizeAnimation::stop() { active = false; void MenuRenderer::ResizeAnimation::stop() {
active = false;
elapsed = 0.0F; elapsed = 0.0F;
} }
void MenuRenderer::ShowHideAnimation::startShow(float to_w, float to_h) { void MenuRenderer::ShowHideAnimation::startShow(float to_w, float to_h) {
type = Type::SHOWING; target_width = to_w; target_height = to_h; type = Type::SHOWING;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F; elapsed = 0.0F;
active = true; active = true;
} }
void MenuRenderer::ShowHideAnimation::startHide() { type = Type::HIDING; void MenuRenderer::ShowHideAnimation::startHide() {
type = Type::HIDING;
elapsed = 0.0F; elapsed = 0.0F;
active = true; active = true;
} }
void MenuRenderer::ShowHideAnimation::stop() { type = Type::NONE; active = false; void MenuRenderer::ShowHideAnimation::stop() {
type = Type::NONE;
active = false;
elapsed = 0.0F; elapsed = 0.0F;
} }
@@ -201,7 +209,6 @@ auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect
return new_rect; return new_rect;
} }
void MenuRenderer::resize(const ServiceMenu *menu_state) { void MenuRenderer::resize(const ServiceMenu *menu_state) {
SDL_FRect new_rect = calculateNewRect(menu_state); SDL_FRect new_rect = calculateNewRect(menu_state);
@@ -286,7 +293,6 @@ void MenuRenderer::updateResizeAnimation(float delta_time) {
options_y_ = rect_.y + upper_height_ + lower_padding_; options_y_ = rect_.y + upper_height_ + lower_padding_;
} }
void MenuRenderer::updatePosition() { void MenuRenderer::updatePosition() {
switch (position_mode_) { switch (position_mode_) {
case PositionMode::CENTERED: case PositionMode::CENTERED:

View File

@@ -88,7 +88,9 @@ class MenuRenderer {
} resize_animation_; } resize_animation_;
struct ShowHideAnimation { struct ShowHideAnimation {
enum class Type { NONE, SHOWING, HIDING }; enum class Type { NONE,
SHOWING,
HIDING };
Type type = Type::NONE; Type type = Type::NONE;
bool active = false; bool active = false;
float target_width, target_height; float target_width, target_height;

View File

@@ -26,13 +26,11 @@ void WindowMessage::render() {
SDL_Renderer* renderer = Screen::get()->getRenderer(); SDL_Renderer* renderer = Screen::get()->getRenderer();
// Dibujar fondo con transparencia // Dibujar fondo con transparencia
SDL_SetRenderDrawColor(renderer, config_.bg_color.r, config_.bg_color.g, SDL_SetRenderDrawColor(renderer, config_.bg_color.r, config_.bg_color.g, config_.bg_color.b, config_.bg_color.a);
config_.bg_color.b, config_.bg_color.a);
SDL_RenderFillRect(renderer, &rect_); SDL_RenderFillRect(renderer, &rect_);
// Dibujar borde // Dibujar borde
SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g, SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g, config_.border_color.b, config_.border_color.a);
config_.border_color.b, config_.border_color.a);
SDL_RenderRect(renderer, &rect_); SDL_RenderRect(renderer, &rect_);
// Solo mostrar contenido si no estamos en animación de show/hide // Solo mostrar contenido si no estamos en animación de show/hide
@@ -54,8 +52,7 @@ void WindowMessage::render() {
// Línea separadora debajo del título (solo si hay título visible) // Línea separadora debajo del título (solo si hay título visible)
if (!visible_title.empty()) { if (!visible_title.empty()) {
SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g, SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g, config_.border_color.b, config_.border_color.a);
config_.border_color.b, config_.border_color.a);
SDL_RenderLine(renderer, SDL_RenderLine(renderer,
rect_.x + config_.padding, rect_.x + config_.padding,
current_y - config_.title_separator_spacing / 2.0F, current_y - config_.title_separator_spacing / 2.0F,
@@ -191,10 +188,8 @@ void WindowMessage::autoSize() {
} }
void WindowMessage::updateStyles() { void WindowMessage::updateStyles() {
title_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.title_color, title_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.title_color, config_.title_color, 0, -2);
config_.title_color, 0, -2); text_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.text_color, config_.text_color, 0, -2);
text_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.text_color,
config_.text_color, 0, -2);
} }
void WindowMessage::updatePosition() { void WindowMessage::updatePosition() {

View File

@@ -83,15 +83,24 @@ class WindowMessage {
// Configuración de colores // Configuración de colores
void setBackgroundColor(const Color& color) { config_.bg_color = color; } void setBackgroundColor(const Color& color) { config_.bg_color = color; }
void setBorderColor(const Color& color) { config_.border_color = color; } void setBorderColor(const Color& color) { config_.border_color = color; }
void setTitleColor(const Color& color) { config_.title_color = color; updateStyles(); } void setTitleColor(const Color& color) {
void setTextColor(const Color& color) { config_.text_color = color; updateStyles(); } config_.title_color = color;
updateStyles();
}
void setTextColor(const Color& color) {
config_.text_color = color;
updateStyles();
}
// Configuración de espaciado // Configuración de espaciado
void setPadding(float padding) { config_.padding = padding; } void setPadding(float padding) { config_.padding = padding; }
void setLineSpacing(float spacing) { config_.line_spacing = spacing; } void setLineSpacing(float spacing) { config_.line_spacing = spacing; }
// Configuración avanzada // Configuración avanzada
void setConfig(const Config& config) { config_ = config; updateStyles(); } void setConfig(const Config& config) {
config_ = config;
updateStyles();
}
[[nodiscard]] auto getConfig() const -> const Config& { return config_; } [[nodiscard]] auto getConfig() const -> const Config& { return config_; }
// Getters // Getters
@@ -148,7 +157,9 @@ class WindowMessage {
// Animación de mostrar/ocultar // Animación de mostrar/ocultar
struct ShowHideAnimation { struct ShowHideAnimation {
enum class Type { NONE, SHOWING, HIDING }; enum class Type { NONE,
SHOWING,
HIDING };
Type type = Type::NONE; Type type = Type::NONE;
bool active = false; bool active = false;