forked from jaildesigner-jailgames/jaildoctors_dilemma
migrat Input a la ultima versió
cohesionats tots els metodes update de les escenes
This commit is contained in:
@@ -42,6 +42,7 @@ set(APP_SOURCES
|
|||||||
# Core - Input
|
# Core - Input
|
||||||
source/core/input/global_inputs.cpp
|
source/core/input/global_inputs.cpp
|
||||||
source/core/input/input.cpp
|
source/core/input/input.cpp
|
||||||
|
source/core/input/input_types.cpp
|
||||||
source/core/input/mouse.cpp
|
source/core/input/mouse.cpp
|
||||||
|
|
||||||
# Core - Rendering
|
# Core - Rendering
|
||||||
|
|||||||
1
Makefile
1
Makefile
@@ -64,6 +64,7 @@ APP_SOURCES := \
|
|||||||
source/main.cpp \
|
source/main.cpp \
|
||||||
source/core/audio/audio.cpp \
|
source/core/audio/audio.cpp \
|
||||||
source/core/input/input.cpp \
|
source/core/input/input.cpp \
|
||||||
|
source/core/input/input_types.cpp \
|
||||||
source/core/input/mouse.cpp \
|
source/core/input/mouse.cpp \
|
||||||
source/core/input/global_inputs.cpp \
|
source/core/input/global_inputs.cpp \
|
||||||
source/core/rendering/screen.cpp \
|
source/core/rendering/screen.cpp \
|
||||||
|
|||||||
@@ -64,7 +64,6 @@ void Audio::playMusic(const std::string& name, const int loop) {
|
|||||||
music_.state = MusicState::PLAYING;
|
music_.state = MusicState::PLAYING;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Pausa la música
|
// Pausa la música
|
||||||
void Audio::pauseMusic() {
|
void Audio::pauseMusic() {
|
||||||
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
||||||
|
|||||||
134
source/core/input/gamepad_config_manager.hpp
Normal file
134
source/core/input/gamepad_config_manager.hpp
Normal 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();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
|
||||||
|
|
||||||
#include "core/input/global_inputs.hpp"
|
#include "core/input/global_inputs.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
@@ -7,9 +5,10 @@
|
|||||||
#include <string> // Para allocator, operator+, char_traits, string
|
#include <string> // Para allocator, operator+, char_traits, string
|
||||||
#include <vector> // Para vector
|
#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 "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 "game/ui/notifier.hpp" // Para Notifier, NotificationText
|
||||||
#include "utils/utils.hpp" // Para stringInVector
|
#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
|
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||||
void check() {
|
void handle() {
|
||||||
if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
quit();
|
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();
|
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();
|
Screen::get()->toggleBorder();
|
||||||
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
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();
|
Screen::get()->toggleVideoMode();
|
||||||
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
|
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()) {
|
if (Screen::get()->decWindowZoom()) {
|
||||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
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()) {
|
if (Screen::get()->incWindowZoom()) {
|
||||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
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();
|
Screen::get()->toggleShaders();
|
||||||
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
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();
|
Screen::get()->nextPalette();
|
||||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
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();
|
Screen::get()->previousPalette();
|
||||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
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()->toggleIntegerScale();
|
||||||
Screen::get()->setVideoMode(Options::video.fullscreen);
|
Screen::get()->setVideoMode(Options::video.fullscreen);
|
||||||
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
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();
|
Screen::get()->toggleDebugInfo();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,5 +2,5 @@
|
|||||||
|
|
||||||
namespace GlobalInputs {
|
namespace GlobalInputs {
|
||||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||||
void check();
|
void handle();
|
||||||
} // namespace GlobalInputs
|
} // namespace GlobalInputs
|
||||||
@@ -1,114 +1,79 @@
|
|||||||
#include "core/input/input.hpp"
|
#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, cerr
|
||||||
#include <iostream> // Para basic_ostream, operator<<, cout, endl
|
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
|
||||||
#include <iterator> // Para distance
|
#include <ranges> // Para __find_if_fn, find_if
|
||||||
#include <unordered_map> // Para unordered_map, operator==, _Node_cons...
|
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair, move
|
||||||
|
|
||||||
// [SINGLETON]
|
// Singleton
|
||||||
Input* Input::input = nullptr;
|
Input* Input::instance = nullptr;
|
||||||
|
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
// Inicializa la instancia única del singleton
|
||||||
void Input::init(const std::string& game_controller_db_path) {
|
void Input::init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file) {
|
||||||
Input::input = new Input(game_controller_db_path);
|
Input::instance = new Input(game_controller_db_path, gamepad_configs_file);
|
||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
// Libera la instancia
|
||||||
void Input::destroy() {
|
void Input::destroy() { delete Input::instance; }
|
||||||
delete Input::input;
|
|
||||||
}
|
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// Obtiene la instancia
|
||||||
auto Input::get() -> Input* {
|
auto Input::get() -> Input* { return Input::instance; }
|
||||||
return Input::input;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Input::Input(const std::string& game_controller_db_path)
|
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
|
||||||
: game_controller_db_path_(game_controller_db_path) {
|
: gamepad_mappings_file_(std::move(game_controller_db_path)),
|
||||||
// Busca si hay mandos conectados
|
gamepad_configs_file_(std::move(gamepad_configs_file)) {
|
||||||
discoverGameControllers();
|
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
||||||
|
initSDLGamePad();
|
||||||
// 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};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a teclas
|
// Asigna inputs a teclas
|
||||||
void Input::bindKey(InputAction input, SDL_Scancode code) {
|
void Input::bindKey(Action action, SDL_Scancode code) {
|
||||||
key_bindings_.at(static_cast<int>(input)).scancode = code;
|
keyboard_.bindings[action].scancode = code;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button) {
|
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button) {
|
||||||
if (controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = button;
|
gamepad->bindings[action].button = button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source) {
|
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source) {
|
||||||
if (controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
|
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si alguna acción está activa
|
||||||
auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) -> bool {
|
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||||
bool success_keyboard = false;
|
bool success_keyboard = false;
|
||||||
bool success_controller = false;
|
bool success_controller = false;
|
||||||
const int INPUT_INDEX = static_cast<int>(input);
|
|
||||||
|
|
||||||
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
|
if (check_keyboard) {
|
||||||
const auto* key_states = SDL_GetKeyboardState(nullptr);
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||||
|
success_keyboard = keyboard_.bindings[action].is_held;
|
||||||
if (repeat) {
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||||
success_keyboard = static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0;
|
success_keyboard = keyboard_.bindings[action].just_pressed;
|
||||||
} 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 (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) {
|
success_controller = checkAxisInput(action, gamepad, repeat);
|
||||||
success_controller = checkAxisInput(input, controller_index, repeat);
|
|
||||||
|
|
||||||
if (!success_controller) {
|
if (!success_controller) {
|
||||||
if (repeat) {
|
success_controller = checkTriggerInput(action, gamepad, 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) {
|
||||||
|
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);
|
return (success_keyboard || success_controller);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay almenos una acción activa
|
||||||
auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool {
|
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||||
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
|
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
||||||
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
|
||||||
|
|
||||||
for (auto& key_binding : key_bindings_) {
|
// --- Comprobación del Teclado ---
|
||||||
if (static_cast<int>(key_states[key_binding.scancode]) != 0 && !key_binding.active) {
|
if (check_keyboard) {
|
||||||
key_binding.active = true;
|
for (const auto& pair : keyboard_.bindings) {
|
||||||
return true;
|
// 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()) {
|
// --- Comprobación del Mando ---
|
||||||
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) {
|
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
||||||
for (int i = 0; i < (int)controller_bindings_.size(); ++i) {
|
if (gamepad != nullptr) {
|
||||||
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button)) != 0 && !controller_bindings_[controller_index][i].active) {
|
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
||||||
controller_bindings_[controller_index][i].active = true;
|
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;
|
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;
|
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
|
// 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
|
// 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
|
// 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
|
// Obtiene el gamepad a partir de un event.id
|
||||||
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
|
||||||
for (int i = 0; i < num_joysticks_; ++i) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
if (gamepad->instance_id == id) {
|
||||||
return i;
|
return gamepad;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
|
||||||
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
|
for (const auto& gamepad : gamepads_) {
|
||||||
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
if (gamepad && gamepad->name == name) {
|
||||||
|
return gamepad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
// Obtiene el SDL_GamepadButton asignado a un action
|
||||||
auto Input::getIndexByName(const std::string& name) const -> int {
|
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
|
||||||
auto it = std::ranges::find(controller_names_, name);
|
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
|
||||||
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// 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
|
// Umbral para considerar el eje como activo
|
||||||
const Sint16 THRESHOLD = 30000;
|
|
||||||
bool axis_active_now = false;
|
bool axis_active_now = false;
|
||||||
|
|
||||||
switch (input) {
|
switch (action) {
|
||||||
case InputAction::LEFT:
|
case Action::LEFT:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
||||||
break;
|
break;
|
||||||
case InputAction::RIGHT:
|
case Action::RIGHT:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_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;
|
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Referencia al binding correspondiente
|
// Referencia al binding correspondiente
|
||||||
auto& binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));
|
auto& binding = gamepad->bindings[action];
|
||||||
|
|
||||||
if (repeat) {
|
if (repeat) {
|
||||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||||
@@ -285,3 +211,289 @@ auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
|
|||||||
// Mantener el estado actual
|
// Mantener el estado actual
|
||||||
return false;
|
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;
|
||||||
|
}
|
||||||
@@ -1,138 +1,194 @@
|
|||||||
#pragma once
|
#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 <array> // Para array
|
||||||
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
|
#include <unordered_map> // Para unordered_map
|
||||||
|
#include <utility> // Para pair
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
// Definiciones de repetición
|
#include "core/input/gamepad_config_manager.hpp" // for GamepadConfig (ptr only), GamepadConfigs
|
||||||
constexpr bool INPUT_ALLOW_REPEAT = true;
|
#include "core/input/input_types.hpp" // for InputAction
|
||||||
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
|
|
||||||
};
|
|
||||||
|
|
||||||
|
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
|
||||||
class Input {
|
class Input {
|
||||||
private:
|
public:
|
||||||
// [SINGLETON] Objeto privado
|
// --- Constantes ---
|
||||||
static Input* input;
|
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 {
|
// --- Tipos ---
|
||||||
|
using Action = InputAction; // Alias para mantener compatibilidad
|
||||||
|
|
||||||
|
// --- Estructuras ---
|
||||||
|
struct KeyState {
|
||||||
Uint8 scancode; // Scancode asociado
|
Uint8 scancode; // Scancode asociado
|
||||||
bool active; // Indica si está activo
|
bool is_held; // Está pulsada ahora mismo
|
||||||
|
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||||
|
|
||||||
// Constructor
|
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
|
||||||
explicit KeyBindings(Uint8 sc = 0, bool act = false)
|
: scancode(scancode),
|
||||||
: scancode(sc),
|
is_held(is_held),
|
||||||
active(act) {}
|
just_pressed(just_pressed) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ControllerBindings {
|
struct ButtonState {
|
||||||
SDL_GamepadButton button; // GameControllerButton asociado
|
int button; // GameControllerButton asociado
|
||||||
bool active; // Indica si está activo
|
bool is_held; // Está pulsada ahora mismo
|
||||||
|
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||||
bool axis_active; // Estado del eje
|
bool axis_active; // Estado del eje
|
||||||
|
bool trigger_active{false}; // Estado del trigger como botón digital
|
||||||
|
|
||||||
// Constructor
|
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
|
||||||
explicit ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false)
|
|
||||||
: button(btn),
|
: button(btn),
|
||||||
active(act),
|
is_held(is_held),
|
||||||
|
just_pressed(just_pressed),
|
||||||
axis_active(axis_act) {}
|
axis_active(axis_act) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Variables
|
struct Keyboard {
|
||||||
std::vector<SDL_Gamepad*> connected_controllers_; // Vector con todos los mandos conectados
|
std::unordered_map<Action, KeyState> bindings;
|
||||||
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
|
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
Keyboard()
|
||||||
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool;
|
: bindings{
|
||||||
|
// Movimiento del jugador
|
||||||
|
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
|
||||||
|
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
|
||||||
|
{Action::JUMP, KeyState(SDL_SCANCODE_UP)},
|
||||||
|
|
||||||
// Constructor
|
// Inputs de control
|
||||||
explicit Input(const std::string& game_controller_db_path);
|
{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
|
// Inputs de sistema
|
||||||
~Input() = default;
|
{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:
|
struct Gamepad {
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
SDL_Gamepad* pad;
|
||||||
static void init(const std::string& game_controller_db_path);
|
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();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
|
||||||
static auto get() -> Input*;
|
static auto get() -> Input*;
|
||||||
|
|
||||||
// Asigna inputs a teclas
|
// --- Métodos de configuración de controles ---
|
||||||
void bindKey(InputAction input, SDL_Scancode code);
|
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
|
// --- Métodos de consulta de entrada ---
|
||||||
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
|
void update();
|
||||||
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source);
|
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
|
// --- Métodos de gestión de mandos ---
|
||||||
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
|
|
||||||
[[nodiscard]] auto gameControllerFound() const -> bool;
|
[[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
|
// --- Métodos de consulta y utilidades ---
|
||||||
[[nodiscard]] auto getNumControllers() const -> int;
|
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
|
||||||
|
|
||||||
// Obten el nombre de un mando de juego
|
// --- Métodos de reseteo de estado de entrada ---
|
||||||
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string;
|
void resetInputStates();
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// --- Eventos ---
|
||||||
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int;
|
auto handleEvent(const SDL_Event& event) -> std::string;
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
void printConnectedGamepads() const;
|
||||||
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton;
|
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
|
||||||
[[nodiscard]] auto getIndexByName(const std::string& name) const -> int;
|
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;
|
||||||
};
|
};
|
||||||
76
source/core/input/input_types.cpp
Normal file
76
source/core/input/input_types.cpp
Normal 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)}};
|
||||||
42
source/core/input/input_types.hpp
Normal file
42
source/core/input/input_types.hpp
Normal 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
|
||||||
@@ -55,8 +55,7 @@ inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int co
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Agrega una nueva entrada al diccionario
|
// Agrega una nueva entrada al diccionario
|
||||||
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind,
|
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind, int& code_length, int prev, int code) {
|
||||||
int& code_length, int prev, int code) {
|
|
||||||
uint8_t first_byte;
|
uint8_t first_byte;
|
||||||
if (code == dictionary_ind) {
|
if (code == dictionary_ind) {
|
||||||
first_byte = findFirstByte(dictionary, prev);
|
first_byte = findFirstByte(dictionary, prev);
|
||||||
|
|||||||
@@ -209,13 +209,6 @@ void Screen::toggleShaders() {
|
|||||||
initShaders();
|
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)
|
// Actualiza la lógica de la clase (versión nueva con delta_time para escenas migradas)
|
||||||
void Screen::update(float delta_time) {
|
void Screen::update(float delta_time) {
|
||||||
fps_.calculate(SDL_GetTicks());
|
fps_.calculate(SDL_GetTicks());
|
||||||
|
|||||||
@@ -153,7 +153,6 @@ class Screen {
|
|||||||
void render();
|
void render();
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// 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)
|
void update(float delta_time); // Para escenas migradas (con delta_time)
|
||||||
|
|
||||||
// Establece el modo de video
|
// Establece el modo de video
|
||||||
|
|||||||
@@ -60,7 +60,6 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(const Animations& animations)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
|
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
|
||||||
: SurfaceMovingSprite(std::move(surface)) {
|
: SurfaceMovingSprite(std::move(surface)) {
|
||||||
@@ -105,8 +104,7 @@ void SurfaceAnimatedSprite::animate(float delta_time) {
|
|||||||
// Calcula el frame actual a partir del tiempo acumulado
|
// Calcula el frame actual a partir del tiempo acumulado
|
||||||
const int TARGET_FRAME = static_cast<int>(
|
const int TARGET_FRAME = static_cast<int>(
|
||||||
animations_[current_animation_].accumulated_time /
|
animations_[current_animation_].accumulated_time /
|
||||||
animations_[current_animation_].speed
|
animations_[current_animation_].speed);
|
||||||
);
|
|
||||||
|
|
||||||
// Si alcanza el final de la animación, maneja el loop
|
// Si alcanza el final de la animación, maneja el loop
|
||||||
if (TARGET_FRAME >= static_cast<int>(animations_[current_animation_].frames.size())) {
|
if (TARGET_FRAME >= static_cast<int>(animations_[current_animation_].frames.size())) {
|
||||||
@@ -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
|
// Helper: Parsea los frames de una animación desde una cadena separada por comas
|
||||||
void parseAnimationFrames(const std::string& value, AnimationData& animation,
|
void parseAnimationFrames(const std::string& value, AnimationData& animation, float frame_width, float frame_height, int frames_per_row, int max_tiles) {
|
||||||
float frame_width, float frame_height,
|
|
||||||
int frames_per_row, int max_tiles) {
|
|
||||||
std::stringstream ss(value);
|
std::stringstream ss(value);
|
||||||
std::string tmp;
|
std::string tmp;
|
||||||
SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height};
|
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) {
|
if (pos != std::string::npos) {
|
||||||
std::string key = line.substr(0, pos);
|
std::string key = line.substr(0, pos);
|
||||||
std::string value = line.substr(pos + 1);
|
std::string value = line.substr(pos + 1);
|
||||||
parseAnimationParameter(key, value, animation, frame_width, frame_height,
|
parseAnimationParameter(key, value, animation, frame_width, frame_height, frames_per_row, max_tiles);
|
||||||
frames_per_row, max_tiles);
|
|
||||||
}
|
}
|
||||||
} while (line != "[/animation]");
|
} 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
|
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
|
||||||
if (line == "[animation]") {
|
if (line == "[animation]") {
|
||||||
AnimationData animation = parseAnimation(animations, index, frame_width, frame_height,
|
AnimationData animation = parseAnimation(animations, index, frame_width, frame_height, frames_per_row, max_tiles);
|
||||||
frames_per_row, max_tiles);
|
|
||||||
animations_.emplace_back(animation);
|
animations_.emplace_back(animation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
|
|
||||||
#include "resource_helper.hpp"
|
#include "resource_helper.hpp"
|
||||||
|
|
||||||
#include "resource_loader.hpp"
|
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "resource_loader.hpp"
|
||||||
|
|
||||||
namespace jdd {
|
namespace jdd {
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
#ifndef RESOURCE_HELPER_HPP
|
#ifndef RESOURCE_HELPER_HPP
|
||||||
#define RESOURCE_HELPER_HPP
|
#define RESOURCE_HELPER_HPP
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
namespace jdd {
|
namespace jdd {
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
|
|||||||
@@ -4,12 +4,12 @@
|
|||||||
#ifndef RESOURCE_LOADER_HPP
|
#ifndef RESOURCE_LOADER_HPP
|
||||||
#define RESOURCE_LOADER_HPP
|
#define RESOURCE_LOADER_HPP
|
||||||
|
|
||||||
#include "resource_pack.hpp"
|
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "resource_pack.hpp"
|
||||||
|
|
||||||
namespace jdd {
|
namespace jdd {
|
||||||
|
|
||||||
// Singleton class for loading resources from pack or filesystem
|
// Singleton class for loading resources from pack or filesystem
|
||||||
|
|||||||
@@ -134,13 +134,12 @@ Director::Director(std::vector<std::string> const& args) {
|
|||||||
#ifdef RELEASE_BUILD
|
#ifdef RELEASE_BUILD
|
||||||
// In release, construct the path manually (not from Asset which has empty executable_path)
|
// In release, construct the path manually (not from Asset which has empty executable_path)
|
||||||
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
|
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
|
||||||
Input::init(gamecontroller_db);
|
Input::init(gamecontroller_db, Asset::get()->get("controllers.json"));
|
||||||
#else
|
#else
|
||||||
// In development, use Asset as normal
|
// 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
|
#endif
|
||||||
|
|
||||||
initInput();
|
|
||||||
Debug::init();
|
Debug::init();
|
||||||
|
|
||||||
// Special handling for cheevos.bin - also needs filesystem path
|
// 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
|
// Crea el indice de ficheros
|
||||||
auto Director::setFileList() -> bool {
|
auto Director::setFileList() -> bool {
|
||||||
// Determinar el prefijo de ruta según la plataforma
|
// Determinar el prefijo de ruta según la plataforma
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ class Director {
|
|||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
|
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
|
auto setFileList() -> bool; // Crea el indice de ficheros
|
||||||
static void runLogo(); // Ejecuta la seccion de juego con el logo
|
static void runLogo(); // Ejecuta la seccion de juego con el logo
|
||||||
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
|
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
|
||||||
|
|
||||||
#include "core/system/global_events.hpp"
|
#include "core/system/global_events.hpp"
|
||||||
|
|
||||||
#include "core/input/mouse.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 {
|
namespace GlobalEvents {
|
||||||
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
// 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
|
// Evento de salida de la aplicación
|
||||||
if (event.type == SDL_EVENT_QUIT) {
|
if (event.type == SDL_EVENT_QUIT) {
|
||||||
SceneManager::current = SceneManager::Scene::QUIT;
|
SceneManager::current = SceneManager::Scene::QUIT;
|
||||||
|
|||||||
@@ -4,5 +4,5 @@
|
|||||||
|
|
||||||
namespace GlobalEvents {
|
namespace GlobalEvents {
|
||||||
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
// 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
|
} // namespace GlobalEvents
|
||||||
25526
source/external/json.hpp
vendored
Normal file
25526
source/external/json.hpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@@ -56,12 +56,12 @@ void Player::checkInput(float delta_time) {
|
|||||||
|
|
||||||
if (!auto_movement_) {
|
if (!auto_movement_) {
|
||||||
// Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
|
// 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;
|
vx_ = -HORIZONTAL_VELOCITY;
|
||||||
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
|
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::RIGHT)) {
|
else if (Input::get()->checkAction(InputAction::RIGHT)) {
|
||||||
vx_ = HORIZONTAL_VELOCITY;
|
vx_ = HORIZONTAL_VELOCITY;
|
||||||
sprite_->setFlip(SDL_FLIP_NONE);
|
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)
|
// Solo puede saltar si ademas de estar (state == STANDING)
|
||||||
// Esta sobre el suelo, rampa o suelo que se mueve
|
// Esta sobre el suelo, rampa o suelo que se mueve
|
||||||
// Esto es para evitar el salto desde el vacio al cambiar de pantalla verticalmente
|
// 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
|
// Reproduce sonidos según el estado
|
||||||
if (state_ == State::FALLING) {
|
if (state_ == State::FALLING) {
|
||||||
playFallSound();
|
playFallSound();
|
||||||
}
|
} else if (state_ == State::STANDING) {
|
||||||
else if (state_ == State::STANDING) {
|
|
||||||
// Si no tiene suelo debajo y no está en rampa descendente -> FALLING
|
// Si no tiene suelo debajo y no está en rampa descendente -> FALLING
|
||||||
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
|
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
|
||||||
last_grounded_position_ = static_cast<int>(y_); // Guarda Y actual al SALIR de STANDING
|
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();
|
playFallSound();
|
||||||
}
|
}
|
||||||
}
|
} else if (state_ == State::JUMPING) {
|
||||||
else if (state_ == State::JUMPING) {
|
|
||||||
playJumpSound();
|
playJumpSound();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,8 +206,7 @@ void Player::handleSlopeMovement(int direction) {
|
|||||||
const LineVertical SIDE = {
|
const LineVertical SIDE = {
|
||||||
.x = SIDE_X,
|
.x = SIDE_X,
|
||||||
.y1 = static_cast<int>(y_) + HEIGHT - 2,
|
.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
|
// Comprueba la rampa correspondiente según la dirección
|
||||||
const int SLOPE_Y = direction < 0 ? room_->checkLeftSlopes(&SIDE) : room_->checkRightSlopes(&SIDE);
|
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,
|
.x = x_ + DISPLACEMENT,
|
||||||
.y = y_,
|
.y = y_,
|
||||||
.w = std::ceil(std::fabs(DISPLACEMENT)),
|
.w = std::ceil(std::fabs(DISPLACEMENT)),
|
||||||
.h = HEIGHT
|
.h = HEIGHT};
|
||||||
};
|
|
||||||
} else {
|
} else {
|
||||||
// Movimiento a la derecha
|
// Movimiento a la derecha
|
||||||
proj = {
|
proj = {
|
||||||
.x = x_ + WIDTH,
|
.x = x_ + WIDTH,
|
||||||
.y = y_,
|
.y = y_,
|
||||||
.w = std::ceil(DISPLACEMENT),
|
.w = std::ceil(DISPLACEMENT),
|
||||||
.h = HEIGHT
|
.h = HEIGHT};
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba la colisión con las superficies
|
// Comprueba la colisión con las superficies
|
||||||
|
|||||||
@@ -869,7 +869,8 @@ auto Room::setEnemy(Enemy::Data* enemy, const std::string& key, const std::strin
|
|||||||
try {
|
try {
|
||||||
/*if (key == "tileSetFile") {
|
/*if (key == "tileSetFile") {
|
||||||
enemy->surface_path = value;
|
enemy->surface_path = value;
|
||||||
} else */if (key == "animation") {
|
} else */
|
||||||
|
if (key == "animation") {
|
||||||
enemy->animation_path = value;
|
enemy->animation_path = value;
|
||||||
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
|
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
|
||||||
} else if (key == "width") {
|
} else if (key == "width") {
|
||||||
@@ -991,8 +992,7 @@ auto Room::loadRoomTileFile(const std::string& file_path, bool verbose) -> std::
|
|||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
||||||
}
|
}
|
||||||
}
|
} else { // El fichero no se puede abrir
|
||||||
else { // El fichero no se puede abrir
|
|
||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
|
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) {
|
if (verbose) {
|
||||||
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
|
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';
|
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,8 @@
|
|||||||
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
|
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
|
|
||||||
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
|
|
||||||
#include "game/defaults.hpp" // Para GameDefaults::VERSION
|
#include "game/defaults.hpp" // Para GameDefaults::VERSION
|
||||||
|
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
|
||||||
|
|
||||||
namespace Options {
|
namespace Options {
|
||||||
// Declaración de funciones internas
|
// 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 << "# Versión de la configuración\n";
|
||||||
file << "version " << version << "\n";
|
file << "version " << version << "\n";
|
||||||
|
|
||||||
|
|
||||||
file << "\n## WINDOW\n";
|
file << "\n## WINDOW\n";
|
||||||
file << "# Zoom de la ventana: 1 = Normal, 2 = Doble, 3 = Triple, ...\n";
|
file << "# Zoom de la ventana: 1 = Normal, 2 = Doble, 3 = Triple, ...\n";
|
||||||
file << "window.zoom " << window.zoom << "\n";
|
file << "window.zoom " << window.zoom << "\n";
|
||||||
@@ -234,4 +233,4 @@ auto setOptions(const std::string& var, const std::string& value) -> bool {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
} // namespace Options
|
||||||
@@ -4,7 +4,9 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para min
|
#include <algorithm> // Para min
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
@@ -40,16 +42,17 @@ Credits::Credits()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Credits::checkEvents() {
|
void Credits::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Credits::checkInput() {
|
void Credits::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa los textos
|
// Inicializa los textos
|
||||||
@@ -153,24 +156,21 @@ void Credits::fillTexture() {
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Credits::update() {
|
void Credits::update() {
|
||||||
// Obtiene el delta time
|
// 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
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el tiempo total
|
updateState(DELTA_TIME); // Actualiza la máquina de estados
|
||||||
total_time_ += current_delta_;
|
|
||||||
|
|
||||||
// Actualiza la máquina de estados
|
|
||||||
updateState(current_delta_);
|
|
||||||
|
|
||||||
// Actualiza la pantalla
|
|
||||||
Screen::get()->update(current_delta_);
|
|
||||||
|
|
||||||
// Actualiza el sprite con el brillo si está después del tiempo de inicio
|
// Actualiza el sprite con el brillo si está después del tiempo de inicio
|
||||||
if (reveal_time_ > SHINE_START_TIME) {
|
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
|
// Transición entre estados
|
||||||
@@ -276,7 +276,6 @@ void Credits::render() {
|
|||||||
void Credits::run() {
|
void Credits::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::CREDITS) {
|
while (SceneManager::current == SceneManager::Scene::CREDITS) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,14 +59,13 @@ class Credits {
|
|||||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||||
float total_time_ = 0.0F; // Tiempo total acumulado
|
float total_time_ = 0.0F; // Tiempo total acumulado
|
||||||
float reveal_time_ = 0.0F; // Tiempo acumulado solo durante revelación (se congela en pausas)
|
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
|
std::vector<Captions> texts_; // Vector con los textos
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza la máquina de estados
|
void updateState(float delta_time); // Actualiza la máquina de estados
|
||||||
void transitionToState(State new_state); // Transición entre estados
|
void transitionToState(State new_state); // Transición entre estados
|
||||||
void iniTexts(); // Inicializa los textos
|
void iniTexts(); // Inicializa los textos
|
||||||
|
|||||||
@@ -4,14 +4,15 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para min
|
#include <algorithm> // Para min
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/rendering/text.hpp" // Para Text, TEXT_STROKE
|
#include "core/rendering/text.hpp" // Para Text, TEXT_STROKE
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/system/global_events.hpp" // Para check
|
#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/options.hpp" // Para Options, options, OptionsGame, SectionS...
|
||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "utils/defines.hpp" // Para GAME_SPEED
|
#include "utils/defines.hpp" // Para GAME_SPEED
|
||||||
@@ -46,22 +47,17 @@ Ending::Ending()
|
|||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void Ending::update() {
|
void Ending::update() {
|
||||||
// Obtiene el delta time
|
// 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
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el tiempo total
|
updateState(DELTA_TIME); // Actualiza la máquina de estados
|
||||||
total_time_ += current_delta_;
|
updateSpriteCovers(); // Actualiza las cortinillas de los elementos
|
||||||
|
|
||||||
// Actualiza la máquina de estados
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
updateState(current_delta_);
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
|
|
||||||
// Actualiza las cortinillas de los elementos
|
|
||||||
updateSpriteCovers();
|
|
||||||
|
|
||||||
// Actualiza el objeto Screen
|
|
||||||
Screen::get()->update(current_delta_);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el final en pantalla
|
// Dibuja el final en pantalla
|
||||||
@@ -98,16 +94,17 @@ void Ending::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Ending::checkEvents() {
|
void Ending::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Ending::checkInput() {
|
void Ending::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transición entre estados
|
// Transición entre estados
|
||||||
@@ -424,7 +421,6 @@ void Ending::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::ENDING) {
|
while (SceneManager::current == SceneManager::Scene::ENDING) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -472,8 +468,7 @@ void Ending::updateSpriteCovers() {
|
|||||||
0,
|
0,
|
||||||
sprite_texts_.at(ti.index).cover_clip_desp,
|
sprite_texts_.at(ti.index).cover_clip_desp,
|
||||||
sprite_texts_.at(ti.index).cover_sprite->getWidth(),
|
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->setY(Y_INITIAL + static_cast<int>(CONTENT_PIXELS));
|
||||||
}
|
}
|
||||||
|
|
||||||
sprite_pics_.at(current_scene_).cover_sprite->setClip(
|
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);
|
||||||
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
|
// Comprueba si se ha de cambiar de escena
|
||||||
|
|||||||
@@ -81,7 +81,6 @@ class Ending {
|
|||||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||||
float total_time_ = 0.0F; // Tiempo total acumulado desde el inicio
|
float total_time_ = 0.0F; // Tiempo total acumulado desde el inicio
|
||||||
float fadeout_time_ = 0.0F; // Tiempo acumulado para el fade-out
|
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_texts_; // Vector con los sprites de texto con su cortinilla
|
||||||
std::vector<EndingSurface> sprite_pics_; // 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)
|
int current_scene_ = 0; // Escena actual (0-4)
|
||||||
@@ -90,8 +89,8 @@ class Ending {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza el objeto
|
void update(); // Actualiza el objeto
|
||||||
void render(); // Dibuja el final en pantalla
|
void render(); // Dibuja el final en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void iniTexts(); // Inicializa los textos
|
void iniTexts(); // Inicializa los textos
|
||||||
void iniPics(); // Inicializa las imagenes
|
void iniPics(); // Inicializa las imagenes
|
||||||
void iniScenes(); // Inicializa las escenas
|
void iniScenes(); // Inicializa las escenas
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
@@ -54,20 +55,19 @@ Ending2::Ending2()
|
|||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void Ending2::update() {
|
void Ending2::update() {
|
||||||
// Obtiene el delta time
|
// Obtiene el delta time
|
||||||
current_delta_ = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el estado
|
updateState(DELTA_TIME); // Actualiza el estado
|
||||||
updateState(current_delta_);
|
|
||||||
|
|
||||||
switch (state_.state) {
|
switch (state_.state) {
|
||||||
case EndingState::CREDITS:
|
case EndingState::CREDITS:
|
||||||
// Actualiza los sprites, los textos y los textos del final
|
// Actualiza los sprites, los textos y los textos del final
|
||||||
updateSprites(current_delta_);
|
updateSprites(DELTA_TIME);
|
||||||
updateTextSprites(current_delta_);
|
updateTextSprites(DELTA_TIME);
|
||||||
updateTexts(current_delta_);
|
updateTexts(DELTA_TIME);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case EndingState::FADING:
|
case EndingState::FADING:
|
||||||
@@ -80,8 +80,8 @@ void Ending2::update() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el objeto
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
Screen::get()->update(current_delta_);
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el final en pantalla
|
// Dibuja el final en pantalla
|
||||||
@@ -127,16 +127,17 @@ void Ending2::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Ending2::checkEvents() {
|
void Ending2::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Ending2::checkInput() {
|
void Ending2::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
@@ -145,7 +146,6 @@ void Ending2::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::ENDING2) {
|
while (SceneManager::current == SceneManager::Scene::ENDING2) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -68,14 +68,13 @@ class Ending2 {
|
|||||||
float sprite_max_width_ = 0; // El valor de ancho del sprite mas ancho
|
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 sprite_max_height_ = 0; // El valor de alto del sprite mas alto
|
||||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
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
|
State state_; // Controla el estado de la clase
|
||||||
|
|
||||||
// --- Fucniones ---
|
// --- Fucniones ---
|
||||||
void update(); // Actualiza el objeto
|
void update(); // Actualiza el objeto
|
||||||
void render(); // Dibuja el final en pantalla
|
void render(); // Dibuja el final en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza el estado
|
void updateState(float delta_time); // Actualiza el estado
|
||||||
void transitionToState(EndingState new_state); // Transición entre estados
|
void transitionToState(EndingState new_state); // Transición entre estados
|
||||||
void iniSpriteList(); // Inicializa la lista de sprites
|
void iniSpriteList(); // Inicializa la lista de sprites
|
||||||
|
|||||||
@@ -5,8 +5,9 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
#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/resources/resource.hpp" // Para ResourceRoom, Resource
|
||||||
#include "core/system/debug.hpp" // Para Debug
|
#include "core/system/debug.hpp" // Para Debug
|
||||||
#include "core/system/global_events.hpp" // Para check
|
#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/cheevos.hpp" // Para Cheevos
|
||||||
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
||||||
#include "game/gameplay/room.hpp" // Para Room, RoomData
|
#include "game/gameplay/room.hpp" // Para Room, RoomData
|
||||||
@@ -69,30 +69,32 @@ Game::~Game() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos de la cola
|
// Comprueba los eventos de la cola
|
||||||
void Game::checkEvents() {
|
void Game::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
checkDebugEvents(event);
|
handleDebugEvents(event);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el teclado
|
// Comprueba el teclado
|
||||||
void Game::checkInput() {
|
void Game::handleInput() {
|
||||||
if (Input::get()->checkInput(InputAction::TOGGLE_MUSIC, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
Input::get()->update();
|
||||||
|
|
||||||
|
if (Input::get()->checkAction(InputAction::TOGGLE_MUSIC, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
board_->music = !board_->music;
|
board_->music = !board_->music;
|
||||||
board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
||||||
Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
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();
|
togglePause();
|
||||||
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
|
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
GlobalInputs::check();
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para el juego
|
// Bucle para el juego
|
||||||
@@ -104,7 +106,6 @@ void Game::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::GAME || SceneManager::current == SceneManager::Scene::DEMO) {
|
while (SceneManager::current == SceneManager::Scene::GAME || SceneManager::current == SceneManager::Scene::DEMO) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,8 +119,8 @@ void Game::update() {
|
|||||||
// Calcula el delta time
|
// Calcula el delta time
|
||||||
const float DELTA_TIME = delta_timer_.tick();
|
const float DELTA_TIME = delta_timer_.tick();
|
||||||
|
|
||||||
// Comprueba el teclado
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
Debug::get()->clear();
|
Debug::get()->clear();
|
||||||
@@ -143,7 +144,8 @@ void Game::update() {
|
|||||||
keepMusicPlaying();
|
keepMusicPlaying();
|
||||||
updateBlackScreen(DELTA_TIME);
|
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
|
#ifdef _DEBUG
|
||||||
updateDebugInfo();
|
updateDebugInfo();
|
||||||
@@ -213,7 +215,7 @@ void Game::renderDebugInfo() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos
|
// 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) {
|
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
|
||||||
switch (event.key.key) {
|
switch (event.key.key) {
|
||||||
case SDL_SCANCODE_G:
|
case SDL_SCANCODE_G:
|
||||||
|
|||||||
@@ -82,10 +82,10 @@ class Game {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
|
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
|
||||||
void render(); // Pinta los objetos en pantalla
|
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
|
void renderRoomName(); // Escribe el nombre de la pantalla
|
||||||
auto changeRoom(const std::string& room_path) -> bool; // Cambia de habitación
|
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
|
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
|
auto checkPlayerAndEnemies() -> bool; // Comprueba las colisiones del jugador con los enemigos
|
||||||
void checkPlayerAndItems(); // Comprueba las colisiones del jugador con los objetos
|
void checkPlayerAndItems(); // Comprueba las colisiones del jugador con los objetos
|
||||||
@@ -112,6 +112,6 @@ class Game {
|
|||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
void updateDebugInfo(); // Pone la información de debug en pantalla
|
void updateDebugInfo(); // Pone la información de debug en pantalla
|
||||||
static void renderDebugInfo(); // 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 handleDebugEvents(const SDL_Event& event); // Comprueba los eventos
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
@@ -5,13 +5,14 @@
|
|||||||
#include <algorithm> // Para min, max
|
#include <algorithm> // Para min, max
|
||||||
#include <string> // Para basic_string, operator+, to_string
|
#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/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
|
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/system/global_events.hpp" // Para check
|
#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/options.hpp" // Para Options, options, OptionsStats, Secti...
|
||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X
|
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X
|
||||||
@@ -45,24 +46,19 @@ GameOver::GameOver()
|
|||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void GameOver::update() {
|
void GameOver::update() {
|
||||||
// Obtiene el delta time desde el último frame
|
// Obtiene el delta time desde el último frame
|
||||||
const float delta = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
elapsed_time_ += delta;
|
elapsed_time_ += DELTA_TIME;
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el estado de la escena
|
updateState(); // Actualiza el estado de la escena
|
||||||
updateState();
|
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
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
updateColor();
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
|
|
||||||
// Actualiza los dos sprites con delta time
|
|
||||||
player_sprite_->update(delta);
|
|
||||||
tv_sprite_->update(delta);
|
|
||||||
|
|
||||||
// Actualiza el objeto Screen
|
|
||||||
Screen::get()->update(delta);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el final en pantalla
|
// Dibuja el final en pantalla
|
||||||
@@ -95,23 +91,23 @@ void GameOver::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void GameOver::checkEvents() {
|
void GameOver::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void GameOver::checkInput() {
|
void GameOver::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
void GameOver::run() {
|
void GameOver::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::GAME_OVER) {
|
while (SceneManager::current == SceneManager::Scene::GAME_OVER) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,8 +58,8 @@ class GameOver {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza el objeto
|
void update(); // Actualiza el objeto
|
||||||
void render(); // Dibuja el final en pantalla
|
void render(); // Dibuja el final en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(); // Actualiza el estado y transiciones
|
void updateState(); // Actualiza el estado y transiciones
|
||||||
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
|
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
|
||||||
void renderSprites(); // Dibuja los sprites
|
void renderSprites(); // Dibuja los sprites
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
@@ -49,16 +50,17 @@ LoadingScreen::~LoadingScreen() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void LoadingScreen::checkEvents() {
|
void LoadingScreen::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void LoadingScreen::checkInput() {
|
void LoadingScreen::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa el array de índices de líneas (imita el direccionamiento de memoria del Spectrum)
|
// 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
|
// Obtener delta time desde el último frame
|
||||||
const float DELTA_TIME = delta_timer_->tick();
|
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
|
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
||||||
|
|
||||||
// Actualizar la carga según el estado actual
|
// Actualizar la carga según el estado actual
|
||||||
@@ -353,7 +357,7 @@ void LoadingScreen::update() {
|
|||||||
|
|
||||||
// Singletones
|
// Singletones
|
||||||
Audio::update(); // Actualiza el objeto Audio
|
Audio::update(); // Actualiza el objeto Audio
|
||||||
Screen::get()->update(); // Actualiza el objeto Screen
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja en pantalla
|
// Dibuja en pantalla
|
||||||
@@ -384,7 +388,6 @@ void LoadingScreen::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::LOADING_SCREEN) {
|
while (SceneManager::current == SceneManager::Scene::LOADING_SCREEN) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -77,8 +77,8 @@ class LoadingScreen {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
||||||
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based)
|
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based)
|
||||||
|
|||||||
@@ -4,7 +4,9 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para std::clamp
|
#include <algorithm> // Para std::clamp
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
@@ -39,16 +41,17 @@ Logo::Logo()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Logo::checkEvents() {
|
void Logo::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Logo::checkInput() {
|
void Logo::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona el logo de JAILGAME (time-based)
|
// Gestiona el logo de JAILGAME (time-based)
|
||||||
@@ -180,10 +183,14 @@ void Logo::update() {
|
|||||||
// Obtener delta time desde el último frame
|
// Obtener delta time desde el último frame
|
||||||
const float DELTA_TIME = delta_timer_->tick();
|
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
|
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
||||||
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
|
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
|
||||||
updateTextureColors(); // Gestiona el color de las texturas
|
updateTextureColors(); // Gestiona el color de las texturas
|
||||||
|
|
||||||
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,7 +214,6 @@ void Logo::render() {
|
|||||||
void Logo::run() {
|
void Logo::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::LOGO) {
|
while (SceneManager::current == SceneManager::Scene::LOGO) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,8 +57,8 @@ class Logo {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
|
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
|
||||||
void updateTextureColors(); // Gestiona el color de las texturas
|
void updateTextureColors(); // Gestiona el color de las texturas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
|
|||||||
@@ -4,8 +4,9 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#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/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
@@ -30,8 +31,7 @@ Title::Title()
|
|||||||
first_active_letter_(0),
|
first_active_letter_(0),
|
||||||
last_active_letter_(0),
|
last_active_letter_(0),
|
||||||
state_time_(0.0F),
|
state_time_(0.0F),
|
||||||
fade_accumulator_(0.0F),
|
fade_accumulator_(0.0F) {
|
||||||
current_delta_(0.0F) {
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? State::SHOW_LOADING_SCREEN : State::SHOW_MENU;
|
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? State::SHOW_LOADING_SCREEN : State::SHOW_MENU;
|
||||||
SceneManager::current = SceneManager::Scene::TITLE;
|
SceneManager::current = SceneManager::Scene::TITLE;
|
||||||
@@ -72,10 +72,10 @@ void Title::initMarquee() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Title::checkEvents() {
|
void Title::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
|
|
||||||
// Solo se comprueban estas teclas si no está activo el menu de logros
|
// Solo se comprueban estas teclas si no está activo el menu de logros
|
||||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||||
@@ -99,24 +99,26 @@ void Title::checkEvents() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Title::checkInput() {
|
void Title::handleInput(float delta_time) {
|
||||||
|
Input::get()->update();
|
||||||
|
|
||||||
if (show_cheevos_) {
|
if (show_cheevos_) {
|
||||||
if (Input::get()->checkInput(InputAction::DOWN, INPUT_ALLOW_REPEAT)) {
|
if (Input::get()->checkAction(InputAction::RIGHT, Input::ALLOW_REPEAT)) {
|
||||||
moveCheevosList(1, current_delta_);
|
moveCheevosList(1, delta_time);
|
||||||
} else if (Input::get()->checkInput(InputAction::UP, INPUT_ALLOW_REPEAT)) {
|
} else if (Input::get()->checkAction(InputAction::LEFT, Input::ALLOW_REPEAT)) {
|
||||||
moveCheevosList(0, current_delta_);
|
moveCheevosList(0, delta_time);
|
||||||
} else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
} else if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
hideCheevosList();
|
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) {
|
if (state_ == State::SHOW_LOADING_SCREEN) {
|
||||||
transitionToState(State::FADE_LOADING_SCREEN);
|
transitionToState(State::FADE_LOADING_SCREEN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GlobalInputs::check();
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la marquesina
|
// Actualiza la marquesina
|
||||||
@@ -169,16 +171,15 @@ void Title::renderMarquee() {
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Title::update() {
|
void Title::update() {
|
||||||
// Obtener delta time
|
// Obtener delta time
|
||||||
current_delta_ = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(DELTA_TIME); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza la pantalla
|
updateState(DELTA_TIME); // Actualiza el estado actual
|
||||||
Screen::get()->update(current_delta_);
|
|
||||||
|
|
||||||
// Actualiza el estado actual
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
updateState(current_delta_);
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado actual
|
// Actualiza el estado actual
|
||||||
@@ -263,7 +264,6 @@ void Title::render() {
|
|||||||
void Title::run() {
|
void Title::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::TITLE) {
|
while (SceneManager::current == SceneManager::Scene::TITLE) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,13 +69,12 @@ class Title {
|
|||||||
State state_; // Estado en el que se encuentra el bucle principal
|
State state_; // Estado en el que se encuentra el bucle principal
|
||||||
float state_time_; // Tiempo acumulado en el estado actual
|
float state_time_; // Tiempo acumulado en el estado actual
|
||||||
float fade_accumulator_; // Acumulador para controlar el fade por tiempo
|
float fade_accumulator_; // Acumulador para controlar el fade por tiempo
|
||||||
float current_delta_; // Delta time del frame actual
|
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
void checkEvents(); // Comprueba el manejador de eventos
|
void handleEvents(); // Comprueba el manejador de eventos
|
||||||
void checkInput(); // Comprueba las entradas
|
void handleInput(float delta_time); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
||||||
void initMarquee(); // Inicializa la marquesina
|
void initMarquee(); // Inicializa la marquesina
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
|
||||||
#include "game/options.hpp" // Para Options, options, NotificationPosition
|
#include "game/options.hpp" // Para Options, options, NotificationPosition
|
||||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||||
#include "utils/utils.hpp" // Para PaletteColor
|
#include "utils/utils.hpp" // Para PaletteColor
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
class DeltaTimer {
|
class DeltaTimer {
|
||||||
|
|||||||
Reference in New Issue
Block a user