reestructuració
This commit is contained in:
267
source/core/input/define_buttons.cpp
Normal file
267
source/core/input/define_buttons.cpp
Normal file
@@ -0,0 +1,267 @@
|
||||
#include "define_buttons.hpp"
|
||||
|
||||
#include <algorithm> // Para __all_of_fn, all_of
|
||||
#include <memory> // Para unique_ptr, allocator, shared_ptr, operator==, make_unique
|
||||
|
||||
#include "input.hpp" // Para Input
|
||||
#include "input_types.hpp" // Para InputAction
|
||||
#include "lang.hpp" // Para getText
|
||||
#include "options.hpp" // Para Gamepad
|
||||
#include "param.hpp" // Para Param, param, ParamGame, ParamServiceMenu
|
||||
#include "resource.hpp" // Para Resource
|
||||
#include "ui/window_message.hpp" // Para WindowMessage
|
||||
#include "utils.hpp" // Para Zone
|
||||
|
||||
DefineButtons::DefineButtons()
|
||||
: input_(Input::get()) {
|
||||
clearButtons();
|
||||
|
||||
auto gamepads = input_->getGamepads();
|
||||
for (const auto& gamepad : gamepads) {
|
||||
controller_names_.emplace_back(Input::getControllerName(gamepad));
|
||||
}
|
||||
|
||||
// Crear la ventana de mensaje
|
||||
WindowMessage::Config config(param.service_menu.window_message);
|
||||
auto text_renderer = Resource::get()->getText("04b_25_flat");
|
||||
window_message_ = std::make_unique<WindowMessage>(
|
||||
text_renderer,
|
||||
Lang::getText("[DEFINE_BUTTONS] TITLE"),
|
||||
config);
|
||||
window_message_->setPosition(param.game.game_area.center_x, param.game.game_area.center_y, WindowMessage::PositionMode::CENTERED);
|
||||
}
|
||||
|
||||
void DefineButtons::render() {
|
||||
if (enabled_ && window_message_) {
|
||||
window_message_->render();
|
||||
}
|
||||
}
|
||||
|
||||
void DefineButtons::update(float delta_time) {
|
||||
if (!enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Actualizar la ventana siempre
|
||||
if (window_message_) {
|
||||
window_message_->update(delta_time);
|
||||
}
|
||||
|
||||
// Manejar la secuencia de cierre si ya terminamos
|
||||
if (finished_ && message_shown_) {
|
||||
message_timer_ += delta_time;
|
||||
|
||||
// Después del delay, iniciar animación de cierre (solo una vez)
|
||||
if (message_timer_ >= MESSAGE_DISPLAY_DURATION_S && !closing_) {
|
||||
if (window_message_) {
|
||||
window_message_->hide(); // Iniciar animación de cierre
|
||||
}
|
||||
closing_ = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DefineButtons::handleEvents(const SDL_Event& event) {
|
||||
if (enabled_) {
|
||||
switch (event.type) {
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
|
||||
doControllerButtonDown(event.gbutton);
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_BUTTON_UP:
|
||||
checkEnd();
|
||||
break;
|
||||
case SDL_EVENT_GAMEPAD_AXIS_MOTION:
|
||||
doControllerAxisMotion(event.gaxis);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto DefineButtons::enable(Options::Gamepad* options_gamepad) -> bool {
|
||||
if (options_gamepad != nullptr) {
|
||||
options_gamepad_ = options_gamepad;
|
||||
enabled_ = true;
|
||||
finished_ = false;
|
||||
index_button_ = 0;
|
||||
message_shown_ = false;
|
||||
closing_ = false;
|
||||
l2_was_pressed_ = false;
|
||||
r2_was_pressed_ = false;
|
||||
clearButtons();
|
||||
updateWindowMessage();
|
||||
|
||||
if (window_message_) {
|
||||
window_message_->autoSize();
|
||||
window_message_->show();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DefineButtons::disable() {
|
||||
enabled_ = false;
|
||||
finished_ = false;
|
||||
message_shown_ = false;
|
||||
closing_ = false;
|
||||
l2_was_pressed_ = false;
|
||||
r2_was_pressed_ = false;
|
||||
|
||||
if (window_message_) {
|
||||
window_message_->hide();
|
||||
}
|
||||
}
|
||||
|
||||
void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent& event) {
|
||||
auto gamepad = input_->getGamepad(event.which);
|
||||
|
||||
if (!gamepad || gamepad != options_gamepad_->instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto BUTTON = static_cast<SDL_GamepadButton>(event.button);
|
||||
if (checkButtonNotInUse(BUTTON)) {
|
||||
buttons_.at(index_button_).button = static_cast<int>(BUTTON);
|
||||
incIndexButton();
|
||||
updateWindowMessage();
|
||||
}
|
||||
}
|
||||
|
||||
void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent& event) {
|
||||
auto gamepad = input_->getGamepad(event.which);
|
||||
|
||||
if (!gamepad || gamepad != options_gamepad_->instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Solo manejamos L2 y R2 como botones con lógica de transición
|
||||
if (event.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER) {
|
||||
bool l2_is_pressed_now = event.value > 16384;
|
||||
|
||||
// Solo actuar en la transición de no presionado a presionado
|
||||
if (l2_is_pressed_now && !l2_was_pressed_) {
|
||||
const auto TRIGGER_BUTTON = Input::TRIGGER_L2_AS_BUTTON;
|
||||
if (checkTriggerNotInUse(TRIGGER_BUTTON)) {
|
||||
buttons_.at(index_button_).button = TRIGGER_BUTTON;
|
||||
incIndexButton();
|
||||
updateWindowMessage();
|
||||
}
|
||||
}
|
||||
|
||||
// Detectar liberación del trigger para llamar checkEnd()
|
||||
if (!l2_is_pressed_now && l2_was_pressed_) {
|
||||
checkEnd();
|
||||
}
|
||||
|
||||
l2_was_pressed_ = l2_is_pressed_now;
|
||||
|
||||
} else if (event.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) {
|
||||
bool r2_is_pressed_now = event.value > 16384;
|
||||
|
||||
// Solo actuar en la transición de no presionado a presionado
|
||||
if (r2_is_pressed_now && !r2_was_pressed_) {
|
||||
const auto TRIGGER_BUTTON = Input::TRIGGER_R2_AS_BUTTON;
|
||||
if (checkTriggerNotInUse(TRIGGER_BUTTON)) {
|
||||
buttons_.at(index_button_).button = TRIGGER_BUTTON;
|
||||
incIndexButton();
|
||||
updateWindowMessage();
|
||||
}
|
||||
}
|
||||
|
||||
// Detectar liberación del trigger para llamar checkEnd()
|
||||
if (!r2_is_pressed_now && r2_was_pressed_) {
|
||||
checkEnd();
|
||||
}
|
||||
|
||||
r2_was_pressed_ = r2_is_pressed_now;
|
||||
}
|
||||
}
|
||||
|
||||
void DefineButtons::bindButtons(Options::Gamepad* options_gamepad) {
|
||||
for (const auto& button : buttons_) {
|
||||
Input::bindGameControllerButton(options_gamepad->instance, button.action, static_cast<SDL_GamepadButton>(button.button));
|
||||
}
|
||||
|
||||
Input::bindGameControllerButton(options_gamepad->instance, Input::Action::SM_SELECT, Input::Action::FIRE_LEFT);
|
||||
Input::bindGameControllerButton(options_gamepad->instance, Input::Action::SM_BACK, Input::Action::FIRE_CENTER);
|
||||
}
|
||||
|
||||
void DefineButtons::incIndexButton() {
|
||||
if (index_button_ < buttons_.size() - 1) {
|
||||
++index_button_;
|
||||
} else {
|
||||
finished_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
|
||||
return std::ranges::all_of(buttons_, [button](const auto& b) -> auto {
|
||||
return b.button != button;
|
||||
});
|
||||
}
|
||||
|
||||
auto DefineButtons::checkTriggerNotInUse(int trigger_button) -> bool {
|
||||
return std::ranges::all_of(buttons_, [trigger_button](const auto& b) -> auto {
|
||||
return b.button != trigger_button;
|
||||
});
|
||||
}
|
||||
|
||||
void DefineButtons::clearButtons() {
|
||||
buttons_.clear();
|
||||
buttons_.emplace_back(Lang::getText("[DEFINE_BUTTONS] FIRE_LEFT"), Input::Action::FIRE_LEFT, static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID));
|
||||
buttons_.emplace_back(Lang::getText("[DEFINE_BUTTONS] FIRE_UP"), Input::Action::FIRE_CENTER, static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID));
|
||||
buttons_.emplace_back(Lang::getText("[DEFINE_BUTTONS] FIRE_RIGHT"), Input::Action::FIRE_RIGHT, static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID));
|
||||
buttons_.emplace_back(Lang::getText("[DEFINE_BUTTONS] START"), Input::Action::START, static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID));
|
||||
buttons_.emplace_back(Lang::getText("[DEFINE_BUTTONS] SERVICE_MENU"), Input::Action::SERVICE, static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID));
|
||||
}
|
||||
|
||||
void DefineButtons::checkEnd() {
|
||||
if (finished_ && !message_shown_) {
|
||||
bindButtons(options_gamepad_);
|
||||
input_->saveGamepadConfigFromGamepad(options_gamepad_->instance);
|
||||
input_->resetInputStates();
|
||||
|
||||
// Mostrar mensaje de finalización
|
||||
if (window_message_) {
|
||||
window_message_->clearTexts();
|
||||
window_message_->addText(Lang::getText("[DEFINE_BUTTONS] CONFIGURATION_COMPLETE"));
|
||||
}
|
||||
|
||||
// Solo marcar que ya mostramos el mensaje
|
||||
message_shown_ = true;
|
||||
message_timer_ = 0.0F;
|
||||
}
|
||||
}
|
||||
|
||||
auto DefineButtons::isReadyToClose() const -> bool {
|
||||
// Solo está listo para cerrar si:
|
||||
// 1. Terminó
|
||||
// 2. Ya mostró el mensaje
|
||||
// 3. Está cerrando
|
||||
// 4. La ventana ya no está visible (animación terminada)
|
||||
return finished_ && message_shown_ && closing_ &&
|
||||
(!window_message_ || !window_message_->isVisible());
|
||||
}
|
||||
|
||||
void DefineButtons::updateWindowMessage() {
|
||||
if (!window_message_ || (options_gamepad_ == nullptr)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Configurar título
|
||||
std::string title = Lang::getText("[DEFINE_BUTTONS] CONFIGURING") + ": " + options_gamepad_->name;
|
||||
window_message_->setTitle(title);
|
||||
|
||||
// Limpiar textos anteriores
|
||||
window_message_->clearTexts();
|
||||
|
||||
if (index_button_ < buttons_.size()) {
|
||||
// Instrucción actual
|
||||
std::string instruction = Lang::getText("[DEFINE_BUTTONS] PRESS_BUTTON_FOR") + ":";
|
||||
window_message_->addText(instruction);
|
||||
window_message_->addText(buttons_.at(index_button_).label);
|
||||
}
|
||||
}
|
||||
80
source/core/input/define_buttons.hpp
Normal file
80
source/core/input/define_buttons.hpp
Normal file
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "input.hpp"
|
||||
#include "ui/window_message.hpp"
|
||||
|
||||
namespace Options {
|
||||
struct Gamepad;
|
||||
}
|
||||
|
||||
// --- Clase DefineButtons: configuración de botones de gamepad ---
|
||||
class DefineButtons {
|
||||
public:
|
||||
// --- Estructuras ---
|
||||
struct Button {
|
||||
std::string label;
|
||||
Input::Action action;
|
||||
int button;
|
||||
|
||||
Button(std::string label, Input::Action action, int button)
|
||||
: label(std::move(label)),
|
||||
action(action),
|
||||
button(button) {}
|
||||
};
|
||||
|
||||
// --- Constructor y destructor ---
|
||||
DefineButtons();
|
||||
~DefineButtons() = default;
|
||||
|
||||
// --- Métodos principales ---
|
||||
void render();
|
||||
void update(float delta_time);
|
||||
void handleEvents(const SDL_Event& event);
|
||||
auto enable(Options::Gamepad* options_gamepad) -> bool;
|
||||
void disable();
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto isReadyToClose() const -> bool;
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||
[[nodiscard]] auto isFinished() const -> bool { return finished_; }
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0F; // Cuánto tiempo mostrar el mensaje en segundos
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
Input* input_ = nullptr; // Entrada del usuario
|
||||
Options::Gamepad* options_gamepad_ = nullptr; // Opciones del gamepad
|
||||
std::unique_ptr<WindowMessage> window_message_; // Mensaje de ventana
|
||||
|
||||
// --- Variables de estado ---
|
||||
std::vector<Button> buttons_; // Lista de botones
|
||||
std::vector<std::string> controller_names_; // Nombres de los controladores
|
||||
size_t index_button_ = 0; // Índice del botón seleccionado
|
||||
float message_timer_ = 0.0F; // Timer en segundos para el mensaje
|
||||
bool enabled_ = false; // Flag para indicar si está activo
|
||||
bool finished_ = false; // Flag para indicar si ha terminado
|
||||
bool closing_ = false; // Flag para indicar que está cerrando
|
||||
bool message_shown_ = false; // Flag para indicar que ya mostró el mensaje
|
||||
bool l2_was_pressed_ = false; // Estado anterior del trigger L2
|
||||
bool r2_was_pressed_ = false; // Estado anterior del trigger R2
|
||||
|
||||
// --- Métodos internos ---
|
||||
void incIndexButton();
|
||||
void doControllerButtonDown(const SDL_GamepadButtonEvent& event);
|
||||
void doControllerAxisMotion(const SDL_GamepadAxisEvent& event);
|
||||
void bindButtons(Options::Gamepad* options_gamepad);
|
||||
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool;
|
||||
auto checkTriggerNotInUse(int trigger_button) -> bool;
|
||||
void clearButtons();
|
||||
void checkEnd();
|
||||
void updateWindowMessage();
|
||||
};
|
||||
136
source/core/input/gamepad_config_manager.hpp
Normal file
136
source/core/input/gamepad_config_manager.hpp
Normal file
@@ -0,0 +1,136 @@
|
||||
#pragma once
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "external/json.hpp"
|
||||
#include "input_types.hpp" // Solo incluimos los tipos compartidos
|
||||
|
||||
// --- 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::FIRE_LEFT, SDL_GAMEPAD_BUTTON_WEST},
|
||||
{InputAction::FIRE_CENTER, SDL_GAMEPAD_BUTTON_NORTH},
|
||||
{InputAction::FIRE_RIGHT, SDL_GAMEPAD_BUTTON_EAST},
|
||||
{InputAction::START, SDL_GAMEPAD_BUTTON_START},
|
||||
{InputAction::SERVICE, SDL_GAMEPAD_BUTTON_BACK}} {}
|
||||
|
||||
// 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; // NOLINT(readability-simplify-boolean-expr)
|
||||
}
|
||||
|
||||
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; // NOLINT(readability-simplify-boolean-expr)
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
};
|
||||
266
source/core/input/global_inputs.cpp
Normal file
266
source/core/input/global_inputs.cpp
Normal file
@@ -0,0 +1,266 @@
|
||||
#include "global_inputs.hpp"
|
||||
|
||||
#include <algorithm> // Para __any_of_fn, any_of
|
||||
#include <functional> // Para function
|
||||
#include <iterator> // Para pair
|
||||
#include <string> // Para basic_string, operator+, allocator, char_traits, string, to_string
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "audio.hpp" // Para Audio
|
||||
#include "input.hpp" // Para Input
|
||||
#include "input_types.hpp" // Para InputAction
|
||||
#include "lang.hpp" // Para getText, getLangFile, getLangName, getNextLangCode, loadFromFile
|
||||
#include "options.hpp" // Para Video, video, Settings, settings, Audio, audio, Window, window
|
||||
#include "screen.hpp" // Para Screen
|
||||
#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode
|
||||
#include "ui/notifier.hpp" // Para Notifier
|
||||
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||
#include "utils.hpp" // Para boolToOnOff
|
||||
|
||||
namespace GlobalInputs {
|
||||
// Termina
|
||||
void quit() {
|
||||
const std::string CODE = "QUIT";
|
||||
if (Notifier::get()->checkCode(CODE)) {
|
||||
// Si la notificación de salir está activa, cambia de sección
|
||||
Section::name = Section::Name::QUIT;
|
||||
Section::options = Section::Options::NONE;
|
||||
} else {
|
||||
// Si la notificación de salir no está activa, muestra la notificación
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 01"), std::string()}, -1, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// Reinicia
|
||||
void reset() {
|
||||
const std::string CODE = "RESET";
|
||||
if (Notifier::get()->checkCode(CODE)) {
|
||||
Section::name = Section::Name::RESET;
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 15")});
|
||||
} else {
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 03"), std::string()}, -1, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// Activa o desactiva el audio
|
||||
void toggleAudio() {
|
||||
Options::audio.enabled = !Options::audio.enabled;
|
||||
Audio::get()->enable(Options::audio.enabled);
|
||||
Notifier::get()->show({"Audio " + boolToOnOff(Options::audio.enabled)});
|
||||
}
|
||||
|
||||
// Cambia el modo de escalado entero
|
||||
void toggleIntegerScale() {
|
||||
Screen::get()->toggleIntegerScale();
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 12") + " " + boolToOnOff(Options::video.integer_scale)});
|
||||
}
|
||||
|
||||
// Activa / desactiva el vsync
|
||||
void toggleVSync() {
|
||||
Screen::get()->toggleVSync();
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 14") + " " + boolToOnOff(Options::video.vsync)});
|
||||
}
|
||||
|
||||
// Activa o desactiva los shaders
|
||||
void toggleShaders() {
|
||||
Screen::toggleShaders();
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 13") + " " + boolToOnOff(Options::video.shader.enabled)});
|
||||
}
|
||||
|
||||
// Cambia entre PostFX y CrtPi
|
||||
void nextShader() {
|
||||
Screen::nextShader();
|
||||
const std::string SHADER_NAME = (Options::video.shader.current_shader == Rendering::ShaderType::CRTPI) ? "CrtPi" : "PostFX";
|
||||
Notifier::get()->show({"Shader: " + SHADER_NAME});
|
||||
}
|
||||
|
||||
// Avanza al siguiente preset PostFX o CrtPi según shader activo
|
||||
void nextPreset() {
|
||||
if (Options::video.shader.current_shader == Rendering::ShaderType::CRTPI) {
|
||||
Screen::nextCrtPiPreset();
|
||||
const std::string name = Options::crtpi_presets.empty() ? "" : Options::crtpi_presets.at(static_cast<size_t>(Options::video.shader.current_crtpi_preset)).name;
|
||||
Notifier::get()->show({"CrtPi: " + name});
|
||||
} else {
|
||||
Screen::nextPostFXPreset();
|
||||
const std::string name = Options::postfx_presets.empty() ? "" : Options::postfx_presets.at(static_cast<size_t>(Options::video.shader.current_postfx_preset)).name;
|
||||
Notifier::get()->show({"PostFX: " + name});
|
||||
}
|
||||
}
|
||||
|
||||
// Activa o desactiva el supersampling
|
||||
void toggleSupersampling() {
|
||||
Screen::toggleSupersampling();
|
||||
Notifier::get()->show({"SS: " + std::string(Options::video.supersampling.enabled ? "ON" : "OFF")});
|
||||
}
|
||||
|
||||
// Cambia al siguiente idioma
|
||||
void setNextLang() {
|
||||
const std::string CODE = "LANG";
|
||||
const auto NEXT_LANG_CODE = Lang::getNextLangCode(Options::settings.language);
|
||||
const auto NEXT_LANG_NAME = Lang::getLangName(NEXT_LANG_CODE);
|
||||
if (Notifier::get()->checkCode(CODE)) {
|
||||
// Si la notificación de cambiar idioma está activa, cambia de de idioma
|
||||
Options::settings.language = NEXT_LANG_CODE;
|
||||
Lang::loadFromFile(Lang::getLangFile(NEXT_LANG_CODE));
|
||||
Section::name = Section::Name::RESET;
|
||||
Section::options = Section::Options::RELOAD;
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 05") + NEXT_LANG_NAME});
|
||||
} else {
|
||||
// Si la notificación de cambiar idioma no está activa, muestra la notificación
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 04") + NEXT_LANG_NAME, std::string()}, -1, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia el modo de disparo
|
||||
void toggleFireMode() {
|
||||
Options::settings.autofire = !Options::settings.autofire;
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 08") + " " + boolToOnOff(Options::settings.autofire)});
|
||||
}
|
||||
|
||||
// Salta una sección del juego
|
||||
void skipSection() {
|
||||
switch (Section::name) {
|
||||
case Section::Name::INTRO:
|
||||
Audio::get()->stopMusic();
|
||||
/* Continua en el case de abajo */
|
||||
case Section::Name::LOGO:
|
||||
case Section::Name::HI_SCORE_TABLE:
|
||||
case Section::Name::INSTRUCTIONS: {
|
||||
Section::name = Section::Name::TITLE;
|
||||
Section::options = Section::Options::TITLE_1;
|
||||
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Activa el menu de servicio
|
||||
void toggleServiceMenu() {
|
||||
ServiceMenu::get()->toggle();
|
||||
}
|
||||
|
||||
// Cambia el modo de pantalla completa
|
||||
void toggleFullscreen() {
|
||||
Screen::get()->toggleFullscreen();
|
||||
const std::string MODE = Options::video.fullscreen ? Lang::getText("[NOTIFICATIONS] 11") : Lang::getText("[NOTIFICATIONS] 10");
|
||||
Notifier::get()->show({MODE});
|
||||
}
|
||||
|
||||
// Reduce el tamaño de la ventana
|
||||
void decWindowSize() {
|
||||
if (Screen::get()->decWindowSize()) {
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 09") + " x" + std::to_string(Options::window.zoom)});
|
||||
}
|
||||
}
|
||||
|
||||
// Aumenta el tamaño de la ventana
|
||||
void incWindowSize() {
|
||||
if (Screen::get()->incWindowSize()) {
|
||||
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 09") + " x" + std::to_string(Options::window.zoom)});
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el boton de servicio
|
||||
auto checkServiceButton() -> bool {
|
||||
// Teclado
|
||||
if (Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
|
||||
toggleServiceMenu();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Mandos
|
||||
if (std::ranges::any_of(Input::get()->getGamepads(), [](const auto& gamepad) -> auto {
|
||||
return Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad);
|
||||
})) {
|
||||
toggleServiceMenu();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba las entradas para elementos del sistema
|
||||
auto checkSystemInputs() -> bool {
|
||||
using Action = Input::Action;
|
||||
|
||||
static const std::vector<std::pair<Action, std::function<void()>>> ACTIONS = {
|
||||
{Action::WINDOW_FULLSCREEN, toggleFullscreen},
|
||||
{Action::WINDOW_DEC_SIZE, decWindowSize},
|
||||
{Action::WINDOW_INC_SIZE, incWindowSize},
|
||||
{Action::EXIT, quit},
|
||||
{Action::RESET, reset},
|
||||
{Action::TOGGLE_AUDIO, toggleAudio},
|
||||
{Action::TOGGLE_AUTO_FIRE, toggleFireMode},
|
||||
{Action::CHANGE_LANG, setNextLang},
|
||||
{Action::TOGGLE_VIDEO_INTEGER_SCALE, toggleIntegerScale},
|
||||
{Action::TOGGLE_VIDEO_VSYNC, toggleVSync},
|
||||
#ifdef _DEBUG
|
||||
{Action::SHOW_INFO, []() -> void { Screen::get()->toggleDebugInfo(); }},
|
||||
#endif
|
||||
};
|
||||
|
||||
if (std::ranges::any_of(ACTIONS, [](const auto& pair) -> auto {
|
||||
if (Input::get()->checkAction(pair.first, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
|
||||
pair.second();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Input::get()->checkAction(Input::Action::TOGGLE_VIDEO_POSTFX, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
|
||||
toggleShaders();
|
||||
return true;
|
||||
}
|
||||
if (Input::get()->checkAction(Input::Action::NEXT_SHADER, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
|
||||
nextShader();
|
||||
return true;
|
||||
}
|
||||
if (Input::get()->checkAction(Input::Action::NEXT_POSTFX_PRESET, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
|
||||
nextPreset();
|
||||
return true;
|
||||
}
|
||||
if (Input::get()->checkAction(Input::Action::TOGGLE_SUPERSAMPLING, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
|
||||
toggleSupersampling();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba el resto de entradas
|
||||
auto checkOtherInputs() -> bool {
|
||||
// Saltar sección
|
||||
if ((Input::get()->checkAnyButton()) && !ServiceMenu::get()->isEnabled()) {
|
||||
skipSection();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba las entradas del Menu de Servicio
|
||||
inline auto checkServiceMenuInputs() -> bool {
|
||||
return ServiceMenu::get()->checkInput();
|
||||
}
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
auto check() -> bool {
|
||||
if (checkServiceButton()) {
|
||||
return true;
|
||||
}
|
||||
if (checkServiceMenuInputs()) {
|
||||
return true;
|
||||
}
|
||||
if (checkSystemInputs()) {
|
||||
return true;
|
||||
}
|
||||
if (checkOtherInputs()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} // namespace GlobalInputs
|
||||
7
source/core/input/global_inputs.hpp
Normal file
7
source/core/input/global_inputs.hpp
Normal file
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
// --- Namespace GlobalInputs: gestiona inputs globales del juego ---
|
||||
namespace GlobalInputs {
|
||||
// --- Funciones ---
|
||||
auto check() -> bool; // Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
} // namespace GlobalInputs
|
||||
542
source/core/input/input.cpp
Normal file
542
source/core/input/input.cpp
Normal file
@@ -0,0 +1,542 @@
|
||||
#include "input.hpp"
|
||||
|
||||
#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 <iostream> // Para basic_ostream, operator<<, cout, cerr
|
||||
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
|
||||
#include <ranges> // Para __find_if_fn, find_if
|
||||
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
|
||||
#include <utility> // Para pair, move
|
||||
|
||||
// Singleton
|
||||
Input* Input::instance = nullptr;
|
||||
|
||||
// Inicializa la instancia única del singleton
|
||||
void Input::init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file) {
|
||||
Input::instance = new Input(game_controller_db_path, gamepad_configs_file);
|
||||
}
|
||||
|
||||
// Libera la instancia
|
||||
void Input::destroy() { delete Input::instance; }
|
||||
|
||||
// Obtiene la instancia
|
||||
auto Input::get() -> Input* { return Input::instance; }
|
||||
|
||||
// Constructor
|
||||
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
|
||||
: gamepad_mappings_file_(std::move(game_controller_db_path)),
|
||||
gamepad_configs_file_(std::move(gamepad_configs_file)) {
|
||||
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
||||
initSDLGamePad();
|
||||
}
|
||||
|
||||
// Asigna inputs a teclas
|
||||
void Input::bindKey(Action action, SDL_Scancode code) {
|
||||
keyboard_.bindings[action].scancode = code;
|
||||
}
|
||||
|
||||
// Asigna inputs a botones del mando
|
||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button) {
|
||||
if (gamepad != nullptr) {
|
||||
gamepad->bindings[action].button = button;
|
||||
}
|
||||
}
|
||||
|
||||
// Asigna inputs a botones del mando
|
||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source) {
|
||||
if (gamepad != nullptr) {
|
||||
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si alguna acción está activa
|
||||
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||
bool success_keyboard = false;
|
||||
bool success_controller = false;
|
||||
|
||||
if (check_keyboard) {
|
||||
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||
success_keyboard = keyboard_.bindings[action].is_held;
|
||||
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||
success_keyboard = keyboard_.bindings[action].just_pressed;
|
||||
}
|
||||
}
|
||||
|
||||
if (gamepad != nullptr) {
|
||||
success_controller = checkAxisInput(action, gamepad, repeat);
|
||||
|
||||
if (!success_controller) {
|
||||
success_controller = checkTriggerInput(action, gamepad, repeat);
|
||||
}
|
||||
|
||||
if (!success_controller) {
|
||||
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||
success_controller = gamepad->bindings[action].is_held;
|
||||
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||
success_controller = gamepad->bindings[action].just_pressed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (success_keyboard || success_controller);
|
||||
}
|
||||
|
||||
// Comprueba si hay almenos una acción activa
|
||||
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
||||
|
||||
// --- Comprobación del Teclado ---
|
||||
if (check_keyboard) {
|
||||
for (const auto& pair : keyboard_.bindings) {
|
||||
// Simplemente leemos el estado pre-calculado por Input::update().
|
||||
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
|
||||
if (pair.second.just_pressed) {
|
||||
return true; // Se encontró una acción recién pulsada.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Comprobación del Mando ---
|
||||
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
||||
if (gamepad != nullptr) {
|
||||
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
||||
for (const auto& pair : gamepad->bindings) {
|
||||
// Leemos el estado pre-calculado para el mando y la acción específicos.
|
||||
if (pair.second.just_pressed) {
|
||||
return true; // Se encontró una acción recién pulsada en el mando.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si hay algún botón pulsado
|
||||
auto Input::checkAnyButton(bool repeat) -> bool {
|
||||
// Solo comprueba los botones definidos previamente
|
||||
for (auto bi : BUTTON_INPUTS) {
|
||||
// Comprueba el teclado
|
||||
if (checkAction(bi, repeat, CHECK_KEYBOARD)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Comprueba los mandos
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si hay algun mando conectado
|
||||
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
|
||||
|
||||
// Obten el nombre de un mando de juego
|
||||
auto Input::getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string {
|
||||
return gamepad == nullptr ? std::string() : gamepad->name;
|
||||
}
|
||||
|
||||
// Obtiene la lista de nombres de mandos
|
||||
auto Input::getControllerNames() const -> std::vector<std::string> {
|
||||
std::vector<std::string> names;
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
names.push_back(gamepad->name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
// Obten el número de mandos conectados
|
||||
auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
|
||||
|
||||
// Obtiene el gamepad a partir de un event.id
|
||||
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (gamepad->instance_id == id) {
|
||||
return gamepad;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (gamepad && gamepad->name == name) {
|
||||
return gamepad;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Obtiene el SDL_GamepadButton asignado a un action
|
||||
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
|
||||
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
|
||||
}
|
||||
|
||||
// Convierte un InputAction a std::string
|
||||
auto Input::inputToString(Action action) -> std::string {
|
||||
switch (action) {
|
||||
case Action::FIRE_LEFT:
|
||||
return "input_fire_left";
|
||||
case Action::FIRE_CENTER:
|
||||
return "input_fire_center";
|
||||
case Action::FIRE_RIGHT:
|
||||
return "input_fire_right";
|
||||
case Action::START:
|
||||
return "input_start";
|
||||
case Action::SERVICE:
|
||||
return "input_service";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Convierte un std::string a InputAction
|
||||
auto Input::stringToInput(const std::string& name) -> Action {
|
||||
static const std::unordered_map<std::string, Action> INPUT_MAP = {
|
||||
{"input_fire_left", Action::FIRE_LEFT},
|
||||
{"input_fire_center", Action::FIRE_CENTER},
|
||||
{"input_fire_right", Action::FIRE_RIGHT},
|
||||
{"input_start", Action::START},
|
||||
{"input_service", Action::SERVICE}};
|
||||
|
||||
auto it = INPUT_MAP.find(name);
|
||||
return it != INPUT_MAP.end() ? it->second : Action::NONE;
|
||||
}
|
||||
|
||||
// Comprueba el eje del mando
|
||||
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||
// Umbral para considerar el eje como activo
|
||||
bool axis_active_now = false;
|
||||
|
||||
switch (action) {
|
||||
case Action::LEFT:
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
||||
break;
|
||||
case Action::RIGHT:
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
||||
break;
|
||||
case Action::UP:
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD;
|
||||
break;
|
||||
case Action::DOWN:
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
// Referencia al binding correspondiente
|
||||
auto& binding = gamepad->bindings[action];
|
||||
|
||||
if (repeat) {
|
||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||
return axis_active_now;
|
||||
} // Si no se permite repetir, aplicamos la lógica de transición
|
||||
if (axis_active_now && !binding.axis_active) {
|
||||
// Transición de inactivo a activo
|
||||
binding.axis_active = true;
|
||||
return true;
|
||||
}
|
||||
if (!axis_active_now && binding.axis_active) {
|
||||
// Transición de activo a inactivo
|
||||
binding.axis_active = false;
|
||||
}
|
||||
// Mantener el estado actual
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba los triggers del mando como botones digitales
|
||||
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||
// Solo manejamos botones específicos que pueden ser triggers
|
||||
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
|
||||
// Solo procesamos L2 y R2 como triggers
|
||||
int button = gamepad->bindings[action].button;
|
||||
|
||||
// Verificar si el botón mapeado corresponde a un trigger virtual
|
||||
// (Para esto necesitamos valores especiales que representen L2/R2 como botones)
|
||||
bool trigger_active_now = false;
|
||||
|
||||
// Usamos constantes especiales para L2 y R2 como botones
|
||||
if (button == TRIGGER_L2_AS_BUTTON) { // L2 como botón
|
||||
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER);
|
||||
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
|
||||
} else if (button == TRIGGER_R2_AS_BUTTON) { // R2 como botón
|
||||
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER);
|
||||
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
|
||||
} else {
|
||||
return false; // No es un trigger
|
||||
}
|
||||
|
||||
// Referencia al binding correspondiente
|
||||
auto& binding = gamepad->bindings[action];
|
||||
|
||||
if (repeat) {
|
||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||
return trigger_active_now;
|
||||
}
|
||||
|
||||
// Si no se permite repetir, aplicamos la lógica de transición
|
||||
if (trigger_active_now && !binding.trigger_active) {
|
||||
// Transición de inactivo a activo
|
||||
binding.trigger_active = true;
|
||||
return true;
|
||||
}
|
||||
if (!trigger_active_now && binding.trigger_active) {
|
||||
// Transición de activo a inactivo
|
||||
binding.trigger_active = false;
|
||||
}
|
||||
|
||||
// Mantener el estado actual
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void Input::addGamepadMappingsFromFile() {
|
||||
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
|
||||
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
void Input::discoverGamepads() {
|
||||
// Enumera los gamepads ya conectados sin drenar la cola de eventos de SDL
|
||||
// (necesario con SDL_MAIN_USE_CALLBACKS, que entrega los eventos por SDL_AppEvent).
|
||||
int count = 0;
|
||||
SDL_JoystickID* joysticks = SDL_GetGamepads(&count);
|
||||
if (joysticks == nullptr) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < count; ++i) {
|
||||
addGamepad(joysticks[i]);
|
||||
}
|
||||
SDL_free(joysticks);
|
||||
}
|
||||
|
||||
void Input::initSDLGamePad() {
|
||||
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
|
||||
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
|
||||
std::cout << "SDL_GAMEPAD could not initialize! SDL Error: " << SDL_GetError() << '\n';
|
||||
} else {
|
||||
addGamepadMappingsFromFile();
|
||||
loadGamepadConfigs();
|
||||
discoverGamepads();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) -> bool {
|
||||
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) -> bool {
|
||||
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.contains(action)) {
|
||||
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) -> bool {
|
||||
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) -> bool {
|
||||
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) -> bool {
|
||||
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;
|
||||
}
|
||||
227
source/core/input/input.hpp
Normal file
227
source/core/input/input.hpp
Normal file
@@ -0,0 +1,227 @@
|
||||
#pragma once
|
||||
|
||||
#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 <unordered_map> // Para unordered_map
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "gamepad_config_manager.hpp" // for GamepadConfig (ptr only), GamepadConfigs
|
||||
#include "input_types.hpp" // for InputAction
|
||||
|
||||
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
|
||||
class Input {
|
||||
public:
|
||||
// --- Constantes ---
|
||||
static constexpr bool ALLOW_REPEAT = true; // Permite repetición
|
||||
static constexpr bool DO_NOT_ALLOW_REPEAT = false; // No permite repetición
|
||||
static constexpr bool CHECK_KEYBOARD = true; // Comprueba teclado
|
||||
static constexpr bool DO_NOT_CHECK_KEYBOARD = false; // No comprueba teclado
|
||||
static constexpr int TRIGGER_L2_AS_BUTTON = 100; // L2 como botón
|
||||
static constexpr int TRIGGER_R2_AS_BUTTON = 101; // R2 como botón
|
||||
|
||||
// --- Tipos ---
|
||||
using Action = InputAction; // Alias para mantener compatibilidad
|
||||
|
||||
// --- Estructuras ---
|
||||
struct KeyState {
|
||||
Uint8 scancode; // Scancode asociado
|
||||
bool is_held; // Está pulsada ahora mismo
|
||||
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||
|
||||
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
|
||||
: scancode(scancode),
|
||||
is_held(is_held),
|
||||
just_pressed(just_pressed) {}
|
||||
};
|
||||
|
||||
struct ButtonState {
|
||||
int button; // GameControllerButton asociado
|
||||
bool is_held; // Está pulsada ahora mismo
|
||||
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||
bool axis_active; // Estado del eje
|
||||
bool trigger_active{false}; // Estado del trigger como botón digital
|
||||
|
||||
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
|
||||
: button(btn),
|
||||
is_held(is_held),
|
||||
just_pressed(just_pressed),
|
||||
axis_active(axis_act) {}
|
||||
};
|
||||
|
||||
struct Keyboard {
|
||||
std::unordered_map<Action, KeyState> bindings{
|
||||
// Movimiento del jugador
|
||||
{Action::UP, KeyState(SDL_SCANCODE_UP)},
|
||||
{Action::DOWN, KeyState(SDL_SCANCODE_DOWN)},
|
||||
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
|
||||
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
|
||||
|
||||
// Disparo del jugador
|
||||
{Action::FIRE_LEFT, KeyState(SDL_SCANCODE_Q)},
|
||||
{Action::FIRE_CENTER, KeyState(SDL_SCANCODE_W)},
|
||||
{Action::FIRE_RIGHT, KeyState(SDL_SCANCODE_E)},
|
||||
|
||||
// Interfaz
|
||||
{Action::START, KeyState(SDL_SCANCODE_RETURN)},
|
||||
|
||||
// Menu de servicio
|
||||
{Action::SERVICE, KeyState(SDL_SCANCODE_F12)},
|
||||
{Action::SM_SELECT, KeyState(SDL_SCANCODE_RETURN)},
|
||||
{Action::SM_BACK, KeyState(SDL_SCANCODE_BACKSPACE)},
|
||||
|
||||
// Control del programa
|
||||
{Action::EXIT, KeyState(SDL_SCANCODE_ESCAPE)},
|
||||
{Action::PAUSE, KeyState(SDL_SCANCODE_P)},
|
||||
{Action::BACK, KeyState(SDL_SCANCODE_BACKSPACE)},
|
||||
|
||||
{Action::WINDOW_DEC_SIZE, KeyState(SDL_SCANCODE_F1)},
|
||||
{Action::WINDOW_INC_SIZE, KeyState(SDL_SCANCODE_F2)},
|
||||
{Action::WINDOW_FULLSCREEN, KeyState(SDL_SCANCODE_F3)},
|
||||
{Action::TOGGLE_VIDEO_POSTFX, KeyState(SDL_SCANCODE_F4)},
|
||||
{Action::NEXT_SHADER, KeyState(SDL_SCANCODE_8)},
|
||||
{Action::NEXT_POSTFX_PRESET, KeyState(SDL_SCANCODE_9)},
|
||||
{Action::TOGGLE_SUPERSAMPLING, KeyState(SDL_SCANCODE_0)},
|
||||
{Action::TOGGLE_VIDEO_INTEGER_SCALE, KeyState(SDL_SCANCODE_F5)},
|
||||
{Action::TOGGLE_VIDEO_VSYNC, KeyState(SDL_SCANCODE_F6)},
|
||||
|
||||
{Action::TOGGLE_AUDIO, KeyState(SDL_SCANCODE_F7)},
|
||||
{Action::TOGGLE_AUTO_FIRE, KeyState(SDL_SCANCODE_F8)},
|
||||
{Action::CHANGE_LANG, KeyState(SDL_SCANCODE_F9)},
|
||||
|
||||
{Action::RESET, KeyState(SDL_SCANCODE_F10)},
|
||||
{Action::SHOW_INFO, KeyState(SDL_SCANCODE_F11)}};
|
||||
|
||||
Keyboard() = default;
|
||||
};
|
||||
|
||||
struct Gamepad {
|
||||
SDL_Gamepad* pad;
|
||||
SDL_JoystickID instance_id;
|
||||
std::string name;
|
||||
std::string path;
|
||||
std::unordered_map<Action, ButtonState> bindings;
|
||||
|
||||
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::UP, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_UP))},
|
||||
{Action::DOWN, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_DOWN))},
|
||||
{Action::LEFT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT))},
|
||||
{Action::RIGHT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT))},
|
||||
|
||||
// Disparo del jugador
|
||||
{Action::FIRE_LEFT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_WEST))},
|
||||
{Action::FIRE_CENTER, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_NORTH))},
|
||||
{Action::FIRE_RIGHT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_EAST))},
|
||||
|
||||
// Interfaz
|
||||
{Action::START, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_START))},
|
||||
{Action::SERVICE, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_BACK))},
|
||||
|
||||
// Menu de servicio
|
||||
{Action::SM_SELECT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_WEST))},
|
||||
{Action::SM_BACK, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_NORTH))}} {}
|
||||
|
||||
~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 auto get() -> Input*;
|
||||
|
||||
// --- Métodos de configuración de controles ---
|
||||
void bindKey(Action action, SDL_Scancode code);
|
||||
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button);
|
||||
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source);
|
||||
|
||||
// --- Métodos de consulta de entrada ---
|
||||
void update();
|
||||
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
|
||||
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
|
||||
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
|
||||
|
||||
// --- Métodos de gestión de mandos ---
|
||||
[[nodiscard]] auto gameControllerFound() const -> bool;
|
||||
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
|
||||
[[nodiscard]] auto getControllerNames() const -> std::vector<std::string>;
|
||||
[[nodiscard]] auto getNumGamepads() const -> int;
|
||||
[[nodiscard]] auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
|
||||
[[nodiscard]] auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
|
||||
[[nodiscard]] auto getGamepads() const -> const Gamepads& { return gamepads_; }
|
||||
|
||||
// --- Métodos de consulta y utilidades ---
|
||||
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
|
||||
[[nodiscard]] static auto inputToString(Action action) -> std::string;
|
||||
[[nodiscard]] static auto stringToInput(const std::string& name) -> Action;
|
||||
|
||||
// --- Métodos de reseteo de estado de entrada ---
|
||||
void resetInputStates();
|
||||
|
||||
// --- Eventos ---
|
||||
auto handleEvent(const SDL_Event& event) -> std::string;
|
||||
|
||||
void printConnectedGamepads() const;
|
||||
|
||||
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
|
||||
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr Sint16 AXIS_THRESHOLD = 30000;
|
||||
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (aproximadamente 50% del rango)
|
||||
static constexpr std::array<Action, 4> BUTTON_INPUTS = {Action::FIRE_LEFT, Action::FIRE_CENTER, Action::FIRE_RIGHT, Action::START}; // 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;
|
||||
};
|
||||
107
source/core/input/input_types.cpp
Normal file
107
source/core/input/input_types.cpp
Normal file
@@ -0,0 +1,107 @@
|
||||
#include "input_types.hpp"
|
||||
|
||||
#include <utility> // Para pair
|
||||
|
||||
// Definición de los mapas
|
||||
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
|
||||
{InputAction::FIRE_LEFT, "FIRE_LEFT"},
|
||||
{InputAction::FIRE_CENTER, "FIRE_CENTER"},
|
||||
{InputAction::FIRE_RIGHT, "FIRE_RIGHT"},
|
||||
{InputAction::START, "START"},
|
||||
{InputAction::SERVICE, "SERVICE"},
|
||||
{InputAction::UP, "UP"},
|
||||
{InputAction::DOWN, "DOWN"},
|
||||
{InputAction::LEFT, "LEFT"},
|
||||
{InputAction::RIGHT, "RIGHT"},
|
||||
{InputAction::SM_SELECT, "SM_SELECT"},
|
||||
{InputAction::SM_BACK, "SM_BACK"},
|
||||
{InputAction::BACK, "BACK"},
|
||||
{InputAction::EXIT, "EXIT"},
|
||||
{InputAction::PAUSE, "PAUSE"},
|
||||
{InputAction::WINDOW_FULLSCREEN, "WINDOW_FULLSCREEN"},
|
||||
{InputAction::WINDOW_INC_SIZE, "WINDOW_INC_SIZE"},
|
||||
{InputAction::WINDOW_DEC_SIZE, "WINDOW_DEC_SIZE"},
|
||||
{InputAction::TOGGLE_VIDEO_POSTFX, "TOGGLE_VIDEO_POSTFX"},
|
||||
{InputAction::NEXT_SHADER, "NEXT_SHADER"},
|
||||
{InputAction::NEXT_POSTFX_PRESET, "NEXT_POSTFX_PRESET"},
|
||||
{InputAction::TOGGLE_SUPERSAMPLING, "TOGGLE_SUPERSAMPLING"},
|
||||
{InputAction::TOGGLE_VIDEO_INTEGER_SCALE, "TOGGLE_VIDEO_INTEGER_SCALE"},
|
||||
{InputAction::TOGGLE_VIDEO_VSYNC, "TOGGLE_VIDEO_VSYNC"},
|
||||
{InputAction::RESET, "RESET"},
|
||||
{InputAction::TOGGLE_AUDIO, "TOGGLE_AUDIO"},
|
||||
{InputAction::CHANGE_LANG, "CHANGE_LANG"},
|
||||
{InputAction::SHOW_INFO, "SHOW_INFO"},
|
||||
{InputAction::CONFIG, "CONFIG"},
|
||||
{InputAction::SWAP_CONTROLLERS, "SWAP_CONTROLLERS"},
|
||||
{InputAction::TOGGLE_AUTO_FIRE, "TOGGLE_AUTO_FIRE"},
|
||||
{InputAction::NONE, "NONE"}};
|
||||
|
||||
const std::unordered_map<std::string, InputAction> STRING_TO_ACTION = {
|
||||
{"FIRE_LEFT", InputAction::FIRE_LEFT},
|
||||
{"FIRE_CENTER", InputAction::FIRE_CENTER},
|
||||
{"FIRE_RIGHT", InputAction::FIRE_RIGHT},
|
||||
{"START", InputAction::START},
|
||||
{"SERVICE", InputAction::SERVICE},
|
||||
{"UP", InputAction::UP},
|
||||
{"DOWN", InputAction::DOWN},
|
||||
{"LEFT", InputAction::LEFT},
|
||||
{"RIGHT", InputAction::RIGHT},
|
||||
{"SM_SELECT", InputAction::SM_SELECT},
|
||||
{"SM_BACK", InputAction::SM_BACK},
|
||||
{"BACK", InputAction::BACK},
|
||||
{"EXIT", InputAction::EXIT},
|
||||
{"PAUSE", InputAction::PAUSE},
|
||||
{"WINDOW_FULLSCREEN", InputAction::WINDOW_FULLSCREEN},
|
||||
{"WINDOW_INC_SIZE", InputAction::WINDOW_INC_SIZE},
|
||||
{"WINDOW_DEC_SIZE", InputAction::WINDOW_DEC_SIZE},
|
||||
{"TOGGLE_VIDEO_POSTFX", InputAction::TOGGLE_VIDEO_POSTFX},
|
||||
{"NEXT_SHADER", InputAction::NEXT_SHADER},
|
||||
{"NEXT_POSTFX_PRESET", InputAction::NEXT_POSTFX_PRESET},
|
||||
{"TOGGLE_SUPERSAMPLING", InputAction::TOGGLE_SUPERSAMPLING},
|
||||
{"TOGGLE_VIDEO_INTEGER_SCALE", InputAction::TOGGLE_VIDEO_INTEGER_SCALE},
|
||||
{"TOGGLE_VIDEO_VSYNC", InputAction::TOGGLE_VIDEO_VSYNC},
|
||||
{"RESET", InputAction::RESET},
|
||||
{"TOGGLE_AUDIO", InputAction::TOGGLE_AUDIO},
|
||||
{"CHANGE_LANG", InputAction::CHANGE_LANG},
|
||||
{"SHOW_INFO", InputAction::SHOW_INFO},
|
||||
{"CONFIG", InputAction::CONFIG},
|
||||
{"SWAP_CONTROLLERS", InputAction::SWAP_CONTROLLERS},
|
||||
{"TOGGLE_AUTO_FIRE", InputAction::TOGGLE_AUTO_FIRE},
|
||||
{"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)}};
|
||||
|
||||
const std::unordered_map<InputAction, InputAction> ACTION_TO_ACTION = {
|
||||
{InputAction::SM_SELECT, InputAction::FIRE_LEFT},
|
||||
{InputAction::SM_BACK, InputAction::FIRE_CENTER},
|
||||
};
|
||||
58
source/core/input/input_types.hpp
Normal file
58
source/core/input/input_types.hpp
Normal file
@@ -0,0 +1,58 @@
|
||||
#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
|
||||
UP,
|
||||
DOWN,
|
||||
LEFT,
|
||||
RIGHT,
|
||||
|
||||
// Inputs personalizados
|
||||
FIRE_LEFT,
|
||||
FIRE_CENTER,
|
||||
FIRE_RIGHT,
|
||||
START,
|
||||
|
||||
// Service Menu
|
||||
SM_SELECT,
|
||||
SM_BACK,
|
||||
|
||||
// Inputs de control
|
||||
BACK,
|
||||
EXIT,
|
||||
PAUSE,
|
||||
SERVICE,
|
||||
WINDOW_FULLSCREEN,
|
||||
WINDOW_INC_SIZE,
|
||||
WINDOW_DEC_SIZE,
|
||||
TOGGLE_VIDEO_POSTFX,
|
||||
NEXT_SHADER,
|
||||
NEXT_POSTFX_PRESET,
|
||||
TOGGLE_SUPERSAMPLING,
|
||||
TOGGLE_VIDEO_INTEGER_SCALE,
|
||||
TOGGLE_VIDEO_VSYNC,
|
||||
RESET,
|
||||
TOGGLE_AUDIO,
|
||||
CHANGE_LANG,
|
||||
SHOW_INFO,
|
||||
CONFIG,
|
||||
SWAP_CONTROLLERS,
|
||||
TOGGLE_AUTO_FIRE,
|
||||
|
||||
// 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
|
||||
extern const std::unordered_map<InputAction, InputAction> ACTION_TO_ACTION; // Mapeo de acción a acción
|
||||
27
source/core/input/mouse.cpp
Normal file
27
source/core/input/mouse.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
#include "mouse.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_HideCursor, SDL_Show...
|
||||
|
||||
namespace Mouse {
|
||||
Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor
|
||||
Uint32 last_mouse_move_time = 0; // Última vez que el ratón se movió
|
||||
bool cursor_visible = true; // Estado del cursor
|
||||
|
||||
void handleEvent(const SDL_Event& event) {
|
||||
if (event.type == SDL_EVENT_MOUSE_MOTION) {
|
||||
last_mouse_move_time = SDL_GetTicks();
|
||||
if (!cursor_visible) {
|
||||
SDL_ShowCursor();
|
||||
cursor_visible = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void updateCursorVisibility() {
|
||||
Uint32 current_time = SDL_GetTicks();
|
||||
if (cursor_visible && (current_time - last_mouse_move_time > cursor_hide_time)) {
|
||||
SDL_HideCursor();
|
||||
cursor_visible = false;
|
||||
}
|
||||
}
|
||||
} // namespace Mouse
|
||||
15
source/core/input/mouse.hpp
Normal file
15
source/core/input/mouse.hpp
Normal file
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h> // Para Uint32, SDL_Event
|
||||
|
||||
// --- Namespace Mouse: gestión del ratón ---
|
||||
namespace Mouse {
|
||||
// --- Variables de estado del cursor ---
|
||||
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor tras inactividad
|
||||
extern Uint32 last_mouse_move_time; // Última vez (en ms) que el ratón se movió
|
||||
extern bool cursor_visible; // Indica si el cursor está visible
|
||||
|
||||
// --- Funciones ---
|
||||
void handleEvent(const SDL_Event& event); // Procesa eventos de ratón (movimiento, clic, etc.)
|
||||
void updateCursorVisibility(); // Actualiza la visibilidad del cursor según la inactividad
|
||||
} // namespace Mouse
|
||||
135
source/core/input/pause_manager.hpp
Normal file
135
source/core/input/pause_manager.hpp
Normal file
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
// --- Clase PauseManager: maneja el sistema de pausa del juego ---
|
||||
class PauseManager {
|
||||
public:
|
||||
// --- Enums ---
|
||||
enum class Source : uint8_t { // Fuentes de pausa
|
||||
NONE = 0,
|
||||
PLAYER = 1 << 0, // 0001
|
||||
SERVICE_MENU = 1 << 1, // 0010
|
||||
FOCUS_LOST = 1 << 2 // 0100
|
||||
};
|
||||
|
||||
// --- Operadores friend ---
|
||||
friend auto operator|(Source a, Source b) -> Source {
|
||||
return static_cast<Source>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b)); // NOLINT(readability-redundant-casting)
|
||||
}
|
||||
|
||||
friend auto operator&(Source a, Source b) -> Source {
|
||||
return static_cast<Source>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b)); // NOLINT(readability-redundant-casting)
|
||||
}
|
||||
|
||||
friend auto operator~(Source a) -> uint8_t {
|
||||
return ~static_cast<uint8_t>(a);
|
||||
}
|
||||
|
||||
friend auto operator&=(Source& a, uint8_t b) -> Source& {
|
||||
a = static_cast<Source>(static_cast<uint8_t>(a) & b);
|
||||
return a;
|
||||
}
|
||||
|
||||
friend auto operator|=(Source& a, Source b) -> Source& {
|
||||
return a = a | b;
|
||||
}
|
||||
|
||||
friend auto operator&=(Source& a, Source b) -> Source& {
|
||||
return a = a & b;
|
||||
}
|
||||
|
||||
// --- Constructor y destructor ---
|
||||
explicit PauseManager(std::function<void(bool)> callback = nullptr) // Constructor con callback opcional
|
||||
: on_pause_changed_callback_(std::move(callback)) {}
|
||||
|
||||
// --- Métodos principales ---
|
||||
void setFlag(Source source, bool enable) { // Establece/quita una fuente de pausa específica
|
||||
bool was_paused = isPaused();
|
||||
|
||||
if (enable) {
|
||||
flags_ |= source;
|
||||
} else {
|
||||
flags_ &= ~source; // Ahora funciona: Source &= uint8_t
|
||||
}
|
||||
|
||||
if (was_paused != isPaused()) {
|
||||
notifyPauseChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// --- Métodos específicos para cada fuente ---
|
||||
void setPlayerPause(bool enable) { setFlag(Source::PLAYER, enable); }
|
||||
void setServiceMenuPause(bool enable) { setFlag(Source::SERVICE_MENU, enable); }
|
||||
void setFocusLossPause(bool enable) { setFlag(Source::FOCUS_LOST, enable); }
|
||||
|
||||
void togglePlayerPause() { setPlayerPause(!isPlayerPaused()); } // Toggle para el jugador (más común)
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto isPaused() const -> bool { return flags_ != Source::NONE; }
|
||||
[[nodiscard]] auto isPlayerPaused() const -> bool { return hasFlag(Source::PLAYER); }
|
||||
[[nodiscard]] auto isServiceMenuPaused() const -> bool { return hasFlag(Source::SERVICE_MENU); }
|
||||
[[nodiscard]] auto isFocusLossPaused() const -> bool { return hasFlag(Source::FOCUS_LOST); }
|
||||
|
||||
[[nodiscard]] auto getFlags() const -> Source { return flags_; } // Obtiene las banderas actuales
|
||||
|
||||
// --- Métodos de utilidad ---
|
||||
void clearAll() { // Limpia todas las pausas (útil para reset)
|
||||
if (isPaused()) {
|
||||
flags_ = Source::NONE;
|
||||
notifyPauseChanged();
|
||||
}
|
||||
}
|
||||
[[nodiscard]] auto getStatusString() const -> std::string { // Método para debug
|
||||
if (flags_ == Source::NONE) {
|
||||
return "Active";
|
||||
}
|
||||
|
||||
std::string result = "Paused by: ";
|
||||
bool first = true;
|
||||
|
||||
if (hasFlag(Source::PLAYER)) {
|
||||
if (!first) {
|
||||
result += ", ";
|
||||
}
|
||||
result += "Player";
|
||||
first = false;
|
||||
}
|
||||
if (hasFlag(Source::SERVICE_MENU)) {
|
||||
if (!first) {
|
||||
result += ", ";
|
||||
}
|
||||
result += "ServiceMenu";
|
||||
first = false;
|
||||
}
|
||||
if (hasFlag(Source::FOCUS_LOST)) {
|
||||
if (!first) {
|
||||
result += ", ";
|
||||
}
|
||||
result += "FocusLoss";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
void setCallback(std::function<void(bool)> callback) { // Permite cambiar el callback en runtime
|
||||
on_pause_changed_callback_ = std::move(callback);
|
||||
}
|
||||
|
||||
private:
|
||||
// --- Variables ---
|
||||
Source flags_ = Source::NONE;
|
||||
std::function<void(bool)> on_pause_changed_callback_;
|
||||
|
||||
// --- Métodos internos ---
|
||||
[[nodiscard]] auto hasFlag(Source flag) const -> bool {
|
||||
return (flags_ & flag) != Source::NONE;
|
||||
}
|
||||
void notifyPauseChanged() {
|
||||
if (on_pause_changed_callback_) {
|
||||
on_pause_changed_callback_(isPaused());
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user