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
void AnimatedSprite::updateFrameCalculations(AnimationConfig& config) {
config.frames_per_row = texture_->getWidth() / config.frame_width;
const int WIDTH = texture_->getWidth() / config.frame_width;
const int HEIGHT = texture_->getHeight() / config.frame_height;
config.frames_per_row = getTexture()->getWidth() / config.frame_width;
const int WIDTH = getTexture()->getWidth() / config.frame_width;
const int HEIGHT = getTexture()->getHeight() / config.frame_height;
config.max_tiles = WIDTH * HEIGHT;
}

View File

@@ -1,10 +1,11 @@
#include "asset.h"
#include <SDL3/SDL.h>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <sstream>
#include "utils.h"
@@ -27,13 +28,14 @@ auto Asset::get() -> Asset * {
void Asset::addToMap(const std::string &file_path, Type type, bool required, bool absolute) {
std::string full_path = absolute ? file_path : executable_path_ + file_path;
std::string filename = getFileName(full_path);
// Verificar si ya existe el archivo
if (file_list_.find(filename) != file_list_.end()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset '%s' already exists, overwriting", filename.c_str());
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset '%s' already exists, overwriting",
filename.c_str());
}
file_list_.emplace(filename, Item{std::move(full_path), type, required});
}
@@ -47,76 +49,81 @@ void Asset::add(const std::string &file_path, Type type, bool required, bool abs
void Asset::loadFromFile(const std::string &config_file_path, const std::string &prefix, const std::string &system_folder) {
std::ifstream file(config_file_path);
if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error: Cannot open config file: %s", config_file_path.c_str());
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error: Cannot open config file: %s",
config_file_path.c_str());
return;
}
std::string line;
int line_number = 0;
while (std::getline(file, line)) {
++line_number;
// Limpiar espacios en blanco al principio y final
line.erase(0, line.find_first_not_of(" \t\r"));
line.erase(line.find_last_not_of(" \t\r") + 1);
// DEBUG: mostrar línea leída (opcional, puedes comentar esta línea)
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Line %d: '%s'", line_number, line.c_str());
// Ignorar líneas vacías y comentarios
if (line.empty() || line[0] == '#' || line[0] == ';') {
continue;
}
// Dividir la línea por el separador '|'
std::vector<std::string> parts;
std::istringstream iss(line);
std::string part;
while (std::getline(iss, part, '|')) {
parts.push_back(part);
}
// Verificar que tenemos al menos tipo y ruta
if (parts.size() < 2) {
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;
}
try {
std::string type_str = parts[0];
std::string path = parts[1];
// Valores por defecto
bool required = true;
bool absolute = false;
// Si hay opciones en el tercer campo, parsearlas
if (parts.size() >= 3) {
parseOptions(parts[2], required, absolute);
}
// Reemplazar variables en la ruta
path = replaceVariables(path, prefix, system_folder);
// Parsear el tipo de asset
Type type = parseAssetType(type_str);
// Añadir al mapa
addToMap(path, type, required, absolute);
} catch (const std::exception &e) {
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,
"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();
}
@@ -126,7 +133,7 @@ auto Asset::get(const std::string &filename) const -> std::string {
if (it != file_list_.end()) {
return it->second.file;
}
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found", filename.c_str());
return "";
}
@@ -139,26 +146,27 @@ auto Asset::exists(const std::string &filename) const -> bool {
// Comprueba que existen todos los elementos
auto Asset::check() const -> bool {
bool success = true;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES");
// Agrupar por tipo para mostrar organizado
std::unordered_map<Type, std::vector<const Item*>> by_type;
std::unordered_map<Type, std::vector<const Item *>> by_type;
for (const auto &[filename, item] : file_list_) {
if (item.required) {
by_type[item.type].push_back(&item);
}
}
// Verificar por tipo
for (int type = 0; type < static_cast<int>(Type::SIZE); ++type) {
Type asset_type = static_cast<Type>(type);
if (by_type.find(asset_type) != by_type.end()) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"\n>> %s FILES", getTypeName(asset_type).c_str());
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"\n>> %s FILES",
getTypeName(asset_type).c_str());
bool type_success = true;
for (const auto *item : by_type[asset_type]) {
if (!checkFile(item->file)) {
@@ -166,20 +174,20 @@ auto Asset::check() const -> bool {
type_success = false;
}
}
if (type_success) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, " All files are OK.");
}
}
}
// Resultado
if (success) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES COMPLETED.\n");
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES FAILED.\n");
}
return success;
}
@@ -188,12 +196,13 @@ auto Asset::checkFile(const std::string &path) -> bool {
std::ifstream file(path);
bool success = file.good();
file.close();
if (!success) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Checking file: %s [ ERROR ]", getFileName(path).c_str());
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Checking file: %s [ ERROR ]",
getFileName(path).c_str());
}
return success;
}
@@ -233,50 +242,60 @@ auto Asset::parseAssetType(const std::string &type_str) -> Type {
// Devuelve el nombre del tipo de recurso
auto Asset::getTypeName(Type type) -> std::string {
switch (type) {
case Type::BITMAP: return "BITMAP";
case Type::MUSIC: return "MUSIC";
case Type::SOUND: return "SOUND";
case Type::FONT: return "FONT";
case Type::LANG: 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";
case Type::BITMAP:
return "BITMAP";
case Type::MUSIC:
return "MUSIC";
case Type::SOUND:
return "SOUND";
case Type::FONT:
return "FONT";
case Type::LANG:
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";
}
}
// Devuelve la lista de recursos de un tipo
auto Asset::getListByType(Type type) const -> std::vector<std::string> {
std::vector<std::string> list;
for (const auto &[filename, item] : file_list_) {
if (item.type == type) {
list.push_back(item.file);
}
}
return list;
}
// Reemplaza variables en las rutas
auto Asset::replaceVariables(const std::string &path, const std::string &prefix, const std::string &system_folder) -> std::string {
std::string result = path;
// Reemplazar ${PREFIX}
size_t pos = 0;
while ((pos = result.find("${PREFIX}", pos)) != std::string::npos) {
result.replace(pos, 9, prefix); // 9 = longitud de "${PREFIX}"
pos += prefix.length();
}
// Reemplazar ${SYSTEM_FOLDER}
pos = 0;
while ((pos = result.find("${SYSTEM_FOLDER}", pos)) != std::string::npos) {
result.replace(pos, 16, system_folder); // 16 = longitud de "${SYSTEM_FOLDER}"
pos += system_folder.length();
}
return result;
}
@@ -288,12 +307,12 @@ auto Asset::parseOptions(const std::string &options, bool &required, bool &absol
std::istringstream iss(options);
std::string option;
while (std::getline(iss, option, ',')) {
// Eliminar espacios
option.erase(0, option.find_first_not_of(" \t"));
option.erase(option.find_last_not_of(" \t") + 1);
if (option == "optional") {
required = false;
} else if (option == "absolute") {

View File

@@ -2,8 +2,8 @@
#include <string>
#include <unordered_map>
#include <vector>
#include <utility>
#include <vector>
// Clase Asset: gestor optimizado de recursos (singleton)
class Asset {
@@ -32,7 +32,7 @@ class Asset {
// --- Métodos para la gestión de recursos ---
void add(const std::string &file_path, Type type, bool required = true, bool absolute = false);
void loadFromFile(const std::string &config_file_path, const std::string &prefix = "", const std::string &system_folder = ""); // Con soporte para variables
[[nodiscard]] auto get(const std::string &filename) const -> std::string; // Mantener nombre original
[[nodiscard]] auto get(const std::string &filename) const -> std::string; // Mantener nombre original
[[nodiscard]] auto check() const -> bool;
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
[[nodiscard]] auto exists(const std::string &filename) const -> bool; // Nueva función para verificar existencia
@@ -40,17 +40,17 @@ class Asset {
private:
// --- Estructura interna para almacenar información de cada recurso ---
struct Item {
std::string file; // Ruta completa del archivo (mantener nombre original)
Type type; // Tipo de recurso
bool required; // Indica si el archivo es obligatorio
std::string file; // Ruta completa del archivo (mantener nombre original)
Type type; // Tipo de recurso
bool required; // Indica si el archivo es obligatorio
Item(std::string path, Type asset_type, bool is_required)
: file(std::move(path)), type(asset_type), required(is_required) {}
Item(std::string path, Type asset_type, bool is_required)
: file(std::move(path)), type(asset_type), required(is_required) {}
};
// --- Variables internas ---
std::unordered_map<std::string, Item> file_list_; // Mapa para búsqueda O(1) (mantener nombre original)
std::string executable_path_; // Ruta del ejecutable
std::string executable_path_; // Ruta del ejecutable
// --- Métodos internos ---
[[nodiscard]] static auto checkFile(const std::string &path) -> bool;

View File

@@ -46,7 +46,7 @@ Director::Director(int argc, std::span<char *> argv) {
Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P;
#elif _DEBUG
Section::name = Section::Name::TITLE;
Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P;
#else // NORMAL GAME
Section::name = Section::Name::LOGO;
@@ -98,9 +98,11 @@ void Director::init() {
Lang::setLanguage(Options::settings.language); // Carga el archivo de idioma
Screen::init(); // Inicializa la pantalla y el sistema de renderizado
Audio::init(); // Activa el sistema de audio
Resource::init(); // Inicializa el sistema de gestión de recursos
// bindInputs(); // Asigna los controles a la entrada del sistema
#ifdef _DEBUG
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
Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones
Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones
@@ -163,7 +165,7 @@ void Director::loadAssets() {
// Cargar la configuración de assets (también aplicar el prefijo al archivo de configuración)
std::string config_path = executable_path_ + prefix + "/data/config/assets.txt";
Asset::get()->loadFromFile(config_path, prefix, system_folder_);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Assets configuration loaded successfully");
// Si falta algun fichero, sale del programa

View File

@@ -72,7 +72,7 @@ void MovingSprite::update() {
}
// 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
void MovingSprite::rotate() {

View File

@@ -247,7 +247,7 @@ class GamepadManager {
private:
static constexpr std::string_view UNASSIGNED_TEXT = "---";
static constexpr size_t MAX_PLAYERS = 2;
std::array<Gamepad, MAX_PLAYERS> gamepads_; // Punteros a las estructuras de mandos de Options
std::array<Gamepad, MAX_PLAYERS> gamepads_; // Punteros a las estructuras de mandos de Options
std::vector<std::shared_ptr<Player>> players_; // Punteros a los jugadores
// Convierte Player::Id a índice del array

View File

@@ -22,7 +22,7 @@
// Constructor
Player::Player(const Config &config)
: 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>()),
hi_score_table_(*config.hi_score_table),
glowing_entry_(*config.glowing_entry),
@@ -32,7 +32,10 @@ Player::Player(const Config &config)
default_pos_y_(config.y),
demo_(config.demo) {
// 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_up_x_offset_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2;
power_sprite_->setPosY(default_pos_y_ - (power_sprite_->getHeight() - player_sprite_->getHeight()));
@@ -460,26 +463,21 @@ void Player::setAnimation() {
player_sprite_->setFlip(flipMode);
break;
}
case State::WAITING:
player_sprite_->setCurrentAnimation("hello");
break;
case State::ROLLING:
case State::CONTINUE_TIME_OUT:
player_sprite_->setCurrentAnimation("rolling");
break;
case State::LYING_ON_THE_FLOOR_FOREVER:
case State::ENTERING_NAME:
case State::CONTINUE:
player_sprite_->setCurrentAnimation("dead");
break;
case State::CELEBRATING:
player_sprite_->setCurrentAnimation("celebration");
break;
default:
break;
}
@@ -782,10 +780,10 @@ void Player::updateInvulnerable() {
if (invulnerable_) {
if (invulnerable_counter_ > 0) {
--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 {
setInvulnerable(false);
player_sprite_->getTexture()->setPalette(coffees_);
player_sprite_->setActiveTexture(coffees_);
}
}
}
@@ -812,7 +810,7 @@ void Player::giveExtraHit() {
extra_hit_ = true;
if (coffees_ < 2) {
coffees_++;
player_sprite_->getTexture()->setPalette(coffees_);
player_sprite_->setActiveTexture(coffees_);
}
}
@@ -821,7 +819,7 @@ void Player::removeExtraHit() {
if (coffees_ > 0) {
coffees_--;
setInvulnerable(true);
player_sprite_->getTexture()->setPalette(coffees_);
player_sprite_->setActiveTexture(coffees_);
}
extra_hit_ = coffees_ != 0;

View File

@@ -5,6 +5,7 @@
#include <algorithm> // Para find_if, max
#include <array> // Para array
#include <cstdlib> // Para exit
#include <iostream> // Para printWithDots
#include <stdexcept> // Para runtime_error
#include <utility> // Para move
@@ -21,23 +22,372 @@
struct JA_Music_t; // lines 11-11
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
Resource *Resource::instance = nullptr;
// Inicializa la instancia única del singleton
void Resource::init() { Resource::instance = new Resource(); }
// Inicializa la instancia única del singleton con modo de carga
void Resource::init(LoadingMode mode) {
Resource::instance = new Resource(mode);
}
// Libera la instancia
void Resource::destroy() { delete Resource::instance; }
void Resource::destroy() {
delete Resource::instance;
Resource::instance = nullptr;
}
// Obtiene la instancia
auto Resource::get() -> Resource * { return Resource::instance; }
// Constructor
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
// Constructor con modo de carga
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
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
void Resource::clear() {
@@ -68,13 +418,13 @@ void Resource::load() {
loadSounds(); // Carga sonidos
loadMusics(); // Carga músicas
#endif
loadTextures(); // Carga texturas
loadTextFiles(); // Carga ficheros de texto
loadAnimations(); // Carga animaciones
loadDemoData(); // Carga datos de demo
addPalettes(); // Añade paletas a las texturas
createText(); // Crea objetos de texto
createTextures(); // Crea texturas a partir de texto
loadTextures(); // Carga texturas
loadTextFiles(); // Carga ficheros de texto
loadAnimations(); // Carga animaciones
loadDemoData(); // Carga datos de demo
createText(); // Crea objetos 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");
// Restablece el sincronismo vertical a su valor original
@@ -84,91 +434,11 @@ void Resource::load() {
// Recarga todos los recursos (limpia y vuelve a cargar)
void Resource::reload() {
clear();
load();
}
// 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;
if (loading_mode_ == LoadingMode::PRELOAD) {
load();
} else {
initResourceLists();
}
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
@@ -182,6 +452,8 @@ void Resource::loadSounds() {
updateLoadingProgress(name);
#ifndef NO_AUDIO
sounds_.emplace_back(name, JA_LoadSound(l.c_str()));
#else
sounds_.emplace_back(name, nullptr);
#endif
printWithDots("Sound : ", name, "[ LOADED ]");
}
@@ -198,6 +470,8 @@ void Resource::loadMusics() {
updateLoadingProgress(name);
#ifndef NO_AUDIO
musics_.emplace_back(name, JA_LoadMusic(l.c_str()));
#else
musics_.emplace_back(name, nullptr);
#endif
printWithDots("Music : ", name, "[ LOADED ]");
}
@@ -254,23 +528,61 @@ void Resource::loadDemoData() {
}
}
// Añade paletas de colores a las texturas principales
void Resource::addPalettes() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> PALETTES");
// Crea las texturas de jugadores con todas sus variantes de paleta
void Resource::createPlayerTextures() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING PLAYER TEXTURES");
// Paletas para el jugador 1
getTexture("player1.gif")->addPaletteFromPalFile(Asset::get()->get("player1_coffee1.pal"));
getTexture("player1.gif")->addPaletteFromPalFile(Asset::get()->get("player1_coffee2.pal"));
getTexture("player1.gif")->addPaletteFromPalFile(Asset::get()->get("player1_invencible.pal"));
// Configuración de jugadores y sus paletas
struct PlayerConfig {
std::string base_texture;
std::vector<std::string> palette_files;
std::string name_prefix;
};
// Paletas para el jugador 2
getTexture("player2.gif")->addPaletteFromPalFile(Asset::get()->get("player2_coffee1.pal"));
getTexture("player2.gif")->addPaletteFromPalFile(Asset::get()->get("player2_coffee2.pal"));
getTexture("player2.gif")->addPaletteFromPalFile(Asset::get()->get("player2_invencible.pal"));
std::vector<PlayerConfig> players = {
{"player1.gif", {"player1_coffee1.pal", "player1_coffee2.pal", "player1_invencible.pal"}, "player1"},
{"player2.gif", {"player2_coffee1.pal", "player2_coffee2.pal", "player2_invencible.pal"}, "player2"}};
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
void Resource::createTextures() {
void Resource::createTextTextures() {
struct NameAndText {
std::string name;
std::string text;
@@ -441,13 +753,16 @@ void Resource::checkEvents() {
}
}
// 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();
// Carga los datos para el modo demostración (sin mostrar progreso)
void Resource::loadDemoDataQuiet() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES (quiet load)");
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)));
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Demo file loaded: %s", file);
}
}
// Inicializa los rectangulos que definen la barra de progreso
@@ -464,7 +779,16 @@ void Resource::initProgressBar() {
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
void Resource::updateProgressBar() {
loading_full_rect_.w = loading_wired_rect_.w * loading_count_.getPercentage();
}
}

View File

@@ -19,10 +19,16 @@ struct JA_Sound_t;
// --- Clase Resource: gestiona todos los recursos del juego (singleton) ---
class Resource {
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 ---
static void init(); // Inicializa el objeto Resource
static void destroy(); // Libera el objeto Resource
static auto get() -> Resource *; // Obtiene el puntero al 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 auto get() -> Resource *; // Obtiene el puntero al objeto Resource
// --- Métodos de acceso a recursos ---
auto getSound(const std::string &name) -> JA_Sound_t *; // Obtiene el sonido por nombre
@@ -35,7 +41,9 @@ class Resource {
// --- Métodos de recarga de 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:
// --- Estructuras para recursos individuales ---
@@ -43,7 +51,7 @@ class Resource {
std::string name; // Nombre del 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) {}
};
@@ -51,7 +59,7 @@ class Resource {
std::string name; // Nombre de 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) {}
};
@@ -59,7 +67,7 @@ class Resource {
std::string name; // Nombre de 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)) {}
};
@@ -67,7 +75,7 @@ class Resource {
std::string name; // Nombre del fichero
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)) {}
};
@@ -75,7 +83,7 @@ class Resource {
std::string name; // Nombre del objeto
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)) {}
};
@@ -83,7 +91,7 @@ class Resource {
std::string name; // Nombre de la animación
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)) {}
};
@@ -102,6 +110,9 @@ class Resource {
}
};
// --- Modo de carga ---
LoadingMode loading_mode_;
// --- Vectores de recursos ---
std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las músicas
@@ -119,19 +130,33 @@ class Resource {
SDL_FRect loading_full_rect_;
// --- Métodos internos de carga y gestión ---
void loadSounds(); // Carga los sonidos
void loadMusics(); // Carga las músicas
void loadTextures(); // Carga las texturas
void loadTextFiles(); // Carga los ficheros de texto
void loadAnimations(); // Carga las animaciones
void loadDemoData(); // Carga los datos para el modo demostración
void addPalettes(); // Añade paletas a las texturas
void createTextures(); // Crea las texturas a partir de los datos cargados
void createText(); // Crea los objetos de texto
void clear(); // Vacía todos los vectores de recursos
void load(); // Carga todos los recursos
void clearSounds(); // Vacía el vector de sonidos
void clearMusics(); // Vacía el vector de músicas
void loadSounds(); // Carga los sonidos
void loadMusics(); // Carga las músicas
void loadTextures(); // Carga las texturas
void loadTextFiles(); // Carga los ficheros de texto
void loadAnimations(); // Carga las animaciones
void loadDemoData(); // Carga los datos para el modo demostración
void loadDemoDataQuiet(); // Carga los datos de demo sin mostrar progreso (para modo lazy)
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 clear(); // Vacía todos los vectores de recursos
void load(); // Carga todos los recursos
void clearSounds(); // Vacía el vector de sonidos
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 ---
void calculateTotalResources(); // Calcula el número de recursos para cargar
@@ -142,8 +167,8 @@ class Resource {
void updateProgressBar(); // Actualiza la barra de estado
// --- Constructores y destructor privados (singleton) ---
Resource(); // Constructor privado
~Resource(); // Destructor privado
explicit Resource(LoadingMode mode); // Constructor privado con modo de carga
~Resource(); // Destructor privado
// --- Instancia singleton ---
static Resource *instance; // Instancia única de Resource

View File

@@ -331,13 +331,19 @@ void Credits::initPlayers() {
// Texturas - Player1
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"));
player_textures.push_back(player1_textures);
// Texturas - Player2
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"));
player_textures.push_back(player2_textures);

View File

@@ -124,6 +124,7 @@ Game::~Game() {
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO;
Audio::get()->stopMusic();
}
ServiceMenu::get()->setStateChangeCallback(nullptr);
#ifdef RECORDING
saveDemoFile(Asset::get()->get("demo1.bin"), demo_.data.at(0));
@@ -162,13 +163,19 @@ void Game::setResources() {
player_textures_.clear();
// Texturas - Player1
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"));
player_textures_.push_back(player1_textures);
// Texturas - Player2
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"));
player_textures_.push_back(player2_textures);

View File

@@ -488,13 +488,19 @@ void Title::initPlayers() {
// Texturas - Player1
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"));
player_textures.push_back(player1_textures);
// Texturas - Player2
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"));
player_textures.push_back(player2_textures);

View File

@@ -1,28 +1,29 @@
#include "sprite.h"
#include <utility> // Para move
#include <vector> // Para vector
#include "texture.h" // Para Texture
// Constructor
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}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: texture_(std::move(texture)),
: textures_{texture},
pos_(rect),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(std::move(texture)),
pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}),
: textures_{texture},
pos_(SDL_FRect{0, 0, static_cast<float>(textures_.at(texture_index_)->getWidth()), static_cast<float>(textures_.at(texture_index_)->getHeight())}),
sprite_clip_(pos_) {}
// Muestra el sprite por pantalla
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
@@ -41,4 +42,13 @@ void Sprite::setPosition(SDL_FPoint point) {
void Sprite::clear() {
pos_ = {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 <memory> // Para shared_ptr
#include <vector> // Para vector
class Texture;
@@ -49,13 +50,22 @@ class Sprite {
void setSpriteClip(float pos_x, float pos_y, float width, float height) { sprite_clip_ = SDL_FRect{pos_x, pos_y, width, height}; }
// --- Textura ---
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return texture_; }
void setTexture(std::shared_ptr<Texture> texture) { texture_ = texture; }
[[nodiscard]] auto getTexture() const -> std::shared_ptr<Texture> { return textures_.at(texture_index_); }
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:
std::shared_ptr<Texture>& getTextureRef() {
return textures_.at(texture_index_);
}
// --- Variables internas ---
std::shared_ptr<Texture> texture_; // Textura donde están todos los dibujos del 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
double zoom_ = 1.0F; // Zoom aplicado a la textura
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 sprite_clip_; // Rectángulo de origen de la textura que se dibujará en pantalla
double zoom_ = 1.0F; // Zoom aplicado a la textura
};

View File

@@ -13,25 +13,33 @@
// --- Implementación de las estructuras de animación ---
void MenuRenderer::ResizeAnimation::start(float from_w, float from_h, float to_w, float to_h) {
start_width = from_w; start_height = from_h;
target_width = to_w; target_height = to_h;
start_width = from_w;
start_height = from_h;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F;
active = true;
}
void MenuRenderer::ResizeAnimation::stop() { active = false;
void MenuRenderer::ResizeAnimation::stop() {
active = false;
elapsed = 0.0F;
}
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;
active = true;
}
void MenuRenderer::ShowHideAnimation::startHide() { type = Type::HIDING;
void MenuRenderer::ShowHideAnimation::startHide() {
type = Type::HIDING;
elapsed = 0.0F;
active = true;
}
void MenuRenderer::ShowHideAnimation::stop() { type = Type::NONE; active = false;
void MenuRenderer::ShowHideAnimation::stop() {
type = Type::NONE;
active = false;
elapsed = 0.0F;
}
@@ -62,7 +70,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b, 255);
SDL_RenderRect(Screen::get()->getRenderer(), &rect_);
SDL_RenderRect(Screen::get()->getRenderer(), &border_rect_);
// Solo renderizar contenido si la animación lo permite
if (shouldShowContent()) {
// Dibuja el título
@@ -101,7 +109,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
void MenuRenderer::update(const ServiceMenu *menu_state) {
float delta_time = 1.0F / 60.0F; // Asumiendo 60 FPS
updateAnimations(delta_time);
if (visible_) {
updateColorCounter();
param.service_menu.selected_color = getAnimatedSelectedColor();
@@ -110,7 +118,7 @@ void MenuRenderer::update(const ServiceMenu *menu_state) {
// --- Nuevos métodos de control ---
void MenuRenderer::show(const ServiceMenu* menu_state) {
void MenuRenderer::show(const ServiceMenu *menu_state) {
if (visible_) {
return;
}
@@ -118,13 +126,13 @@ void MenuRenderer::show(const ServiceMenu* menu_state) {
// Calcula el tamaño final y lo usa para la animación
SDL_FRect target_rect = calculateNewRect(menu_state);
// Detener cualquier animación anterior
resize_animation_.stop();
// Iniciar animación de mostrar
show_hide_animation_.startShow(target_rect.w, target_rect.h);
// El tamaño inicial es cero para la animación
rect_.w = 0.0F;
rect_.h = 0.0F;
@@ -194,14 +202,13 @@ auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect
const auto &display_options = menu_state->getDisplayOptions();
lower_height_ = ((!display_options.empty() ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
height_ = std::min(upper_height_ + lower_height_, max_menu_height_);
SDL_FRect new_rect = {0, 0, (float)width_, (float)height_};
// La posición x, y se establecerá en `updatePosition`
return new_rect;
}
void MenuRenderer::resize(const ServiceMenu *menu_state) {
SDL_FRect new_rect = calculateNewRect(menu_state);
@@ -219,7 +226,7 @@ void MenuRenderer::setSize(const ServiceMenu *menu_state) {
SDL_FRect new_rect = calculateNewRect(menu_state);
rect_.w = new_rect.w;
rect_.h = new_rect.h;
show_hide_animation_.stop();
resize_animation_.stop();
@@ -242,7 +249,7 @@ void MenuRenderer::updateAnimations(float delta_time) {
void MenuRenderer::updateShowHideAnimation(float delta_time) {
show_hide_animation_.elapsed += delta_time;
float duration = show_hide_animation_.duration;
if (show_hide_animation_.elapsed >= duration) {
if (show_hide_animation_.type == ShowHideAnimation::Type::SHOWING) {
rect_.w = show_hide_animation_.target_width;
@@ -286,7 +293,6 @@ void MenuRenderer::updateResizeAnimation(float delta_time) {
options_y_ = rect_.y + upper_height_ + lower_padding_;
}
void MenuRenderer::updatePosition() {
switch (position_mode_) {
case PositionMode::CENTERED:

View File

@@ -37,7 +37,7 @@ class MenuRenderer {
// --- Nuevos: Métodos de configuración de posición ---
void setPosition(float x, float y, PositionMode mode);
// Método para notificar al renderer que el layout puede haber cambiado
void onLayoutChanged(const ServiceMenu *menu_state);
void setLayout(const ServiceMenu *menu_state);
@@ -77,27 +77,29 @@ class MenuRenderer {
// --- Estructuras de Animación (inspirado en WindowMessage) ---
struct ResizeAnimation {
bool active = false;
float start_width, start_height;
float target_width, target_height;
float elapsed = 0.0F;
float duration = 0.2F;
bool active = false;
float start_width, start_height;
float target_width, target_height;
float elapsed = 0.0F;
float duration = 0.2F;
void start(float from_w, float from_h, float to_w, float to_h);
void stop();
void start(float from_w, float from_h, float to_w, float to_h);
void stop();
} resize_animation_;
struct ShowHideAnimation {
enum class Type { NONE, SHOWING, HIDING };
Type type = Type::NONE;
bool active = false;
float target_width, target_height;
float elapsed = 0.0F;
float duration = 0.25F;
enum class Type { NONE,
SHOWING,
HIDING };
Type type = Type::NONE;
bool active = false;
float target_width, target_height;
float elapsed = 0.0F;
float duration = 0.25F;
void startShow(float to_w, float to_h);
void startHide();
void stop();
void startShow(float to_w, float to_h);
void startHide();
void stop();
} show_hide_animation_;
// --- Anchos precalculados ---
@@ -109,7 +111,7 @@ class MenuRenderer {
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
void resize(const ServiceMenu *menu_state);
void setSize(const ServiceMenu *menu_state);
void updateAnimations(float delta_time);
void updateResizeAnimation(float delta_time);
void updateShowHideAnimation(float delta_time);

View File

@@ -49,7 +49,7 @@ void ServiceMenu::toggle() {
}
playBackSound();
if (!enabled_) { // Si está cerrado, abrir
reset();
Options::gamepad_manager.assignAndLinkGamepads();

View File

@@ -26,13 +26,11 @@ void WindowMessage::render() {
SDL_Renderer* renderer = Screen::get()->getRenderer();
// Dibujar fondo con transparencia
SDL_SetRenderDrawColor(renderer, config_.bg_color.r, config_.bg_color.g,
config_.bg_color.b, config_.bg_color.a);
SDL_SetRenderDrawColor(renderer, config_.bg_color.r, config_.bg_color.g, config_.bg_color.b, config_.bg_color.a);
SDL_RenderFillRect(renderer, &rect_);
// Dibujar borde
SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g,
config_.border_color.b, config_.border_color.a);
SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g, config_.border_color.b, config_.border_color.a);
SDL_RenderRect(renderer, &rect_);
// 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)
if (!visible_title.empty()) {
SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g,
config_.border_color.b, config_.border_color.a);
SDL_SetRenderDrawColor(renderer, config_.border_color.r, config_.border_color.g, config_.border_color.b, config_.border_color.a);
SDL_RenderLine(renderer,
rect_.x + config_.padding,
current_y - config_.title_separator_spacing / 2.0F,
@@ -91,34 +88,34 @@ void WindowMessage::update() {
void WindowMessage::show() {
if (visible_) {
return; // Ya visible
return; // Ya visible
}
visible_ = true;
ensureTextFits();
// Detener cualquier animación anterior
resize_animation_.stop();
// Iniciar animación de mostrar desde tamaño 0
show_hide_animation_.startShow(rect_.w, rect_.h);
rect_.w = 0.0F;
rect_.h = 0.0F;
updatePosition(); // Reposicionar con tamaño 0
updatePosition(); // Reposicionar con tamaño 0
}
void WindowMessage::hide() {
if (!visible_) {
return; // Ya oculto
return; // Ya oculto
}
// Detener cualquier animación anterior
resize_animation_.stop();
// Guardar el tamaño actual para la animación
show_hide_animation_.target_width = rect_.w;
show_hide_animation_.target_height = rect_.h;
// Iniciar animación de ocultar hacia tamaño 0
show_hide_animation_.startHide();
}
@@ -158,7 +155,7 @@ void WindowMessage::setPosition(float x, float y, PositionMode mode) {
void WindowMessage::setSize(float width, float height) {
rect_.w = width;
rect_.h = height;
updatePosition(); // Reposicionar después de cambiar el tamaño
updatePosition(); // Reposicionar después de cambiar el tamaño
}
void WindowMessage::centerOnScreen() {
@@ -167,18 +164,18 @@ void WindowMessage::centerOnScreen() {
void WindowMessage::autoSize() {
if (show_hide_animation_.active) {
return; // No redimensionar durante show/hide
return; // No redimensionar durante show/hide
}
if (resize_animation_.active) {
resize_animation_.stop(); // Detener animación anterior
resize_animation_.stop(); // Detener animación anterior
}
float old_width = rect_.w;
float old_height = rect_.h;
calculateAutoSize();
// Solo animar si hay cambio en el tamaño y la ventana está visible
if (visible_ && (old_width != rect_.w || old_height != rect_.h)) {
resize_animation_.start(old_width, old_height, rect_.w, rect_.h);
@@ -186,21 +183,19 @@ void WindowMessage::autoSize() {
rect_.w = old_width;
rect_.h = old_height;
} else {
updatePosition(); // Reposicionar después de ajustar el tamaño
updatePosition(); // Reposicionar después de ajustar el tamaño
}
}
void WindowMessage::updateStyles() {
title_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.title_color,
config_.title_color, 0, -2);
text_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.text_color,
config_.text_color, 0, -2);
title_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.title_color, config_.title_color, 0, -2);
text_style_ = Text::Style(Text::CENTER | Text::COLOR, config_.text_color, config_.text_color, 0, -2);
}
void WindowMessage::updatePosition() {
switch (position_mode_) {
case PositionMode::CENTERED:
rect_.x = anchor_.x- rect_.w / 2.0F;
rect_.x = anchor_.x - rect_.w / 2.0F;
rect_.y = anchor_.y - rect_.h / 2.0F;
break;
case PositionMode::FIXED:
@@ -217,10 +212,10 @@ void WindowMessage::updatePosition() {
void WindowMessage::ensureTextFits() {
float required_width = calculateContentWidth() + (config_.padding * 2) + config_.text_safety_margin;
float required_height = calculateContentHeight() + (config_.padding * 2) + config_.text_safety_margin;
// Verificar si el tamaño actual es suficiente
if (rect_.w < required_width || rect_.h < required_height) {
autoSize(); // Recalcular tamaño automáticamente
autoSize(); // Recalcular tamaño automáticamente
}
}
@@ -239,7 +234,7 @@ void WindowMessage::calculateAutoSize() {
// Aplicar límites máximos basados en el tamaño de pantalla
float max_width = getScreenWidth() * config_.max_width_ratio;
float max_height = getScreenHeight() * config_.max_height_ratio;
rect_.w = std::min(rect_.w, max_width);
rect_.h = std::min(rect_.h, max_height);
}
@@ -264,7 +259,7 @@ auto WindowMessage::calculateContentHeight() const -> float {
}
auto WindowMessage::calculateContentWidth() const -> float {
float max_width = config_.min_width - (config_.padding * 2); // Ancho mínimo sin padding
float max_width = config_.min_width - (config_.padding * 2); // Ancho mínimo sin padding
// Ancho del título
if (!title_.empty()) {
@@ -299,7 +294,7 @@ void WindowMessage::updateAnimation(float delta_time) {
if (show_hide_animation_.active) {
updateShowHideAnimation(delta_time);
}
if (resize_animation_.active) {
updateResizeAnimation(delta_time);
}
@@ -309,9 +304,9 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
if (!show_hide_animation_.active) {
return;
}
show_hide_animation_.elapsed += delta_time;
if (show_hide_animation_.isFinished(config_.animation_duration)) {
// Animación terminada
if (show_hide_animation_.type == ShowHideAnimation::Type::SHOWING) {
@@ -324,13 +319,13 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
rect_.h = 0.0F;
visible_ = false;
}
show_hide_animation_.stop();
updatePosition();
} else {
// Interpolar el tamaño
float progress = easeOut(show_hide_animation_.getProgress(config_.animation_duration));
if (show_hide_animation_.type == ShowHideAnimation::Type::SHOWING) {
// Crecer desde 0 hasta el tamaño objetivo
rect_.w = show_hide_animation_.target_width * progress;
@@ -340,8 +335,8 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
rect_.w = show_hide_animation_.target_width * (1.0F - progress);
rect_.h = show_hide_animation_.target_height * (1.0F - progress);
}
updatePosition(); // Mantener la posición centrada durante la animación
updatePosition(); // Mantener la posición centrada durante la animación
}
}
@@ -349,9 +344,9 @@ void WindowMessage::updateResizeAnimation(float delta_time) {
if (!resize_animation_.active) {
return;
}
resize_animation_.elapsed += delta_time;
if (resize_animation_.isFinished(config_.animation_duration)) {
// Animación terminada
rect_.w = resize_animation_.target_width;
@@ -361,13 +356,13 @@ void WindowMessage::updateResizeAnimation(float delta_time) {
} else {
// Interpolar el tamaño
float progress = easeOut(resize_animation_.getProgress(config_.animation_duration));
rect_.w = resize_animation_.start_width +
(resize_animation_.target_width - resize_animation_.start_width) * progress;
rect_.h = resize_animation_.start_height +
(resize_animation_.target_height - resize_animation_.start_height) * progress;
updatePosition(); // Mantener la posición centrada durante la animación
rect_.w = resize_animation_.start_width +
(resize_animation_.target_width - resize_animation_.start_width) * progress;
rect_.h = resize_animation_.start_height +
(resize_animation_.target_height - resize_animation_.start_height) * progress;
updatePosition(); // Mantener la posición centrada durante la animación
}
}
@@ -390,13 +385,13 @@ auto WindowMessage::getTruncatedText(const std::string& text, float available_wi
if (text.empty()) {
return text;
}
// Si el texto completo cabe, devolverlo tal como está
int text_width = text_renderer_->length(text, -2);
if (text_width <= available_width) {
return text;
}
// Si no hay espacio suficiente, devolver string vacío
if (available_width < 10.0F) { // Mínimo espacio para al menos un carácter
return "";
@@ -406,12 +401,12 @@ auto WindowMessage::getTruncatedText(const std::string& text, float available_wi
int left = 0;
int right = text.length();
int best_length = 0;
while (left <= right) {
int mid = (left + right) / 2;
std::string partial = text.substr(0, mid);
int partial_width = text_renderer_->length(partial, -2);
if (partial_width <= available_width) {
best_length = mid;
left = mid + 1;
@@ -419,6 +414,6 @@ auto WindowMessage::getTruncatedText(const std::string& text, float available_wi
right = mid - 1;
}
}
return text.substr(0, best_length);
}

View File

@@ -7,7 +7,7 @@
#include <vector>
#include "color.h"
#include "text.h"
#include "text.h"
class WindowMessage {
public:
@@ -17,34 +17,34 @@ class WindowMessage {
};
struct Config {
// Colores
Color bg_color;
Color border_color;
Color title_color;
Color text_color;
// Espaciado y dimensiones
float padding{15.0f};
float line_spacing{5.0f};
float title_separator_spacing{10.0f}; // Espacio extra para separador del título
// Colores
Color bg_color;
Color border_color;
Color title_color;
Color text_color;
// Límites de tamaño
float min_width{200.0f};
float min_height{100.0f};
float max_width_ratio{0.8f}; // % máximo de ancho de pantalla
float max_height_ratio{0.8f}; // % máximo de alto de pantalla
// Espaciado y dimensiones
float padding{15.0f};
float line_spacing{5.0f};
float title_separator_spacing{10.0f}; // Espacio extra para separador del título
// Margen de seguridad para texto
float text_safety_margin{20.0f}; // Margen extra para evitar texto cortado
// Límites de tamaño
float min_width{200.0f};
float min_height{100.0f};
float max_width_ratio{0.8f}; // % máximo de ancho de pantalla
float max_height_ratio{0.8f}; // % máximo de alto de pantalla
// Animaciones
float animation_duration{0.3f}; // Duración en segundos para todas las animaciones
// Margen de seguridad para texto
float text_safety_margin{20.0f}; // Margen extra para evitar texto cortado
// Constructor con valores por defecto
Config()
: bg_color{40, 40, 60, 220}, border_color{100, 100, 120, 255}, title_color{255, 255, 255, 255}, text_color{200, 200, 200, 255}
// Animaciones
float animation_duration{0.3f}; // Duración en segundos para todas las animaciones
{}
// Constructor con valores por defecto
Config()
: bg_color{40, 40, 60, 220}, border_color{100, 100, 120, 255}, title_color{255, 255, 255, 255}, text_color{200, 200, 200, 255}
{}
};
WindowMessage(
@@ -69,7 +69,7 @@ class WindowMessage {
void setTexts(const std::vector<std::string>& texts);
void addText(const std::string& text);
void clearTexts();
// Control de redimensionado automático
void enableAutoResize(bool enabled) { auto_resize_enabled_ = enabled; }
[[nodiscard]] auto isAutoResizeEnabled() const -> bool { return auto_resize_enabled_; }
@@ -78,20 +78,29 @@ class WindowMessage {
void setPosition(float x, float y, PositionMode mode = PositionMode::CENTERED);
void setSize(float width, float height);
void centerOnScreen();
void autoSize(); // Ajusta automáticamente al contenido y reposiciona si es necesario
void autoSize(); // Ajusta automáticamente al contenido y reposiciona si es necesario
// Configuración de colores
void setBackgroundColor(const Color& color) { config_.bg_color = color; }
void setBorderColor(const Color& color) { config_.border_color = color; }
void setTitleColor(const Color& color) { config_.title_color = color; updateStyles(); }
void setTextColor(const Color& color) { config_.text_color = color; updateStyles(); }
void setTitleColor(const Color& color) {
config_.title_color = color;
updateStyles();
}
void setTextColor(const Color& color) {
config_.text_color = color;
updateStyles();
}
// Configuración de espaciado
void setPadding(float padding) { config_.padding = padding; }
void setLineSpacing(float spacing) { config_.line_spacing = spacing; }
// 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_; }
// Getters
@@ -102,15 +111,15 @@ class WindowMessage {
private:
std::shared_ptr<Text> text_renderer_;
Config config_;
// Estado de visibilidad y redimensionado
bool visible_ = false;
bool auto_resize_enabled_ = true; // Por defecto habilitado
bool auto_resize_enabled_ = true; // Por defecto habilitado
// Contenido
std::string title_;
std::vector<std::string> texts_;
// Posición y tamaño
SDL_FRect rect_{0, 0, 300, 200};
PositionMode position_mode_ = PositionMode::CENTERED;
@@ -118,94 +127,96 @@ class WindowMessage {
// Animación de redimensionado
struct ResizeAnimation {
bool active = false;
float start_width, start_height;
float target_width, target_height;
float elapsed = 0.0F;
bool active = false;
float start_width, start_height;
float target_width, target_height;
float elapsed = 0.0F;
void start(float from_w, float from_h, float to_w, float to_h) {
start_width = from_w;
start_height = from_h;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F;
active = true;
}
void stop() {
active = false;
elapsed = 0.0F;
}
[[nodiscard]] auto isFinished(float duration) const -> bool {
return elapsed >= duration;
}
[[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0F);
}
void start(float from_w, float from_h, float to_w, float to_h) {
start_width = from_w;
start_height = from_h;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F;
active = true;
}
void stop() {
active = false;
elapsed = 0.0F;
}
[[nodiscard]] auto isFinished(float duration) const -> bool {
return elapsed >= duration;
}
[[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0F);
}
} resize_animation_;
// Animación de mostrar/ocultar
struct ShowHideAnimation {
enum class Type { NONE, SHOWING, HIDING };
Type type = Type::NONE;
bool active = false;
float target_width, target_height; // Tamaño final al mostrar
float elapsed = 0.0F;
enum class Type { NONE,
SHOWING,
HIDING };
void startShow(float to_w, float to_h) {
type = Type::SHOWING;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F;
active = true;
}
void startHide() {
type = Type::HIDING;
elapsed = 0.0F;
active = true;
}
void stop() {
type = Type::NONE;
active = false;
elapsed = 0.0F;
}
[[nodiscard]] auto isFinished(float duration) const -> bool {
return elapsed >= duration;
}
[[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0F);
}
Type type = Type::NONE;
bool active = false;
float target_width, target_height; // Tamaño final al mostrar
float elapsed = 0.0F;
void startShow(float to_w, float to_h) {
type = Type::SHOWING;
target_width = to_w;
target_height = to_h;
elapsed = 0.0F;
active = true;
}
void startHide() {
type = Type::HIDING;
elapsed = 0.0F;
active = true;
}
void stop() {
type = Type::NONE;
active = false;
elapsed = 0.0F;
}
[[nodiscard]] auto isFinished(float duration) const -> bool {
return elapsed >= duration;
}
[[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0F);
}
} show_hide_animation_;
// Estilos
Text::Style title_style_;
Text::Style text_style_;
// Métodos privados
void calculateAutoSize();
void updatePosition(); // Actualiza la posición según el modo y punto de anclaje
void updateStyles(); // Actualiza los estilos de texto cuando cambian los colores
void ensureTextFits(); // Verifica y ajusta para que todo el texto sea visible
void triggerAutoResize(); // Inicia redimensionado automático si está habilitado
void updateAnimation(float delta_time); // Actualiza la animación de redimensionado
void updateShowHideAnimation(float delta_time); // Actualiza la animación de mostrar/ocultar
void updateResizeAnimation(float delta_time); // Actualiza la animación de redimensionado
void updatePosition(); // Actualiza la posición según el modo y punto de anclaje
void updateStyles(); // Actualiza los estilos de texto cuando cambian los colores
void ensureTextFits(); // Verifica y ajusta para que todo el texto sea visible
void triggerAutoResize(); // Inicia redimensionado automático si está habilitado
void updateAnimation(float delta_time); // Actualiza la animación de redimensionado
void updateShowHideAnimation(float delta_time); // Actualiza la animación de mostrar/ocultar
void updateResizeAnimation(float delta_time); // Actualiza la animación de redimensionado
// Función de suavizado (ease-out)
[[nodiscard]] static auto easeOut(float t) -> float;
// Métodos para manejo de texto durante animación
[[nodiscard]] auto getTruncatedText(const std::string& text, float available_width) const -> std::string;
[[nodiscard]] auto getAvailableTextWidth() const -> float;
[[nodiscard]] auto shouldShowContent() const -> bool; // Si mostrar el contenido (texto, líneas, etc.)
[[nodiscard]] auto shouldShowContent() const -> bool; // Si mostrar el contenido (texto, líneas, etc.)
[[nodiscard]] auto calculateContentHeight() const -> float;
[[nodiscard]] auto calculateContentWidth() const -> float;
[[nodiscard]] static auto getScreenWidth() -> float;