From 46974ef2eb699345bda98b35b6ffae41cc262fc2 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Fri, 17 Oct 2025 21:45:19 +0200 Subject: [PATCH] renombrades extensions .h a .hpp --- development_guidelines.md | 43 ------ source/animated_sprite.cpp | 14 +- ...{animated_sprite.h => animated_sprite.hpp} | 4 +- source/asset.cpp | 51 +++---- source/{asset.h => asset.hpp} | 30 ++--- source/asset_integrated.cpp | 22 +-- ...sset_integrated.h => asset_integrated.hpp} | 16 +-- source/audio.cpp | 14 +- source/{audio.h => audio.hpp} | 16 +-- source/background.cpp | 20 +-- source/{background.h => background.hpp} | 44 +++--- source/balloon.cpp | 12 +- source/{balloon.h => balloon.hpp} | 80 +++++------ source/balloon_formations.cpp | 18 +-- ...on_formations.h => balloon_formations.hpp} | 6 +- source/balloon_manager.cpp | 20 +-- ...{balloon_manager.h => balloon_manager.hpp} | 24 ++-- source/bullet.cpp | 8 +- source/{bullet.h => bullet.hpp} | 14 +- source/bullet_manager.cpp | 21 ++- .../{bullet_manager.h => bullet_manager.hpp} | 16 +-- source/color.cpp | 6 +- source/{color.h => color.hpp} | 13 +- source/{defaults.h => defaults.hpp} | 10 +- source/define_buttons.cpp | 38 +++--- .../{define_buttons.h => define_buttons.hpp} | 18 +-- source/demo.cpp | 19 +-- source/{demo.h => demo.hpp} | 5 +- source/difficulty.cpp | 2 +- source/{difficulty.h => difficulty.hpp} | 0 source/director.cpp | 58 ++++---- source/{director.h => director.hpp} | 8 +- source/enter_name.cpp | 6 +- source/{enter_name.h => enter_name.hpp} | 16 +-- source/explosions.cpp | 10 +- source/{explosions.h => explosions.hpp} | 10 +- source/external/gif.cpp | 2 +- source/external/{gif.h => gif.hpp} | 0 source/external/stb_image.h | 2 +- source/fade.cpp | 24 ++-- source/{fade.h => fade.hpp} | 4 +- source/game_logo.cpp | 32 +++-- source/game_logo.h | 125 ------------------ source/game_logo.hpp | 125 ++++++++++++++++++ ...g_manager.h => gamepad_config_manager.hpp} | 2 +- source/global_events.cpp | 24 ++-- source/{global_events.h => global_events.hpp} | 2 +- source/global_inputs.cpp | 22 +-- source/{global_inputs.h => global_inputs.hpp} | 0 source/{hit.h => hit.hpp} | 4 +- source/input.cpp | 90 ++++++------- source/{input.h => input.hpp} | 46 +++---- source/input_types.cpp | 2 +- source/{input_types.h => input_types.hpp} | 0 source/item.cpp | 6 +- source/{item.h => item.hpp} | 4 +- source/lang.cpp | 36 ++--- source/{lang.h => lang.hpp} | 6 +- source/main.cpp | 2 +- source/manage_hiscore_table.cpp | 20 +-- ...score_table.h => manage_hiscore_table.hpp} | 12 +- source/mouse.cpp | 4 +- source/{mouse.h => mouse.hpp} | 2 +- source/moving_sprite.cpp | 8 +- source/{moving_sprite.h => moving_sprite.hpp} | 2 +- source/options.cpp | 15 +-- source/{options.h => options.hpp} | 12 +- source/param.cpp | 12 +- source/{param.h => param.hpp} | 8 +- source/path_sprite.cpp | 35 ++--- source/{path_sprite.h => path_sprite.hpp} | 51 +++---- source/{pause_manager.h => pause_manager.hpp} | 0 source/player.cpp | 26 ++-- source/{player.h => player.hpp} | 16 +-- source/rendering/opengl/opengl_shader.cpp | 98 +++++++++----- source/rendering/opengl/opengl_shader.h | 98 -------------- source/rendering/opengl/opengl_shader.hpp | 98 ++++++++++++++ source/rendering/shader_backend.h | 55 -------- source/rendering/shader_backend.hpp | 56 ++++++++ source/resource.cpp | 16 +-- source/{resource.h => resource.hpp} | 46 +++---- source/resource_helper.cpp | 2 +- ...{resource_helper.h => resource_helper.hpp} | 2 +- source/resource_loader.cpp | 2 +- ...{resource_loader.h => resource_loader.hpp} | 2 +- source/resource_pack.cpp | 2 +- source/{resource_pack.h => resource_pack.hpp} | 0 source/scoreboard.cpp | 48 +++---- source/{scoreboard.h => scoreboard.hpp} | 14 +- source/screen.cpp | 46 +++---- source/{screen.h => screen.hpp} | 108 +++++++-------- source/sections/credits.cpp | 52 ++++---- source/sections/{credits.h => credits.hpp} | 72 +++++----- source/sections/game.cpp | 72 +++++----- source/sections/{game.h => game.hpp} | 30 ++--- source/sections/hiscore_table.cpp | 64 ++++----- .../{hiscore_table.h => hiscore_table.hpp} | 22 +-- source/sections/instructions.cpp | 34 ++--- .../{instructions.h => instructions.hpp} | 14 +- source/sections/intro.cpp | 34 ++--- source/sections/{intro.h => intro.hpp} | 10 +- source/sections/logo.cpp | 32 ++--- source/sections/{logo.h => logo.hpp} | 18 +-- source/sections/title.cpp | 49 +++---- source/sections/{title.h => title.hpp} | 10 +- source/{service_menu.h => service_menu.hpp} | 0 source/shutdown.cpp | 2 +- source/{shutdown.h => shutdown.hpp} | 0 source/smart_sprite.cpp | 4 +- source/{smart_sprite.h => smart_sprite.hpp} | 20 +-- source/sprite.cpp | 4 +- source/{sprite.h => sprite.hpp} | 0 source/stage.cpp | 2 +- source/{stage.h => stage.hpp} | 2 +- ...{stage_interface.h => stage_interface.hpp} | 0 source/system_utils.cpp | 2 +- source/{system_utils.h => system_utils.hpp} | 0 source/tabe.cpp | 11 +- source/{tabe.h => tabe.hpp} | 6 +- source/text.cpp | 70 +++++----- source/{text.h => text.hpp} | 38 +++--- source/texture.cpp | 52 ++++---- source/{texture.h => texture.hpp} | 36 ++--- source/tiled_bg.cpp | 11 +- source/{tiled_bg.h => tiled_bg.hpp} | 31 +++-- source/ui/logger.h | 70 ---------- source/ui/logger.hpp | 70 ++++++++++ source/ui/menu_option.cpp | 4 +- source/ui/{menu_option.h => menu_option.hpp} | 40 +++--- source/ui/menu_renderer.cpp | 50 +++---- .../ui/{menu_renderer.h => menu_renderer.hpp} | 32 ++--- source/ui/notifier.cpp | 16 +-- source/ui/{notifier.h => notifier.hpp} | 50 +++---- source/ui/service_menu.cpp | 86 ++++++------ .../ui/{service_menu.h => service_menu.hpp} | 26 ++-- source/ui/ui_message.cpp | 6 +- source/ui/{ui_message.h => ui_message.hpp} | 12 +- source/ui/window_message.cpp | 8 +- .../{window_message.h => window_message.hpp} | 6 +- source/utils.cpp | 35 +++-- source/{utils.h => utils.hpp} | 2 - source/version.h.in | 6 +- source/writer.cpp | 6 +- source/{writer.h => writer.hpp} | 24 ++-- 144 files changed, 1758 insertions(+), 1783 deletions(-) delete mode 100644 development_guidelines.md rename source/{animated_sprite.h => animated_sprite.hpp} (97%) rename source/{asset.h => asset.hpp} (73%) rename source/{asset_integrated.h => asset_integrated.hpp} (56%) rename source/{audio.h => audio.hpp} (88%) rename source/{background.h => background.hpp} (79%) rename source/{balloon.h => balloon.hpp} (79%) rename source/{balloon_formations.h => balloon_formations.hpp} (93%) rename source/{balloon_manager.h => balloon_manager.hpp} (88%) rename source/{bullet.h => bullet.hpp} (89%) rename source/{bullet_manager.h => bullet_manager.hpp} (87%) rename source/{color.h => color.hpp} (94%) rename source/{defaults.h => defaults.hpp} (97%) rename source/{define_buttons.h => define_buttons.hpp} (86%) rename source/{demo.h => demo.hpp} (95%) rename source/{difficulty.h => difficulty.hpp} (100%) rename source/{director.h => director.hpp} (86%) rename source/{enter_name.h => enter_name.hpp} (68%) rename source/{explosions.h => explosions.hpp} (84%) rename source/external/{gif.h => gif.hpp} (100%) rename source/{fade.h => fade.hpp} (98%) delete mode 100644 source/game_logo.h create mode 100644 source/game_logo.hpp rename source/{gamepad_config_manager.h => gamepad_config_manager.hpp} (98%) rename source/{global_events.h => global_events.hpp} (78%) rename source/{global_inputs.h => global_inputs.hpp} (100%) rename source/{hit.h => hit.hpp} (95%) rename source/{input.h => input.hpp} (88%) rename source/{input_types.h => input_types.hpp} (100%) rename source/{item.h => item.hpp} (98%) rename source/{lang.h => lang.hpp} (90%) rename source/{manage_hiscore_table.h => manage_hiscore_table.hpp} (77%) rename source/{mouse.h => mouse.hpp} (90%) rename source/{moving_sprite.h => moving_sprite.hpp} (99%) rename source/{options.h => options.hpp} (97%) rename source/{param.h => param.hpp} (98%) rename source/{path_sprite.h => path_sprite.hpp} (57%) rename source/{pause_manager.h => pause_manager.hpp} (100%) rename source/{player.h => player.hpp} (98%) delete mode 100644 source/rendering/opengl/opengl_shader.h create mode 100644 source/rendering/opengl/opengl_shader.hpp delete mode 100644 source/rendering/shader_backend.h create mode 100644 source/rendering/shader_backend.hpp rename source/{resource.h => resource.hpp} (84%) rename source/{resource_helper.h => resource_helper.hpp} (98%) rename source/{resource_loader.h => resource_loader.hpp} (97%) rename source/{resource_pack.h => resource_pack.hpp} (100%) rename source/{scoreboard.h => scoreboard.hpp} (95%) rename source/{screen.h => screen.hpp} (69%) rename source/sections/{credits.h => credits.hpp} (61%) rename source/sections/{game.h => game.hpp} (95%) rename source/sections/{hiscore_table.h => hiscore_table.hpp} (89%) rename source/sections/{instructions.h => instructions.hpp} (91%) rename source/sections/{intro.h => intro.hpp} (96%) rename source/sections/{logo.h => logo.hpp} (91%) rename source/sections/{title.h => title.hpp} (95%) rename source/{service_menu.h => service_menu.hpp} (100%) rename source/{shutdown.h => shutdown.hpp} (100%) rename source/{smart_sprite.h => smart_sprite.hpp} (71%) rename source/{sprite.h => sprite.hpp} (100%) rename source/{stage.h => stage.hpp} (99%) rename source/{stage_interface.h => stage_interface.hpp} (100%) rename source/{system_utils.h => system_utils.hpp} (100%) rename source/{tabe.h => tabe.hpp} (97%) rename source/{text.h => text.hpp} (75%) rename source/{texture.h => texture.hpp} (69%) rename source/{tiled_bg.h => tiled_bg.hpp} (73%) delete mode 100644 source/ui/logger.h create mode 100644 source/ui/logger.hpp rename source/ui/{menu_option.h => menu_option.hpp} (87%) rename source/ui/{menu_renderer.h => menu_renderer.hpp} (82%) rename source/ui/{notifier.h => notifier.hpp} (68%) rename source/ui/{service_menu.h => service_menu.hpp} (85%) rename source/ui/{ui_message.h => ui_message.hpp} (80%) rename source/ui/{window_message.h => window_message.hpp} (98%) rename source/{utils.h => utils.hpp} (99%) rename source/{writer.h => writer.hpp} (67%) diff --git a/development_guidelines.md b/development_guidelines.md deleted file mode 100644 index 1f67463..0000000 --- a/development_guidelines.md +++ /dev/null @@ -1,43 +0,0 @@ -# Directrices de Desarrollo - Coffee Crisis Arcade Edition - -## Directrices Principales Confirmadas - -### 1. **Sistema Temporal** -- **TODO migrado de frame based a time based** -- **Delta time en segundos (float)** -- **Unidades de tiempo: SOLO segundos** (no frames, no milisegundos) - -### 2. **Contadores y Timers** -- **CRECIENTES**: para sistemas con múltiples eventos temporales (timeline) - - Patrón: `elapsed_time += deltaTime; if (elapsed_time >= EVENT_TIME) { /* acción */ }` -- **DECRECIENTES**: para contadores con diferentes valores de inicialización - - Patrón: `timer -= deltaTime; if (timer <= 0.0f) { /* acción */ timer = DURATION; }` - -### 3. **Números Mágicos** -- **Definidos en constantes** -- **Preferencia**: cabecera de la clase -- **Excepción**: si es algo local a un método específico - -## Problemas Pendientes de Reparación (game.cpp) - -### ❌ PENDIENTES -1. **param.fade.post_duration_ms verification** (líneas 89, 1671) -2. **setRotateSpeed verification** (línea 797) -3. **TOTAL_DEMO_DATA - 200 magic number** (línea 1669) -4. **Comprehensive magic number search** - Buscar 100, 150, 200, 250, 300, 400, 500, 1000 - -### 4. **Velocidades y Aceleraciones** -- **Velocidades**: pixels/segundo -- **Aceleraciones**: pixels/segundo² - -### 5. **Documentación de Conversiones** -- **Comentarios explicativos** en cambios críticos de timing -- Documentar conversiones frame→tiempo en el código - -### 6. **Patrón de Constantes** -- Crear constantes para valores repetidos (evitar duplicación) -- Nombres descriptivos para constantes de tiempo - ---- - -**Estado**: Directrices completas confirmadas \ No newline at end of file diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 3e0d823..d93669f 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -1,4 +1,4 @@ -#include "animated_sprite.h" +#include "animated_sprite.hpp" #include // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError, SDL_FRect @@ -9,9 +9,9 @@ #include // Para runtime_error #include // Para pair -#include "resource_helper.h" // Para ResourceHelper -#include "texture.h" // Para Texture -#include "utils.h" // Para printWithDots +#include "resource_helper.hpp" // Para ResourceHelper +#include "texture.hpp" // Para Texture +#include "utils.hpp" // Para printWithDots // Carga las animaciones en un vector(Animations) desde un fichero auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer { @@ -94,12 +94,12 @@ void AnimatedSprite::animate(float deltaTime) { // Acumular tiempo transcurrido animations_[current_animation_].time_accumulator += deltaTime; - + // Verificar si es momento de cambiar frame if (animations_[current_animation_].time_accumulator >= animations_[current_animation_].speed) { animations_[current_animation_].time_accumulator -= animations_[current_animation_].speed; animations_[current_animation_].current_frame++; - + // Si alcanza el final de la animación if (animations_[current_animation_].current_frame >= animations_[current_animation_].frames.size()) { if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame @@ -110,7 +110,7 @@ void AnimatedSprite::animate(float deltaTime) { animations_[current_animation_].current_frame = animations_[current_animation_].loop; } } - + // Actualizar el sprite clip updateSpriteClip(); } diff --git a/source/animated_sprite.h b/source/animated_sprite.hpp similarity index 97% rename from source/animated_sprite.h rename to source/animated_sprite.hpp index 2d3475a..2c44e7d 100644 --- a/source/animated_sprite.h +++ b/source/animated_sprite.hpp @@ -10,7 +10,7 @@ #include #include // Para vector -#include "moving_sprite.h" // Para MovingSprite +#include "moving_sprite.hpp" // Para MovingSprite // Declaración adelantada class Texture; @@ -55,7 +55,7 @@ class AnimatedSprite : public MovingSprite { ~AnimatedSprite() override = default; // --- Métodos principales --- - void update(float deltaTime) override; // Actualiza la animación (time-based) + void update(float deltaTime) override; // Actualiza la animación (time-based) // --- Control de animaciones --- void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre diff --git a/source/asset.cpp b/source/asset.cpp index baf9810..c1f7bf7 100644 --- a/source/asset.cpp +++ b/source/asset.cpp @@ -1,4 +1,4 @@ -#include "asset.h" +#include "asset.hpp" #include // Para SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn @@ -10,14 +10,14 @@ #include // Para basic_istringstream #include // Para runtime_error -#include "resource_helper.h" // Para ResourceHelper -#include "utils.h" // Para getFileName -#include "ui/logger.h" // Pâra Logger +#include "resource_helper.hpp" // Para ResourceHelper +#include "ui/logger.hpp" // Pâra Logger +#include "utils.hpp" // Para getFileName // Singleton -Asset *Asset::instance = nullptr; +Asset* Asset::instance = nullptr; -void Asset::init(const std::string &executable_path) { +void Asset::init(const std::string& executable_path) { Asset::instance = new Asset(executable_path); } @@ -25,12 +25,12 @@ void Asset::destroy() { delete Asset::instance; } -auto Asset::get() -> Asset * { +auto Asset::get() -> Asset* { return Asset::instance; } // Añade un elemento al mapa (función auxiliar) -void Asset::addToMap(const std::string &file_path, Type type, bool required, bool absolute) { +void 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); @@ -45,13 +45,13 @@ void Asset::addToMap(const std::string &file_path, Type type, bool required, boo } // Añade un elemento a la lista -void Asset::add(const std::string &file_path, Type type, bool required, bool absolute) { +void Asset::add(const std::string& file_path, Type type, bool required, bool absolute) { addToMap(file_path, type, required, absolute); } // Carga recursos desde un archivo de configuración con soporte para variables // Carga recursos desde un archivo de configuración con soporte para variables -void Asset::loadFromFile(const std::string &config_file_path, const std::string &prefix, const std::string &system_folder) { +void 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, @@ -96,7 +96,7 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string } try { - const std::string &type_str = parts[0]; + const std::string& type_str = parts[0]; std::string path = parts[1]; // Valores por defecto @@ -117,7 +117,7 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string // Añadir al mapa addToMap(path, type, required, absolute); - } catch (const std::exception &e) { + } catch (const std::exception& e) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error parsing line %d in config file: %s", line_number, @@ -133,7 +133,7 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string } // Devuelve la ruta completa a un fichero (búsqueda O(1)) -auto Asset::get(const std::string &filename) const -> std::string { +auto Asset::get(const std::string& filename) const -> std::string { auto it = file_list_.find(filename); if (it != file_list_.end()) { return it->second.file; @@ -144,7 +144,7 @@ auto Asset::get(const std::string &filename) const -> std::string { } // Carga datos del archivo usando ResourceHelper -auto Asset::loadData(const std::string &filename) const -> std::vector { +auto Asset::loadData(const std::string& filename) const -> std::vector { auto it = file_list_.find(filename); if (it != file_list_.end()) { return ResourceHelper::loadFile(it->second.file); @@ -155,7 +155,7 @@ auto Asset::loadData(const std::string &filename) const -> std::vector } // Verifica si un recurso existe -auto Asset::exists(const std::string &filename) const -> bool { +auto Asset::exists(const std::string& filename) const -> bool { return file_list_.find(filename) != file_list_.end(); } @@ -163,13 +163,13 @@ auto Asset::exists(const std::string &filename) const -> bool { auto Asset::check() const -> bool { bool success = true; - //SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES"); + // SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES"); Logger::section("CHECKING FILES", Logger::CYAN); // Agrupar por tipo para mostrar organizado - std::unordered_map> by_type; + std::unordered_map> by_type; - for (const auto &[filename, item] : file_list_) { + for (const auto& [filename, item] : file_list_) { if (item.required) { by_type[item.type].push_back(&item); } @@ -185,7 +185,7 @@ auto Asset::check() const -> bool { getTypeName(asset_type).c_str()); bool type_success = true; - for (const auto *item : by_type[asset_type]) { + for (const auto* item : by_type[asset_type]) { if (!checkFile(item->file)) { success = false; type_success = false; @@ -209,7 +209,7 @@ auto Asset::check() const -> bool { } // Comprueba que existe un fichero -auto Asset::checkFile(const std::string &path) const -> bool { +auto Asset::checkFile(const std::string& path) const -> bool { // Construir ruta del pack usando executable_path_ std::string pack_path = executable_path_ + "resources.pack"; bool pack_exists = std::filesystem::exists(pack_path); @@ -226,7 +226,8 @@ auto Asset::checkFile(const std::string &path) const -> bool { if (!success) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error: Could not open file: %s", path.c_str()); + "Error: Could not open file: %s", + path.c_str()); } return success; @@ -234,7 +235,7 @@ auto Asset::checkFile(const std::string &path) const -> bool { } // Parsea string a Type -auto Asset::parseAssetType(const std::string &type_str) -> Type { +auto Asset::parseAssetType(const std::string& type_str) -> Type { if (type_str == "BITMAP") { return Type::BITMAP; } @@ -296,7 +297,7 @@ auto Asset::getTypeName(Type type) -> std::string { auto Asset::getListByType(Type type) const -> std::vector { std::vector list; - for (const auto &[filename, item] : file_list_) { + for (const auto& [filename, item] : file_list_) { if (item.type == type) { list.push_back(item.file); } @@ -309,7 +310,7 @@ auto Asset::getListByType(Type type) const -> std::vector { } // Reemplaza variables en las rutas -auto Asset::replaceVariables(const std::string &path, const std::string &prefix, const std::string &system_folder) -> std::string { +auto Asset::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string { std::string result = path; // Reemplazar ${PREFIX} @@ -330,7 +331,7 @@ auto Asset::replaceVariables(const std::string &path, const std::string &prefix, } // Parsea las opciones de una línea de configuración -auto Asset::parseOptions(const std::string &options, bool &required, bool &absolute) -> void { +auto Asset::parseOptions(const std::string& options, bool& required, bool& absolute) -> void { if (options.empty()) { return; } diff --git a/source/asset.h b/source/asset.hpp similarity index 73% rename from source/asset.h rename to source/asset.hpp index c279f06..df36c49 100644 --- a/source/asset.h +++ b/source/asset.hpp @@ -24,20 +24,20 @@ class Asset { }; // --- Métodos de singleton --- - static void init(const std::string &executable_path); + static void init(const std::string& executable_path); static void destroy(); - static auto get() -> Asset *; - Asset(const Asset &) = delete; - auto operator=(const Asset &) -> Asset & = delete; + static auto get() -> Asset*; + Asset(const Asset&) = delete; + auto operator=(const Asset&) -> Asset& = delete; // --- 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 loadData(const std::string &filename) const -> std::vector; // Carga datos del archivo + 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 loadData(const std::string& filename) const -> std::vector; // Carga datos del archivo [[nodiscard]] auto check() const -> bool; [[nodiscard]] auto getListByType(Type type) const -> std::vector; - [[nodiscard]] auto exists(const std::string &filename) const -> bool; // Nueva función para verificar existencia + [[nodiscard]] auto exists(const std::string& filename) const -> bool; // Nueva función para verificar existencia private: // --- Estructuras privadas --- @@ -57,12 +57,12 @@ class Asset { std::string executable_path_; // Ruta del ejecutable // --- Métodos internos --- - [[nodiscard]] auto checkFile(const std::string &path) const -> bool; // Verifica si un archivo existe + [[nodiscard]] auto checkFile(const std::string& path) const -> bool; // Verifica si un archivo existe [[nodiscard]] static auto getTypeName(Type type) -> std::string; // Obtiene el nombre del tipo - [[nodiscard]] static auto parseAssetType(const std::string &type_str) -> Type; // Convierte string a tipo - void addToMap(const std::string &file_path, Type type, bool required, bool absolute); // Añade archivo al mapa - [[nodiscard]] static auto replaceVariables(const std::string &path, const std::string &prefix, const std::string &system_folder) -> std::string; // Reemplaza variables en la ruta - static auto parseOptions(const std::string &options, bool &required, bool &absolute) -> void; // Parsea opciones + [[nodiscard]] static auto parseAssetType(const std::string& type_str) -> Type; // Convierte string a tipo + void addToMap(const std::string& file_path, Type type, bool required, bool absolute); // Añade archivo al mapa + [[nodiscard]] static auto replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string; // Reemplaza variables en la ruta + static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones // --- Constructores y destructor privados (singleton) --- explicit Asset(std::string executable_path) // Constructor privado @@ -70,5 +70,5 @@ class Asset { ~Asset() = default; // Destructor privado // --- Instancia singleton --- - static Asset *instance; // Instancia única de Asset + static Asset* instance; // Instancia única de Asset }; \ No newline at end of file diff --git a/source/asset_integrated.cpp b/source/asset_integrated.cpp index a657253..76af270 100644 --- a/source/asset_integrated.cpp +++ b/source/asset_integrated.cpp @@ -1,4 +1,4 @@ -#include "asset_integrated.h" +#include "asset_integrated.hpp" #include #include @@ -6,13 +6,13 @@ bool AssetIntegrated::resource_pack_enabled_ = false; -void AssetIntegrated::initWithResourcePack(const std::string &executable_path, - const std::string &resource_pack_path) { +void AssetIntegrated::initWithResourcePack(const std::string& executable_path, + const std::string& resource_pack_path) { // Inicializar Asset normal Asset::init(executable_path); // Inicializar ResourceLoader - auto &loader = ResourceLoader::getInstance(); + auto& loader = ResourceLoader::getInstance(); if (loader.initialize(resource_pack_path, true)) { resource_pack_enabled_ = true; std::cout << "Asset system initialized with resource pack: " << resource_pack_path << std::endl; @@ -22,10 +22,10 @@ void AssetIntegrated::initWithResourcePack(const std::string &executable_path, } } -std::vector AssetIntegrated::loadFile(const std::string &filename) { +std::vector AssetIntegrated::loadFile(const std::string& filename) { if (shouldUseResourcePack(filename) && resource_pack_enabled_) { // Intentar cargar del pack de recursos - auto &loader = ResourceLoader::getInstance(); + auto& loader = ResourceLoader::getInstance(); // Convertir ruta completa a ruta relativa para el pack std::string relativePath = filename; @@ -53,7 +53,7 @@ std::vector AssetIntegrated::loadFile(const std::string &filename) { file.seekg(0, std::ios::beg); std::vector data(fileSize); - if (!file.read(reinterpret_cast(data.data()), fileSize)) { + if (!file.read(reinterpret_cast(data.data()), fileSize)) { std::cerr << "Error: Could not read file: " << filename << std::endl; return {}; } @@ -61,9 +61,9 @@ std::vector AssetIntegrated::loadFile(const std::string &filename) { return data; } -bool AssetIntegrated::fileExists(const std::string &filename) const { +bool AssetIntegrated::fileExists(const std::string& filename) const { if (shouldUseResourcePack(filename) && resource_pack_enabled_) { - auto &loader = ResourceLoader::getInstance(); + auto& loader = ResourceLoader::getInstance(); // Convertir ruta completa a ruta relativa para el pack std::string relativePath = filename; @@ -81,12 +81,12 @@ bool AssetIntegrated::fileExists(const std::string &filename) const { return std::filesystem::exists(filename); } -std::string AssetIntegrated::getSystemPath(const std::string &filename) const { +std::string AssetIntegrated::getSystemPath(const std::string& filename) const { // Los archivos de sistema/config siempre van al filesystem return filename; } -bool AssetIntegrated::shouldUseResourcePack(const std::string &filepath) const { +bool AssetIntegrated::shouldUseResourcePack(const std::string& filepath) const { // Los archivos que NO van al pack: // - Archivos de config/ (ahora están fuera de data/) // - Archivos con absolute=true en assets.txt diff --git a/source/asset_integrated.h b/source/asset_integrated.hpp similarity index 56% rename from source/asset_integrated.h rename to source/asset_integrated.hpp index 9a85213..0c92048 100644 --- a/source/asset_integrated.h +++ b/source/asset_integrated.hpp @@ -2,28 +2,28 @@ #include -#include "asset.h" -#include "resource_loader.h" +#include "asset.hpp" +#include "resource_loader.hpp" // Extensión de Asset que integra ResourceLoader class AssetIntegrated : public Asset { public: // Inicializa Asset con ResourceLoader - static void initWithResourcePack(const std::string &executable_path, - const std::string &resource_pack_path = "resources.pack"); + static void initWithResourcePack(const std::string& executable_path, + const std::string& resource_pack_path = "resources.pack"); // Carga un archivo usando ResourceLoader como primera opción - std::vector loadFile(const std::string &filename); + std::vector loadFile(const std::string& filename); // Verifica si un archivo existe (pack o filesystem) - bool fileExists(const std::string &filename) const; + bool fileExists(const std::string& filename) const; // Obtiene la ruta completa para archivos del sistema/config - std::string getSystemPath(const std::string &filename) const; + std::string getSystemPath(const std::string& filename) const; private: static bool resource_pack_enabled_; // Determina si un archivo debe cargarse del pack o del filesystem - bool shouldUseResourcePack(const std::string &filepath) const; + bool shouldUseResourcePack(const std::string& filepath) const; }; \ No newline at end of file diff --git a/source/audio.cpp b/source/audio.cpp index 588bcd4..09ba8bf 100644 --- a/source/audio.cpp +++ b/source/audio.cpp @@ -1,15 +1,15 @@ -#include "audio.h" +#include "audio.hpp" #include // Para SDL_LogInfo, SDL_LogCategory, SDL_G... #include // Para clamp #include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM... -#include "options.h" // Para AudioOptions, audio, MusicOptions -#include "resource.h" // Para Resource +#include "options.hpp" // Para AudioOptions, audio, MusicOptions +#include "resource.hpp" // Para Resource // Singleton -Audio *Audio::instance = nullptr; +Audio* Audio::instance = nullptr; // Inicializa la instancia única del singleton void Audio::init() { Audio::instance = new Audio(); } @@ -18,7 +18,7 @@ void Audio::init() { Audio::instance = new Audio(); } void Audio::destroy() { delete Audio::instance; } // Obtiene la instancia -auto Audio::get() -> Audio * { return Audio::instance; } +auto Audio::get() -> Audio* { return Audio::instance; } // Constructor Audio::Audio() { initSDLAudio(); } @@ -34,7 +34,7 @@ void Audio::update() { } // Reproduce la música -void Audio::playMusic(const std::string &name, const int loop) { +void Audio::playMusic(const std::string& name, const int loop) { music_.name = name; music_.loop = (loop != 0); @@ -69,7 +69,7 @@ void Audio::stopMusic() { } // Reproduce un sonido -void Audio::playSound(const std::string &name, Group group) const { +void Audio::playSound(const std::string& name, Group group) const { if (sound_enabled_) { JA_PlaySound(Resource::get()->getSound(name), 0, static_cast(group)); } diff --git a/source/audio.h b/source/audio.hpp similarity index 88% rename from source/audio.h rename to source/audio.hpp index 996ee97..4e5c547 100644 --- a/source/audio.h +++ b/source/audio.hpp @@ -25,24 +25,24 @@ class Audio { static constexpr int FREQUENCY = 48000; // Frecuencia de audio // --- Métodos de singleton --- - static void init(); // Inicializa el objeto Audio - static void destroy(); // Libera el objeto Audio - static auto get() -> Audio *; // Obtiene el puntero al objeto Audio - Audio(const Audio &) = delete; // Evitar copia - auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación + static void init(); // Inicializa el objeto Audio + static void destroy(); // Libera el objeto Audio + static auto get() -> Audio*; // Obtiene el puntero al objeto Audio + Audio(const Audio&) = delete; // Evitar copia + auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación // --- Método principal --- static void update(); // --- Control de Música --- - void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle + void playMusic(const std::string& name, int loop = -1); // Reproducir música en bucle void pauseMusic(); // Pausar reproducción de música void resumeMusic(); // Continua la música pausada void stopMusic(); // Detener completamente la música void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música // --- Control de Sonidos --- - void playSound(const std::string &name, Group group = Group::GAME) const; // Reproducir sonido puntual + void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual void stopAllSounds() const; // Detener todos los sonidos // --- Configuración General --- @@ -107,5 +107,5 @@ class Audio { ~Audio(); // Destructor privado // --- Instancia singleton --- - static Audio *instance; // Instancia única de Audio + static Audio* instance; // Instancia única de Audio }; \ No newline at end of file diff --git a/source/background.cpp b/source/background.cpp index 4e7aa3e..020c703 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -1,5 +1,5 @@ #define _USE_MATH_DEFINES -#include "background.h" +#include "background.hpp" #include // Para SDL_FRect, SDL_SetRenderTarget, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetRenderTarget, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_TextureAccess, SDL_FPoint @@ -7,14 +7,14 @@ #include // Para M_PI, cos, sin #include -#include "animated_sprite.h" // Para MovingSprite -#include "moving_sprite.h" // Para MovingSprite -#include "param.h" // Para Param, ParamBackground, param -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture -#include "utils.h" // Para funciones de easing +#include "animated_sprite.hpp" // Para MovingSprite +#include "moving_sprite.hpp" // Para MovingSprite +#include "param.hpp" // Para Param, ParamBackground, param +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "sprite.hpp" // Para Sprite +#include "texture.hpp" // Para Texture +#include "utils.hpp" // Para funciones de easing // Constructor Background::Background(float total_progress_to_complete) @@ -116,7 +116,7 @@ void Background::initializeSpriteProperties() { grass_sprite_->setPos(0.0F, base_ - 10.0F); grass_sprite_->setWidth(320.0F); grass_sprite_->setHeight(10.0F); - //grass_sprite_->setCurrentAnimation(0); + // grass_sprite_->setCurrentAnimation(0); buildings_sprite_->setY(base_ - buildings_sprite_->getHeight()); sun_sprite_->setPosition(sun_path_.front()); diff --git a/source/background.h b/source/background.hpp similarity index 79% rename from source/background.h rename to source/background.hpp index 0e58470..5344518 100644 --- a/source/background.h +++ b/source/background.hpp @@ -8,7 +8,7 @@ #include // Para unique_ptr, shared_ptr #include // Para vector -#include "color.h" // Para Color +#include "color.hpp" // Para Color class MovingSprite; class Sprite; @@ -94,27 +94,27 @@ class Background { ProgressCallback progress_callback_; // Callback para notificar cambios de progreso // --- Variables de estado --- - std::vector sun_path_; // Recorrido del sol - std::vector moon_path_; // Recorrido de la luna - std::array gradient_rect_; // Fondos degradados - std::array top_clouds_rect_; // Nubes superiores - std::array bottom_clouds_rect_; // Nubes inferiores - SDL_FRect rect_; // Tamaño del objeto - SDL_FRect src_rect_; // Parte del objeto para copiar en pantalla - SDL_FRect dst_rect_; // Posición en pantalla donde se copia el objeto - Color attenuate_color_; // Color de atenuación - State state_ = State::NORMAL; // Estado actual - float progress_ = 0.0F; // Progresión interna - float clouds_speed_ = 0; // Velocidad de las nubes - float transition_ = 0; // Porcentaje de transición - size_t gradient_number_ = 0; // Índice de fondo degradado - size_t alpha_color_texture_ = 0; // Transparencia de atenuación - size_t previous_alpha_color_texture_ = 0; // Transparencia anterior - size_t sun_index_ = 0; // Índice del recorrido del sol - size_t moon_index_ = 0; // Índice del recorrido de la luna - int base_ = 0; // Posición base del fondo - Uint8 alpha_ = 0; // Transparencia entre fases - bool manual_mode_ = false; // Si está en modo manual + std::vector sun_path_; // Recorrido del sol + std::vector moon_path_; // Recorrido de la luna + std::array gradient_rect_; // Fondos degradados + std::array top_clouds_rect_; // Nubes superiores + std::array bottom_clouds_rect_; // Nubes inferiores + SDL_FRect rect_; // Tamaño del objeto + SDL_FRect src_rect_; // Parte del objeto para copiar en pantalla + SDL_FRect dst_rect_; // Posición en pantalla donde se copia el objeto + Color attenuate_color_; // Color de atenuación + State state_ = State::NORMAL; // Estado actual + float progress_ = 0.0F; // Progresión interna + float clouds_speed_ = 0; // Velocidad de las nubes + float transition_ = 0; // Porcentaje de transición + size_t gradient_number_ = 0; // Índice de fondo degradado + size_t alpha_color_texture_ = 0; // Transparencia de atenuación + size_t previous_alpha_color_texture_ = 0; // Transparencia anterior + size_t sun_index_ = 0; // Índice del recorrido del sol + size_t moon_index_ = 0; // Índice del recorrido de la luna + int base_ = 0; // Posición base del fondo + Uint8 alpha_ = 0; // Transparencia entre fases + bool manual_mode_ = false; // Si está en modo manual // --- Variables para transición suave de completado --- float completion_transition_timer_ = 0.0f; // Timer para la transición de completado diff --git a/source/balloon.cpp b/source/balloon.cpp index 3cb6c24..2427ece 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -1,14 +1,14 @@ -#include "balloon.h" +#include "balloon.hpp" #include // Para clamp #include // Para array #include // Para fabs -#include "animated_sprite.h" // Para AnimatedSprite -#include "audio.h" // Para Audio -#include "param.h" // Para Param, ParamBalloon, param -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "audio.hpp" // Para Audio +#include "param.hpp" // Para Param, ParamBalloon, param +#include "sprite.hpp" // Para Sprite +#include "texture.hpp" // Para Texture // Constructor Balloon::Balloon(const Config& config) diff --git a/source/balloon.h b/source/balloon.hpp similarity index 79% rename from source/balloon.h rename to source/balloon.hpp index 4a6eda0..73ad5c1 100644 --- a/source/balloon.h +++ b/source/balloon.hpp @@ -8,8 +8,8 @@ #include // Para string_view #include // Para vector -#include "animated_sprite.h" // Para AnimatedSprite -#include "utils.h" // Para Circle +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "utils.hpp" // Para Circle class Texture; @@ -89,11 +89,11 @@ class Balloon { ~Balloon() = default; // --- Métodos principales --- - void alignTo(int x); // Centra el globo en la posición X - void render(); // Pinta el globo en la pantalla - void move(float deltaTime); // Actualiza la posición y estados del globo (time-based) - void update(float deltaTime); // Actualiza el globo (posición, animación, contadores) (time-based) - void stop(); // Detiene el globo + void alignTo(int x); // Centra el globo en la posición X + void render(); // Pinta el globo en la pantalla + void move(float deltaTime); // Actualiza la posición y estados del globo (time-based) + void update(float deltaTime); // Actualiza el globo (posición, animación, contadores) (time-based) + void stop(); // Detiene el globo void start(); // Pone el globo en movimiento void pop(bool should_sound = false); // Explota el globo @@ -123,7 +123,7 @@ class Balloon { // --- Setters --- void setVelY(float vel_y) { vy_ = vel_y; } void setVelX(float vel_x) { vx_ = vel_x; } - void alterVelX(float percent) {vx_ *= percent; } + void alterVelX(float percent) { vx_ *= percent; } void setGameTempo(float tempo) { game_tempo_ = tempo; } void setInvulnerable(bool value) { invulnerable_ = value; } void setBouncingSound(bool value) { sound_.bouncing_enabled = value; } @@ -245,34 +245,34 @@ class Balloon { std::unique_ptr sprite_; // Sprite del objeto globo // --- Variables de estado y físicas --- - float x_; // Posición X - float y_; // Posición Y - float w_; // Ancho - float h_; // Alto - float vx_; // Velocidad X - float vy_; // Velocidad Y - float gravity_; // Aceleración en Y - float default_vy_; // Velocidad inicial al rebotar - float max_vy_; // Máxima velocidad en Y - bool being_created_; // Si el globo se está creando - bool enabled_ = true; // Si el globo está activo - bool invulnerable_; // Si el globo es invulnerable - bool stopped_; // Si el globo está parado - bool use_reversed_colors_ = false; // Si se usa el color alternativo - Circle collider_; // Círculo de colisión - float creation_counter_; // Temporizador de creación - float creation_counter_ini_; // Valor inicial del temporizador de creación - Uint16 score_; // Puntos al destruir el globo - Type type_; // Tipo de globo - Size size_; // Tamaño de globo - Uint8 menace_; // Amenaza que genera el globo - Uint32 counter_ = 0; // Contador interno - float game_tempo_; // Multiplicador de tempo del juego - float movement_accumulator_ = 0.0f; // Acumulador para movimiento durante creación (deltaTime) - Uint8 power_; // Poder que alberga el globo - SDL_FRect play_area_; // Zona de movimiento del globo - Sound sound_; // Configuración de sonido del globo - BounceEffect bounce_effect_; // Efecto de rebote + float x_; // Posición X + float y_; // Posición Y + float w_; // Ancho + float h_; // Alto + float vx_; // Velocidad X + float vy_; // Velocidad Y + float gravity_; // Aceleración en Y + float default_vy_; // Velocidad inicial al rebotar + float max_vy_; // Máxima velocidad en Y + bool being_created_; // Si el globo se está creando + bool enabled_ = true; // Si el globo está activo + bool invulnerable_; // Si el globo es invulnerable + bool stopped_; // Si el globo está parado + bool use_reversed_colors_ = false; // Si se usa el color alternativo + Circle collider_; // Círculo de colisión + float creation_counter_; // Temporizador de creación + float creation_counter_ini_; // Valor inicial del temporizador de creación + Uint16 score_; // Puntos al destruir el globo + Type type_; // Tipo de globo + Size size_; // Tamaño de globo + Uint8 menace_; // Amenaza que genera el globo + Uint32 counter_ = 0; // Contador interno + float game_tempo_; // Multiplicador de tempo del juego + float movement_accumulator_ = 0.0f; // Acumulador para movimiento durante creación (deltaTime) + Uint8 power_; // Poder que alberga el globo + SDL_FRect play_area_; // Zona de movimiento del globo + Sound sound_; // Configuración de sonido del globo + BounceEffect bounce_effect_; // Efecto de rebote // --- Posicionamiento y transformación --- void shiftColliders(); // Alinea el círculo de colisión con el sprite @@ -284,9 +284,9 @@ class Balloon { void playPoppingSound(); // Reproduce el sonido de reventar // --- Movimiento y física --- - void handleHorizontalMovement(float deltaTime); // Maneja el movimiento horizontal (time-based) - void handleVerticalMovement(float deltaTime); // Maneja el movimiento vertical (time-based) - void applyGravity(float deltaTime); // Aplica la gravedad al objeto (time-based) + void handleHorizontalMovement(float deltaTime); // Maneja el movimiento horizontal (time-based) + void handleVerticalMovement(float deltaTime); // Maneja el movimiento vertical (time-based) + void applyGravity(float deltaTime); // Aplica la gravedad al objeto (time-based) // --- Rebote --- void enableBounceEffect(); // Activa el efecto de rebote @@ -301,5 +301,5 @@ class Balloon { void handleBottomCollision(); // Maneja la colisión inferior // --- Lógica de estado --- - void updateState(float deltaTime); // Actualiza los estados del globo (time-based) + void updateState(float deltaTime); // Actualiza los estados del globo (time-based) }; \ No newline at end of file diff --git a/source/balloon_formations.cpp b/source/balloon_formations.cpp index a4cba1f..da1ab77 100644 --- a/source/balloon_formations.cpp +++ b/source/balloon_formations.cpp @@ -1,4 +1,4 @@ -#include "balloon_formations.h" +#include "balloon_formations.hpp" #include // Para max, min, copy #include // Para array @@ -11,10 +11,10 @@ #include // Para basic_istringstream #include // Para string, char_traits, allocator, operator==, stoi, getline, operator<=>, basic_string -#include "asset.h" // Para Asset -#include "balloon.h" // Para Balloon -#include "param.h" // Para Param, ParamGame, param -#include "utils.h" // Para Zone, BLOCK +#include "asset.hpp" // Para Asset +#include "balloon.hpp" // Para Balloon +#include "param.hpp" // Para Param, ParamGame, param +#include "utils.hpp" // Para Zone, BLOCK void BalloonFormations::initFormations() { // Calcular posiciones base @@ -235,10 +235,10 @@ void BalloonFormations::createFloaterVariants() { #ifdef _DEBUG void BalloonFormations::addTestFormation() { std::vector test_params = { - {10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334f}, // 200 frames ÷ 60fps = 3.334s - {50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334f}, // 200 frames ÷ 60fps = 3.334s - {90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334f}, // 200 frames ÷ 60fps = 3.334s - {140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334f}}; // 200 frames ÷ 60fps = 3.334s + {10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334f}, // 200 frames ÷ 60fps = 3.334s + {50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334f}, // 200 frames ÷ 60fps = 3.334s + {90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334f}, // 200 frames ÷ 60fps = 3.334s + {140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334f}}; // 200 frames ÷ 60fps = 3.334s formations_.at(99) = Formation(test_params); } diff --git a/source/balloon_formations.h b/source/balloon_formations.hpp similarity index 93% rename from source/balloon_formations.h rename to source/balloon_formations.hpp index a8800c6..c67891d 100644 --- a/source/balloon_formations.h +++ b/source/balloon_formations.hpp @@ -8,7 +8,7 @@ #include // Para pair #include // Para vector -#include "balloon.h" // Para Balloon +#include "balloon.hpp" // Para Balloon // --- Clase BalloonFormations --- class BalloonFormations { @@ -81,8 +81,8 @@ class BalloonFormations { private: // --- Constantes --- - static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos - static constexpr float CREATION_TIME = 5.0f; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s) + static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos + static constexpr float CREATION_TIME = 5.0f; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s) static constexpr float DEFAULT_CREATION_TIME = 3.334f; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s) // --- Variables --- diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index b0116a9..a0ab18b 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -1,19 +1,19 @@ -#include "balloon_manager.h" +#include "balloon_manager.hpp" #include // Para remove_if #include #include // Para rand #include // Para accumulate -#include "balloon.h" // Para Balloon, Balloon::SCORE.at( )ALLOON_VELX... -#include "balloon_formations.h" // Para BalloonFormationParams, BalloonForma... -#include "color.h" // Para Zone, Color, flash_color -#include "explosions.h" // Para Explosions -#include "param.h" // Para Param, ParamGame, param -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "stage_interface.h" // Para IStageInfo -#include "utils.h" +#include "balloon.hpp" // Para Balloon, Balloon::SCORE.at( )ALLOON_VELX... +#include "balloon_formations.hpp" // Para BalloonFormationParams, BalloonForma... +#include "color.hpp" // Para Zone, Color, flash_color +#include "explosions.hpp" // Para Explosions +#include "param.hpp" // Para Param, ParamGame, param +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "stage_interface.hpp" // Para IStageInfo +#include "utils.hpp" // Constructor BalloonManager::BalloonManager(IStageInfo* stage_info) diff --git a/source/balloon_manager.h b/source/balloon_manager.hpp similarity index 88% rename from source/balloon_manager.h rename to source/balloon_manager.hpp index 6aa82ee..c43256b 100644 --- a/source/balloon_manager.h +++ b/source/balloon_manager.hpp @@ -8,12 +8,12 @@ #include // Para string #include // Para vector -#include "balloon.h" // Para BALLOON_SPEED, Balloon, Balloon::Size (ptr only), Balloon::Type (ptr only) -#include "balloon_formations.h" // Para BalloonFormations -#include "explosions.h" // Para Explosions -#include "param.h" // Para Param, ParamGame, param -#include "stage_interface.h" // Para IStageInfo -#include "utils.h" // Para Zone +#include "balloon.hpp" // Para BALLOON_SPEED, Balloon, Balloon::Size (ptr only), Balloon::Type (ptr only) +#include "balloon_formations.hpp" // Para BalloonFormations +#include "explosions.hpp" // Para Explosions +#include "param.hpp" // Para Param, ParamGame, param +#include "stage_interface.hpp" // Para IStageInfo +#include "utils.hpp" // Para Zone class Texture; @@ -24,7 +24,7 @@ using Balloons = std::vector>; class BalloonManager { public: // --- Constructor y destructor --- - BalloonManager(IStageInfo *stage_info); + BalloonManager(IStageInfo* stage_info); ~BalloonManager() = default; // --- Métodos principales --- @@ -41,7 +41,7 @@ class BalloonManager { // --- Creación de globos --- auto createBalloon(Balloon::Config config) -> std::shared_ptr; // Crea un nuevo globo - void createChildBalloon(const std::shared_ptr &balloon, const std::string &direction); // Crea un globo a partir de otro + void createChildBalloon(const std::shared_ptr& balloon, const std::string& direction); // Crea un globo a partir de otro void createPowerBall(); // Crea una PowerBall void createTwoBigBalloons(); // Crea dos globos grandes @@ -54,8 +54,8 @@ class BalloonManager { auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla // --- Manipulación de globos existentes --- - auto popBalloon(const std::shared_ptr &balloon) -> int; // Explosiona un globo, creando otros si aplica - auto destroyBalloon(std::shared_ptr &balloon) -> int; // Explosiona un globo sin crear otros + auto popBalloon(const std::shared_ptr& balloon) -> int; // Explosiona un globo, creando otros si aplica + auto destroyBalloon(std::shared_ptr& balloon) -> int; // Explosiona un globo sin crear otros auto destroyAllBalloons() -> int; // Destruye todos los globos void stopAllBalloons(); // Detiene el movimiento de los globos void startAllBalloons(); // Reactiva el movimiento de los globos @@ -77,7 +77,7 @@ class BalloonManager { // --- Getters --- auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos [[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; } - auto getBalloons() -> Balloons & { return balloons_; } + auto getBalloons() -> Balloons& { return balloons_; } [[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); } private: @@ -94,7 +94,7 @@ class BalloonManager { std::vector> explosions_textures_; // Texturas de explosiones std::vector> balloon_animations_; // Animaciones de los globos std::vector> explosions_animations_; // Animaciones de las explosiones - IStageInfo *stage_info_; // Informacion de la pantalla actual + IStageInfo* stage_info_; // Informacion de la pantalla actual // --- Variables de estado --- SDL_FRect play_area_ = param.game.play_area.rect; diff --git a/source/bullet.cpp b/source/bullet.cpp index ff4c558..def7764 100644 --- a/source/bullet.cpp +++ b/source/bullet.cpp @@ -1,11 +1,11 @@ -#include "bullet.h" +#include "bullet.hpp" #include // Para allocator, unique_ptr, make_unique #include // Para char_traits, basic_string, operator+, string -#include "param.h" // Para Param, ParamGame, param -#include "player.h" // Para Player::Id -#include "resource.h" // Para Resource +#include "param.hpp" // Para Param, ParamGame, param +#include "player.hpp" // Para Player::Id +#include "resource.hpp" // Para Resource // Constructor Bullet::Bullet(float x, float y, Type type, Color color, int owner) diff --git a/source/bullet.h b/source/bullet.hpp similarity index 89% rename from source/bullet.h rename to source/bullet.hpp index a4180d2..a13ff54 100644 --- a/source/bullet.h +++ b/source/bullet.hpp @@ -5,8 +5,8 @@ #include // Para unique_ptr #include // Para string -#include "animated_sprite.h" // Para AnimatedSprite -#include "utils.h" // Para Circle +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "utils.hpp" // Para Circle // --- Clase Bullet: representa una bala del jugador --- class Bullet { @@ -37,7 +37,7 @@ class Bullet { // --- Constructor y destructor --- Bullet(float x, float y, Type type, Color color, int owner); // Constructor principal - ~Bullet() = default; // Destructor + ~Bullet() = default; // Destructor // --- Métodos principales --- void render(); // Dibuja la bala en pantalla @@ -68,9 +68,9 @@ class Bullet { float vel_x_; // Velocidad en el eje X // --- Métodos internos --- - void shiftColliders(); // Ajusta el círculo de colisión - void shiftSprite(); // Ajusta el sprite - auto move(float deltaTime) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based) - static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala + void shiftColliders(); // Ajusta el círculo de colisión + void shiftSprite(); // Ajusta el sprite + auto move(float deltaTime) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based) + static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación }; diff --git a/source/bullet_manager.cpp b/source/bullet_manager.cpp index a637630..d9a743a 100644 --- a/source/bullet_manager.cpp +++ b/source/bullet_manager.cpp @@ -1,10 +1,10 @@ -#include "bullet_manager.h" +#include "bullet_manager.hpp" #include // Para remove_if -#include "bullet.h" // Para Bullet -#include "param.h" // Para param -#include "player.h" // Para Player +#include "bullet.hpp" // Para Bullet +#include "param.hpp" // Para param +#include "player.hpp" // Para Player // Constructor BulletManager::BulletManager() @@ -39,10 +39,9 @@ void BulletManager::freeBullets() { if (!bullets_.empty()) { // Elimina las balas deshabilitadas del vector bullets_.erase( - std::remove_if(bullets_.begin(), bullets_.end(), - [](const std::shared_ptr& bullet) { - return !bullet->isEnabled(); - }), + std::remove_if(bullets_.begin(), bullets_.end(), [](const std::shared_ptr& bullet) { + return !bullet->isEnabled(); + }), bullets_.end()); } } @@ -103,7 +102,7 @@ auto BulletManager::isBulletOutOfBounds(const std::shared_ptr& bullet) - auto collider = bullet->getCollider(); return (collider.x < play_area_.x || - collider.x > play_area_.x + play_area_.w || - collider.y < play_area_.y || - collider.y > play_area_.y + play_area_.h); + collider.x > play_area_.x + play_area_.w || + collider.y < play_area_.y || + collider.y > play_area_.y + play_area_.h); } \ No newline at end of file diff --git a/source/bullet_manager.h b/source/bullet_manager.hpp similarity index 87% rename from source/bullet_manager.h rename to source/bullet_manager.hpp index 740497a..32eccce 100644 --- a/source/bullet_manager.h +++ b/source/bullet_manager.hpp @@ -6,8 +6,8 @@ #include // Para shared_ptr, unique_ptr #include // Para vector -#include "bullet.h" // Para Bullet -#include "utils.h" // Para Circle +#include "bullet.hpp" // Para Bullet +#include "utils.hpp" // Para Circle // --- Types --- using Bullets = std::vector>; @@ -49,16 +49,16 @@ class BulletManager { void clearAllBullets(); // Elimina todas las balas // --- Detección de colisiones --- - void checkCollisions(); // Verifica colisiones de todas las balas - void setTabeCollisionCallback(CollisionCallback callback); // Establece callback para colisión con Tabe - void setBalloonCollisionCallback(CollisionCallback callback); // Establece callback para colisión con globos - void setOutOfBoundsCallback(OutOfBoundsCallback callback); // Establece callback para balas fuera de límites + void checkCollisions(); // Verifica colisiones de todas las balas + void setTabeCollisionCallback(CollisionCallback callback); // Establece callback para colisión con Tabe + void setBalloonCollisionCallback(CollisionCallback callback); // Establece callback para colisión con globos + void setOutOfBoundsCallback(OutOfBoundsCallback callback); // Establece callback para balas fuera de límites // --- Configuración --- void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego // --- Getters --- - auto getBullets() -> Bullets& { return bullets_; } // Obtiene referencia al vector de balas + auto getBullets() -> Bullets& { return bullets_; } // Obtiene referencia al vector de balas [[nodiscard]] auto getNumBullets() const -> int { return bullets_.size(); } // Obtiene el número de balas activas private: @@ -71,7 +71,7 @@ class BulletManager { // --- Callbacks para colisiones --- CollisionCallback tabe_collision_callback_; // Callback para colisión con Tabe CollisionCallback balloon_collision_callback_; // Callback para colisión con globos - OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites + OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites // --- Métodos internos --- void processBulletUpdate(const std::shared_ptr& bullet, float deltaTime); // Procesa actualización individual diff --git a/source/color.cpp b/source/color.cpp index c852c39..f37d1dc 100644 --- a/source/color.cpp +++ b/source/color.cpp @@ -1,5 +1,5 @@ #define _USE_MATH_DEFINES -#include "color.h" +#include "color.hpp" #include // Para isxdigit #include // Para sinf, fmaxf, fminf, M_PI, fmodf, roundf, fmod @@ -8,7 +8,7 @@ #include // Para basic_string, stoi, string // Método estático para crear Color desde string hexadecimal -auto Color::fromHex(const std::string &hex_str) -> Color { +auto Color::fromHex(const std::string& hex_str) -> Color { std::string hex = hex_str; // Quitar '#' si existe @@ -117,7 +117,7 @@ constexpr auto Color::hsvToRgb(HSV hsv) -> Color { // Implementaciones del namespace Colors namespace Colors { // Obtiene un color del vector de colores imitando al Coche Fantástico -auto getColorLikeKnightRider(const std::vector &colors, int counter) -> Color { +auto getColorLikeKnightRider(const std::vector& colors, int counter) -> Color { int cycle_length = (colors.size() * 2) - 2; size_t n = counter % cycle_length; diff --git a/source/color.h b/source/color.hpp similarity index 94% rename from source/color.h rename to source/color.hpp index 7b6822d..2a84cfd 100644 --- a/source/color.h +++ b/source/color.hpp @@ -69,17 +69,17 @@ struct Color { } // Método estático para crear Color desde string hexadecimal - static auto fromHex(const std::string &hex_str) -> Color; + static auto fromHex(const std::string& hex_str) -> Color; // Conversiones de formato de color [[nodiscard]] constexpr static auto rgbToHsv(Color color) -> HSV; [[nodiscard]] constexpr static auto hsvToRgb(HSV hsv) -> Color; - [[nodiscard]] constexpr auto IS_EQUAL_TO(const Color &other) const -> bool { + [[nodiscard]] constexpr auto IS_EQUAL_TO(const Color& other) const -> bool { return r == other.r && g == other.g && b == other.b && a == other.a; } - [[nodiscard]] constexpr auto APPROACH_TO(const Color &target, int step = DEFAULT_APPROACH_STEP) const -> Color { + [[nodiscard]] constexpr auto APPROACH_TO(const Color& target, int step = DEFAULT_APPROACH_STEP) const -> Color { auto approach_component = [step](Uint8 current, Uint8 target_val) -> Uint8 { if (std::abs(current - target_val) <= step) { return target_val; @@ -96,7 +96,7 @@ struct Color { } // Interpolación lineal hacia otro color (t=0.0: this, t=1.0: target) - [[nodiscard]] constexpr auto LERP(const Color &target, float t) const -> Color { + [[nodiscard]] constexpr auto LERP(const Color& target, float t) const -> Color { // Asegurar que t esté en el rango [0.0, 1.0] t = std::clamp(t, 0.0f, 1.0f); @@ -109,8 +109,7 @@ struct Color { lerp_component(r, target.r), lerp_component(g, target.g), lerp_component(b, target.b), - lerp_component(a, target.a) - ); + lerp_component(a, target.a)); } // Sobrecarga para aceptar componentes RGBA directamente @@ -157,6 +156,6 @@ constexpr Color PINK_SKY = Color(0XFF, 0X6B, 0X97); constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B); // --- Funciones --- -auto getColorLikeKnightRider(const std::vector &colors, int counter) -> Color; +auto getColorLikeKnightRider(const std::vector& colors, int counter) -> Color; auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle; } // namespace Colors \ No newline at end of file diff --git a/source/defaults.h b/source/defaults.hpp similarity index 97% rename from source/defaults.h rename to source/defaults.hpp index 8a1e10e..5f7c4ac 100644 --- a/source/defaults.h +++ b/source/defaults.hpp @@ -4,9 +4,9 @@ #include -#include "color.h" -#include "ui/notifier.h" // Para Notifier::Position -#include "version.h" // Para Version::APP_NAME +#include "color.hpp" +#include "ui/notifier.hpp" // Para Notifier::Position +#include "version.h" // Para Version::APP_NAME // --- Namespace GameDefaults: configuración centralizada con valores por defecto del juego --- namespace GameDefaults { @@ -15,8 +15,8 @@ namespace GameDefaults { namespace Game { constexpr float WIDTH = 320.0F; constexpr float HEIGHT = 256.0F; -constexpr int NAME_ENTRY_IDLE_TIME = 10; -constexpr int NAME_ENTRY_TOTAL_TIME = 60; +constexpr int NAME_ENTRY_IDLE_TIME = 10; +constexpr int NAME_ENTRY_TOTAL_TIME = 60; constexpr bool HIT_STOP = false; constexpr int HIT_STOP_MS = 500; constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0 diff --git a/source/define_buttons.cpp b/source/define_buttons.cpp index d25d180..2ca5c64 100644 --- a/source/define_buttons.cpp +++ b/source/define_buttons.cpp @@ -1,25 +1,25 @@ -#include "define_buttons.h" +#include "define_buttons.hpp" #include // Para __all_of_fn, all_of #include // Para identity #include // Para allocator, unique_ptr, shared_ptr, make_unique, operator== -#include "color.h" // Para Color -#include "input.h" // Para Input -#include "input_types.h" // Para InputAction -#include "lang.h" // Para getText -#include "options.h" // Para Gamepad -#include "param.h" // Para Param, ParamGame, param -#include "resource.h" // Para Resource -#include "ui/window_message.h" // Para WindowMessage -#include "utils.h" // Para Zone +#include "color.hpp" // Para Color +#include "input.hpp" // Para Input +#include "input_types.hpp" // Para InputAction +#include "lang.hpp" // Para getText +#include "options.hpp" // Para Gamepad +#include "param.hpp" // Para Param, ParamGame, param +#include "resource.hpp" // Para Resource +#include "ui/window_message.hpp" // Para WindowMessage +#include "utils.hpp" // Para Zone DefineButtons::DefineButtons() : input_(Input::get()) { clearButtons(); auto gamepads = input_->getGamepads(); - for (const auto &gamepad : gamepads) { + for (const auto& gamepad : gamepads) { controller_names_.emplace_back(Input::getControllerName(gamepad)); } @@ -63,7 +63,7 @@ void DefineButtons::update(float delta_time) { } } -void DefineButtons::handleEvents(const SDL_Event &event) { +void DefineButtons::handleEvents(const SDL_Event& event) { if (enabled_) { switch (event.type) { case SDL_EVENT_GAMEPAD_BUTTON_DOWN: @@ -81,7 +81,7 @@ void DefineButtons::handleEvents(const SDL_Event &event) { } } -auto DefineButtons::enable(Options::Gamepad *options_gamepad) -> bool { +auto DefineButtons::enable(Options::Gamepad* options_gamepad) -> bool { if (options_gamepad != nullptr) { options_gamepad_ = options_gamepad; enabled_ = true; @@ -117,7 +117,7 @@ void DefineButtons::disable() { } } -void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent &event) { +void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent& event) { auto gamepad = input_->getGamepad(event.which); if (!gamepad || gamepad != options_gamepad_->instance) { @@ -132,7 +132,7 @@ void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent &event) } } -void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent &event) { +void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent& event) { auto gamepad = input_->getGamepad(event.which); if (!gamepad || gamepad != options_gamepad_->instance) { @@ -182,8 +182,8 @@ void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent &event) { } } -void DefineButtons::bindButtons(Options::Gamepad *options_gamepad) { - for (const auto &button : buttons_) { +void DefineButtons::bindButtons(Options::Gamepad* options_gamepad) { + for (const auto& button : buttons_) { Input::bindGameControllerButton(options_gamepad->instance, button.action, static_cast(button.button)); } @@ -200,13 +200,13 @@ void DefineButtons::incIndexButton() { } auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool { - return std::ranges::all_of(buttons_, [button](const auto &b) { + return std::ranges::all_of(buttons_, [button](const auto& b) { return b.button != button; }); } auto DefineButtons::checkTriggerNotInUse(int trigger_button) -> bool { - return std::ranges::all_of(buttons_, [trigger_button](const auto &b) { + return std::ranges::all_of(buttons_, [trigger_button](const auto& b) { return b.button != trigger_button; }); } diff --git a/source/define_buttons.h b/source/define_buttons.hpp similarity index 86% rename from source/define_buttons.h rename to source/define_buttons.hpp index 15cd719..6f45a4b 100644 --- a/source/define_buttons.h +++ b/source/define_buttons.hpp @@ -8,8 +8,8 @@ #include #include -#include "input.h" -#include "ui/window_message.h" +#include "input.hpp" +#include "ui/window_message.hpp" namespace Options { struct Gamepad; @@ -37,8 +37,8 @@ class DefineButtons { // --- Métodos principales --- void render(); void update(float delta_time); - void handleEvents(const SDL_Event &event); - auto enable(Options::Gamepad *options_gamepad) -> bool; + void handleEvents(const SDL_Event& event); + auto enable(Options::Gamepad* options_gamepad) -> bool; void disable(); // --- Getters --- @@ -51,8 +51,8 @@ class DefineButtons { static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0f; // Cuánto tiempo mostrar el mensaje en segundos // --- Objetos y punteros --- - Input *input_ = nullptr; // Entrada del usuario - Options::Gamepad *options_gamepad_ = nullptr; // Opciones del gamepad + Input* input_ = nullptr; // Entrada del usuario + Options::Gamepad* options_gamepad_ = nullptr; // Opciones del gamepad std::unique_ptr window_message_; // Mensaje de ventana // --- Variables de estado --- @@ -69,9 +69,9 @@ class DefineButtons { // --- Métodos internos --- void incIndexButton(); - void doControllerButtonDown(const SDL_GamepadButtonEvent &event); - void doControllerAxisMotion(const SDL_GamepadAxisEvent &event); - void bindButtons(Options::Gamepad *options_gamepad); + void doControllerButtonDown(const SDL_GamepadButtonEvent& event); + void doControllerAxisMotion(const SDL_GamepadAxisEvent& event); + void bindButtons(Options::Gamepad* options_gamepad); auto checkButtonNotInUse(SDL_GamepadButton button) -> bool; auto checkTriggerNotInUse(int trigger_button) -> bool; void clearButtons(); diff --git a/source/demo.cpp b/source/demo.cpp index 0f26a71..f6ac983 100644 --- a/source/demo.cpp +++ b/source/demo.cpp @@ -1,16 +1,17 @@ -#include "demo.h" +#include "demo.hpp" -#include // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO -#include // Para runtime_error +#include // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO -#include "resource_helper.h" // Para ResourceHelper -#include "utils.h" // Para printWithDots, getFileName +#include // Para runtime_error + +#include "resource_helper.hpp" // Para ResourceHelper +#include "utils.hpp" // Para printWithDots, getFileName // Carga el fichero de datos para la demo -auto loadDemoDataFromFile(const std::string &file_path) -> DemoData { +auto loadDemoDataFromFile(const std::string& file_path) -> DemoData { DemoData dd; - SDL_IOStream *file = nullptr; + SDL_IOStream* file = nullptr; // Intentar cargar desde ResourceHelper primero auto resource_data = ResourceHelper::loadFile(file_path); @@ -42,13 +43,13 @@ auto loadDemoDataFromFile(const std::string &file_path) -> DemoData { #ifdef RECORDING // Guarda el fichero de datos para la demo -bool saveDemoFile(const std::string &file_path, const DemoData &dd) { +bool saveDemoFile(const std::string& file_path, const DemoData& dd) { auto success = true; auto file = SDL_IOFromFile(file_path.c_str(), "w+b"); if (file) { // Guarda los datos - for (const auto &data : dd) { + for (const auto& data : dd) { if (SDL_WriteIO(file, &data, sizeof(DemoKeys)) != sizeof(DemoKeys)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al escribir el fichero %s", getFileName(file_path).c_str()); success = false; diff --git a/source/demo.h b/source/demo.hpp similarity index 95% rename from source/demo.h rename to source/demo.hpp index 46012d0..150cca7 100644 --- a/source/demo.h +++ b/source/demo.hpp @@ -1,8 +1,9 @@ #pragma once #include // Para Uint8 -#include // Para string -#include // Para vector + +#include // Para string +#include // Para vector // --- Constantes --- constexpr int TOTAL_DEMO_DATA = 2000; diff --git a/source/difficulty.cpp b/source/difficulty.cpp index 0f862e5..4e53bdc 100644 --- a/source/difficulty.cpp +++ b/source/difficulty.cpp @@ -1,4 +1,4 @@ -#include "difficulty.h" +#include "difficulty.hpp" #include // Para vector diff --git a/source/difficulty.h b/source/difficulty.hpp similarity index 100% rename from source/difficulty.h rename to source/difficulty.hpp diff --git a/source/director.cpp b/source/director.cpp index c55c51f..483799b 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -1,5 +1,5 @@ // IWYU pragma: no_include -#include "director.h" +#include "director.hpp" #include // Para SDL_LogInfo, SDL_LogCategory, SDL_SetLogPriority, SDL_LogPriority, SDL_Quit @@ -11,33 +11,33 @@ #include // Para runtime_error #include // Para allocator, char_traits, operator==, string, basic_string, operator+ -#include "asset.h" // Para Asset -#include "audio.h" // Para Audio -#include "input.h" // Para Input -#include "lang.h" // Para setLanguage -#include "manage_hiscore_table.h" // Para ManageHiScoreTable -#include "options.h" // Para loadFromFile, saveToFile, Settings, settings, setConfigFile, setControllersFile -#include "param.h" // Para loadParamsFromFile -#include "player.h" // Para Player -#include "resource.h" // Para Resource -#include "resource_helper.h" // Para ResourceHelper -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, Options, name, options, AttractMode, attract_mode -#include "sections/credits.h" // Para Credits -#include "sections/game.h" // Para Game -#include "sections/hiscore_table.h" // Para HiScoreTable -#include "sections/instructions.h" // Para Instructions -#include "sections/intro.h" // Para Intro -#include "sections/logo.h" // Para Logo -#include "sections/title.h" // Para Title -#include "shutdown.h" // Para resultToString, shutdownSystem, ShutdownResult -#include "system_utils.h" // Para createApplicationFolder, resultToString, Result -#include "ui/notifier.h" // Para Notifier -#include "ui/service_menu.h" // Para ServiceMenu -#include "utils.h" // Para Overrides, overrides, getPath +#include "asset.hpp" // Para Asset +#include "audio.hpp" // Para Audio +#include "input.hpp" // Para Input +#include "lang.hpp" // Para setLanguage +#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable +#include "options.hpp" // Para loadFromFile, saveToFile, Settings, settings, setConfigFile, setControllersFile +#include "param.hpp" // Para loadParamsFromFile +#include "player.hpp" // Para Player +#include "resource.hpp" // Para Resource +#include "resource_helper.hpp" // Para ResourceHelper +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, Options, name, options, AttractMode, attract_mode +#include "sections/credits.hpp" // Para Credits +#include "sections/game.hpp" // Para Game +#include "sections/hiscore_table.hpp" // Para HiScoreTable +#include "sections/instructions.hpp" // Para Instructions +#include "sections/intro.hpp" // Para Intro +#include "sections/logo.hpp" // Para Logo +#include "sections/title.hpp" // Para Title +#include "shutdown.hpp" // Para resultToString, shutdownSystem, ShutdownResult +#include "system_utils.hpp" // Para createApplicationFolder, resultToString, Result +#include "ui/notifier.hpp" // Para Notifier +#include "ui/service_menu.hpp" // Para ServiceMenu +#include "utils.hpp" // Para Overrides, overrides, getPath // Constructor -Director::Director(int argc, std::span argv) { +Director::Director(int argc, std::span argv) { #ifdef RECORDING Section::name = Section::Name::GAME; Section::options = Section::Options::GAME_PLAY_1P; @@ -86,7 +86,7 @@ void Director::init() { #endif loadAssets(); // Crea el índice de archivos Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles - Options::setConfigFile(Asset::get()->get("config_v2.txt")); // Establece el fichero de configuración + Options::setConfigFile(Asset::get()->get("config_v2.txt")); // Establece el fichero de configuración Options::setControllersFile(Asset::get()->get("controllers.json")); // Establece el fichero de configuración de mandos Options::loadFromFile(); // Carga el archivo de configuración loadParams(); // Carga los parámetros del programa @@ -173,7 +173,7 @@ void Director::loadAssets() { } // Comprueba los parametros del programa -void Director::checkProgramArguments(int argc, std::span argv) { +void Director::checkProgramArguments(int argc, std::span argv) { // Obtener la ruta absoluta del ejecutable std::filesystem::path exe_path = std::filesystem::absolute(argv[0]); executable_path_ = exe_path.parent_path().string(); @@ -196,7 +196,7 @@ void Director::checkProgramArguments(int argc, std::span argv) { } // Crea la carpeta del sistema donde guardar datos -void Director::createSystemFolder(const std::string &folder) { +void Director::createSystemFolder(const std::string& folder) { auto result = SystemUtils::createApplicationFolder(folder, system_folder_); if (result != SystemUtils::Result::SUCCESS) { diff --git a/source/director.h b/source/director.hpp similarity index 86% rename from source/director.h rename to source/director.hpp index 324360f..4ac0deb 100644 --- a/source/director.h +++ b/source/director.hpp @@ -11,7 +11,7 @@ enum class Code : int; class Director { public: // --- Constructor y destructor --- - Director(int argc, std::span argv); + Director(int argc, std::span argv); ~Director(); // --- Bucle principal --- @@ -29,11 +29,11 @@ class Director { // --- Configuración inicial --- static void loadParams(); // Carga los parámetros del programa static void loadScoreFile(); // Carga el fichero de puntuaciones - void createSystemFolder(const std::string &folder); // Crea la carpeta del sistema + void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema // --- Gestión de entrada y archivos --- - void loadAssets(); // Crea el índice de archivos disponibles - void checkProgramArguments(int argc, std::span argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays) + void loadAssets(); // Crea el índice de archivos disponibles + void checkProgramArguments(int argc, std::span argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays) // --- Secciones del programa --- static void runLogo(); // Ejecuta la pantalla con el logo diff --git a/source/enter_name.cpp b/source/enter_name.cpp index 5929800..1624af7 100644 --- a/source/enter_name.cpp +++ b/source/enter_name.cpp @@ -1,4 +1,4 @@ -#include "enter_name.h" +#include "enter_name.hpp" #include // Para array #include // Para rand @@ -10,7 +10,7 @@ EnterName::EnterName() selected_index_(0) {} // Inicializa el objeto -void EnterName::init(const std::string &name) { +void EnterName::init(const std::string& name) { name_ = sanitizeName(name); selected_index_ = 0; } @@ -80,7 +80,7 @@ auto EnterName::getCarousel(int size) const -> std::string { } // Valida y limpia el nombre: solo caracteres legales y longitud máxima -auto EnterName::sanitizeName(const std::string &name) const -> std::string { +auto EnterName::sanitizeName(const std::string& name) const -> std::string { std::string sanitized; for (size_t i = 0; i < name.length() && sanitized.length() < MAX_NAME_SIZE; ++i) { diff --git a/source/enter_name.h b/source/enter_name.hpp similarity index 68% rename from source/enter_name.h rename to source/enter_name.hpp index 8f60dce..09f85d6 100644 --- a/source/enter_name.h +++ b/source/enter_name.hpp @@ -12,7 +12,7 @@ class EnterName { EnterName(); ~EnterName() = default; - void init(const std::string &name = ""); // Inicializa con nombre opcional (vacío por defecto) + void init(const std::string& name = ""); // Inicializa con nombre opcional (vacío por defecto) void incIndex(); // Incrementa el índice del carácter seleccionado en la lista void decIndex(); // Decrementa el índice del carácter seleccionado en la lista @@ -20,11 +20,11 @@ class EnterName { void addCharacter(); // Añade el carácter seleccionado al nombre void removeLastCharacter(); // Elimina el último carácter del nombre - auto getFinalName() -> std::string; // Obtiene el nombre final (o aleatorio si vacío) - [[nodiscard]] auto getCurrentName() const -> std::string { return name_; } // Obtiene el nombre actual en proceso - [[nodiscard]] auto getSelectedCharacter(int offset = 0) const -> std::string; // Devuelve el carácter seleccionado con offset relativo - [[nodiscard]] auto getCarousel(int size) const -> std::string; // Devuelve el carrusel de caracteres (size debe ser impar) - [[nodiscard]] auto getSelectedIndex() const -> int { return selected_index_; } // Obtiene el índice del carácter seleccionado + auto getFinalName() -> std::string; // Obtiene el nombre final (o aleatorio si vacío) + [[nodiscard]] auto getCurrentName() const -> std::string { return name_; } // Obtiene el nombre actual en proceso + [[nodiscard]] auto getSelectedCharacter(int offset = 0) const -> std::string; // Devuelve el carácter seleccionado con offset relativo + [[nodiscard]] auto getCarousel(int size) const -> std::string; // Devuelve el carrusel de caracteres (size debe ser impar) + [[nodiscard]] auto getSelectedIndex() const -> int { return selected_index_; } // Obtiene el índice del carácter seleccionado [[nodiscard]] auto getCharacterList() const -> const std::string& { return character_list_; } // Obtiene la lista completa de caracteres private: @@ -33,6 +33,6 @@ class EnterName { std::string name_; // Nombre en proceso int selected_index_ = 0; // Índice del carácter seleccionado en "character_list_" - [[nodiscard]] auto sanitizeName(const std::string &name) const -> std::string; // Valida y limpia el nombre - static auto getRandomName() -> std::string; // Devuelve un nombre al azar + [[nodiscard]] auto sanitizeName(const std::string& name) const -> std::string; // Valida y limpia el nombre + static auto getRandomName() -> std::string; // Devuelve un nombre al azar }; \ No newline at end of file diff --git a/source/explosions.cpp b/source/explosions.cpp index 383c36e..9360b40 100644 --- a/source/explosions.cpp +++ b/source/explosions.cpp @@ -1,14 +1,14 @@ -#include "explosions.h" +#include "explosions.hpp" #include // Para max -#include "animated_sprite.h" // Para AnimatedSprite +#include "animated_sprite.hpp" // Para AnimatedSprite class Texture; // lines 4-4 // Actualiza la lógica de la clase (time-based) void Explosions::update(float deltaTime) { - for (auto &explosion : explosions_) { + for (auto& explosion : explosions_) { explosion->update(deltaTime); } @@ -18,13 +18,13 @@ void Explosions::update(float deltaTime) { // Dibuja el objeto en pantalla void Explosions::render() { - for (auto &explosion : explosions_) { + for (auto& explosion : explosions_) { explosion->render(); } } // Añade texturas al objeto -void Explosions::addTexture(int size, const std::shared_ptr &texture, const std::vector &animation) { +void Explosions::addTexture(int size, const std::shared_ptr& texture, const std::vector& animation) { textures_.emplace_back(size, texture, animation); } diff --git a/source/explosions.h b/source/explosions.hpp similarity index 84% rename from source/explosions.h rename to source/explosions.hpp index 98aef09..421f0b9 100644 --- a/source/explosions.h +++ b/source/explosions.hpp @@ -5,7 +5,7 @@ #include // Para move #include // Para vector -#include "animated_sprite.h" // Para AnimatedSprite +#include "animated_sprite.hpp" // Para AnimatedSprite class Texture; @@ -15,7 +15,7 @@ struct ExplosionTexture { std::shared_ptr texture; // Textura para la explosión std::vector animation; // Animación para la textura - ExplosionTexture(int sz, std::shared_ptr tex, const std::vector &anim) + ExplosionTexture(int sz, std::shared_ptr tex, const std::vector& anim) : size(sz), texture(std::move(tex)), animation(anim) {} @@ -29,11 +29,11 @@ class Explosions { ~Explosions() = default; // Destructor por defecto // --- Métodos principales --- - void update(float deltaTime); // Actualiza la lógica de la clase (time-based) - void render(); // Dibuja el objeto en pantalla + void update(float deltaTime); // Actualiza la lógica de la clase (time-based) + void render(); // Dibuja el objeto en pantalla // --- Configuración --- - void addTexture(int size, const std::shared_ptr &texture, const std::vector &animation); // Añade texturas al objeto + void addTexture(int size, const std::shared_ptr& texture, const std::vector& animation); // Añade texturas al objeto void add(int x, int y, int size); // Añade una explosión private: diff --git a/source/external/gif.cpp b/source/external/gif.cpp index 28b4d20..45ea58d 100644 --- a/source/external/gif.cpp +++ b/source/external/gif.cpp @@ -1,4 +1,4 @@ -#include "gif.h" +#include "gif.hpp" #include // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo #include // Para memcpy, size_t diff --git a/source/external/gif.h b/source/external/gif.hpp similarity index 100% rename from source/external/gif.h rename to source/external/gif.hpp diff --git a/source/external/stb_image.h b/source/external/stb_image.h index 076a4e0..6a1f446 100644 --- a/source/external/stb_image.h +++ b/source/external/stb_image.h @@ -10,7 +10,7 @@ #include ... #include ... #define STB_IMAGE_IMPLEMENTATION - #include "stb_image.h" + #include "stb_image.hpp" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free diff --git a/source/fade.cpp b/source/fade.cpp index eb7d1b9..1a13c65 100644 --- a/source/fade.cpp +++ b/source/fade.cpp @@ -1,13 +1,13 @@ -#include "fade.h" +#include "fade.hpp" #include // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderTarget, SDL_RenderFillRect, SDL_SetRenderDrawBlendMode, SDL_SetRenderDrawColor, Uint8, SDL_GetRenderDrawBlendMode, SDL_BLENDMODE_NONE, SDL_BlendMode, SDL_CreateTexture, SDL_DestroyTexture, SDL_RenderClear, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_TextureAccess #include // Para min, max #include // Para rand, size_t -#include "color.h" // Para Color -#include "param.h" // Para Param, param, ParamGame, ParamFade -#include "screen.h" // Para Screen +#include "color.hpp" // Para Color +#include "param.hpp" // Para Param, param, ParamGame, ParamFade +#include "screen.hpp" // Para Screen // Constructor Fade::Fade() @@ -170,7 +170,7 @@ void Fade::updateCenterFade() { } void Fade::drawCenterFadeRectangles() { - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_); @@ -378,7 +378,7 @@ void Fade::activateDiagonal(int diagonal_index, Uint32 current_time) { } void Fade::drawDiagonal() { - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); // CRÍTICO: Limpiar la textura antes de dibujar @@ -425,7 +425,7 @@ void Fade::drawDiagonal() { } void Fade::drawRandomSquares(int active_count) { - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); SDL_BlendMode blend_mode; @@ -443,7 +443,7 @@ void Fade::drawRandomSquares(int active_count) { } void Fade::drawRandomSquares2() { - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); // CRÍTICO: Limpiar la textura antes de dibujar @@ -500,7 +500,7 @@ void Fade::updateVenetianFade() { } void Fade::drawVenetianBlinds() { - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); SDL_BlendMode blend_mode; @@ -508,7 +508,7 @@ void Fade::drawVenetianBlinds() { SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_NONE); SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_); - for (const auto &rect : square_) { + for (const auto& rect : square_) { SDL_RenderFillRect(renderer_, &rect); } @@ -525,7 +525,7 @@ void Fade::updateVenetianRectangles() { void Fade::calculateVenetianProgress() { int completed = 0; - for (const auto &square : square_) { + for (const auto& square : square_) { if (square.h >= param.fade.venetian_size) { ++completed; } @@ -699,7 +699,7 @@ void Fade::setColor(Color color) { // Limpia el backbuffer void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) { // Dibujamos sobre el backbuffer_ - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); // Pintamos la textura con el color del fade diff --git a/source/fade.h b/source/fade.hpp similarity index 98% rename from source/fade.h rename to source/fade.hpp index 4981c66..03cd652 100644 --- a/source/fade.h +++ b/source/fade.hpp @@ -58,8 +58,8 @@ class Fade { private: // --- Objetos y punteros --- - SDL_Renderer *renderer_; // Renderizador de la ventana - SDL_Texture *backbuffer_; // Backbuffer para efectos + SDL_Renderer* renderer_; // Renderizador de la ventana + SDL_Texture* backbuffer_; // Backbuffer para efectos // --- Variables de estado --- std::vector square_; // Vector de cuadrados diff --git a/source/game_logo.cpp b/source/game_logo.cpp index b7779c5..39862b5 100644 --- a/source/game_logo.cpp +++ b/source/game_logo.cpp @@ -1,22 +1,22 @@ -#include "game_logo.h" +#include "game_logo.hpp" #include // Para SDL_SetTextureScaleMode, SDL_FlipMode, SDL_ScaleMode #include // Para max -#include "animated_sprite.h" // Para AnimatedSprite -#include "audio.h" // Para Audio -#include "color.h" // Para Color -#include "param.h" // Para Param, param, ParamGame, ParamTitle -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "smart_sprite.h" // Para SmartSprite -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "audio.hpp" // Para Audio +#include "color.hpp" // Para Color +#include "param.hpp" // Para Param, param, ParamGame, ParamTitle +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "smart_sprite.hpp" // Para SmartSprite +#include "sprite.hpp" // Para Sprite +#include "texture.hpp" // Para Texture constexpr int ZOOM_FACTOR = 5; -constexpr float FLASH_DELAY_S = 0.05f; // 3 frames → 0.05s -constexpr float FLASH_DURATION_S = 0.1f; // 6 frames → 0.1s (3 + 3) +constexpr float FLASH_DELAY_S = 0.05f; // 3 frames → 0.05s +constexpr float FLASH_DURATION_S = 0.1f; // 6 frames → 0.1s (3 + 3) constexpr Color FLASH_COLOR = Color(0xFF, 0xFF, 0xFF); // Color blanco para el flash // Constructor @@ -193,10 +193,9 @@ void GameLogo::handleArcadeEditionShaking(float deltaTime) { } } - void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime) { shake_.time_accumulator += deltaTime; - + if (shake_.time_accumulator >= SHAKE_DELAY_S) { shake_.time_accumulator -= SHAKE_DELAY_S; const auto DISPLACEMENT = calculateShakeDisplacement(); @@ -211,9 +210,9 @@ void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* seco void GameLogo::processArcadeEditionShake(float deltaTime) { // Delay fijo en segundos (shake_.delay era frames, ahora usamos constante) float delayTime = SHAKE_DELAY_S; - + shake_.time_accumulator += deltaTime; - + if (shake_.time_accumulator >= delayTime) { shake_.time_accumulator -= delayTime; const auto DISPLACEMENT = calculateShakeDisplacement(); @@ -255,7 +254,6 @@ void GameLogo::updateDustSprites(float deltaTime) { void GameLogo::updatePostFinishedCounter(float deltaTime) { if (coffee_crisis_status_ == Status::FINISHED && arcade_edition_status_ == Status::FINISHED) { - post_finished_timer_ += deltaTime; } } diff --git a/source/game_logo.h b/source/game_logo.h deleted file mode 100644 index 58e90e7..0000000 --- a/source/game_logo.h +++ /dev/null @@ -1,125 +0,0 @@ -#pragma once - -#include // Para unique_ptr, shared_ptr - -#include "animated_sprite.h" // Para AnimatedSprite -#include "smart_sprite.h" // Para SmartSprite -#include "sprite.h" // Para Sprite - -class Texture; - -// --- Clase GameLogo: gestor del logo del juego --- -class GameLogo { - public: - // --- Constantes --- - static constexpr float COFFEE_VEL_Y = 0.15F * 1000.0F; // Velocidad Y de coffee sprite (pixels/s) - 0.15F * 1000 = 150 pixels/s - static constexpr float COFFEE_ACCEL_Y = 0.00036F * 1000000.0F; // Aceleración Y de coffee sprite (pixels/s²) - 0.00036F * 1000000 = 360 pixels/s² - static constexpr float CRISIS_VEL_Y = -0.15F * 1000.0F; // Velocidad Y de crisis sprite (pixels/s) - -0.15F * 1000 = -150 pixels/s - static constexpr float CRISIS_ACCEL_Y = -0.00036F * 1000000.0F; // Aceleración Y de crisis sprite (pixels/s²) - -0.00036F * 1000000 = -360 pixels/s² - static constexpr int CRISIS_OFFSET_X = 15; // Desplazamiento X de crisis sprite - static constexpr int DUST_SIZE = 16; // Tamaño de dust sprites - static constexpr float ZOOM_DECREMENT_PER_S = 0.006F * 1000.0F; // Decremento de zoom por segundo (0.006F * 1000 = 6.0F per second) - static constexpr float SHAKE_DELAY_S = 33.34F / 1000.0F; // Delay de shake en segundos (33.34ms / 1000 = 0.03334s) - static constexpr float POST_FINISHED_FRAME_TIME_S = 16.67F / 1000.0F; // Tiempo entre decrementos del counter (16.67ms / 1000 = 0.01667s) - - // --- Constructores y destructor --- - GameLogo(int x, int y); - ~GameLogo() = default; - - // --- Métodos principales --- - void render(); // Pinta la clase en pantalla - void update(float deltaTime); // Actualiza la lógica de la clase (time-based) - void enable(); // Activa la clase - - // --- Getters --- - [[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación - - private: - // --- Enums --- - enum class Status { - DISABLED, // Deshabilitado - MOVING, // En movimiento - SHAKING, // Temblando - FINISHED, // Terminado - }; - - // --- Estructuras privadas --- - struct Shake { - int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x - int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse (frame-based) - int length = 8; // Cantidad de desplazamientos a realizar - int remaining = length; // Cantidad de desplazamientos pendientes a realizar - int counter = delay; // Contador para el retraso (frame-based) - float time_accumulator = 0.0f; // Acumulador de tiempo para deltaTime - int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento - - Shake() = default; - Shake(int d, int de, int l, int o) - : desp(d), - delay(de), - length(l), - remaining(l), - counter(de), - origin(o) {} - - void init(int d, int de, int l, int o) { - desp = d; - delay = de; - length = l; - remaining = l; - counter = de; - time_accumulator = 0.0f; - origin = o; - } - }; - - // --- Objetos y punteros --- - std::shared_ptr dust_texture_; // Textura con los graficos del polvo - std::shared_ptr coffee_texture_; // Textura con los graficos de la palabra "COFFEE" - std::shared_ptr crisis_texture_; // Textura con los graficos de la palabra "CRISIS" - std::shared_ptr arcade_edition_texture_; // Textura con los graficos de "Arcade Edition" - - std::unique_ptr dust_left_sprite_; // Sprite del polvo (izquierda) - std::unique_ptr dust_right_sprite_; // Sprite del polvo (derecha) - std::unique_ptr coffee_sprite_; // Sprite de "COFFEE" - std::unique_ptr crisis_sprite_; // Sprite de "CRISIS" - std::unique_ptr arcade_edition_sprite_; // Sprite de "Arcade Edition" - - // --- Variables de estado --- - Shake shake_; // Efecto de agitación - Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS" - Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION" - float x_; // Posición X del logo - float y_; // Posición Y del logo - float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION" - float post_finished_delay_s_ = POST_FINISHED_FRAME_TIME_S; // Retraso final tras animaciones (s) - float post_finished_timer_ = 0.0f; // Timer acumulado para retraso final (s) - - // --- Inicialización --- - void init(); // Inicializa las variables - [[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial - - // --- Actualización de estados específicos --- - void updateCoffeeCrisis(float deltaTime); // Actualiza el estado de "Coffee Crisis" (time-based) - void updateArcadeEdition(float deltaTime); // Actualiza el estado de "Arcade Edition" (time-based) - void updatePostFinishedCounter(float deltaTime); // Actualiza el contador tras finalizar una animación (time-based) - - // --- Efectos visuales: movimiento y sacudidas --- - void handleCoffeeCrisisMoving(float deltaTime); // Maneja el movimiento de "Coffee Crisis" (time-based) - void handleCoffeeCrisisShaking(float deltaTime); // Maneja la sacudida de "Coffee Crisis" (time-based) - void handleArcadeEditionMoving(float deltaTime); // Maneja el movimiento de "Arcade Edition" (time-based) - void handleArcadeEditionShaking(float deltaTime); // Maneja la sacudida de "Arcade Edition" (time-based) - void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite = nullptr); // Procesa el efecto de sacudida en sprites (frame-based) - void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime); // Procesa el efecto de sacudida en sprites (time-based) - void processArcadeEditionShake(float deltaTime); // Procesa la sacudida específica de "Arcade Edition" (time-based) - [[nodiscard]] auto calculateShakeDisplacement() const -> int; // Calcula el desplazamiento de la sacudida - - // --- Gestión de finalización de efectos --- - void handleCoffeeCrisisFinished(float deltaTime); // Maneja el final de la animación "Coffee Crisis" (time-based) - void finishCoffeeCrisisShaking(); // Finaliza la sacudida de "Coffee Crisis" - void finishArcadeEditionMoving(); // Finaliza el movimiento de "Arcade Edition" - - // --- Utilidades --- - static void playTitleEffects(); // Reproduce efectos visuales/sonoros del título - void updateDustSprites(float deltaTime); // Actualiza los sprites de polvo (time-based) -}; \ No newline at end of file diff --git a/source/game_logo.hpp b/source/game_logo.hpp new file mode 100644 index 0000000..4dba500 --- /dev/null +++ b/source/game_logo.hpp @@ -0,0 +1,125 @@ +#pragma once + +#include // Para unique_ptr, shared_ptr + +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "smart_sprite.hpp" // Para SmartSprite +#include "sprite.hpp" // Para Sprite + +class Texture; + +// --- Clase GameLogo: gestor del logo del juego --- +class GameLogo { + public: + // --- Constantes --- + static constexpr float COFFEE_VEL_Y = 0.15F * 1000.0F; // Velocidad Y de coffee sprite (pixels/s) - 0.15F * 1000 = 150 pixels/s + static constexpr float COFFEE_ACCEL_Y = 0.00036F * 1000000.0F; // Aceleración Y de coffee sprite (pixels/s²) - 0.00036F * 1000000 = 360 pixels/s² + static constexpr float CRISIS_VEL_Y = -0.15F * 1000.0F; // Velocidad Y de crisis sprite (pixels/s) - -0.15F * 1000 = -150 pixels/s + static constexpr float CRISIS_ACCEL_Y = -0.00036F * 1000000.0F; // Aceleración Y de crisis sprite (pixels/s²) - -0.00036F * 1000000 = -360 pixels/s² + static constexpr int CRISIS_OFFSET_X = 15; // Desplazamiento X de crisis sprite + static constexpr int DUST_SIZE = 16; // Tamaño de dust sprites + static constexpr float ZOOM_DECREMENT_PER_S = 0.006F * 1000.0F; // Decremento de zoom por segundo (0.006F * 1000 = 6.0F per second) + static constexpr float SHAKE_DELAY_S = 33.34F / 1000.0F; // Delay de shake en segundos (33.34ms / 1000 = 0.03334s) + static constexpr float POST_FINISHED_FRAME_TIME_S = 16.67F / 1000.0F; // Tiempo entre decrementos del counter (16.67ms / 1000 = 0.01667s) + + // --- Constructores y destructor --- + GameLogo(int x, int y); + ~GameLogo() = default; + + // --- Métodos principales --- + void render(); // Pinta la clase en pantalla + void update(float deltaTime); // Actualiza la lógica de la clase (time-based) + void enable(); // Activa la clase + + // --- Getters --- + [[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación + + private: + // --- Enums --- + enum class Status { + DISABLED, // Deshabilitado + MOVING, // En movimiento + SHAKING, // Temblando + FINISHED, // Terminado + }; + + // --- Estructuras privadas --- + struct Shake { + int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x + int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse (frame-based) + int length = 8; // Cantidad de desplazamientos a realizar + int remaining = length; // Cantidad de desplazamientos pendientes a realizar + int counter = delay; // Contador para el retraso (frame-based) + float time_accumulator = 0.0f; // Acumulador de tiempo para deltaTime + int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento + + Shake() = default; + Shake(int d, int de, int l, int o) + : desp(d), + delay(de), + length(l), + remaining(l), + counter(de), + origin(o) {} + + void init(int d, int de, int l, int o) { + desp = d; + delay = de; + length = l; + remaining = l; + counter = de; + time_accumulator = 0.0f; + origin = o; + } + }; + + // --- Objetos y punteros --- + std::shared_ptr dust_texture_; // Textura con los graficos del polvo + std::shared_ptr coffee_texture_; // Textura con los graficos de la palabra "COFFEE" + std::shared_ptr crisis_texture_; // Textura con los graficos de la palabra "CRISIS" + std::shared_ptr arcade_edition_texture_; // Textura con los graficos de "Arcade Edition" + + std::unique_ptr dust_left_sprite_; // Sprite del polvo (izquierda) + std::unique_ptr dust_right_sprite_; // Sprite del polvo (derecha) + std::unique_ptr coffee_sprite_; // Sprite de "COFFEE" + std::unique_ptr crisis_sprite_; // Sprite de "CRISIS" + std::unique_ptr arcade_edition_sprite_; // Sprite de "Arcade Edition" + + // --- Variables de estado --- + Shake shake_; // Efecto de agitación + Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS" + Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION" + float x_; // Posición X del logo + float y_; // Posición Y del logo + float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION" + float post_finished_delay_s_ = POST_FINISHED_FRAME_TIME_S; // Retraso final tras animaciones (s) + float post_finished_timer_ = 0.0f; // Timer acumulado para retraso final (s) + + // --- Inicialización --- + void init(); // Inicializa las variables + [[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial + + // --- Actualización de estados específicos --- + void updateCoffeeCrisis(float deltaTime); // Actualiza el estado de "Coffee Crisis" (time-based) + void updateArcadeEdition(float deltaTime); // Actualiza el estado de "Arcade Edition" (time-based) + void updatePostFinishedCounter(float deltaTime); // Actualiza el contador tras finalizar una animación (time-based) + + // --- Efectos visuales: movimiento y sacudidas --- + void handleCoffeeCrisisMoving(float deltaTime); // Maneja el movimiento de "Coffee Crisis" (time-based) + void handleCoffeeCrisisShaking(float deltaTime); // Maneja la sacudida de "Coffee Crisis" (time-based) + void handleArcadeEditionMoving(float deltaTime); // Maneja el movimiento de "Arcade Edition" (time-based) + void handleArcadeEditionShaking(float deltaTime); // Maneja la sacudida de "Arcade Edition" (time-based) + void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite = nullptr); // Procesa el efecto de sacudida en sprites (frame-based) + void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime); // Procesa el efecto de sacudida en sprites (time-based) + void processArcadeEditionShake(float deltaTime); // Procesa la sacudida específica de "Arcade Edition" (time-based) + [[nodiscard]] auto calculateShakeDisplacement() const -> int; // Calcula el desplazamiento de la sacudida + + // --- Gestión de finalización de efectos --- + void handleCoffeeCrisisFinished(float deltaTime); // Maneja el final de la animación "Coffee Crisis" (time-based) + void finishCoffeeCrisisShaking(); // Finaliza la sacudida de "Coffee Crisis" + void finishArcadeEditionMoving(); // Finaliza el movimiento de "Arcade Edition" + + // --- Utilidades --- + static void playTitleEffects(); // Reproduce efectos visuales/sonoros del título + void updateDustSprites(float deltaTime); // Actualiza los sprites de polvo (time-based) +}; \ No newline at end of file diff --git a/source/gamepad_config_manager.h b/source/gamepad_config_manager.hpp similarity index 98% rename from source/gamepad_config_manager.h rename to source/gamepad_config_manager.hpp index 31e1041..1714275 100644 --- a/source/gamepad_config_manager.h +++ b/source/gamepad_config_manager.hpp @@ -6,7 +6,7 @@ #include #include "external/json.hpp" -#include "input_types.h" // Solo incluimos los tipos compartidos +#include "input_types.hpp" // Solo incluimos los tipos compartidos // --- Estructuras --- struct GamepadConfig { diff --git a/source/global_events.cpp b/source/global_events.cpp index 5a7c571..f1bb7d6 100644 --- a/source/global_events.cpp +++ b/source/global_events.cpp @@ -1,4 +1,4 @@ -#include "global_events.h" +#include "global_events.hpp" #include // Para SDL_EventType, SDL_Event, SDL_LogInfo, SDL_LogCategory @@ -6,19 +6,19 @@ #include // Para allocator, operator+, string #include // Para vector -#include "input.h" // Para Input -#include "lang.h" // Para getText -#include "mouse.h" // Para handleEvent -#include "options.h" // Para GamepadManager, gamepad_manager -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, Options, name, options -#include "ui/notifier.h" // Para Notifier -#include "ui/service_menu.h" // Para ServiceMenu +#include "input.hpp" // Para Input +#include "lang.hpp" // Para getText +#include "mouse.hpp" // Para handleEvent +#include "options.hpp" // Para GamepadManager, gamepad_manager +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, Options, name, options +#include "ui/notifier.hpp" // Para Notifier +#include "ui/service_menu.hpp" // Para ServiceMenu namespace GlobalEvents { // Comprueba los eventos de Input y muestra notificaciones -void handleInputEvents(const SDL_Event &event) { - static auto *input_ = Input::get(); +void handleInputEvents(const SDL_Event& event) { + static auto* input_ = Input::get(); auto message = input_->handleEvent(event); if (message.empty()) { @@ -41,7 +41,7 @@ void handleInputEvents(const SDL_Event &event) { } // Comprueba los eventos que se pueden producir en cualquier sección del juego -void handle(const SDL_Event &event) { +void handle(const SDL_Event& event) { switch (event.type) { case SDL_EVENT_QUIT: // Evento de salida de la aplicación Section::name = Section::Name::QUIT; diff --git a/source/global_events.h b/source/global_events.hpp similarity index 78% rename from source/global_events.h rename to source/global_events.hpp index 5a654bd..b213aa4 100644 --- a/source/global_events.h +++ b/source/global_events.hpp @@ -5,5 +5,5 @@ // --- Namespace GlobalEvents: maneja eventos globales del juego --- namespace GlobalEvents { // --- Funciones --- -void handle(const SDL_Event &event); // Comprueba los eventos que se pueden producir en cualquier sección del juego +void handle(const SDL_Event& event); // Comprueba los eventos que se pueden producir en cualquier sección del juego } // namespace GlobalEvents \ No newline at end of file diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index 6f10fe2..76fa741 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -1,4 +1,4 @@ -#include "global_inputs.h" +#include "global_inputs.hpp" #include // Para std::ranges::any_of #include // Para function @@ -7,16 +7,16 @@ #include // Para pair #include // Para vector -#include "audio.h" // Para Audio -#include "input.h" // Para Input -#include "input_types.h" // Para InputAction -#include "lang.h" // Para getText, getLangFile, getLangName, getNextLangCode, loadFromFile -#include "options.h" // Para Video, video, Settings, settings, Audio, audio, Window, window -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode -#include "ui/notifier.h" // Para Notifier -#include "ui/service_menu.h" // Para ServiceMenu -#include "utils.h" // Para boolToOnOff +#include "audio.hpp" // Para Audio +#include "input.hpp" // Para Input +#include "input_types.hpp" // Para InputAction +#include "lang.hpp" // Para getText, getLangFile, getLangName, getNextLangCode, loadFromFile +#include "options.hpp" // Para Video, video, Settings, settings, Audio, audio, Window, window +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode +#include "ui/notifier.hpp" // Para Notifier +#include "ui/service_menu.hpp" // Para ServiceMenu +#include "utils.hpp" // Para boolToOnOff namespace GlobalInputs { // Termina diff --git a/source/global_inputs.h b/source/global_inputs.hpp similarity index 100% rename from source/global_inputs.h rename to source/global_inputs.hpp diff --git a/source/hit.h b/source/hit.hpp similarity index 95% rename from source/hit.h rename to source/hit.hpp index 72f1b2f..08901b4 100644 --- a/source/hit.h +++ b/source/hit.hpp @@ -4,8 +4,8 @@ #include // Para std::unique_ptr y std::shared_ptr -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture +#include "sprite.hpp" // Para Sprite +#include "texture.hpp" // Para Texture // --- Estructura Hit: representa una colisión o impacto visual --- struct Hit { diff --git a/source/input.cpp b/source/input.cpp index 5d4bf86..825faac 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -1,4 +1,4 @@ -#include "input.h" +#include "input.hpp" #include // Para SDL_GamepadButton, SDL_GetGamepadAxis, SDL_GetError, SDL_GamepadAxis, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogCategory, SDL_LogError, SDL_LogInfo, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, SDL_Gamepad, SDL_Scancode @@ -9,10 +9,10 @@ #include // Para pair, move // Singleton -Input *Input::instance = nullptr; +Input* Input::instance = nullptr; // Inicializa la instancia única del singleton -void Input::init(const std::string &game_controller_db_path, const std::string &gamepad_configs_file) { +void Input::init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file) { Input::instance = new Input(game_controller_db_path, gamepad_configs_file); } @@ -20,7 +20,7 @@ void Input::init(const std::string &game_controller_db_path, const std::string & void Input::destroy() { delete Input::instance; } // Obtiene la instancia -auto Input::get() -> Input * { return Input::instance; } +auto Input::get() -> Input* { return Input::instance; } // Constructor Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file) @@ -36,21 +36,21 @@ void Input::bindKey(Action action, SDL_Scancode code) { } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(const std::shared_ptr &gamepad, Action action, SDL_GamepadButton button) { +void Input::bindGameControllerButton(const std::shared_ptr& gamepad, Action action, SDL_GamepadButton button) { if (gamepad != nullptr) { gamepad->bindings[action].button = button; } } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(const std::shared_ptr &gamepad, Action action_target, Action action_source) { +void Input::bindGameControllerButton(const std::shared_ptr& gamepad, Action action_target, Action action_source) { if (gamepad != nullptr) { gamepad->bindings[action_target].button = gamepad->bindings[action_source].button; } } // Comprueba si alguna acción está activa -auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr &gamepad) -> bool { +auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr& gamepad) -> bool { bool success_keyboard = false; bool success_controller = false; @@ -82,12 +82,12 @@ auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const s } // Comprueba si hay almenos una acción activa -auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr &gamepad) -> bool { +auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr& gamepad) -> bool { // Obtenemos el número total de acciones posibles para iterar sobre ellas. // --- Comprobación del Teclado --- if (check_keyboard) { - for (const auto &pair : keyboard_.bindings) { + for (const auto& pair : keyboard_.bindings) { // Simplemente leemos el estado pre-calculado por Input::update(). // Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'. if (pair.second.just_pressed) { @@ -100,7 +100,7 @@ auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr &g // Comprobamos si hay mandos y si el índice solicitado es válido. if (gamepad != nullptr) { // Iteramos sobre todas las acciones, no sobre el número de mandos. - for (const auto &pair : gamepad->bindings) { + for (const auto& pair : gamepad->bindings) { // Leemos el estado pre-calculado para el mando y la acción específicos. if (pair.second.just_pressed) { return true; // Se encontró una acción recién pulsada en el mando. @@ -122,7 +122,7 @@ auto Input::checkAnyButton(bool repeat) -> bool { } // Comprueba los mandos - for (const auto &gamepad : gamepads_) { + for (const auto& gamepad : gamepads_) { if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) { return true; } @@ -136,14 +136,14 @@ auto Input::checkAnyButton(bool repeat) -> bool { auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); } // Obten el nombre de un mando de juego -auto Input::getControllerName(const std::shared_ptr &gamepad) -> std::string { +auto Input::getControllerName(const std::shared_ptr& gamepad) -> std::string { return gamepad == nullptr ? std::string() : gamepad->name; } // Obtiene la lista de nombres de mandos auto Input::getControllerNames() const -> std::vector { std::vector names; - for (const auto &gamepad : gamepads_) { + for (const auto& gamepad : gamepads_) { names.push_back(gamepad->name); } return names; @@ -154,7 +154,7 @@ auto Input::getNumGamepads() const -> int { return gamepads_.size(); } // Obtiene el gamepad a partir de un event.id auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr { - for (const auto &gamepad : gamepads_) { + for (const auto& gamepad : gamepads_) { if (gamepad->instance_id == id) { return gamepad; } @@ -162,8 +162,8 @@ auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr std::shared_ptr { - for (const auto &gamepad : gamepads_) { +auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr { + for (const auto& gamepad : gamepads_) { if (gamepad && gamepad->name == name) { return gamepad; } @@ -172,7 +172,7 @@ auto Input::getGamepadByName(const std::string &name) const -> std::shared_ptr &gamepad, Action action) -> SDL_GamepadButton { +auto Input::getControllerBinding(const std::shared_ptr& gamepad, Action action) -> SDL_GamepadButton { return static_cast(gamepad->bindings[action].button); } @@ -195,7 +195,7 @@ auto Input::inputToString(Action action) -> std::string { } // Convierte un std::string a InputAction -auto Input::stringToInput(const std::string &name) -> Action { +auto Input::stringToInput(const std::string& name) -> Action { static const std::unordered_map INPUT_MAP = { {"input_fire_left", Action::FIRE_LEFT}, {"input_fire_center", Action::FIRE_CENTER}, @@ -208,7 +208,7 @@ auto Input::stringToInput(const std::string &name) -> Action { } // Comprueba el eje del mando -auto Input::checkAxisInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool { +auto Input::checkAxisInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool { // Umbral para considerar el eje como activo bool axis_active_now = false; @@ -230,7 +230,7 @@ auto Input::checkAxisInput(Action action, const std::shared_ptr &gamepa } // Referencia al binding correspondiente - auto &binding = gamepad->bindings[action]; + auto& binding = gamepad->bindings[action]; if (repeat) { // Si se permite repetir, simplemente devolvemos el estado actual @@ -250,7 +250,7 @@ auto Input::checkAxisInput(Action action, const std::shared_ptr &gamepa } // Comprueba los triggers del mando como botones digitales -auto Input::checkTriggerInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool { +auto Input::checkTriggerInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool { // Solo manejamos botones específicos que pueden ser triggers if (gamepad->bindings[action].button != static_cast(SDL_GAMEPAD_BUTTON_INVALID)) { // Solo procesamos L2 y R2 como triggers @@ -272,7 +272,7 @@ auto Input::checkTriggerInput(Action action, const std::shared_ptr &gam } // Referencia al binding correspondiente - auto &binding = gamepad->bindings[action]; + auto& binding = gamepad->bindings[action]; if (repeat) { // Si se permite repetir, simplemente devolvemos el estado actual @@ -325,13 +325,13 @@ void Input::initSDLGamePad() { void Input::resetInputStates() { // Resetear todos los KeyBindings.active a false - for (auto &key : keyboard_.bindings) { + for (auto& key : keyboard_.bindings) { key.second.is_held = false; key.second.just_pressed = false; } // Resetear todos los ControllerBindings.active a false - for (auto &gamepad : gamepads_) { - for (auto &binding : gamepad->bindings) { + for (auto& gamepad : gamepads_) { + for (auto& binding : gamepad->bindings) { binding.second.is_held = false; binding.second.just_pressed = false; binding.second.trigger_active = false; @@ -341,9 +341,9 @@ void Input::resetInputStates() { void Input::update() { // --- TECLADO --- - const bool *key_states = SDL_GetKeyboardState(nullptr); + const bool* key_states = SDL_GetKeyboardState(nullptr); - for (auto &binding : keyboard_.bindings) { + for (auto& binding : keyboard_.bindings) { bool key_is_down_now = key_states[binding.second.scancode]; // El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo @@ -352,8 +352,8 @@ void Input::update() { } // --- MANDOS --- - for (const auto &gamepad : gamepads_) { - for (auto &binding : gamepad->bindings) { + for (const auto& gamepad : gamepads_) { + for (auto& binding : gamepad->bindings) { bool button_is_down_now = static_cast(SDL_GetGamepadButton(gamepad->pad, static_cast(binding.second.button))) != 0; // El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo @@ -363,7 +363,7 @@ void Input::update() { } } -auto Input::handleEvent(const SDL_Event &event) -> std::string { +auto Input::handleEvent(const SDL_Event& event) -> std::string { switch (event.type) { case SDL_EVENT_GAMEPAD_ADDED: return addGamepad(event.gdevice.which); @@ -374,7 +374,7 @@ auto Input::handleEvent(const SDL_Event &event) -> std::string { } auto Input::addGamepad(int device_index) -> std::string { - SDL_Gamepad *pad = SDL_OpenGamepad(device_index); + SDL_Gamepad* pad = SDL_OpenGamepad(device_index); if (pad == nullptr) { std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n'; return {}; @@ -390,7 +390,7 @@ auto Input::addGamepad(int device_index) -> std::string { } auto Input::removeGamepad(SDL_JoystickID id) -> std::string { - auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr &gamepad) { + auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr& gamepad) { return gamepad->instance_id == id; }); @@ -411,7 +411,7 @@ void Input::printConnectedGamepads() const { } std::cout << "Gamepads conectados:\n"; - for (const auto &gamepad : gamepads_) { + for (const auto& gamepad : gamepads_) { std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name; std::cout << " - ID: " << gamepad->instance_id << ", Nombre: " << name << ")" << '\n'; @@ -434,14 +434,14 @@ void Input::applyGamepadConfig(std::shared_ptr gamepad) { } // --- Buscar configuración por RUTA (path) --- - auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig &config) { + auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) { return config.path == gamepad->path; }); if (config_it != gamepad_configs_.end()) { // Se encontró una configuración específica para este puerto/dispositivo. La aplicamos. std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n'; - for (const auto &[action, button] : config_it->bindings) { + for (const auto& [action, button] : config_it->bindings) { if (gamepad->bindings.find(action) != gamepad->bindings.end()) { gamepad->bindings[action].button = button; } @@ -456,7 +456,7 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr gamepad) { } // --- CAMBIO CLAVE: Buscar si ya existe una configuración por RUTA (path) --- - auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig &config) { + auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) { return config.path == gamepad->path; }); @@ -465,7 +465,7 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr gamepad) { new_config.bindings.clear(); // Copiar todos los bindings actuales del gamepad - for (const auto &[action, buttonState] : gamepad->bindings) { + for (const auto& [action, buttonState] : gamepad->bindings) { new_config.bindings[action] = static_cast(buttonState.button); } @@ -482,14 +482,14 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr gamepad) { } // Método para establecer el archivo de configuración (opcional) -void Input::setGamepadConfigsFile(const std::string &filename) { +void Input::setGamepadConfigsFile(const std::string& filename) { gamepad_configs_file_ = filename; loadGamepadConfigs(); // Recargar con el nuevo archivo } // Método para obtener configuración de un gamepad específico (opcional) -auto Input::getGamepadConfig(const std::string &gamepad_name) -> GamepadConfig * { - auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig &config) { +auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig* { + auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) { return config.name == gamepad_name; }); @@ -497,8 +497,8 @@ auto Input::getGamepadConfig(const std::string &gamepad_name) -> GamepadConfig * } // Método para eliminar configuración de gamepad (opcional) -auto Input::removeGamepadConfig(const std::string &gamepad_name) -> bool { - auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig &config) { +auto Input::removeGamepadConfig(const std::string& gamepad_name) -> bool { + auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) { return config.name == gamepad_name; }); @@ -511,21 +511,21 @@ auto Input::removeGamepadConfig(const std::string &gamepad_name) -> bool { return false; } -auto Input::findAvailableGamepadByName(const std::string &gamepad_name) -> std::shared_ptr { +auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr { // Si no hay gamepads disponibles, devolver gamepad por defecto if (gamepads_.empty()) { return nullptr; } // Buscar por nombre - for (const auto &gamepad : gamepads_) { + for (const auto& gamepad : gamepads_) { if (gamepad && gamepad->name == gamepad_name) { return gamepad; } } // Si no se encuentra por nombre, devolver el primer gamepad válido - for (const auto &gamepad : gamepads_) { + for (const auto& gamepad : gamepads_) { if (gamepad) { return gamepad; } diff --git a/source/input.h b/source/input.hpp similarity index 88% rename from source/input.h rename to source/input.hpp index 37d9c76..bc3d816 100644 --- a/source/input.h +++ b/source/input.hpp @@ -8,8 +8,8 @@ #include // Para unordered_map #include // Para vector -#include "gamepad_config_manager.h" // Para GamepadConfig (ptr only), GamepadConfigs -#include "input_types.h" // Para InputAction +#include "gamepad_config_manager.hpp" // Para GamepadConfig (ptr only), GamepadConfigs +#include "input_types.hpp" // Para InputAction // --- Clase Input: gestiona la entrada de teclado y mandos (singleton) --- class Input { @@ -96,13 +96,13 @@ class Input { }; struct Gamepad { - SDL_Gamepad *pad; + SDL_Gamepad* pad; SDL_JoystickID instance_id; std::string name; std::string path; std::unordered_map bindings; - Gamepad(SDL_Gamepad *gamepad) + Gamepad(SDL_Gamepad* gamepad) : pad(gamepad), instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))), name(std::string(SDL_GetGamepadName(gamepad))), @@ -143,44 +143,44 @@ class Input { using Gamepads = std::vector>; // Vector de gamepads // --- Métodos de singleton --- - static void init(const std::string &game_controller_db_path, const std::string &gamepad_configs_file); + static void init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file); static void destroy(); - static auto get() -> Input *; + static auto get() -> Input*; // --- Métodos de configuración de controles --- void bindKey(Action action, SDL_Scancode code); - static void bindGameControllerButton(const std::shared_ptr &gamepad, Action action, SDL_GamepadButton button); - static void bindGameControllerButton(const std::shared_ptr &gamepad, Action action_target, Action action_source); + static void bindGameControllerButton(const std::shared_ptr& gamepad, Action action, SDL_GamepadButton button); + static void bindGameControllerButton(const std::shared_ptr& gamepad, Action action_target, Action action_source); // --- Métodos de consulta de entrada --- void update(); - auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr &gamepad = nullptr) -> bool; - auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr &gamepad = nullptr) -> bool; + auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr& gamepad = nullptr) -> bool; + auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr& gamepad = nullptr) -> bool; auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool; // --- Métodos de gestión de mandos --- [[nodiscard]] auto gameControllerFound() const -> bool; - static auto getControllerName(const std::shared_ptr &gamepad) -> std::string; + static auto getControllerName(const std::shared_ptr& gamepad) -> std::string; auto getControllerNames() const -> std::vector; [[nodiscard]] auto getNumGamepads() const -> int; auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr; - auto getGamepadByName(const std::string &name) const -> std::shared_ptr; - auto getGamepads() const -> const Gamepads & { return gamepads_; } + auto getGamepadByName(const std::string& name) const -> std::shared_ptr; + auto getGamepads() const -> const Gamepads& { return gamepads_; } // --- Métodos de consulta y utilidades --- - [[nodiscard]] static auto getControllerBinding(const std::shared_ptr &gamepad, Action action) -> SDL_GamepadButton; + [[nodiscard]] static auto getControllerBinding(const std::shared_ptr& gamepad, Action action) -> SDL_GamepadButton; [[nodiscard]] static auto inputToString(Action action) -> std::string; - [[nodiscard]] static auto stringToInput(const std::string &name) -> Action; + [[nodiscard]] static auto stringToInput(const std::string& name) -> Action; // --- Métodos de reseteo de estado de entrada --- void resetInputStates(); // --- Eventos --- - auto handleEvent(const SDL_Event &event) -> std::string; + auto handleEvent(const SDL_Event& event) -> std::string; void printConnectedGamepads() const; - auto findAvailableGamepadByName(const std::string &gamepad_name) -> std::shared_ptr; + auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr; void saveGamepadConfigFromGamepad(std::shared_ptr gamepad); private: @@ -198,8 +198,8 @@ class Input { // --- Métodos internos --- void initSDLGamePad(); - static auto checkAxisInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool; - static auto checkTriggerInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool; + static auto checkAxisInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool; + static auto checkTriggerInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool; auto addGamepad(int device_index) -> std::string; auto removeGamepad(SDL_JoystickID id) -> std::string; void addGamepadMappingsFromFile(); @@ -211,14 +211,14 @@ class Input { void applyGamepadConfig(std::shared_ptr gamepad); // Métodos auxiliares opcionales - void setGamepadConfigsFile(const std::string &filename); - auto getGamepadConfig(const std::string &gamepad_name) -> GamepadConfig *; - auto removeGamepadConfig(const std::string &gamepad_name) -> bool; + void setGamepadConfigsFile(const std::string& filename); + auto getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig*; + auto removeGamepadConfig(const std::string& gamepad_name) -> bool; // --- Constructor y destructor --- explicit Input(std::string game_controller_db_path, std::string gamepad_configs_file); ~Input() = default; // --- Singleton --- - static Input *instance; + static Input* instance; }; \ No newline at end of file diff --git a/source/input_types.cpp b/source/input_types.cpp index 745e40c..446147e 100644 --- a/source/input_types.cpp +++ b/source/input_types.cpp @@ -1,4 +1,4 @@ -#include "input_types.h" +#include "input_types.hpp" // Definición de los mapas const std::unordered_map ACTION_TO_STRING = { diff --git a/source/input_types.h b/source/input_types.hpp similarity index 100% rename from source/input_types.h rename to source/input_types.hpp diff --git a/source/item.cpp b/source/item.cpp index ceff45c..69da192 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -1,11 +1,11 @@ -#include "item.h" +#include "item.hpp" #include // Para clamp #include // Para fmod #include // Para rand -#include "animated_sprite.h" // Para AnimatedSprite -#include "param.h" // Para Param, ParamGame, param +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "param.hpp" // Para Param, ParamGame, param class Texture; // lines 6-6 diff --git a/source/item.h b/source/item.hpp similarity index 98% rename from source/item.h rename to source/item.hpp index 7051ea8..28997a7 100644 --- a/source/item.h +++ b/source/item.hpp @@ -6,8 +6,8 @@ #include // Para string #include // Para vector -#include "animated_sprite.h" // Para AnimatedSprite -#include "utils.h" // Para Circle +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "utils.hpp" // Para Circle class Texture; diff --git a/source/lang.cpp b/source/lang.cpp index b0082a8..05eb3c9 100644 --- a/source/lang.cpp +++ b/source/lang.cpp @@ -1,4 +1,4 @@ -#include "lang.h" +#include "lang.hpp" #include // Para size_t #include // Para exception @@ -7,11 +7,11 @@ #include // Para pair #include // Para vector -#include "asset.h" // Para Asset -#include "difficulty.h" // Para Difficulty -#include "external/json.hpp" // Para basic_json, iteration_proxy_value, oper... -#include "options.h" // Para SettingsOpt... -#include "resource_helper.h" // Para ResourceHelper +#include "asset.hpp" // Para Asset +#include "difficulty.hpp" // Para Difficulty +#include "external/json.hpp" // Para basic_json, iteration_proxy_value, oper... +#include "options.hpp" // Para SettingsOpt... +#include "resource_helper.hpp" // Para ResourceHelper using json = nlohmann::json; @@ -25,7 +25,7 @@ std::vector languages = { {Code::ENGLISH, "Ingles", "en_UK.json"}}; // Inicializa los textos del juego en el idioma seleccionado -auto loadFromFile(const std::string &file_path) -> bool { +auto loadFromFile(const std::string& file_path) -> bool { texts.clear(); // Intentar cargar desde ResourceHelper primero @@ -47,10 +47,10 @@ auto loadFromFile(const std::string &file_path) -> bool { rfile >> j; } - for (const auto &el : j.items()) { + for (const auto& el : j.items()) { texts[el.key()] = el.value(); } - } catch (const std::exception &e) { + } catch (const std::exception& e) { // Puedes loguear el error si quieres return false; } @@ -59,7 +59,7 @@ auto loadFromFile(const std::string &file_path) -> bool { } // Obtiene el texto por clave -auto getText(const std::string &key) -> std::string { +auto getText(const std::string& key) -> std::string { auto it = texts.find(key); if (it != texts.end()) { return it->second; @@ -80,7 +80,7 @@ auto getNextLangCode(Code lang) -> Code { // Obtiene un idioma del vector de idiomas a partir de un código auto getLanguage(Code code) -> Language { - for (const auto &lang : languages) { + for (const auto& lang : languages) { if (lang.code == code) { return lang; } @@ -90,8 +90,8 @@ auto getLanguage(Code code) -> Language { } // Devuelve el código de un idioma a partir de un nombre -auto getCodeFromName(const std::string &name) -> Code { - for (const auto &lang : languages) { +auto getCodeFromName(const std::string& name) -> Code { + for (const auto& lang : languages) { if (lang.name == name) { return lang.code; } @@ -102,7 +102,7 @@ auto getCodeFromName(const std::string &name) -> Code { // Devuelve el nombre de un idioma a partir de un código auto getNameFromCode(Code code) -> std::string { - for (const auto &lang : languages) { + for (const auto& lang : languages) { if (lang.code == code) { return lang.name; } @@ -113,7 +113,7 @@ auto getNameFromCode(Code code) -> std::string { // Actualiza los nombres de los idiomas void updateLanguageNames() { - for (auto &lang : languages) { + for (auto& lang : languages) { switch (lang.code) { case Code::SPANISH: lang.name = Lang::getText("[SERVICE_MENU] LANG_ES"); @@ -134,10 +134,10 @@ void updateLanguageNames() { // Actualiza los nombres de las dificultades void updateDifficultyNames() { // 1. Pide una referencia MODIFICABLE a la lista de dificultades - auto &difficulties = Difficulty::getDifficulties(); + auto& difficulties = Difficulty::getDifficulties(); // 2. Recorre la lista - for (auto &difficulty_info : difficulties) { + for (auto& difficulty_info : difficulties) { // 3. Para cada dificultad, usa su código para obtener el texto traducido y actualizar su nombre switch (difficulty_info.code) { case Difficulty::Code::EASY: @@ -155,7 +155,7 @@ void updateDifficultyNames() { // Obtiene una fichero a partir de un lang::Code auto getLanguageFileName(Lang::Code code) -> std::string { - for (const auto &lang : languages) { + for (const auto& lang : languages) { if (lang.code == code) { return Asset::get()->get(lang.file_name); } diff --git a/source/lang.h b/source/lang.hpp similarity index 90% rename from source/lang.h rename to source/lang.hpp index ed0b483..a64665c 100644 --- a/source/lang.h +++ b/source/lang.hpp @@ -25,11 +25,11 @@ struct Language { }; // --- Funciones --- -auto loadFromFile(const std::string &file_path) -> bool; // Carga los textos desde el fichero JSON especificado -auto getText(const std::string &key) -> std::string; // Obtiene el texto por clave +auto loadFromFile(const std::string& file_path) -> bool; // Carga los textos desde el fichero JSON especificado +auto getText(const std::string& key) -> std::string; // Obtiene el texto por clave auto getNextLangCode(Code current_lang) -> Code; // Obtiene el código del siguiente idioma (circular) auto getLanguage(Code code) -> Language; // Obtiene el idioma correspondiente al código proporcionado -auto getCodeFromName(const std::string &name) -> Code; // Devuelve el código de un idioma a partir de un nombre +auto getCodeFromName(const std::string& name) -> Code; // Devuelve el código de un idioma a partir de un nombre auto getNameFromCode(Code code) -> std::string; // Devuelve el nombre de un idioma a partir de un código void updateLanguageNames(); // Actualiza los nombres de los idiomas auto getLanguageFileName(Code code) -> std::string; // Obtiene el nombre del fichero de textos asociado a un código de idioma diff --git a/source/main.cpp b/source/main.cpp index f1df7b5..229210e 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -10,7 +10,7 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024 #include // Para make_unique, unique_ptr #include // Para span -#include "director.h" // Para Director +#include "director.hpp" // Para Director auto main(int argc, char* argv[]) -> int { // Crea el objeto Director diff --git a/source/manage_hiscore_table.cpp b/source/manage_hiscore_table.cpp index 6ecdced..7f1f96b 100644 --- a/source/manage_hiscore_table.cpp +++ b/source/manage_hiscore_table.cpp @@ -1,11 +1,11 @@ -#include "manage_hiscore_table.h" +#include "manage_hiscore_table.hpp" #include // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO, SDL_GetError, SDL_IOFromFile, SDL_LogCategory, SDL_LogError, SDL_LogInfo #include // Para find_if, sort #include // Para distance -#include "utils.h" // Para getFileName +#include "utils.hpp" // Para getFileName // Resetea la tabla a los valores por defecto void ManageHiScoreTable::clear() { @@ -54,7 +54,7 @@ void ManageHiScoreTable::clear() { } // Añade un elemento a la tabla -auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int { +auto ManageHiScoreTable::add(const HiScoreEntry& entry) -> int { // Añade la entrada a la tabla table_.push_back(entry); @@ -62,7 +62,7 @@ auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int { sort(); // Encontrar la posición del nuevo elemento - auto it = std::ranges::find_if(table_, [&](const HiScoreEntry &e) { + auto it = std::ranges::find_if(table_, [&](const HiScoreEntry& e) { return e.name == entry.name && e.score == entry.score && e.one_credit_complete == entry.one_credit_complete; }); @@ -89,17 +89,17 @@ auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int { void ManageHiScoreTable::sort() { struct { - auto operator()(const HiScoreEntry &a, const HiScoreEntry &b) const -> bool { return a.score > b.score; } + auto operator()(const HiScoreEntry& a, const HiScoreEntry& b) const -> bool { return a.score > b.score; } } score_descending_comparator; std::ranges::sort(table_, score_descending_comparator); } // Carga la tabla desde un fichero -auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool { +auto ManageHiScoreTable::loadFromFile(const std::string& file_path) -> bool { clear(); auto success = true; - auto *file = SDL_IOFromFile(file_path.c_str(), "rb"); + auto* file = SDL_IOFromFile(file_path.c_str(), "rb"); if (file != nullptr) { table_.clear(); // Limpia la tabla actual @@ -143,9 +143,9 @@ auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool { } // Guarda la tabla en un fichero -auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool { +auto ManageHiScoreTable::saveToFile(const std::string& file_path) -> bool { auto success = true; - auto *file = SDL_IOFromFile(file_path.c_str(), "w+b"); + auto* file = SDL_IOFromFile(file_path.c_str(), "w+b"); if (file != nullptr) { // Guarda el número de entradas en la tabla @@ -154,7 +154,7 @@ auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool { // Guarda los datos de cada entrada for (int i = 0; i < table_size; ++i) { - const HiScoreEntry &entry = table_.at(i); + const HiScoreEntry& entry = table_.at(i); // Guarda la puntuación SDL_WriteIO(file, &entry.score, sizeof(int)); diff --git a/source/manage_hiscore_table.h b/source/manage_hiscore_table.hpp similarity index 77% rename from source/manage_hiscore_table.h rename to source/manage_hiscore_table.hpp index 76a2b68..5ee9566 100644 --- a/source/manage_hiscore_table.h +++ b/source/manage_hiscore_table.hpp @@ -10,7 +10,7 @@ struct HiScoreEntry { bool one_credit_complete; // Indica si se ha conseguido 1CC // Constructor - explicit HiScoreEntry(const std::string &name = "", int score = 0, bool one_credit_complete = false) + explicit HiScoreEntry(const std::string& name = "", int score = 0, bool one_credit_complete = false) : name(name.substr(0, 6)), score(score), one_credit_complete(one_credit_complete) {} @@ -26,19 +26,19 @@ class ManageHiScoreTable { static constexpr int NO_ENTRY = -1; // --- Constructor y destructor --- - explicit ManageHiScoreTable(Table &table) // Constructor con referencia a tabla + explicit ManageHiScoreTable(Table& table) // Constructor con referencia a tabla : table_(table) {} ~ManageHiScoreTable() = default; // Destructor // --- Métodos públicos --- void clear(); // Resetea la tabla a los valores por defecto - auto add(const HiScoreEntry &entry) -> int; // Añade un elemento a la tabla (devuelve la posición en la que se inserta) - auto loadFromFile(const std::string &file_path) -> bool; // Carga la tabla con los datos de un fichero - auto saveToFile(const std::string &file_path) -> bool; // Guarda la tabla en un fichero + auto add(const HiScoreEntry& entry) -> int; // Añade un elemento a la tabla (devuelve la posición en la que se inserta) + auto loadFromFile(const std::string& file_path) -> bool; // Carga la tabla con los datos de un fichero + auto saveToFile(const std::string& file_path) -> bool; // Guarda la tabla en un fichero private: // --- Variables privadas --- - Table &table_; // Referencia a la tabla con los records + Table& table_; // Referencia a la tabla con los records // --- Métodos privados --- void sort(); // Ordena la tabla diff --git a/source/mouse.cpp b/source/mouse.cpp index 02080d9..0ae7249 100644 --- a/source/mouse.cpp +++ b/source/mouse.cpp @@ -1,4 +1,4 @@ -#include "mouse.h" +#include "mouse.hpp" #include // Para SDL_GetTicks, Uint32, SDL_HideCursor, SDL_Show... @@ -7,7 +7,7 @@ Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el curs Uint32 last_mouse_move_time = 0; // Última vez que el ratón se movió bool cursor_visible = true; // Estado del cursor -void handleEvent(const SDL_Event &event) { +void handleEvent(const SDL_Event& event) { if (event.type == SDL_EVENT_MOUSE_MOTION) { last_mouse_move_time = SDL_GetTicks(); if (!cursor_visible) { diff --git a/source/mouse.h b/source/mouse.hpp similarity index 90% rename from source/mouse.h rename to source/mouse.hpp index a7ff0c3..c61f122 100644 --- a/source/mouse.h +++ b/source/mouse.hpp @@ -10,6 +10,6 @@ extern Uint32 last_mouse_move_time; // Última vez (en ms) que el ratón se mov extern bool cursor_visible; // Indica si el cursor está visible // --- Funciones --- -void handleEvent(const SDL_Event &event); // Procesa eventos de ratón (movimiento, clic, etc.) +void handleEvent(const SDL_Event& event); // Procesa eventos de ratón (movimiento, clic, etc.) void updateCursorVisibility(); // Actualiza la visibilidad del cursor según la inactividad } // namespace Mouse \ No newline at end of file diff --git a/source/moving_sprite.cpp b/source/moving_sprite.cpp index f453607..159be3c 100644 --- a/source/moving_sprite.cpp +++ b/source/moving_sprite.cpp @@ -1,9 +1,9 @@ -#include "moving_sprite.h" +#include "moving_sprite.hpp" -#include // Para std::abs +#include // Para std::abs #include -#include "texture.h" // Para Texture +#include "texture.hpp" // Para Texture // Constructor MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos, Rotate rotate, float horizontal_zoom, float vertical_zoom, SDL_FlipMode flip) @@ -75,7 +75,7 @@ void MovingSprite::update(float deltaTime) { } // Muestra el sprite por pantalla -void MovingSprite::render() { +void MovingSprite::render() { getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_); } diff --git a/source/moving_sprite.h b/source/moving_sprite.hpp similarity index 99% rename from source/moving_sprite.h rename to source/moving_sprite.hpp index 163cfe0..85b9ebe 100644 --- a/source/moving_sprite.h +++ b/source/moving_sprite.hpp @@ -5,7 +5,7 @@ #include // Para max #include // Para shared_ptr -#include "sprite.h" // Para Sprite +#include "sprite.hpp" // Para Sprite class Texture; diff --git a/source/options.cpp b/source/options.cpp index 7909403..5e7a386 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -1,4 +1,4 @@ -#include "options.h" +#include "options.hpp" #include // Para SDL_ScaleMode, SDL_GamepadButton, SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn @@ -6,18 +6,18 @@ #include // Para size_t #include // Para basic_ostream, operator<<, basic_ostream::operator<<, basic_ofstream, basic_istream, basic_ifstream, ifstream, ofstream #include // Para function -#include // Para istringstream #include // Para map, operator==, _Rb_tree_const_iterator #include // Para std::ranges::any_of +#include // Para istringstream #include // Para invalid_argument, out_of_range #include // Para char_traits, stoi, operator==, operator<<, allocator, string, basic_string, operator<=>, getline #include // Para swap, pair #include // Para vector -#include "difficulty.h" // Para Code, init -#include "input.h" // Para InputDevice -#include "lang.h" // Para Code -#include "utils.h" // Para boolToString, stringToBool, getFileName +#include "difficulty.hpp" // Para Code, init +#include "input.hpp" // Para InputDevice +#include "lang.hpp" // Para Code +#include "utils.hpp" // Para boolToString, stringToBool, getFileName namespace Options { // --- Variables globales --- @@ -59,7 +59,7 @@ auto loadFromFile() -> bool { init(); std::ifstream file(settings.config_file); - bool file_exists = file.is_open(); // Guardamos si el fichero existía al abrirlo + bool file_exists = file.is_open(); // Guardamos si el fichero existía al abrirlo // 2. Si el fichero existe, lo leemos para obtener los nombres de los mandos. if (file_exists) { @@ -105,7 +105,6 @@ auto loadFromFile() -> bool { return true; } - // Guarda el fichero de configuración auto saveToFile() -> bool { std::ofstream file(settings.config_file); diff --git a/source/options.h b/source/options.hpp similarity index 97% rename from source/options.h rename to source/options.hpp index 4920a42..cb28f78 100644 --- a/source/options.h +++ b/source/options.hpp @@ -14,12 +14,12 @@ #include // Para swap #include // Para vector -#include "defaults.h" // Para GameDefaults -#include "difficulty.h" // Para Code -#include "input.h" // Para Input -#include "lang.h" // Para Code -#include "manage_hiscore_table.h" // Para ManageHiScoreTable, Table -#include "player.h" // Para Player +#include "defaults.hpp" // Para GameDefaults +#include "difficulty.hpp" // Para Code +#include "input.hpp" // Para Input +#include "lang.hpp" // Para Code +#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable, Table +#include "player.hpp" // Para Player // --- Namespace Options: gestión de configuración y opciones del juego --- namespace Options { diff --git a/source/param.cpp b/source/param.cpp index dba51ff..6963fe7 100644 --- a/source/param.cpp +++ b/source/param.cpp @@ -1,4 +1,4 @@ -#include "param.h" +#include "param.hpp" #include // Para SDL_LogCategory, SDL_LogError, SDL_LogInfo @@ -9,9 +9,9 @@ #include // Para operator==, stoi, char_traits, string, ope... #include -#include "color.h" -#include "ui/notifier.h" // Para Notifier::Position -#include "utils.h" +#include "color.hpp" +#include "ui/notifier.hpp" // Para Notifier::Position +#include "utils.hpp" // Variable global - ahora se inicializa automáticamente con valores por defecto Param param; @@ -90,7 +90,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool { {"game.play_area.rect.x", [](const std::string& v) { param.game.play_area.rect.x = std::stoi(v); }}, {"game.play_area.rect.y", [](const std::string& v) { param.game.play_area.rect.y = std::stoi(v); }}, {"game.play_area.rect.w", [](const std::string& v) { param.game.play_area.rect.w = std::stoi(v); }}, - {"game.play_area.rect.h", [](const std::string& v) { param.game.play_area.rect.h = std::stoi(v); }}, + {"game.play_area.rect.hpp", [](const std::string& v) { param.game.play_area.rect.h = std::stoi(v); }}, {"game.name_entry_idle_time", [](const std::string& v) { param.game.name_entry_idle_time = std::stoi(v); }}, {"game.name_entry_total_time", [](const std::string& v) { param.game.name_entry_total_time = std::stoi(v); }}, {"game.hit_stop_ms", [](const std::string& v) { param.game.hit_stop_ms = std::stoi(v); }}, @@ -102,7 +102,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool { {"scoreboard.rect.x", [](const std::string& v) { param.scoreboard.rect.x = std::stoi(v); }}, {"scoreboard.rect.y", [](const std::string& v) { param.scoreboard.rect.y = std::stoi(v); }}, {"scoreboard.rect.w", [](const std::string& v) { param.scoreboard.rect.w = std::stoi(v); }}, - {"scoreboard.rect.h", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }}, + {"scoreboard.rect.hpp", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }}, {"scoreboard.skip_countdown_value", [](const std::string& v) { param.scoreboard.skip_countdown_value = std::stoi(v); }}, {"title.press_start_position", [](const std::string& v) { param.title.press_start_position = std::stoi(v); }}, {"title.arcade_edition_position", [](const std::string& v) { param.title.arcade_edition_position = std::stoi(v); }}, diff --git a/source/param.h b/source/param.hpp similarity index 98% rename from source/param.h rename to source/param.hpp index 3758a53..5ab69a2 100644 --- a/source/param.h +++ b/source/param.hpp @@ -5,10 +5,10 @@ #include // Para array #include // Para basic_string, string -#include "color.h" // Para Color, Zone -#include "defaults.h" // Para los valores por defecto -#include "ui/notifier.h" // Para Notifier::Position -#include "utils.h" +#include "color.hpp" // Para Color, Zone +#include "defaults.hpp" // Para los valores por defecto +#include "ui/notifier.hpp" // Para Notifier::Position +#include "utils.hpp" // --- Parámetros del juego --- struct ParamGame { diff --git a/source/path_sprite.cpp b/source/path_sprite.cpp index 1407cf3..1740dcc 100644 --- a/source/path_sprite.cpp +++ b/source/path_sprite.cpp @@ -1,17 +1,18 @@ // IWYU pragma: no_include -#include "path_sprite.h" +#include "path_sprite.hpp" #include // Para function #include // Para move // Constructor para paths por puntos (convertido a segundos) -Path::Path(const std::vector &spots_init, float waiting_time_s_init) - : spots(spots_init), is_point_path(true) { +Path::Path(const std::vector& spots_init, float waiting_time_s_init) + : spots(spots_init), + is_point_path(true) { waiting_time_s = waiting_time_s_init; } // Devuelve un vector con los puntos que conforman la ruta -auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function &easing_function) -> std::vector { +auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function& easing_function) -> std::vector { std::vector v; v.reserve(steps); @@ -74,50 +75,50 @@ void PathSprite::addPath(Path path, bool centered) { switch (path_centered) { case PathCentered::ON_X: { // Centrar en el eje X (para paths Verticales) - const float X_offset = pos_.w / 2.0f; // Asume que pos_.w está inicializado por el constructor de Sprite + const float X_offset = pos_.w / 2.0f; // Asume que pos_.w está inicializado por el constructor de Sprite if (path.is_point_path) { const float X_base = !path.spots.empty() ? path.spots.front().x : 0.0f; const float X = X_base - X_offset; - for (auto &spot : path.spots) { + for (auto& spot : path.spots) { spot.x = X; } } else { // Es un path generado, ajustamos la posición fija (que es X) path.fixed_pos -= X_offset; } - paths_.emplace_back(std::move(path)); // Usamos std::move + paths_.emplace_back(std::move(path)); // Usamos std::move break; } case PathCentered::ON_Y: { // Centrar en el eje Y (para paths Horizontales) - const float Y_offset = pos_.h / 2.0f; // Asume que pos_.h está inicializado + const float Y_offset = pos_.h / 2.0f; // Asume que pos_.h está inicializado if (path.is_point_path) { const float Y_base = !path.spots.empty() ? path.spots.front().y : 0.0f; const float Y = Y_base - Y_offset; - for (auto &spot : path.spots) { + for (auto& spot : path.spots) { spot.y = Y; } } else { // Es un path generado, ajustamos la posición fija (que es Y) path.fixed_pos -= Y_offset; } - paths_.emplace_back(std::move(path)); // Usamos std::move + paths_.emplace_back(std::move(path)); // Usamos std::move break; } default: // Sin centrado - paths_.emplace_back(std::move(path)); // Usamos std::move + paths_.emplace_back(std::move(path)); // Usamos std::move break; } } // Añade un recorrido generado (en segundos) -void PathSprite::addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function &easing_function, float waiting_time_s) { +void PathSprite::addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function& easing_function, float waiting_time_s) { paths_.emplace_back(start, end, type, fixed_pos, duration_s, waiting_time_s, easing_function); } // Añade un recorrido por puntos (en segundos) -void PathSprite::addPath(const std::vector &spots, float waiting_time_s) { +void PathSprite::addPath(const std::vector& spots, float waiting_time_s) { paths_.emplace_back(spots, waiting_time_s); } @@ -130,9 +131,9 @@ void PathSprite::enable() { enabled_ = true; // Establece la posición inicial - auto &path = paths_.at(current_path_); + auto& path = paths_.at(current_path_); if (path.is_point_path) { - const auto &p = path.spots.at(path.counter); + const auto& p = path.spots.at(path.counter); setPosition(p); } else { // Para paths generados, establecer posición inicial @@ -148,11 +149,11 @@ void PathSprite::enable() { // Coloca el sprite en los diferentes puntos del recorrido void PathSprite::moveThroughCurrentPath(float delta_time) { - auto &path = paths_.at(current_path_); + auto& path = paths_.at(current_path_); if (path.is_point_path) { // Lógica para paths por puntos (compatibilidad) - const auto &p = path.spots.at(path.counter); + const auto& p = path.spots.at(path.counter); setPosition(p); if (!path.on_destination) { diff --git a/source/path_sprite.h b/source/path_sprite.hpp similarity index 57% rename from source/path_sprite.h rename to source/path_sprite.hpp index a957ba8..444a6d1 100644 --- a/source/path_sprite.h +++ b/source/path_sprite.hpp @@ -7,7 +7,7 @@ #include #include // Para vector -#include "sprite.h" // Para Sprite +#include "sprite.hpp" // Para Sprite class Texture; @@ -24,26 +24,31 @@ enum class PathCentered { // Centrado del recorrido }; // --- Estructuras --- -struct Path { // Define un recorrido para el sprite - float start_pos; // Posición inicial - float end_pos; // Posición final - PathType type; // Tipo de movimiento (horizontal/vertical) - float fixed_pos; // Posición fija en el eje contrario - float duration_s; // Duración de la animación en segundos - float waiting_time_s; // Tiempo de espera una vez en el destino - std::function easing_function; // Función de easing - float elapsed_time = 0.0f; // Tiempo transcurrido - float waiting_elapsed = 0.0f; // Tiempo de espera transcurrido - bool on_destination = false; // Indica si ha llegado al destino - bool finished = false; // Indica si ha terminado de esperarse +struct Path { // Define un recorrido para el sprite + float start_pos; // Posición inicial + float end_pos; // Posición final + PathType type; // Tipo de movimiento (horizontal/vertical) + float fixed_pos; // Posición fija en el eje contrario + float duration_s; // Duración de la animación en segundos + float waiting_time_s; // Tiempo de espera una vez en el destino + std::function easing_function; // Función de easing + float elapsed_time = 0.0f; // Tiempo transcurrido + float waiting_elapsed = 0.0f; // Tiempo de espera transcurrido + bool on_destination = false; // Indica si ha llegado al destino + bool finished = false; // Indica si ha terminado de esperarse // Constructor para paths generados Path(float start, float end, PathType path_type, float fixed, float duration, float waiting, std::function easing) - : start_pos(start), end_pos(end), type(path_type), fixed_pos(fixed), - duration_s(duration), waiting_time_s(waiting), easing_function(std::move(easing)) {} + : start_pos(start), + end_pos(end), + type(path_type), + fixed_pos(fixed), + duration_s(duration), + waiting_time_s(waiting), + easing_function(std::move(easing)) {} // Constructor para paths por puntos (convertido a segundos) - Path(const std::vector &spots_init, float waiting_time_s_init); + Path(const std::vector& spots_init, float waiting_time_s_init); // Variables para paths por puntos std::vector spots; // Solo para paths por puntos @@ -52,7 +57,7 @@ struct Path { // Define un re }; // --- Funciones --- -auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function &easing_function) -> std::vector; // Devuelve un vector con los puntos que conforman la ruta +auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function& easing_function) -> std::vector; // Devuelve un vector con los puntos que conforman la ruta // --- Clase PathSprite: Sprite que sigue uno o varios recorridos --- class PathSprite : public Sprite { @@ -63,13 +68,13 @@ class PathSprite : public Sprite { ~PathSprite() override = default; // --- Métodos principales --- - void update(float delta_time); // Actualiza la posición del sprite según el recorrido (delta_time en segundos) - void render() override; // Muestra el sprite por pantalla + void update(float delta_time); // Actualiza la posición del sprite según el recorrido (delta_time en segundos) + void render() override; // Muestra el sprite por pantalla // --- Gestión de recorridos --- - void addPath(Path path, bool centered = false); // Añade un recorrido (Path) - void addPath(const std::vector &spots, float waiting_time_s = 0.0f); // Añade un recorrido a partir de puntos - void addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function &easing_function, float waiting_time_s = 0.0f); // Añade un recorrido generado + void addPath(Path path, bool centered = false); // Añade un recorrido (Path) + void addPath(const std::vector& spots, float waiting_time_s = 0.0f); // Añade un recorrido a partir de puntos + void addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function& easing_function, float waiting_time_s = 0.0f); // Añade un recorrido generado // --- Estado y control --- void enable(); // Habilita el objeto @@ -87,5 +92,5 @@ class PathSprite : public Sprite { // --- Métodos internos --- void moveThroughCurrentPath(float delta_time); // Coloca el sprite en los diferentes puntos del recorrido - void goToNextPathOrDie(); // Cambia de recorrido o finaliza + void goToNextPathOrDie(); // Cambia de recorrido o finaliza }; \ No newline at end of file diff --git a/source/pause_manager.h b/source/pause_manager.hpp similarity index 100% rename from source/pause_manager.h rename to source/pause_manager.hpp diff --git a/source/player.cpp b/source/player.cpp index b749ad2..7b9c8bd 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -1,4 +1,4 @@ -#include "player.h" +#include "player.hpp" #include // Para SDL_GetTicks, SDL_FlipMode @@ -6,17 +6,17 @@ #include // Para fmod #include // Para rand -#include "animated_sprite.h" // Para AnimatedSprite -#include "asset.h" // Para Asset -#include "audio.h" // Para Audio -#include "input.h" // Para Input -#include "input_types.h" // Para InputAction -#include "manage_hiscore_table.h" // Para ManageHiScoreTable, HiScoreEntry -#include "param.h" // Para Param, ParamGame, param -#include "scoreboard.h" // Para Scoreboard -#include "stage.h" // Para power_can_be_added -#include "stage_interface.h" // Para IStageInfo -#include "texture.h" // Para Texture +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "asset.hpp" // Para Asset +#include "audio.hpp" // Para Audio +#include "input.hpp" // Para Input +#include "input_types.hpp" // Para InputAction +#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable, HiScoreEntry +#include "param.hpp" // Para Param, ParamGame, param +#include "scoreboard.hpp" // Para Scoreboard +#include "stage.hpp" // Para power_can_be_added +#include "stage_interface.hpp" // Para IStageInfo +#include "texture.hpp" // Para Texture #ifdef _DEBUG #include #endif @@ -615,7 +615,7 @@ void Player::setPlayingState(State state) { break; } case State::SHOWING_NAME: { - showing_name_time_accumulator_ = 0.0f; // Inicializar acumulador time-based + showing_name_time_accumulator_ = 0.0f; // Inicializar acumulador time-based setScoreboardMode(Scoreboard::Mode::ENTER_TO_SHOW_NAME); // Iniciar animación de transición Scoreboard::get()->setEnterName(scoreboard_panel_, last_enter_name_); addScoreToScoreBoard(); diff --git a/source/player.h b/source/player.hpp similarity index 98% rename from source/player.h rename to source/player.hpp index 305357f..e0fac7a 100644 --- a/source/player.h +++ b/source/player.hpp @@ -7,14 +7,14 @@ #include // Para pair #include // Para vector -#include "animated_sprite.h" // Para AnimatedSprite -#include "bullet.h" // Para Bullet -#include "enter_name.h" // Para EnterName -#include "input.h" // Para Input -#include "manage_hiscore_table.h" // Para Table -#include "scoreboard.h" // Para Scoreboard -#include "stage_interface.h" // Para IStageInfo -#include "utils.h" // Para Circle +#include "animated_sprite.hpp" // Para AnimatedSprite +#include "bullet.hpp" // Para Bullet +#include "enter_name.hpp" // Para EnterName +#include "input.hpp" // Para Input +#include "manage_hiscore_table.hpp" // Para Table +#include "scoreboard.hpp" // Para Scoreboard +#include "stage_interface.hpp" // Para IStageInfo +#include "utils.hpp" // Para Circle class Texture; diff --git a/source/rendering/opengl/opengl_shader.cpp b/source/rendering/opengl/opengl_shader.cpp index 3c296c2..15ce6ba 100644 --- a/source/rendering/opengl/opengl_shader.cpp +++ b/source/rendering/opengl/opengl_shader.cpp @@ -1,6 +1,7 @@ -#include "opengl_shader.h" +#include "opengl_shader.hpp" #include + #include #include #include @@ -40,12 +41,12 @@ bool OpenGLShader::initGLExtensions() { glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray"); return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv && - glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram && - glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog && - glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f && - glGenVertexArrays && glBindVertexArray && glDeleteVertexArrays && - glGenBuffers && glBindBuffer && glBufferData && glDeleteBuffers && - glVertexAttribPointer && glEnableVertexAttribArray; + glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram && + glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog && + glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f && + glGenVertexArrays && glBindVertexArray && glDeleteVertexArrays && + glGenBuffers && glBindBuffer && glBufferData && glDeleteBuffers && + glVertexAttribPointer && glEnableVertexAttribArray; } #endif @@ -53,14 +54,16 @@ void OpenGLShader::checkGLError(const char* operation) { GLenum error = glGetError(); if (error != GL_NO_ERROR) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error OpenGL en %s: 0x%x", operation, error); + "Error OpenGL en %s: 0x%x", + operation, + error); } } GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type) { if (source.empty()) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "ERROR: El código fuente del shader está vacío"); + "ERROR: El código fuente del shader está vacío"); return 0; } @@ -83,14 +86,15 @@ GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled); if (compiled != GL_TRUE) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error en compilación del shader"); + "Error en compilación del shader"); GLint log_length; glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length); if (log_length > 0) { std::vector log(log_length); glGetShaderInfoLog(shader_id, log_length, &log_length, log.data()); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Log de compilación: %s", log.data()); + "Log de compilación: %s", + log.data()); } glDeleteShader(shader_id); return 0; @@ -103,7 +107,7 @@ GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) { GLuint program = glCreateProgram(); if (program == 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error al crear programa de shaders"); + "Error al crear programa de shaders"); return 0; } @@ -120,14 +124,15 @@ GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) { glGetProgramiv(program, GL_LINK_STATUS, &linked); if (linked != GL_TRUE) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error al enlazar programa"); + "Error al enlazar programa"); GLint log_length; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length); if (log_length > 0) { std::vector log(log_length); glGetProgramInfoLog(program, log_length, &log_length, log.data()); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Log de enlace: %s", log.data()); + "Log de enlace: %s", + log.data()); } glDeleteProgram(program); return 0; @@ -144,16 +149,32 @@ void OpenGLShader::createQuadGeometry() { // Formato: x, y, u, v float vertices[] = { // Posición // TexCoords - -1.0f, -1.0f, 0.0f, 0.0f, // Inferior izquierda - 1.0f, -1.0f, 1.0f, 0.0f, // Inferior derecha - 1.0f, 1.0f, 1.0f, 1.0f, // Superior derecha - -1.0f, 1.0f, 0.0f, 1.0f // Superior izquierda + -1.0f, + -1.0f, + 0.0f, + 0.0f, // Inferior izquierda + 1.0f, + -1.0f, + 1.0f, + 0.0f, // Inferior derecha + 1.0f, + 1.0f, + 1.0f, + 1.0f, // Superior derecha + -1.0f, + 1.0f, + 0.0f, + 1.0f // Superior izquierda }; // Índices para dibujar el quad con dos triángulos unsigned int indices[] = { - 0, 1, 2, // Primer triángulo - 2, 3, 0 // Segundo triángulo + 0, + 1, + 2, // Primer triángulo + 2, + 3, + 0 // Segundo triángulo }; // Generar y configurar VAO @@ -207,7 +228,7 @@ GLuint OpenGLShader::getTextureID(SDL_Texture* texture) { if (texture_id == 0) { SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, - "No se pudo obtener ID de textura OpenGL, usando 1 por defecto"); + "No se pudo obtener ID de textura OpenGL, usando 1 por defecto"); texture_id = 1; } @@ -215,16 +236,16 @@ GLuint OpenGLShader::getTextureID(SDL_Texture* texture) { } bool OpenGLShader::init(SDL_Window* window, - SDL_Texture* texture, - const std::string& vertex_source, - const std::string& fragment_source) { + SDL_Texture* texture, + const std::string& vertex_source, + const std::string& fragment_source) { window_ = window; back_buffer_ = texture; renderer_ = SDL_GetRenderer(window); if (!renderer_) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error: No se pudo obtener el renderer"); + "Error: No se pudo obtener el renderer"); return false; } @@ -233,14 +254,18 @@ bool OpenGLShader::init(SDL_Window* window, SDL_GetTextureSize(back_buffer_, &texture_width_, &texture_height_); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, - "Inicializando shaders: ventana=%dx%d, textura=%.0fx%.0f", - window_width_, window_height_, texture_width_, texture_height_); + "Inicializando shaders: ventana=%dx%d, textura=%.0fx%.0f", + window_width_, + window_height_, + texture_width_, + texture_height_); // Verificar que es OpenGL const char* renderer_name = SDL_GetRendererName(renderer_); if (!renderer_name || strncmp(renderer_name, "opengl", 6) != 0) { SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, - "Renderer no es OpenGL: %s", renderer_name ? renderer_name : "unknown"); + "Renderer no es OpenGL: %s", + renderer_name ? renderer_name : "unknown"); return false; } @@ -248,7 +273,7 @@ bool OpenGLShader::init(SDL_Window* window, // Inicializar extensiones OpenGL en Windows/Linux if (!initGLExtensions()) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error al inicializar extensiones OpenGL"); + "Error al inicializar extensiones OpenGL"); return false; } #endif @@ -265,7 +290,7 @@ bool OpenGLShader::init(SDL_Window* window, if (vertex_shader == 0 || fragment_shader == 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error al compilar shaders"); + "Error al compilar shaders"); if (vertex_shader != 0) glDeleteShader(vertex_shader); if (fragment_shader != 0) glDeleteShader(fragment_shader); return false; @@ -280,7 +305,7 @@ bool OpenGLShader::init(SDL_Window* window, if (program_id_ == 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error al crear programa de shaders"); + "Error al crear programa de shaders"); return false; } @@ -292,19 +317,20 @@ bool OpenGLShader::init(SDL_Window* window, texture_size_location_ = glGetUniformLocation(program_id_, "TextureSize"); if (texture_size_location_ != -1) { SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, - "Configurando TextureSize uniform: %.0fx%.0f", - texture_width_, texture_height_); + "Configurando TextureSize uniform: %.0fx%.0f", + texture_width_, + texture_height_); glUniform2f(texture_size_location_, texture_width_, texture_height_); checkGLError("glUniform2f(TextureSize)"); } else { SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, - "Uniform 'TextureSize' no encontrado en shader"); + "Uniform 'TextureSize' no encontrado en shader"); } glUseProgram(0); is_initialized_ = true; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, - "** OpenGL 3.3 Shader Backend inicializado correctamente"); + "** OpenGL 3.3 Shader Backend inicializado correctamente"); return true; } @@ -459,4 +485,4 @@ void OpenGLShader::cleanup() { back_buffer_ = nullptr; } -} // namespace Rendering +} // namespace Rendering diff --git a/source/rendering/opengl/opengl_shader.h b/source/rendering/opengl/opengl_shader.h deleted file mode 100644 index 957d211..0000000 --- a/source/rendering/opengl/opengl_shader.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include "../shader_backend.h" - -#ifdef __APPLE__ -#include -#else -#include -#endif - -namespace Rendering { - -/** - * @brief Backend de shaders usando OpenGL 3.3 Core Profile - * - * Implementa el renderizado de shaders usando APIs modernas de OpenGL: - * - VAO (Vertex Array Objects) - * - VBO (Vertex Buffer Objects) - * - Shaders GLSL #version 330 core - */ -class OpenGLShader : public ShaderBackend { -public: - OpenGLShader() = default; - ~OpenGLShader() override; - - bool init(SDL_Window* window, - SDL_Texture* texture, - const std::string& vertex_source, - const std::string& fragment_source) override; - - void render() override; - void setTextureSize(float width, float height) override; - void cleanup() override; - bool isHardwareAccelerated() const override { return is_initialized_; } - -private: - // Funciones auxiliares - bool initGLExtensions(); - GLuint compileShader(const std::string& source, GLenum shader_type); - GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader); - void createQuadGeometry(); - GLuint getTextureID(SDL_Texture* texture); - void checkGLError(const char* operation); - - // Estado SDL - SDL_Window* window_ = nullptr; - SDL_Renderer* renderer_ = nullptr; - SDL_Texture* back_buffer_ = nullptr; - - // Estado OpenGL - GLuint program_id_ = 0; - GLuint vao_ = 0; // Vertex Array Object - GLuint vbo_ = 0; // Vertex Buffer Object - GLuint ebo_ = 0; // Element Buffer Object - - // Ubicaciones de uniforms - GLint texture_size_location_ = -1; - - // Tamaños - int window_width_ = 0; - int window_height_ = 0; - float texture_width_ = 0.0f; - float texture_height_ = 0.0f; - - // Estado - bool is_initialized_ = false; - -#ifndef __APPLE__ - // Punteros a funciones OpenGL en Windows/Linux - PFNGLCREATESHADERPROC glCreateShader = nullptr; - PFNGLSHADERSOURCEPROC glShaderSource = nullptr; - PFNGLCOMPILESHADERPROC glCompileShader = nullptr; - PFNGLGETSHADERIVPROC glGetShaderiv = nullptr; - PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr; - PFNGLDELETESHADERPROC glDeleteShader = nullptr; - PFNGLATTACHSHADERPROC glAttachShader = nullptr; - PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr; - PFNGLLINKPROGRAMPROC glLinkProgram = nullptr; - PFNGLVALIDATEPROGRAMPROC glValidateProgram = nullptr; - PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr; - PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr; - PFNGLUSEPROGRAMPROC glUseProgram = nullptr; - PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr; - PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr; - PFNGLUNIFORM2FPROC glUniform2f = nullptr; - PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr; - PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr; - PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr; - PFNGLGENBUFFERSPROC glGenBuffers = nullptr; - PFNGLBINDBUFFERPROC glBindBuffer = nullptr; - PFNGLBUFFERDATAPROC glBufferData = nullptr; - PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr; - PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr; - PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr; -#endif -}; - -} // namespace Rendering diff --git a/source/rendering/opengl/opengl_shader.hpp b/source/rendering/opengl/opengl_shader.hpp new file mode 100644 index 0000000..7c979fd --- /dev/null +++ b/source/rendering/opengl/opengl_shader.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include "../shader_backend.hpp" + +#ifdef __APPLE__ +#include +#else +#include +#endif + +namespace Rendering { + +/** + * @brief Backend de shaders usando OpenGL 3.3 Core Profile + * + * Implementa el renderizado de shaders usando APIs modernas de OpenGL: + * - VAO (Vertex Array Objects) + * - VBO (Vertex Buffer Objects) + * - Shaders GLSL #version 330 core + */ +class OpenGLShader : public ShaderBackend { + public: + OpenGLShader() = default; + ~OpenGLShader() override; + + bool init(SDL_Window* window, + SDL_Texture* texture, + const std::string& vertex_source, + const std::string& fragment_source) override; + + void render() override; + void setTextureSize(float width, float height) override; + void cleanup() override; + bool isHardwareAccelerated() const override { return is_initialized_; } + + private: + // Funciones auxiliares + bool initGLExtensions(); + GLuint compileShader(const std::string& source, GLenum shader_type); + GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader); + void createQuadGeometry(); + GLuint getTextureID(SDL_Texture* texture); + void checkGLError(const char* operation); + + // Estado SDL + SDL_Window* window_ = nullptr; + SDL_Renderer* renderer_ = nullptr; + SDL_Texture* back_buffer_ = nullptr; + + // Estado OpenGL + GLuint program_id_ = 0; + GLuint vao_ = 0; // Vertex Array Object + GLuint vbo_ = 0; // Vertex Buffer Object + GLuint ebo_ = 0; // Element Buffer Object + + // Ubicaciones de uniforms + GLint texture_size_location_ = -1; + + // Tamaños + int window_width_ = 0; + int window_height_ = 0; + float texture_width_ = 0.0f; + float texture_height_ = 0.0f; + + // Estado + bool is_initialized_ = false; + +#ifndef __APPLE__ + // Punteros a funciones OpenGL en Windows/Linux + PFNGLCREATESHADERPROC glCreateShader = nullptr; + PFNGLSHADERSOURCEPROC glShaderSource = nullptr; + PFNGLCOMPILESHADERPROC glCompileShader = nullptr; + PFNGLGETSHADERIVPROC glGetShaderiv = nullptr; + PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr; + PFNGLDELETESHADERPROC glDeleteShader = nullptr; + PFNGLATTACHSHADERPROC glAttachShader = nullptr; + PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr; + PFNGLLINKPROGRAMPROC glLinkProgram = nullptr; + PFNGLVALIDATEPROGRAMPROC glValidateProgram = nullptr; + PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr; + PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr; + PFNGLUSEPROGRAMPROC glUseProgram = nullptr; + PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr; + PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr; + PFNGLUNIFORM2FPROC glUniform2f = nullptr; + PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr; + PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr; + PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr; + PFNGLGENBUFFERSPROC glGenBuffers = nullptr; + PFNGLBINDBUFFERPROC glBindBuffer = nullptr; + PFNGLBUFFERDATAPROC glBufferData = nullptr; + PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr; + PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr; + PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr; +#endif +}; + +} // namespace Rendering diff --git a/source/rendering/shader_backend.h b/source/rendering/shader_backend.h deleted file mode 100644 index b9fd170..0000000 --- a/source/rendering/shader_backend.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include - -namespace Rendering { - -/** - * @brief Interfaz abstracta para backends de renderizado con shaders - * - * Esta interfaz define el contrato que todos los backends de shaders - * deben cumplir (OpenGL, Metal, Vulkan, etc.) - */ -class ShaderBackend { -public: - virtual ~ShaderBackend() = default; - - /** - * @brief Inicializa el backend de shaders - * @param window Ventana SDL - * @param texture Textura de backbuffer a la que aplicar shaders - * @param vertex_source Código fuente del vertex shader - * @param fragment_source Código fuente del fragment shader - * @return true si la inicialización fue exitosa - */ - virtual bool init(SDL_Window* window, - SDL_Texture* texture, - const std::string& vertex_source, - const std::string& fragment_source) = 0; - - /** - * @brief Renderiza la textura con los shaders aplicados - */ - virtual void render() = 0; - - /** - * @brief Establece el tamaño de la textura como parámetro del shader - * @param width Ancho de la textura - * @param height Alto de la textura - */ - virtual void setTextureSize(float width, float height) = 0; - - /** - * @brief Limpia y libera recursos del backend - */ - virtual void cleanup() = 0; - - /** - * @brief Verifica si el backend está usando aceleración por hardware - * @return true si usa aceleración (OpenGL/Metal/Vulkan) - */ - virtual bool isHardwareAccelerated() const = 0; -}; - -} // namespace Rendering diff --git a/source/rendering/shader_backend.hpp b/source/rendering/shader_backend.hpp new file mode 100644 index 0000000..55fb8e0 --- /dev/null +++ b/source/rendering/shader_backend.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include + +#include + +namespace Rendering { + +/** + * @brief Interfaz abstracta para backends de renderizado con shaders + * + * Esta interfaz define el contrato que todos los backends de shaders + * deben cumplir (OpenGL, Metal, Vulkan, etc.) + */ +class ShaderBackend { + public: + virtual ~ShaderBackend() = default; + + /** + * @brief Inicializa el backend de shaders + * @param window Ventana SDL + * @param texture Textura de backbuffer a la que aplicar shaders + * @param vertex_source Código fuente del vertex shader + * @param fragment_source Código fuente del fragment shader + * @return true si la inicialización fue exitosa + */ + virtual bool init(SDL_Window* window, + SDL_Texture* texture, + const std::string& vertex_source, + const std::string& fragment_source) = 0; + + /** + * @brief Renderiza la textura con los shaders aplicados + */ + virtual void render() = 0; + + /** + * @brief Establece el tamaño de la textura como parámetro del shader + * @param width Ancho de la textura + * @param height Alto de la textura + */ + virtual void setTextureSize(float width, float height) = 0; + + /** + * @brief Limpia y libera recursos del backend + */ + virtual void cleanup() = 0; + + /** + * @brief Verifica si el backend está usando aceleración por hardware + * @return true si usa aceleración (OpenGL/Metal/Vulkan) + */ + virtual bool isHardwareAccelerated() const = 0; +}; + +} // namespace Rendering diff --git a/source/resource.cpp b/source/resource.cpp index d760bf0..84ef9ab 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -1,4 +1,4 @@ -#include "resource.h" +#include "resource.hpp" #include // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError, SDL_SetRenderDrawColor, SDL_EventType, SDL_PollEvent, SDL_RenderFillRect, SDL_RenderRect, SDLK_ESCAPE, SDL_Event @@ -10,14 +10,14 @@ #include // Para runtime_error #include // Para move -#include "asset.h" // Para Asset -#include "color.h" // Para Color +#include "asset.hpp" // Para Asset +#include "color.hpp" // Para Color #include "external/jail_audio.h" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound -#include "lang.h" // Para getText -#include "param.h" // Para Param, param, ParamResource, ParamGame -#include "resource_helper.h" // Para ResourceHelper -#include "screen.h" // Para Screen -#include "text.h" // Para Text +#include "lang.hpp" // Para getText +#include "param.hpp" // Para Param, param, ParamResource, ParamGame +#include "resource_helper.hpp" // Para ResourceHelper +#include "screen.hpp" // Para Screen +#include "text.hpp" // Para Text #include "version.h" // Para Version::APP_NAME y Version::GIT_HASH struct JA_Music_t; // lines 11-11 diff --git a/source/resource.h b/source/resource.hpp similarity index 84% rename from source/resource.h rename to source/resource.hpp index a5515ef..02e847c 100644 --- a/source/resource.h +++ b/source/resource.hpp @@ -8,10 +8,10 @@ #include // Para move #include // Para vector -#include "animated_sprite.h" // Para AnimationsFileBuffer -#include "text.h" // Para Text, TextFile -#include "texture.h" // Para Texture -#include "demo.h" // Para DemoData +#include "animated_sprite.hpp" // Para AnimationsFileBuffer +#include "demo.hpp" // Para DemoData +#include "text.hpp" // Para Text, TextFile +#include "texture.hpp" // Para Texture struct JA_Music_t; struct JA_Sound_t; @@ -28,16 +28,16 @@ class Resource { // --- Métodos de singleton --- 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 + 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 - auto getMusic(const std::string &name) -> JA_Music_t *; // Obtiene la música por nombre - auto getTexture(const std::string &name) -> std::shared_ptr; // Obtiene la textura por nombre - auto getTextFile(const std::string &name) -> std::shared_ptr; // Obtiene el fichero de texto por nombre - auto getText(const std::string &name) -> std::shared_ptr; // Obtiene el objeto de texto por nombre - auto getAnimation(const std::string &name) -> AnimationsFileBuffer &; // Obtiene la animación por nombre - auto getDemoData(int index) -> DemoData &; // Obtiene los datos de demo por índice + auto getSound(const std::string& name) -> JA_Sound_t*; // Obtiene el sonido por nombre + auto getMusic(const std::string& name) -> JA_Music_t*; // Obtiene la música por nombre + auto getTexture(const std::string& name) -> std::shared_ptr; // Obtiene la textura por nombre + auto getTextFile(const std::string& name) -> std::shared_ptr; // Obtiene el fichero de texto por nombre + auto getText(const std::string& name) -> std::shared_ptr; // Obtiene el objeto de texto por nombre + auto getAnimation(const std::string& name) -> AnimationsFileBuffer&; // Obtiene la animación por nombre + auto getDemoData(int index) -> DemoData&; // Obtiene los datos de demo por índice // --- Métodos de recarga de recursos --- void reload(); // Recarga todos los recursos @@ -49,18 +49,18 @@ class Resource { // --- Estructuras para recursos individuales --- struct ResourceSound { 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 = nullptr) + ResourceSound(std::string name, JA_Sound_t* sound = nullptr) : name(std::move(name)), sound(sound) {} }; struct ResourceMusic { 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 = nullptr) + ResourceMusic(std::string name, JA_Music_t* music = nullptr) : name(std::move(name)), music(music) {} }; @@ -169,12 +169,12 @@ class Resource { // --- Métodos para carga perezosa --- void initResourceLists(); // Inicializa las listas de recursos sin cargar el contenido - static auto loadSoundLazy(const std::string &name) -> JA_Sound_t *; // Carga un sonido específico bajo demanda - static auto loadMusicLazy(const std::string &name) -> JA_Music_t *; // Carga una música específica bajo demanda - static auto loadTextureLazy(const std::string &name) -> std::shared_ptr; // Carga una textura específica bajo demanda - static auto loadTextFileLazy(const std::string &name) -> std::shared_ptr; // Carga un fichero de texto específico bajo demanda - auto loadTextLazy(const std::string &name) -> std::shared_ptr; // Carga un objeto de texto específico bajo demanda - static auto loadAnimationLazy(const std::string &name) -> AnimationsFileBuffer; // Carga una animación específica bajo demanda + static auto loadSoundLazy(const std::string& name) -> JA_Sound_t*; // Carga un sonido específico bajo demanda + static auto loadMusicLazy(const std::string& name) -> JA_Music_t*; // Carga una música específica bajo demanda + static auto loadTextureLazy(const std::string& name) -> std::shared_ptr; // Carga una textura específica bajo demanda + static auto loadTextFileLazy(const std::string& name) -> std::shared_ptr; // Carga un fichero de texto específico bajo demanda + auto loadTextLazy(const std::string& name) -> std::shared_ptr; // Carga un objeto de texto específico bajo demanda + static 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 @@ -189,5 +189,5 @@ class Resource { ~Resource(); // Destructor privado // --- Instancia singleton --- - static Resource *instance; // Instancia única de Resource + static Resource* instance; // Instancia única de Resource }; \ No newline at end of file diff --git a/source/resource_helper.cpp b/source/resource_helper.cpp index 62e42a1..aeae436 100644 --- a/source/resource_helper.cpp +++ b/source/resource_helper.cpp @@ -1,4 +1,4 @@ -#include "resource_helper.h" +#include "resource_helper.hpp" #include #include diff --git a/source/resource_helper.h b/source/resource_helper.hpp similarity index 98% rename from source/resource_helper.h rename to source/resource_helper.hpp index ee07c31..740f474 100644 --- a/source/resource_helper.h +++ b/source/resource_helper.hpp @@ -6,7 +6,7 @@ #include #include -#include "resource_loader.h" +#include "resource_loader.hpp" // Helper functions para integrar ResourceLoader con el sistema existente namespace ResourceHelper { diff --git a/source/resource_loader.cpp b/source/resource_loader.cpp index 256c5f0..73d4970 100644 --- a/source/resource_loader.cpp +++ b/source/resource_loader.cpp @@ -1,4 +1,4 @@ -#include "resource_loader.h" +#include "resource_loader.hpp" #include #include diff --git a/source/resource_loader.h b/source/resource_loader.hpp similarity index 97% rename from source/resource_loader.h rename to source/resource_loader.hpp index 130b27d..aa0d451 100644 --- a/source/resource_loader.h +++ b/source/resource_loader.hpp @@ -3,7 +3,7 @@ #include -#include "resource_pack.h" +#include "resource_pack.hpp" class ResourceLoader { private: diff --git a/source/resource_pack.cpp b/source/resource_pack.cpp index 2beb9e8..c949f1b 100644 --- a/source/resource_pack.cpp +++ b/source/resource_pack.cpp @@ -1,4 +1,4 @@ -#include "resource_pack.h" +#include "resource_pack.hpp" #include #include diff --git a/source/resource_pack.h b/source/resource_pack.hpp similarity index 100% rename from source/resource_pack.h rename to source/resource_pack.hpp diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 7143470..329148b 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -1,4 +1,4 @@ -#include "scoreboard.h" +#include "scoreboard.hpp" #include // Para SDL_DestroyTexture, SDL_SetRenderDrawColor, SDL_SetRenderTarget, SDL_CreateTexture, SDL_GetRenderTarget, SDL_GetTicks, SDL_RenderClear, SDL_RenderLine, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_FRect, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_Texture, SDL_TextureAccess @@ -7,16 +7,16 @@ #include // Para operator<<, setfill, setw #include // Para basic_ostream, basic_ostringstream, basic_ostream::operator<<, ostringstream -#include "color.h" -#include "enter_name.h" // Para NAME_SIZE -#include "lang.h" // Para getText -#include "param.h" // Para Param, ParamScoreboard, param -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text, Text::CENTER, Text::COLOR -#include "texture.h" // Para Texture -#include "utils.h" // Para easeOutCubic +#include "color.hpp" +#include "enter_name.hpp" // Para NAME_SIZE +#include "lang.hpp" // Para getText +#include "param.hpp" // Para Param, ParamScoreboard, param +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "sprite.hpp" // Para Sprite +#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR +#include "texture.hpp" // Para Texture +#include "utils.hpp" // Para easeOutCubic // .at(SINGLETON) Hay que definir las variables estáticas, desde el .h sólo la hemos declarado Scoreboard* Scoreboard::instance = nullptr; @@ -125,7 +125,7 @@ void Scoreboard::setCarouselAnimation(Id id, int selected_index, EnterName* ente if (direction > LIST_SIZE / 2) { direction = -(LIST_SIZE - direction); // Wrap backward (ej: Z → A) } else if (direction < -LIST_SIZE / 2) { - direction = LIST_SIZE + direction; // Wrap forward (ej: A → Z) + direction = LIST_SIZE + direction; // Wrap forward (ej: A → Z) } // Normalizar a -1 o +1 @@ -447,21 +447,17 @@ void Scoreboard::renderScoreToEnterNameMode(size_t panel_index) { // ========== Texto que SALE hacia arriba ========== // name_ (sale desde ROW1 hacia arriba) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y - t * delta_1_to_2, - name_.at(panel_index), 1, text_color1_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y - t * delta_1_to_2, name_.at(panel_index), 1, text_color1_); // ========== Textos que SE MUEVEN hacia arriba ========== // score_ (se mueve de ROW2 a ROW1) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y - t * delta_1_to_2, - updateScoreText(score_.at(panel_index)), 1, text_color2_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y - t * delta_1_to_2, updateScoreText(score_.at(panel_index)), 1, text_color2_); // "ENTER NAME" (se mueve de ROW3 a ROW2) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - t * delta_2_to_3, - Lang::getText("[SCOREBOARD] 11"), 1, text_color1_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - t * delta_2_to_3, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_); // enter_name_ (se mueve de ROW4 a ROW3) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - t * delta_3_to_4, - enter_name_.at(panel_index), 1, text_color2_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - t * delta_3_to_4, enter_name_.at(panel_index), 1, text_color2_); // ========== Elemento que ENTRA desde abajo ========== // CARRUSEL (entra desde debajo de ROW4 hacia ROW4) @@ -505,21 +501,17 @@ void Scoreboard::renderEnterToShowNameMode(size_t panel_index) { // ========== Texto que ENTRA desde arriba ========== // name_ (entra desde arriba hacia ROW1) // Debe venir desde donde estaría ROW0, que está a delta_1_to_2 píxeles arriba de ROW1 - text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2 - delta_1_to_2, - name_.at(panel_index), 1, text_color1_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2 - delta_1_to_2, name_.at(panel_index), 1, text_color1_); // ========== Textos que SE MUEVEN (renderizar UNA sola vez) ========== // SCORE (se mueve de ROW1 a ROW2) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2, - updateScoreText(score_.at(panel_index)), 1, text_color2_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2, updateScoreText(score_.at(panel_index)), 1, text_color2_); // "ENTER NAME" (se mueve de ROW2 a ROW3) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y + t * delta_2_to_3, - Lang::getText("[SCOREBOARD] 11"), 1, text_color1_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y + t * delta_2_to_3, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_); // enter_name_ (se mueve de ROW3 a ROW4) - text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y + t * delta_3_to_4, - enter_name_.at(panel_index), 1, text_color2_); + text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y + t * delta_3_to_4, enter_name_.at(panel_index), 1, text_color2_); // ========== Elemento que SALE hacia abajo ========== // CARRUSEL (sale desde ROW4 hacia abajo, fuera de pantalla) diff --git a/source/scoreboard.h b/source/scoreboard.hpp similarity index 95% rename from source/scoreboard.h rename to source/scoreboard.hpp index 781b36b..4947863 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.hpp @@ -11,7 +11,7 @@ // Forward declarations class EnterName; -#include "color.h" // Para Color +#include "color.hpp" // Para Color class Sprite; class Text; @@ -37,7 +37,7 @@ class Scoreboard { DEMO, SCORE_TO_ENTER_NAME, // Transición animada: SCORE → ENTER_NAME ENTER_NAME, - ENTER_TO_SHOW_NAME, // Transición animada: ENTER_NAME → SHOW_NAME + ENTER_TO_SHOW_NAME, // Transición animada: ENTER_NAME → SHOW_NAME SHOW_NAME, GAME_COMPLETED, NUM_MODES, @@ -88,11 +88,11 @@ class Scoreboard { std::array(Id::SIZE)> name_ = {}; // Nombre de cada jugador std::array(Id::SIZE)> enter_name_ = {}; // Nombre introducido para la tabla de records std::array(Id::SIZE)> character_selected_ = {}; // Caracter seleccionado - std::array(Id::SIZE)> enter_name_ref_ = {}; // Referencias a EnterName para obtener character_list_ - std::array(Id::SIZE)> carousel_position_ = {}; // Posición actual del carrusel (índice en character_list_) - std::array(Id::SIZE)> carousel_target_ = {}; // Posición objetivo del carrusel - std::array(Id::SIZE)> carousel_prev_index_ = {}; // Índice previo para detectar cambios - std::array(Id::SIZE)> text_slide_offset_ = {}; // Progreso de animación de deslizamiento (0.0 a 1.0) + std::array(Id::SIZE)> enter_name_ref_ = {}; // Referencias a EnterName para obtener character_list_ + std::array(Id::SIZE)> carousel_position_ = {}; // Posición actual del carrusel (índice en character_list_) + std::array(Id::SIZE)> carousel_target_ = {}; // Posición objetivo del carrusel + std::array(Id::SIZE)> carousel_prev_index_ = {}; // Índice previo para detectar cambios + std::array(Id::SIZE)> text_slide_offset_ = {}; // Progreso de animación de deslizamiento (0.0 a 1.0) std::array(Id::SIZE)> panel_ = {}; // Lista con todos los paneles del marcador Colors::Cycle name_color_cycle_; // Ciclo de colores para destacar el nombre una vez introducido Color animated_color_; // Color actual animado (ciclo automático cada 100ms) diff --git a/source/screen.cpp b/source/screen.cpp index 320d3f6..b63e9bb 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -1,4 +1,4 @@ -#include "screen.h" +#include "screen.hpp" #include // Para SDL_SetRenderTarget, SDL_LogCategory, SDL_LogInfo, SDL_RenderTexture, SDL_SetRenderDrawColor, SDL_SetRenderVSync, SDL_GetError, SDL_LogError, SDL_RendererLogicalPresentation, SDL_SetRenderLogicalPresentation, SDL_CreateTexture, SDL_DestroyTexture, SDL_DestroyWindow, SDL_GetTicks, SDL_Quit, SDL_RENDERER_VSYNC_DISABLED, SDL_RenderClear, SDL_CreateRenderer, SDL_CreateWindow, SDL_DestroyRenderer, SDL_DisplayID, SDL_FRect, SDL_GetCurrentDisplayMode, SDL_GetDisplayName, SDL_GetDisplays, SDL_GetRenderTarget, SDL_GetWindowPosition, SDL_GetWindowSize, SDL_Init, SDL_LogWarn, SDL_PixelFormat, SDL_RenderFillRect, SDL_RenderPresent, SDL_SetHint, SDL_SetRenderDrawBlendMode, SDL_SetTextureScaleMode, SDL_SetWindowFullscreen, SDL_SetWindowPosition, SDL_SetWindowSize, SDL_TextureAccess, SDL_free, SDL_BLENDMODE_BLEND, SDL_HINT_RENDER_DRIVER, SDL_INIT_VIDEO, SDL_PRIu32, SDL_ScaleMode, SDL_WINDOW_FULLSCREEN, SDL_WINDOW_OPENGL, SDL_WindowFlags @@ -8,19 +8,19 @@ #include // Para allocator, shared_ptr, make_shared, __shared_ptr_access #include // Para operator+, char_traits, to_string, string -#include "asset.h" // Para Asset -#include "mouse.h" // Para updateCursorVisibility -#include "rendering/opengl/opengl_shader.h" // Para OpenGLShader -#include "options.h" // Para VideoOptions, video, WindowOptions, window -#include "param.h" // Para Param, param, ParamGame, ParamDebug -#include "text.h" // Para Text, Text::COLOR, Text::STROKE -#include "texture.h" // Para Texture -#include "ui/notifier.h" // Para Notifier -#include "ui/service_menu.h" // Para ServiceMenu -#include "utils.h" // Para Zone +#include "asset.hpp" // Para Asset +#include "mouse.hpp" // Para updateCursorVisibility +#include "options.hpp" // Para VideoOptions, video, WindowOptions, window +#include "param.hpp" // Para Param, param, ParamGame, ParamDebug +#include "rendering/opengl/opengl_shader.hpp" // Para OpenGLShader +#include "text.hpp" // Para Text, Text::COLOR, Text::STROKE +#include "texture.hpp" // Para Texture +#include "ui/notifier.hpp" // Para Notifier +#include "ui/service_menu.hpp" // Para ServiceMenu +#include "utils.hpp" // Para Zone // Singleton -Screen *Screen::instance = nullptr; +Screen* Screen::instance = nullptr; // Inicializa la instancia única del singleton void Screen::init() { Screen::instance = new Screen(); } @@ -29,7 +29,7 @@ void Screen::init() { Screen::instance = new Screen(); } void Screen::destroy() { delete Screen::instance; } // Obtiene la instancia -auto Screen::get() -> Screen * { return Screen::instance; } +auto Screen::get() -> Screen* { return Screen::instance; } // Constructor Screen::Screen() @@ -189,10 +189,10 @@ void Screen::renderFlash() { void Screen::renderShake() { if (shake_effect_.enabled) { // Guarda el renderizador actual para dejarlo despues como estaba - auto *current_target = SDL_GetRenderTarget(renderer_); + auto* current_target = SDL_GetRenderTarget(renderer_); // Crea una textura temporal - auto *temp_texture = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height); + auto* temp_texture = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height); // Vuelca game_canvas_ a la textura temporal SDL_SetRenderTarget(renderer_, temp_texture); @@ -221,7 +221,7 @@ void Screen::renderInfo() { debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.DARKEN(150)); #ifdef RECORDING // RECORDING - debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length("RECORDING"), 2*(1 + debug_info_.text->getCharacterSize()), "RECORDING", 1, param.debug.color, 1, param.debug.color.DARKEN(150)); + debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length("RECORDING"), 2 * (1 + debug_info_.text->getCharacterSize()), "RECORDING", 1, param.debug.color, 1, param.debug.color.DARKEN(150)); #endif } } @@ -239,10 +239,10 @@ void Screen::loadShaders() { VERTEX_FILE = "crtpi_vertex.glsl"; data = Asset::get()->loadData(VERTEX_FILE); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, - "Usando shaders OpenGL Desktop 3.3"); + "Usando shaders OpenGL Desktop 3.3"); } else { SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, - "Usando shaders OpenGL ES 3.0 (Raspberry Pi)"); + "Usando shaders OpenGL ES 3.0 (Raspberry Pi)"); } if (!data.empty()) { @@ -280,7 +280,7 @@ void Screen::initShaders() { // En macOS, OpenGL está deprecated y rinde mal // TODO: Implementar backend de Metal para shaders en macOS SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, - "Shaders no disponibles en macOS (OpenGL deprecated). Usa Metal backend."); + "Shaders no disponibles en macOS (OpenGL deprecated). Usa Metal backend."); #endif } @@ -415,19 +415,19 @@ auto Screen::initSDLVideo() -> bool { void Screen::getDisplayInfo() { int i; int num_displays = 0; - SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); + SDL_DisplayID* displays = SDL_GetDisplays(&num_displays); if (displays != nullptr) { for (i = 0; i < num_displays; ++i) { SDL_DisplayID instance_id = displays[i]; - const char *name = SDL_GetDisplayName(instance_id); + const char* name = SDL_GetDisplayName(instance_id); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Display %" SDL_PRIu32 ": %s", instance_id, (name != nullptr) ? name : "Unknown"); } - const auto *dm = SDL_GetCurrentDisplayMode(displays[0]); + const auto* dm = SDL_GetCurrentDisplayMode(displays[0]); // Guarda información del monitor en display_monitor_ - const char *first_display_name = SDL_GetDisplayName(displays[0]); + const char* first_display_name = SDL_GetDisplayName(displays[0]); display_monitor_.name = (first_display_name != nullptr) ? first_display_name : "Unknown"; display_monitor_.width = static_cast(dm->w); display_monitor_.height = static_cast(dm->h); diff --git a/source/screen.h b/source/screen.hpp similarity index 69% rename from source/screen.h rename to source/screen.hpp index e31503e..b276d0a 100644 --- a/source/screen.h +++ b/source/screen.hpp @@ -5,8 +5,8 @@ #include // Para shared_ptr #include // Para string -#include "color.h" // Para Color -#include "options.h" // Para VideoOptions, video +#include "color.hpp" // Para Color +#include "options.hpp" // Para VideoOptions, video // Forward declarations class Notifier; @@ -14,16 +14,16 @@ class ServiceMenu; class Text; namespace Rendering { - class ShaderBackend; +class ShaderBackend; } // --- Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales (singleton) --- class Screen { public: // --- Métodos de singleton --- - static void init(); // Inicializa el objeto Screen - static void destroy(); // Libera el objeto Screen - static auto get() -> Screen *; // Obtiene el puntero al objeto Screen + static void init(); // Inicializa el objeto Screen + static void destroy(); // Libera el objeto Screen + static auto get() -> Screen*; // Obtiene el puntero al objeto Screen // --- Métodos principales --- void update(float delta_time); // Recibe deltaTime de las secciones y actualiza la lógica @@ -44,15 +44,15 @@ class Screen { // --- Efectos visuales --- void shake(int desp = 2, float delay_s = 0.05f, float duration_s = 0.133f) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay_s, duration_s); } // Agita la pantalla (tiempo en segundos) - void flash(Color color, float duration_s = 0.167f, float delay_s = 0.0f) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos) - void toggleShaders(); // Alterna entre activar y desactivar los shaders - void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero - void toggleVSync(); // Alterna entre activar y desactivar el V-Sync - void setVSync(bool enabled); // Establece el estado del V-Sync - void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla + void flash(Color color, float duration_s = 0.167f, float delay_s = 0.0f) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos) + void toggleShaders(); // Alterna entre activar y desactivar los shaders + void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero + void toggleVSync(); // Alterna entre activar y desactivar el V-Sync + void setVSync(bool enabled); // Establece el estado del V-Sync + void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla // --- Getters --- - auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador + auto getRenderer() -> SDL_Renderer* { return renderer_; } // Obtiene el renderizador void show() { SDL_ShowWindow(window_); } // Muestra la ventana void hide() { SDL_HideWindow(window_); } // Oculta la ventana void getSingletons(); // Obtiene los punteros a los singletones @@ -101,11 +101,11 @@ class Screen { // Efecto de flash en pantalla: pinta la pantalla de un color durante un tiempo struct FlashEffect { - bool enabled; // Indica si el efecto está activo - float duration_s; // Duración total del efecto en segundos - float delay_s; // Retraso antes de mostrar el flash en segundos - float timer_s; // Timer en segundos (contador decreciente) - Color color; // Color del flash + bool enabled; // Indica si el efecto está activo + float duration_s; // Duración total del efecto en segundos + float delay_s; // Retraso antes de mostrar el flash en segundos + float timer_s; // Timer en segundos (contador decreciente) + Color color; // Color del flash explicit FlashEffect(bool enabled = false, float duration_s = 0.0f, float delay_s = 0.0f, Color color = Color(0xFF, 0xFF, 0xFF)) : enabled(enabled), @@ -127,14 +127,14 @@ class Screen { // Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor struct ShakeEffect { - int desp; // Desplazamiento máximo de la sacudida (en píxeles) - float delay_s; // Segundos entre cada movimiento de sacudida - float counter_s; // Timer para el siguiente movimiento (decreciente) - float duration_s; // Duración total del efecto en segundos - float remaining_s; // Tiempo restante de sacudida - int original_pos; // Posición original de la imagen (x) - int original_width; // Ancho original de la imagen - bool enabled; // Indica si el efecto está activo + int desp; // Desplazamiento máximo de la sacudida (en píxeles) + float delay_s; // Segundos entre cada movimiento de sacudida + float counter_s; // Timer para el siguiente movimiento (decreciente) + float duration_s; // Duración total del efecto en segundos + float remaining_s; // Tiempo restante de sacudida + int original_pos; // Posición original de la imagen (x) + int original_width; // Ancho original de la imagen + bool enabled; // Indica si el efecto está activo explicit ShakeEffect(bool en = false, int dp = 2, float dl_s = 0.05f, float cnt_s = 0.0f, float len_s = 0.133f, float rem_s = 0.0f, int orig_pos = 0, int orig_width = 800) : desp(dp), @@ -147,7 +147,7 @@ class Screen { enabled(en) {} // Activa el efecto de sacudida y guarda la posición y tamaño originales - void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, float new_delay_s = -1.0f, float new_duration_s = -1.0f) { + void enable(SDL_FRect& src_rect, SDL_FRect& dst_rect, int new_desp = -1, float new_delay_s = -1.0f, float new_duration_s = -1.0f) { if (!enabled) { enabled = true; original_pos = src_rect.x; @@ -172,13 +172,13 @@ class Screen { } // Actualiza el estado del efecto de sacudida - void update(SDL_FRect &src_rect, SDL_FRect &dst_rect, float delta_time) { + void update(SDL_FRect& src_rect, SDL_FRect& dst_rect, float delta_time) { if (enabled) { counter_s -= delta_time; if (counter_s <= 0.0f) { counter_s = delay_s; // Alternar desplazamiento basado en tiempo restante - const bool SHAKE_LEFT = static_cast(remaining_s * 30.0f) % 2 == 0; // ~30 cambios por segundo + const bool SHAKE_LEFT = static_cast(remaining_s * 30.0f) % 2 == 0; // ~30 cambios por segundo const auto SRC_DESP = SHAKE_LEFT ? 0 : desp; const auto DST_DESP = SHAKE_LEFT ? desp : 0; src_rect.x = original_pos + SRC_DESP; @@ -208,45 +208,45 @@ class Screen { #endif // --- Objetos y punteros --- - SDL_Window *window_; // Ventana de la aplicación - SDL_Renderer *renderer_; // El renderizador de la ventana - SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador - ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio - Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla - std::shared_ptr text_; // Objeto para escribir texto en pantalla + SDL_Window* window_; // Ventana de la aplicación + SDL_Renderer* renderer_; // El renderizador de la ventana + SDL_Texture* game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador + ServiceMenu* service_menu_; // Objeto para mostrar el menú de servicio + Notifier* notifier_; // Objeto para mostrar las notificaciones por pantalla + std::shared_ptr text_; // Objeto para escribir texto en pantalla std::unique_ptr shader_backend_; // Backend de shaders (OpenGL/Metal/Vulkan) // --- Variables de estado --- - SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego - SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego + SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego + SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego std::string vertex_shader_source_; // Almacena el vertex shader std::string fragment_shader_source_; // Almacena el fragment shader - FPS fps_; // Gestión de frames por segundo - FlashEffect flash_effect_; // Efecto de flash en pantalla - ShakeEffect shake_effect_; // Efecto de agitar la pantalla - bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada - DisplayMonitor display_monitor_; // Información del monitor actual + FPS fps_; // Gestión de frames por segundo + FlashEffect flash_effect_; // Efecto de flash en pantalla + ShakeEffect shake_effect_; // Efecto de agitar la pantalla + bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada + DisplayMonitor display_monitor_; // Información del monitor actual #ifdef _DEBUG Debug debug_info_; // Información de debug #endif // --- Métodos internos --- - auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana - void renderFlash(); // Dibuja el efecto de flash en la pantalla - void renderShake(); // Aplica el efecto de agitar la pantalla - void renderInfo(); // Muestra información por pantalla - void renderPresent(); // Selecciona y ejecuta el método de renderizado adecuado - void loadShaders(); // Carga el contenido del archivo GLSL - void adjustWindowSize(); // Calcula el tamaño de la ventana - void getDisplayInfo(); // Obtiene información sobre la pantalla - void renderOverlays(); // Renderiza todos los overlays y efectos - void renderAttenuate(); // Atenúa la pantalla - void createText(); // Crea el objeto de texto + auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana + void renderFlash(); // Dibuja el efecto de flash en la pantalla + void renderShake(); // Aplica el efecto de agitar la pantalla + void renderInfo(); // Muestra información por pantalla + void renderPresent(); // Selecciona y ejecuta el método de renderizado adecuado + void loadShaders(); // Carga el contenido del archivo GLSL + void adjustWindowSize(); // Calcula el tamaño de la ventana + void getDisplayInfo(); // Obtiene información sobre la pantalla + void renderOverlays(); // Renderiza todos los overlays y efectos + void renderAttenuate(); // Atenúa la pantalla + void createText(); // Crea el objeto de texto // --- Constructores y destructor privados (singleton) --- Screen(); // Constructor privado ~Screen(); // Destructor privado // --- Instancia singleton --- - static Screen *instance; // Instancia única de Screen + static Screen* instance; // Instancia única de Screen }; \ No newline at end of file diff --git a/source/sections/credits.cpp b/source/sections/credits.cpp index b83a78b..87ddd79 100644 --- a/source/sections/credits.cpp +++ b/source/sections/credits.cpp @@ -1,5 +1,5 @@ // IWYU pragma: no_include -#include "credits.h" +#include "credits.hpp" #include // Para SDL_RenderFillRect, SDL_RenderTexture, SDL_SetRenderTarget, SDL_SetRenderDrawColor, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetTicks, SDL_GetRenderTarget, SDL_PixelFormat, SDL_PollEvent, SDL_RenderClear, SDL_RenderRect, SDL_SetTextureBlendMode, SDL_TextureAccess, SDL_BLENDMODE_BLEND, SDL_Event @@ -10,25 +10,25 @@ #include // Para string_view #include // Para vector -#include "audio.h" // Para Audio -#include "balloon_manager.h" // Para BalloonManager -#include "color.h" // Para Zone, Colors::SHADOW_TEXT, Colors::NO_COLOR_MOD, Color -#include "fade.h" // Para Fade, FadeType, FadeMode -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input, Input::ALLOW_REPEAT -#include "lang.h" // Para getText -#include "param.h" // Para Param, param, ParamGame, ParamFade -#include "player.h" // Para Player, PlayerState -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text, Text::CENTER, Text::SHADOW -#include "texture.h" // Para Texture -#include "tiled_bg.h" // Para TiledBG, TiledBGMode -#include "ui/service_menu.h" // Para ServiceMenu -#include "utils.h" +#include "audio.hpp" // Para Audio +#include "balloon_manager.hpp" // Para BalloonManager +#include "color.hpp" // Para Zone, Colors::SHADOW_TEXT, Colors::NO_COLOR_MOD, Color +#include "fade.hpp" // Para Fade, FadeType, FadeMode +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "input.hpp" // Para Input, Input::ALLOW_REPEAT +#include "lang.hpp" // Para getText +#include "param.hpp" // Para Param, param, ParamGame, ParamFade +#include "player.hpp" // Para Player, PlayerState +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name +#include "sprite.hpp" // Para Sprite +#include "text.hpp" // Para Text, Text::CENTER, Text::SHADOW +#include "texture.hpp" // Para Texture +#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode +#include "ui/service_menu.hpp" // Para ServiceMenu +#include "utils.hpp" // Textos constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner"; @@ -105,7 +105,7 @@ void Credits::update(float deltaTime) { const float multiplier = want_to_pass_ ? 4.0f : 1.0f; const float adjusted_delta_time = deltaTime * multiplier; - static auto *const SCREEN = Screen::get(); + static auto* const SCREEN = Screen::get(); SCREEN->update(deltaTime); // Actualiza el objeto screen Audio::update(); // Actualiza el objeto audio @@ -126,7 +126,7 @@ void Credits::update(float deltaTime) { // Dibuja Credits::en patalla void Credits::render() { - static auto *const SCREEN = Screen::get(); + static auto* const SCREEN = Screen::get(); SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego SDL_RenderTexture(SCREEN->getRenderer(), canvas_, nullptr, nullptr); // Copia la textura con la zona de juego a la pantalla @@ -251,7 +251,7 @@ void Credits::fillTextTexture() { // Dibuja todos los sprites en la textura void Credits::fillCanvas() { // Cambia el destino del renderizador - auto *temp = SDL_GetRenderTarget(Screen::get()->getRenderer()); + auto* temp = SDL_GetRenderTarget(Screen::get()->getRenderer()); SDL_SetRenderTarget(Screen::get()->getRenderer(), canvas_); // Dibuja el fondo, los globos y los jugadores @@ -411,7 +411,7 @@ void Credits::initPlayers() { players_.back()->setPlayingState(Player::State::CREDITS); // Registra los jugadores en Options - for (const auto &player : players_) { + for (const auto& player : players_) { Options::keyboard.addPlayer(player); Options::gamepad_manager.addPlayer(player); } @@ -541,14 +541,14 @@ void Credits::cycleColors() { // Actualza los jugadores (time-based) void Credits::updatePlayers(float deltaTime) { - for (auto &player : players_) { + for (auto& player : players_) { player->update(deltaTime); } } // Renderiza los jugadores void Credits::renderPlayers() { - for (auto const &player : players_) { + for (auto const& player : players_) { player->render(); } } diff --git a/source/sections/credits.h b/source/sections/credits.hpp similarity index 61% rename from source/sections/credits.h rename to source/sections/credits.hpp index 7be39e8..b576a2b 100644 --- a/source/sections/credits.h +++ b/source/sections/credits.hpp @@ -5,10 +5,10 @@ #include // Para unique_ptr, shared_ptr #include // Para vector -#include "color.h" // Para Zone, Color -#include "options.h" // Para AudioOptions, MusicOptions, audio -#include "param.h" // Para Param, ParamGame, param -#include "utils.h" +#include "color.hpp" // Para Zone, Color +#include "options.hpp" // Para AudioOptions, MusicOptions, audio +#include "param.hpp" // Para Param, ParamGame, param +#include "utils.hpp" // Declaraciones adelantadas class BalloonManager; @@ -27,7 +27,7 @@ class Credits { private: // --- Métodos del bucle principal --- - void update(float deltaTime); // Actualización principal de la lógica (time-based) + void update(float deltaTime); // Actualización principal de la lógica (time-based) auto calculateDeltaTime() -> float; // Calcula el deltatime private: @@ -42,14 +42,14 @@ class Credits { std::vector> players_; // Vector de jugadores // --- Gestión de texturas --- - SDL_Texture *text_texture_; // Textura con el texto de créditos - SDL_Texture *canvas_; // Textura donde se dibuja todo + SDL_Texture* text_texture_; // Textura con el texto de créditos + SDL_Texture* canvas_; // Textura donde se dibuja todo // --- Temporización y contadores --- - Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime - float counter_ = 0; // Contador principal de lógica - float counter_pre_fade_ = 0; // Activación del fundido final - float counter_prevent_endless_ = 0; // Prevención de bucle infinito + Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime + float counter_ = 0; // Contador principal de lógica + float counter_pre_fade_ = 0; // Activación del fundido final + float counter_prevent_endless_ = 0; // Prevención de bucle infinito // --- Variables de estado --- bool fading_ = false; // Estado del fade final @@ -67,16 +67,16 @@ class Credits { // --- Estado de acumuladores para animaciones --- struct CreditsState { - float texture_accumulator = 0.0f; - float balloon_accumulator = 0.0f; - float powerball_accumulator = 0.0f; - float black_rect_accumulator = 0.0f; - float r = 255.0f; // UPPER_LIMIT - float g = 0.0f; // LOWER_LIMIT - float b = 0.0f; // LOWER_LIMIT - float step_r = -0.5f; - float step_g = 0.3f; - float step_b = 0.1f; + float texture_accumulator = 0.0f; + float balloon_accumulator = 0.0f; + float powerball_accumulator = 0.0f; + float black_rect_accumulator = 0.0f; + float r = 255.0f; // UPPER_LIMIT + float g = 0.0f; // LOWER_LIMIT + float b = 0.0f; // LOWER_LIMIT + float step_r = -0.5f; + float step_g = 0.3f; + float step_b = 0.1f; } credits_state_; // --- Rectángulos de renderizado --- @@ -125,25 +125,25 @@ class Credits { void checkInput(); // Procesamiento de entrada // --- Métodos de renderizado --- - void fillTextTexture(); // Crear textura de texto de créditos - void fillCanvas(); // Renderizar todos los sprites y fondos - void renderPlayers(); // Renderiza los jugadores + void fillTextTexture(); // Crear textura de texto de créditos + void fillCanvas(); // Renderizar todos los sprites y fondos + void renderPlayers(); // Renderiza los jugadores // --- Métodos de lógica del juego --- - void throwBalloons(); // Lanzar globos al escenario (frame-based) - void throwBalloons(float deltaTime); // Lanzar globos al escenario (time-based) - void initPlayers(); // Inicializar jugadores - void updateAllFades(); // Actualizar estados de fade (frame-based) - void updateAllFades(float deltaTime); // Actualizar estados de fade (time-based) - void cycleColors(); // Cambiar colores de fondo - void updatePlayers(float deltaTime); // Actualza los jugadores (time-based) + void throwBalloons(); // Lanzar globos al escenario (frame-based) + void throwBalloons(float deltaTime); // Lanzar globos al escenario (time-based) + void initPlayers(); // Inicializar jugadores + void updateAllFades(); // Actualizar estados de fade (frame-based) + void updateAllFades(float deltaTime); // Actualizar estados de fade (time-based) + void cycleColors(); // Cambiar colores de fondo + void updatePlayers(float deltaTime); // Actualza los jugadores (time-based) // --- Métodos de interfaz --- - void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based) - void updateBlackRects(float deltaTime); // Actualizar rectángulos negros (letterbox) (time-based) - void updateRedRect(); // Actualizar rectángulo rojo (borde) - void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based) - void updateTextureDstRects(float deltaTime); // Actualizar destinos de texturas (time-based) + void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based) + void updateBlackRects(float deltaTime); // Actualizar rectángulos negros (letterbox) (time-based) + void updateRedRect(); // Actualizar rectángulo rojo (borde) + void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based) + void updateTextureDstRects(float deltaTime); // Actualizar destinos de texturas (time-based) // --- Métodos de audio --- static void setVolume(int amount); // Establecer volumen diff --git a/source/sections/game.cpp b/source/sections/game.cpp index 815ac8d..e67190e 100644 --- a/source/sections/game.cpp +++ b/source/sections/game.cpp @@ -1,4 +1,4 @@ -#include "game.h" +#include "game.hpp" #include // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_CreateTexture, SDL_Delay, SDL_DestroyTexture, SDL_EventType, SDL_GetRenderTarget, SDL_PollEvent, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_Event, SDL_PixelFormat, SDL_Point, SDL_TextureAccess @@ -11,42 +11,42 @@ #include // std::random_device, std::default_random_engine #include // Para move -#include "asset.h" // Para Asset -#include "audio.h" // Para Audio -#include "background.h" // Para Background -#include "balloon.h" // Para Balloon -#include "balloon_manager.h" // Para BalloonManager -#include "bullet.h" // Para Bullet, Bullet::Type, BulletMoveStatus -#include "bullet_manager.h" // Para BulletManager -#include "color.h" // Para Color, Colors::FLASH -#include "difficulty.h" // Para Code -#include "fade.h" // Para Fade, FadeType, FadeMode -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "hit.h" // Para Hit -#include "input.h" // Para Input -#include "input_types.h" // Para InputAction -#include "item.h" // Para Item, ItemType -#include "lang.h" // Para getText -#include "manage_hiscore_table.h" // Para HiScoreEntry, ManageHiScoreTable -#include "param.h" // Para Param, param, ParamGame, ParamScoreboard, ParamFade, ParamBalloon -#include "path_sprite.h" // Para Path, PathSprite, createPath, PathType -#include "pause_manager.h" // Para PauseManager -#include "player.h" // Para Player -#include "resource.h" // Para Resource -#include "scoreboard.h" // Para Scoreboard -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, AttractMode, Options, attract_mode, options -#include "smart_sprite.h" // Para SmartSprite -#include "stage.h" // Para number, Stage, get, total_power, power, init, power_can_be_added, stages -#include "tabe.h" // Para Tabe -#include "text.h" // Para Text -#include "texture.h" // Para Texture -#include "ui/service_menu.h" // Para ServiceMenu +#include "asset.hpp" // Para Asset +#include "audio.hpp" // Para Audio +#include "background.hpp" // Para Background +#include "balloon.hpp" // Para Balloon +#include "balloon_manager.hpp" // Para BalloonManager +#include "bullet.hpp" // Para Bullet, Bullet::Type, BulletMoveStatus +#include "bullet_manager.hpp" // Para BulletManager +#include "color.hpp" // Para Color, Colors::FLASH +#include "difficulty.hpp" // Para Code +#include "fade.hpp" // Para Fade, FadeType, FadeMode +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "hit.hpp" // Para Hit +#include "input.hpp" // Para Input +#include "input_types.hpp" // Para InputAction +#include "item.hpp" // Para Item, ItemType +#include "lang.hpp" // Para getText +#include "manage_hiscore_table.hpp" // Para HiScoreEntry, ManageHiScoreTable +#include "param.hpp" // Para Param, param, ParamGame, ParamScoreboard, ParamFade, ParamBalloon +#include "path_sprite.hpp" // Para Path, PathSprite, createPath, PathType +#include "pause_manager.hpp" // Para PauseManager +#include "player.hpp" // Para Player +#include "resource.hpp" // Para Resource +#include "scoreboard.hpp" // Para Scoreboard +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, AttractMode, Options, attract_mode, options +#include "smart_sprite.hpp" // Para SmartSprite +#include "stage.hpp" // Para number, Stage, get, total_power, power, init, power_can_be_added, stages +#include "tabe.hpp" // Para Tabe +#include "text.hpp" // Para Text +#include "texture.hpp" // Para Texture +#include "ui/service_menu.hpp" // Para ServiceMenu #ifdef _DEBUG #include // Para std::cout -#include "ui/notifier.h" // Para Notifier +#include "ui/notifier.hpp" // Para Notifier #endif // Constructor @@ -902,8 +902,8 @@ void Game::render() { fade_in_->render(); // Dibuja el fade de entrada fade_out_->render(); // Dibuja el fade de salida - //SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255); - //SDL_RenderLine(renderer_, param.game.play_area.rect.x, param.game.play_area.center_y, param.game.play_area.rect.w, param.game.play_area.center_y); + // SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255); + // SDL_RenderLine(renderer_, param.game.play_area.rect.x, param.game.play_area.center_y, param.game.play_area.rect.w, param.game.play_area.center_y); screen_->render(); // Vuelca el contenido del renderizador en pantalla } diff --git a/source/sections/game.h b/source/sections/game.hpp similarity index 95% rename from source/sections/game.h rename to source/sections/game.hpp index a35e21a..e3d31e8 100644 --- a/source/sections/game.h +++ b/source/sections/game.hpp @@ -6,18 +6,18 @@ #include // Para string #include // Para vector -#include "bullet.h" // Para Bullet -#include "bullet_manager.h" // Para BulletManager -#include "hit.h" // Para Hit -#include "item.h" // Para Item, ItemType -#include "manage_hiscore_table.h" // Para HiScoreEntry -#include "options.h" // Para Settings, settings -#include "path_sprite.h" // Para PathSprite, Path -#include "player.h" // Para Player -#include "smart_sprite.h" // Para SmartSprite -#include "stage.h" // Para StageManager -#include "demo.h" // Para Demo -#include "utils.h" // Para otras utilidades +#include "bullet.hpp" // Para Bullet +#include "bullet_manager.hpp" // Para BulletManager +#include "demo.hpp" // Para Demo +#include "hit.hpp" // Para Hit +#include "item.hpp" // Para Item, ItemType +#include "manage_hiscore_table.hpp" // Para HiScoreEntry +#include "options.hpp" // Para Settings, settings +#include "path_sprite.hpp" // Para PathSprite, Path +#include "player.hpp" // Para Player +#include "smart_sprite.hpp" // Para SmartSprite +#include "stage.hpp" // Para StageManager +#include "utils.hpp" // Para otras utilidades class Background; class Balloon; @@ -316,10 +316,10 @@ class Game { void setMenace(); // Calcula y establece amenaza según globos activos // --- Puntuación y marcador --- - void updateHiScore(); // Actualiza el récord máximo si es necesario + void updateHiScore(); // Actualiza el récord máximo si es necesario void updateScoreboard(float deltaTime); // Actualiza la visualización del marcador - void updateHiScoreName(); // Pone en el marcador el nombre del primer jugador de la tabla - void initScoreboard(); // Inicializa el sistema de puntuación + void updateHiScoreName(); // Pone en el marcador el nombre del primer jugador de la tabla + void initScoreboard(); // Inicializa el sistema de puntuación // --- Modo demostración --- void initDemo(Player::Id player_id); // Inicializa variables para el modo demostración diff --git a/source/sections/hiscore_table.cpp b/source/sections/hiscore_table.cpp index 29c17e7..8529c50 100644 --- a/source/sections/hiscore_table.cpp +++ b/source/sections/hiscore_table.cpp @@ -1,4 +1,4 @@ -#include "hiscore_table.h" +#include "hiscore_table.hpp" #include // Para SDL_GetTicks, SDL_SetRenderTarget @@ -7,25 +7,25 @@ #include // Para function #include // Para vector -#include "audio.h" // Para Audio -#include "background.h" // Para Background -#include "color.h" // Para Color, easeOutQuint, Colors::NO_COLOR_MOD -#include "fade.h" // Para Fade, FadeMode, FadeType -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input -#include "lang.h" // Para getText -#include "manage_hiscore_table.h" // Para HiScoreEntry -#include "options.h" // Para SettingsOptions, settings -#include "param.h" // Para Param, param, ParamGame, ParamFade -#include "path_sprite.h" // Para PathSprite, Path, PathType -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, Options, options -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text, Text::SHADOW, Text::COLOR -#include "texture.h" // Para Texture -#include "utils.h" +#include "audio.hpp" // Para Audio +#include "background.hpp" // Para Background +#include "color.hpp" // Para Color, easeOutQuint, Colors::NO_COLOR_MOD +#include "fade.hpp" // Para Fade, FadeMode, FadeType +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "input.hpp" // Para Input +#include "lang.hpp" // Para getText +#include "manage_hiscore_table.hpp" // Para HiScoreEntry +#include "options.hpp" // Para SettingsOptions, settings +#include "param.hpp" // Para Param, param, ParamGame, ParamFade +#include "path_sprite.hpp" // Para PathSprite, Path, PathType +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, Options, options +#include "sprite.hpp" // Para Sprite +#include "text.hpp" // Para Text, Text::SHADOW, Text::COLOR +#include "texture.hpp" // Para Texture +#include "utils.hpp" // Constructor HiScoreTable::HiScoreTable() @@ -54,9 +54,9 @@ HiScoreTable::~HiScoreTable() { // Actualiza las variables void HiScoreTable::update(float delta_time) { - elapsed_time_ += delta_time; // Incrementa el tiempo transcurrido - - static auto *const SCREEN = Screen::get(); + elapsed_time_ += delta_time; // Incrementa el tiempo transcurrido + + static auto* const SCREEN = Screen::get(); SCREEN->update(delta_time); // Actualiza el objeto screen Audio::update(); // Actualiza el objeto audio @@ -69,16 +69,16 @@ void HiScoreTable::update(float delta_time) { // Pinta en pantalla void HiScoreTable::render() { - static auto *const SCREEN = Screen::get(); + static auto* const SCREEN = Screen::get(); SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego SCREEN->clean(); // Limpia la pantalla - background_->render(); // Pinta el fondo - float counter_equivalent = elapsed_time_ * 60.0f; // Convertir tiempo a equivalente frame para UI + background_->render(); // Pinta el fondo + float counter_equivalent = elapsed_time_ * 60.0f; // Convertir tiempo a equivalente frame para UI view_area_.y = std::max(0.0F, param.game.height - counter_equivalent + 100); // Establece la ventana del backbuffer SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador - fade_->render(); // Renderiza el fade + fade_->render(); // Renderiza el fade SCREEN->render(); // Vuelca el contenido del renderizador en pantalla } @@ -86,7 +86,7 @@ void HiScoreTable::render() { // Dibuja los sprites en la textura void HiScoreTable::fillTexture() { // Pinta en el backbuffer el texto y los sprites - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, backbuffer_); SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0); SDL_RenderClear(renderer_); @@ -95,7 +95,7 @@ void HiScoreTable::fillTexture() { header_->render(); // Escribe los nombres de la tabla de puntuaciones - for (auto const &entry : entry_names_) { + for (auto const& entry : entry_names_) { entry->render(); } @@ -209,7 +209,7 @@ void HiScoreTable::createSprites() { const auto TABLE_POSITION = format(i + 1) + ". "; const auto SCORE = format(Options::settings.hi_score_table.at(i).score); const auto NUM_DOTS = ENTRY_LENGTH - Options::settings.hi_score_table.at(i).name.size() - SCORE.size(); - const auto *const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : ""; + const auto* const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : ""; std::string dots; for (int j = 0; j < (int)NUM_DOTS; ++j) { dots = dots + "."; @@ -272,7 +272,7 @@ void HiScoreTable::updateSprites(float delta_time) { } } } - for (auto const &entry : entry_names_) { + for (auto const& entry : entry_names_) { entry->update(delta_time); } @@ -359,7 +359,7 @@ void HiScoreTable::iniEntryColors() { void HiScoreTable::glowEntryNames() { int color_counter = static_cast(elapsed_time_ * 60.0f / 5.0f); // Convertir tiempo a equivalente frame const Color ENTRY_COLOR = getEntryColor(color_counter); - for (const auto &entry_index : Options::settings.glowing_entries) { + for (const auto& entry_index : Options::settings.glowing_entries) { if (entry_index != -1) { entry_names_.at(entry_index)->getTexture()->setColor(ENTRY_COLOR); } diff --git a/source/sections/hiscore_table.h b/source/sections/hiscore_table.hpp similarity index 89% rename from source/sections/hiscore_table.h rename to source/sections/hiscore_table.hpp index b9f21e0..4686674 100644 --- a/source/sections/hiscore_table.h +++ b/source/sections/hiscore_table.hpp @@ -6,9 +6,9 @@ #include // Para string #include // Para vector -#include "color.h" // Para Color -#include "fade.h" // Para Fade -#include "path_sprite.h" // Para Path, PathSprite (ptr only) +#include "color.hpp" // Para Color +#include "fade.hpp" // Para Fade +#include "path_sprite.hpp" // Para Path, PathSprite (ptr only) class Background; class Sprite; @@ -39,8 +39,8 @@ class HiScoreTable { static constexpr float CLOUDS_SPEED = -6.0f; // Velocidad nubes (pixels/s) // --- Objetos y punteros --- - SDL_Renderer *renderer_; // El renderizador de la ventana - SDL_Texture *backbuffer_; // Textura para usar como backbuffer + SDL_Renderer* renderer_; // El renderizador de la ventana + SDL_Texture* backbuffer_; // Textura para usar como backbuffer std::unique_ptr fade_; // Objeto para renderizar fades std::unique_ptr background_; // Objeto para dibujar el fondo del juego @@ -58,13 +58,13 @@ class HiScoreTable { // --- Flags para eventos basados en tiempo --- struct HiScoreFlags { - bool background_changed = false; - bool fade_activated = false; + bool background_changed = false; + bool fade_activated = false; - void reset() { - background_changed = false; - fade_activated = false; - } + void reset() { + background_changed = false; + fade_activated = false; + } } hiscore_flags_; // --- Métodos internos --- diff --git a/source/sections/instructions.cpp b/source/sections/instructions.cpp index 1d0fc30..b8da7fb 100644 --- a/source/sections/instructions.cpp +++ b/source/sections/instructions.cpp @@ -1,4 +1,4 @@ -#include "instructions.h" +#include "instructions.hpp" #include // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_Re... @@ -8,22 +8,22 @@ #include // Para move #include // Para vector -#include "audio.h" // Para Audio -#include "color.h" // Para Color, Colors::SHADOW_TEXT, Zone, NO_TEXT_C... -#include "fade.h" // Para Fade, FadeMode, FadeType -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input -#include "item.h" // Para Item -#include "lang.h" // Para getText -#include "param.h" // Para Param, param, ParamGame, ParamFade, Param... -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, Options, options -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW -#include "tiled_bg.h" // Para TiledBG, TiledBGMode -#include "utils.h" +#include "audio.hpp" // Para Audio +#include "color.hpp" // Para Color, Colors::SHADOW_TEXT, Zone, NO_TEXT_C... +#include "fade.hpp" // Para Fade, FadeMode, FadeType +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "input.hpp" // Para Input +#include "item.hpp" // Para Item +#include "lang.hpp" // Para getText +#include "param.hpp" // Para Param, param, ParamGame, ParamFade, Param... +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, Options, options +#include "sprite.hpp" // Para Sprite +#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW +#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode +#include "utils.hpp" // Constructor Instructions::Instructions() diff --git a/source/sections/instructions.h b/source/sections/instructions.hpp similarity index 91% rename from source/sections/instructions.h rename to source/sections/instructions.hpp index 6918d82..7ee7013 100644 --- a/source/sections/instructions.h +++ b/source/sections/instructions.hpp @@ -5,7 +5,7 @@ #include // Para unique_ptr, shared_ptr #include // Para vector -#include "sprite.h" // Para Sprite +#include "sprite.hpp" // Para Sprite class Fade; class Text; @@ -57,9 +57,9 @@ class Instructions { static constexpr float LINE_START_DELAY_MS = 5.0f; // Retraso entre líneas (5ms) // --- Objetos y punteros --- - SDL_Renderer *renderer_; // El renderizador de la ventana - SDL_Texture *texture_; // Textura fija con el texto - SDL_Texture *backbuffer_; // Textura para usar como backbuffer + SDL_Renderer* renderer_; // El renderizador de la ventana + SDL_Texture* texture_; // Textura fija con el texto + SDL_Texture* backbuffer_; // Textura para usar como backbuffer std::vector> item_textures_; // Vector con las texturas de los items std::vector> sprites_; // Vector con los sprites de los items @@ -88,8 +88,8 @@ class Instructions { void iniSprites(); // Inicializa los sprites de los items void updateSprites(); // Actualiza los sprites static auto initializeLines(int height) -> std::vector; // Inicializa las líneas animadas - static auto moveLines(std::vector &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas (ya usa tiempo real) - static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector &lines); // Renderiza las líneas - void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos + static auto moveLines(std::vector& lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas (ya usa tiempo real) + static void renderLines(SDL_Renderer* renderer, SDL_Texture* texture, const std::vector& lines); // Renderiza las líneas + void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame }; \ No newline at end of file diff --git a/source/sections/intro.cpp b/source/sections/intro.cpp index 0cc2ac4..d1b74b0 100644 --- a/source/sections/intro.cpp +++ b/source/sections/intro.cpp @@ -1,4 +1,4 @@ -#include "intro.h" +#include "intro.hpp" #include // Para SDL_GetTicks, SDL_SetRenderDrawColor, SDL_FRect, SDL_RenderFillRect, SDL_GetRenderTarget, SDL_RenderClear, SDL_RenderRect, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_PollEvent, SDL_RenderTexture, SDL_TextureAccess, SDL_Event, Uint32 @@ -8,22 +8,22 @@ #include // Para basic_string, string #include // Para move -#include "audio.h" // Para Audio -#include "color.h" // Para Color -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input -#include "lang.h" // Para getText -#include "param.h" // Para Param, param, ParamGame, ParamIntro, ParamTitle -#include "path_sprite.h" // Para PathSprite, PathType -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, Options, options -#include "text.h" // Para Text -#include "texture.h" // Para Texture -#include "tiled_bg.h" // Para TiledBG, TiledBGMode -#include "utils.h" // Para Zone, easeInOutExpo, easeInElastic, easeOutBounce, easeOutElastic, easeOutQuad, easeOutQuint -#include "writer.h" // Para Writer +#include "audio.hpp" // Para Audio +#include "color.hpp" // Para Color +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "input.hpp" // Para Input +#include "lang.hpp" // Para getText +#include "param.hpp" // Para Param, param, ParamGame, ParamIntro, ParamTitle +#include "path_sprite.hpp" // Para PathSprite, PathType +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, Options, options +#include "text.hpp" // Para Text +#include "texture.hpp" // Para Texture +#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode +#include "utils.hpp" // Para Zone, easeInOutExpo, easeInElastic, easeOutBounce, easeOutElastic, easeOutQuad, easeOutQuint +#include "writer.hpp" // Para Writer // Constructor Intro::Intro() diff --git a/source/sections/intro.h b/source/sections/intro.hpp similarity index 96% rename from source/sections/intro.h rename to source/sections/intro.hpp index 161b715..afd7acd 100644 --- a/source/sections/intro.h +++ b/source/sections/intro.hpp @@ -5,11 +5,11 @@ #include // Para unique_ptr #include // Para vector -#include "color.h" // Para Color -#include "param.h" // Para Param, ParamIntro, param -#include "path_sprite.h" // Para PathSprite -#include "tiled_bg.h" // Para TiledBG -#include "writer.h" // Para Writer +#include "color.hpp" // Para Color +#include "param.hpp" // Para Param, ParamIntro, param +#include "path_sprite.hpp" // Para PathSprite +#include "tiled_bg.hpp" // Para TiledBG +#include "writer.hpp" // Para Writer // --- Clase Intro: secuencia cinemática de introducción del juego --- // diff --git a/source/sections/logo.cpp b/source/sections/logo.cpp index a167212..2e9d5ff 100644 --- a/source/sections/logo.cpp +++ b/source/sections/logo.cpp @@ -1,21 +1,21 @@ -#include "logo.h" +#include "logo.hpp" #include // Para SDL_GetTicks, SDL_PollEvent, SDL_Event, SDL_FRect #include // Para move -#include "audio.h" // Para Audio -#include "color.h" // Para Color -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input -#include "param.h" // Para Param, ParamGame, param -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture -#include "utils.h" // Para Zone +#include "audio.hpp" // Para Audio +#include "color.hpp" // Para Color +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "input.hpp" // Para Input +#include "param.hpp" // Para Param, ParamGame, param +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name +#include "sprite.hpp" // Para Sprite +#include "texture.hpp" // Para Texture +#include "utils.hpp" // Para Zone // Constructor Logo::Logo() @@ -138,7 +138,7 @@ void Logo::updateTextureColors(float delta_time) { void Logo::update(float delta_time) { elapsed_time_s_ += delta_time; // Acumula el tiempo transcurrido - static auto *const SCREEN = Screen::get(); + static auto* const SCREEN = Screen::get(); SCREEN->update(delta_time); // Actualiza el objeto screen Audio::update(); // Actualiza el objeto audio @@ -149,7 +149,7 @@ void Logo::update(float delta_time) { // Dibuja en pantalla void Logo::render() { - static auto *const SCREEN = Screen::get(); + static auto* const SCREEN = Screen::get(); SCREEN->start(); SCREEN->clean(); @@ -184,7 +184,7 @@ void Logo::run() { // Renderiza el logo de JAILGAMES void Logo::renderJAILGAMES() { // Dibuja los sprites - for (auto &sprite : jail_sprite_) { + for (auto& sprite : jail_sprite_) { sprite->render(); } diff --git a/source/sections/logo.h b/source/sections/logo.hpp similarity index 91% rename from source/sections/logo.h rename to source/sections/logo.hpp index 314c34c..9c33d7a 100644 --- a/source/sections/logo.h +++ b/source/sections/logo.hpp @@ -5,8 +5,8 @@ #include // Para unique_ptr, shared_ptr #include // Para vector -#include "color.h" // Para Color -#include "sprite.h" // Para Sprite +#include "color.hpp" // Para Color +#include "sprite.hpp" // Para Sprite class Texture; @@ -36,13 +36,13 @@ class Logo { private: // --- Constantes de tiempo (en segundos) --- - static constexpr float SOUND_TRIGGER_TIME_S = 0.5f; // Tiempo para activar el sonido del logo - static constexpr float SHOW_SINCE_SPRITE_TIME_S = 1.167f; // Tiempo para mostrar el sprite "SINCE 1998" - static constexpr float INIT_FADE_TIME_S = 5.0f; // Tiempo de inicio del fade a negro - static constexpr float END_LOGO_TIME_S = 6.668f; // Tiempo de finalización del logo - static constexpr float POST_LOGO_DURATION_S = 0.333f; // Duración adicional después del fade - static constexpr float LOGO_SPEED_PX_PER_S = 480.0f; // Velocidad de desplazamiento (píxeles por segundo) - 8.0f/16.67f*1000 - static constexpr float COLOR_CHANGE_INTERVAL_S = 0.0667f; // Intervalo entre cambios de color (~4 frames a 60fps) + static constexpr float SOUND_TRIGGER_TIME_S = 0.5f; // Tiempo para activar el sonido del logo + static constexpr float SHOW_SINCE_SPRITE_TIME_S = 1.167f; // Tiempo para mostrar el sprite "SINCE 1998" + static constexpr float INIT_FADE_TIME_S = 5.0f; // Tiempo de inicio del fade a negro + static constexpr float END_LOGO_TIME_S = 6.668f; // Tiempo de finalización del logo + static constexpr float POST_LOGO_DURATION_S = 0.333f; // Duración adicional después del fade + static constexpr float LOGO_SPEED_PX_PER_S = 480.0f; // Velocidad de desplazamiento (píxeles por segundo) - 8.0f/16.67f*1000 + static constexpr float COLOR_CHANGE_INTERVAL_S = 0.0667f; // Intervalo entre cambios de color (~4 frames a 60fps) // --- Constantes de layout --- static constexpr int SINCE_SPRITE_Y_OFFSET = 83; // Posición Y base del sprite "Since 1998" diff --git a/source/sections/title.cpp b/source/sections/title.cpp index 34ba844..27f35c1 100644 --- a/source/sections/title.cpp +++ b/source/sections/title.cpp @@ -1,4 +1,4 @@ -#include "title.h" +#include "title.hpp" #include // Para SDL_GetTicks, Uint32, SDL_Event, SDL_PollEvent, SDL_EventType @@ -6,27 +6,27 @@ #include // Para operator+, char_traits, to_string, string, basic_string #include // Para vector -#include "audio.h" // Para Audio -#include "color.h" // Para Colors::NO_COLOR_MOD, Colors::TITLE_SHADOW_TEXT -#include "fade.h" // Para Fade, FadeType -#include "game_logo.h" // Para GameLogo -#include "global_events.h" // Para check -#include "global_inputs.h" // Para check -#include "input.h" // Para Input -#include "input_types.h" // Para InputAction -#include "lang.h" // Para getText -#include "options.h" // Para Gamepad, GamepadManager, gamepad_manager, Settings, settings, Keyboard, keyboard, getPlayerWhoUsesKeyboard, swapControllers, swapKeyboard -#include "param.h" // Para Param, param, ParamGame, ParamTitle, ParamFade -#include "player.h" // Para Player -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text -#include "tiled_bg.h" // Para TiledBG, TiledBGMode -#include "ui/notifier.h" // Para Notifier -#include "ui/service_menu.h" // Para ServiceMenu -#include "utils.h" // Para Zone, BLOCK +#include "audio.hpp" // Para Audio +#include "color.hpp" // Para Colors::NO_COLOR_MOD, Colors::TITLE_SHADOW_TEXT +#include "fade.hpp" // Para Fade, FadeType +#include "game_logo.hpp" // Para GameLogo +#include "global_events.hpp" // Para check +#include "global_inputs.hpp" // Para check +#include "input.hpp" // Para Input +#include "input_types.hpp" // Para InputAction +#include "lang.hpp" // Para getText +#include "options.hpp" // Para Gamepad, GamepadManager, gamepad_manager, Settings, settings, Keyboard, keyboard, getPlayerWhoUsesKeyboard, swapControllers, swapKeyboard +#include "param.hpp" // Para Param, param, ParamGame, ParamTitle, ParamFade +#include "player.hpp" // Para Player +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode +#include "sprite.hpp" // Para Sprite +#include "text.hpp" // Para Text +#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode +#include "ui/notifier.hpp" // Para Notifier +#include "ui/service_menu.hpp" // Para ServiceMenu +#include "utils.hpp" // Para Zone, BLOCK class Texture; @@ -45,7 +45,8 @@ Title::Title() state_(State::LOGO_ANIMATING), num_controllers_(Input::get()->getNumGamepads()) #ifdef _DEBUG - , debug_color_(param.title.bg_color) + , + debug_color_(param.title.bg_color) #endif { // Configura objetos @@ -84,7 +85,7 @@ Title::~Title() { // Actualiza las variables del objeto void Title::update(float deltaTime) { - static auto *const SCREEN = Screen::get(); + static auto* const SCREEN = Screen::get(); SCREEN->update(deltaTime); // Actualiza el objeto screen Audio::update(); // Actualiza el objeto audio diff --git a/source/sections/title.h b/source/sections/title.hpp similarity index 95% rename from source/sections/title.h rename to source/sections/title.hpp index 6f2c3e3..d4d8546 100644 --- a/source/sections/title.h +++ b/source/sections/title.hpp @@ -6,7 +6,7 @@ #include // Para string_view #include // Para vector -#include "player.h" // Para Player +#include "player.hpp" // Para Player #include "section.hpp" // Para Options, Name (ptr only) class Fade; @@ -130,11 +130,11 @@ class Title { auto getPlayer(Player::Id id) -> std::shared_ptr; // Obtiene un jugador a partir de su "id" // --- Visualización / Renderizado --- - void render(); // Dibuja el objeto en pantalla - void updateFade(); // Actualiza el efecto de fundido (fade in/out) + void render(); // Dibuja el objeto en pantalla + void updateFade(); // Actualiza el efecto de fundido (fade in/out) void updateStartPrompt(float deltaTime); // Actualiza el mensaje de "Pulsa Start" - void renderStartPrompt(); // Dibuja el mensaje de "Pulsa Start" en pantalla - void renderCopyright(); // Dibuja el aviso de copyright + void renderStartPrompt(); // Dibuja el mensaje de "Pulsa Start" en pantalla + void renderCopyright(); // Dibuja el aviso de copyright // --- Utilidades estáticas --- static void swapControllers(); // Intercambia la asignación de mandos a los jugadores diff --git a/source/service_menu.h b/source/service_menu.hpp similarity index 100% rename from source/service_menu.h rename to source/service_menu.hpp diff --git a/source/shutdown.cpp b/source/shutdown.cpp index 6c03cb2..9fc4a4f 100644 --- a/source/shutdown.cpp +++ b/source/shutdown.cpp @@ -1,4 +1,4 @@ -#include "shutdown.h" +#include "shutdown.hpp" #include #include diff --git a/source/shutdown.h b/source/shutdown.hpp similarity index 100% rename from source/shutdown.h rename to source/shutdown.hpp diff --git a/source/smart_sprite.cpp b/source/smart_sprite.cpp index d9d4f0f..fb893ae 100644 --- a/source/smart_sprite.cpp +++ b/source/smart_sprite.cpp @@ -1,6 +1,6 @@ -#include "smart_sprite.h" +#include "smart_sprite.hpp" -#include "moving_sprite.h" // Para MovingSprite +#include "moving_sprite.hpp" // Para MovingSprite // Actualiza la posición y comprueba si ha llegado a su destino (time-based) void SmartSprite::update(float deltaTime) { diff --git a/source/smart_sprite.h b/source/smart_sprite.hpp similarity index 71% rename from source/smart_sprite.h rename to source/smart_sprite.hpp index 0b0d26f..bcfe394 100644 --- a/source/smart_sprite.h +++ b/source/smart_sprite.hpp @@ -3,7 +3,7 @@ #include // Para shared_ptr #include -#include "animated_sprite.h" // Para AnimatedSprite +#include "animated_sprite.hpp" // Para AnimatedSprite class Texture; @@ -17,7 +17,7 @@ class SmartSprite : public AnimatedSprite { // --- Métodos principales --- void update(float deltaTime) override; // Actualiza la posición y comprueba si ha llegado a su destino (time-based) - void render() override; // Dibuja el sprite + void render() override; // Dibuja el sprite // --- Getters --- auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X @@ -33,15 +33,15 @@ class SmartSprite : public AnimatedSprite { private: // --- Variables de estado --- - int dest_x_ = 0; // Posición de destino en el eje X - int dest_y_ = 0; // Posición de destino en el eje Y - float finished_delay_ms_ = 0.0f; // Retraso para deshabilitarlo (ms) - float finished_timer_ = 0.0f; // Timer acumulado (ms) - bool on_destination_ = false; // Indica si está en el destino - bool finished_ = false; // Indica si ya ha terminado - bool enabled_ = false; // Indica si el objeto está habilitado + int dest_x_ = 0; // Posición de destino en el eje X + int dest_y_ = 0; // Posición de destino en el eje Y + float finished_delay_ms_ = 0.0f; // Retraso para deshabilitarlo (ms) + float finished_timer_ = 0.0f; // Timer acumulado (ms) + bool on_destination_ = false; // Indica si está en el destino + bool finished_ = false; // Indica si ya ha terminado + bool enabled_ = false; // Indica si el objeto está habilitado // --- Métodos internos --- void checkFinished(float deltaTime); // Comprueba si ha terminado (time-based) - void checkMove(); // Comprueba el movimiento + void checkMove(); // Comprueba el movimiento }; \ No newline at end of file diff --git a/source/sprite.cpp b/source/sprite.cpp index 2429265..668584a 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -1,9 +1,9 @@ -#include "sprite.h" +#include "sprite.hpp" #include #include // Para vector -#include "texture.h" // Para Texture +#include "texture.hpp" // Para Texture // Constructor Sprite::Sprite(std::shared_ptr texture, float pos_x, float pos_y, float width, float height) diff --git a/source/sprite.h b/source/sprite.hpp similarity index 100% rename from source/sprite.h rename to source/sprite.hpp diff --git a/source/stage.cpp b/source/stage.cpp index ab605ce..c24306a 100644 --- a/source/stage.cpp +++ b/source/stage.cpp @@ -1,4 +1,4 @@ -#include "stage.h" +#include "stage.hpp" #include #include diff --git a/source/stage.h b/source/stage.hpp similarity index 99% rename from source/stage.h rename to source/stage.hpp index 0bfc01a..fda56c1 100644 --- a/source/stage.h +++ b/source/stage.hpp @@ -5,7 +5,7 @@ #include // Para string #include // Para vector -#include "stage_interface.h" // Para IStageInfo +#include "stage_interface.hpp" // Para IStageInfo // --- Enums --- enum class PowerCollectionState { diff --git a/source/stage_interface.h b/source/stage_interface.hpp similarity index 100% rename from source/stage_interface.h rename to source/stage_interface.hpp diff --git a/source/system_utils.cpp b/source/system_utils.cpp index f4a5093..819f4dc 100644 --- a/source/system_utils.cpp +++ b/source/system_utils.cpp @@ -1,4 +1,4 @@ -#include "system_utils.h" +#include "system_utils.hpp" #include diff --git a/source/system_utils.h b/source/system_utils.hpp similarity index 100% rename from source/system_utils.h rename to source/system_utils.hpp diff --git a/source/tabe.cpp b/source/tabe.cpp index d6ef4cf..619c3ce 100644 --- a/source/tabe.cpp +++ b/source/tabe.cpp @@ -1,5 +1,5 @@ // IWYU pragma: no_include -#include "tabe.h" +#include "tabe.hpp" #include // Para SDL_FlipMode, SDL_GetTicks @@ -7,10 +7,10 @@ #include // Para array #include // Para rand, abs -#include "audio.h" // Para Audio -#include "param.h" // Para Param, ParamGame, param -#include "resource.h" // Para Resource -#include "utils.h" // Para Zone +#include "audio.hpp" // Para Audio +#include "param.hpp" // Para Param, ParamGame, param +#include "resource.hpp" // Para Resource +#include "utils.hpp" // Para Zone // Constructor Tabe::Tabe() @@ -40,7 +40,6 @@ void Tabe::render() { // Mueve el objeto (time-based) void Tabe::move(float deltaTime) { - const int X = static_cast(x_); speed_ += accel_ * deltaTime; x_ += speed_ * deltaTime; diff --git a/source/tabe.h b/source/tabe.hpp similarity index 97% rename from source/tabe.h rename to source/tabe.hpp index 4fde522..00aa28b 100644 --- a/source/tabe.h +++ b/source/tabe.hpp @@ -5,7 +5,7 @@ #include // Para rand #include // Para unique_ptr -#include "animated_sprite.h" // Para AnimatedSprite +#include "animated_sprite.hpp" // Para AnimatedSprite // --- Clase Tabe --- class Tabe { @@ -26,8 +26,8 @@ class Tabe { ~Tabe() = default; // --- Métodos principales --- - void update(float deltaTime); // Actualiza la lógica (time-based) - void render(); // Dibuja el objeto + void update(float deltaTime); // Actualiza la lógica (time-based) + void render(); // Dibuja el objeto void enable(); // Habilita el objeto void setState(State state); // Establece el estado auto tryToGetBonus() -> bool; // Intenta obtener el bonus diff --git a/source/text.cpp b/source/text.cpp index 5cbbc12..dbf69bc 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -1,4 +1,4 @@ -#include "text.h" +#include "text.hpp" #include // Para Uint8, SDL_GetRenderTarget, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_SetRenderTarget, SDL_FRect, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_TextureAccess @@ -8,15 +8,15 @@ #include // Para runtime_error #include // Para string_view -#include "color.h" // Para Color -#include "resource_helper.h" // Para ResourceHelper -#include "screen.h" // Para Screen -#include "sprite.h" // Para Sprite -#include "texture.h" // Para Texture -#include "utils.h" // Para getFileName, printWithDots +#include "color.hpp" // Para Color +#include "resource_helper.hpp" // Para ResourceHelper +#include "screen.hpp" // Para Screen +#include "sprite.hpp" // Para Sprite +#include "texture.hpp" // Para Texture +#include "utils.hpp" // Para getFileName, printWithDots // Constructor -Text::Text(const std::shared_ptr &texture, const std::string &text_file) { +Text::Text(const std::shared_ptr& texture, const std::string& text_file) { // Carga los offsets desde el fichero auto tf = loadFile(text_file); @@ -37,7 +37,7 @@ Text::Text(const std::shared_ptr &texture, const std::string &text_file } // Constructor -Text::Text(const std::shared_ptr &texture, const std::shared_ptr &text_file) { +Text::Text(const std::shared_ptr& texture, const std::shared_ptr& text_file) { // Inicializa variables desde la estructura box_height_ = text_file->box_height; box_width_ = text_file->box_width; @@ -55,7 +55,7 @@ Text::Text(const std::shared_ptr &texture, const std::shared_ptr &texture, const std::shared_ptr &white_texture, const std::string &text_file) { +Text::Text(const std::shared_ptr& texture, const std::shared_ptr& white_texture, const std::string& text_file) { // Carga los offsets desde el fichero auto tf = loadFile(text_file); @@ -77,7 +77,7 @@ Text::Text(const std::shared_ptr &texture, const std::shared_ptr &texture, const std::shared_ptr &white_texture, const std::shared_ptr &text_file) { +Text::Text(const std::shared_ptr& texture, const std::shared_ptr& white_texture, const std::shared_ptr& text_file) { // Inicializa variables desde la estructura box_height_ = text_file->box_height; box_width_ = text_file->box_width; @@ -96,7 +96,7 @@ Text::Text(const std::shared_ptr &texture, const std::shared_ptr std::shared_ptr { - auto *renderer = Screen::get()->getRenderer(); +auto Text::writeToTexture(const std::string& text, int zoom, int kerning, int length) -> std::shared_ptr { + auto* renderer = Screen::get()->getRenderer(); auto texture = std::make_shared(renderer); auto width = Text::length(text, kerning) * zoom; auto height = box_height_ * zoom; - auto *temp = SDL_GetRenderTarget(renderer); + auto* temp = SDL_GetRenderTarget(renderer); texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); texture->setBlendMode(SDL_BLENDMODE_BLEND); @@ -154,8 +154,8 @@ auto Text::writeToTexture(const std::string &text, int zoom, int kerning, int le } // Escribe el texto con extras en una textura -auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int length) -> std::shared_ptr { - auto *renderer = Screen::get()->getRenderer(); +auto Text::writeDXToTexture(Uint8 flags, const std::string& text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int length) -> std::shared_ptr { + auto* renderer = Screen::get()->getRenderer(); auto texture = std::make_shared(renderer); // Calcula las dimensiones considerando los efectos @@ -181,7 +181,7 @@ auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, C height = base_height + shadow_distance; } - auto *temp = SDL_GetRenderTarget(renderer); + auto* temp = SDL_GetRenderTarget(renderer); texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); texture->setBlendMode(SDL_BLENDMODE_BLEND); @@ -195,16 +195,16 @@ auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, C } // Escribe el texto con colores -void Text::writeColored(int x, int y, const std::string &text, Color color, int kerning, int length) { +void Text::writeColored(int x, int y, const std::string& text, Color color, int kerning, int length) { writeColoredWithSprite(sprite_.get(), x, y, text, color, kerning, length); } // Escribe el texto con colores usando un sprite específico -void Text::writeColoredWithSprite(Sprite *sprite, int x, int y, const std::string &text, Color color, int kerning, int length) { +void Text::writeColoredWithSprite(Sprite* sprite, int x, int y, const std::string& text, Color color, int kerning, int length) { int shift = 0; const std::string_view VISIBLE_TEXT = (length == -1) ? std::string_view(text) : std::string_view(text).substr(0, length); - auto *texture = sprite->getTexture().get(); + auto* texture = sprite->getTexture().get(); // Guarda el alpha original y aplica el nuevo Uint8 original_alpha; @@ -230,9 +230,9 @@ void Text::writeColoredWithSprite(Sprite *sprite, int x, int y, const std::strin } // Escribe stroke con alpha correcto usando textura temporal -void Text::writeStrokeWithAlpha(int x, int y, const std::string &text, int kerning, Color stroke_color, Uint8 shadow_distance, int length) { - auto *renderer = Screen::get()->getRenderer(); - auto *original_target = SDL_GetRenderTarget(renderer); +void Text::writeStrokeWithAlpha(int x, int y, const std::string& text, int kerning, Color stroke_color, Uint8 shadow_distance, int length) { + auto* renderer = Screen::get()->getRenderer(); + auto* original_target = SDL_GetRenderTarget(renderer); // Calcula dimensiones de la textura temporal auto text_width = Text::length(text, kerning); @@ -251,7 +251,7 @@ void Text::writeStrokeWithAlpha(int x, int y, const std::string &text, int kerni SDL_RenderClear(renderer); // Selecciona el sprite apropiado para el stroke - auto *stroke_sprite = white_sprite_ ? white_sprite_.get() : sprite_.get(); + auto* stroke_sprite = white_sprite_ ? white_sprite_.get() : sprite_.get(); // Renderiza stroke sin alpha (sólido) en textura temporal Color solid_color = Color(stroke_color.r, stroke_color.g, stroke_color.b, 255); @@ -272,19 +272,19 @@ void Text::writeStrokeWithAlpha(int x, int y, const std::string &text, int kerni } // Escribe el texto con sombra -void Text::writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance, int kerning, int length) { +void Text::writeShadowed(int x, int y, const std::string& text, Color color, Uint8 shadow_distance, int kerning, int length) { writeDX(Text::SHADOW, x, y, text, kerning, color, shadow_distance, color, length); write(x, y, text, kerning, length); // Dibuja el texto principal encima } // Escribe el texto centrado en un punto x -void Text::writeCentered(int x, int y, const std::string &text, int kerning, int length) { +void Text::writeCentered(int x, int y, const std::string& text, int kerning, int length) { x -= (Text::length(text, kerning) / 2); write(x, y, text, kerning, length); } // Escribe texto con extras -void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int length) { +void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int length) { const auto CENTERED = ((flags & Text::CENTER) == Text::CENTER); const auto SHADOWED = ((flags & Text::SHADOW) == Text::SHADOW); const auto COLORED = ((flags & Text::COLOR) == Text::COLOR); @@ -330,14 +330,14 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni } // Escribe texto a partir de un TextStyle -void Text::writeStyle(int x, int y, const std::string &text, const Style &style, int length) { +void Text::writeStyle(int x, int y, const std::string& text, const Style& style, int length) { writeDX(style.flags, x, y, text, style.kerning, style.text_color, style.shadow_distance, style.shadow_color); } // Obtiene la longitud en pixels de una cadena -auto Text::length(const std::string &text, int kerning) const -> int { +auto Text::length(const std::string& text, int kerning) const -> int { int shift = 0; - for (const auto &ch : text) { + for (const auto& ch : text) { // Convertimos a unsigned char para obtener el valor ASCII correcto (0-255) const auto INDEX = static_cast(ch); @@ -362,11 +362,11 @@ void Text::setFixedWidth(bool value) { } // Llena una estructuta TextFile desde un fichero -auto Text::loadFile(const std::string &file_path) -> std::shared_ptr { +auto Text::loadFile(const std::string& file_path) -> std::shared_ptr { auto tf = std::make_shared(); // Inicializa a cero el vector con las coordenadas - for (auto &i : tf->offset) { + for (auto& i : tf->offset) { i.x = 0; i.y = 0; i.w = 0; @@ -391,7 +391,7 @@ auto Text::loadFile(const std::string &file_path) -> std::shared_ptr file.open(file_path); } - std::istream &input_stream = using_resource_data ? stream : static_cast(file); + std::istream& input_stream = using_resource_data ? stream : static_cast(file); if ((using_resource_data && stream.good()) || (!using_resource_data && file.is_open() && file.good())) { std::string buffer; diff --git a/source/text.h b/source/text.hpp similarity index 75% rename from source/text.h rename to source/text.hpp index e2943ef..c770b32 100644 --- a/source/text.h +++ b/source/text.hpp @@ -6,8 +6,8 @@ #include // Para shared_ptr, unique_ptr #include // Para string -#include "color.h" // Para Color -#include "sprite.h" // Para Sprite +#include "color.hpp" // Para Color +#include "sprite.hpp" // Para Sprite class Texture; @@ -52,40 +52,40 @@ class Text { }; // --- Constructores y destructor --- - Text(const std::shared_ptr &texture, const std::string &text_file); - Text(const std::shared_ptr &texture, const std::shared_ptr &text_file); - Text(const std::shared_ptr &texture, const std::shared_ptr &white_texture, const std::string &text_file); - Text(const std::shared_ptr &texture, const std::shared_ptr &white_texture, const std::shared_ptr &text_file); + Text(const std::shared_ptr& texture, const std::string& text_file); + Text(const std::shared_ptr& texture, const std::shared_ptr& text_file); + Text(const std::shared_ptr& texture, const std::shared_ptr& white_texture, const std::string& text_file); + Text(const std::shared_ptr& texture, const std::shared_ptr& white_texture, const std::shared_ptr& text_file); ~Text() = default; // --- Métodos de escritura en pantalla --- - void write(int x, int y, const std::string &text, int kerning = 1, int length = -1); // Escribe el texto en pantalla - void write2X(int x, int y, const std::string &text, int kerning = 1, int length = -1); // Escribe el texto al doble de tamaño + void write(int x, int y, const std::string& text, int kerning = 1, int length = -1); // Escribe el texto en pantalla + void write2X(int x, int y, const std::string& text, int kerning = 1, int length = -1); // Escribe el texto al doble de tamaño // --- Escritura en textura --- - auto writeToTexture(const std::string &text, int zoom = 1, int kerning = 1, int length = -1) -> std::shared_ptr; // Escribe el texto en una textura - auto writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int length = -1) -> std::shared_ptr; // Escribe el texto con extras en una textura + auto writeToTexture(const std::string& text, int zoom = 1, int kerning = 1, int length = -1) -> std::shared_ptr; // Escribe el texto en una textura + auto writeDXToTexture(Uint8 flags, const std::string& text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int length = -1) -> std::shared_ptr; // Escribe el texto con extras en una textura // --- Métodos de escritura avanzada --- - void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int length = -1); // Escribe el texto con colores - void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int length = -1); // Escribe el texto con sombra - void writeCentered(int x, int y, const std::string &text, int kerning = 1, int length = -1); // Escribe el texto centrado en un punto x - void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int length = -1); // Escribe texto con extras - void writeStyle(int x, int y, const std::string &text, const Style &style, int length = -1); // Escribe texto a partir de un TextStyle + void writeColored(int x, int y, const std::string& text, Color color, int kerning = 1, int length = -1); // Escribe el texto con colores + void writeShadowed(int x, int y, const std::string& text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int length = -1); // Escribe el texto con sombra + void writeCentered(int x, int y, const std::string& text, int kerning = 1, int length = -1); // Escribe el texto centrado en un punto x + void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int length = -1); // Escribe texto con extras + void writeStyle(int x, int y, const std::string& text, const Style& style, int length = -1); // Escribe texto a partir de un TextStyle // --- Utilidades --- - [[nodiscard]] auto length(const std::string &text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena + [[nodiscard]] auto length(const std::string& text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño de caracter actual // --- Configuración --- void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra // --- Métodos estáticos --- - static auto loadFile(const std::string &file_path) -> std::shared_ptr; // Llena una estructura Text::File desde un fichero + static auto loadFile(const std::string& file_path) -> std::shared_ptr; // Llena una estructura Text::File desde un fichero // --- Métodos privados --- - void writeColoredWithSprite(Sprite *sprite, int x, int y, const std::string &text, Color color, int kerning = 1, int length = -1); // Escribe con un sprite específico - void writeStrokeWithAlpha(int x, int y, const std::string &text, int kerning, Color stroke_color, Uint8 shadow_distance, int length = -1); // Escribe stroke con alpha correcto + void writeColoredWithSprite(Sprite* sprite, int x, int y, const std::string& text, Color color, int kerning = 1, int length = -1); // Escribe con un sprite específico + void writeStrokeWithAlpha(int x, int y, const std::string& text, int kerning, Color stroke_color, Uint8 shadow_distance, int length = -1); // Escribe stroke con alpha correcto private: // --- Objetos y punteros --- diff --git a/source/texture.cpp b/source/texture.cpp index 4cab5bc..5be5d7d 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -1,5 +1,5 @@ #define STB_IMAGE_IMPLEMENTATION -#include "texture.h" +#include "texture.hpp" #include // Para SDL_LogError, SDL_LogCategory, Uint8, SDL_... @@ -12,14 +12,14 @@ #include #include // Para vector -#include "color.h" // Para getFileName, Color, printWithDots -#include "external/gif.h" // Para Gif -#include "resource_helper.h" // Para ResourceHelper -#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha -#include "utils.h" +#include "color.hpp" // Para getFileName, Color, printWithDots +#include "external/gif.hpp" // Para Gif +#include "resource_helper.hpp" // Para ResourceHelper +#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha +#include "utils.hpp" // Constructor -Texture::Texture(SDL_Renderer *renderer, std::string path) +Texture::Texture(SDL_Renderer* renderer, std::string path) : renderer_(renderer), path_(std::move(path)) { // Carga el fichero en la textura @@ -56,7 +56,7 @@ Texture::~Texture() { } // Carga una imagen desde un fichero -auto Texture::loadFromFile(const std::string &file_path) -> bool { +auto Texture::loadFromFile(const std::string& file_path) -> bool { if (file_path.empty()) { return false; } @@ -65,7 +65,7 @@ auto Texture::loadFromFile(const std::string &file_path) -> bool { int width; int height; int orig_format; - unsigned char *data = nullptr; + unsigned char* data = nullptr; // Intentar cargar desde ResourceHelper primero auto resource_data = ResourceHelper::loadFile(file_path); @@ -93,10 +93,10 @@ auto Texture::loadFromFile(const std::string &file_path) -> bool { unloadTexture(); // La textura final - SDL_Texture *new_texture = nullptr; + SDL_Texture* new_texture = nullptr; // Carga la imagen desde una ruta específica - auto *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast(data), pitch); + auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast(data), pitch); if (loaded_surface == nullptr) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load image %s", file_path.c_str()); } else { @@ -164,7 +164,7 @@ void Texture::setAlpha(Uint8 alpha) { } // Renderiza la textura en un punto específico -void Texture::render(int x, int y, SDL_FRect *clip, float horizontal_zoom, float vertical_zoom, double angle, SDL_FPoint *center, SDL_FlipMode flip) { +void Texture::render(int x, int y, SDL_FRect* clip, float horizontal_zoom, float vertical_zoom, double angle, SDL_FPoint* center, SDL_FlipMode flip) { // Establece el destino de renderizado en la pantalla SDL_FRect render_quad = {static_cast(x), static_cast(y), static_cast(width_), static_cast(height_)}; @@ -189,7 +189,7 @@ void Texture::render(int x, int y, SDL_FRect *clip, float horizontal_zoom, float } // Establece la textura como objetivo de renderizado -void Texture::setAsRenderTarget(SDL_Renderer *renderer) { +void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); } @@ -209,7 +209,7 @@ auto Texture::reLoad() -> bool { } // Obtiene la textura -auto Texture::getSDLTexture() -> SDL_Texture * { +auto Texture::getSDLTexture() -> SDL_Texture* { return texture_; } @@ -221,7 +221,7 @@ void Texture::unloadSurface() { } // Crea una surface desde un fichero .gif -auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr { +auto Texture::loadSurface(const std::string& file_path) -> std::shared_ptr { // Libera la superficie actual unloadSurface(); @@ -245,7 +245,7 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr(buffer.data()), size)) { + if (!file.read(reinterpret_cast(buffer.data()), size)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al leer el fichero %s", file_path.c_str()); throw std::runtime_error("Error al leer el fichero: " + file_path); } @@ -279,16 +279,16 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr(&pixels), &pitch); + SDL_LockTexture(texture_, nullptr, reinterpret_cast(&pixels), &pitch); for (int i = 0; i < width_ * height_; ++i) { pixels[i] = palettes_[current_palette_][surface_->data[i]]; } @@ -301,7 +301,7 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color) { } // Carga una paleta desde un fichero -auto Texture::loadPaletteFromFile(const std::string &file_path, bool quiet) -> Palette { +auto Texture::loadPaletteFromFile(const std::string& file_path, bool quiet) -> Palette { Palette palette; std::vector buffer; @@ -323,7 +323,7 @@ auto Texture::loadPaletteFromFile(const std::string &file_path, bool quiet) -> P file.seekg(0, std::ios::beg); buffer.resize(size); - if (!file.read(reinterpret_cast(buffer.data()), size)) { + if (!file.read(reinterpret_cast(buffer.data()), size)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo leer completamente el fichero %s", file_path.c_str()); throw std::runtime_error("Error al leer el fichero: " + file_path); } @@ -351,13 +351,13 @@ auto Texture::loadPaletteFromFile(const std::string &file_path, bool quiet) -> P } // Añade una paleta a la lista -void Texture::addPaletteFromGifFile(const std::string &path, bool quiet) { +void Texture::addPaletteFromGifFile(const std::string& path, bool quiet) { palettes_.emplace_back(loadPaletteFromFile(path, quiet)); setPaletteColor(palettes_.size() - 1, 0, 0x00000000); } // Añade una paleta a la lista -void Texture::addPaletteFromPalFile(const std::string &path) { +void Texture::addPaletteFromPalFile(const std::string& path) { palettes_.emplace_back(readPalFile(path, true)); // Usar modo silencioso setPaletteColor(palettes_.size() - 1, 0, 0x00000000); } @@ -371,10 +371,10 @@ void Texture::setPalette(size_t palette) { } // Obtiene el renderizador -auto Texture::getRenderer() -> SDL_Renderer * { return renderer_; } +auto Texture::getRenderer() -> SDL_Renderer* { return renderer_; } // Carga una paleta desde un archivo .pal -auto Texture::readPalFile(const std::string &file_path, bool quiet) -> Palette { +auto Texture::readPalFile(const std::string& file_path, bool quiet) -> Palette { Palette palette{}; palette.fill(0); // Inicializar todo con 0 (transparente por defecto) @@ -398,7 +398,7 @@ auto Texture::readPalFile(const std::string &file_path, bool quiet) -> Palette { } } - std::istream &input_stream = using_resource_data ? stream : static_cast(file); + std::istream& input_stream = using_resource_data ? stream : static_cast(file); std::string line; int line_number = 0; diff --git a/source/texture.h b/source/texture.hpp similarity index 69% rename from source/texture.h rename to source/texture.hpp index ca239ad..159252b 100644 --- a/source/texture.h +++ b/source/texture.hpp @@ -30,17 +30,17 @@ struct Surface { class Texture { public: // --- Constructores y destructor --- - explicit Texture(SDL_Renderer *renderer, std::string path = std::string()); + explicit Texture(SDL_Renderer* renderer, std::string path = std::string()); ~Texture(); // --- Carga y creación --- - auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero + auto loadFromFile(const std::string& path) -> bool; // Carga una imagen desde un fichero auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco auto reLoad() -> bool; // Recarga la textura // --- Renderizado --- - void render(int x, int y, SDL_FRect *clip = nullptr, float horizontal_zoom = 1, float vertical_zoom = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico - void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado + void render(int x, int y, SDL_FRect* clip = nullptr, float horizontal_zoom = 1, float vertical_zoom = 1, double angle = 0.0, SDL_FPoint* center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico + void setAsRenderTarget(SDL_Renderer* renderer); // Establece la textura como objetivo de renderizado // --- Modificadores de color y blending --- void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación @@ -49,21 +49,21 @@ class Texture { void setAlpha(Uint8 alpha); // Establece el alpha para la modulación // --- Paletas --- - void addPaletteFromGifFile(const std::string &path, bool quiet = false); // Añade una paleta a la lista - void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista - void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta - void setPalette(size_t palette); // Cambia la paleta de la textura + void addPaletteFromGifFile(const std::string& path, bool quiet = false); // Añade una paleta a la lista + void addPaletteFromPalFile(const std::string& path); // Añade una paleta a la lista + void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta + void setPalette(size_t palette); // Cambia la paleta de la textura // --- Getters --- [[nodiscard]] auto getWidth() const -> int; // Obtiene el ancho de la imagen [[nodiscard]] auto getHeight() const -> int; // Obtiene el alto de la imagen - auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL - auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador + auto getSDLTexture() -> SDL_Texture*; // Obtiene la textura SDL + auto getRenderer() -> SDL_Renderer*; // Obtiene el renderizador private: // --- Objetos y punteros --- - SDL_Renderer *renderer_; // Renderizador donde dibujar la textura - SDL_Texture *texture_ = nullptr; // La textura + SDL_Renderer* renderer_; // Renderizador donde dibujar la textura + SDL_Texture* texture_ = nullptr; // La textura std::shared_ptr surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta // --- Variables --- @@ -74,10 +74,10 @@ class Texture { int current_palette_ = 0; // Índice de la paleta en uso // --- Métodos internos --- - auto loadSurface(const std::string &file_path) -> std::shared_ptr; // Crea una surface desde un fichero .gif - void flipSurface(); // Vuelca la surface en la textura - static auto loadPaletteFromFile(const std::string &file_path, bool quiet = false) -> Palette; // Carga una paleta desde un fichero - void unloadTexture(); // Libera la memoria de la textura - void unloadSurface(); // Libera la surface actual - static auto readPalFile(const std::string &file_path, bool quiet = false) -> Palette; // Carga una paleta desde un archivo .pal + auto loadSurface(const std::string& file_path) -> std::shared_ptr; // Crea una surface desde un fichero .gif + void flipSurface(); // Vuelca la surface en la textura + static auto loadPaletteFromFile(const std::string& file_path, bool quiet = false) -> Palette; // Carga una paleta desde un fichero + void unloadTexture(); // Libera la memoria de la textura + void unloadSurface(); // Libera la surface actual + static auto readPalFile(const std::string& file_path, bool quiet = false) -> Palette; // Carga una paleta desde un archivo .pal }; \ No newline at end of file diff --git a/source/tiled_bg.cpp b/source/tiled_bg.cpp index 2830ee1..051e795 100644 --- a/source/tiled_bg.cpp +++ b/source/tiled_bg.cpp @@ -1,4 +1,4 @@ -#include "tiled_bg.h" +#include "tiled_bg.hpp" #include // Para SDL_SetRenderTarget, SDL_CreateTexture, SDL_DestroyTexture, SDL_FRect, SDL_GetRenderTarget, SDL_RenderTexture, SDL_PixelFormat, SDL_TextureAccess @@ -8,9 +8,9 @@ #include // Para allocator, unique_ptr, make_unique #include // Para pi -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "sprite.h" // Para Sprite +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "sprite.hpp" // Para Sprite // Constructor TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode) @@ -39,7 +39,6 @@ TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode) window_ = {.x = 0, .y = 0, .w = pos_.w, .h = pos_.h}; break; } - } // Destructor @@ -53,7 +52,7 @@ void TiledBG::fillTexture() { auto tile = std::make_unique(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH, TILE_HEIGHT}); // Prepara para dibujar sobre la textura - auto *temp = SDL_GetRenderTarget(renderer_); + auto* temp = SDL_GetRenderTarget(renderer_); SDL_SetRenderTarget(renderer_, canvas_); // Rellena la textura con el tile diff --git a/source/tiled_bg.h b/source/tiled_bg.hpp similarity index 73% rename from source/tiled_bg.h rename to source/tiled_bg.hpp index c5a1b42..39c250c 100644 --- a/source/tiled_bg.h +++ b/source/tiled_bg.hpp @@ -2,8 +2,7 @@ #include // Para SDL_FRect, SDL_SetTextureColorMod, SDL_Renderer, SDL_Texture - -#include "color.h" // Para Color +#include "color.hpp" // Para Color // --- Enums --- enum class TiledBGMode : int { // Modos de funcionamiento para el tileado de fondo @@ -33,7 +32,7 @@ class TiledBG { void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura // --- Getters --- - [[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0F; } // Indica si está parado + [[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0F; } // Indica si está parado [[nodiscard]] auto isChangingSpeed() const -> bool { return changing_speed_; } // Indica si está cambiando velocidad gradualmente private: @@ -45,23 +44,23 @@ class TiledBG { static constexpr float MIN_SPEED = 0.1f; // Velocidad mínima // --- Objetos y punteros --- - SDL_Renderer *renderer_; // El renderizador de la ventana - SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles + SDL_Renderer* renderer_; // El renderizador de la ventana + SDL_Texture* canvas_; // Textura donde dibujar el fondo formado por tiles // --- Variables de estado --- - SDL_FRect pos_; // Posición y tamaño del mosaico - SDL_FRect window_; // Ventana visible para la textura de fondo del título - TiledBGMode mode_; // Tipo de movimiento del mosaico - float desp_ = 0.0F; // Desplazamiento aplicado - float speed_ = 1.0F; // Incremento que se añade al desplazamiento a cada bucle - bool stopping_ = false; // Indica si se está deteniendo + SDL_FRect pos_; // Posición y tamaño del mosaico + SDL_FRect window_; // Ventana visible para la textura de fondo del título + TiledBGMode mode_; // Tipo de movimiento del mosaico + float desp_ = 0.0F; // Desplazamiento aplicado + float speed_ = 1.0F; // Incremento que se añade al desplazamiento a cada bucle + bool stopping_ = false; // Indica si se está deteniendo // --- Variables para cambio gradual de velocidad --- - bool changing_speed_ = false; // Indica si está cambiando velocidad gradualmente - float initial_speed_ = 0.0F; // Velocidad inicial del cambio - float target_speed_ = 0.0F; // Velocidad objetivo del cambio - float change_duration_s_ = 0.0F; // Duración total del cambio en segundos - float change_timer_s_ = 0.0F; // Tiempo transcurrido del cambio + bool changing_speed_ = false; // Indica si está cambiando velocidad gradualmente + float initial_speed_ = 0.0F; // Velocidad inicial del cambio + float target_speed_ = 0.0F; // Velocidad objetivo del cambio + float change_duration_s_ = 0.0F; // Duración total del cambio en segundos + float change_timer_s_ = 0.0F; // Tiempo transcurrido del cambio // --- Métodos internos --- void fillTexture(); // Rellena la textura con el contenido diff --git a/source/ui/logger.h b/source/ui/logger.h deleted file mode 100644 index 21e3673..0000000 --- a/source/ui/logger.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include -#include - -namespace Logger { - - // Colores ANSI - inline constexpr const char* RESET = "\033[0m"; - inline constexpr const char* RED = "\033[31m"; - inline constexpr const char* GREEN = "\033[32m"; - inline constexpr const char* YELLOW = "\033[33m"; - inline constexpr const char* BLUE = "\033[34m"; - inline constexpr const char* MAGENTA = "\033[35m"; - inline constexpr const char* CYAN = "\033[36m"; - inline constexpr const char* WHITE = "\033[37m"; - - // Ancho total global para alineación - inline constexpr size_t TOTAL_WIDTH = 52; - - // Sección - inline void section(const std::string& title, const std::string& color = CYAN) { - std::cout << "\n" << color - << "========================================\n" - << " " << title << "\n" - << "========================================" - << RESET << "\n"; - } - - // Info - inline void info(const std::string& msg, const std::string& color = WHITE) { - std::cout << " " << color << msg << RESET << "\n"; - } - - // Dots genérico - inline void dots(const std::string& prefix, - const std::string& middle, - const std::string& suffix, - const std::string& suffixColor = GREEN) - { - size_t field_width = TOTAL_WIDTH > (prefix.size() + suffix.size()) - ? TOTAL_WIDTH - prefix.size() - suffix.size() - : 0; - - std::string field_text; - if (middle.size() < field_width) { - field_text = middle + std::string(field_width - middle.size(), '.'); - } else { - field_text = middle.substr(0, field_width); - } - - std::cout << prefix << field_text - << suffixColor << suffix << RESET - << "\n"; - } - - // Status con true/false, usando dots y sufijos fijos - inline void status(const std::string& name, bool ok) { - // Ambos sufijos tienen 9 caracteres → alineación perfecta - constexpr const char* OK_LABEL = "[ OK ]"; - constexpr const char* ERROR_LABEL = "[ ERROR ]"; - - if (ok) { - dots(" ", name, OK_LABEL, GREEN); - } else { - dots(" ", name, ERROR_LABEL, RED); - } - } - -} // namespace Logger diff --git a/source/ui/logger.hpp b/source/ui/logger.hpp new file mode 100644 index 0000000..0fd0f24 --- /dev/null +++ b/source/ui/logger.hpp @@ -0,0 +1,70 @@ +#pragma once + +#include +#include + +namespace Logger { + +// Colores ANSI +inline constexpr const char* RESET = "\033[0m"; +inline constexpr const char* RED = "\033[31m"; +inline constexpr const char* GREEN = "\033[32m"; +inline constexpr const char* YELLOW = "\033[33m"; +inline constexpr const char* BLUE = "\033[34m"; +inline constexpr const char* MAGENTA = "\033[35m"; +inline constexpr const char* CYAN = "\033[36m"; +inline constexpr const char* WHITE = "\033[37m"; + +// Ancho total global para alineación +inline constexpr size_t TOTAL_WIDTH = 52; + +// Sección +inline void section(const std::string& title, const std::string& color = CYAN) { + std::cout << "\n" + << color + << "========================================\n" + << " " << title << "\n" + << "========================================" + << RESET << "\n"; +} + +// Info +inline void info(const std::string& msg, const std::string& color = WHITE) { + std::cout << " " << color << msg << RESET << "\n"; +} + +// Dots genérico +inline void dots(const std::string& prefix, + const std::string& middle, + const std::string& suffix, + const std::string& suffixColor = GREEN) { + size_t field_width = TOTAL_WIDTH > (prefix.size() + suffix.size()) + ? TOTAL_WIDTH - prefix.size() - suffix.size() + : 0; + + std::string field_text; + if (middle.size() < field_width) { + field_text = middle + std::string(field_width - middle.size(), '.'); + } else { + field_text = middle.substr(0, field_width); + } + + std::cout << prefix << field_text + << suffixColor << suffix << RESET + << "\n"; +} + +// Status con true/false, usando dots y sufijos fijos +inline void status(const std::string& name, bool ok) { + // Ambos sufijos tienen 9 caracteres → alineación perfecta + constexpr const char* OK_LABEL = "[ OK ]"; + constexpr const char* ERROR_LABEL = "[ ERROR ]"; + + if (ok) { + dots(" ", name, OK_LABEL, GREEN); + } else { + dots(" ", name, ERROR_LABEL, RED); + } +} + +} // namespace Logger diff --git a/source/ui/menu_option.cpp b/source/ui/menu_option.cpp index 83aed10..a7875b3 100644 --- a/source/ui/menu_option.cpp +++ b/source/ui/menu_option.cpp @@ -1,10 +1,10 @@ -#include "menu_option.h" +#include "menu_option.hpp" #include // Para find #include // Para distance #include // Para allocator -#include "text.h" // Para Text +#include "text.hpp" // Para Text auto ActionListOption::getValueAsString() const -> std::string { if (value_getter_) { diff --git a/source/ui/menu_option.h b/source/ui/menu_option.hpp similarity index 87% rename from source/ui/menu_option.h rename to source/ui/menu_option.hpp index b768d3d..e361109 100644 --- a/source/ui/menu_option.h +++ b/source/ui/menu_option.hpp @@ -7,9 +7,9 @@ #include // Para move #include // Para vector -#include "lang.h" // Para getText -#include "text.h" // Para Text -#include "ui/service_menu.h" // Para ServiceMenu +#include "lang.hpp" // Para getText +#include "text.hpp" // Para Text +#include "ui/service_menu.hpp" // Para ServiceMenu // --- Clase MenuOption: interfaz base para todas las opciones del menú --- class MenuOption { @@ -29,7 +29,7 @@ class MenuOption { virtual ~MenuOption() = default; // --- Getters --- - [[nodiscard]] auto getCaption() const -> const std::string & { return caption_; } + [[nodiscard]] auto getCaption() const -> const std::string& { return caption_; } [[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; } [[nodiscard]] auto isHidden() const -> bool { return hidden_; } void setHidden(bool hidden) { hidden_ = hidden; } @@ -40,7 +40,7 @@ class MenuOption { [[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; } virtual void executeAction() {} - virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; } // Método virtual para que cada opción calcule el ancho de su valor más largo + virtual auto getMaxValueWidth(Text* text_renderer) const -> int { return 0; } // Método virtual para que cada opción calcule el ancho de su valor más largo protected: // --- Variables --- @@ -53,7 +53,7 @@ class MenuOption { class BoolOption : public MenuOption { public: - BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var) + BoolOption(const std::string& cap, ServiceMenu::SettingsGroup grp, bool* var) : MenuOption(cap, grp), linked_variable_(var) {} @@ -64,19 +64,19 @@ class BoolOption : public MenuOption { void adjustValue(bool /*adjust_up*/) override { *linked_variable_ = !*linked_variable_; } - auto getMaxValueWidth(Text *text_renderer) const -> int override { + auto getMaxValueWidth(Text* text_renderer) const -> int override { return std::max( text_renderer->length(Lang::getText("[SERVICE_MENU] ON"), -2), text_renderer->length(Lang::getText("[SERVICE_MENU] OFF"), -2)); } private: - bool *linked_variable_; + bool* linked_variable_; }; class IntOption : public MenuOption { public: - IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step) + IntOption(const std::string& cap, ServiceMenu::SettingsGroup grp, int* var, int min, int max, int step) : MenuOption(cap, grp), linked_variable_(var), min_value_(min), @@ -89,7 +89,7 @@ class IntOption : public MenuOption { int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_); *linked_variable_ = std::clamp(new_value, min_value_, max_value_); } - auto getMaxValueWidth(Text *text_renderer) const -> int override { + auto getMaxValueWidth(Text* text_renderer) const -> int override { int max_width = 0; // Iterar por todos los valores posibles en el rango @@ -102,13 +102,13 @@ class IntOption : public MenuOption { } private: - int *linked_variable_; + int* linked_variable_; int min_value_, max_value_, step_value_; }; class ListOption : public MenuOption { public: - ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector values, std::function current_value_getter, std::function new_value_setter) + ListOption(const std::string& cap, ServiceMenu::SettingsGroup grp, std::vector values, std::function current_value_getter, std::function new_value_setter) : MenuOption(cap, grp), value_list_(std::move(values)), getter_(std::move(current_value_getter)), @@ -139,9 +139,9 @@ class ListOption : public MenuOption { : (list_index_ + size - 1) % size; setter_(value_list_[list_index_]); } - auto getMaxValueWidth(Text *text_renderer) const -> int override { + auto getMaxValueWidth(Text* text_renderer) const -> int override { int max_w = 0; - for (const auto &val : value_list_) { + for (const auto& val : value_list_) { max_w = std::max(max_w, text_renderer->length(val, -2)); } return max_w; @@ -150,13 +150,13 @@ class ListOption : public MenuOption { private: std::vector value_list_; std::function getter_; - std::function setter_; + std::function setter_; size_t list_index_{0}; }; class FolderOption : public MenuOption { public: - FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target) + FolderOption(const std::string& cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target) : MenuOption(cap, grp), target_group_(target) {} @@ -169,7 +169,7 @@ class FolderOption : public MenuOption { class ActionOption : public MenuOption { public: - ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function action, bool hidden = false) + ActionOption(const std::string& cap, ServiceMenu::SettingsGroup grp, std::function action, bool hidden = false) : MenuOption(cap, grp, hidden), action_(std::move(action)) {} @@ -188,10 +188,10 @@ class ActionOption : public MenuOption { class ActionListOption : public MenuOption { public: using ValueGetter = std::function; - using ValueSetter = std::function; + using ValueSetter = std::function; using ActionExecutor = std::function; - ActionListOption(const std::string &caption, ServiceMenu::SettingsGroup group, std::vector options, ValueGetter getter, ValueSetter setter, ActionExecutor action_executor, bool hidden = false) + ActionListOption(const std::string& caption, ServiceMenu::SettingsGroup group, std::vector options, ValueGetter getter, ValueSetter setter, ActionExecutor action_executor, bool hidden = false) : MenuOption(caption, group, hidden), options_(std::move(options)), value_getter_(std::move(getter)), @@ -202,7 +202,7 @@ class ActionListOption : public MenuOption { [[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::BOTH; } [[nodiscard]] auto getValueAsString() const -> std::string override; - [[nodiscard]] auto getMaxValueWidth(Text *text) const -> int override; + [[nodiscard]] auto getMaxValueWidth(Text* text) const -> int override; void adjustValue(bool up) override; void executeAction() override; void sync(); // Sincroniza con el valor actual diff --git a/source/ui/menu_renderer.cpp b/source/ui/menu_renderer.cpp index acced61..c4d9c9c 100644 --- a/source/ui/menu_renderer.cpp +++ b/source/ui/menu_renderer.cpp @@ -1,14 +1,14 @@ -#include "menu_renderer.h" +#include "menu_renderer.hpp" #include #include -#include "color.h" -#include "menu_option.h" -#include "param.h" -#include "screen.h" -#include "text.h" -#include "utils.h" +#include "color.hpp" +#include "menu_option.hpp" +#include "param.hpp" +#include "screen.hpp" +#include "text.hpp" +#include "utils.hpp" // --- Implementación de las estructuras de animación --- @@ -43,14 +43,14 @@ void MenuRenderer::ShowHideAnimation::stop() { elapsed = 0.0F; } -MenuRenderer::MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr element_text, std::shared_ptr title_text) +MenuRenderer::MenuRenderer(const ServiceMenu* menu_state, std::shared_ptr element_text, std::shared_ptr title_text) : element_text_(std::move(element_text)), title_text_(std::move(title_text)) { initializeMaxSizes(); setPosition(param.game.game_area.center_x, param.game.game_area.center_y, PositionMode::CENTERED); } -void MenuRenderer::render(const ServiceMenu *menu_state) { +void MenuRenderer::render(const ServiceMenu* menu_state) { if (!visible_) { return; } @@ -85,11 +85,11 @@ void MenuRenderer::render(const ServiceMenu *menu_state) { // Dibuja las opciones y = options_y_; - const auto &option_pairs = menu_state->getOptionPairs(); + const auto& option_pairs = menu_state->getOptionPairs(); for (size_t i = 0; i < option_pairs.size(); ++i) { const bool IS_SELECTED = (i == menu_state->getSelectedIndex()); - const Color ¤t_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color; + const Color& current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color; if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) { const int AVAILABLE_WIDTH = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2) - element_text_->length(option_pairs.at(i).first, -2) - ServiceMenu::MIN_GAP_OPTION_VALUE; @@ -107,7 +107,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) { } } -void MenuRenderer::update(const ServiceMenu *menu_state, float delta_time) { +void MenuRenderer::update(const ServiceMenu* menu_state, float delta_time) { updateAnimations(delta_time); if (visible_) { @@ -118,7 +118,7 @@ void MenuRenderer::update(const ServiceMenu *menu_state, float delta_time) { // --- Nuevos métodos de control --- -void MenuRenderer::show(const ServiceMenu *menu_state) { +void MenuRenderer::show(const ServiceMenu* menu_state) { if (visible_) { return; } @@ -162,13 +162,13 @@ void MenuRenderer::setPosition(float x, float y, PositionMode mode) { // --- Métodos de layout --- -void MenuRenderer::onLayoutChanged(const ServiceMenu *menu_state) { +void MenuRenderer::onLayoutChanged(const ServiceMenu* menu_state) { precalculateMenuWidths(menu_state->getAllOptions(), menu_state); setAnchors(menu_state); resize(menu_state); } -void MenuRenderer::setLayout(const ServiceMenu *menu_state) { +void MenuRenderer::setLayout(const ServiceMenu* menu_state) { precalculateMenuWidths(menu_state->getAllOptions(), menu_state); setAnchors(menu_state); setSize(menu_state); @@ -179,7 +179,7 @@ void MenuRenderer::initializeMaxSizes() { max_menu_height_ = static_cast(param.game.game_area.rect.h * 0.9F); } -void MenuRenderer::setAnchors(const ServiceMenu *menu_state) { +void MenuRenderer::setAnchors(const ServiceMenu* menu_state) { size_t max_entries = 0; for (int i = 0; i < 5; ++i) { max_entries = std::max(max_entries, menu_state->countOptionsInGroup(static_cast(i))); @@ -197,9 +197,9 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) { height_ = upper_height_ + lower_height_; } -auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect { +auto MenuRenderer::calculateNewRect(const ServiceMenu* menu_state) -> SDL_FRect { width_ = std::min(static_cast(getMenuWidthForGroup(menu_state->getCurrentGroup())), max_menu_width_); - const auto &display_options = menu_state->getDisplayOptions(); + 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_); @@ -209,7 +209,7 @@ auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect return new_rect; } -void MenuRenderer::resize(const ServiceMenu *menu_state) { +void MenuRenderer::resize(const ServiceMenu* menu_state) { SDL_FRect new_rect = calculateNewRect(menu_state); if (rect_.w != new_rect.w || rect_.h != new_rect.h) { @@ -222,7 +222,7 @@ void MenuRenderer::resize(const ServiceMenu *menu_state) { options_y_ = rect_.y + upper_height_ + lower_padding_; } -void MenuRenderer::setSize(const ServiceMenu *menu_state) { +void MenuRenderer::setSize(const ServiceMenu* menu_state) { SDL_FRect new_rect = calculateNewRect(menu_state); rect_.w = new_rect.w; rect_.h = new_rect.h; @@ -310,15 +310,15 @@ void MenuRenderer::updatePosition() { // Resto de métodos (sin cambios significativos) -void MenuRenderer::precalculateMenuWidths(const std::vector> &all_options, const ServiceMenu *menu_state) { - for (int &w : group_menu_widths_) { +void MenuRenderer::precalculateMenuWidths(const std::vector>& all_options, const ServiceMenu* menu_state) { + for (int& w : group_menu_widths_) { w = ServiceMenu::MIN_WIDTH; } for (int group = 0; group < 5; ++group) { auto sg = static_cast(group); int max_option_width = 0; int max_value_width = 0; - for (const auto &option : all_options) { + for (const auto& option : all_options) { if (option->getGroup() != sg) { continue; } @@ -361,7 +361,7 @@ auto MenuRenderer::setRect(SDL_FRect rect) -> SDL_FRect { border_rect_ = {.x = rect.x - 1, .y = rect.y + 1, .w = rect.w + 2, .h = rect.h - 2}; return rect; } -auto MenuRenderer::getTruncatedValueWidth(const std::string &value, int available_width) const -> int { +auto MenuRenderer::getTruncatedValueWidth(const std::string& value, int available_width) const -> int { int value_width = element_text_->length(value, -2); if (value_width <= available_width) { return value_width; @@ -385,7 +385,7 @@ auto MenuRenderer::getTruncatedValueWidth(const std::string &value, int availabl return element_text_->length(truncated, -2); } -auto MenuRenderer::getTruncatedValue(const std::string &value, int available_width) const -> std::string { +auto MenuRenderer::getTruncatedValue(const std::string& value, int available_width) const -> std::string { int value_width = element_text_->length(value, -2); if (value_width <= available_width) { return value; diff --git a/source/ui/menu_renderer.h b/source/ui/menu_renderer.hpp similarity index 82% rename from source/ui/menu_renderer.h rename to source/ui/menu_renderer.hpp index 639b849..0637932 100644 --- a/source/ui/menu_renderer.h +++ b/source/ui/menu_renderer.hpp @@ -8,8 +8,8 @@ #include #include -#include "color.h" -#include "ui/service_menu.h" +#include "color.hpp" +#include "ui/service_menu.hpp" class MenuOption; class Text; @@ -22,14 +22,14 @@ class MenuRenderer { FIXED // La esquina superior izquierda coincide con el punto }; - MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr element_text, std::shared_ptr title_text); + MenuRenderer(const ServiceMenu* menu_state, std::shared_ptr element_text, std::shared_ptr title_text); // --- Métodos principales de la vista --- - void render(const ServiceMenu *menu_state); - void update(const ServiceMenu *menu_state, float delta_time); + void render(const ServiceMenu* menu_state); + void update(const ServiceMenu* menu_state, float delta_time); // --- Nuevos: Métodos de control de visibilidad y animación --- - void show(const ServiceMenu *menu_state); + void show(const ServiceMenu* menu_state); void hide(); [[nodiscard]] auto isVisible() const -> bool { return visible_; } [[nodiscard]] auto isFullyVisible() const -> bool { return visible_ && !show_hide_animation_.active && !resize_animation_.active; } @@ -39,11 +39,11 @@ class MenuRenderer { 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); + void onLayoutChanged(const ServiceMenu* menu_state); + void setLayout(const ServiceMenu* menu_state); // Getters - [[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; } + [[nodiscard]] auto getRect() const -> const SDL_FRect& { return rect_; } private: // --- Referencias a los renderizadores de texto --- @@ -107,23 +107,23 @@ class MenuRenderer { // --- Métodos privados de la vista --- void initializeMaxSizes(); - void setAnchors(const ServiceMenu *menu_state); - auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect; - void resize(const ServiceMenu *menu_state); - void setSize(const ServiceMenu *menu_state); + void setAnchors(const ServiceMenu* menu_state); + 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); void updatePosition(); - void precalculateMenuWidths(const std::vector> &all_options, const ServiceMenu *menu_state); + void precalculateMenuWidths(const std::vector>& all_options, const ServiceMenu* menu_state); [[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int; [[nodiscard]] auto getAnimatedSelectedColor() const -> Color; void updateColorCounter(); auto setRect(SDL_FRect rect) -> SDL_FRect; - [[nodiscard]] auto getTruncatedValueWidth(const std::string &value, int available_width) const -> int; - [[nodiscard]] auto getTruncatedValue(const std::string &value, int available_width) const -> std::string; + [[nodiscard]] auto getTruncatedValueWidth(const std::string& value, int available_width) const -> int; + [[nodiscard]] auto getTruncatedValue(const std::string& value, int available_width) const -> std::string; [[nodiscard]] static auto easeOut(float t) -> float; [[nodiscard]] auto shouldShowContent() const -> bool; }; \ No newline at end of file diff --git a/source/ui/notifier.cpp b/source/ui/notifier.cpp index 9164018..362ccae 100644 --- a/source/ui/notifier.cpp +++ b/source/ui/notifier.cpp @@ -1,4 +1,4 @@ -#include "notifier.h" +#include "notifier.hpp" #include // Para SDL_RenderFillRect, SDL_FRect, SDL_RenderClear @@ -7,12 +7,12 @@ #include #include // Para vector -#include "audio.h" // Para Audio -#include "param.h" // Para Param, param, ParamNotification, ParamGame -#include "screen.h" // Para Screen -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text -#include "texture.h" // Para Texture +#include "audio.hpp" // Para Audio +#include "param.hpp" // Para Param, param, ParamNotification, ParamGame +#include "screen.hpp" // Para Screen +#include "sprite.hpp" // Para Sprite +#include "text.hpp" // Para Text +#include "texture.hpp" // Para Texture // Singleton Notifier* Notifier::instance = nullptr; @@ -142,7 +142,7 @@ void Notifier::transitionToStayState(int index) { auto& notification = notifications_[index]; notification.state = State::STAY; notification.texture->setAlpha(255); - notification.rect.y = static_cast(notification.y); // Asegurar posición exacta + notification.rect.y = static_cast(notification.y); // Asegurar posición exacta notification.timer = 0.0f; } diff --git a/source/ui/notifier.h b/source/ui/notifier.hpp similarity index 68% rename from source/ui/notifier.h rename to source/ui/notifier.hpp index f424f2c..00e0eb9 100644 --- a/source/ui/notifier.h +++ b/source/ui/notifier.hpp @@ -6,8 +6,8 @@ #include // Para basic_string, string #include // Para vector -#include "color.h" // Para stringInVector, Color -#include "utils.h" +#include "color.hpp" // Para stringInVector, Color +#include "utils.hpp" class Sprite; class Text; @@ -26,24 +26,24 @@ class Notifier { }; // --- Métodos de singleton --- - static void init(const std::string &icon_file, std::shared_ptr text); // Inicializa el singleton + static void init(const std::string& icon_file, std::shared_ptr text); // Inicializa el singleton static void destroy(); // Libera el singleton - static auto get() -> Notifier *; // Obtiene la instancia + static auto get() -> Notifier*; // Obtiene la instancia // --- Métodos principales --- - void render(); // Dibuja las notificaciones por pantalla + void render(); // Dibuja las notificaciones por pantalla void update(float delta_time); // Actualiza el estado de las notificaciones // --- Gestión de notificaciones --- - void show(std::vector texts, int icon = -1, const std::string &code = std::string()); // Muestra una notificación de texto por pantalla + void show(std::vector texts, int icon = -1, const std::string& code = std::string()); // Muestra una notificación de texto por pantalla [[nodiscard]] auto isActive() const -> bool { return !notifications_.empty(); } // Indica si hay notificaciones activas auto getCodes() -> std::vector; // Obtiene los códigos de las notificaciones activas - auto checkCode(const std::string &code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto + auto checkCode(const std::string& code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto private: // --- Constantes de tiempo (en segundos) --- - static constexpr float STAY_DURATION_S = 2.5f; // Tiempo que se ve la notificación (150 frames @ 60fps) - static constexpr float ANIMATION_SPEED_PX_PER_S = 60.0f; // Velocidad de animación (1 pixel/frame @ 60fps) + static constexpr float STAY_DURATION_S = 2.5f; // Tiempo que se ve la notificación (150 frames @ 60fps) + static constexpr float ANIMATION_SPEED_PX_PER_S = 60.0f; // Velocidad de animación (1 pixel/frame @ 60fps) // --- Enums privados --- enum class State { @@ -79,7 +79,7 @@ class Notifier { }; // --- Objetos y punteros --- - SDL_Renderer *renderer_; // El renderizador de la ventana + SDL_Renderer* renderer_; // El renderizador de la ventana std::shared_ptr icon_texture_; // Textura para los iconos de las notificaciones std::shared_ptr text_; // Objeto para dibujar texto @@ -87,26 +87,26 @@ class Notifier { std::vector notifications_; // Lista de notificaciones activas Color bg_color_; // Color de fondo de las notificaciones // Nota: wait_time_ eliminado, ahora se usa STAY_DURATION_S - bool stack_; // Indica si las notificaciones se apilan - bool has_icons_; // Indica si el notificador tiene textura para iconos + bool stack_; // Indica si las notificaciones se apilan + bool has_icons_; // Indica si el notificador tiene textura para iconos // --- Métodos internos --- - void clearFinishedNotifications(); // Elimina las notificaciones cuyo estado es FINISHED - void clearAllNotifications(); // Elimina todas las notificaciones activas, sin importar el estado - [[nodiscard]] auto shouldProcessNotification(int index) const -> bool; // Determina si una notificación debe ser procesada (según su estado y posición) - void processNotification(int index, float delta_time); // Procesa una notificación en la posición dada: actualiza su estado y comportamiento visual - static void playNotificationSoundIfNeeded(const Notification ¬ification); // Reproduce sonido asociado si es necesario (dependiendo del estado o contenido) - void updateNotificationState(int index, float delta_time); // Actualiza el estado interno de una notificación (ej. de RISING a STAY) - void handleRisingState(int index, float delta_time); // Lógica de animación para el estado RISING (apareciendo) - void handleStayState(int index); // Lógica para mantener una notificación visible en el estado STAY - void handleVanishingState(int index, float delta_time); // Lógica de animación para el estado VANISHING (desapareciendo) - static void moveNotificationVertically(Notification ¬ification, float pixels_to_move); // Mueve verticalmente una notificación con la cantidad de pixels especificada - void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final + void clearFinishedNotifications(); // Elimina las notificaciones cuyo estado es FINISHED + void clearAllNotifications(); // Elimina todas las notificaciones activas, sin importar el estado + [[nodiscard]] auto shouldProcessNotification(int index) const -> bool; // Determina si una notificación debe ser procesada (según su estado y posición) + void processNotification(int index, float delta_time); // Procesa una notificación en la posición dada: actualiza su estado y comportamiento visual + static void playNotificationSoundIfNeeded(const Notification& notification); // Reproduce sonido asociado si es necesario (dependiendo del estado o contenido) + void updateNotificationState(int index, float delta_time); // Actualiza el estado interno de una notificación (ej. de RISING a STAY) + void handleRisingState(int index, float delta_time); // Lógica de animación para el estado RISING (apareciendo) + void handleStayState(int index); // Lógica para mantener una notificación visible en el estado STAY + void handleVanishingState(int index, float delta_time); // Lógica de animación para el estado VANISHING (desapareciendo) + static void moveNotificationVertically(Notification& notification, float pixels_to_move); // Mueve verticalmente una notificación con la cantidad de pixels especificada + void transitionToStayState(int index); // Cambia el estado de una notificación de RISING a STAY cuando ha alcanzado su posición final // --- Constructores y destructor privados (singleton) --- - Notifier(const std::string &icon_file, std::shared_ptr text); // Constructor privado + Notifier(const std::string& icon_file, std::shared_ptr text); // Constructor privado ~Notifier() = default; // Destructor privado // --- Instancia singleton --- - static Notifier *instance; // Instancia única de Notifier + static Notifier* instance; // Instancia única de Notifier }; \ No newline at end of file diff --git a/source/ui/service_menu.cpp b/source/ui/service_menu.cpp index fe02674..05cc4f2 100644 --- a/source/ui/service_menu.cpp +++ b/source/ui/service_menu.cpp @@ -1,29 +1,29 @@ -#include "ui/service_menu.h" +#include "ui/service_menu.hpp" #include -#include "audio.h" // Para Audio -#include "define_buttons.h" // Para DefineButtons -#include "difficulty.h" // Para getCodeFromName, getNameFromCode -#include "input.h" // Para Input -#include "input_types.h" // Para InputAction -#include "lang.h" // Para getText, getCodeFromName, getNameFromCode -#include "menu_option.h" // Para MenuOption, ActionOption, BoolOption, ListOption, FolderOption, IntOption, ActionListOption -#include "menu_renderer.h" // Para MenuRenderer -#include "options.h" // Para GamepadManager, gamepad_manager, PendingChanges, Video, pending_changes, video, Audio, Gamepad, Settings, audio, checkPendingChanges, settings, Window, getPlayerWhoUsesKeyboard, playerIdToString, stringToPlayerId, window, Keyboard, Music, Sound, keyboard -#include "param.h" // Para Param, param, ParamGame, ParamServiceMenu -#include "player.h" // Para Player -#include "resource.h" // Para Resource -#include "screen.h" // Para Screen -#include "section.hpp" // Para Name, name, Options, options -#include "ui/ui_message.h" // Para UIMessage -#include "utils.h" // Para Zone +#include "audio.hpp" // Para Audio +#include "define_buttons.hpp" // Para DefineButtons +#include "difficulty.hpp" // Para getCodeFromName, getNameFromCode +#include "input.hpp" // Para Input +#include "input_types.hpp" // Para InputAction +#include "lang.hpp" // Para getText, getCodeFromName, getNameFromCode +#include "menu_option.hpp" // Para MenuOption, ActionOption, BoolOption, ListOption, FolderOption, IntOption, ActionListOption +#include "menu_renderer.hpp" // Para MenuRenderer +#include "options.hpp" // Para GamepadManager, gamepad_manager, PendingChanges, Video, pending_changes, video, Audio, Gamepad, Settings, audio, checkPendingChanges, settings, Window, getPlayerWhoUsesKeyboard, playerIdToString, stringToPlayerId, window, Keyboard, Music, Sound, keyboard +#include "param.hpp" // Para Param, param, ParamGame, ParamServiceMenu +#include "player.hpp" // Para Player +#include "resource.hpp" // Para Resource +#include "screen.hpp" // Para Screen +#include "section.hpp" // Para Name, name, Options, options +#include "ui/ui_message.hpp" // Para UIMessage +#include "utils.hpp" // Para Zone // Singleton -ServiceMenu *ServiceMenu::instance = nullptr; +ServiceMenu* ServiceMenu::instance = nullptr; void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); } void ServiceMenu::destroy() { delete ServiceMenu::instance; } -auto ServiceMenu::get() -> ServiceMenu * { return ServiceMenu::instance; } +auto ServiceMenu::get() -> ServiceMenu* { return ServiceMenu::instance; } // Constructor ServiceMenu::ServiceMenu() @@ -153,7 +153,7 @@ void ServiceMenu::adjustOption(bool adjust_up) { if (display_options_.empty()) { return; } - auto &selected_option = display_options_.at(selected_); + auto& selected_option = display_options_.at(selected_); if (selected_option->getBehavior() == MenuOption::Behavior::ADJUST) { selected_option->adjustValue(adjust_up); applySettings(); @@ -169,13 +169,13 @@ void ServiceMenu::selectOption() { main_menu_selected_ = selected_; } - auto *selected_option = display_options_.at(selected_); + auto* selected_option = display_options_.at(selected_); if (selected_option == nullptr) { // This shouldn't happen in normal operation, but protects against null pointer return; } - if (auto *folder = dynamic_cast(selected_option)) { + if (auto* folder = dynamic_cast(selected_option)) { previous_settings_group_ = current_settings_group_; current_settings_group_ = folder->getTargetGroup(); selected_ = 0; @@ -190,7 +190,7 @@ void ServiceMenu::selectOption() { void ServiceMenu::updateDisplayOptions() { display_options_.clear(); - for (auto &option : options_) { + for (auto& option : options_) { if (option->getGroup() == current_settings_group_ && !option->isHidden()) { display_options_.push_back(option.get()); } @@ -200,7 +200,7 @@ void ServiceMenu::updateDisplayOptions() { void ServiceMenu::updateOptionPairs() { option_pairs_.clear(); - for (const auto &option : display_options_) { + for (const auto& option : display_options_) { option_pairs_.emplace_back(option->getCaption(), option->getValueAsString()); } } @@ -249,8 +249,8 @@ void ServiceMenu::applySettingsSettings() { setHiddenOptions(); } -auto ServiceMenu::getOptionByCaption(const std::string &caption) const -> MenuOption * { - for (const auto &option : options_) { +auto ServiceMenu::getOptionByCaption(const std::string& caption) const -> MenuOption* { + for (const auto& option : options_) { if (option->getCaption() == caption) { return option.get(); } @@ -274,7 +274,7 @@ auto ServiceMenu::getCurrentGroupAlignment() const -> ServiceMenu::GroupAlignmen auto ServiceMenu::countOptionsInGroup(SettingsGroup group) const -> size_t { size_t count = 0; - for (const auto &option : options_) { + for (const auto& option : options_) { if (option->getGroup() == group && !option->isHidden()) { count++; } @@ -294,12 +294,12 @@ void ServiceMenu::initializeOptions() { []() { return Options::gamepad_manager.getGamepad(Player::Id::PLAYER1).name; }, - [](const std::string &val) { + [](const std::string& val) { Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER1, Input::get()->getGamepadByName(val), val); }, [this]() { // Acción: configurar botones del mando del jugador 1 - auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1); + auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1); if ((gamepad != nullptr) && gamepad->instance) { define_buttons_->enable(gamepad); } @@ -312,12 +312,12 @@ void ServiceMenu::initializeOptions() { []() { return Options::gamepad_manager.getGamepad(Player::Id::PLAYER2).name; }, - [](const std::string &val) { + [](const std::string& val) { Options::gamepad_manager.assignGamepadToPlayer(Player::Id::PLAYER2, Input::get()->getGamepadByName(val), val); }, [this]() { // Acción: configurar botones del mando del jugador 2 - auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2); + auto* gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2); if ((gamepad != nullptr) && gamepad->instance) { define_buttons_->enable(gamepad); } @@ -334,7 +334,7 @@ void ServiceMenu::initializeOptions() { // Devolver el jugador actual asignado al teclado return Options::playerIdToString(Options::getPlayerWhoUsesKeyboard()); }, - [](const std::string &val) { + [](const std::string& val) { // Asignar el teclado al jugador seleccionado Options::keyboard.assignTo(Options::stringToPlayerId(val)); })); @@ -424,7 +424,7 @@ void ServiceMenu::initializeOptions() { []() { return Lang::getNameFromCode(Options::pending_changes.new_language); }, - [](const std::string &val) { + [](const std::string& val) { Options::pending_changes.new_language = Lang::getCodeFromName(val); Options::checkPendingChanges(); })); @@ -439,7 +439,7 @@ void ServiceMenu::initializeOptions() { []() { return Difficulty::getNameFromCode(Options::pending_changes.new_difficulty); }, - [](const std::string &val) { + [](const std::string& val) { Options::pending_changes.new_difficulty = Difficulty::getCodeFromName(val); Options::checkPendingChanges(); })); @@ -507,8 +507,8 @@ void ServiceMenu::initializeOptions() { // Sincroniza los valores de las opciones tipo lista void ServiceMenu::adjustListValues() { - for (auto &option : options_) { - if (auto *list_option = dynamic_cast(option.get())) { + for (auto& option : options_) { + if (auto* list_option = dynamic_cast(option.get())) { list_option->sync(); } } @@ -543,14 +543,14 @@ auto ServiceMenu::settingsGroupToString(SettingsGroup group) -> std::string { // Establece el estado de oculto de ciertas opciones void ServiceMenu::setHiddenOptions() { { - auto *option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE")); + auto* option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE")); if (option != nullptr) { option->setHidden(Options::video.fullscreen); } } { - auto *option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN")); + auto* option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN")); if (option != nullptr) { option->setHidden(!Options::settings.shutdown_enabled); } @@ -559,7 +559,7 @@ void ServiceMenu::setHiddenOptions() { updateMenu(); // El menú debe refrescarse si algo se oculta } -void ServiceMenu::handleEvent(const SDL_Event &event) { +void ServiceMenu::handleEvent(const SDL_Event& event) { if (!enabled_) { return; } @@ -577,7 +577,7 @@ auto ServiceMenu::checkInput() -> bool { return false; } - static auto *input_ = Input::get(); + static auto* input_ = Input::get(); using Action = Input::Action; const std::vector>> ACTIONS = { @@ -590,7 +590,7 @@ auto ServiceMenu::checkInput() -> bool { }; // Teclado - for (const auto &[action, func] : ACTIONS) { + for (const auto& [action, func] : ACTIONS) { if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) { func(); return true; @@ -598,8 +598,8 @@ auto ServiceMenu::checkInput() -> bool { } // Mandos - for (const auto &gamepad : input_->getGamepads()) { - for (const auto &[action, func] : ACTIONS) { + for (const auto& gamepad : input_->getGamepads()) { + for (const auto& [action, func] : ACTIONS) { if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { func(); return true; diff --git a/source/ui/service_menu.h b/source/ui/service_menu.hpp similarity index 85% rename from source/ui/service_menu.h rename to source/ui/service_menu.hpp index 66f59ca..6a53837 100644 --- a/source/ui/service_menu.h +++ b/source/ui/service_menu.hpp @@ -9,8 +9,8 @@ #include // Para pair #include // Para vector -#include "define_buttons.h" // Para DefineButtons -#include "ui_message.h" // Para UIMessage +#include "define_buttons.hpp" // Para DefineButtons +#include "ui_message.hpp" // Para UIMessage class MenuOption; class MenuRenderer; @@ -40,9 +40,9 @@ class ServiceMenu { // --- Métodos de singleton --- static void init(); static void destroy(); - static auto get() -> ServiceMenu *; - ServiceMenu(const ServiceMenu &) = delete; - auto operator=(const ServiceMenu &) -> ServiceMenu & = delete; + static auto get() -> ServiceMenu*; + ServiceMenu(const ServiceMenu&) = delete; + auto operator=(const ServiceMenu&) -> ServiceMenu& = delete; // --- Métodos principales --- void toggle(); @@ -58,7 +58,7 @@ class ServiceMenu { void moveBack(); // --- Método para manejar eventos --- - void handleEvent(const SDL_Event &event); + void handleEvent(const SDL_Event& event); auto checkInput() -> bool; // --- Método principal para refresco externo --- @@ -73,19 +73,19 @@ class ServiceMenu { // --- Getters para que el Renderer pueda leer el estado --- [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } - [[nodiscard]] auto getTitle() const -> const std::string & { return title_; } + [[nodiscard]] auto getTitle() const -> const std::string& { return title_; } [[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; } [[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment; - [[nodiscard]] auto getDisplayOptions() const -> const std::vector & { return display_options_; } - [[nodiscard]] auto getAllOptions() const -> const std::vector> & { return options_; } + [[nodiscard]] auto getDisplayOptions() const -> const std::vector& { return display_options_; } + [[nodiscard]] auto getAllOptions() const -> const std::vector>& { return options_; } [[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; } - [[nodiscard]] auto getOptionPairs() const -> const std::vector> & { return option_pairs_; } + [[nodiscard]] auto getOptionPairs() const -> const std::vector>& { return option_pairs_; } [[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t; private: bool enabled_ = false; std::vector> options_; - std::vector display_options_; + std::vector display_options_; std::vector> option_pairs_; SettingsGroup current_settings_group_; SettingsGroup previous_settings_group_; @@ -108,7 +108,7 @@ class ServiceMenu { void applyVideoSettings(); static void applyAudioSettings(); void applySettingsSettings(); - [[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *; + [[nodiscard]] auto getOptionByCaption(const std::string& caption) const -> MenuOption*; void adjustListValues(); static void playMoveSound(); static void playAdjustSound(); @@ -123,5 +123,5 @@ class ServiceMenu { ~ServiceMenu() = default; // --- Instancia singleton --- - static ServiceMenu *instance; + static ServiceMenu* instance; }; \ No newline at end of file diff --git a/source/ui/ui_message.cpp b/source/ui/ui_message.cpp index c735758..709f695 100644 --- a/source/ui/ui_message.cpp +++ b/source/ui/ui_message.cpp @@ -1,12 +1,12 @@ -#include "ui_message.h" +#include "ui_message.hpp" #include // Para pow #include -#include "text.h" // Para Text::CENTER, Text::COLOR, Text +#include "text.hpp" // Para Text::CENTER, Text::COLOR, Text // Constructor: inicializa el renderizador, el texto y el color del mensaje -UIMessage::UIMessage(std::shared_ptr text_renderer, std::string message_text, const Color &color) +UIMessage::UIMessage(std::shared_ptr text_renderer, std::string message_text, const Color& color) : text_renderer_(std::move(text_renderer)), text_(std::move(message_text)), color_(color) {} diff --git a/source/ui/ui_message.h b/source/ui/ui_message.hpp similarity index 80% rename from source/ui/ui_message.h rename to source/ui/ui_message.hpp index 8622497..f598194 100644 --- a/source/ui/ui_message.h +++ b/source/ui/ui_message.hpp @@ -3,7 +3,7 @@ #include // Para shared_ptr #include // Para string -#include "color.h" // Para Color +#include "color.hpp" // Para Color class Text; @@ -11,7 +11,7 @@ class Text; class UIMessage { public: // Constructor: recibe el renderizador de texto, el mensaje y el color - UIMessage(std::shared_ptr text_renderer, std::string message_text, const Color &color); + UIMessage(std::shared_ptr text_renderer, std::string message_text, const Color& color); // Muestra el mensaje con animación de entrada void show(); @@ -45,11 +45,11 @@ class UIMessage { float y_offset_ = 0.0F; // Desplazamiento vertical actual del mensaje (para animación) // --- Animación --- - float start_y_ = 0.0F; // Posición Y inicial de la animación - float target_y_ = 0.0F; // Posición Y objetivo de la animación - float animation_timer_ = 0.0F; // Timer actual de la animación en segundos + float start_y_ = 0.0F; // Posición Y inicial de la animación + float target_y_ = 0.0F; // Posición Y objetivo de la animación + float animation_timer_ = 0.0F; // Timer actual de la animación en segundos static constexpr float ANIMATION_DURATION_S = 0.133f; // Duración total de la animación (8 frames @ 60fps) - static constexpr float DESP = -8.0F; // Distancia a desplazarse + static constexpr float DESP = -8.0F; // Distancia a desplazarse // Actualiza la interpolación de la animación (ease out/in cubic) void updateAnimation(float delta_time); diff --git a/source/ui/window_message.cpp b/source/ui/window_message.cpp index 70c3622..c7b81d1 100644 --- a/source/ui/window_message.cpp +++ b/source/ui/window_message.cpp @@ -1,11 +1,11 @@ -#include "window_message.h" +#include "window_message.hpp" #include #include -#include "param.h" -#include "screen.h" -#include "text.h" +#include "param.hpp" +#include "screen.hpp" +#include "text.hpp" WindowMessage::WindowMessage( std::shared_ptr text_renderer, diff --git a/source/ui/window_message.h b/source/ui/window_message.hpp similarity index 98% rename from source/ui/window_message.h rename to source/ui/window_message.hpp index 48dfc5f..2d85172 100644 --- a/source/ui/window_message.h +++ b/source/ui/window_message.hpp @@ -7,9 +7,9 @@ #include // Para string #include // Para vector -#include "color.h" // Para Color -#include "param.h" // Para param -#include "text.h" // Para Text +#include "color.hpp" // Para Color +#include "param.hpp" // Para param +#include "text.hpp" // Para Text class WindowMessage { public: diff --git a/source/utils.cpp b/source/utils.cpp index a04238a..f06b3b2 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -1,5 +1,5 @@ #define _USE_MATH_DEFINES -#include "utils.h" +#include "utils.hpp" #include // Para SDL_RenderPoint, SDL_FRect, SDL_FPoint, SDL_CloseIO, SDL_IOFromFile, SDL_LogCategory, SDL_LogError, SDL_LogInfo, SDL_ReadIO, SDL_Renderer @@ -12,8 +12,8 @@ #include // Para runtime_error #include // Para basic_string, allocator, string, operator==, operator+, char_traits -#include "lang.h" // Para getText -#include "resource_helper.h" // Para ResourceHelper +#include "lang.hpp" // Para getText +#include "resource_helper.hpp" // Para ResourceHelper // Variables Overrides overrides = Overrides(); @@ -26,7 +26,7 @@ auto distanceSquared(int x1, int y1, int x2, int y2) -> double { } // Obtiene el punto de colisión entre dos circulos -auto getCollisionPoint(const Circle &a, const Circle &b) -> SDL_FPoint { +auto getCollisionPoint(const Circle& a, const Circle& b) -> SDL_FPoint { float dx = b.x - a.x; float dy = b.y - a.y; float dist = std::sqrt((dx * dx) + (dy * dy)); @@ -44,7 +44,7 @@ auto getCollisionPoint(const Circle &a, const Circle &b) -> SDL_FPoint { } // Detector de colisiones entre dos circulos -auto checkCollision(const Circle &a, const Circle &b) -> bool { +auto checkCollision(const Circle& a, const Circle& b) -> bool { // Calcula el radio total al cuadrado int total_radius_squared = (a.r + b.r) * (a.r + b.r); @@ -53,7 +53,7 @@ auto checkCollision(const Circle &a, const Circle &b) -> bool { } // Detector de colisiones entre un circulo y un rectangulo -auto checkCollision(const Circle &a, const SDL_FRect &b) -> bool { +auto checkCollision(const Circle& a, const SDL_FRect& b) -> bool { // Encuentra el punto más cercano en el rectángulo float c_x = std::clamp(static_cast(a.x), b.x, b.x + b.w); float c_y = std::clamp(static_cast(a.y), b.y, b.y + b.h); @@ -63,7 +63,7 @@ auto checkCollision(const Circle &a, const SDL_FRect &b) -> bool { } // Detector de colisiones entre dos rectangulos -auto checkCollision(const SDL_FRect &a, const SDL_FRect &b) -> bool { +auto checkCollision(const SDL_FRect& a, const SDL_FRect& b) -> bool { const int LEFT_A = a.x; const int RIGHT_A = a.x + a.w; const int TOP_A = a.y; @@ -90,7 +90,7 @@ auto checkCollision(const SDL_FRect &a, const SDL_FRect &b) -> bool { } // Detector de colisiones entre un punto y un rectangulo -auto checkCollision(const SDL_FPoint &p, const SDL_FRect &r) -> bool { +auto checkCollision(const SDL_FPoint& p, const SDL_FRect& r) -> bool { if (p.x < r.x || p.x > r.x + r.w) { return false; } @@ -101,7 +101,7 @@ auto checkCollision(const SDL_FPoint &p, const SDL_FRect &r) -> bool { } // Convierte una cadena en un valor booleano -auto stringToBool(const std::string &str) -> bool { +auto stringToBool(const std::string& str) -> bool { std::string s = trim(toLower(str)); return (s == "true" || s == "1" || s == "yes" || s == "on"); } @@ -117,14 +117,14 @@ auto boolToOnOff(bool value) -> std::string { } // Convierte una cadena a minusculas -auto toLower(const std::string &str) -> std::string { +auto toLower(const std::string& str) -> std::string { std::string result = str; std::ranges::transform(result, result.begin(), [](unsigned char c) { return std::tolower(c); }); return result; } // Dibuja un circulo -void drawCircle(SDL_Renderer *renderer, int32_t center_x, int32_t center_y, int32_t radius) { +void drawCircle(SDL_Renderer* renderer, int32_t center_x, int32_t center_y, int32_t radius) { const int32_t DIAMETER = (radius * 2); int32_t x = (radius - 1); @@ -159,7 +159,7 @@ void drawCircle(SDL_Renderer *renderer, int32_t center_x, int32_t center_y, int3 } // Quita los espacioes en un string -auto trim(const std::string &str) -> std::string { +auto trim(const std::string& str) -> std::string { auto start = std::ranges::find_if_not(str, ::isspace); auto end = std::ranges::find_if_not(std::ranges::reverse_view(str), ::isspace).base(); return (start < end ? std::string(start, end) : std::string()); @@ -290,12 +290,12 @@ auto easeInCubic(double time) -> double { } // Comprueba si una vector contiene una cadena -auto stringInVector(const std::vector &vec, const std::string &str) -> bool { +auto stringInVector(const std::vector& vec, const std::string& str) -> bool { return std::ranges::find(vec, str) != vec.end(); } // Imprime por pantalla una línea de texto de tamaño fijo rellena con puntos -void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3) { +void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3) { constexpr size_t TOTAL_WIDTH = 52; // Calcula el ancho del campo para text2 restando la longitud de text1 y text3 @@ -320,20 +320,19 @@ void printWithDots(const std::string &text1, const std::string &text2, const std SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s", formatted_text.c_str()); } - // Obtiene el nombre de un fichero a partir de una ruta completa -auto getFileName(const std::string &path) -> std::string { +auto getFileName(const std::string& path) -> std::string { return std::filesystem::path(path).filename().string(); } // Obtiene la ruta eliminando el nombre del fichero -auto getPath(const std::string &full_path) -> std::string { +auto getPath(const std::string& full_path) -> std::string { std::filesystem::path path(full_path); return path.parent_path().string(); } // Trunca un string y le añade puntos suspensivos -auto truncateWithEllipsis(const std::string &input, size_t length) -> std::string { +auto truncateWithEllipsis(const std::string& input, size_t length) -> std::string { if (input.size() <= length) { return input; } diff --git a/source/utils.h b/source/utils.hpp similarity index 99% rename from source/utils.h rename to source/utils.hpp index bd4669f..7368582 100644 --- a/source/utils.h +++ b/source/utils.hpp @@ -31,7 +31,6 @@ struct Circle { r(radius) {} }; - struct Zone { SDL_FRect rect; // Rectangulo que define la zona float center_x; // Anclaje al 50% del eje X @@ -88,7 +87,6 @@ auto stringInVector(const std::vector& vec, const std::string& str) void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3); // Imprime una línea con puntos auto truncateWithEllipsis(const std::string& input, size_t length) -> std::string; // Trunca un string y le añade puntos suspensivos - // Ficheros y rutas auto getFileName(const std::string& path) -> std::string; // Obtiene el nombre de un fichero a partir de una ruta auto getPath(const std::string& full_path) -> std::string; // Obtiene la ruta eliminando el nombre del fichero \ No newline at end of file diff --git a/source/version.h.in b/source/version.h.in index 29d5615..2e26cb2 100644 --- a/source/version.h.in +++ b/source/version.h.in @@ -1,6 +1,6 @@ #pragma once namespace Version { - constexpr const char* GIT_HASH = "@GIT_HASH@"; - constexpr const char* APP_NAME = "Coffee Crisis Arcade Edition"; -} \ No newline at end of file +constexpr const char* GIT_HASH = "@GIT_HASH@"; +constexpr const char* APP_NAME = "Coffee Crisis Arcade Edition"; +} // namespace Version \ No newline at end of file diff --git a/source/writer.cpp b/source/writer.cpp index ed16f43..d9377f1 100644 --- a/source/writer.cpp +++ b/source/writer.cpp @@ -1,6 +1,6 @@ -#include "writer.h" +#include "writer.hpp" -#include "text.h" // Para Text +#include "text.hpp" // Para Text // Actualiza el objeto (delta_time en ms) void Writer::update(float delta_time) { @@ -53,7 +53,7 @@ void Writer::setKerning(int value) { } // Establece el valor de la variable -void Writer::setCaption(const std::string &text) { +void Writer::setCaption(const std::string& text) { caption_ = text; length_ = text.length(); } diff --git a/source/writer.h b/source/writer.hpp similarity index 67% rename from source/writer.h rename to source/writer.hpp index 154dbdc..f5ec807 100644 --- a/source/writer.h +++ b/source/writer.hpp @@ -15,15 +15,15 @@ class Writer { ~Writer() = default; // --- Métodos principales --- - void update(float delta_time); // Actualiza el objeto (delta_time en ms) - void updateS(float delta_time); // Actualiza el objeto (delta_time en segundos) - void render() const; // Dibuja el objeto en pantalla + void update(float delta_time); // Actualiza el objeto (delta_time en ms) + void updateS(float delta_time); // Actualiza el objeto (delta_time en segundos) + void render() const; // Dibuja el objeto en pantalla // --- Setters --- void setPosX(int value); // Establece la posición X void setPosY(int value); // Establece la posición Y void setKerning(int value); // Establece el kerning (espaciado entre caracteres) - void setCaption(const std::string &text); // Establece el texto a escribir + void setCaption(const std::string& text); // Establece el texto a escribir void setSpeed(int value); // Establece la velocidad de escritura (frames) void setSpeedS(float value); // Establece la velocidad de escritura (segundos entre caracteres) void setEnabled(bool value); // Habilita o deshabilita el objeto @@ -41,17 +41,17 @@ class Writer { std::shared_ptr text_; // Objeto encargado de escribir el texto // --- Variables de estado --- - std::string caption_; // El texto para escribir - int pos_x_ = 0; // Posición en el eje X donde empezar a escribir el texto - int pos_y_ = 0; // Posición en el eje Y donde empezar a escribir el texto - int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres - float speed_interval_ = 0.0f; // Intervalo entre caracteres (ms para compatibilidad) + std::string caption_; // El texto para escribir + int pos_x_ = 0; // Posición en el eje X donde empezar a escribir el texto + int pos_y_ = 0; // Posición en el eje Y donde empezar a escribir el texto + int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres + float speed_interval_ = 0.0f; // Intervalo entre caracteres (ms para compatibilidad) float writing_timer_ = 0.0f; // Temporizador de escritura para cada caracter int index_ = 0; // Posición del texto que se está escribiendo int length_ = 0; // Longitud de la cadena a escribir float enabled_timer_ = 0.0f; // Temporizador para deshabilitar el objeto float enabled_timer_target_ = 0.0f; // Tiempo objetivo para deshabilitar el objeto - bool completed_ = false; // Indica si se ha escrito todo el texto - bool enabled_ = false; // Indica si el objeto está habilitado - bool finished_ = false; // Indica si ya ha terminado + bool completed_ = false; // Indica si se ha escrito todo el texto + bool enabled_ = false; // Indica si el objeto está habilitado + bool finished_ = false; // Indica si ya ha terminado }; \ No newline at end of file