migrat Input a la ultima versió

cohesionats tots els metodes update de les escenes
This commit is contained in:
2025-11-01 22:28:51 +01:00
parent 1dd750ba0c
commit 824e7417ad
58 changed files with 26926 additions and 978 deletions

View File

@@ -42,6 +42,7 @@ set(APP_SOURCES
# Core - Input
source/core/input/global_inputs.cpp
source/core/input/input.cpp
source/core/input/input_types.cpp
source/core/input/mouse.cpp
# Core - Rendering

View File

@@ -64,6 +64,7 @@ APP_SOURCES := \
source/main.cpp \
source/core/audio/audio.cpp \
source/core/input/input.cpp \
source/core/input/input_types.cpp \
source/core/input/mouse.cpp \
source/core/input/global_inputs.cpp \
source/core/rendering/screen.cpp \

View File

@@ -52,7 +52,7 @@ void Audio::playMusic(const std::string& name, const int loop) {
// Si hay algo reproduciéndose, detenerlo primero (si el backend lo requiere)
if (music_.state == MusicState::PLAYING) {
JA_StopMusic(); // sustituir por la función de stop real del API si tiene otro nombre
JA_StopMusic(); // sustituir por la función de stop real del API si tiene otro nombre
}
// Llamada al motor para reproducir la nueva pista
@@ -64,7 +64,6 @@ void Audio::playMusic(const std::string& name, const int loop) {
music_.state = MusicState::PLAYING;
}
// Pausa la música
void Audio::pauseMusic() {
if (music_enabled_ && music_.state == MusicState::PLAYING) {

View File

@@ -0,0 +1,134 @@
#pragma once
#include <fstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "core/input/input_types.hpp" // Solo incluimos los tipos compartidos
#include "external/json.hpp"
// --- Estructuras ---
struct GamepadConfig {
std::string name; // Nombre del dispositivo
std::string path; // Ruta física del dispositivo
std::unordered_map<InputAction, SDL_GamepadButton> bindings; // Asociación acción-botón
GamepadConfig(std::string name, std::string path)
: name(std::move(name)),
path(std::move(path)),
bindings{
{InputAction::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT},
{InputAction::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
{InputAction::JUMP, SDL_GAMEPAD_BUTTON_WEST}} {}
// Reasigna un botón a una acción
void rebindAction(InputAction action, SDL_GamepadButton new_button) {
bindings[action] = new_button;
}
};
// --- Tipos ---
using GamepadConfigs = std::vector<GamepadConfig>; // Vector de configuraciones de gamepad
// --- Clase GamepadConfigManager: gestor de configuraciones de gamepad ---
class GamepadConfigManager {
public:
// --- Métodos estáticos ---
static auto writeToJson(const GamepadConfigs& configs, const std::string& filename) -> bool { // Escribir configuraciones a JSON
try {
nlohmann::json j;
j["gamepads"] = nlohmann::json::array();
for (const auto& config : configs) {
nlohmann::json gamepad_json;
gamepad_json["name"] = config.name;
gamepad_json["path"] = config.path;
gamepad_json["bindings"] = nlohmann::json::object();
// Convertir bindings a JSON
for (const auto& [action, button] : config.bindings) {
auto action_it = ACTION_TO_STRING.find(action);
auto button_it = BUTTON_TO_STRING.find(button);
if (action_it != ACTION_TO_STRING.end() && button_it != BUTTON_TO_STRING.end()) {
gamepad_json["bindings"][action_it->second] = button_it->second;
}
}
j["gamepads"].push_back(gamepad_json);
}
// Escribir al archivo
std::ofstream file(filename);
if (!file.is_open()) {
return false;
}
file << j.dump(4); // Formato con indentación de 4 espacios
file.close();
return true;
} catch (const std::exception& e) {
// Log del error si tienes sistema de logging
return false;
}
}
// Leer vector de GamepadConfig desde archivo JSON
static auto readFromJson(GamepadConfigs& configs, const std::string& filename) -> bool {
try {
std::ifstream file(filename);
if (!file.is_open()) {
return false;
}
nlohmann::json j;
file >> j;
file.close();
configs.clear();
if (!j.contains("gamepads") || !j["gamepads"].is_array()) {
return false;
}
for (const auto& gamepad_json : j["gamepads"]) {
if (!gamepad_json.contains("name") || !gamepad_json.contains("bindings")) {
continue; // Saltar configuraciones malformadas
}
// Leer el campo path si existe, si no dejarlo vacío
std::string path = gamepad_json.contains("path") ? gamepad_json["path"].get<std::string>() : "";
GamepadConfig config(gamepad_json["name"], path);
// Limpiar bindings por defecto para cargar los del archivo
config.bindings.clear();
// Cargar bindings desde JSON
for (const auto& [actionStr, buttonStr] : gamepad_json["bindings"].items()) {
auto action_it = STRING_TO_ACTION.find(actionStr);
auto button_it = STRING_TO_BUTTON.find(buttonStr);
if (action_it != STRING_TO_ACTION.end() && button_it != STRING_TO_BUTTON.end()) {
config.bindings[action_it->second] = button_it->second;
}
}
configs.push_back(config);
}
return true;
} catch (const std::exception& e) {
// Log del error si tienes sistema de logging
return false;
}
}
// Método auxiliar para verificar si un archivo existe
static auto fileExists(const std::string& filename) -> bool {
std::ifstream file(filename);
return file.good();
}
};

View File

@@ -1,5 +1,3 @@
#include "game/scene_manager.hpp" // Para SceneManager
#include "core/input/global_inputs.hpp"
#include <SDL3/SDL.h>
@@ -7,9 +5,10 @@
#include <string> // Para allocator, operator+, char_traits, string
#include <vector> // Para vector
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
#include "core/rendering/screen.hpp" // Para Screen
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText
#include "utils/utils.hpp" // Para stringInVector
@@ -46,59 +45,59 @@ void skipSection() {
}
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check() {
if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT)) {
void handle() {
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
quit();
}
else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
skipSection();
}
else if (Input::get()->checkInput(InputAction::TOGGLE_BORDER, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_BORDER, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleBorder();
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::TOGGLE_VIDEOMODE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_VIDEOMODE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleVideoMode();
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::WINDOW_DEC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::WINDOW_DEC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
if (Screen::get()->decWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
}
}
else if (Input::get()->checkInput(InputAction::WINDOW_INC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::WINDOW_INC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
if (Screen::get()->incWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
}
}
else if (Input::get()->checkInput(InputAction::TOGGLE_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_SHADERS, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleShaders();
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::NEXT_PALETTE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::NEXT_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->nextPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::PREVIOUS_PALETTE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::PREVIOUS_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->previousPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::TOGGLE_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_INTEGER_SCALE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleIntegerScale();
Screen::get()->setVideoMode(Options::video.fullscreen);
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::SHOW_DEBUG_INFO, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::SHOW_DEBUG_INFO, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleDebugInfo();
}
}

View File

@@ -2,5 +2,5 @@
namespace GlobalInputs {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check();
void handle();
} // namespace GlobalInputs

View File

@@ -1,114 +1,79 @@
#include "core/input/input.hpp"
#include <SDL3/SDL.h>
#include <SDL3/SDL.h> // Para SDL_GetGamepadAxis, SDL_GamepadAxis, SDL_GamepadButton, SDL_GetError, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogError, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, Sint16, SDL_Gamepad, SDL_LogCategory, SDL_Scancode
#include <algorithm> // Para find
#include <iostream> // Para basic_ostream, operator<<, cout, endl
#include <iterator> // Para distance
#include <unordered_map> // Para unordered_map, operator==, _Node_cons...
#include <utility> // Para pair
#include <iostream> // Para basic_ostream, operator<<, cout, cerr
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
#include <ranges> // Para __find_if_fn, find_if
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
#include <utility> // Para pair, move
// [SINGLETON]
Input* Input::input = nullptr;
// Singleton
Input* Input::instance = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Input::init(const std::string& game_controller_db_path) {
Input::input = new Input(game_controller_db_path);
// Inicializa la instancia única del singleton
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);
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Input::destroy() {
delete Input::input;
}
// Libera la instancia
void Input::destroy() { delete Input::instance; }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
auto Input::get() -> Input* {
return Input::input;
}
// Obtiene la instancia
auto Input::get() -> Input* { return Input::instance; }
// Constructor
Input::Input(const std::string& game_controller_db_path)
: game_controller_db_path_(game_controller_db_path) {
// Busca si hay mandos conectados
discoverGameControllers();
// Inicializa los vectores
key_bindings_.resize(static_cast<int>(InputAction::SIZE), KeyBindings());
controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(InputAction::SIZE), ControllerBindings()));
// Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
button_inputs_ = {InputAction::JUMP};
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
: gamepad_mappings_file_(std::move(game_controller_db_path)),
gamepad_configs_file_(std::move(gamepad_configs_file)) {
// Inicializa el subsistema SDL_INIT_GAMEPAD
initSDLGamePad();
}
// Asigna inputs a teclas
void Input::bindKey(InputAction input, SDL_Scancode code) {
key_bindings_.at(static_cast<int>(input)).scancode = code;
void Input::bindKey(Action action, SDL_Scancode code) {
keyboard_.bindings[action].scancode = code;
}
// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button) {
if (controller_index < num_gamepads_) {
controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = 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(int controller_index, InputAction input_target, InputAction input_source) {
if (controller_index < num_gamepads_) {
controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
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 un input esta activo
auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) -> bool {
// Comprueba si alguna acción está activa
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;
const int INPUT_INDEX = static_cast<int>(input);
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
const auto* key_states = SDL_GetKeyboardState(nullptr);
if (repeat) {
success_keyboard = static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0;
} else {
if (!key_bindings_[INPUT_INDEX].active) {
if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0) {
key_bindings_[INPUT_INDEX].active = true;
success_keyboard = true;
} else {
success_keyboard = false;
}
} else {
if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) == 0) {
key_bindings_[INPUT_INDEX].active = false;
}
success_keyboard = false;
}
if (check_keyboard) {
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
success_keyboard = keyboard_.bindings[action].is_held;
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
success_keyboard = keyboard_.bindings[action].just_pressed;
}
}
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) {
success_controller = checkAxisInput(input, controller_index, repeat);
if (gamepad != nullptr) {
success_controller = checkAxisInput(action, gamepad, repeat);
if (!success_controller) {
if (repeat) {
success_controller = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0;
} else {
if (!controller_bindings_.at(controller_index).at(INPUT_INDEX).active) {
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0) {
controller_bindings_.at(controller_index).at(INPUT_INDEX).active = true;
success_controller = true;
} else {
success_controller = false;
}
} else {
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) == 0) {
controller_bindings_.at(controller_index).at(INPUT_INDEX).active = false;
}
success_controller = false;
}
}
if (!success_controller) {
success_controller = checkTriggerInput(action, gamepad, repeat);
}
if (!success_controller) {
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
success_controller = gamepad->bindings[action].is_held;
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
success_controller = gamepad->bindings[action].just_pressed;
}
}
}
@@ -116,26 +81,50 @@ auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
return (success_keyboard || success_controller);
}
// Comprueba si hay almenos un input activo
auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool {
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
const bool* key_states = SDL_GetKeyboardState(nullptr);
// Comprueba si hay almenos una acción activa
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.
for (auto& key_binding : key_bindings_) {
if (static_cast<int>(key_states[key_binding.scancode]) != 0 && !key_binding.active) {
key_binding.active = true;
return true;
// --- Comprobación del Teclado ---
if (check_keyboard) {
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) {
return true; // Se encontró una acción recién pulsada.
}
}
}
if (gameControllerFound()) {
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) {
for (int i = 0; i < (int)controller_bindings_.size(); ++i) {
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button)) != 0 && !controller_bindings_[controller_index][i].active) {
controller_bindings_[controller_index][i].active = true;
return true;
}
// --- Comprobación del Mando ---
// 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) {
// 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.
}
}
}
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
return false;
}
// Comprueba si hay algún botón pulsado
auto Input::checkAnyButton(bool repeat) -> bool {
// Solo comprueba los botones definidos previamente
for (auto bi : BUTTON_INPUTS) {
// Comprueba el teclado
if (checkAction(bi, repeat, CHECK_KEYBOARD)) {
return true;
}
// Comprueba los mandos
for (const auto& gamepad : gamepads_) {
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
return true;
}
}
}
@@ -143,131 +132,68 @@ auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool
return false;
}
// Busca si hay mandos conectados
auto Input::discoverGameControllers() -> bool {
bool found = false;
// Asegúrate de que el subsistema de gamepads está inicializado
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
SDL_InitSubSystem(SDL_INIT_GAMEPAD);
}
// Carga el mapping de mandos desde archivo
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
std::cout << "Error, could not load " << game_controller_db_path_.c_str()
<< " file: " << SDL_GetError() << '\n';
}
// En SDL3 ya no existe SDL_NumJoysticks()
// Ahora se obtiene un array dinámico de IDs
int num_joysticks = 0;
SDL_JoystickID* joystick_ids = SDL_GetJoysticks(&num_joysticks);
num_joysticks_ = num_joysticks;
num_gamepads_ = 0;
joysticks_.clear();
// Recorremos todos los joysticks detectados
for (int i = 0; i < num_joysticks_; ++i) {
SDL_Joystick* joy = SDL_OpenJoystick(joystick_ids[i]);
joysticks_.push_back(joy);
if (SDL_IsGamepad(joystick_ids[i])) {
num_gamepads_++;
}
}
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << '\n';
if (num_joysticks_ != num_gamepads_) {
std::cout << "Joysticks found: " << num_joysticks_ << '\n';
std::cout << "Gamepads found : " << num_gamepads_ << '\n';
} else {
std::cout << "Gamepads found: " << num_gamepads_ << '\n';
}
if (num_gamepads_ > 0) {
found = true;
for (int i = 0; i < num_joysticks_; i++) {
if (SDL_IsGamepad(joystick_ids[i])) {
SDL_Gamepad* pad = SDL_OpenGamepad(joystick_ids[i]);
if ((pad != nullptr) && SDL_GamepadConnected(pad)) {
connected_controllers_.push_back(pad);
const char* name = SDL_GetGamepadName(pad);
std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << '\n';
controller_names_.emplace_back((name != nullptr) ? name : "Unknown");
} else {
std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
}
}
}
// En SDL3 ya no hace falta SDL_GameControllerEventState()
// Los eventos de gamepad están siempre habilitados
}
SDL_free(joystick_ids);
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << '\n';
return found;
}
// Comprueba si hay algun mando conectado
auto Input::gameControllerFound() const -> bool { return num_gamepads_ > 0; }
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
// Obten el nombre de un mando de juego
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : 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_) {
names.push_back(gamepad->name);
}
return names;
}
// Obten el número de mandos conectados
auto Input::getNumControllers() const -> int { return num_gamepads_; }
auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
// Obtiene el indice del controlador a partir de un event.id
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
for (int i = 0; i < num_joysticks_; ++i) {
if (SDL_GetJoystickID(joysticks_[i]) == id) {
return i;
// 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_) {
if (gamepad->instance_id == id) {
return gamepad;
}
}
return -1;
return nullptr;
}
// Obtiene el SDL_GamepadButton asignado a un input
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
return controller_bindings_[controller_index][static_cast<int>(input)].button;
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;
}
}
return nullptr;
}
// Obtiene el indice a partir del nombre del mando
auto Input::getIndexByName(const std::string& name) const -> int {
auto it = std::ranges::find(controller_names_, name);
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
// Obtiene el SDL_GamepadButton asignado a un action
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
}
// Comprueba el eje del mando
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
// Umbral para considerar el eje como activo
const Sint16 THRESHOLD = 30000;
bool axis_active_now = false;
switch (input) {
case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -THRESHOLD;
switch (action) {
case Action::LEFT:
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
break;
case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > THRESHOLD;
break;
case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -THRESHOLD;
break;
case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > THRESHOLD;
case Action::RIGHT:
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
break;
default:
return false;
}
// Referencia al binding correspondiente
auto& binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));
auto& binding = gamepad->bindings[action];
if (repeat) {
// Si se permite repetir, simplemente devolvemos el estado actual
@@ -284,4 +210,290 @@ auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
}
// Mantener el estado actual
return false;
}
// Comprueba los triggers del mando como botones digitales
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
int button = gamepad->bindings[action].button;
// Verificar si el botón mapeado corresponde a un trigger virtual
// (Para esto necesitamos valores especiales que representen L2/R2 como botones)
bool trigger_active_now = false;
// Usamos constantes especiales para L2 y R2 como botones
if (button == TRIGGER_L2_AS_BUTTON) { // L2 como botón
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER);
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
} else if (button == TRIGGER_R2_AS_BUTTON) { // R2 como botón
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER);
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
} else {
return false; // No es un trigger
}
// Referencia al binding correspondiente
auto& binding = gamepad->bindings[action];
if (repeat) {
// Si se permite repetir, simplemente devolvemos el estado actual
return trigger_active_now;
}
// Si no se permite repetir, aplicamos la lógica de transición
if (trigger_active_now && !binding.trigger_active) {
// Transición de inactivo a activo
binding.trigger_active = true;
return true;
}
if (!trigger_active_now && binding.trigger_active) {
// Transición de activo a inactivo
binding.trigger_active = false;
}
// Mantener el estado actual
return false;
}
return false;
}
void Input::addGamepadMappingsFromFile() {
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n';
}
}
void Input::discoverGamepads() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
handleEvent(event); // Comprueba mandos conectados
}
}
void Input::initSDLGamePad() {
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError());
} else {
addGamepadMappingsFromFile();
loadGamepadConfigs();
discoverGamepads();
std::cout << "Input System initialized successfully\n";
}
}
}
void Input::resetInputStates() {
// Resetear todos los KeyBindings.active a false
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) {
binding.second.is_held = false;
binding.second.just_pressed = false;
binding.second.trigger_active = false;
}
}
}
void Input::update() {
// --- TECLADO ---
const bool* key_states = SDL_GetKeyboardState(nullptr);
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
binding.second.just_pressed = key_is_down_now && !binding.second.is_held;
binding.second.is_held = key_is_down_now;
}
// --- MANDOS ---
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
binding.second.just_pressed = button_is_down_now && !binding.second.is_held;
binding.second.is_held = button_is_down_now;
}
}
}
auto Input::handleEvent(const SDL_Event& event) -> std::string {
switch (event.type) {
case SDL_EVENT_GAMEPAD_ADDED:
return addGamepad(event.gdevice.which);
case SDL_EVENT_GAMEPAD_REMOVED:
return removeGamepad(event.gdevice.which);
}
return {};
}
auto Input::addGamepad(int device_index) -> std::string {
SDL_Gamepad* pad = SDL_OpenGamepad(device_index);
if (pad == nullptr) {
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
return {};
}
auto gamepad = std::make_shared<Gamepad>(pad);
auto name = gamepad->name;
std::cout << "Gamepad connected (" << name << ")" << '\n';
applyGamepadConfig(gamepad);
saveGamepadConfigFromGamepad(gamepad);
gamepads_.push_back(std::move(gamepad));
return name + " CONNECTED";
}
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) {
return gamepad->instance_id == id;
});
if (it != gamepads_.end()) {
std::string name = (*it)->name;
std::cout << "Gamepad disconnected (" << name << ")" << '\n';
gamepads_.erase(it);
return name + " DISCONNECTED";
}
std::cerr << "No se encontró el gamepad con ID " << id << '\n';
return {};
}
void Input::printConnectedGamepads() const {
if (gamepads_.empty()) {
std::cout << "No hay gamepads conectados." << '\n';
return;
}
std::cout << "Gamepads conectados:\n";
for (const auto& gamepad : gamepads_) {
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
std::cout << " - ID: " << gamepad->instance_id
<< ", Nombre: " << name << ")" << '\n';
}
}
void Input::loadGamepadConfigs() {
if (GamepadConfigManager::fileExists(gamepad_configs_file_)) {
GamepadConfigManager::readFromJson(gamepad_configs_, gamepad_configs_file_);
}
}
void Input::saveGamepadConfigs() {
GamepadConfigManager::writeToJson(gamepad_configs_, gamepad_configs_file_);
}
void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
if (!gamepad || gamepad->path.empty()) { // No podemos aplicar config sin una ruta
return;
}
// --- Buscar configuración por RUTA (path) ---
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) {
if (gamepad->bindings.find(action) != gamepad->bindings.end()) {
gamepad->bindings[action].button = button;
}
}
}
// Opcional: Podrías añadir un fallback para buscar por nombre si no se encuentra por ruta.
}
void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
if (!gamepad || gamepad->path.empty()) { // No podemos guardar una config sin una ruta
return;
}
// --- 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) {
return config.path == gamepad->path;
});
// Crear nueva configuración desde el gamepad, incluyendo nombre y ruta
GamepadConfig new_config(gamepad->name, gamepad->path); // <--- CAMBIO: Pasamos ambos
new_config.bindings.clear();
// Copiar todos los bindings actuales del gamepad
for (const auto& [action, buttonState] : gamepad->bindings) {
new_config.bindings[action] = static_cast<SDL_GamepadButton>(buttonState.button);
}
if (config_it != gamepad_configs_.end()) {
// Sobreescribir configuración existente para esta ruta
*config_it = new_config;
} else {
// Añadir nueva configuración
gamepad_configs_.push_back(new_config);
}
// Guardar cambios inmediatamente
saveGamepadConfigs();
}
// Método para establecer el archivo de configuración (opcional)
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) {
return config.name == gamepad_name;
});
return (config_it != gamepad_configs_.end()) ? &(*config_it) : nullptr;
}
// 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) {
return config.name == gamepad_name;
});
if (config_it != gamepad_configs_.end()) {
gamepad_configs_.erase(config_it);
saveGamepadConfigs();
return true;
}
return false;
}
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_) {
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_) {
if (gamepad) {
return gamepad;
}
}
// Si llegamos aquí, no hay gamepads válidos
return nullptr;
}

View File

@@ -1,138 +1,194 @@
#pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton, SDL_JoystickID, SDL_CloseGamepad, SDL_Gamepad, SDL_GetGamepadJoystick, SDL_GetGamepadName, SDL_GetGamepadPath, SDL_GetJoystickID, Sint16, Uint8, SDL_Event
#include <string> // Para string, basic_string
#include <vector> // Para vector
#include <array> // Para array
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <unordered_map> // Para unordered_map
#include <utility> // Para pair
#include <vector> // Para vector
// Definiciones de repetición
constexpr bool INPUT_ALLOW_REPEAT = true;
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
// Tipos de entrada
enum class InputDeviceToUse : int {
KEYBOARD = 0,
CONTROLLER = 1,
ANY = 2,
};
enum class InputAction {
// Inputs obligatorios
UP,
DOWN,
LEFT,
RIGHT,
PAUSE,
EXIT,
ACCEPT,
CANCEL,
// Inputs personalizados
JUMP,
WINDOW_INC_ZOOM,
WINDOW_DEC_ZOOM,
TOGGLE_VIDEOMODE,
TOGGLE_INTEGER_SCALE,
TOGGLE_BORDER,
TOGGLE_MUSIC,
NEXT_PALETTE,
PREVIOUS_PALETTE,
TOGGLE_SHADERS,
SHOW_DEBUG_INFO,
// Input obligatorio
NONE,
SIZE
};
#include "core/input/gamepad_config_manager.hpp" // for GamepadConfig (ptr only), GamepadConfigs
#include "core/input/input_types.hpp" // for InputAction
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
class Input {
private:
// [SINGLETON] Objeto privado
static Input* input;
public:
// --- Constantes ---
static constexpr bool ALLOW_REPEAT = true; // Permite repetición
static constexpr bool DO_NOT_ALLOW_REPEAT = false; // No permite repetición
static constexpr bool CHECK_KEYBOARD = true; // Comprueba teclado
static constexpr bool DO_NOT_CHECK_KEYBOARD = false; // No comprueba teclado
static constexpr int TRIGGER_L2_AS_BUTTON = 100; // L2 como botón
static constexpr int TRIGGER_R2_AS_BUTTON = 101; // R2 como botón
struct KeyBindings {
Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo
// --- Tipos ---
using Action = InputAction; // Alias para mantener compatibilidad
// Constructor
explicit KeyBindings(Uint8 sc = 0, bool act = false)
: scancode(sc),
active(act) {}
// --- Estructuras ---
struct KeyState {
Uint8 scancode; // Scancode asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
: scancode(scancode),
is_held(is_held),
just_pressed(just_pressed) {}
};
struct ControllerBindings {
SDL_GamepadButton button; // GameControllerButton asociado
bool active; // Indica si está activo
bool axis_active; // Estado del eje
struct ButtonState {
int button; // GameControllerButton asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
bool axis_active; // Estado del eje
bool trigger_active{false}; // Estado del trigger como botón digital
// Constructor
explicit ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false)
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn),
active(act),
is_held(is_held),
just_pressed(just_pressed),
axis_active(axis_act) {}
};
// Variables
std::vector<SDL_Gamepad*> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_Joystick*> joysticks_; // Vector con todos los joysticks conectados
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociadas a los inputs predefinidos para cada mando
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
int num_joysticks_ = 0; // Número de joysticks conectados
int num_gamepads_ = 0; // Número de mandos conectados
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
struct Keyboard {
std::unordered_map<Action, KeyState> bindings;
// Comprueba el eje del mando
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool;
Keyboard()
: bindings{
// Movimiento del jugador
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
{Action::JUMP, KeyState(SDL_SCANCODE_UP)},
// Constructor
explicit Input(const std::string& game_controller_db_path);
// Inputs de control
{Action::ACCEPT, KeyState(SDL_SCANCODE_RETURN)},
{Action::CANCEL, KeyState(SDL_SCANCODE_ESCAPE)},
{Action::PAUSE, KeyState(SDL_SCANCODE_H)},
{Action::EXIT, KeyState(SDL_SCANCODE_ESCAPE)},
// Destructor
~Input() = default;
// Inputs de sistema
{Action::WINDOW_DEC_ZOOM, KeyState(SDL_SCANCODE_F1)},
{Action::WINDOW_INC_ZOOM, KeyState(SDL_SCANCODE_F2)},
{Action::TOGGLE_VIDEOMODE, KeyState(SDL_SCANCODE_F3)},
{Action::TOGGLE_SHADERS, KeyState(SDL_SCANCODE_F4)},
{Action::NEXT_PALETTE, KeyState(SDL_SCANCODE_F5)},
{Action::PREVIOUS_PALETTE, KeyState(SDL_SCANCODE_F6)},
{Action::TOGGLE_INTEGER_SCALE, KeyState(SDL_SCANCODE_F7)},
{Action::SHOW_DEBUG_INFO, KeyState(SDL_SCANCODE_F12)},
{Action::TOGGLE_MUSIC, KeyState(SDL_SCANCODE_M)},
{Action::TOGGLE_BORDER, KeyState(SDL_SCANCODE_B)}} {}
};
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init(const std::string& game_controller_db_path);
struct Gamepad {
SDL_Gamepad* pad;
SDL_JoystickID instance_id;
std::string name;
std::string path;
std::unordered_map<Action, ButtonState> bindings;
// [SINGLETON] Destruiremos el objeto con esta función estática
Gamepad(SDL_Gamepad* gamepad)
: pad(gamepad),
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
name(std::string(SDL_GetGamepadName(gamepad))),
path(std::string(SDL_GetGamepadPath(pad))),
bindings{
// Movimiento del jugador
{Action::LEFT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT))},
{Action::RIGHT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT))},
{Action::JUMP, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_WEST))}} {}
~Gamepad() {
if (pad != nullptr) {
SDL_CloseGamepad(pad);
}
}
// Reasigna un botón a una acción
void rebindAction(Action action, SDL_GamepadButton new_button) {
bindings[action] = static_cast<int>(new_button);
}
};
// --- Tipos ---
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 destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static auto get() -> Input*;
// Asigna inputs a teclas
void bindKey(InputAction input, SDL_Scancode code);
// --- 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);
// Asigna inputs a botones del mando
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_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 checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
// Comprueba si un input esta activo
auto checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
// Comprueba si hay almenos un input activo
auto checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
// Busca si hay mandos conectados
auto discoverGameControllers() -> bool;
// Comprueba si hay algun mando conectado
// --- Métodos de gestión de mandos ---
[[nodiscard]] auto gameControllerFound() const -> bool;
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_; }
// Obten el número de mandos conectados
[[nodiscard]] auto getNumControllers() const -> int;
// --- Métodos de consulta y utilidades ---
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
// Obten el nombre de un mando de juego
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string;
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates();
// Obtiene el indice del controlador a partir de un event.id
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int;
// --- Eventos ---
auto handleEvent(const SDL_Event& event) -> std::string;
// Obtiene el SDL_GamepadButton asignado a un input
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton;
void printConnectedGamepads() const;
// Obtiene el indice a partir del nombre del mando
[[nodiscard]] auto getIndexByName(const std::string& name) const -> int;
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
private:
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD = 30000;
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (aproximadamente 50% del rango)
static constexpr std::array<Action, 1> BUTTON_INPUTS = {Action::JUMP}; // Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
// --- Variables internas ---
Gamepads gamepads_;
Keyboard keyboard_;
std::string gamepad_mappings_file_;
std::string gamepad_configs_file_;
GamepadConfigs gamepad_configs_;
// --- 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;
auto addGamepad(int device_index) -> std::string;
auto removeGamepad(SDL_JoystickID id) -> std::string;
void addGamepadMappingsFromFile();
void discoverGamepads();
// --- Métodos para integración con GamepadConfigManager ---
void loadGamepadConfigs();
void saveGamepadConfigs();
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;
// --- Constructor y destructor ---
explicit Input(std::string game_controller_db_path, std::string gamepad_configs_file);
~Input() = default;
// --- Singleton ---
static Input* instance;
};

View File

@@ -0,0 +1,76 @@
#include "input_types.hpp"
#include <utility> // Para pair
// Definición de los mapas
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
{InputAction::LEFT, "LEFT"},
{InputAction::RIGHT, "RIGHT"},
{InputAction::JUMP, "JUMP"},
{InputAction::PAUSE, "PAUSE"},
{InputAction::EXIT, "EXIT"},
{InputAction::ACCEPT, "ACCEPT"},
{InputAction::CANCEL, "CANCEL"},
{InputAction::WINDOW_INC_ZOOM, "WINDOW_INC_ZOOM"},
{InputAction::WINDOW_DEC_ZOOM, "WINDOW_DEC_ZOOM"},
{InputAction::TOGGLE_VIDEOMODE, "TOGGLE_VIDEOMODE"},
{InputAction::TOGGLE_INTEGER_SCALE, "TOGGLE_INTEGER_SCALE"},
{InputAction::TOGGLE_BORDER, "TOGGLE_BORDER"},
{InputAction::TOGGLE_MUSIC, "TOGGLE_MUSIC"},
{InputAction::NEXT_PALETTE, "NEXT_PALETTE"},
{InputAction::PREVIOUS_PALETTE, "PREVIOUS_PALETTE"},
{InputAction::TOGGLE_SHADERS, "TOGGLE_SHADERS"},
{InputAction::SHOW_DEBUG_INFO, "SHOW_DEBUG_INFO"},
{InputAction::NONE, "NONE"}};
const std::unordered_map<std::string, InputAction> STRING_TO_ACTION = {
{"LEFT", InputAction::LEFT},
{"RIGHT", InputAction::RIGHT},
{"JUMP", InputAction::JUMP},
{"PAUSE", InputAction::PAUSE},
{"EXIT", InputAction::EXIT},
{"ACCEPT", InputAction::ACCEPT},
{"CANCEL", InputAction::CANCEL},
{"WINDOW_INC_ZOOM", InputAction::WINDOW_INC_ZOOM},
{"WINDOW_DEC_ZOOM", InputAction::WINDOW_DEC_ZOOM},
{"TOGGLE_VIDEOMODE", InputAction::TOGGLE_VIDEOMODE},
{"TOGGLE_INTEGER_SCALE", InputAction::TOGGLE_INTEGER_SCALE},
{"TOGGLE_BORDER", InputAction::TOGGLE_BORDER},
{"TOGGLE_MUSIC", InputAction::TOGGLE_MUSIC},
{"NEXT_PALETTE", InputAction::NEXT_PALETTE},
{"PREVIOUS_PALETTE", InputAction::PREVIOUS_PALETTE},
{"TOGGLE_SHADERS", InputAction::TOGGLE_SHADERS},
{"SHOW_DEBUG_INFO", InputAction::SHOW_DEBUG_INFO},
{"NONE", InputAction::NONE}};
const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING = {
{SDL_GAMEPAD_BUTTON_WEST, "WEST"},
{SDL_GAMEPAD_BUTTON_NORTH, "NORTH"},
{SDL_GAMEPAD_BUTTON_EAST, "EAST"},
{SDL_GAMEPAD_BUTTON_SOUTH, "SOUTH"},
{SDL_GAMEPAD_BUTTON_START, "START"},
{SDL_GAMEPAD_BUTTON_BACK, "BACK"},
{SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, "LEFT_SHOULDER"},
{SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, "RIGHT_SHOULDER"},
{SDL_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP"},
{SDL_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN"},
{SDL_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT"},
{SDL_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT"},
{static_cast<SDL_GamepadButton>(100), "L2_AS_BUTTON"},
{static_cast<SDL_GamepadButton>(101), "R2_AS_BUTTON"}};
const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON = {
{"WEST", SDL_GAMEPAD_BUTTON_WEST},
{"NORTH", SDL_GAMEPAD_BUTTON_NORTH},
{"EAST", SDL_GAMEPAD_BUTTON_EAST},
{"SOUTH", SDL_GAMEPAD_BUTTON_SOUTH},
{"START", SDL_GAMEPAD_BUTTON_START},
{"BACK", SDL_GAMEPAD_BUTTON_BACK},
{"LEFT_SHOULDER", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
{"RIGHT_SHOULDER", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
{"DPAD_UP", SDL_GAMEPAD_BUTTON_DPAD_UP},
{"DPAD_DOWN", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
{"DPAD_LEFT", SDL_GAMEPAD_BUTTON_DPAD_LEFT},
{"DPAD_RIGHT", SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
{"L2_AS_BUTTON", static_cast<SDL_GamepadButton>(100)},
{"R2_AS_BUTTON", static_cast<SDL_GamepadButton>(101)}};

View File

@@ -0,0 +1,42 @@
#pragma once
#include <SDL3/SDL.h>
#include <string>
#include <unordered_map>
// --- Enums ---
enum class InputAction : int { // Acciones de entrada posibles en el juego
// Inputs de movimiento
LEFT,
RIGHT,
JUMP,
// Inputs de control
PAUSE,
EXIT,
ACCEPT,
CANCEL,
// Inputs de sistema
WINDOW_INC_ZOOM,
WINDOW_DEC_ZOOM,
TOGGLE_VIDEOMODE,
TOGGLE_INTEGER_SCALE,
TOGGLE_BORDER,
TOGGLE_MUSIC,
NEXT_PALETTE,
PREVIOUS_PALETTE,
TOGGLE_SHADERS,
SHOW_DEBUG_INFO,
// Input obligatorio
NONE,
SIZE,
};
// --- Variables ---
extern const std::unordered_map<InputAction, std::string> ACTION_TO_STRING; // Mapeo de acción a string
extern const std::unordered_map<std::string, InputAction> STRING_TO_ACTION; // Mapeo de string a acción
extern const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING; // Mapeo de botón a string
extern const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON; // Mapeo de string a botón

View File

@@ -55,8 +55,7 @@ inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int co
}
// Agrega una nueva entrada al diccionario
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind,
int& code_length, int prev, int code) {
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind, int& code_length, int prev, int code) {
uint8_t first_byte;
if (code == dictionary_ind) {
first_byte = findFirstByte(dictionary, prev);

View File

@@ -209,13 +209,6 @@ void Screen::toggleShaders() {
initShaders();
}
// Actualiza la lógica de la clase (versión antigua para escenas no migradas)
void Screen::update() {
fps_.calculate(SDL_GetTicks());
Notifier::get()->update(0.016f); // Asume ~60 FPS (16ms por frame)
Mouse::updateCursorVisibility();
}
// Actualiza la lógica de la clase (versión nueva con delta_time para escenas migradas)
void Screen::update(float delta_time) {
fps_.calculate(SDL_GetTicks());

View File

@@ -153,7 +153,6 @@ class Screen {
void render();
// Actualiza la lógica de la clase
void update(); // Para escenas no migradas (sin delta_time)
void update(float delta_time); // Para escenas migradas (con delta_time)
// Establece el modo de video
@@ -196,7 +195,7 @@ class Screen {
void hide();
// Establece el renderizador para las surfaces
void setRendererSurface(const std::shared_ptr<Surface> &surface = nullptr);
void setRendererSurface(const std::shared_ptr<Surface>& surface = nullptr);
// Cambia la paleta
void nextPalette();

View File

@@ -14,8 +14,8 @@
#include <stdexcept> // Para runtime_error
#include <vector> // Para vector
#include "core/rendering/gif.hpp" // Para Gif
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/gif.hpp" // Para Gif
#include "core/rendering/screen.hpp" // Para Screen
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
// Carga una paleta desde un archivo .gif

View File

@@ -7,10 +7,10 @@
#include <stdexcept> // Para runtime_error
#include <utility>
#include "core/rendering/surface.hpp" // Para Surface
#include "core/resources/resource.hpp" // Para Resource
#include "core/rendering/surface.hpp" // Para Surface
#include "core/resources/resource.hpp" // Para Resource
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "utils/utils.hpp" // Para printWithDots
#include "utils/utils.hpp" // Para printWithDots
// Carga las animaciones en un vector(Animations) desde un fichero
auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
@@ -30,14 +30,14 @@ auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
std::vector<std::string> buffer;
std::string line;
while (std::getline(stream, line)) {
// Eliminar \r de Windows line endings
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (!line.empty()) {
buffer.push_back(line);
}
}
// Eliminar \r de Windows line endings
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (!line.empty()) {
buffer.push_back(line);
}
}
return buffer;
}
@@ -60,7 +60,6 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(const Animations& animations)
}
}
// Constructor
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
: SurfaceMovingSprite(std::move(surface)) {
@@ -105,8 +104,7 @@ void SurfaceAnimatedSprite::animate(float delta_time) {
// Calcula el frame actual a partir del tiempo acumulado
const int TARGET_FRAME = static_cast<int>(
animations_[current_animation_].accumulated_time /
animations_[current_animation_].speed
);
animations_[current_animation_].speed);
// Si alcanza el final de la animación, maneja el loop
if (TARGET_FRAME >= static_cast<int>(animations_[current_animation_].frames.size())) {
@@ -137,7 +135,7 @@ void SurfaceAnimatedSprite::animate(float delta_time) {
// Establece el clip del frame actual
if (animations_[current_animation_].current_frame >= 0 &&
animations_[current_animation_].current_frame <
static_cast<int>(animations_[current_animation_].frames.size())) {
static_cast<int>(animations_[current_animation_].frames.size())) {
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
}
}
@@ -215,9 +213,7 @@ auto parseGlobalParameter(const std::string& line, std::shared_ptr<Surface>& sur
}
// Helper: Parsea los frames de una animación desde una cadena separada por comas
void parseAnimationFrames(const std::string& value, AnimationData& animation,
float frame_width, float frame_height,
int frames_per_row, int max_tiles) {
void parseAnimationFrames(const std::string& value, AnimationData& animation, float frame_width, float frame_height, int frames_per_row, int max_tiles) {
std::stringstream ss(value);
std::string tmp;
SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height};
@@ -269,8 +265,7 @@ auto parseAnimation(const Animations& animations, size_t& index, float frame_wid
if (pos != std::string::npos) {
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
parseAnimationParameter(key, value, animation, frame_width, frame_height,
frames_per_row, max_tiles);
parseAnimationParameter(key, value, animation, frame_width, frame_height, frames_per_row, max_tiles);
}
} while (line != "[/animation]");
@@ -302,8 +297,7 @@ void SurfaceAnimatedSprite::setAnimations(const Animations& animations) {
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") {
AnimationData animation = parseAnimation(animations, index, frame_width, frame_height,
frames_per_row, max_tiles);
AnimationData animation = parseAnimation(animations, index, frame_width, frame_height, frames_per_row, max_tiles);
animations_.emplace_back(animation);
}

View File

@@ -54,5 +54,5 @@ void SurfaceSprite::clear() {
// Actualiza el estado del sprite (time-based)
void SurfaceSprite::update(float delta_time) {
// Base implementation does nothing (static sprites)
(void)delta_time; // Evita warning de parámetro no usado
(void)delta_time; // Evita warning de parámetro no usado
}

View File

@@ -8,11 +8,11 @@
#include <sstream> // Para istringstream
#include <stdexcept> // Para runtime_error
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
// Llena una estructuta TextFile desde un fichero
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile> {

View File

@@ -102,7 +102,7 @@ struct ResourceTileMap {
// Estructura para almacenar habitaciones y su nombre
struct ResourceRoom {
std::string name; // Nombre de la habitación
std::string name; // Nombre de la habitación
std::shared_ptr<Room::Data> room; // Habitación
// Constructor
@@ -152,7 +152,7 @@ class Resource {
std::vector<ResourceTileMap> tile_maps_; // Vector con los mapas de tiles
std::vector<ResourceRoom> rooms_; // Vector con las habitaciones
ResourceCount count_; // Contador de recursos
ResourceCount count_; // Contador de recursos
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
// Carga los sonidos

View File

@@ -3,13 +3,13 @@
#include "resource_helper.hpp"
#include "resource_loader.hpp"
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include "resource_loader.hpp"
namespace jdd {
namespace ResourceHelper {

View File

@@ -4,9 +4,9 @@
#ifndef RESOURCE_HELPER_HPP
#define RESOURCE_HELPER_HPP
#include <cstdint>
#include <string>
#include <vector>
#include <cstdint>
namespace jdd {
namespace ResourceHelper {
@@ -15,7 +15,7 @@ namespace ResourceHelper {
// pack_file: Path to resources.pack
// enable_fallback: Allow loading from filesystem if pack not available
auto initializeResourceSystem(const std::string& pack_file = "resources.pack",
bool enable_fallback = true) -> bool;
bool enable_fallback = true) -> bool;
// Shutdown the resource system
void shutdownResourceSystem();

View File

@@ -4,64 +4,64 @@
#ifndef RESOURCE_LOADER_HPP
#define RESOURCE_LOADER_HPP
#include "resource_pack.hpp"
#include <memory>
#include <string>
#include <vector>
#include "resource_pack.hpp"
namespace jdd {
// Singleton class for loading resources from pack or filesystem
class ResourceLoader {
public:
// Get singleton instance
static auto get() -> ResourceLoader&;
public:
// Get singleton instance
static auto get() -> ResourceLoader&;
// Initialize with a pack file (optional)
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool;
// Initialize with a pack file (optional)
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool;
// Load a resource (tries pack first, then filesystem if fallback enabled)
auto loadResource(const std::string& filename) -> std::vector<uint8_t>;
// Load a resource (tries pack first, then filesystem if fallback enabled)
auto loadResource(const std::string& filename) -> std::vector<uint8_t>;
// Check if a resource exists
auto resourceExists(const std::string& filename) -> bool;
// Check if a resource exists
auto resourceExists(const std::string& filename) -> bool;
// Check if pack is loaded
auto isPackLoaded() const -> bool;
// Check if pack is loaded
auto isPackLoaded() const -> bool;
// Get pack statistics
auto getPackResourceCount() const -> size_t;
// Get pack statistics
auto getPackResourceCount() const -> size_t;
// Validate pack integrity (checksum)
auto validatePack() const -> bool;
// Validate pack integrity (checksum)
auto validatePack() const -> bool;
// Load assets.txt from pack (for release builds)
auto loadAssetsConfig() const -> std::string;
// Load assets.txt from pack (for release builds)
auto loadAssetsConfig() const -> std::string;
// Cleanup
void shutdown();
// Cleanup
void shutdown();
private:
ResourceLoader() = default;
~ResourceLoader() = default;
private:
ResourceLoader() = default;
~ResourceLoader() = default;
// Disable copy/move
ResourceLoader(const ResourceLoader&) = delete;
ResourceLoader& operator=(const ResourceLoader&) = delete;
ResourceLoader(ResourceLoader&&) = delete;
ResourceLoader& operator=(ResourceLoader&&) = delete;
// Disable copy/move
ResourceLoader(const ResourceLoader&) = delete;
ResourceLoader& operator=(const ResourceLoader&) = delete;
ResourceLoader(ResourceLoader&&) = delete;
ResourceLoader& operator=(ResourceLoader&&) = delete;
// Load from filesystem
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>;
// Load from filesystem
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>;
// Check if file exists on filesystem
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
// Check if file exists on filesystem
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
// Member data
std::unique_ptr<ResourcePack> resource_pack_;
bool fallback_to_files_{true};
bool initialized_{false};
// Member data
std::unique_ptr<ResourcePack> resource_pack_;
bool fallback_to_files_{true};
bool initialized_{false};
};
} // namespace jdd

View File

@@ -81,7 +81,7 @@ auto ResourcePack::addFile(const std::string& filepath, const std::string& pack_
// Add all files from a directory recursively
auto ResourcePack::addDirectory(const std::string& dir_path,
const std::string& base_path) -> bool {
const std::string& base_path) -> bool {
namespace fs = std::filesystem;
if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
@@ -244,7 +244,7 @@ auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8
}
std::vector<uint8_t> result(data_.begin() + entry.offset,
data_.begin() + entry.offset + entry.size);
data_.begin() + entry.offset + entry.size);
// Verify checksum
uint32_t checksum = calculateChecksum(result);

View File

@@ -15,10 +15,10 @@ namespace jdd {
// Entry metadata for each resource in the pack
struct ResourceEntry {
std::string filename; // Relative path within pack
uint64_t offset; // Byte offset in data block
uint64_t size; // Size in bytes
uint32_t checksum; // CRC32 checksum for verification
std::string filename; // Relative path within pack
uint64_t offset; // Byte offset in data block
uint64_t size; // Size in bytes
uint32_t checksum; // CRC32 checksum for verification
};
// Resource pack file format
@@ -26,67 +26,67 @@ struct ResourceEntry {
// Metadata: Count + array of ResourceEntry
// Data: Encrypted data block
class ResourcePack {
public:
ResourcePack() = default;
~ResourcePack() = default;
public:
ResourcePack() = default;
~ResourcePack() = default;
// Disable copy/move
ResourcePack(const ResourcePack&) = delete;
ResourcePack& operator=(const ResourcePack&) = delete;
ResourcePack(ResourcePack&&) = delete;
ResourcePack& operator=(ResourcePack&&) = delete;
// Disable copy/move
ResourcePack(const ResourcePack&) = delete;
ResourcePack& operator=(const ResourcePack&) = delete;
ResourcePack(ResourcePack&&) = delete;
ResourcePack& operator=(ResourcePack&&) = delete;
// Add a single file to the pack
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool;
// Add a single file to the pack
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool;
// Add all files from a directory recursively
auto addDirectory(const std::string& dir_path, const std::string& base_path = "")
-> bool;
// Add all files from a directory recursively
auto addDirectory(const std::string& dir_path, const std::string& base_path = "")
-> bool;
// Save the pack to a file
auto savePack(const std::string& pack_file) -> bool;
// Save the pack to a file
auto savePack(const std::string& pack_file) -> bool;
// Load a pack from a file
auto loadPack(const std::string& pack_file) -> bool;
// Load a pack from a file
auto loadPack(const std::string& pack_file) -> bool;
// Get a resource by name
auto getResource(const std::string& filename) -> std::vector<uint8_t>;
// Get a resource by name
auto getResource(const std::string& filename) -> std::vector<uint8_t>;
// Check if a resource exists
auto hasResource(const std::string& filename) const -> bool;
// Check if a resource exists
auto hasResource(const std::string& filename) const -> bool;
// Get list of all resources
auto getResourceList() const -> std::vector<std::string>;
// Get list of all resources
auto getResourceList() const -> std::vector<std::string>;
// Check if pack is loaded
auto isLoaded() const -> bool { return loaded_; }
// Check if pack is loaded
auto isLoaded() const -> bool { return loaded_; }
// Get pack statistics
auto getResourceCount() const -> size_t { return resources_.size(); }
auto getDataSize() const -> size_t { return data_.size(); }
// Get pack statistics
auto getResourceCount() const -> size_t { return resources_.size(); }
auto getDataSize() const -> size_t { return data_.size(); }
// Calculate overall pack checksum (for validation)
auto calculatePackChecksum() const -> uint32_t;
// Calculate overall pack checksum (for validation)
auto calculatePackChecksum() const -> uint32_t;
private:
static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'};
static constexpr uint32_t VERSION = 1;
static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024";
private:
static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'};
static constexpr uint32_t VERSION = 1;
static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024";
// Calculate CRC32 checksum
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
// Calculate CRC32 checksum
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
// XOR encryption/decryption
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
// XOR encryption/decryption
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
// Read file from disk
static auto readFile(const std::string& filepath) -> std::vector<uint8_t>;
// Read file from disk
static auto readFile(const std::string& filepath) -> std::vector<uint8_t>;
// Member data
std::unordered_map<std::string, ResourceEntry> resources_;
std::vector<uint8_t> data_; // Encrypted data block
bool loaded_{false};
// Member data
std::unordered_map<std::string, ResourceEntry> resources_;
std::vector<uint8_t> data_; // Encrypted data block
bool loaded_{false};
};
} // namespace jdd

View File

@@ -11,27 +11,27 @@
#include <memory> // Para make_unique, unique_ptr
#include <string> // Para operator+, allocator, char_traits
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/input.hpp" // Para Input, InputAction
#include "core/rendering/screen.hpp" // Para Screen
#include "core/resources/asset.hpp" // Para Asset, AssetType
#include "core/resources/resource.hpp" // Para Resource
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/input.hpp" // Para Input, InputAction
#include "core/rendering/screen.hpp" // Para Screen
#include "core/resources/asset.hpp" // Para Asset, AssetType
#include "core/resources/resource.hpp" // Para Resource
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "core/resources/resource_loader.hpp" // Para ResourceLoader
#include "core/system/debug.hpp" // Para Debug
#include "game/gameplay/cheevos.hpp" // Para Cheevos
#include "game/options.hpp" // Para Options, options, OptionsVideo
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/scenes/credits.hpp" // Para Credits
#include "game/scenes/ending.hpp" // Para Ending
#include "game/scenes/ending2.hpp" // Para Ending2
#include "game/scenes/game.hpp" // Para Game, GameMode
#include "game/scenes/game_over.hpp" // Para GameOver
#include "game/scenes/loading_screen.hpp" // Para LoadingScreen
#include "game/scenes/logo.hpp" // Para Logo
#include "game/scenes/title.hpp" // Para Title
#include "game/ui/notifier.hpp" // Para Notifier
#include "utils/defines.hpp" // Para WINDOW_CAPTION
#include "core/system/debug.hpp" // Para Debug
#include "game/gameplay/cheevos.hpp" // Para Cheevos
#include "game/options.hpp" // Para Options, options, OptionsVideo
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/scenes/credits.hpp" // Para Credits
#include "game/scenes/ending.hpp" // Para Ending
#include "game/scenes/ending2.hpp" // Para Ending2
#include "game/scenes/game.hpp" // Para Game, GameMode
#include "game/scenes/game_over.hpp" // Para GameOver
#include "game/scenes/loading_screen.hpp" // Para LoadingScreen
#include "game/scenes/logo.hpp" // Para Logo
#include "game/scenes/title.hpp" // Para Title
#include "game/ui/notifier.hpp" // Para Notifier
#include "utils/defines.hpp" // Para WINDOW_CAPTION
#ifndef _WIN32
#include <pwd.h>
@@ -92,7 +92,7 @@ Director::Director(std::vector<std::string> const& args) {
// 4. Initialize Asset system with config from pack
// NOTE: In release, don't use executable_path or PREFIX - paths in pack are relative
// Pass empty string to avoid issues when running from different directories
Asset::init(""); // Empty executable_path in release
Asset::init(""); // Empty executable_path in release
Asset::get()->loadFromString(assets_config, "", system_folder_); // Empty PREFIX for pack
std::cout << "Asset system initialized from pack\n";
@@ -134,13 +134,12 @@ Director::Director(std::vector<std::string> const& args) {
#ifdef RELEASE_BUILD
// In release, construct the path manually (not from Asset which has empty executable_path)
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
Input::init(gamecontroller_db);
Input::init(gamecontroller_db, Asset::get()->get("controllers.json"));
#else
// In development, use Asset as normal
Input::init(Asset::get()->get("gamecontrollerdb.txt"));
Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles
#endif
initInput();
Debug::init();
// Special handling for cheevos.bin - also needs filesystem path
@@ -249,72 +248,6 @@ void Director::createSystemFolder(const std::string& folder) {
}
}
// Inicia las variables necesarias para arrancar el programa
void Director::initInput() {
// Busca si hay un mando conectado
Input::get()->discoverGameControllers();
// Teclado - Movimiento
if (Options::keys == Options::ControlScheme::CURSOR) {
Input::get()->bindKey(InputAction::JUMP, SDL_SCANCODE_UP);
Input::get()->bindKey(InputAction::LEFT, SDL_SCANCODE_LEFT);
Input::get()->bindKey(InputAction::RIGHT, SDL_SCANCODE_RIGHT);
Input::get()->bindKey(InputAction::UP, SDL_SCANCODE_UP);
Input::get()->bindKey(InputAction::DOWN, SDL_SCANCODE_DOWN);
} else if (Options::keys == Options::ControlScheme::OPQA) {
Input::get()->bindKey(InputAction::JUMP, SDL_SCANCODE_Q);
Input::get()->bindKey(InputAction::LEFT, SDL_SCANCODE_O);
Input::get()->bindKey(InputAction::RIGHT, SDL_SCANCODE_P);
Input::get()->bindKey(InputAction::UP, SDL_SCANCODE_Q);
Input::get()->bindKey(InputAction::DOWN, SDL_SCANCODE_A);
} else if (Options::keys == Options::ControlScheme::WASD) {
Input::get()->bindKey(InputAction::JUMP, SDL_SCANCODE_W);
Input::get()->bindKey(InputAction::LEFT, SDL_SCANCODE_A);
Input::get()->bindKey(InputAction::RIGHT, SDL_SCANCODE_D);
Input::get()->bindKey(InputAction::UP, SDL_SCANCODE_W);
Input::get()->bindKey(InputAction::DOWN, SDL_SCANCODE_S);
}
// Teclado - Otros
Input::get()->bindKey(InputAction::ACCEPT, SDL_SCANCODE_RETURN);
Input::get()->bindKey(InputAction::CANCEL, SDL_SCANCODE_ESCAPE);
Input::get()->bindKey(InputAction::PAUSE, SDL_SCANCODE_H);
Input::get()->bindKey(InputAction::EXIT, SDL_SCANCODE_ESCAPE);
Input::get()->bindKey(InputAction::WINDOW_DEC_ZOOM, SDL_SCANCODE_F1);
Input::get()->bindKey(InputAction::WINDOW_INC_ZOOM, SDL_SCANCODE_F2);
Input::get()->bindKey(InputAction::TOGGLE_VIDEOMODE, SDL_SCANCODE_F3);
Input::get()->bindKey(InputAction::TOGGLE_SHADERS, SDL_SCANCODE_F4);
Input::get()->bindKey(InputAction::NEXT_PALETTE, SDL_SCANCODE_F5);
Input::get()->bindKey(InputAction::PREVIOUS_PALETTE, SDL_SCANCODE_F6);
Input::get()->bindKey(InputAction::TOGGLE_INTEGER_SCALE, SDL_SCANCODE_F7);
Input::get()->bindKey(InputAction::SHOW_DEBUG_INFO, SDL_SCANCODE_F12);
Input::get()->bindKey(InputAction::TOGGLE_MUSIC, SDL_SCANCODE_M);
Input::get()->bindKey(InputAction::TOGGLE_BORDER, SDL_SCANCODE_B);
// MANDO
const int NUM_GAMEPADS = Input::get()->getNumControllers();
for (int i = 0; i < NUM_GAMEPADS; ++i) {
// Movimiento
Input::get()->bindGameControllerButton(i, InputAction::JUMP, SDL_GAMEPAD_BUTTON_SOUTH);
Input::get()->bindGameControllerButton(i, InputAction::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
Input::get()->bindGameControllerButton(i, InputAction::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
// Otros
Input::get()->bindGameControllerButton(i, InputAction::ACCEPT, SDL_GAMEPAD_BUTTON_SOUTH);
Input::get()->bindGameControllerButton(i, InputAction::CANCEL, SDL_GAMEPAD_BUTTON_EAST);
#ifdef GAME_CONSOLE
Input::get()->bindGameControllerButton(i, InputAction::input_pause, SDL_GAMEPAD_BUTTON_BACK);
Input::get()->bindGameControllerButton(i, InputAction::input_exit, SDL_GAMEPAD_BUTTON_START);
#else
Input::get()->bindGameControllerButton(i, InputAction::PAUSE, SDL_GAMEPAD_BUTTON_START);
Input::get()->bindGameControllerButton(i, InputAction::EXIT, SDL_GAMEPAD_BUTTON_BACK);
#endif
Input::get()->bindGameControllerButton(i, InputAction::NEXT_PALETTE, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
Input::get()->bindGameControllerButton(i, InputAction::TOGGLE_MUSIC, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
Input::get()->bindGameControllerButton(i, InputAction::TOGGLE_BORDER, SDL_GAMEPAD_BUTTON_NORTH);
}
}
// Crea el indice de ficheros
auto Director::setFileList() -> bool {
// Determinar el prefijo de ruta según la plataforma

View File

@@ -8,18 +8,17 @@
class Director {
public:
Director(std::vector<std::string> const& args); // Constructor
~Director(); // Destructor
static auto run() -> int; // Bucle principal
~Director(); // Destructor
static auto run() -> int; // Bucle principal
private:
// --- Variables ---
std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos
std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos
static auto checkProgramArguments(std::vector<std::string> const& args) -> std::string; // Comprueba los parametros del programa
// --- Funciones ---
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
static void initInput(); // Inicializa el objeto Input
auto setFileList() -> bool; // Crea el indice de ficheros
static void runLogo(); // Ejecuta la seccion de juego con el logo
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga

View File

@@ -1,13 +1,12 @@
#include "game/scene_manager.hpp" // Para SceneManager
#include "core/system/global_events.hpp"
#include "core/input/mouse.hpp"
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
#include "game/scene_manager.hpp" // Para SceneManager
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void check(const SDL_Event& event) {
void handle(const SDL_Event& event) {
// Evento de salida de la aplicación
if (event.type == SDL_EVENT_QUIT) {
SceneManager::current = SceneManager::Scene::QUIT;

View File

@@ -4,5 +4,5 @@
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void check(const SDL_Event& event);
void handle(const SDL_Event& event);
} // namespace GlobalEvents

25526
source/external/json.hpp vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,7 @@
// Constructor
Enemy::Enemy(const Data& enemy)
// [DOC:29/10/2025] la surface ara se pillarà del .ANI
: sprite_(std::make_shared<SurfaceAnimatedSprite>(/*Resource::get()->getSurface(enemy.surface_path), */Resource::get()->getAnimations(enemy.animation_path))),
: sprite_(std::make_shared<SurfaceAnimatedSprite>(/*Resource::get()->getSurface(enemy.surface_path), */ Resource::get()->getAnimations(enemy.animation_path))),
color_string_(enemy.color),
x1_(enemy.x1),
x2_(enemy.x2),

View File

@@ -18,18 +18,18 @@ class Enemy {
int w = 0; // Anchura del enemigo
int h = 0; // Altura del enemigo
[/DOC] */
float x = 0.0F; // Posición inicial en el eje X
float y = 0.0F; // Posición inicial en el eje Y
float vx = 0.0F; // Velocidad en el eje X
float vy = 0.0F; // Velocidad en el eje Y
int x1 = 0; // Límite izquierdo de la ruta en el eje X
int x2 = 0; // Límite derecho de la ruta en el eje X
int y1 = 0; // Límite superior de la ruta en el eje Y
int y2 = 0; // Límite inferior de la ruta en el eje Y
bool flip = false; // Indica si el enemigo hace flip al terminar su ruta
bool mirror = false; // Indica si el enemigo está volteado verticalmente
int frame = 0; // Frame inicial para la animación del enemigo
std::string color; // Color del enemigo
float x = 0.0F; // Posición inicial en el eje X
float y = 0.0F; // Posición inicial en el eje Y
float vx = 0.0F; // Velocidad en el eje X
float vy = 0.0F; // Velocidad en el eje Y
int x1 = 0; // Límite izquierdo de la ruta en el eje X
int x2 = 0; // Límite derecho de la ruta en el eje X
int y1 = 0; // Límite superior de la ruta en el eje Y
int y2 = 0; // Límite inferior de la ruta en el eje Y
bool flip = false; // Indica si el enemigo hace flip al terminar su ruta
bool mirror = false; // Indica si el enemigo está volteado verticalmente
int frame = 0; // Frame inicial para la animación del enemigo
std::string color; // Color del enemigo
// Constructor por defecto
Data() = default;

View File

@@ -22,7 +22,7 @@ class Item {
// Constructor
Data() = default;
};
// Constructor y Destructor
explicit Item(const Data& item);
~Item() = default;

View File

@@ -56,12 +56,12 @@ void Player::checkInput(float delta_time) {
if (!auto_movement_) {
// Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
if (Input::get()->checkInput(InputAction::LEFT)) {
if (Input::get()->checkAction(InputAction::LEFT)) {
vx_ = -HORIZONTAL_VELOCITY;
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
}
else if (Input::get()->checkInput(InputAction::RIGHT)) {
else if (Input::get()->checkAction(InputAction::RIGHT)) {
vx_ = HORIZONTAL_VELOCITY;
sprite_->setFlip(SDL_FLIP_NONE);
}
@@ -84,7 +84,7 @@ void Player::checkInput(float delta_time) {
}
}
if (Input::get()->checkInput(InputAction::JUMP)) {
if (Input::get()->checkAction(InputAction::JUMP)) {
// Solo puede saltar si ademas de estar (state == STANDING)
// Esta sobre el suelo, rampa o suelo que se mueve
// Esto es para evitar el salto desde el vacio al cambiar de pantalla verticalmente
@@ -132,16 +132,14 @@ void Player::checkState(float delta_time) {
// Reproduce sonidos según el estado
if (state_ == State::FALLING) {
playFallSound();
}
else if (state_ == State::STANDING) {
} else if (state_ == State::STANDING) {
// Si no tiene suelo debajo y no está en rampa descendente -> FALLING
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
last_grounded_position_ = static_cast<int>(y_); // Guarda Y actual al SALIR de STANDING
setState(State::FALLING); // setState() establece vx_=0, vy_=MAX_VY
setState(State::FALLING); // setState() establece vx_=0, vy_=MAX_VY
playFallSound();
}
}
else if (state_ == State::JUMPING) {
} else if (state_ == State::JUMPING) {
playJumpSound();
}
}
@@ -208,8 +206,7 @@ void Player::handleSlopeMovement(int direction) {
const LineVertical SIDE = {
.x = SIDE_X,
.y1 = static_cast<int>(y_) + HEIGHT - 2,
.y2 = static_cast<int>(y_) + HEIGHT - 1
};
.y2 = static_cast<int>(y_) + HEIGHT - 1};
// Comprueba la rampa correspondiente según la dirección
const int SLOPE_Y = direction < 0 ? room_->checkLeftSlopes(&SIDE) : room_->checkRightSlopes(&SIDE);
@@ -233,16 +230,14 @@ void Player::moveHorizontal(float delta_time, int direction) {
.x = x_ + DISPLACEMENT,
.y = y_,
.w = std::ceil(std::fabs(DISPLACEMENT)),
.h = HEIGHT
};
.h = HEIGHT};
} else {
// Movimiento a la derecha
proj = {
.x = x_ + WIDTH,
.y = y_,
.w = std::ceil(DISPLACEMENT),
.h = HEIGHT
};
.h = HEIGHT};
}
// Comprueba la colisión con las superficies
@@ -351,14 +346,14 @@ void Player::moveVerticalDown(float delta_time) {
// Orquesta el movimiento del jugador
void Player::move(float delta_time) {
applyGravity(delta_time); // Aplica gravedad al jugador
checkState(delta_time); // Comprueba el estado del jugador
applyGravity(delta_time); // Aplica gravedad al jugador
checkState(delta_time); // Comprueba el estado del jugador
// Movimiento horizontal
if (vx_ < 0.0F) {
moveHorizontal(delta_time, -1); // Izquierda
} else if (vx_ > 0.0F) {
moveHorizontal(delta_time, 1); // Derecha
moveHorizontal(delta_time, 1); // Derecha
}
// Si ha salido del suelo, el jugador cae
@@ -623,7 +618,7 @@ void Player::initSprite(const std::string& animations_path) {
// Actualiza collider_box y collision points
void Player::updateColliderGeometry() {
placeSprite(); // Coloca el sprite en la posición del jugador
placeSprite(); // Coloca el sprite en la posición del jugador
collider_box_ = getRect(); // Actualiza el rectangulo de colisión
updateColliderPoints(); // Actualiza los puntos de colisión
}

View File

@@ -66,18 +66,18 @@ class Player {
~Player() = default;
// --- Funciones ---
void render(); // Pinta el enemigo en pantalla
void update(float delta_time); // Actualiza las variables del objeto
[[nodiscard]] auto getOnBorder() const -> bool { return is_on_border_; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
[[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra
void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; } // Obtiene el rectangulo que delimita al jugador
auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador
void render(); // Pinta el enemigo en pantalla
void update(float delta_time); // Actualiza las variables del objeto
[[nodiscard]] auto getOnBorder() const -> bool { return is_on_border_; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
[[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra
void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; } // Obtiene el rectangulo que delimita al jugador
auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador
auto getSpawnParams() -> SpawnData { return {x_, y_, vx_, vy_, last_grounded_position_, state_, sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador
void setColor(); // Establece el color del jugador
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); } // Establece la habitación en la que se encuentra el jugador
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; } // Comprueba si el jugador esta vivo
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
void setColor(); // Establece el color del jugador
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); } // Establece la habitación en la que se encuentra el jugador
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; } // Comprueba si el jugador esta vivo
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
private:
// --- Constantes ---
@@ -99,15 +99,15 @@ class Player {
std::unique_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del jugador
// --- Variables de posición y física ---
float x_ = 0.0F; // Posición del jugador en el eje X
float y_ = 0.0F; // Posición del jugador en el eje Y
float y_prev_ = 0.0F; // Posición Y del frame anterior (para detectar hitos de distancia en sonidos)
float vx_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje X
float vy_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje Y
float x_ = 0.0F; // Posición del jugador en el eje X
float y_ = 0.0F; // Posición del jugador en el eje Y
float y_prev_ = 0.0F; // Posición Y del frame anterior (para detectar hitos de distancia en sonidos)
float vx_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje X
float vy_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje Y
// --- Variables de estado ---
State state_ = State::STANDING; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
State previous_state_ = State::STANDING; // Estado previo en el que se encontraba el jugador
State state_ = State::STANDING; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
State previous_state_ = State::STANDING; // Estado previo en el que se encontraba el jugador
// --- Variables de colisión ---
SDL_FRect collider_box_; // Caja de colisión con los enemigos u objetos
@@ -116,17 +116,17 @@ class Player {
std::array<SDL_FPoint, 2> feet_{}; // Contiene los puntos que hay en el pie del jugador
// --- Variables de juego ---
bool is_on_border_ = false; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
bool is_alive_ = true; // Indica si el jugador esta vivo o no
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
bool auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
Room::Border border_ = Room::Border::TOP; // Indica en cual de los cuatro bordes se encuentra
int last_grounded_position_ = 0; // Ultima posición en Y en la que se estaba en contacto con el suelo (hace doble función: tracking de caída + altura inicial del salto)
bool is_on_border_ = false; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
bool is_alive_ = true; // Indica si el jugador esta vivo o no
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
bool auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
Room::Border border_ = Room::Border::TOP; // Indica en cual de los cuatro bordes se encuentra
int last_grounded_position_ = 0; // Ultima posición en Y en la que se estaba en contacto con el suelo (hace doble función: tracking de caída + altura inicial del salto)
// --- Variables de renderizado y sonido ---
Uint8 color_ = 0; // Color del jugador
std::vector<JA_Sound_t*> jumping_sound_; // Vecor con todos los sonidos del salto
std::vector<JA_Sound_t*> falling_sound_; // Vecor con todos los sonidos de la caída
Uint8 color_ = 0; // Color del jugador
std::vector<JA_Sound_t*> jumping_sound_; // Vecor con todos los sonidos del salto
std::vector<JA_Sound_t*> falling_sound_; // Vecor con todos los sonidos de la caída
// --- Funciones de inicialización ---
void initSprite(const std::string& animations_path); // Inicializa el sprite del jugador
@@ -134,38 +134,38 @@ class Player {
void applySpawnValues(const SpawnData& spawn); // Aplica los valores de spawn al jugador
// --- Funciones de procesamiento de entrada ---
void checkInput(float delta_time); // Comprueba las entradas y modifica variables
void checkInput(float delta_time); // Comprueba las entradas y modifica variables
// --- Funciones de gestión de estado ---
void checkState(float delta_time); // Comprueba el estado del jugador y actualiza variables
void setState(State value); // Cambia el estado del jugador
void checkState(float delta_time); // Comprueba el estado del jugador y actualiza variables
void setState(State value); // Cambia el estado del jugador
// --- Funciones de física ---
void applyGravity(float delta_time); // Aplica gravedad al jugador
void applyGravity(float delta_time); // Aplica gravedad al jugador
// --- Funciones de movimiento y colisión ---
void move(float delta_time); // Orquesta el movimiento del jugador
void moveHorizontal(float delta_time, int direction); // Maneja el movimiento horizontal (-1: izq, 1: der)
void moveVerticalUp(float delta_time); // Maneja el movimiento vertical hacia arriba
void moveVerticalDown(float delta_time); // Maneja el movimiento vertical hacia abajo
void handleSlopeMovement(int direction); // Maneja el movimiento sobre rampas
void move(float delta_time); // Orquesta el movimiento del jugador
void moveHorizontal(float delta_time, int direction); // Maneja el movimiento horizontal (-1: izq, 1: der)
void moveVerticalUp(float delta_time); // Maneja el movimiento vertical hacia arriba
void moveVerticalDown(float delta_time); // Maneja el movimiento vertical hacia abajo
void handleSlopeMovement(int direction); // Maneja el movimiento sobre rampas
// --- Funciones de detección de superficies ---
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
auto isOnAutoSurface() -> bool; // Comprueba si el jugador esta sobre una superficie automática
auto isOnDownSlope() -> bool; // Comprueba si el jugador está sobre una rampa hacia abajo
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
auto isOnAutoSurface() -> bool; // Comprueba si el jugador esta sobre una superficie automática
auto isOnDownSlope() -> bool; // Comprueba si el jugador está sobre una rampa hacia abajo
// --- Funciones de actualización de geometría ---
void updateColliderGeometry(); // Actualiza collider_box y collision points
void updateColliderPoints(); // Actualiza los puntos de colisión
void updateFeet(); // Actualiza los puntos de los pies
void placeSprite(); // Coloca el sprite en la posición del jugador
void updateColliderGeometry(); // Actualiza collider_box y collision points
void updateColliderPoints(); // Actualiza los puntos de colisión
void updateFeet(); // Actualiza los puntos de los pies
void placeSprite(); // Coloca el sprite en la posición del jugador
// --- Funciones de finalización ---
void animate(float delta_time); // Establece la animación del jugador
void checkBorders(); // Comprueba si se halla en alguno de los cuatro bordes
void checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
auto checkKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
void playJumpSound(); // Calcula y reproduce el sonido de salto
void playFallSound(); // Calcula y reproduce el sonido de caer
void animate(float delta_time); // Establece la animación del jugador
void checkBorders(); // Comprueba si se halla en alguno de los cuatro bordes
void checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
auto checkKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
void playJumpSound(); // Calcula y reproduce el sonido de salto
void playFallSound(); // Calcula y reproduce el sonido de caer
};

View File

@@ -7,18 +7,18 @@
#include <sstream> // Para basic_stringstream
#include <utility>
#include "core/audio/audio.hpp" // Para Audio
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/resources/resource.hpp" // Para Resource
#include "core/audio/audio.hpp" // Para Audio
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/resources/resource.hpp" // Para Resource
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "core/system/debug.hpp" // Para Debug
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData
#include "game/options.hpp" // Para Options, OptionsStats, options
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
#include "core/system/debug.hpp" // Para Debug
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData
#include "game/options.hpp" // Para Options, OptionsStats, options
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
// Constructor
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
@@ -869,14 +869,15 @@ auto Room::setEnemy(Enemy::Data* enemy, const std::string& key, const std::strin
try {
/*if (key == "tileSetFile") {
enemy->surface_path = value;
} else */if (key == "animation") {
} else */
if (key == "animation") {
enemy->animation_path = value;
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
} else if (key == "width") {
enemy->w = std::stoi(value);
} else if (key == "height") {
enemy->h = std::stoi(value);
[/DOC] */
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
} else if (key == "width") {
enemy->w = std::stoi(value);
} else if (key == "height") {
enemy->h = std::stoi(value);
[/DOC] */
} else if (key == "x") {
enemy->x = std::stof(value) * TILE_SIZE;
} else if (key == "y") {
@@ -991,8 +992,7 @@ auto Room::loadRoomTileFile(const std::string& file_path, bool verbose) -> std::
if (verbose) {
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
}
}
else { // El fichero no se puede abrir
} else { // El fichero no se puede abrir
if (verbose) {
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
}
@@ -1046,8 +1046,7 @@ auto Room::loadRoomFile(const std::string& file_path, bool verbose) -> Data {
if (verbose) {
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
}
}
else { // El fichero no se puede abrir
} else { // El fichero no se puede abrir
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
}

View File

@@ -34,27 +34,27 @@ class Room {
};
struct AnimatedTile {
std::shared_ptr<SurfaceSprite> sprite; // SurfaceSprite para dibujar el tile
int x_orig = 0; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
std::shared_ptr<SurfaceSprite> sprite; // SurfaceSprite para dibujar el tile
int x_orig = 0; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
};
struct Data {
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
std::string bg_color; // Color de fondo de la habitación
std::string border_color; // Color del borde de la pantalla
std::string item_color1; // Color 1 para los items de la habitación
std::string item_color2; // Color 2 para los items de la habitación
std::string upper_room; // Identificador de la habitación que se encuentra arriba
std::string lower_room; // Identificador de la habitación que se encuentra abajo
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
std::string tile_set_file; // Imagen con los gráficos para la habitación
std::string tile_map_file; // Fichero con el mapa de índices de tile
int conveyor_belt_direction = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
std::vector<int> tile_map; // Índice de los tiles a dibujar en la habitación
std::vector<Enemy::Data> enemies; // Listado con los enemigos de la habitación
std::vector<Item::Data> items; // Listado con los items que hay en la habitación
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
std::string bg_color; // Color de fondo de la habitación
std::string border_color; // Color del borde de la pantalla
std::string item_color1; // Color 1 para los items de la habitación
std::string item_color2; // Color 2 para los items de la habitación
std::string upper_room; // Identificador de la habitación que se encuentra arriba
std::string lower_room; // Identificador de la habitación que se encuentra abajo
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
std::string tile_set_file; // Imagen con los gráficos para la habitación
std::string tile_map_file; // Fichero con el mapa de índices de tile
int conveyor_belt_direction = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
std::vector<int> tile_map; // Índice de los tiles a dibujar en la habitación
std::vector<Enemy::Data> enemies; // Listado con los enemigos de la habitación
std::vector<Item::Data> items; // Listado con los items que hay en la habitación
// Constructor por defecto
Data() = default;
@@ -108,34 +108,34 @@ class Room {
std::shared_ptr<ScoreboardData> data_; // Puntero a los datos del marcador
// --- Variables ---
std::string number_; // Numero de la habitación
std::string name_; // Nombre de la habitación
std::string bg_color_; // Color de fondo de la habitación
std::string border_color_; // Color del borde de la pantalla
std::string item_color1_; // Color 1 para los items de la habitación
std::string item_color2_; // Color 2 para los items de la habitación
std::string upper_room_; // Identificador de la habitación que se encuentra arriba
std::string lower_room_; // Identificador de la habitación que se encuentra abajp
std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda
std::string right_room_; // Identificador de la habitación que se encuentra a la derecha
std::string tile_set_file_; // Imagen con los graficos para la habitación
std::string tile_map_file_; // Fichero con el mapa de indices de tile
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación
int conveyor_belt_direction_ = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
std::vector<LineHorizontal> bottom_floors_; // Lista con las superficies inferiores de la habitación
std::vector<LineHorizontal> top_floors_; // Lista con las superficies superiores de la habitación
std::vector<LineVertical> left_walls_; // Lista con las superficies laterales de la parte izquierda de la habitación
std::vector<LineVertical> right_walls_; // Lista con las superficies laterales de la parte derecha de la habitación
std::vector<LineDiagonal> left_slopes_; // Lista con todas las rampas que suben hacia la izquierda
std::vector<LineDiagonal> right_slopes_; // Lista con todas las rampas que suben hacia la derecha
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones (time-based)
bool is_paused_ = false; // Indica si el mapa esta en modo pausa
std::string number_; // Numero de la habitación
std::string name_; // Nombre de la habitación
std::string bg_color_; // Color de fondo de la habitación
std::string border_color_; // Color del borde de la pantalla
std::string item_color1_; // Color 1 para los items de la habitación
std::string item_color2_; // Color 2 para los items de la habitación
std::string upper_room_; // Identificador de la habitación que se encuentra arriba
std::string lower_room_; // Identificador de la habitación que se encuentra abajp
std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda
std::string right_room_; // Identificador de la habitación que se encuentra a la derecha
std::string tile_set_file_; // Imagen con los graficos para la habitación
std::string tile_map_file_; // Fichero con el mapa de indices de tile
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación
int conveyor_belt_direction_ = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
std::vector<LineHorizontal> bottom_floors_; // Lista con las superficies inferiores de la habitación
std::vector<LineHorizontal> top_floors_; // Lista con las superficies superiores de la habitación
std::vector<LineVertical> left_walls_; // Lista con las superficies laterales de la parte izquierda de la habitación
std::vector<LineVertical> right_walls_; // Lista con las superficies laterales de la parte derecha de la habitación
std::vector<LineDiagonal> left_slopes_; // Lista con todas las rampas que suben hacia la izquierda
std::vector<LineDiagonal> right_slopes_; // Lista con todas las rampas que suben hacia la derecha
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones (time-based)
bool is_paused_ = false; // Indica si el mapa esta en modo pausa
// Constantes de tiempo
static constexpr float CONVEYOR_FRAME_DURATION = 0.05F; // Duración de cada frame de conveyor belt (3 frames @ 60fps)
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
int tile_set_width_ = 0; // Ancho del tileset en tiles
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
int tile_set_width_ = 0; // Ancho del tileset en tiles
// --- Funciones ---
void initializeRoom(const Data& room); // Inicializa los valores

View File

@@ -21,7 +21,7 @@ Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
constexpr float SURFACE_HEIGHT = 6.0F * TILE_SIZE;
// Reserva memoria para los objetos
//auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif");
// auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif");
auto player_animations = Resource::get()->getAnimations(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani");
player_sprite_ = std::make_shared<SurfaceAnimatedSprite>(player_animations);
player_sprite_->setCurrentAnimation("walk_menu");

View File

@@ -2,8 +2,8 @@
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <utility>
#include <vector> // Para vector
class SurfaceAnimatedSprite; // lines 10-10
@@ -74,13 +74,13 @@ class Scoreboard {
static constexpr int SPRITE_WALK_FRAMES = 4; // Número de frames de animación
// Variables
std::vector<Uint8> color_; // Vector con los colores del objeto
bool is_paused_; // Indica si el marcador esta en modo pausa
Uint32 paused_time_; // Milisegundos que ha estado el marcador en pausa
Uint32 paused_time_elapsed_; // Tiempo acumulado en pausa
ClockData clock_; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
Uint8 items_color_; // Color de la cantidad de items recogidos
SDL_FRect surface_dest_; // Rectangulo donde dibujar la surface del marcador
std::vector<Uint8> color_; // Vector con los colores del objeto
bool is_paused_; // Indica si el marcador esta en modo pausa
Uint32 paused_time_; // Milisegundos que ha estado el marcador en pausa
Uint32 paused_time_elapsed_; // Tiempo acumulado en pausa
ClockData clock_; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
Uint8 items_color_; // Color de la cantidad de items recogidos
SDL_FRect surface_dest_; // Rectangulo donde dibujar la surface del marcador
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones
float items_color_timer_ = 0.0F; // Timer para parpadeo de color de items

View File

@@ -41,7 +41,7 @@ class Stats {
public:
// Constructostd::string nst stdstd::string nst std::string& buffer);
Stats(std::string file, std::string buffer);
// Destructor
~Stats();

View File

@@ -2,19 +2,19 @@
#include <SDL3/SDL.h>
#include <algorithm> // Para find_if
#include <cctype> // Para isspace
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
#include <functional> // Para function
#include <iostream> // Para cout, cerr
#include <algorithm> // Para find_if
#include <cctype> // Para isspace
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
#include <functional> // Para function
#include <iostream> // Para cout, cerr
#include <ranges>
#include <sstream> // Para basic_istringstream
#include <string> // Para char_traits, string, operator<<, hash
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
#include <utility> // Para pair
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
#include "game/defaults.hpp" // Para GameDefaults::VERSION
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
namespace Options {
// Declaración de funciones internas
@@ -145,7 +145,6 @@ auto saveToFile(const std::string& file_path) -> bool {
file << "# Versión de la configuración\n";
file << "version " << version << "\n";
file << "\n## WINDOW\n";
file << "# Zoom de la ventana: 1 = Normal, 2 = Doble, 3 = Triple, ...\n";
file << "window.zoom " << window.zoom << "\n";
@@ -234,4 +233,4 @@ auto setOptions(const std::string& var, const std::string& value) -> bool {
}
return false;
}
}
} // namespace Options

View File

@@ -4,7 +4,9 @@
#include <algorithm> // Para min
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
@@ -40,16 +42,17 @@ Credits::Credits()
}
// Comprueba el manejador de eventos
void Credits::checkEvents() {
void Credits::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
}
}
// Comprueba las entradas
void Credits::checkInput() {
GlobalInputs::check();
void Credits::handleInput() {
Input::get()->update();
GlobalInputs::handle();
}
// Inicializa los textos
@@ -153,24 +156,21 @@ void Credits::fillTexture() {
// Actualiza las variables
void Credits::update() {
// Obtiene el delta time
current_delta_ = delta_timer_->tick();
const float DELTA_TIME = delta_timer_->tick();
total_time_ += DELTA_TIME; // Actualiza el tiempo total
// Comprueba las entradas
checkInput();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
// Actualiza el tiempo total
total_time_ += current_delta_;
// Actualiza la máquina de estados
updateState(current_delta_);
// Actualiza la pantalla
Screen::get()->update(current_delta_);
updateState(DELTA_TIME); // Actualiza la máquina de estados
// Actualiza el sprite con el brillo si está después del tiempo de inicio
if (reveal_time_ > SHINE_START_TIME) {
shining_sprite_->update(current_delta_);
shining_sprite_->update(DELTA_TIME);
}
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
// Transición entre estados
@@ -276,7 +276,6 @@ void Credits::render() {
void Credits::run() {
while (SceneManager::current == SceneManager::Scene::CREDITS) {
update();
checkEvents();
render();
}
}

View File

@@ -33,16 +33,16 @@ class Credits {
};
// --- Constantes de tiempo (basado en 60 FPS) ---
static constexpr float REVEAL_PHASE_1_DURATION = 3.733F; // 224 frames @ 60fps
static constexpr float PAUSE_DURATION = 1.667F; // 100 frames @ 60fps
static constexpr float REVEAL_PHASE_2_DURATION = 5.333F; // 320 frames (544-224) @ 60fps
static constexpr float REVEAL_PHASE_3_DURATION = 2.133F; // 128 frames (672-544) @ 60fps
static constexpr float DISPLAY_WITH_SHINE_DURATION = 7.967F; // 478 frames (1150-672) @ 60fps
static constexpr float FADE_OUT_DURATION = 0.833F; // 50 frames (1200-1150) @ 60fps
static constexpr float TOTAL_DURATION = 20.0F; // 1200 frames @ 60fps
static constexpr float SHINE_START_TIME = 12.833F; // 770 frames @ 60fps
static constexpr float FADE_OUT_START = 19.167F; // 1150 frames @ 60fps
static constexpr float REVEAL_SPEED = 60.0F; // counter equivalente por segundo @ 60fps
static constexpr float REVEAL_PHASE_1_DURATION = 3.733F; // 224 frames @ 60fps
static constexpr float PAUSE_DURATION = 1.667F; // 100 frames @ 60fps
static constexpr float REVEAL_PHASE_2_DURATION = 5.333F; // 320 frames (544-224) @ 60fps
static constexpr float REVEAL_PHASE_3_DURATION = 2.133F; // 128 frames (672-544) @ 60fps
static constexpr float DISPLAY_WITH_SHINE_DURATION = 7.967F; // 478 frames (1150-672) @ 60fps
static constexpr float FADE_OUT_DURATION = 0.833F; // 50 frames (1200-1150) @ 60fps
static constexpr float TOTAL_DURATION = 20.0F; // 1200 frames @ 60fps
static constexpr float SHINE_START_TIME = 12.833F; // 770 frames @ 60fps
static constexpr float FADE_OUT_START = 19.167F; // 1150 frames @ 60fps
static constexpr float REVEAL_SPEED = 60.0F; // counter equivalente por segundo @ 60fps
struct Captions {
std::string label; // Texto a escribir
Uint8 color; // Color del texto
@@ -59,16 +59,15 @@ class Credits {
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
float total_time_ = 0.0F; // Tiempo total acumulado
float reveal_time_ = 0.0F; // Tiempo acumulado solo durante revelación (se congela en pausas)
float current_delta_ = 0.0F; // Delta time del frame actual
std::vector<Captions> texts_; // Vector con los textos
// --- Funciones ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza la máquina de estados
void transitionToState(State new_state); // Transición entre estados
void iniTexts(); // Inicializa los textos
void fillTexture(); // Escribe el texto en la textura
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza la máquina de estados
void transitionToState(State new_state); // Transición entre estados
void iniTexts(); // Inicializa los textos
void fillTexture(); // Escribe el texto en la textura
};

View File

@@ -4,14 +4,15 @@
#include <algorithm> // Para min
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/rendering/text.hpp" // Para Text, TEXT_STROKE
#include "core/resources/resource.hpp" // Para Resource
#include "core/system/global_events.hpp" // Para check
#include "core/audio/audio.hpp" // Para Audio
#include "game/options.hpp" // Para Options, options, OptionsGame, SectionS...
#include "game/scene_manager.hpp" // Para SceneManager
#include "utils/defines.hpp" // Para GAME_SPEED
@@ -46,22 +47,17 @@ Ending::Ending()
// Actualiza el objeto
void Ending::update() {
// Obtiene el delta time
current_delta_ = delta_timer_->tick();
const float DELTA_TIME = delta_timer_->tick();
total_time_ += DELTA_TIME; // Actualiza el tiempo total
// Comprueba las entradas
checkInput();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
// Actualiza el tiempo total
total_time_ += current_delta_;
updateState(DELTA_TIME); // Actualiza la máquina de estados
updateSpriteCovers(); // Actualiza las cortinillas de los elementos
// Actualiza la máquina de estados
updateState(current_delta_);
// Actualiza las cortinillas de los elementos
updateSpriteCovers();
// Actualiza el objeto Screen
Screen::get()->update(current_delta_);
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
// Dibuja el final en pantalla
@@ -98,16 +94,17 @@ void Ending::render() {
}
// Comprueba el manejador de eventos
void Ending::checkEvents() {
void Ending::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
}
}
// Comprueba las entradas
void Ending::checkInput() {
GlobalInputs::check();
void Ending::handleInput() {
Input::get()->update();
GlobalInputs::handle();
}
// Transición entre estados
@@ -424,7 +421,6 @@ void Ending::run() {
while (SceneManager::current == SceneManager::Scene::ENDING) {
update();
checkEvents();
render();
}
@@ -472,8 +468,7 @@ void Ending::updateSpriteCovers() {
0,
sprite_texts_.at(ti.index).cover_clip_desp,
sprite_texts_.at(ti.index).cover_sprite->getWidth(),
sprite_texts_.at(ti.index).cover_clip_height
);
sprite_texts_.at(ti.index).cover_clip_height);
}
}
@@ -496,12 +491,7 @@ void Ending::updateSpriteCovers() {
sprite_pics_.at(current_scene_).cover_sprite->setY(Y_INITIAL + static_cast<int>(CONTENT_PIXELS));
}
sprite_pics_.at(current_scene_).cover_sprite->setClip(
0,
sprite_pics_.at(current_scene_).cover_clip_desp,
sprite_pics_.at(current_scene_).cover_sprite->getWidth(),
sprite_pics_.at(current_scene_).cover_clip_height
);
sprite_pics_.at(current_scene_).cover_sprite->setClip(0, sprite_pics_.at(current_scene_).cover_clip_desp, sprite_pics_.at(current_scene_).cover_sprite->getWidth(), sprite_pics_.at(current_scene_).cover_clip_height);
}
// Comprueba si se ha de cambiar de escena

View File

@@ -31,17 +31,17 @@ class Ending {
};
// --- Constantes de tiempo (basado en 60 FPS) ---
static constexpr float WARMUP_DURATION = 3.333F; // 200 frames @ 60fps
static constexpr float FADEOUT_DURATION = 1.667F; // 100 frames @ 60fps
static constexpr float SCENE_0_DURATION = 16.667F; // 1000 frames @ 60fps
static constexpr float SCENE_1_DURATION = 23.333F; // 1400 frames @ 60fps
static constexpr float SCENE_2_DURATION = 16.667F; // 1000 frames @ 60fps
static constexpr float SCENE_3_DURATION = 13.333F; // 800 frames @ 60fps
static constexpr float SCENE_4_DURATION = 16.667F; // 1000 frames @ 60fps
static constexpr float TEXT_REVEAL_SPEED = 30.0F; // 2px cada 4 frames @ 60fps
static constexpr float IMAGE_REVEAL_SPEED = 60.0F; // 2px cada 2 frames @ 60fps
static constexpr float TEXT_LAPSE = 1.333F; // 80 frames @ 60fps
static constexpr float FADEOUT_START_OFFSET = 1.667F; // Inicio fade-out 100 frames antes del fin
static constexpr float WARMUP_DURATION = 3.333F; // 200 frames @ 60fps
static constexpr float FADEOUT_DURATION = 1.667F; // 100 frames @ 60fps
static constexpr float SCENE_0_DURATION = 16.667F; // 1000 frames @ 60fps
static constexpr float SCENE_1_DURATION = 23.333F; // 1400 frames @ 60fps
static constexpr float SCENE_2_DURATION = 16.667F; // 1000 frames @ 60fps
static constexpr float SCENE_3_DURATION = 13.333F; // 800 frames @ 60fps
static constexpr float SCENE_4_DURATION = 16.667F; // 1000 frames @ 60fps
static constexpr float TEXT_REVEAL_SPEED = 30.0F; // 2px cada 4 frames @ 60fps
static constexpr float IMAGE_REVEAL_SPEED = 60.0F; // 2px cada 2 frames @ 60fps
static constexpr float TEXT_LAPSE = 1.333F; // 80 frames @ 60fps
static constexpr float FADEOUT_START_OFFSET = 1.667F; // Inicio fade-out 100 frames antes del fin
// --- Estructuras ---
struct EndingSurface // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla
@@ -81,25 +81,24 @@ class Ending {
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
float total_time_ = 0.0F; // Tiempo total acumulado desde el inicio
float fadeout_time_ = 0.0F; // Tiempo acumulado para el fade-out
float current_delta_ = 0.0F; // Delta time del frame actual
std::vector<EndingSurface> sprite_texts_; // Vector con los sprites de texto con su cortinilla
std::vector<EndingSurface> sprite_pics_; // Vector con los sprites de texto con su cortinilla
int current_scene_ = 0; // Escena actual (0-4)
std::vector<SceneData> scenes_; // Vector con los textos e imagenes de cada escena
// --- Funciones ---
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void iniTexts(); // Inicializa los textos
void iniPics(); // Inicializa las imagenes
void iniScenes(); // Inicializa las escenas
void updateState(float delta_time); // Actualiza la máquina de estados
void transitionToState(State new_state); // Transición entre estados
void updateSpriteCovers(); // Actualiza las cortinillas de los elementos
void checkChangeScene(); // Comprueba si se ha de cambiar de escena
void fillCoverTexture(); // Rellena la textura para la cortinilla
void renderCoverTexture(); // Dibuja la cortinilla de cambio de escena
void updateMusicVolume() const; // Actualiza el volumen de la musica
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void iniTexts(); // Inicializa los textos
void iniPics(); // Inicializa las imagenes
void iniScenes(); // Inicializa las escenas
void updateState(float delta_time); // Actualiza la máquina de estados
void transitionToState(State new_state); // Transición entre estados
void updateSpriteCovers(); // Actualiza las cortinillas de los elementos
void checkChangeScene(); // Comprueba si se ha de cambiar de escena
void fillCoverTexture(); // Rellena la textura para la cortinilla
void renderCoverTexture(); // Dibuja la cortinilla de cambio de escena
void updateMusicVolume() const; // Actualiza el volumen de la musica
};

View File

@@ -6,6 +6,7 @@
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
@@ -54,20 +55,19 @@ Ending2::Ending2()
// Actualiza el objeto
void Ending2::update() {
// Obtiene el delta time
current_delta_ = delta_timer_->tick();
const float DELTA_TIME = delta_timer_->tick();
// Comprueba las entradas
checkInput();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
// Actualiza el estado
updateState(current_delta_);
updateState(DELTA_TIME); // Actualiza el estado
switch (state_.state) {
case EndingState::CREDITS:
// Actualiza los sprites, los textos y los textos del final
updateSprites(current_delta_);
updateTextSprites(current_delta_);
updateTexts(current_delta_);
updateSprites(DELTA_TIME);
updateTextSprites(DELTA_TIME);
updateTexts(DELTA_TIME);
break;
case EndingState::FADING:
@@ -80,8 +80,8 @@ void Ending2::update() {
break;
}
// Actualiza el objeto
Screen::get()->update(current_delta_);
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
// Dibuja el final en pantalla
@@ -127,16 +127,17 @@ void Ending2::render() {
}
// Comprueba el manejador de eventos
void Ending2::checkEvents() {
void Ending2::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
}
}
// Comprueba las entradas
void Ending2::checkInput() {
GlobalInputs::check();
void Ending2::handleInput() {
Input::get()->update();
GlobalInputs::handle();
}
// Bucle principal
@@ -145,7 +146,6 @@ void Ending2::run() {
while (SceneManager::current == SceneManager::Scene::ENDING2) {
update();
checkEvents();
render();
}

View File

@@ -50,11 +50,11 @@ class Ending2 {
static constexpr int TEXT_SPACING_MULTIPLIER = 2; // Multiplicador para espaciado entre líneas de texto
// Constantes de tiempo (basadas en tiempo real, no en frames)
static constexpr float SPRITE_DESP_SPEED = -12.0F; // Velocidad de desplazamiento en pixels/segundo (era -0.2 px/frame @ 60fps)
static constexpr float STATE_PRE_CREDITS_DURATION = 3.0F; // Duración del estado previo a créditos en segundos
static constexpr float STATE_POST_CREDITS_DURATION = 5.0F; // Duración del estado posterior a créditos en segundos
static constexpr float STATE_FADE_DURATION = 5.0F; // Duración del fade final en segundos
static constexpr int MUSIC_FADE_DURATION = 3000; // Duración del fade de música en milisegundos (para Audio API)
static constexpr float SPRITE_DESP_SPEED = -12.0F; // Velocidad de desplazamiento en pixels/segundo (era -0.2 px/frame @ 60fps)
static constexpr float STATE_PRE_CREDITS_DURATION = 3.0F; // Duración del estado previo a créditos en segundos
static constexpr float STATE_POST_CREDITS_DURATION = 5.0F; // Duración del estado posterior a créditos en segundos
static constexpr float STATE_FADE_DURATION = 5.0F; // Duración del fade final en segundos
static constexpr int MUSIC_FADE_DURATION = 3000; // Duración del fade de música en milisegundos (para Audio API)
// --- Objetos y punteros ---
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar
@@ -68,26 +68,25 @@ class Ending2 {
float sprite_max_width_ = 0; // El valor de ancho del sprite mas ancho
float sprite_max_height_ = 0; // El valor de alto del sprite mas alto
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
float current_delta_ = 0.0F; // Delta time del frame actual
State state_; // Controla el estado de la clase
// --- Fucniones ---
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado
void transitionToState(EndingState new_state); // Transición entre estados
void iniSpriteList(); // Inicializa la lista de sprites
void loadSprites(); // Carga todos los sprites desde una lista
void updateSprites(float delta); // Actualiza los sprites
void updateTextSprites(float delta); // Actualiza los sprites de texto
void updateTexts(float delta); // Actualiza los sprites de texto del final
void renderSprites(); // Dibuja los sprites
void renderSpriteTexts(); // Dibuja los sprites con el texto
void renderTexts(); // Dibuja los sprites con el texto del final
void placeSprites(); // Coloca los sprites en su sito
void createSpriteTexts(); // Crea los sprites con las texturas con los textos
void createTexts(); // Crea los sprites con las texturas con los textos del final
void updateFinalFade(); // Actualiza el fade final
void iniSpriteList(); // Inicializa la lista de sprites
void loadSprites(); // Carga todos los sprites desde una lista
void updateSprites(float delta); // Actualiza los sprites
void updateTextSprites(float delta); // Actualiza los sprites de texto
void updateTexts(float delta); // Actualiza los sprites de texto del final
void renderSprites(); // Dibuja los sprites
void renderSpriteTexts(); // Dibuja los sprites con el texto
void renderTexts(); // Dibuja los sprites con el texto del final
void placeSprites(); // Coloca los sprites en su sito
void createSpriteTexts(); // Crea los sprites con las texturas con los textos
void createTexts(); // Crea los sprites con las texturas con los textos del final
void updateFinalFade(); // Actualiza el fade final
};

View File

@@ -5,8 +5,9 @@
#include <utility>
#include <vector> // Para vector
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
@@ -14,7 +15,6 @@
#include "core/resources/resource.hpp" // Para ResourceRoom, Resource
#include "core/system/debug.hpp" // Para Debug
#include "core/system/global_events.hpp" // Para check
#include "core/audio/audio.hpp" // Para Audio
#include "game/gameplay/cheevos.hpp" // Para Cheevos
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
#include "game/gameplay/room.hpp" // Para Room, RoomData
@@ -69,30 +69,32 @@ Game::~Game() {
}
// Comprueba los eventos de la cola
void Game::checkEvents() {
void Game::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
#ifdef _DEBUG
checkDebugEvents(event);
handleDebugEvents(event);
#endif
}
}
// Comprueba el teclado
void Game::checkInput() {
if (Input::get()->checkInput(InputAction::TOGGLE_MUSIC, INPUT_DO_NOT_ALLOW_REPEAT)) {
void Game::handleInput() {
Input::get()->update();
if (Input::get()->checkAction(InputAction::TOGGLE_MUSIC, Input::DO_NOT_ALLOW_REPEAT)) {
board_->music = !board_->music;
board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) {
togglePause();
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
}
GlobalInputs::check();
GlobalInputs::handle();
}
// Bucle para el juego
@@ -104,7 +106,6 @@ void Game::run() {
while (SceneManager::current == SceneManager::Scene::GAME || SceneManager::current == SceneManager::Scene::DEMO) {
update();
checkEvents();
render();
}
@@ -118,8 +119,8 @@ void Game::update() {
// Calcula el delta time
const float DELTA_TIME = delta_timer_.tick();
// Comprueba el teclado
checkInput();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
#ifdef _DEBUG
Debug::get()->clear();
@@ -143,7 +144,8 @@ void Game::update() {
keepMusicPlaying();
updateBlackScreen(DELTA_TIME);
Screen::get()->update(DELTA_TIME);
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
#ifdef _DEBUG
updateDebugInfo();
@@ -213,7 +215,7 @@ void Game::renderDebugInfo() {
}
// Comprueba los eventos
void Game::checkDebugEvents(const SDL_Event& event) {
void Game::handleDebugEvents(const SDL_Event& event) {
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
switch (event.key.key) {
case SDL_SCANCODE_G:
@@ -588,8 +590,8 @@ void Game::keepMusicPlaying() {
// Si la música no está sonando
if (Audio::get()->getMusicState() == Audio::MusicState::STOPPED) {
Audio::get()->playMusic(MUSIC_PATH);
}
Audio::get()->playMusic(MUSIC_PATH);
}
}
// DEMO MODE: Inicializa las variables para el modo demo

View File

@@ -82,10 +82,10 @@ class Game {
// --- Funciones ---
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
void render(); // Pinta los objetos en pantalla
void checkEvents(); // Comprueba los eventos de la cola
void handleEvents(); // Comprueba los eventos de la cola
void renderRoomName(); // Escribe el nombre de la pantalla
auto changeRoom(const std::string& room_path) -> bool; // Cambia de habitación
void checkInput(); // Comprueba el teclado
void handleInput(); // Comprueba el teclado
void checkPlayerIsOnBorder(); // Comprueba si el jugador esta en el borde de la pantalla y actua
auto checkPlayerAndEnemies() -> bool; // Comprueba las colisiones del jugador con los enemigos
void checkPlayerAndItems(); // Comprueba las colisiones del jugador con los objetos
@@ -110,8 +110,8 @@ class Game {
void demoInit(); // DEMO MODE: Inicializa las variables para el modo demo
void demoCheckRoomChange(float delta_time); // DEMO MODE: Comprueba si se ha de cambiar de habitación
#ifdef _DEBUG
void updateDebugInfo(); // Pone la información de debug en pantalla
static void renderDebugInfo(); // Pone la información de debug en pantalla
void checkDebugEvents(const SDL_Event& event); // Comprueba los eventos
void updateDebugInfo(); // Pone la información de debug en pantalla
static void renderDebugInfo(); // Pone la información de debug en pantalla
void handleDebugEvents(const SDL_Event& event); // Comprueba los eventos
#endif
};

View File

@@ -5,13 +5,14 @@
#include <algorithm> // Para min, max
#include <string> // Para basic_string, operator+, to_string
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
#include "core/resources/resource.hpp" // Para Resource
#include "core/system/global_events.hpp" // Para check
#include "core/audio/audio.hpp" // Para Audio
#include "game/options.hpp" // Para Options, options, OptionsStats, Secti...
#include "game/scene_manager.hpp" // Para SceneManager
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X
@@ -45,24 +46,19 @@ GameOver::GameOver()
// Actualiza el objeto
void GameOver::update() {
// Obtiene el delta time desde el último frame
const float delta = delta_timer_->tick();
elapsed_time_ += delta;
const float DELTA_TIME = delta_timer_->tick();
elapsed_time_ += DELTA_TIME;
// Comprueba las entradas
checkInput();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
// Actualiza el estado de la escena
updateState();
updateState(); // Actualiza el estado de la escena
updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
player_sprite_->update(DELTA_TIME); // Actualiza el sprite
tv_sprite_->update(DELTA_TIME); // Actualiza el sprite
// Actualiza el color usado para renderizar los textos e imagenes
updateColor();
// Actualiza los dos sprites con delta time
player_sprite_->update(delta);
tv_sprite_->update(delta);
// Actualiza el objeto Screen
Screen::get()->update(delta);
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
// Dibuja el final en pantalla
@@ -95,23 +91,23 @@ void GameOver::render() {
}
// Comprueba el manejador de eventos
void GameOver::checkEvents() {
void GameOver::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
}
}
// Comprueba las entradas
void GameOver::checkInput() {
GlobalInputs::check();
void GameOver::handleInput() {
Input::get()->update();
GlobalInputs::handle();
}
// Bucle principal
void GameOver::run() {
while (SceneManager::current == SceneManager::Scene::GAME_OVER) {
update();
checkEvents();
render();
}
}

View File

@@ -19,35 +19,35 @@ class GameOver {
private:
// --- Estados ---
enum class State {
WAITING, // Espera inicial antes de empezar
FADE_IN, // Fade in de colores desde black
DISPLAY, // Mostrando contenido con color brillante
FADE_OUT, // Fade out hacia black
ENDING, // Pantalla en negro antes de salir
TRANSITION // Cambio a logo
WAITING, // Espera inicial antes de empezar
FADE_IN, // Fade in de colores desde black
DISPLAY, // Mostrando contenido con color brillante
FADE_OUT, // Fade out hacia black
ENDING, // Pantalla en negro antes de salir
TRANSITION // Cambio a logo
};
// --- Constantes de Duración (segundos) ---
static constexpr float WAITING_DURATION = 0.8f; // Espera inicial
static constexpr float FADE_IN_DURATION = 0.32f; // Duración del fade in
static constexpr float DISPLAY_DURATION = 4.64f; // Duración mostrando contenido
static constexpr float FADE_OUT_DURATION = 0.32f; // Duración del fade out
static constexpr float ENDING_DURATION = 1.12f; // Espera en negro antes de salir
static constexpr float WAITING_DURATION = 0.8f; // Espera inicial
static constexpr float FADE_IN_DURATION = 0.32f; // Duración del fade in
static constexpr float DISPLAY_DURATION = 4.64f; // Duración mostrando contenido
static constexpr float FADE_OUT_DURATION = 0.32f; // Duración del fade out
static constexpr float ENDING_DURATION = 1.12f; // Espera en negro antes de salir
// --- Constantes de Posición ---
static constexpr int TEXT_Y = 32; // Posición Y del texto principal
static constexpr int SPRITE_Y_OFFSET = 30; // Offset Y para sprites desde TEXT_Y
static constexpr int PLAYER_X_OFFSET = 10; // Offset X del jugador desde el centro
static constexpr int TV_X_OFFSET = 10; // Offset X del TV desde el centro
static constexpr int ITEMS_Y_OFFSET = 80; // Offset Y del texto de items desde TEXT_Y
static constexpr int ROOMS_Y_OFFSET = 90; // Offset Y del texto de rooms desde TEXT_Y
static constexpr int NIGHTMARE_TITLE_Y_OFFSET = 110; // Offset Y del título nightmare desde TEXT_Y
static constexpr int NIGHTMARE_TEXT_Y_OFFSET = 120; // Offset Y del texto nightmare desde TEXT_Y
static constexpr int TEXT_Y = 32; // Posición Y del texto principal
static constexpr int SPRITE_Y_OFFSET = 30; // Offset Y para sprites desde TEXT_Y
static constexpr int PLAYER_X_OFFSET = 10; // Offset X del jugador desde el centro
static constexpr int TV_X_OFFSET = 10; // Offset X del TV desde el centro
static constexpr int ITEMS_Y_OFFSET = 80; // Offset Y del texto de items desde TEXT_Y
static constexpr int ROOMS_Y_OFFSET = 90; // Offset Y del texto de rooms desde TEXT_Y
static constexpr int NIGHTMARE_TITLE_Y_OFFSET = 110; // Offset Y del título nightmare desde TEXT_Y
static constexpr int NIGHTMARE_TEXT_Y_OFFSET = 120; // Offset Y del texto nightmare desde TEXT_Y
// --- Objetos y punteros ---
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite con el jugador
std::shared_ptr<SurfaceAnimatedSprite> tv_sprite_; // Sprite con el televisor
std::shared_ptr<DeltaTimer> delta_timer_; // Timer para time-based logic
std::shared_ptr<DeltaTimer> delta_timer_; // Timer para time-based logic
// --- Variables ---
State state_ = State::WAITING; // Estado actual de la escena
@@ -56,11 +56,11 @@ class GameOver {
Uint8 color_; // Color usado para el texto y los sprites
// --- Funciones ---
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void updateState(); // Actualiza el estado y transiciones
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
void renderSprites(); // Dibuja los sprites
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(); // Actualiza el estado y transiciones
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
void renderSprites(); // Dibuja los sprites
};

View File

@@ -6,6 +6,7 @@
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
@@ -49,16 +50,17 @@ LoadingScreen::~LoadingScreen() {
}
// Comprueba el manejador de eventos
void LoadingScreen::checkEvents() {
void LoadingScreen::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
}
}
// Comprueba las entradas
void LoadingScreen::checkInput() {
GlobalInputs::check();
void LoadingScreen::handleInput() {
Input::get()->update();
GlobalInputs::handle();
}
// Inicializa el array de índices de líneas (imita el direccionamiento de memoria del Spectrum)
@@ -323,7 +325,9 @@ void LoadingScreen::update() {
// Obtener delta time desde el último frame
const float DELTA_TIME = delta_timer_->tick();
checkInput(); // Comprueba las entradas
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
// Actualizar la carga según el estado actual
@@ -352,8 +356,8 @@ void LoadingScreen::update() {
}
// Singletones
Audio::update(); // Actualiza el objeto Audio
Screen::get()->update(); // Actualiza el objeto Screen
Audio::update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
// Dibuja en pantalla
@@ -384,7 +388,6 @@ void LoadingScreen::run() {
while (SceneManager::current == SceneManager::Scene::LOADING_SCREEN) {
update();
checkEvents();
render();
}

View File

@@ -77,8 +77,8 @@ class LoadingScreen {
// --- Funciones ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(State new_state); // Transiciona a un nuevo estado
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based)

View File

@@ -4,7 +4,9 @@
#include <algorithm> // Para std::clamp
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
@@ -39,16 +41,17 @@ Logo::Logo()
}
// Comprueba el manejador de eventos
void Logo::checkEvents() {
void Logo::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
}
}
// Comprueba las entradas
void Logo::checkInput() {
GlobalInputs::check();
void Logo::handleInput() {
Input::get()->update();
GlobalInputs::handle();
}
// Gestiona el logo de JAILGAME (time-based)
@@ -180,10 +183,14 @@ void Logo::update() {
// Obtener delta time desde el último frame
const float DELTA_TIME = delta_timer_->tick();
checkInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
updateTextureColors(); // Gestiona el color de las texturas
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
updateTextureColors(); // Gestiona el color de las texturas
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
@@ -207,7 +214,6 @@ void Logo::render() {
void Logo::run() {
while (SceneManager::current == SceneManager::Scene::LOGO) {
update();
checkEvents();
render();
}
}

View File

@@ -57,8 +57,8 @@ class Logo {
// --- Funciones ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
void updateTextureColors(); // Gestiona el color de las texturas
void updateState(float delta_time); // Actualiza el estado actual

View File

@@ -4,8 +4,9 @@
#include <algorithm> // Para clamp
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/global_inputs.hpp" // Para check
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT, REP...
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT, REP...
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
@@ -30,8 +31,7 @@ Title::Title()
first_active_letter_(0),
last_active_letter_(0),
state_time_(0.0F),
fade_accumulator_(0.0F),
current_delta_(0.0F) {
fade_accumulator_(0.0F) {
// Inicializa variables
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? State::SHOW_LOADING_SCREEN : State::SHOW_MENU;
SceneManager::current = SceneManager::Scene::TITLE;
@@ -72,10 +72,10 @@ void Title::initMarquee() {
}
// Comprueba el manejador de eventos
void Title::checkEvents() {
void Title::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::check(event);
GlobalEvents::handle(event);
// Solo se comprueban estas teclas si no está activo el menu de logros
if (event.type == SDL_EVENT_KEY_DOWN) {
@@ -99,24 +99,26 @@ void Title::checkEvents() {
}
// Comprueba las entradas
void Title::checkInput() {
void Title::handleInput(float delta_time) {
Input::get()->update();
if (show_cheevos_) {
if (Input::get()->checkInput(InputAction::DOWN, INPUT_ALLOW_REPEAT)) {
moveCheevosList(1, current_delta_);
} else if (Input::get()->checkInput(InputAction::UP, INPUT_ALLOW_REPEAT)) {
moveCheevosList(0, current_delta_);
} else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
if (Input::get()->checkAction(InputAction::RIGHT, Input::ALLOW_REPEAT)) {
moveCheevosList(1, delta_time);
} else if (Input::get()->checkAction(InputAction::LEFT, Input::ALLOW_REPEAT)) {
moveCheevosList(0, delta_time);
} else if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
hideCheevosList();
}
}
if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
if (state_ == State::SHOW_LOADING_SCREEN) {
transitionToState(State::FADE_LOADING_SCREEN);
}
}
GlobalInputs::check();
GlobalInputs::handle();
}
// Actualiza la marquesina
@@ -169,16 +171,15 @@ void Title::renderMarquee() {
// Actualiza las variables
void Title::update() {
// Obtener delta time
current_delta_ = delta_timer_->tick();
const float DELTA_TIME = delta_timer_->tick();
// Comprueba las entradas
checkInput();
handleEvents(); // Comprueba los eventos
handleInput(DELTA_TIME); // Comprueba las entradas
// Actualiza la pantalla
Screen::get()->update(current_delta_);
updateState(DELTA_TIME); // Actualiza el estado actual
// Actualiza el estado actual
updateState(current_delta_);
Audio::get()->update(); // Actualiza el objeto Audio
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
}
// Actualiza el estado actual
@@ -263,7 +264,6 @@ void Title::render() {
void Title::run() {
while (SceneManager::current == SceneManager::Scene::TITLE) {
update();
checkEvents();
render();
}
}

View File

@@ -69,13 +69,12 @@ class Title {
State state_; // Estado en el que se encuentra el bucle principal
float state_time_; // Tiempo acumulado en el estado actual
float fade_accumulator_; // Acumulador para controlar el fade por tiempo
float current_delta_; // Delta time del frame actual
// --- Funciones ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
void checkEvents(); // Comprueba el manejador de eventos
void checkInput(); // Comprueba las entradas
void handleEvents(); // Comprueba el manejador de eventos
void handleInput(float delta_time); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(State new_state); // Transiciona a un nuevo estado
void initMarquee(); // Inicializa la marquesina

View File

@@ -8,12 +8,12 @@
#include <string> // Para string, basic_string
#include <vector> // Para vector
#include "core/audio/audio.hpp" // Para Audio
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/surface.hpp" // Para Surface
#include "core/rendering/surface_sprite.hpp" // Para SSprite
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
#include "core/resources/resource.hpp" // Para Resource
#include "core/audio/audio.hpp" // Para Audio
#include "game/options.hpp" // Para Options, options, NotificationPosition
#include "utils/delta_timer.hpp" // Para DeltaTimer
#include "utils/utils.hpp" // Para PaletteColor

View File

@@ -62,8 +62,8 @@ class Notifier {
explicit Notification() = default;
};
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
std::shared_ptr<Text> text_; // Objeto para dibujar texto
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
std::shared_ptr<Text> text_; // Objeto para dibujar texto
std::unique_ptr<DeltaTimer> delta_timer_; // Timer for frame-independent animations
// Variables

View File

@@ -1,27 +1,28 @@
#pragma once
#include <SDL3/SDL.h>
#include <algorithm>
class DeltaTimer {
public:
DeltaTimer() noexcept;
public:
DeltaTimer() noexcept;
// Calcula delta en segundos y actualiza el contador interno
auto tick() noexcept -> float;
// Calcula delta en segundos y actualiza el contador interno
auto tick() noexcept -> float;
// Devuelve el delta estimado desde el último tick sin actualizar el contador
[[nodiscard]] auto peek() const noexcept -> float;
// Devuelve el delta estimado desde el último tick sin actualizar el contador
[[nodiscard]] auto peek() const noexcept -> float;
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
void reset(Uint64 counter = 0) noexcept;
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
void reset(Uint64 counter = 0) noexcept;
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
void setTimeScale(float scale) noexcept;
[[nodiscard]] auto getTimeScale() const noexcept -> float;
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
void setTimeScale(float scale) noexcept;
[[nodiscard]] auto getTimeScale() const noexcept -> float;
private:
Uint64 last_counter_;
double perf_freq_;
float time_scale_;
private:
Uint64 last_counter_;
double perf_freq_;
float time_scale_;
};