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