renombrades extensions .h a .hpp
This commit is contained in:
@@ -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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "animated_sprite.h"
|
||||
#include "animated_sprite.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError, SDL_FRect
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <utility> // 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();
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#include <utility>
|
||||
#include <vector> // 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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "asset.h"
|
||||
#include "asset.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn
|
||||
|
||||
@@ -10,14 +10,14 @@
|
||||
#include <sstream> // Para basic_istringstream
|
||||
#include <stdexcept> // 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<uint8_t> {
|
||||
auto Asset::loadData(const std::string& filename) const -> std::vector<uint8_t> {
|
||||
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<uint8_t>
|
||||
}
|
||||
|
||||
// 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<Type, std::vector<const Item *>> by_type;
|
||||
std::unordered_map<Type, std::vector<const Item*>> 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::string> {
|
||||
std::vector<std::string> 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<std::string> {
|
||||
}
|
||||
|
||||
// Reemplaza variables en las rutas
|
||||
auto Asset::replaceVariables(const std::string &path, const std::string &prefix, const std::string &system_folder) -> std::string {
|
||||
auto 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;
|
||||
}
|
||||
|
||||
@@ -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<uint8_t>; // 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<uint8_t>; // Carga datos del archivo
|
||||
[[nodiscard]] auto check() const -> bool;
|
||||
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
|
||||
[[nodiscard]] auto exists(const std::string &filename) const -> bool; // Nueva función para verificar existencia
|
||||
[[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
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "asset_integrated.h"
|
||||
#include "asset_integrated.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
@@ -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<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
||||
std::vector<uint8_t> 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<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
||||
file.seekg(0, std::ios::beg);
|
||||
|
||||
std::vector<uint8_t> data(fileSize);
|
||||
if (!file.read(reinterpret_cast<char *>(data.data()), fileSize)) {
|
||||
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
||||
std::cerr << "Error: Could not read file: " << filename << std::endl;
|
||||
return {};
|
||||
}
|
||||
@@ -61,9 +61,9 @@ std::vector<uint8_t> 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
|
||||
|
||||
@@ -2,28 +2,28 @@
|
||||
|
||||
#include <memory>
|
||||
|
||||
#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<uint8_t> loadFile(const std::string &filename);
|
||||
std::vector<uint8_t> 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;
|
||||
};
|
||||
@@ -1,15 +1,15 @@
|
||||
#include "audio.h"
|
||||
#include "audio.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_G...
|
||||
|
||||
#include <algorithm> // 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<int>(group));
|
||||
}
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
#define _USE_MATH_DEFINES
|
||||
#include "background.h"
|
||||
#include "background.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <cmath> // Para M_PI, cos, sin
|
||||
#include <utility>
|
||||
|
||||
#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());
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <vector> // 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<SDL_FPoint> sun_path_; // Recorrido del sol
|
||||
std::vector<SDL_FPoint> moon_path_; // Recorrido de la luna
|
||||
std::array<SDL_FRect, STAGES> gradient_rect_; // Fondos degradados
|
||||
std::array<SDL_FRect, 4> top_clouds_rect_; // Nubes superiores
|
||||
std::array<SDL_FRect, 4> 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<SDL_FPoint> sun_path_; // Recorrido del sol
|
||||
std::vector<SDL_FPoint> moon_path_; // Recorrido de la luna
|
||||
std::array<SDL_FRect, STAGES> gradient_rect_; // Fondos degradados
|
||||
std::array<SDL_FRect, 4> top_clouds_rect_; // Nubes superiores
|
||||
std::array<SDL_FRect, 4> 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
|
||||
@@ -1,14 +1,14 @@
|
||||
#include "balloon.h"
|
||||
#include "balloon.hpp"
|
||||
|
||||
#include <algorithm> // Para clamp
|
||||
#include <array> // Para array
|
||||
#include <cmath> // 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)
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
#include <string_view> // Para string_view
|
||||
#include <vector> // 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<AnimatedSprite> 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)
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "balloon_formations.h"
|
||||
#include "balloon_formations.hpp"
|
||||
|
||||
#include <algorithm> // Para max, min, copy
|
||||
#include <array> // Para array
|
||||
@@ -11,10 +11,10 @@
|
||||
#include <sstream> // Para basic_istringstream
|
||||
#include <string> // 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<SpawnParams> 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);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // 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 ---
|
||||
@@ -1,19 +1,19 @@
|
||||
#include "balloon_manager.h"
|
||||
#include "balloon_manager.hpp"
|
||||
|
||||
#include <algorithm> // Para remove_if
|
||||
#include <array>
|
||||
#include <cstdlib> // Para rand
|
||||
#include <numeric> // 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)
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // 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<std::shared_ptr<Balloon>>;
|
||||
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<Balloon>; // Crea un nuevo globo
|
||||
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
||||
void createChildBalloon(const std::shared_ptr<Balloon>& 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> &balloon) -> int; // Explosiona un globo, creando otros si aplica
|
||||
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
|
||||
auto popBalloon(const std::shared_ptr<Balloon>& balloon) -> int; // Explosiona un globo, creando otros si aplica
|
||||
auto destroyBalloon(std::shared_ptr<Balloon>& 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<std::shared_ptr<Texture>> explosions_textures_; // Texturas de explosiones
|
||||
std::vector<std::vector<std::string>> balloon_animations_; // Animaciones de los globos
|
||||
std::vector<std::vector<std::string>> 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;
|
||||
@@ -1,11 +1,11 @@
|
||||
#include "bullet.h"
|
||||
#include "bullet.hpp"
|
||||
|
||||
#include <memory> // Para allocator, unique_ptr, make_unique
|
||||
#include <string> // 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)
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
#include <memory> // Para unique_ptr
|
||||
#include <string> // 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
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
#include "bullet_manager.h"
|
||||
#include "bullet_manager.hpp"
|
||||
|
||||
#include <algorithm> // 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>& bullet) {
|
||||
return !bullet->isEnabled();
|
||||
}),
|
||||
std::remove_if(bullets_.begin(), bullets_.end(), [](const std::shared_ptr<Bullet>& bullet) {
|
||||
return !bullet->isEnabled();
|
||||
}),
|
||||
bullets_.end());
|
||||
}
|
||||
}
|
||||
@@ -103,7 +102,7 @@ auto BulletManager::isBulletOutOfBounds(const std::shared_ptr<Bullet>& 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);
|
||||
}
|
||||
@@ -6,8 +6,8 @@
|
||||
#include <memory> // Para shared_ptr, unique_ptr
|
||||
#include <vector> // 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<std::shared_ptr<Bullet>>;
|
||||
@@ -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>& bullet, float deltaTime); // Procesa actualización individual
|
||||
@@ -1,5 +1,5 @@
|
||||
#define _USE_MATH_DEFINES
|
||||
#include "color.h"
|
||||
#include "color.hpp"
|
||||
|
||||
#include <cctype> // Para isxdigit
|
||||
#include <cmath> // Para sinf, fmaxf, fminf, M_PI, fmodf, roundf, fmod
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <string> // 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<Color> &colors, int counter) -> Color {
|
||||
auto getColorLikeKnightRider(const std::vector<Color>& colors, int counter) -> Color {
|
||||
int cycle_length = (colors.size() * 2) - 2;
|
||||
size_t n = counter % cycle_length;
|
||||
|
||||
|
||||
@@ -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<Color> &colors, int counter) -> Color;
|
||||
auto getColorLikeKnightRider(const std::vector<Color>& colors, int counter) -> Color;
|
||||
auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle;
|
||||
} // namespace Colors
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
#include <array>
|
||||
|
||||
#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
|
||||
@@ -1,25 +1,25 @@
|
||||
#include "define_buttons.h"
|
||||
#include "define_buttons.hpp"
|
||||
|
||||
#include <algorithm> // Para __all_of_fn, all_of
|
||||
#include <functional> // Para identity
|
||||
#include <memory> // 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<SDL_GamepadButton>(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;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#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<WindowMessage> 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();
|
||||
@@ -1,16 +1,17 @@
|
||||
#include "demo.h"
|
||||
#include "demo.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <SDL3/SDL.h> // 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 <stdexcept> // 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;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h> // Para Uint8
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
// --- Constantes ---
|
||||
constexpr int TOTAL_DEMO_DATA = 2000;
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "difficulty.h"
|
||||
#include "difficulty.hpp"
|
||||
|
||||
#include <vector> // Para vector
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// IWYU pragma: no_include <bits/chrono.h>
|
||||
#include "director.h"
|
||||
#include "director.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_SetLogPriority, SDL_LogPriority, SDL_Quit
|
||||
|
||||
@@ -11,33 +11,33 @@
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <string> // 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<char *> argv) {
|
||||
Director::Director(int argc, std::span<char*> 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<char *> argv) {
|
||||
void Director::checkProgramArguments(int argc, std::span<char*> 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<char *> 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) {
|
||||
|
||||
@@ -11,7 +11,7 @@ enum class Code : int;
|
||||
class Director {
|
||||
public:
|
||||
// --- Constructor y destructor ---
|
||||
Director(int argc, std::span<char *> argv);
|
||||
Director(int argc, std::span<char*> 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<char *> 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<char*> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
||||
|
||||
// --- Secciones del programa ---
|
||||
static void runLogo(); // Ejecuta la pantalla con el logo
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "enter_name.h"
|
||||
#include "enter_name.hpp"
|
||||
|
||||
#include <array> // Para array
|
||||
#include <cstdlib> // 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) {
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -1,14 +1,14 @@
|
||||
#include "explosions.h"
|
||||
#include "explosions.hpp"
|
||||
|
||||
#include <algorithm> // 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> &texture, const std::vector<std::string> &animation) {
|
||||
void Explosions::addTexture(int size, const std::shared_ptr<Texture>& texture, const std::vector<std::string>& animation) {
|
||||
textures_.emplace_back(size, texture, animation);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <utility> // Para move
|
||||
#include <vector> // 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> texture; // Textura para la explosión
|
||||
std::vector<std::string> animation; // Animación para la textura
|
||||
|
||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string>& 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> &texture, const std::vector<std::string> &animation); // Añade texturas al objeto
|
||||
void addTexture(int size, const std::shared_ptr<Texture>& texture, const std::vector<std::string>& animation); // Añade texturas al objeto
|
||||
void add(int x, int y, int size); // Añade una explosión
|
||||
|
||||
private:
|
||||
2
source/external/gif.cpp
vendored
2
source/external/gif.cpp
vendored
@@ -1,4 +1,4 @@
|
||||
#include "gif.h"
|
||||
#include "gif.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo
|
||||
#include <cstring> // Para memcpy, size_t
|
||||
|
||||
2
source/external/stb_image.h
vendored
2
source/external/stb_image.h
vendored
@@ -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
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
#include "fade.h"
|
||||
#include "fade.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <algorithm> // Para min, max
|
||||
#include <cstdlib> // 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
|
||||
|
||||
@@ -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<SDL_FRect> square_; // Vector de cuadrados
|
||||
@@ -1,22 +1,22 @@
|
||||
#include "game_logo.h"
|
||||
#include "game_logo.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_SetTextureScaleMode, SDL_FlipMode, SDL_ScaleMode
|
||||
|
||||
#include <algorithm> // 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory> // 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<Texture> dust_texture_; // Textura con los graficos del polvo
|
||||
std::shared_ptr<Texture> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
||||
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la palabra "CRISIS"
|
||||
std::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
||||
|
||||
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
||||
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite del polvo (derecha)
|
||||
std::unique_ptr<SmartSprite> coffee_sprite_; // Sprite de "COFFEE"
|
||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite de "CRISIS"
|
||||
std::unique_ptr<Sprite> 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)
|
||||
};
|
||||
125
source/game_logo.hpp
Normal file
125
source/game_logo.hpp
Normal file
@@ -0,0 +1,125 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory> // 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<Texture> dust_texture_; // Textura con los graficos del polvo
|
||||
std::shared_ptr<Texture> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
||||
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la palabra "CRISIS"
|
||||
std::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
||||
|
||||
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
||||
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite del polvo (derecha)
|
||||
std::unique_ptr<SmartSprite> coffee_sprite_; // Sprite de "COFFEE"
|
||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite de "CRISIS"
|
||||
std::unique_ptr<Sprite> 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)
|
||||
};
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <vector>
|
||||
|
||||
#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 {
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "global_events.h"
|
||||
#include "global_events.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_EventType, SDL_Event, SDL_LogInfo, SDL_LogCategory
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
#include <string> // Para allocator, operator+, string
|
||||
#include <vector> // 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;
|
||||
|
||||
@@ -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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "global_inputs.h"
|
||||
#include "global_inputs.hpp"
|
||||
|
||||
#include <algorithm> // Para std::ranges::any_of
|
||||
#include <functional> // Para function
|
||||
@@ -7,16 +7,16 @@
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // 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
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#include <memory> // 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 {
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "input.h"
|
||||
#include "input.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <utility> // 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> &gamepad, Action action, SDL_GamepadButton button) {
|
||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& 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> &gamepad, Action action_target, Action action_source) {
|
||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& 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> &gamepad) -> bool {
|
||||
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad>& 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> &gamepad) -> bool {
|
||||
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& 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<Gamepad> &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> &gamepad) -> std::string {
|
||||
auto Input::getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string {
|
||||
return gamepad == nullptr ? std::string() : gamepad->name;
|
||||
}
|
||||
|
||||
// Obtiene la lista de nombres de mandos
|
||||
auto Input::getControllerNames() const -> std::vector<std::string> {
|
||||
std::vector<std::string> 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<Input::Gamepad> {
|
||||
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<Input::Gamepa
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto Input::getGamepadByName(const std::string &name) const -> std::shared_ptr<Input::Gamepad> {
|
||||
for (const auto &gamepad : gamepads_) {
|
||||
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
|
||||
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<I
|
||||
}
|
||||
|
||||
// Obtiene el SDL_GamepadButton asignado a un action
|
||||
auto Input::getControllerBinding(const std::shared_ptr<Gamepad> &gamepad, Action action) -> SDL_GamepadButton {
|
||||
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
|
||||
return static_cast<SDL_GamepadButton>(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<std::string, Action> 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> &gamepad, bool repeat) -> bool {
|
||||
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& 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<Gamepad> &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<Gamepad> &gamepa
|
||||
}
|
||||
|
||||
// Comprueba los triggers del mando como botones digitales
|
||||
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool {
|
||||
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||
// Solo manejamos botones específicos que pueden ser triggers
|
||||
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
|
||||
// Solo procesamos L2 y R2 como triggers
|
||||
@@ -272,7 +272,7 @@ auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &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<int>(SDL_GetGamepadButton(gamepad->pad, static_cast<SDL_GamepadButton>(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> &gamepad) {
|
||||
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& 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> 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> 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> 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<SDL_GamepadButton>(buttonState.button);
|
||||
}
|
||||
|
||||
@@ -482,14 +482,14 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> 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<Input::Gamepad> {
|
||||
auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Input::Gamepad> {
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
#include <unordered_map> // Para unordered_map
|
||||
#include <vector> // 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<Action, ButtonState> 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<std::shared_ptr<Gamepad>>; // 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> &gamepad, Action action, SDL_GamepadButton button);
|
||||
static void bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action_target, Action action_source);
|
||||
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button);
|
||||
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& 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> &gamepad = nullptr) -> bool;
|
||||
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad> &gamepad = nullptr) -> bool;
|
||||
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
|
||||
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& 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> &gamepad) -> std::string;
|
||||
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
|
||||
auto getControllerNames() const -> std::vector<std::string>;
|
||||
[[nodiscard]] auto getNumGamepads() const -> int;
|
||||
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
|
||||
auto getGamepadByName(const std::string &name) const -> std::shared_ptr<Input::Gamepad>;
|
||||
auto getGamepads() const -> const Gamepads & { return gamepads_; }
|
||||
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
|
||||
auto getGamepads() const -> const Gamepads& { return gamepads_; }
|
||||
|
||||
// --- Métodos de consulta y utilidades ---
|
||||
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad> &gamepad, Action action) -> SDL_GamepadButton;
|
||||
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& 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<Gamepad>;
|
||||
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
|
||||
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
|
||||
|
||||
private:
|
||||
@@ -198,8 +198,8 @@ class Input {
|
||||
|
||||
// --- Métodos internos ---
|
||||
void initSDLGamePad();
|
||||
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool;
|
||||
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool;
|
||||
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
|
||||
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& 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> 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;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "input_types.h"
|
||||
#include "input_types.hpp"
|
||||
|
||||
// Definición de los mapas
|
||||
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
#include "item.h"
|
||||
#include "item.hpp"
|
||||
|
||||
#include <algorithm> // Para clamp
|
||||
#include <cmath> // Para fmod
|
||||
#include <cstdlib> // 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
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // 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;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "lang.h"
|
||||
#include "lang.hpp"
|
||||
|
||||
#include <cstddef> // Para size_t
|
||||
#include <exception> // Para exception
|
||||
@@ -7,11 +7,11 @@
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // 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<Language> 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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -10,7 +10,7 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
|
||||
#include <memory> // Para make_unique, unique_ptr
|
||||
#include <span> // Para span
|
||||
|
||||
#include "director.h" // Para Director
|
||||
#include "director.hpp" // Para Director
|
||||
|
||||
auto main(int argc, char* argv[]) -> int {
|
||||
// Crea el objeto Director
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
#include "manage_hiscore_table.h"
|
||||
#include "manage_hiscore_table.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO, SDL_GetError, SDL_IOFromFile, SDL_LogCategory, SDL_LogError, SDL_LogInfo
|
||||
|
||||
#include <algorithm> // Para find_if, sort
|
||||
#include <iterator> // 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));
|
||||
|
||||
@@ -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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "mouse.h"
|
||||
#include "mouse.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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) {
|
||||
|
||||
@@ -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
|
||||
@@ -1,9 +1,9 @@
|
||||
#include "moving_sprite.h"
|
||||
#include "moving_sprite.hpp"
|
||||
|
||||
#include <cmath> // Para std::abs
|
||||
#include <cmath> // Para std::abs
|
||||
#include <utility>
|
||||
|
||||
#include "texture.h" // Para Texture
|
||||
#include "texture.hpp" // Para Texture
|
||||
|
||||
// Constructor
|
||||
MovingSprite::MovingSprite(std::shared_ptr<Texture> 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_);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <algorithm> // Para max
|
||||
#include <memory> // Para shared_ptr
|
||||
|
||||
#include "sprite.h" // Para Sprite
|
||||
#include "sprite.hpp" // Para Sprite
|
||||
|
||||
class Texture;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "options.h"
|
||||
#include "options.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_ScaleMode, SDL_GamepadButton, SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
#include <cstddef> // Para size_t
|
||||
#include <fstream> // Para basic_ostream, operator<<, basic_ostream::operator<<, basic_ofstream, basic_istream, basic_ifstream, ifstream, ofstream
|
||||
#include <functional> // Para function
|
||||
#include <sstream> // Para istringstream
|
||||
#include <map> // Para map, operator==, _Rb_tree_const_iterator
|
||||
#include <ranges> // Para std::ranges::any_of
|
||||
#include <sstream> // Para istringstream
|
||||
#include <stdexcept> // Para invalid_argument, out_of_range
|
||||
#include <string> // Para char_traits, stoi, operator==, operator<<, allocator, string, basic_string, operator<=>, getline
|
||||
#include <utility> // Para swap, pair
|
||||
#include <vector> // 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);
|
||||
|
||||
@@ -14,12 +14,12 @@
|
||||
#include <utility> // Para swap
|
||||
#include <vector> // 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 {
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "param.h"
|
||||
#include "param.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogCategory, SDL_LogError, SDL_LogInfo
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
#include <string> // Para operator==, stoi, char_traits, string, ope...
|
||||
#include <unordered_map>
|
||||
|
||||
#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); }},
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
#include <array> // Para array
|
||||
#include <string> // 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 {
|
||||
@@ -1,17 +1,18 @@
|
||||
// IWYU pragma: no_include <bits/std_abs.h>
|
||||
#include "path_sprite.h"
|
||||
#include "path_sprite.hpp"
|
||||
|
||||
#include <functional> // Para function
|
||||
#include <utility> // Para move
|
||||
|
||||
// Constructor para paths por puntos (convertido a segundos)
|
||||
Path::Path(const std::vector<SDL_FPoint> &spots_init, float waiting_time_s_init)
|
||||
: spots(spots_init), is_point_path(true) {
|
||||
Path::Path(const std::vector<SDL_FPoint>& 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<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
|
||||
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)>& easing_function) -> std::vector<SDL_FPoint> {
|
||||
std::vector<SDL_FPoint> 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<double(double)> &easing_function, float waiting_time_s) {
|
||||
void PathSprite::addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)>& 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<SDL_FPoint> &spots, float waiting_time_s) {
|
||||
void PathSprite::addPath(const std::vector<SDL_FPoint>& 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) {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
#include <utility>
|
||||
#include <vector> // 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<double(double)> 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<double(double)> 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<double(double)> 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<SDL_FPoint> &spots_init, float waiting_time_s_init);
|
||||
Path(const std::vector<SDL_FPoint>& spots_init, float waiting_time_s_init);
|
||||
|
||||
// Variables para paths por puntos
|
||||
std::vector<SDL_FPoint> 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<double(double)> &easing_function) -> std::vector<SDL_FPoint>; // 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<double(double)>& easing_function) -> std::vector<SDL_FPoint>; // 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<SDL_FPoint> &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<double(double)> &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<SDL_FPoint>& 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<double(double)>& 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
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "player.h"
|
||||
#include "player.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
#include <cmath> // Para fmod
|
||||
#include <cstdlib> // 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 <iostream>
|
||||
#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();
|
||||
|
||||
@@ -7,14 +7,14 @@
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // 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;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "opengl_shader.h"
|
||||
#include "opengl_shader.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
@@ -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<char> 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<char> 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
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "../shader_backend.h"
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <OpenGL/gl3.h>
|
||||
#else
|
||||
#include <SDL3/SDL_opengl.h>
|
||||
#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
|
||||
98
source/rendering/opengl/opengl_shader.hpp
Normal file
98
source/rendering/opengl/opengl_shader.hpp
Normal file
@@ -0,0 +1,98 @@
|
||||
#pragma once
|
||||
|
||||
#include "../shader_backend.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <OpenGL/gl3.h>
|
||||
#else
|
||||
#include <SDL3/SDL_opengl.h>
|
||||
#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
|
||||
@@ -1,55 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
56
source/rendering/shader_backend.hpp
Normal file
56
source/rendering/shader_backend.hpp
Normal file
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "resource.h"
|
||||
#include "resource.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <stdexcept> // Para runtime_error
|
||||
#include <utility> // 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
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
#include <utility> // Para move
|
||||
#include <vector> // 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<Texture>; // Obtiene la textura por nombre
|
||||
auto getTextFile(const std::string &name) -> std::shared_ptr<Text::File>; // Obtiene el fichero de texto por nombre
|
||||
auto getText(const std::string &name) -> std::shared_ptr<Text>; // 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<Texture>; // Obtiene la textura por nombre
|
||||
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>; // Obtiene el fichero de texto por nombre
|
||||
auto getText(const std::string& name) -> std::shared_ptr<Text>; // 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<Texture>; // Carga una textura específica bajo demanda
|
||||
static auto loadTextFileLazy(const std::string &name) -> std::shared_ptr<Text::File>; // Carga un fichero de texto específico bajo demanda
|
||||
auto loadTextLazy(const std::string &name) -> std::shared_ptr<Text>; // Carga un objeto de texto específico bajo demanda
|
||||
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<Texture>; // Carga una textura específica bajo demanda
|
||||
static auto loadTextFileLazy(const std::string& name) -> std::shared_ptr<Text::File>; // Carga un fichero de texto específico bajo demanda
|
||||
auto loadTextLazy(const std::string& name) -> std::shared_ptr<Text>; // Carga un objeto de texto específico bajo demanda
|
||||
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
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "resource_helper.h"
|
||||
#include "resource_helper.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "resource_loader.h"
|
||||
#include "resource_loader.hpp"
|
||||
|
||||
// Helper functions para integrar ResourceLoader con el sistema existente
|
||||
namespace ResourceHelper {
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "resource_loader.h"
|
||||
#include "resource_loader.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "resource_pack.h"
|
||||
#include "resource_pack.hpp"
|
||||
|
||||
class ResourceLoader {
|
||||
private:
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "resource_pack.h"
|
||||
#include "resource_pack.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "scoreboard.h"
|
||||
#include "scoreboard.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <iomanip> // Para operator<<, setfill, setw
|
||||
#include <sstream> // 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)
|
||||
|
||||
@@ -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<std::string, static_cast<int>(Id::SIZE)> name_ = {}; // Nombre de cada jugador
|
||||
std::array<std::string, static_cast<int>(Id::SIZE)> enter_name_ = {}; // Nombre introducido para la tabla de records
|
||||
std::array<std::string, static_cast<int>(Id::SIZE)> character_selected_ = {}; // Caracter seleccionado
|
||||
std::array<EnterName*, static_cast<int>(Id::SIZE)> enter_name_ref_ = {}; // Referencias a EnterName para obtener character_list_
|
||||
std::array<float, static_cast<int>(Id::SIZE)> carousel_position_ = {}; // Posición actual del carrusel (índice en character_list_)
|
||||
std::array<float, static_cast<int>(Id::SIZE)> carousel_target_ = {}; // Posición objetivo del carrusel
|
||||
std::array<int, static_cast<int>(Id::SIZE)> carousel_prev_index_ = {}; // Índice previo para detectar cambios
|
||||
std::array<float, static_cast<int>(Id::SIZE)> text_slide_offset_ = {}; // Progreso de animación de deslizamiento (0.0 a 1.0)
|
||||
std::array<EnterName*, static_cast<int>(Id::SIZE)> enter_name_ref_ = {}; // Referencias a EnterName para obtener character_list_
|
||||
std::array<float, static_cast<int>(Id::SIZE)> carousel_position_ = {}; // Posición actual del carrusel (índice en character_list_)
|
||||
std::array<float, static_cast<int>(Id::SIZE)> carousel_target_ = {}; // Posición objetivo del carrusel
|
||||
std::array<int, static_cast<int>(Id::SIZE)> carousel_prev_index_ = {}; // Índice previo para detectar cambios
|
||||
std::array<float, static_cast<int>(Id::SIZE)> text_slide_offset_ = {}; // Progreso de animación de deslizamiento (0.0 a 1.0)
|
||||
std::array<Panel, static_cast<int>(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)
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "screen.h"
|
||||
#include "screen.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <memory> // Para allocator, shared_ptr, make_shared, __shared_ptr_access
|
||||
#include <string> // 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<int>(dm->w);
|
||||
display_monitor_.height = static_cast<int>(dm->h);
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // 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<int>(remaining_s * 30.0f) % 2 == 0; // ~30 cambios por segundo
|
||||
const bool SHAKE_LEFT = static_cast<int>(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> 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> text_; // Objeto para escribir texto en pantalla
|
||||
std::unique_ptr<Rendering::ShaderBackend> 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
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
// IWYU pragma: no_include <bits/std_abs.h>
|
||||
#include "credits.h"
|
||||
#include "credits.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <string_view> // Para string_view
|
||||
#include <vector> // 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <vector> // 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<std::shared_ptr<Player>> 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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "game.h"
|
||||
#include "game.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <random> // std::random_device, std::default_random_engine
|
||||
#include <utility> // 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 <iostream> // 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
|
||||
}
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // 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
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "hiscore_table.h"
|
||||
#include "hiscore_table.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
||||
|
||||
@@ -7,25 +7,25 @@
|
||||
#include <functional> // Para function
|
||||
#include <vector> // 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<int>(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);
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
#include <string> // Para string
|
||||
#include <vector> // 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> fade_; // Objeto para renderizar fades
|
||||
std::unique_ptr<Background> 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 ---
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "instructions.h"
|
||||
#include "instructions.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_Re...
|
||||
|
||||
@@ -8,22 +8,22 @@
|
||||
#include <utility> // Para move
|
||||
#include <vector> // 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()
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <vector> // 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<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
||||
std::vector<std::unique_ptr<Sprite>> 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<Line>; // Inicializa las líneas animadas
|
||||
static auto moveLines(std::vector<Line> &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<Line> &lines); // Renderiza las líneas
|
||||
void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos
|
||||
static auto moveLines(std::vector<Line>& 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<Line>& 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
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "intro.h"
|
||||
#include "intro.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // 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 <string> // Para basic_string, string
|
||||
#include <utility> // 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()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user