integrada classe Input
This commit is contained in:
594
source/core/input/input.cpp
Normal file
594
source/core/input/input.cpp
Normal file
@@ -0,0 +1,594 @@
|
||||
#include "core/input/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
|
||||
|
||||
#include "game/options.hpp" // Para Options::controls
|
||||
|
||||
// Singleton
|
||||
Input* Input::instance = nullptr;
|
||||
|
||||
// Inicializa la instancia única del singleton
|
||||
void Input::init(const std::string& game_controller_db_path) {
|
||||
Input::instance = new Input(game_controller_db_path);
|
||||
}
|
||||
|
||||
// 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)
|
||||
: gamepad_mappings_file_(std::move(game_controller_db_path)) {
|
||||
// Inicializar bindings del teclado (valores por defecto)
|
||||
// Estos serán sobrescritos por applyPlayer1BindingsFromOptions()
|
||||
keyboard_.bindings = {
|
||||
// Movimiento del jugador
|
||||
{Action::LEFT, KeyState{.scancode = SDL_SCANCODE_LEFT}},
|
||||
{Action::RIGHT, KeyState{.scancode = SDL_SCANCODE_RIGHT}},
|
||||
{Action::THRUST, KeyState{.scancode = SDL_SCANCODE_UP}},
|
||||
{Action::SHOOT, KeyState{.scancode = SDL_SCANCODE_SPACE}},
|
||||
|
||||
// Inputs de sistema (globales)
|
||||
{Action::WINDOW_DEC_ZOOM, KeyState{.scancode = SDL_SCANCODE_F1}},
|
||||
{Action::WINDOW_INC_ZOOM, KeyState{.scancode = SDL_SCANCODE_F2}},
|
||||
{Action::TOGGLE_FULLSCREEN, KeyState{.scancode = SDL_SCANCODE_F3}},
|
||||
{Action::TOGGLE_VSYNC, KeyState{.scancode = SDL_SCANCODE_F4}},
|
||||
{Action::EXIT, KeyState{.scancode = SDL_SCANCODE_ESCAPE}}};
|
||||
|
||||
initSDLGamePad(); // Inicializa el subsistema SDL_INIT_GAMEPAD
|
||||
}
|
||||
|
||||
// Asigna inputs a teclas
|
||||
void Input::bindKey(Action action, SDL_Scancode code) {
|
||||
keyboard_.bindings[action].scancode = code;
|
||||
}
|
||||
|
||||
// Aplica las teclas configuradas desde Options
|
||||
void Input::applyKeyboardBindingsFromOptions() {
|
||||
bindKey(Action::LEFT, Options::keyboard_controls.key_left);
|
||||
bindKey(Action::RIGHT, Options::keyboard_controls.key_right);
|
||||
bindKey(Action::THRUST, Options::keyboard_controls.key_thrust);
|
||||
}
|
||||
|
||||
// Aplica configuración de botones del gamepad desde Options al primer gamepad conectado
|
||||
void Input::applyGamepadBindingsFromOptions() {
|
||||
// Si no hay gamepads conectados, no hay nada que hacer
|
||||
if (gamepads_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Obtener el primer gamepad conectado
|
||||
const auto& gamepad = gamepads_[0];
|
||||
|
||||
// Aplicar bindings desde Options
|
||||
// Los valores pueden ser:
|
||||
// - 0-20+: Botones SDL_GamepadButton (DPAD, face buttons, shoulders)
|
||||
// - 100: L2 trigger
|
||||
// - 101: R2 trigger
|
||||
// - 200+: Ejes del stick analógico
|
||||
gamepad->bindings[Action::LEFT].button = Options::gamepad_controls.button_left;
|
||||
gamepad->bindings[Action::RIGHT].button = Options::gamepad_controls.button_right;
|
||||
gamepad->bindings[Action::THRUST].button = Options::gamepad_controls.button_thrust;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
// Si gamepad es nullptr pero hay mandos conectados, usar el primero
|
||||
std::shared_ptr<Gamepad> active_gamepad = gamepad;
|
||||
if (active_gamepad == nullptr && !gamepads_.empty()) {
|
||||
active_gamepad = gamepads_[0];
|
||||
}
|
||||
|
||||
if (active_gamepad != nullptr) {
|
||||
success_controller = checkAxisInput(action, active_gamepad, repeat);
|
||||
|
||||
if (!success_controller) {
|
||||
success_controller = checkTriggerInput(action, active_gamepad, repeat);
|
||||
}
|
||||
|
||||
if (!success_controller) {
|
||||
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||
success_controller = active_gamepad->bindings[action].is_held;
|
||||
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||
success_controller = active_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.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si gamepad es nullptr pero hay mandos conectados, usar el primero
|
||||
std::shared_ptr<Gamepad> active_gamepad = gamepad;
|
||||
if (active_gamepad == nullptr && !gamepads_.empty()) {
|
||||
active_gamepad = gamepads_[0];
|
||||
}
|
||||
|
||||
// --- Comprobación del Mando ---
|
||||
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
||||
if (active_gamepad != nullptr) {
|
||||
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
||||
for (const auto& pair : active_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);
|
||||
}
|
||||
|
||||
// Comprueba el eje del mando
|
||||
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||
// Obtener el binding configurado para esta acción
|
||||
auto& binding = gamepad->bindings[action];
|
||||
|
||||
// Solo revisar ejes si el binding está configurado como eje (valores 200+)
|
||||
// 200 = Left stick izquierda, 201 = Left stick derecha
|
||||
if (binding.button < 200) {
|
||||
// El binding no es un eje, no revisar axis
|
||||
return false;
|
||||
}
|
||||
|
||||
// Determinar qué eje y dirección revisar según el binding
|
||||
bool axis_active_now = false;
|
||||
|
||||
if (binding.button == 200) {
|
||||
// Left stick izquierda
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
||||
} else if (binding.button == 201) {
|
||||
// Left stick derecha
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
||||
} else {
|
||||
// Binding de eje no soportado
|
||||
return false;
|
||||
}
|
||||
|
||||
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() {
|
||||
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();
|
||||
discoverGamepads();
|
||||
std::cout << "\n** INPUT SYSTEM **\n";
|
||||
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 (const 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);
|
||||
|
||||
// Actualizar bindings globales (F1-F4, ESC)
|
||||
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;
|
||||
}
|
||||
|
||||
// Actualizar bindings de jugador 1
|
||||
for (auto& binding : player1_keyboard_bindings_) {
|
||||
bool key_is_down_now = key_states[binding.second.scancode];
|
||||
binding.second.just_pressed = key_is_down_now && !binding.second.is_held;
|
||||
binding.second.is_held = key_is_down_now;
|
||||
}
|
||||
|
||||
// Actualizar bindings de jugador 2
|
||||
for (auto& binding : player2_keyboard_bindings_) {
|
||||
bool key_is_down_now = key_states[binding.second.scancode];
|
||||
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';
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// ========== MÉTODOS ESPECÍFICOS POR JUGADOR (ORNI) ==========
|
||||
|
||||
// Aplica configuración de controles del jugador 1
|
||||
void Input::applyPlayer1BindingsFromOptions() {
|
||||
// 1. Aplicar bindings de teclado (NO usar bindKey, llenar mapa específico)
|
||||
player1_keyboard_bindings_[Action::LEFT].scancode = Options::player1.keyboard.key_left;
|
||||
player1_keyboard_bindings_[Action::RIGHT].scancode = Options::player1.keyboard.key_right;
|
||||
player1_keyboard_bindings_[Action::THRUST].scancode = Options::player1.keyboard.key_thrust;
|
||||
player1_keyboard_bindings_[Action::SHOOT].scancode = Options::player1.keyboard.key_shoot;
|
||||
|
||||
// 2. Encontrar gamepad por nombre (o usar primer gamepad como fallback)
|
||||
std::shared_ptr<Gamepad> gamepad = nullptr;
|
||||
if (Options::player1.gamepad_name.empty()) {
|
||||
// Fallback: usar primer gamepad disponible
|
||||
gamepad = (gamepads_.size() > 0) ? gamepads_[0] : nullptr;
|
||||
} else {
|
||||
// Buscar por nombre
|
||||
gamepad = findAvailableGamepadByName(Options::player1.gamepad_name);
|
||||
}
|
||||
|
||||
if (!gamepad) {
|
||||
player1_gamepad_ = nullptr;
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Aplicar bindings de gamepad
|
||||
gamepad->bindings[Action::LEFT].button = Options::player1.gamepad.button_left;
|
||||
gamepad->bindings[Action::RIGHT].button = Options::player1.gamepad.button_right;
|
||||
gamepad->bindings[Action::THRUST].button = Options::player1.gamepad.button_thrust;
|
||||
gamepad->bindings[Action::SHOOT].button = Options::player1.gamepad.button_shoot;
|
||||
|
||||
// 4. Cachear referencia
|
||||
player1_gamepad_ = gamepad;
|
||||
}
|
||||
|
||||
// Aplica configuración de controles del jugador 2
|
||||
void Input::applyPlayer2BindingsFromOptions() {
|
||||
// 1. Aplicar bindings de teclado (mapa específico de P2, no sobrescribe P1)
|
||||
player2_keyboard_bindings_[Action::LEFT].scancode = Options::player2.keyboard.key_left;
|
||||
player2_keyboard_bindings_[Action::RIGHT].scancode = Options::player2.keyboard.key_right;
|
||||
player2_keyboard_bindings_[Action::THRUST].scancode = Options::player2.keyboard.key_thrust;
|
||||
player2_keyboard_bindings_[Action::SHOOT].scancode = Options::player2.keyboard.key_shoot;
|
||||
|
||||
// 2. Encontrar gamepad por nombre (o usar segundo gamepad como fallback)
|
||||
std::shared_ptr<Gamepad> gamepad = nullptr;
|
||||
if (Options::player2.gamepad_name.empty()) {
|
||||
// Fallback: usar segundo gamepad disponible
|
||||
gamepad = (gamepads_.size() > 1) ? gamepads_[1] : nullptr;
|
||||
} else {
|
||||
// Buscar por nombre
|
||||
gamepad = findAvailableGamepadByName(Options::player2.gamepad_name);
|
||||
}
|
||||
|
||||
if (!gamepad) {
|
||||
player2_gamepad_ = nullptr;
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Aplicar bindings de gamepad
|
||||
gamepad->bindings[Action::LEFT].button = Options::player2.gamepad.button_left;
|
||||
gamepad->bindings[Action::RIGHT].button = Options::player2.gamepad.button_right;
|
||||
gamepad->bindings[Action::THRUST].button = Options::player2.gamepad.button_thrust;
|
||||
gamepad->bindings[Action::SHOOT].button = Options::player2.gamepad.button_shoot;
|
||||
|
||||
// 4. Cachear referencia
|
||||
player2_gamepad_ = gamepad;
|
||||
}
|
||||
|
||||
// Consulta de input para jugador 1
|
||||
auto Input::checkActionPlayer1(Action action, bool repeat) -> bool {
|
||||
// Comprobar teclado con el mapa específico de P1
|
||||
bool keyboard_active = false;
|
||||
|
||||
if (player1_keyboard_bindings_.contains(action)) {
|
||||
if (repeat) {
|
||||
keyboard_active = player1_keyboard_bindings_[action].is_held;
|
||||
} else {
|
||||
keyboard_active = player1_keyboard_bindings_[action].just_pressed;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprobar gamepad de P1
|
||||
bool gamepad_active = false;
|
||||
if (player1_gamepad_) {
|
||||
gamepad_active = checkAction(action, repeat, DO_NOT_CHECK_KEYBOARD, player1_gamepad_);
|
||||
}
|
||||
|
||||
return keyboard_active || gamepad_active;
|
||||
}
|
||||
|
||||
// Consulta de input para jugador 2
|
||||
auto Input::checkActionPlayer2(Action action, bool repeat) -> bool {
|
||||
// Comprobar teclado con el mapa específico de P2
|
||||
bool keyboard_active = false;
|
||||
|
||||
if (player2_keyboard_bindings_.contains(action)) {
|
||||
if (repeat) {
|
||||
keyboard_active = player2_keyboard_bindings_[action].is_held;
|
||||
} else {
|
||||
keyboard_active = player2_keyboard_bindings_[action].just_pressed;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprobar gamepad de P2
|
||||
bool gamepad_active = false;
|
||||
if (player2_gamepad_) {
|
||||
gamepad_active = checkAction(action, repeat, DO_NOT_CHECK_KEYBOARD, player2_gamepad_);
|
||||
}
|
||||
|
||||
return keyboard_active || gamepad_active;
|
||||
}
|
||||
158
source/core/input/input.hpp
Normal file
158
source/core/input/input.hpp
Normal file
@@ -0,0 +1,158 @@
|
||||
#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 "core/input/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{0}; // Scancode asociado
|
||||
bool is_held{false}; // Está pulsada ahora mismo
|
||||
bool just_pressed{false}; // Se acaba de pulsar en este fotograma
|
||||
};
|
||||
|
||||
struct ButtonState {
|
||||
int button{static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)}; // GameControllerButton asociado
|
||||
bool is_held{false}; // Está pulsada ahora mismo
|
||||
bool just_pressed{false}; // Se acaba de pulsar en este fotograma
|
||||
bool axis_active{false}; // Estado del eje
|
||||
bool trigger_active{false}; // Estado del trigger como botón digital
|
||||
};
|
||||
|
||||
struct Keyboard {
|
||||
std::unordered_map<Action, KeyState> bindings; // Mapa de acciones a estados de tecla
|
||||
};
|
||||
|
||||
struct Gamepad {
|
||||
SDL_Gamepad* pad{nullptr}; // Puntero al gamepad SDL
|
||||
SDL_JoystickID instance_id{0}; // ID de instancia del joystick
|
||||
std::string name; // Nombre del gamepad
|
||||
std::string path; // Ruta del dispositivo
|
||||
std::unordered_map<Action, ButtonState> bindings; // Mapa de acciones a estados de botón
|
||||
|
||||
explicit 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 y acciones del jugador
|
||||
{Action::LEFT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT)}},
|
||||
{Action::RIGHT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT)}},
|
||||
{Action::THRUST, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_WEST)}},
|
||||
{Action::SHOOT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_SOUTH)}}} {}
|
||||
|
||||
~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].button = static_cast<int>(new_button);
|
||||
}
|
||||
};
|
||||
|
||||
// --- Tipos ---
|
||||
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
|
||||
|
||||
// --- Singleton ---
|
||||
static void init(const std::string& game_controller_db_path);
|
||||
static void destroy();
|
||||
static auto get() -> Input*;
|
||||
|
||||
// --- Actualización del sistema ---
|
||||
void update(); // Actualiza estados de entrada
|
||||
|
||||
// --- Configuración de controles ---
|
||||
void bindKey(Action action, SDL_Scancode code);
|
||||
void applyKeyboardBindingsFromOptions();
|
||||
void applyGamepadBindingsFromOptions();
|
||||
|
||||
// Configuración por jugador (Orni - dos jugadores)
|
||||
void applyPlayer1BindingsFromOptions();
|
||||
void applyPlayer2BindingsFromOptions();
|
||||
|
||||
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);
|
||||
|
||||
// --- Consulta de entrada ---
|
||||
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;
|
||||
void resetInputStates();
|
||||
|
||||
// Consulta por jugador (Orni - dos jugadores)
|
||||
auto checkActionPlayer1(Action action, bool repeat = true) -> bool;
|
||||
auto checkActionPlayer2(Action action, bool repeat = true) -> bool;
|
||||
|
||||
// --- Gestión de gamepads ---
|
||||
[[nodiscard]] auto gameControllerFound() const -> bool;
|
||||
[[nodiscard]] auto getNumGamepads() const -> int;
|
||||
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
|
||||
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
|
||||
auto getGamepads() const -> const Gamepads& { return gamepads_; }
|
||||
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
|
||||
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
|
||||
auto getControllerNames() const -> std::vector<std::string>;
|
||||
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
|
||||
void printConnectedGamepads() const;
|
||||
|
||||
// --- Eventos ---
|
||||
auto handleEvent(const SDL_Event& event) -> std::string;
|
||||
|
||||
private:
|
||||
// --- Constantes ---
|
||||
static constexpr Sint16 AXIS_THRESHOLD = 30000; // Umbral para ejes analógicos
|
||||
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (50% del rango)
|
||||
static constexpr std::array<Action, 1> BUTTON_INPUTS = {Action::SHOOT}; // Inputs que usan botones
|
||||
|
||||
// --- Métodos ---
|
||||
explicit Input(std::string game_controller_db_path);
|
||||
~Input() = default;
|
||||
|
||||
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();
|
||||
|
||||
// --- Variables miembro ---
|
||||
static Input* instance; // Instancia única del singleton
|
||||
|
||||
Gamepads gamepads_; // Lista de gamepads conectados
|
||||
Keyboard keyboard_{}; // Estado del teclado (solo acciones globales)
|
||||
std::string gamepad_mappings_file_; // Ruta al archivo de mappings
|
||||
|
||||
// Referencias cacheadas a gamepads por jugador (Orni)
|
||||
std::shared_ptr<Gamepad> player1_gamepad_;
|
||||
std::shared_ptr<Gamepad> player2_gamepad_;
|
||||
|
||||
// Mapas de bindings separados por jugador (Orni - dos jugadores)
|
||||
std::unordered_map<Action, KeyState> player1_keyboard_bindings_;
|
||||
std::unordered_map<Action, KeyState> player2_keyboard_bindings_;
|
||||
};
|
||||
60
source/core/input/input_types.cpp
Normal file
60
source/core/input/input_types.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#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::THRUST, "THRUST"},
|
||||
{InputAction::SHOOT, "SHOOT"},
|
||||
{InputAction::WINDOW_INC_ZOOM, "WINDOW_INC_ZOOM"},
|
||||
{InputAction::WINDOW_DEC_ZOOM, "WINDOW_DEC_ZOOM"},
|
||||
{InputAction::TOGGLE_FULLSCREEN, "TOGGLE_FULLSCREEN"},
|
||||
{InputAction::TOGGLE_VSYNC, "TOGGLE_VSYNC"},
|
||||
{InputAction::EXIT, "EXIT"},
|
||||
{InputAction::NONE, "NONE"}};
|
||||
|
||||
const std::unordered_map<std::string, InputAction> STRING_TO_ACTION = {
|
||||
{"LEFT", InputAction::LEFT},
|
||||
{"RIGHT", InputAction::RIGHT},
|
||||
{"THRUST", InputAction::THRUST},
|
||||
{"SHOOT", InputAction::SHOOT},
|
||||
{"WINDOW_INC_ZOOM", InputAction::WINDOW_INC_ZOOM},
|
||||
{"WINDOW_DEC_ZOOM", InputAction::WINDOW_DEC_ZOOM},
|
||||
{"TOGGLE_FULLSCREEN", InputAction::TOGGLE_FULLSCREEN},
|
||||
{"TOGGLE_VSYNC", InputAction::TOGGLE_VSYNC},
|
||||
{"EXIT", InputAction::EXIT},
|
||||
{"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)}};
|
||||
32
source/core/input/input_types.hpp
Normal file
32
source/core/input/input_types.hpp
Normal file
@@ -0,0 +1,32 @@
|
||||
#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 juego (movimiento y acción)
|
||||
LEFT, // Rotar izquierda
|
||||
RIGHT, // Rotar derecha
|
||||
THRUST, // Acelerar
|
||||
SHOOT, // Disparar
|
||||
|
||||
// Inputs de sistema (globales)
|
||||
WINDOW_INC_ZOOM, // F2
|
||||
WINDOW_DEC_ZOOM, // F1
|
||||
TOGGLE_FULLSCREEN, // F3
|
||||
TOGGLE_VSYNC, // F4
|
||||
EXIT, // ESC
|
||||
|
||||
// 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
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/audio/audio_cache.hpp"
|
||||
#include "core/defaults.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/rendering/sdl_manager.hpp"
|
||||
#include "core/resources/resource_helper.hpp"
|
||||
#include "core/resources/resource_loader.hpp"
|
||||
@@ -88,12 +89,21 @@ Director::Director(std::vector<std::string> const& args) {
|
||||
// Carregar o crear configuració
|
||||
Options::loadFromFile();
|
||||
|
||||
// Inicialitzar sistema d'input
|
||||
Input::init("data/gamecontrollerdb.txt");
|
||||
|
||||
// Aplicar configuració de controls dels jugadors
|
||||
Input::get()->applyPlayer1BindingsFromOptions();
|
||||
Input::get()->applyPlayer2BindingsFromOptions();
|
||||
|
||||
if (Options::console) {
|
||||
std::cout << "Configuració carregada\n";
|
||||
std::cout << " Finestra: " << Options::window.width << "×"
|
||||
<< Options::window.height << '\n';
|
||||
std::cout << " Física: rotation=" << Options::physics.rotation_speed
|
||||
<< " rad/s\n";
|
||||
std::cout << " Input: " << Input::get()->getNumGamepads()
|
||||
<< " gamepad(s) detectat(s)\n";
|
||||
}
|
||||
|
||||
std::cout << '\n';
|
||||
@@ -103,6 +113,9 @@ Director::~Director() {
|
||||
// Guardar opcions
|
||||
Options::saveToFile();
|
||||
|
||||
// Cleanup input
|
||||
Input::destroy();
|
||||
|
||||
// Cleanup audio
|
||||
Audio::destroy();
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
#include "global_events.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/input/mouse.hpp"
|
||||
#include "core/rendering/sdl_manager.hpp"
|
||||
#include "context_escenes.hpp"
|
||||
@@ -14,40 +17,53 @@ using Escena = ContextEscenes::Escena;
|
||||
namespace GlobalEvents {
|
||||
|
||||
bool handle(const SDL_Event& event, SDLManager& sdl, ContextEscenes& context) {
|
||||
// Tecles globals de finestra (F1/F2/F3)
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_F1:
|
||||
sdl.decreaseWindowSize();
|
||||
return true;
|
||||
case SDLK_F2:
|
||||
sdl.increaseWindowSize();
|
||||
return true;
|
||||
case SDLK_F3:
|
||||
sdl.toggleFullscreen();
|
||||
return true;
|
||||
case SDLK_F4:
|
||||
sdl.toggleVSync();
|
||||
return true;
|
||||
case SDLK_ESCAPE:
|
||||
context.canviar_escena(Escena::EIXIR);
|
||||
GestorEscenes::actual = Escena::EIXIR;
|
||||
return true;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
// 1. Permitir que Input procese el evento (para hotplug de gamepads)
|
||||
auto event_msg = Input::get()->handleEvent(event);
|
||||
if (!event_msg.empty()) {
|
||||
std::cout << "[Input] " << event_msg << std::endl;
|
||||
}
|
||||
|
||||
// Tancar finestra
|
||||
// 2. Procesar SDL_EVENT_QUIT directamente (no es input de juego)
|
||||
if (event.type == SDL_EVENT_QUIT) {
|
||||
context.canviar_escena(Escena::EIXIR);
|
||||
GestorEscenes::actual = Escena::EIXIR;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Gestió del ratolí (auto-ocultar)
|
||||
// 3. Gestió del ratolí (auto-ocultar)
|
||||
Mouse::handleEvent(event);
|
||||
|
||||
// 4. Procesar acciones globales directamente desde eventos SDL
|
||||
// (NO usar Input::checkAction() para evitar desfase de timing)
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
switch (event.key.scancode) {
|
||||
case SDL_SCANCODE_F1:
|
||||
sdl.decreaseWindowSize();
|
||||
return true;
|
||||
|
||||
case SDL_SCANCODE_F2:
|
||||
sdl.increaseWindowSize();
|
||||
return true;
|
||||
|
||||
case SDL_SCANCODE_F3:
|
||||
sdl.toggleFullscreen();
|
||||
return true;
|
||||
|
||||
case SDL_SCANCODE_F4:
|
||||
sdl.toggleVSync();
|
||||
return true;
|
||||
|
||||
case SDL_SCANCODE_ESCAPE:
|
||||
context.canviar_escena(Escena::EIXIR);
|
||||
GestorEscenes::actual = Escena::EIXIR;
|
||||
return true;
|
||||
|
||||
default:
|
||||
// Tecla no global
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return false; // Event no processat
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "core/defaults.hpp"
|
||||
#include "core/graphics/shape_loader.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/rendering/shape_renderer.hpp"
|
||||
#include "game/constants.hpp"
|
||||
|
||||
@@ -71,35 +72,43 @@ void Nau::processar_input(float delta_time, uint8_t player_id) {
|
||||
if (esta_tocada_)
|
||||
return;
|
||||
|
||||
// Obtenir estat actual del teclat (no events, sinó estat continu)
|
||||
const bool* keyboard_state = SDL_GetKeyboardState(nullptr);
|
||||
auto* input = Input::get();
|
||||
|
||||
// Seleccionar controles según player_id
|
||||
SDL_Scancode key_right = (player_id == 0)
|
||||
? Defaults::Controls::P1::ROTATE_RIGHT
|
||||
: Defaults::Controls::P2::ROTATE_RIGHT;
|
||||
SDL_Scancode key_left = (player_id == 0)
|
||||
? Defaults::Controls::P1::ROTATE_LEFT
|
||||
: Defaults::Controls::P2::ROTATE_LEFT;
|
||||
SDL_Scancode key_thrust = (player_id == 0)
|
||||
? Defaults::Controls::P1::THRUST
|
||||
: Defaults::Controls::P2::THRUST;
|
||||
// Processar input segons el jugador
|
||||
if (player_id == 0) {
|
||||
// Jugador 1
|
||||
if (input->checkActionPlayer1(InputAction::RIGHT, Input::ALLOW_REPEAT)) {
|
||||
angle_ += Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
|
||||
// Rotació
|
||||
if (keyboard_state[key_right]) {
|
||||
angle_ += Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
if (input->checkActionPlayer1(InputAction::LEFT, Input::ALLOW_REPEAT)) {
|
||||
angle_ -= Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
|
||||
if (keyboard_state[key_left]) {
|
||||
angle_ -= Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
if (input->checkActionPlayer1(InputAction::THRUST, Input::ALLOW_REPEAT)) {
|
||||
if (velocitat_ < Defaults::Physics::MAX_VELOCITY) {
|
||||
velocitat_ += Defaults::Physics::ACCELERATION * delta_time;
|
||||
if (velocitat_ > Defaults::Physics::MAX_VELOCITY) {
|
||||
velocitat_ = Defaults::Physics::MAX_VELOCITY;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Jugador 2
|
||||
if (input->checkActionPlayer2(InputAction::RIGHT, Input::ALLOW_REPEAT)) {
|
||||
angle_ += Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
|
||||
// Acceleració
|
||||
if (keyboard_state[key_thrust]) {
|
||||
if (velocitat_ < Defaults::Physics::MAX_VELOCITY) {
|
||||
velocitat_ += Defaults::Physics::ACCELERATION * delta_time;
|
||||
if (velocitat_ > Defaults::Physics::MAX_VELOCITY) {
|
||||
velocitat_ = Defaults::Physics::MAX_VELOCITY;
|
||||
if (input->checkActionPlayer2(InputAction::LEFT, Input::ALLOW_REPEAT)) {
|
||||
angle_ -= Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
|
||||
if (input->checkActionPlayer2(InputAction::THRUST, Input::ALLOW_REPEAT)) {
|
||||
if (velocitat_ < Defaults::Physics::MAX_VELOCITY) {
|
||||
velocitat_ += Defaults::Physics::ACCELERATION * delta_time;
|
||||
if (velocitat_ > Defaults::Physics::MAX_VELOCITY) {
|
||||
velocitat_ = Defaults::Physics::MAX_VELOCITY;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/input/mouse.hpp"
|
||||
#include "core/math/easing.hpp"
|
||||
#include "core/rendering/line_renderer.hpp"
|
||||
@@ -74,6 +75,9 @@ void EscenaJoc::executar() {
|
||||
// Actualitzar visibilitat del cursor (auto-ocultar)
|
||||
Mouse::updateCursorVisibility();
|
||||
|
||||
// Actualitzar sistema d'input ABANS del event loop
|
||||
Input::get()->update();
|
||||
|
||||
// Processar events SDL
|
||||
while (SDL_PollEvent(&event)) {
|
||||
// Manejo de finestra
|
||||
@@ -82,12 +86,7 @@ void EscenaJoc::executar() {
|
||||
}
|
||||
|
||||
// Events globals (F1/F2/F3/ESC/QUIT)
|
||||
if (GlobalEvents::handle(event, sdl_, context_)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Processament específic del joc (SPACE per disparar)
|
||||
processar_input(event);
|
||||
GlobalEvents::handle(event, sdl_, context_);
|
||||
}
|
||||
|
||||
// Actualitzar física del joc amb delta_time real
|
||||
@@ -180,6 +179,21 @@ void EscenaJoc::inicialitzar() {
|
||||
}
|
||||
|
||||
void EscenaJoc::actualitzar(float delta_time) {
|
||||
// Processar disparos (state-based, no event-based)
|
||||
if (!game_over_) {
|
||||
auto* input = Input::get();
|
||||
|
||||
// Jugador 1 dispara
|
||||
if (input->checkActionPlayer1(InputAction::SHOOT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
disparar_bala(0);
|
||||
}
|
||||
|
||||
// Jugador 2 dispara
|
||||
if (input->checkActionPlayer2(InputAction::SHOOT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
disparar_bala(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Check game over state first
|
||||
if (game_over_) {
|
||||
// Game over: only update timer, enemies, bullets, and debris
|
||||
@@ -534,28 +548,6 @@ void EscenaJoc::dibuixar() {
|
||||
}
|
||||
}
|
||||
|
||||
void EscenaJoc::processar_input(const SDL_Event& event) {
|
||||
// Ignore ship controls during game over
|
||||
if (game_over_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Processament d'input per events puntuals (no continus)
|
||||
// L'input continu (fletxes/WASD) es processa en actualitzar() amb
|
||||
// SDL_GetKeyboardState()
|
||||
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
// P1 shoot
|
||||
if (event.key.key == Defaults::Controls::P1::SHOOT) {
|
||||
disparar_bala(0);
|
||||
}
|
||||
// P2 shoot
|
||||
else if (event.key.key == Defaults::Controls::P2::SHOOT) {
|
||||
disparar_bala(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EscenaJoc::tocado(uint8_t player_id) {
|
||||
// Death sequence: 3 phases
|
||||
// Phase 1: First call (itocado_per_jugador_[player_id] == 0) - trigger explosion
|
||||
|
||||
@@ -34,7 +34,6 @@ class EscenaJoc {
|
||||
void inicialitzar();
|
||||
void actualitzar(float delta_time);
|
||||
void dibuixar();
|
||||
void processar_input(const SDL_Event& event);
|
||||
|
||||
private:
|
||||
SDLManager& sdl_;
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/graphics/shape_loader.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/input/mouse.hpp"
|
||||
#include "core/rendering/shape_renderer.hpp"
|
||||
#include "core/system/context_escenes.hpp"
|
||||
@@ -82,6 +83,9 @@ void EscenaLogo::executar() {
|
||||
// Actualitzar visibilitat del cursor (auto-ocultar)
|
||||
Mouse::updateCursorVisibility();
|
||||
|
||||
// Actualitzar sistema d'input ABANS del event loop
|
||||
Input::get()->update();
|
||||
|
||||
// Processar events SDL
|
||||
while (SDL_PollEvent(&event)) {
|
||||
// Manejo de finestra
|
||||
@@ -312,6 +316,12 @@ void EscenaLogo::actualitzar(float delta_time) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Verificar botones de skip (SHOOT P1/P2)
|
||||
if (checkSkipButtonPressed()) {
|
||||
context_.canviar_escena(Escena::TITOL, Opcio::JUMP_TO_TITLE_MAIN);
|
||||
GestorEscenes::actual = Escena::TITOL;
|
||||
}
|
||||
|
||||
// Actualitzar animacions de debris
|
||||
debris_manager_->actualitzar(delta_time);
|
||||
}
|
||||
@@ -404,16 +414,17 @@ void EscenaLogo::dibuixar() {
|
||||
sdl_.presenta();
|
||||
}
|
||||
|
||||
void EscenaLogo::processar_events(const SDL_Event& event) {
|
||||
// Qualsevol tecla o clic de ratolí salta a la pantalla de títol
|
||||
if (event.type == SDL_EVENT_KEY_DOWN ||
|
||||
event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
// Utilitzar context per especificar escena i opció
|
||||
context_.canviar_escena(
|
||||
Escena::TITOL,
|
||||
Opcio::JUMP_TO_TITLE_MAIN
|
||||
);
|
||||
// Backward compatibility: També actualitzar GestorEscenes::actual
|
||||
GestorEscenes::actual = Escena::TITOL;
|
||||
auto EscenaLogo::checkSkipButtonPressed() -> bool {
|
||||
auto* input = Input::get();
|
||||
for (auto action : SKIP_BUTTONS_LOGO) {
|
||||
if (input->checkActionPlayer1(action, Input::DO_NOT_ALLOW_REPEAT) ||
|
||||
input->checkActionPlayer2(action, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void EscenaLogo::processar_events(const SDL_Event& event) {
|
||||
// No procesar eventos genéricos aquí - la lógica se movió a actualitzar()
|
||||
}
|
||||
|
||||
@@ -6,16 +6,23 @@
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "game/effects/debris_manager.hpp"
|
||||
#include "core/defaults.hpp"
|
||||
#include "core/graphics/shape.hpp"
|
||||
#include "core/input/input_types.hpp"
|
||||
#include "core/rendering/sdl_manager.hpp"
|
||||
#include "core/system/context_escenes.hpp"
|
||||
#include "core/types.hpp"
|
||||
|
||||
// Botones que permiten saltar la escena (extensible)
|
||||
static constexpr std::array<InputAction, 1> SKIP_BUTTONS_LOGO = {
|
||||
InputAction::SHOOT
|
||||
};
|
||||
|
||||
class EscenaLogo {
|
||||
public:
|
||||
explicit EscenaLogo(SDLManager& sdl, GestorEscenes::ContextEscenes& context);
|
||||
@@ -80,6 +87,7 @@ class EscenaLogo {
|
||||
void actualitzar_explosions(float delta_time);
|
||||
void dibuixar();
|
||||
void processar_events(const SDL_Event& event);
|
||||
auto checkSkipButtonPressed() -> bool;
|
||||
|
||||
// Mètodes de gestió d'estats
|
||||
void canviar_estat(EstatAnimacio nou_estat);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/graphics/shape_loader.hpp"
|
||||
#include "core/input/input.hpp"
|
||||
#include "core/input/mouse.hpp"
|
||||
#include "core/rendering/shape_renderer.hpp"
|
||||
#include "core/system/context_escenes.hpp"
|
||||
@@ -254,6 +255,9 @@ void EscenaTitol::executar() {
|
||||
// Actualitzar visibilitat del cursor (auto-ocultar)
|
||||
Mouse::updateCursorVisibility();
|
||||
|
||||
// Actualitzar sistema d'input ABANS del event loop
|
||||
Input::get()->update();
|
||||
|
||||
// Processar events SDL
|
||||
while (SDL_PollEvent(&event)) {
|
||||
// Manejo de finestra
|
||||
@@ -368,6 +372,37 @@ void EscenaTitol::actualitzar(float delta_time) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Verificar botones de skip (SHOOT P1/P2)
|
||||
if (checkSkipButtonPressed()) {
|
||||
switch (estat_actual_) {
|
||||
case EstatTitol::STARFIELD_FADE_IN:
|
||||
// Saltar fade-in, ir a MAIN
|
||||
estat_actual_ = EstatTitol::MAIN;
|
||||
starfield_->set_brightness(BRIGHTNESS_STARFIELD);
|
||||
temps_estat_main_ = 0.0f;
|
||||
break;
|
||||
|
||||
case EstatTitol::STARFIELD:
|
||||
// Saltar starfield, ir a MAIN
|
||||
estat_actual_ = EstatTitol::MAIN;
|
||||
temps_estat_main_ = 0.0f;
|
||||
break;
|
||||
|
||||
case EstatTitol::MAIN:
|
||||
// Iniciar partida (transición a JOC)
|
||||
context_.canviar_escena(Escena::JOC);
|
||||
estat_actual_ = EstatTitol::TRANSITION_TO_GAME;
|
||||
temps_acumulat_ = 0.0f;
|
||||
Audio::get()->fadeOutMusic(MUSIC_FADE);
|
||||
Audio::get()->playSound(Defaults::Sound::LASER, Audio::Group::GAME);
|
||||
break;
|
||||
|
||||
case EstatTitol::TRANSITION_TO_GAME:
|
||||
// Ignorar inputs durante transición
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EscenaTitol::actualitzar_animacio_logo(float delta_time) {
|
||||
@@ -540,40 +575,17 @@ void EscenaTitol::dibuixar() {
|
||||
}
|
||||
}
|
||||
|
||||
void EscenaTitol::processar_events(const SDL_Event& event) {
|
||||
// Qualsevol tecla o clic de ratolí
|
||||
if (event.type == SDL_EVENT_KEY_DOWN ||
|
||||
event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
switch (estat_actual_) {
|
||||
case EstatTitol::STARFIELD_FADE_IN:
|
||||
// Saltar directament a MAIN (ometre fade-in i starfield)
|
||||
estat_actual_ = EstatTitol::MAIN;
|
||||
starfield_->set_brightness(BRIGHTNESS_STARFIELD); // Assegurar brightness final
|
||||
temps_estat_main_ = 0.0f; // Reset timer per animació de títol
|
||||
break;
|
||||
|
||||
case EstatTitol::STARFIELD:
|
||||
// Saltar a MAIN
|
||||
estat_actual_ = EstatTitol::MAIN;
|
||||
temps_estat_main_ = 0.0f; // Reset timer
|
||||
break;
|
||||
|
||||
case EstatTitol::MAIN:
|
||||
// Utilitzar context per transició a JOC
|
||||
context_.canviar_escena(Escena::JOC);
|
||||
// NO actualitzar GestorEscenes::actual aquí!
|
||||
// La transició es fa en l'estat TRANSITION_TO_GAME
|
||||
|
||||
// Iniciar transició amb fade-out de música
|
||||
estat_actual_ = EstatTitol::TRANSITION_TO_GAME;
|
||||
temps_acumulat_ = 0.0f; // Reset del comptador
|
||||
Audio::get()->fadeOutMusic(MUSIC_FADE); // Fade
|
||||
Audio::get()->playSound(Defaults::Sound::LASER, Audio::Group::GAME);
|
||||
break;
|
||||
|
||||
case EstatTitol::TRANSITION_TO_GAME:
|
||||
// Ignorar inputs durant la transició
|
||||
break;
|
||||
auto EscenaTitol::checkSkipButtonPressed() -> bool {
|
||||
auto* input = Input::get();
|
||||
for (auto action : SKIP_BUTTONS_TITOL) {
|
||||
if (input->checkActionPlayer1(action, Input::DO_NOT_ALLOW_REPEAT) ||
|
||||
input->checkActionPlayer2(action, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void EscenaTitol::processar_events(const SDL_Event& event) {
|
||||
// No procesar eventos genéricos aquí - la lógica se movió a actualitzar()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
@@ -13,10 +14,16 @@
|
||||
#include "core/graphics/shape.hpp"
|
||||
#include "core/graphics/starfield.hpp"
|
||||
#include "core/graphics/vector_text.hpp"
|
||||
#include "core/input/input_types.hpp"
|
||||
#include "core/rendering/sdl_manager.hpp"
|
||||
#include "core/system/context_escenes.hpp"
|
||||
#include "core/types.hpp"
|
||||
|
||||
// Botones que permiten saltar/avanzar la escena (extensible)
|
||||
static constexpr std::array<InputAction, 1> SKIP_BUTTONS_TITOL = {
|
||||
InputAction::SHOOT
|
||||
};
|
||||
|
||||
class EscenaTitol {
|
||||
public:
|
||||
explicit EscenaTitol(SDLManager& sdl, GestorEscenes::ContextEscenes& context);
|
||||
@@ -97,5 +104,6 @@ class EscenaTitol {
|
||||
void actualitzar_animacio_logo(float delta_time); // Actualitza l'animació orbital del logo
|
||||
void dibuixar();
|
||||
void processar_events(const SDL_Event& event);
|
||||
auto checkSkipButtonPressed() -> bool;
|
||||
void inicialitzar_titol(); // Carrega i posiciona les lletres del títol
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "core/defaults.hpp"
|
||||
#include "external/fkyaml_node.hpp"
|
||||
@@ -10,6 +11,111 @@
|
||||
|
||||
namespace Options {
|
||||
|
||||
// ========== FUNCIONS AUXILIARS PER CONVERSIÓ DE CONTROLES ==========
|
||||
|
||||
// Mapa de SDL_Scancode a string
|
||||
static const std::unordered_map<SDL_Scancode, std::string> SCANCODE_TO_STRING = {
|
||||
{SDL_SCANCODE_A, "A"}, {SDL_SCANCODE_B, "B"}, {SDL_SCANCODE_C, "C"}, {SDL_SCANCODE_D, "D"},
|
||||
{SDL_SCANCODE_E, "E"}, {SDL_SCANCODE_F, "F"}, {SDL_SCANCODE_G, "G"}, {SDL_SCANCODE_H, "H"},
|
||||
{SDL_SCANCODE_I, "I"}, {SDL_SCANCODE_J, "J"}, {SDL_SCANCODE_K, "K"}, {SDL_SCANCODE_L, "L"},
|
||||
{SDL_SCANCODE_M, "M"}, {SDL_SCANCODE_N, "N"}, {SDL_SCANCODE_O, "O"}, {SDL_SCANCODE_P, "P"},
|
||||
{SDL_SCANCODE_Q, "Q"}, {SDL_SCANCODE_R, "R"}, {SDL_SCANCODE_S, "S"}, {SDL_SCANCODE_T, "T"},
|
||||
{SDL_SCANCODE_U, "U"}, {SDL_SCANCODE_V, "V"}, {SDL_SCANCODE_W, "W"}, {SDL_SCANCODE_X, "X"},
|
||||
{SDL_SCANCODE_Y, "Y"}, {SDL_SCANCODE_Z, "Z"},
|
||||
{SDL_SCANCODE_1, "1"}, {SDL_SCANCODE_2, "2"}, {SDL_SCANCODE_3, "3"}, {SDL_SCANCODE_4, "4"},
|
||||
{SDL_SCANCODE_5, "5"}, {SDL_SCANCODE_6, "6"}, {SDL_SCANCODE_7, "7"}, {SDL_SCANCODE_8, "8"},
|
||||
{SDL_SCANCODE_9, "9"}, {SDL_SCANCODE_0, "0"},
|
||||
{SDL_SCANCODE_RETURN, "RETURN"}, {SDL_SCANCODE_ESCAPE, "ESCAPE"},
|
||||
{SDL_SCANCODE_BACKSPACE, "BACKSPACE"}, {SDL_SCANCODE_TAB, "TAB"},
|
||||
{SDL_SCANCODE_SPACE, "SPACE"},
|
||||
{SDL_SCANCODE_UP, "UP"}, {SDL_SCANCODE_DOWN, "DOWN"},
|
||||
{SDL_SCANCODE_LEFT, "LEFT"}, {SDL_SCANCODE_RIGHT, "RIGHT"},
|
||||
{SDL_SCANCODE_LSHIFT, "LSHIFT"}, {SDL_SCANCODE_RSHIFT, "RSHIFT"},
|
||||
{SDL_SCANCODE_LCTRL, "LCTRL"}, {SDL_SCANCODE_RCTRL, "RCTRL"},
|
||||
{SDL_SCANCODE_LALT, "LALT"}, {SDL_SCANCODE_RALT, "RALT"}
|
||||
};
|
||||
|
||||
// Mapa invers: string a SDL_Scancode
|
||||
static const std::unordered_map<std::string, SDL_Scancode> STRING_TO_SCANCODE = {
|
||||
{"A", SDL_SCANCODE_A}, {"B", SDL_SCANCODE_B}, {"C", SDL_SCANCODE_C}, {"D", SDL_SCANCODE_D},
|
||||
{"E", SDL_SCANCODE_E}, {"F", SDL_SCANCODE_F}, {"G", SDL_SCANCODE_G}, {"H", SDL_SCANCODE_H},
|
||||
{"I", SDL_SCANCODE_I}, {"J", SDL_SCANCODE_J}, {"K", SDL_SCANCODE_K}, {"L", SDL_SCANCODE_L},
|
||||
{"M", SDL_SCANCODE_M}, {"N", SDL_SCANCODE_N}, {"O", SDL_SCANCODE_O}, {"P", SDL_SCANCODE_P},
|
||||
{"Q", SDL_SCANCODE_Q}, {"R", SDL_SCANCODE_R}, {"S", SDL_SCANCODE_S}, {"T", SDL_SCANCODE_T},
|
||||
{"U", SDL_SCANCODE_U}, {"V", SDL_SCANCODE_V}, {"W", SDL_SCANCODE_W}, {"X", SDL_SCANCODE_X},
|
||||
{"Y", SDL_SCANCODE_Y}, {"Z", SDL_SCANCODE_Z},
|
||||
{"1", SDL_SCANCODE_1}, {"2", SDL_SCANCODE_2}, {"3", SDL_SCANCODE_3}, {"4", SDL_SCANCODE_4},
|
||||
{"5", SDL_SCANCODE_5}, {"6", SDL_SCANCODE_6}, {"7", SDL_SCANCODE_7}, {"8", SDL_SCANCODE_8},
|
||||
{"9", SDL_SCANCODE_9}, {"0", SDL_SCANCODE_0},
|
||||
{"RETURN", SDL_SCANCODE_RETURN}, {"ESCAPE", SDL_SCANCODE_ESCAPE},
|
||||
{"BACKSPACE", SDL_SCANCODE_BACKSPACE}, {"TAB", SDL_SCANCODE_TAB},
|
||||
{"SPACE", SDL_SCANCODE_SPACE},
|
||||
{"UP", SDL_SCANCODE_UP}, {"DOWN", SDL_SCANCODE_DOWN},
|
||||
{"LEFT", SDL_SCANCODE_LEFT}, {"RIGHT", SDL_SCANCODE_RIGHT},
|
||||
{"LSHIFT", SDL_SCANCODE_LSHIFT}, {"RSHIFT", SDL_SCANCODE_RSHIFT},
|
||||
{"LCTRL", SDL_SCANCODE_LCTRL}, {"RCTRL", SDL_SCANCODE_RCTRL},
|
||||
{"LALT", SDL_SCANCODE_LALT}, {"RALT", SDL_SCANCODE_RALT}
|
||||
};
|
||||
|
||||
// Mapa de botó de gamepad (int) a string
|
||||
static const std::unordered_map<int, std::string> BUTTON_TO_STRING = {
|
||||
{SDL_GAMEPAD_BUTTON_SOUTH, "SOUTH"}, // A (Xbox), Cross (PS)
|
||||
{SDL_GAMEPAD_BUTTON_EAST, "EAST"}, // B (Xbox), Circle (PS)
|
||||
{SDL_GAMEPAD_BUTTON_WEST, "WEST"}, // X (Xbox), Square (PS)
|
||||
{SDL_GAMEPAD_BUTTON_NORTH, "NORTH"}, // Y (Xbox), Triangle (PS)
|
||||
{SDL_GAMEPAD_BUTTON_BACK, "BACK"},
|
||||
{SDL_GAMEPAD_BUTTON_START, "START"},
|
||||
{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"},
|
||||
{100, "L2_AS_BUTTON"}, // Trigger L2 com a botó digital
|
||||
{101, "R2_AS_BUTTON"} // Trigger R2 com a botó digital
|
||||
};
|
||||
|
||||
// Mapa invers: string a botó de gamepad
|
||||
static const std::unordered_map<std::string, int> STRING_TO_BUTTON = {
|
||||
{"SOUTH", SDL_GAMEPAD_BUTTON_SOUTH},
|
||||
{"EAST", SDL_GAMEPAD_BUTTON_EAST},
|
||||
{"WEST", SDL_GAMEPAD_BUTTON_WEST},
|
||||
{"NORTH", SDL_GAMEPAD_BUTTON_NORTH},
|
||||
{"BACK", SDL_GAMEPAD_BUTTON_BACK},
|
||||
{"START", SDL_GAMEPAD_BUTTON_START},
|
||||
{"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", 100},
|
||||
{"R2_AS_BUTTON", 101}
|
||||
};
|
||||
|
||||
static auto scancodeToString(SDL_Scancode code) -> std::string {
|
||||
auto it = SCANCODE_TO_STRING.find(code);
|
||||
return (it != SCANCODE_TO_STRING.end()) ? it->second : "UNKNOWN";
|
||||
}
|
||||
|
||||
static auto stringToScancode(const std::string& str) -> SDL_Scancode {
|
||||
auto it = STRING_TO_SCANCODE.find(str);
|
||||
return (it != STRING_TO_SCANCODE.end()) ? it->second : SDL_SCANCODE_UNKNOWN;
|
||||
}
|
||||
|
||||
static auto buttonToString(int button) -> std::string {
|
||||
auto it = BUTTON_TO_STRING.find(button);
|
||||
return (it != BUTTON_TO_STRING.end()) ? it->second : "UNKNOWN";
|
||||
}
|
||||
|
||||
static auto stringToButton(const std::string& str) -> int {
|
||||
auto it = STRING_TO_BUTTON.find(str);
|
||||
return (it != STRING_TO_BUTTON.end()) ? it->second : SDL_GAMEPAD_BUTTON_INVALID;
|
||||
}
|
||||
|
||||
// ========== FI FUNCIONS AUXILIARS ==========
|
||||
|
||||
|
||||
// Inicialitzar opcions amb valors per defecte de Defaults::
|
||||
void init() {
|
||||
#ifdef _DEBUG
|
||||
@@ -278,6 +384,80 @@ static void loadAudioConfigFromYaml(const fkyaml::node& yaml) {
|
||||
}
|
||||
}
|
||||
|
||||
// Carregar controls del jugador 1 des de YAML
|
||||
static void loadPlayer1ControlsFromYaml(const fkyaml::node& yaml) {
|
||||
if (!yaml.contains("player1")) return;
|
||||
|
||||
const auto& p1 = yaml["player1"];
|
||||
|
||||
// Carregar controls de teclat
|
||||
if (p1.contains("keyboard")) {
|
||||
const auto& kb = p1["keyboard"];
|
||||
if (kb.contains("key_left"))
|
||||
player1.keyboard.key_left = stringToScancode(kb["key_left"].get_value<std::string>());
|
||||
if (kb.contains("key_right"))
|
||||
player1.keyboard.key_right = stringToScancode(kb["key_right"].get_value<std::string>());
|
||||
if (kb.contains("key_thrust"))
|
||||
player1.keyboard.key_thrust = stringToScancode(kb["key_thrust"].get_value<std::string>());
|
||||
if (kb.contains("key_shoot"))
|
||||
player1.keyboard.key_shoot = stringToScancode(kb["key_shoot"].get_value<std::string>());
|
||||
}
|
||||
|
||||
// Carregar controls de gamepad
|
||||
if (p1.contains("gamepad")) {
|
||||
const auto& gp = p1["gamepad"];
|
||||
if (gp.contains("button_left"))
|
||||
player1.gamepad.button_left = stringToButton(gp["button_left"].get_value<std::string>());
|
||||
if (gp.contains("button_right"))
|
||||
player1.gamepad.button_right = stringToButton(gp["button_right"].get_value<std::string>());
|
||||
if (gp.contains("button_thrust"))
|
||||
player1.gamepad.button_thrust = stringToButton(gp["button_thrust"].get_value<std::string>());
|
||||
if (gp.contains("button_shoot"))
|
||||
player1.gamepad.button_shoot = stringToButton(gp["button_shoot"].get_value<std::string>());
|
||||
}
|
||||
|
||||
// Carregar nom del gamepad
|
||||
if (p1.contains("gamepad_name"))
|
||||
player1.gamepad_name = p1["gamepad_name"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Carregar controls del jugador 2 des de YAML
|
||||
static void loadPlayer2ControlsFromYaml(const fkyaml::node& yaml) {
|
||||
if (!yaml.contains("player2")) return;
|
||||
|
||||
const auto& p2 = yaml["player2"];
|
||||
|
||||
// Carregar controls de teclat
|
||||
if (p2.contains("keyboard")) {
|
||||
const auto& kb = p2["keyboard"];
|
||||
if (kb.contains("key_left"))
|
||||
player2.keyboard.key_left = stringToScancode(kb["key_left"].get_value<std::string>());
|
||||
if (kb.contains("key_right"))
|
||||
player2.keyboard.key_right = stringToScancode(kb["key_right"].get_value<std::string>());
|
||||
if (kb.contains("key_thrust"))
|
||||
player2.keyboard.key_thrust = stringToScancode(kb["key_thrust"].get_value<std::string>());
|
||||
if (kb.contains("key_shoot"))
|
||||
player2.keyboard.key_shoot = stringToScancode(kb["key_shoot"].get_value<std::string>());
|
||||
}
|
||||
|
||||
// Carregar controls de gamepad
|
||||
if (p2.contains("gamepad")) {
|
||||
const auto& gp = p2["gamepad"];
|
||||
if (gp.contains("button_left"))
|
||||
player2.gamepad.button_left = stringToButton(gp["button_left"].get_value<std::string>());
|
||||
if (gp.contains("button_right"))
|
||||
player2.gamepad.button_right = stringToButton(gp["button_right"].get_value<std::string>());
|
||||
if (gp.contains("button_thrust"))
|
||||
player2.gamepad.button_thrust = stringToButton(gp["button_thrust"].get_value<std::string>());
|
||||
if (gp.contains("button_shoot"))
|
||||
player2.gamepad.button_shoot = stringToButton(gp["button_shoot"].get_value<std::string>());
|
||||
}
|
||||
|
||||
// Carregar nom del gamepad
|
||||
if (p2.contains("gamepad_name"))
|
||||
player2.gamepad_name = p2["gamepad_name"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Carregar configuració des del fitxer YAML
|
||||
auto loadFromFile() -> bool {
|
||||
const std::string CONFIG_VERSION = std::string(Project::VERSION);
|
||||
@@ -325,6 +505,8 @@ auto loadFromFile() -> bool {
|
||||
loadGameplayConfigFromYaml(yaml);
|
||||
loadRenderingConfigFromYaml(yaml);
|
||||
loadAudioConfigFromYaml(yaml);
|
||||
loadPlayer1ControlsFromYaml(yaml);
|
||||
loadPlayer2ControlsFromYaml(yaml);
|
||||
|
||||
if (console) {
|
||||
std::cout << "Config carregada correctament des de: " << config_file_path
|
||||
@@ -345,6 +527,40 @@ auto loadFromFile() -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Guardar controls del jugador 1 a YAML
|
||||
static void savePlayer1ControlsToYaml(std::ofstream& file) {
|
||||
file << "# CONTROLS JUGADOR 1\n";
|
||||
file << "player1:\n";
|
||||
file << " keyboard:\n";
|
||||
file << " key_left: " << scancodeToString(player1.keyboard.key_left) << "\n";
|
||||
file << " key_right: " << scancodeToString(player1.keyboard.key_right) << "\n";
|
||||
file << " key_thrust: " << scancodeToString(player1.keyboard.key_thrust) << "\n";
|
||||
file << " key_shoot: " << scancodeToString(player1.keyboard.key_shoot) << "\n";
|
||||
file << " gamepad:\n";
|
||||
file << " button_left: " << buttonToString(player1.gamepad.button_left) << "\n";
|
||||
file << " button_right: " << buttonToString(player1.gamepad.button_right) << "\n";
|
||||
file << " button_thrust: " << buttonToString(player1.gamepad.button_thrust) << "\n";
|
||||
file << " button_shoot: " << buttonToString(player1.gamepad.button_shoot) << "\n";
|
||||
file << " gamepad_name: \"" << player1.gamepad_name << "\" # Buit = primer disponible\n\n";
|
||||
}
|
||||
|
||||
// Guardar controls del jugador 2 a YAML
|
||||
static void savePlayer2ControlsToYaml(std::ofstream& file) {
|
||||
file << "# CONTROLS JUGADOR 2\n";
|
||||
file << "player2:\n";
|
||||
file << " keyboard:\n";
|
||||
file << " key_left: " << scancodeToString(player2.keyboard.key_left) << "\n";
|
||||
file << " key_right: " << scancodeToString(player2.keyboard.key_right) << "\n";
|
||||
file << " key_thrust: " << scancodeToString(player2.keyboard.key_thrust) << "\n";
|
||||
file << " key_shoot: " << scancodeToString(player2.keyboard.key_shoot) << "\n";
|
||||
file << " gamepad:\n";
|
||||
file << " button_left: " << buttonToString(player2.gamepad.button_left) << "\n";
|
||||
file << " button_right: " << buttonToString(player2.gamepad.button_right) << "\n";
|
||||
file << " button_thrust: " << buttonToString(player2.gamepad.button_thrust) << "\n";
|
||||
file << " button_shoot: " << buttonToString(player2.gamepad.button_shoot) << "\n";
|
||||
file << " gamepad_name: \"" << player2.gamepad_name << "\" # Buit = segon disponible\n\n";
|
||||
}
|
||||
|
||||
// Guardar configuració al fitxer YAML
|
||||
auto saveToFile() -> bool {
|
||||
std::ofstream file(config_file_path);
|
||||
@@ -399,7 +615,11 @@ auto saveToFile() -> bool {
|
||||
file << " volume: " << audio.music.volume << " # 0.0 to 1.0\n";
|
||||
file << " sound:\n";
|
||||
file << " enabled: " << (audio.sound.enabled ? "true" : "false") << "\n";
|
||||
file << " volume: " << audio.sound.volume << " # 0.0 to 1.0\n";
|
||||
file << " volume: " << audio.sound.volume << " # 0.0 to 1.0\n\n";
|
||||
|
||||
// Guardar controls de jugadors
|
||||
savePlayer1ControlsToYaml(file);
|
||||
savePlayer2ControlsToYaml(file);
|
||||
|
||||
file.close();
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_Scancode
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Options {
|
||||
@@ -48,6 +50,28 @@ struct Audio {
|
||||
float volume{1.0f};
|
||||
};
|
||||
|
||||
// Controles de jugadors
|
||||
|
||||
struct KeyboardControls {
|
||||
SDL_Scancode key_left{SDL_SCANCODE_LEFT};
|
||||
SDL_Scancode key_right{SDL_SCANCODE_RIGHT};
|
||||
SDL_Scancode key_thrust{SDL_SCANCODE_UP};
|
||||
SDL_Scancode key_shoot{SDL_SCANCODE_SPACE};
|
||||
};
|
||||
|
||||
struct GamepadControls {
|
||||
int button_left{SDL_GAMEPAD_BUTTON_DPAD_LEFT};
|
||||
int button_right{SDL_GAMEPAD_BUTTON_DPAD_RIGHT};
|
||||
int button_thrust{SDL_GAMEPAD_BUTTON_WEST}; // X button
|
||||
int button_shoot{SDL_GAMEPAD_BUTTON_SOUTH}; // A button
|
||||
};
|
||||
|
||||
struct PlayerControls {
|
||||
KeyboardControls keyboard{};
|
||||
GamepadControls gamepad{};
|
||||
std::string gamepad_name{""}; // Buit = auto-assignar per índex
|
||||
};
|
||||
|
||||
// Variables globals (inline per evitar ODR violations)
|
||||
|
||||
inline std::string version{}; // Versió del config per validació
|
||||
@@ -58,6 +82,29 @@ inline Gameplay gameplay{};
|
||||
inline Rendering rendering{};
|
||||
inline Audio audio{};
|
||||
|
||||
// Controles per jugador
|
||||
inline PlayerControls player1{
|
||||
.keyboard =
|
||||
{.key_left = SDL_SCANCODE_LEFT,
|
||||
.key_right = SDL_SCANCODE_RIGHT,
|
||||
.key_thrust = SDL_SCANCODE_UP,
|
||||
.key_shoot = SDL_SCANCODE_SPACE},
|
||||
.gamepad_name = "" // Primer gamepad disponible
|
||||
};
|
||||
|
||||
inline PlayerControls player2{
|
||||
.keyboard =
|
||||
{.key_left = SDL_SCANCODE_A,
|
||||
.key_right = SDL_SCANCODE_D,
|
||||
.key_thrust = SDL_SCANCODE_W,
|
||||
.key_shoot = SDL_SCANCODE_LSHIFT},
|
||||
.gamepad_name = "" // Segon gamepad disponible
|
||||
};
|
||||
|
||||
// Per compatibilitat amb pollo (no utilitzat en orni, però necessari per Input)
|
||||
inline KeyboardControls keyboard_controls{};
|
||||
inline GamepadControls gamepad_controls{};
|
||||
|
||||
inline std::string config_file_path{}; // Establert per setConfigFile()
|
||||
|
||||
// Funcions públiques
|
||||
|
||||
Reference in New Issue
Block a user