From 0248614add99c1df1bc7c9ff97091f678ff75aca Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 12:36:28 -0400 Subject: [PATCH] GC Adapter Implementation --- src/core/hle/service/hid/controllers/npad.cpp | 42 ++- src/input_common/CMakeLists.txt | 6 + src/input_common/analog_from_button.cpp | 3 +- src/input_common/gcadapter/gc_adapter.cpp | 350 ++++++++++++++++++ src/input_common/gcadapter/gc_adapter.h | 116 ++++++ src/input_common/gcadapter/gc_poller.cpp | 310 ++++++++++++++++ src/input_common/gcadapter/gc_poller.h | 59 +++ src/input_common/keyboard.cpp | 13 +- src/input_common/main.cpp | 23 +- src/input_common/main.h | 9 + src/input_common/motion_emu.cpp | 5 +- src/input_common/sdl/sdl_impl.cpp | 53 ++- src/input_common/udp/client.cpp | 134 ++++--- src/input_common/udp/client.h | 2 + src/input_common/udp/protocol.h | 32 +- src/input_common/udp/udp.cpp | 18 +- .../configuration/configure_input_player.cpp | 131 +++++-- .../configuration/configure_input_player.h | 8 +- 18 files changed, 1156 insertions(+), 158 deletions(-) create mode 100644 src/input_common/gcadapter/gc_adapter.cpp create mode 100644 src/input_common/gcadapter/gc_adapter.h create mode 100644 src/input_common/gcadapter/gc_poller.cpp create mode 100644 src/input_common/gcadapter/gc_poller.h diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp index c55d900e2..d92325cb5 100644 --- a/src/core/hle/service/hid/controllers/npad.cpp +++ b/src/core/hle/service/hid/controllers/npad.cpp @@ -44,7 +44,7 @@ static Controller_NPad::NPadControllerType MapSettingsTypeToNPad(Settings::Contr case Settings::ControllerType::RightJoycon: return Controller_NPad::NPadControllerType::JoyRight; default: - UNREACHABLE(); + UNREACHABLE(); return Controller_NPad::NPadControllerType::JoyDual; } } @@ -93,7 +93,10 @@ u32 Controller_NPad::IndexToNPad(std::size_t index) { }; } -Controller_NPad::Controller_NPad(Core::System& system) : ControllerBase(system), system(system) {} +Controller_NPad::Controller_NPad(Core::System& system) + : ControllerBase(system), system(system) { +} + Controller_NPad::~Controller_NPad() = default; void Controller_NPad::InitNewlyAddedControler(std::size_t controller_idx) { @@ -106,7 +109,7 @@ void Controller_NPad::InitNewlyAddedControler(std::size_t controller_idx) { controller.device_type.raw = 0; switch (controller_type) { case NPadControllerType::None: - UNREACHABLE(); + UNREACHABLE(); break; case NPadControllerType::Handheld: controller.joy_styles.handheld.Assign(1); @@ -194,7 +197,8 @@ void Controller_NPad::OnInit() { std::transform( Settings::values.players.begin(), Settings::values.players.end(), - connected_controllers.begin(), [](const Settings::PlayerInput& player) { + connected_controllers.begin(), [](const Settings::PlayerInput& player) + { return ControllerHolder{MapSettingsTypeToNPad(player.type), player.connected}; }); @@ -238,7 +242,8 @@ void Controller_NPad::OnLoadInputDevices() { } } -void Controller_NPad::OnRelease() {} +void Controller_NPad::OnRelease() { +} void Controller_NPad::RequestPadStateUpdate(u32 npad_id) { const auto controller_idx = NPadIdToIndex(npad_id); @@ -276,27 +281,31 @@ void Controller_NPad::RequestPadStateUpdate(u32 npad_id) { pad_state.d_down.Assign(button_state[DDown - BUTTON_HID_BEGIN]->GetStatus()); pad_state.l_stick_right.Assign( - analog_state[static_cast(JoystickId::Joystick_Left)]->GetAnalogDirectionStatus( + analog_state[static_cast(JoystickId::Joystick_Left)]-> + GetAnalogDirectionStatus( Input::AnalogDirection::RIGHT)); pad_state.l_stick_left.Assign( - analog_state[static_cast(JoystickId::Joystick_Left)]->GetAnalogDirectionStatus( + analog_state[static_cast(JoystickId::Joystick_Left)]-> + GetAnalogDirectionStatus( Input::AnalogDirection::LEFT)); pad_state.l_stick_up.Assign( - analog_state[static_cast(JoystickId::Joystick_Left)]->GetAnalogDirectionStatus( + analog_state[static_cast(JoystickId::Joystick_Left)]-> + GetAnalogDirectionStatus( Input::AnalogDirection::UP)); pad_state.l_stick_down.Assign( - analog_state[static_cast(JoystickId::Joystick_Left)]->GetAnalogDirectionStatus( + analog_state[static_cast(JoystickId::Joystick_Left)]-> + GetAnalogDirectionStatus( Input::AnalogDirection::DOWN)); pad_state.r_stick_right.Assign( analog_state[static_cast(JoystickId::Joystick_Right)] - ->GetAnalogDirectionStatus(Input::AnalogDirection::RIGHT)); + ->GetAnalogDirectionStatus(Input::AnalogDirection::RIGHT)); pad_state.r_stick_left.Assign(analog_state[static_cast(JoystickId::Joystick_Right)] - ->GetAnalogDirectionStatus(Input::AnalogDirection::LEFT)); + ->GetAnalogDirectionStatus(Input::AnalogDirection::LEFT)); pad_state.r_stick_up.Assign(analog_state[static_cast(JoystickId::Joystick_Right)] - ->GetAnalogDirectionStatus(Input::AnalogDirection::UP)); + ->GetAnalogDirectionStatus(Input::AnalogDirection::UP)); pad_state.r_stick_down.Assign(analog_state[static_cast(JoystickId::Joystick_Right)] - ->GetAnalogDirectionStatus(Input::AnalogDirection::DOWN)); + ->GetAnalogDirectionStatus(Input::AnalogDirection::DOWN)); pad_state.left_sl.Assign(button_state[SL - BUTTON_HID_BEGIN]->GetStatus()); pad_state.left_sr.Assign(button_state[SR - BUTTON_HID_BEGIN]->GetStatus()); @@ -363,7 +372,7 @@ void Controller_NPad::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* switch (controller_type) { case NPadControllerType::None: - UNREACHABLE(); + UNREACHABLE(); break; case NPadControllerType::Handheld: handheld_entry.connection_status.raw = 0; @@ -459,8 +468,9 @@ void Controller_NPad::SetSupportedNPadIdTypes(u8* data, std::size_t length) { continue; } const auto requested_controller = - i <= MAX_NPAD_ID ? MapSettingsTypeToNPad(Settings::values.players[i].type) - : NPadControllerType::Handheld; + i <= MAX_NPAD_ID + ? MapSettingsTypeToNPad(Settings::values.players[i].type) + : NPadControllerType::Handheld; if (!IsControllerSupported(requested_controller)) { const auto is_handheld = requested_controller == NPadControllerType::Handheld; if (is_handheld) { diff --git a/src/input_common/CMakeLists.txt b/src/input_common/CMakeLists.txt index a9c2392b1..3bd76dd23 100644 --- a/src/input_common/CMakeLists.txt +++ b/src/input_common/CMakeLists.txt @@ -7,6 +7,10 @@ add_library(input_common STATIC main.h motion_emu.cpp motion_emu.h + gcadapter/gc_adapter.cpp + gcadapter/gc_adapter.h + gcadapter/gc_poller.cpp + gcadapter/gc_poller.h sdl/sdl.cpp sdl/sdl.h udp/client.cpp @@ -26,5 +30,7 @@ if(SDL2_FOUND) target_compile_definitions(input_common PRIVATE HAVE_SDL2) endif() +target_link_libraries(input_common PUBLIC ${LIBUSB_LIBRARIES}) + create_target_directory_groups(input_common) target_link_libraries(input_common PUBLIC core PRIVATE common Boost::boost) diff --git a/src/input_common/analog_from_button.cpp b/src/input_common/analog_from_button.cpp index 6cabdaa3c..8116fcf9f 100755 --- a/src/input_common/analog_from_button.cpp +++ b/src/input_common/analog_from_button.cpp @@ -14,7 +14,8 @@ public: float modifier_scale_) : up(std::move(up_)), down(std::move(down_)), left(std::move(left_)), right(std::move(right_)), modifier(std::move(modifier_)), - modifier_scale(modifier_scale_) {} + modifier_scale(modifier_scale_) { + } std::tuple GetStatus() const override { constexpr float SQRT_HALF = 0.707106781f; diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp new file mode 100644 index 000000000..d42261d61 --- /dev/null +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -0,0 +1,350 @@ +// Copyright 2014 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. +//* +#include "common/logging/log.h" +#include "common/threadsafe_queue.h" +#include "input_common/gcadapter/gc_adapter.h" + +Common::SPSCQueue pad_queue[4]; +struct GCState state[4]; + +namespace GCAdapter { + +static libusb_device_handle* usb_adapter_handle = nullptr; +static u8 adapter_controllers_status[4] = { + ControllerTypes::CONTROLLER_NONE, ControllerTypes::CONTROLLER_NONE, + ControllerTypes::CONTROLLER_NONE, ControllerTypes::CONTROLLER_NONE}; + +static std::mutex s_mutex; + +static std::thread adapter_input_thread; +static bool adapter_thread_running; + +static std::mutex initialization_mutex; +static std::thread detect_thread; +static bool detect_thread_running = false; + +static libusb_context* libusb_ctx; + +static u8 input_endpoint = 0; + +static bool configuring = false; + +GCPadStatus CheckStatus(int port, u8 adapter_payload[37]) { + GCPadStatus pad = {}; + bool get_origin = false; + + u8 type = adapter_payload[1 + (9 * port)] >> 4; + if (type) + get_origin = true; + + adapter_controllers_status[port] = type; + + if (adapter_controllers_status[port] != ControllerTypes::CONTROLLER_NONE) { + u8 b1 = adapter_payload[1 + (9 * port) + 1]; + u8 b2 = adapter_payload[1 + (9 * port) + 2]; + + if (b1 & (1 << 0)) + pad.button |= PAD_BUTTON_A; + if (b1 & (1 << 1)) + pad.button |= PAD_BUTTON_B; + if (b1 & (1 << 2)) + pad.button |= PAD_BUTTON_X; + if (b1 & (1 << 3)) + pad.button |= PAD_BUTTON_Y; + + if (b1 & (1 << 4)) + pad.button |= PAD_BUTTON_LEFT; + if (b1 & (1 << 5)) + pad.button |= PAD_BUTTON_RIGHT; + if (b1 & (1 << 6)) + pad.button |= PAD_BUTTON_DOWN; + if (b1 & (1 << 7)) + pad.button |= PAD_BUTTON_UP; + + if (b2 & (1 << 0)) + pad.button |= PAD_BUTTON_START; + if (b2 & (1 << 1)) + pad.button |= PAD_TRIGGER_Z; + if (b2 & (1 << 2)) + pad.button |= PAD_TRIGGER_R; + if (b2 & (1 << 3)) + pad.button |= PAD_TRIGGER_L; + + if (get_origin) + pad.button |= PAD_GET_ORIGIN; + + pad.stickX = adapter_payload[1 + (9 * port) + 3]; + pad.stickY = adapter_payload[1 + (9 * port) + 4]; + pad.substickX = adapter_payload[1 + (9 * port) + 5]; + pad.substickY = adapter_payload[1 + (9 * port) + 6]; + pad.triggerLeft = adapter_payload[1 + (9 * port) + 7]; + pad.triggerRight = adapter_payload[1 + (9 * port) + 8]; + } + return pad; +} + +void PadToState(GCPadStatus pad, GCState& state) { + //std::lock_guard lock{s_mutex}; + state.buttons.insert_or_assign(PAD_BUTTON_A, pad.button & PAD_BUTTON_A); + state.buttons.insert_or_assign(PAD_BUTTON_B, pad.button & PAD_BUTTON_B); + state.buttons.insert_or_assign(PAD_BUTTON_X, pad.button & PAD_BUTTON_X); + state.buttons.insert_or_assign(PAD_BUTTON_Y, pad.button & PAD_BUTTON_Y); + state.buttons.insert_or_assign(PAD_BUTTON_LEFT, pad.button & PAD_BUTTON_LEFT); + state.buttons.insert_or_assign(PAD_BUTTON_RIGHT, pad.button & PAD_BUTTON_RIGHT); + state.buttons.insert_or_assign(PAD_BUTTON_DOWN, pad.button & PAD_BUTTON_DOWN); + state.buttons.insert_or_assign(PAD_BUTTON_UP, pad.button & PAD_BUTTON_UP); + state.buttons.insert_or_assign(PAD_BUTTON_START, pad.button & PAD_BUTTON_START); + state.buttons.insert_or_assign(PAD_TRIGGER_Z, pad.button & PAD_TRIGGER_Z); + state.buttons.insert_or_assign(PAD_TRIGGER_L, pad.button & PAD_TRIGGER_L); + state.buttons.insert_or_assign(PAD_TRIGGER_R, pad.button & PAD_TRIGGER_R); + state.axes.insert_or_assign(STICK_X, pad.stickX); + state.axes.insert_or_assign(STICK_Y, pad.stickY); + state.axes.insert_or_assign(SUBSTICK_X, pad.substickX); + state.axes.insert_or_assign(SUBSTICK_Y, pad.substickY); + state.axes.insert_or_assign(TRIGGER_LEFT, pad.triggerLeft); + state.axes.insert_or_assign(TRIGGER_RIGHT, pad.triggerRight); +} + +static void Read() { + LOG_INFO(Input, "GC Adapter Read() thread started"); + + int payload_size_in; + u8 adapter_payload[37]; + while (adapter_thread_running) { + libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload, + sizeof(adapter_payload), &payload_size_in, 32); + + int payload_size = 0; + u8 controller_payload_copy[37]; + + { + std::lock_guard lk(s_mutex); + std::copy(std::begin(adapter_payload), std::end(adapter_payload), + std::begin(controller_payload_copy)); + payload_size = payload_size_in; + } + + GCPadStatus pad[4]; + if (payload_size != sizeof(controller_payload_copy) || + controller_payload_copy[0] != LIBUSB_DT_HID) { + LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size, + controller_payload_copy[0]); + } else { + for (int i = 0; i < 4; i++) + pad[i] = CheckStatus(i, controller_payload_copy); + } + for (int port = 0; port < 4; port++) { + if (DeviceConnected(port) && configuring) { + if (pad[port].button != PAD_GET_ORIGIN) + pad_queue[port].Push(pad[port]); + + // Accounting for a threshold here because of some controller variance + if (pad[port].stickX > pad[port].MAIN_STICK_CENTER_X + pad[port].THRESHOLD || + pad[port].stickX < pad[port].MAIN_STICK_CENTER_X - pad[port].THRESHOLD) { + pad[port].axis_which = STICK_X; + pad[port].axis_value = pad[port].stickX; + pad_queue[port].Push(pad[port]); + } + if (pad[port].stickY > pad[port].MAIN_STICK_CENTER_Y + pad[port].THRESHOLD || + pad[port].stickY < pad[port].MAIN_STICK_CENTER_Y - pad[port].THRESHOLD) { + pad[port].axis_which = STICK_Y; + pad[port].axis_value = pad[port].stickY; + pad_queue[port].Push(pad[port]); + } + if (pad[port].substickX > pad[port].C_STICK_CENTER_X + pad[port].THRESHOLD || + pad[port].substickX < pad[port].C_STICK_CENTER_X - pad[port].THRESHOLD) { + pad[port].axis_which = SUBSTICK_X; + pad[port].axis_value = pad[port].substickX; + pad_queue[port].Push(pad[port]); + } + if (pad[port].substickY > pad[port].C_STICK_CENTER_Y + pad[port].THRESHOLD || + pad[port].substickY < pad[port].C_STICK_CENTER_Y - pad[port].THRESHOLD) { + pad[port].axis_which = SUBSTICK_Y; + pad[port].axis_value = pad[port].substickY; + pad_queue[port].Push(pad[port]); + } + } + PadToState(pad[port], state[port]); + } + std::this_thread::yield(); + } +} + +static void ScanThreadFunc() { + LOG_INFO(Input, "GC Adapter scanning thread started"); + + while (detect_thread_running) { + if (usb_adapter_handle == nullptr) { + std::lock_guard lk(initialization_mutex); + Setup(); + } + Sleep(500); + } +} + +void Init() { + + if (usb_adapter_handle != nullptr) + return; + LOG_INFO(Input, "GC Adapter Initialization started"); + + current_status = NO_ADAPTER_DETECTED; + libusb_init(&libusb_ctx); + + StartScanThread(); +} + +void StartScanThread() { + if (detect_thread_running) + return; + if (!libusb_ctx) + return; + + detect_thread_running = true; + detect_thread = std::thread(ScanThreadFunc); +} + +void StopScanThread() { + detect_thread.join(); +} + +static void Setup() { + // Reset the error status in case the adapter gets unplugged + if (current_status < 0) + current_status = NO_ADAPTER_DETECTED; + + for (int i = 0; i < 4; i++) + adapter_controllers_status[i] = ControllerTypes::CONTROLLER_NONE; + + libusb_device** devs; // pointer to list of connected usb devices + + int cnt = libusb_get_device_list(libusb_ctx, &devs); //get the list of devices + + for (int i = 0; i < cnt; i++) { + if (CheckDeviceAccess(devs[i])) { + // GC Adapter found, registering it + GetGCEndpoint(devs[i]); + break; + } + } +} + +static bool CheckDeviceAccess(libusb_device* device) { + libusb_device_descriptor desc; + int ret = libusb_get_device_descriptor(device, &desc); + if (ret) { + // could not acquire the descriptor, no point in trying to use it. + LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: %d", ret); + return false; + } + + if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) { + // This isn’t the device we are looking for. + return false; + } + ret = libusb_open(device, &usb_adapter_handle); + + if (ret == LIBUSB_ERROR_ACCESS) { + LOG_ERROR(Input, + "Yuzu can not gain access to this device: ID %04X:%04X.", + desc.idVendor, desc.idProduct); + return false; + } + if (ret) { + LOG_ERROR(Input, "libusb_open failed to open device with error = %d", ret); + return false; + } + + ret = libusb_kernel_driver_active(usb_adapter_handle, 0); + if (ret == 1) { + ret = libusb_detach_kernel_driver(usb_adapter_handle, 0); + if (ret != 0 && ret != LIBUSB_ERROR_NOT_SUPPORTED) + LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = %d", ret); + } + + if (ret != 0 && ret != LIBUSB_ERROR_NOT_SUPPORTED) { + libusb_close(usb_adapter_handle); + usb_adapter_handle = nullptr; + return false; + } + + ret = libusb_claim_interface(usb_adapter_handle, 0); + if (ret) { + LOG_ERROR(Input, "libusb_claim_interface failed with error = %d", ret); + libusb_close(usb_adapter_handle); + usb_adapter_handle = nullptr; + return false; + } + + return true; +} + +static void GetGCEndpoint(libusb_device* device) { + libusb_config_descriptor* config = nullptr; + libusb_get_config_descriptor(device, 0, &config); + for (u8 ic = 0; ic < config->bNumInterfaces; ic++) { + const libusb_interface* interfaceContainer = &config->interface[ic]; + for (int i = 0; i < interfaceContainer->num_altsetting; i++) { + const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i]; + for (u8 e = 0; e < interface->bNumEndpoints; e++) { + const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e]; + if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) + input_endpoint = endpoint->bEndpointAddress; + } + } + } + + adapter_thread_running = true; + current_status = ADAPTER_DETECTED; + + adapter_input_thread = std::thread(Read); // Read input +} + +void Shutdown() { + StopScanThread(); + Reset(); + + current_status = NO_ADAPTER_DETECTED; +} + +static void Reset() { + std::unique_lock lock(initialization_mutex, std::defer_lock); + if (!lock.try_lock()) + return; + if (current_status != ADAPTER_DETECTED) + return; + + if (adapter_thread_running) + adapter_input_thread.join(); + + for (int i = 0; i < 4; i++) + adapter_controllers_status[i] = ControllerTypes::CONTROLLER_NONE; + + current_status = NO_ADAPTER_DETECTED; + + if (usb_adapter_handle) { + libusb_release_interface(usb_adapter_handle, 0); + libusb_close(usb_adapter_handle); + usb_adapter_handle = nullptr; + } +} + +bool DeviceConnected(int port) { + return adapter_controllers_status[port] != ControllerTypes::CONTROLLER_NONE; +} + +void ResetDeviceType(int port) { + adapter_controllers_status[port] = ControllerTypes::CONTROLLER_NONE; +} + +void BeginConfiguration() { + configuring = true; +} + +void EndConfiguration() { + configuring = false; +} + +} // end of namespace GCAdapter diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h new file mode 100644 index 000000000..9b02d1382 --- /dev/null +++ b/src/input_common/gcadapter/gc_adapter.h @@ -0,0 +1,116 @@ +#pragma once +#include +#include +#include +#include +#include "common/common_types.h" + + +enum { + PAD_USE_ORIGIN = 0x0080, + PAD_GET_ORIGIN = 0x2000, + PAD_ERR_STATUS = 0x8000, +}; + +enum PadButton { + PAD_BUTTON_LEFT = 0x0001, + PAD_BUTTON_RIGHT = 0x0002, + PAD_BUTTON_DOWN = 0x0004, + PAD_BUTTON_UP = 0x0008, + PAD_TRIGGER_Z = 0x0010, + PAD_TRIGGER_R = 0x0020, + PAD_TRIGGER_L = 0x0040, + PAD_BUTTON_A = 0x0100, + PAD_BUTTON_B = 0x0200, + PAD_BUTTON_X = 0x0400, + PAD_BUTTON_Y = 0x0800, + PAD_BUTTON_START = 0x1000, + // Below is for compatibility with "AxisButton" type + PAD_STICK = 0x2000, + +}; + +enum PadAxes { STICK_X, STICK_Y, SUBSTICK_X, SUBSTICK_Y, TRIGGER_LEFT, TRIGGER_RIGHT }; + +struct GCPadStatus { + u16 button; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits + u8 stickX; // 0 <= stickX <= 255 + u8 stickY; // 0 <= stickY <= 255 + u8 substickX; // 0 <= substickX <= 255 + u8 substickY; // 0 <= substickY <= 255 + u8 triggerLeft; // 0 <= triggerLeft <= 255 + u8 triggerRight; // 0 <= triggerRight <= 255 + bool isConnected{true}; + + static const u8 MAIN_STICK_CENTER_X = 0x80; + static const u8 MAIN_STICK_CENTER_Y = 0x80; + static const u8 MAIN_STICK_RADIUS = 0x7f; + static const u8 C_STICK_CENTER_X = 0x80; + static const u8 C_STICK_CENTER_Y = 0x80; + static const u8 C_STICK_RADIUS = 0x7f; + + static const u8 TRIGGER_CENTER = 20; + static const u8 THRESHOLD = 10; + u8 port; + u8 axis_which = 255; + u8 axis_value = 255; +}; + +struct GCState { + std::unordered_map buttons; + std::unordered_map axes; +}; + + +namespace GCAdapter { +enum ControllerTypes { + CONTROLLER_NONE = 0, + CONTROLLER_WIRED = 1, + CONTROLLER_WIRELESS = 2 +}; + +enum { + NO_ADAPTER_DETECTED = 0, + ADAPTER_DETECTED = 1, +}; + +// Current adapter status: detected/not detected/in error (holds the error code) +static int current_status = NO_ADAPTER_DETECTED; + +GCPadStatus CheckStatus(int port, u8 adapter_payload[37]); +/// Initialize the GC Adapter capture and read sequence +void Init(); + +/// Close the adapter read thread and release the adapter +void Shutdown(); + +/// Begin scanning for the GC Adapter. +void StartScanThread(); + +/// Stop scanning for the adapter +void StopScanThread(); + +/// Returns true if there is a device connected to port +bool DeviceConnected(int port); + +/// Resets status of device connected to port +void ResetDeviceType(int port); + +/// Returns true if we successfully gain access to GC Adapter +bool CheckDeviceAccess(libusb_device* device); + +/// Captures GC Adapter endpoint address, +void GetGCEndpoint(libusb_device* device); + +/// For shutting down, clear all data, join all threads, release usb +void Reset(); + +/// For use in initialization, querying devices to find the adapter +void Setup(); + +/// Used for polling +void BeginConfiguration(); + +void EndConfiguration(); + +} // end of namespace GCAdapter diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp new file mode 100644 index 000000000..772bd8890 --- /dev/null +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -0,0 +1,310 @@ +#include +#include +#include +#include +#include "input_common/gcadapter/gc_poller.h" +#include "input_common/gcadapter/gc_adapter.h" +#include "common/threadsafe_queue.h" + +// Using extern as to avoid multply defined symbols. +extern Common::SPSCQueue pad_queue[4]; +extern struct GCState state[4]; + +namespace InputCommon { + +class GCButton final : public Input::ButtonDevice { +public: + explicit GCButton(int port_, int button_, int axis_) + : port(port_), button(button_) { + } + + ~GCButton() override; + + bool GetStatus() const override { + return state[port].buttons.at(button); + } + +private: + const int port; + const int button; +}; + +class GCAxisButton final : public Input::ButtonDevice { +public: + explicit GCAxisButton(int port_, int axis_, float threshold_, + bool trigger_if_greater_) + : port(port_), axis(axis_), threshold(threshold_), + trigger_if_greater(trigger_if_greater_) { + } + + + bool GetStatus() const override { + const float axis_value = (state[port].axes.at(axis) - 128.0f) / 128.0f; + if (trigger_if_greater) { + return axis_value > 0.10f; //TODO(ameerj) : Fix threshold. + } + return axis_value < -0.10f; + } + +private: + const int port; + const int axis; + float threshold; + bool trigger_if_greater; +}; + +GCButtonFactory::GCButtonFactory() { + GCAdapter::Init(); +} + +GCButton::~GCButton() { + GCAdapter::Shutdown(); +} + +std::unique_ptr GCButtonFactory::Create(const Common::ParamPackage& params) { + int button_id = params.Get("button", 0); + int port = params.Get("port", 0); + // For Axis buttons, used by the binary sticks. + if (params.Has("axis")) { + const int axis = params.Get("axis", 0); + const float threshold = params.Get("threshold", 0.5f); + const std::string direction_name = params.Get("direction", ""); + bool trigger_if_greater; + if (direction_name == "+") { + trigger_if_greater = true; + } else if (direction_name == "-") { + trigger_if_greater = false; + } else { + trigger_if_greater = true; + LOG_ERROR(Input, "Unknown direction {}", direction_name); + } + return std::make_unique(port, axis, threshold, trigger_if_greater); + } + + std::unique_ptr button = + std::make_unique(port, button_id, params.Get("axis", 0)); + return std::move(button); +} + +Common::ParamPackage GCButtonFactory::GetNextInput() { + Common::ParamPackage params; + GCPadStatus pad; + for (int i = 0; i < 4; i++) { + while (pad_queue[i].Pop(pad)) { + // This while loop will break on the earliest detected button + params.Set("engine", "gcpad"); + params.Set("port", i); + // I was debating whether to keep these verbose for ease of reading + // or to use a while loop shifting the bits to test and set the value. + if (pad.button & PAD_BUTTON_A) { + params.Set("button", PAD_BUTTON_A); + break; + } + if (pad.button & PAD_BUTTON_B) { + params.Set("button", PAD_BUTTON_B); + break; + } + if (pad.button & PAD_BUTTON_X) { + params.Set("button", PAD_BUTTON_X); + break; + } + if (pad.button & PAD_BUTTON_Y) { + params.Set("button", PAD_BUTTON_Y); + break; + } + if (pad.button & PAD_BUTTON_DOWN) { + params.Set("button", PAD_BUTTON_DOWN); + break; + } + if (pad.button & PAD_BUTTON_LEFT) { + params.Set("button", PAD_BUTTON_LEFT); + break; + } + if (pad.button & PAD_BUTTON_RIGHT) { + params.Set("button", PAD_BUTTON_RIGHT); + break; + } + if (pad.button & PAD_BUTTON_UP) { + params.Set("button", PAD_BUTTON_UP); + break; + } + if (pad.button & PAD_TRIGGER_L) { + params.Set("button", PAD_TRIGGER_L); + break; + } + if (pad.button & PAD_TRIGGER_R) { + params.Set("button", PAD_TRIGGER_R); + break; + } + if (pad.button & PAD_TRIGGER_Z) { + params.Set("button", PAD_TRIGGER_Z); + break; + } + if (pad.button & PAD_BUTTON_START) { + params.Set("button", PAD_BUTTON_START); + break; + } + // For Axis button implementation + if (pad.axis_which != 255) { + params.Set("axis", pad.axis_which); + params.Set("button", PAD_STICK); + if (pad.axis_value > 128) { + params.Set("direction", "+"); + params.Set("threshold", "0.5"); + } else { + params.Set("direction", "-"); + params.Set("threshold", "-0.5"); + } + break; + } + } + } + return params; +} + +void GCButtonFactory::BeginConfiguration() { + polling = true; + for (int i = 0; i < 4; i++) + pad_queue[i].Clear(); + GCAdapter::BeginConfiguration(); +} + +void GCButtonFactory::EndConfiguration() { + polling = false; + + for (int i = 0; i < 4; i++) + pad_queue[i].Clear(); + GCAdapter::EndConfiguration(); +} + +class GCAnalog final : public Input::AnalogDevice { +public: + GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_) + : port(port_), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_) { + } + + float GetAxis(int axis) const { + std::lock_guard lock{mutex}; + // division is not by a perfect 128 to account for some variance in center location + // e.g. my device idled at 131 in X, 120 in Y, and full range of motion was in range [20-230] + return (state[port].axes.at(axis) - 128.0f) / 95.0f; + } + + std::tuple GetAnalog(int axis_x, int axis_y) const { + float x = GetAxis(axis_x); + float y = GetAxis(axis_y); + + // Make sure the coordinates are in the unit circle, + // otherwise normalize it. + float r = x * x + y * y; + if (r > 1.0f) { + r = std::sqrt(r); + x /= r; + y /= r; + } + + return std::make_tuple(x, y); + } + + std::tuple GetStatus() const override { + const auto [x, y] = GetAnalog(axis_x, axis_y); + const float r = std::sqrt((x * x) + (y * y)); + if (r > deadzone) { + return std::make_tuple(x / r * (r - deadzone) / (1 - deadzone), + y / r * (r - deadzone) / (1 - deadzone)); + } + return std::make_tuple(0.0f, 0.0f); + } + + bool GetAnalogDirectionStatus(Input::AnalogDirection direction) const override { + const auto [x, y] = GetStatus(); + const float directional_deadzone = 0.4f; + switch (direction) { + case Input::AnalogDirection::RIGHT: + return x > directional_deadzone; + case Input::AnalogDirection::LEFT: + return x < -directional_deadzone; + case Input::AnalogDirection::UP: + return y > directional_deadzone; + case Input::AnalogDirection::DOWN: + return y < -directional_deadzone; + } + return false; + } + +private: + const int port; + const int axis_x; + const int axis_y; + const float deadzone; + mutable std::mutex mutex; +}; + + +/// An analog device factory that creates analog devices from GC Adapter +GCAnalogFactory::GCAnalogFactory() {}; + + +/** +* Creates analog device from joystick axes +* @param params contains parameters for creating the device: +* - "port": the nth gcpad on the adapter +* - "axis_x": the index of the axis to be bind as x-axis +* - "axis_y": the index of the axis to be bind as y-axis +*/ +std::unique_ptr GCAnalogFactory::Create(const Common::ParamPackage& params) { + const std::string guid = params.Get("guid", "0"); + const int port = params.Get("port", 0); + const int axis_x = params.Get("axis_x", 0); + const int axis_y = params.Get("axis_y", 1); + const float deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, .99f); + + return std::make_unique(port, axis_x, axis_y, deadzone); +} + +void GCAnalogFactory::BeginConfiguration() { + polling = true; + for (int i = 0; i < 4; i++) + pad_queue[i].Clear(); + GCAdapter::BeginConfiguration(); +} + +void GCAnalogFactory::EndConfiguration() { + polling = false; + for (int i = 0; i < 4; i++) + pad_queue[i].Clear(); + GCAdapter::EndConfiguration(); +} + +Common::ParamPackage GCAnalogFactory::GetNextInput() { + GCPadStatus pad; + for (int i = 0; i < 4; i++) { + while (pad_queue[i].Pop(pad)) { + if (pad.axis_which == 255 || std::abs((pad.axis_value - 128.0f) / 128.0f) < 0.1) { + continue; + } + // An analog device needs two axes, so we need to store the axis for later and wait for + // a second SDL event. The axes also must be from the same joystick. + const int axis = pad.axis_which; + if (analog_x_axis == -1) { + analog_x_axis = axis; + controller_number = i; + } else if (analog_y_axis == -1 && analog_x_axis != axis && controller_number == i) { + analog_y_axis = axis; + } + } + } + Common::ParamPackage params; + if (analog_x_axis != -1 && analog_y_axis != -1) { + params.Set("engine", "gcpad"); + params.Set("port", controller_number); + params.Set("axis_x", analog_x_axis); + params.Set("axis_y", analog_y_axis); + analog_x_axis = -1; + analog_y_axis = -1; + controller_number = -1; + return params; + } + return params; +} +} // namespace InputCommon diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h new file mode 100644 index 000000000..d115b1d2a --- /dev/null +++ b/src/input_common/gcadapter/gc_poller.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include "core/frontend/input.h" + +namespace InputCommon { + + +/** + * A button device factory representing a gcpad. It receives gcpad events and forward them + * to all button devices it created. + */ +class GCButtonFactory final : public Input::Factory { +public: + GCButtonFactory(); + + /** + * Creates a button device from a button press + * @param params contains parameters for creating the device: + * - "code": the code of the key to bind with the button + */ + std::unique_ptr Create(const Common::ParamPackage& params) override; + + Common::ParamPackage GetNextInput(); + + /// For device input configuration/polling + void BeginConfiguration(); + void EndConfiguration(); + + bool IsPolling() { + return polling; + } + +private: + bool polling = false; +}; + +/// An analog device factory that creates analog devices from GC Adapter +class GCAnalogFactory final : public Input::Factory { +public: + GCAnalogFactory(); + std::unique_ptr Create(const Common::ParamPackage& params) override; + Common::ParamPackage GetNextInput(); + + /// For device input configuration/polling + void BeginConfiguration(); + void EndConfiguration(); + + bool IsPolling() { + return polling; + } + +private: + int analog_x_axis = -1; + int analog_y_axis = -1; + int controller_number = -1; + bool polling = false; +}; +} // namespace InputCommon diff --git a/src/input_common/keyboard.cpp b/src/input_common/keyboard.cpp index afb8e6612..d76791860 100644 --- a/src/input_common/keyboard.cpp +++ b/src/input_common/keyboard.cpp @@ -13,7 +13,8 @@ namespace InputCommon { class KeyButton final : public Input::ButtonDevice { public: explicit KeyButton(std::shared_ptr key_button_list_) - : key_button_list(std::move(key_button_list_)) {} + : key_button_list(std::move(key_button_list_)) { + } ~KeyButton() override; @@ -49,8 +50,10 @@ public: void ChangeKeyStatus(int key_code, bool pressed) { std::lock_guard guard{mutex}; for (const KeyButtonPair& pair : list) { - if (pair.key_code == key_code) + if (pair.key_code == key_code) { pair.key_button->status.store(pressed); + break; + } } } @@ -66,7 +69,9 @@ private: std::list list; }; -Keyboard::Keyboard() : key_button_list{std::make_shared()} {} +Keyboard::Keyboard() + : key_button_list{std::make_shared()} { +} KeyButton::~KeyButton() { key_button_list->RemoveKeyButton(this); @@ -76,7 +81,7 @@ std::unique_ptr Keyboard::Create(const Common::ParamPackage int key_code = params.Get("code", 0); std::unique_ptr button = std::make_unique(key_button_list); key_button_list->AddKeyButton(key_code, button.get()); - return button; + return std::move(button); } void Keyboard::PressKey(int key_code) { diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index 95e351e24..be13129af 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -4,8 +4,11 @@ #include #include +#include +#include #include "common/param_package.h" #include "input_common/analog_from_button.h" +#include "input_common/gcadapter/gc_poller.h" #include "input_common/keyboard.h" #include "input_common/main.h" #include "input_common/motion_emu.h" @@ -22,8 +25,15 @@ static std::shared_ptr motion_emu; static std::unique_ptr sdl; #endif static std::unique_ptr udp; +static std::shared_ptr gcbuttons; +static std::shared_ptr gcanalog; void Init() { + gcbuttons = std::make_shared(); + Input::RegisterFactory("gcpad", gcbuttons); + gcanalog = std::make_shared(); + Input::RegisterFactory("gcpad", gcanalog); + keyboard = std::make_shared(); Input::RegisterFactory("keyboard", keyboard); Input::RegisterFactory("analog_from_button", @@ -34,8 +44,10 @@ void Init() { #ifdef HAVE_SDL2 sdl = SDL::Init(); #endif + /* udp = CemuhookUDP::Init(); + */ } void Shutdown() { @@ -48,6 +60,8 @@ void Shutdown() { sdl.reset(); #endif udp.reset(); + Input::UnregisterFactory("gcpad"); + gcbuttons.reset(); } Keyboard* GetKeyboard() { @@ -58,6 +72,14 @@ MotionEmu* GetMotionEmu() { return motion_emu.get(); } +GCButtonFactory* GetGCButtons() { + return gcbuttons.get(); +} + +GCAnalogFactory* GetGCAnalogs() { + return gcanalog.get(); +} + std::string GenerateKeyboardParam(int key_code) { Common::ParamPackage param{ {"engine", "keyboard"}, @@ -88,7 +110,6 @@ std::vector> GetPollers(DeviceType type) { #ifdef HAVE_SDL2 pollers = sdl->GetPollers(type); #endif - return pollers; } diff --git a/src/input_common/main.h b/src/input_common/main.h index 77a0ce90b..be2e7a6c4 100644 --- a/src/input_common/main.h +++ b/src/input_common/main.h @@ -7,6 +7,8 @@ #include #include #include +#include "input_common/gcadapter/gc_poller.h" +#include "input_common/gcadapter/gc_adapter.h" namespace Common { class ParamPackage; @@ -30,6 +32,13 @@ class MotionEmu; /// Gets the motion emulation factory. MotionEmu* GetMotionEmu(); +class GCButtonFactory; +class GCAnalogFactory; + +GCButtonFactory* GetGCButtons(); +GCAnalogFactory* GetGCAnalogs(); + + /// Generates a serialized param package for creating a keyboard button device std::string GenerateKeyboardParam(int key_code); diff --git a/src/input_common/motion_emu.cpp b/src/input_common/motion_emu.cpp index d4cdf76a3..b7120311a 100644 --- a/src/input_common/motion_emu.cpp +++ b/src/input_common/motion_emu.cpp @@ -22,7 +22,8 @@ public: : update_millisecond(update_millisecond), update_duration(std::chrono::duration_cast( std::chrono::milliseconds(update_millisecond))), - sensitivity(sensitivity), motion_emu_thread(&MotionEmuDevice::MotionEmuThread, this) {} + sensitivity(sensitivity), motion_emu_thread(&MotionEmuDevice::MotionEmuThread, this) { + } ~MotionEmuDevice() { if (motion_emu_thread.joinable()) { @@ -145,7 +146,7 @@ std::unique_ptr MotionEmu::Create(const Common::ParamPackag // Previously created device is disconnected here. Having two motion devices for 3DS is not // expected. current_device = device_wrapper->device; - return device_wrapper; + return std::move(device_wrapper); } void MotionEmu::BeginTilt(int x, int y) { diff --git a/src/input_common/sdl/sdl_impl.cpp b/src/input_common/sdl/sdl_impl.cpp index 675b477fa..3c1820c4a 100644 --- a/src/input_common/sdl/sdl_impl.cpp +++ b/src/input_common/sdl/sdl_impl.cpp @@ -49,7 +49,8 @@ static int SDLEventWatcher(void* user_data, SDL_Event* event) { class SDLJoystick { public: SDLJoystick(std::string guid_, int port_, SDL_Joystick* joystick) - : guid{std::move(guid_)}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose} {} + : guid{std::move(guid_)}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose} { + } void SetButton(int button, bool value) { std::lock_guard lock{mutex}; @@ -97,6 +98,7 @@ public: std::lock_guard lock{mutex}; return (state.hats.at(hat) & direction) != 0; } + /** * The guid of the joystick */ @@ -125,6 +127,7 @@ private: std::unordered_map axes; std::unordered_map hats; } state; + std::string guid; int port; std::unique_ptr sdl_joystick; @@ -155,7 +158,8 @@ std::shared_ptr SDLState::GetSDLJoystickBySDLID(SDL_JoystickID sdl_ if (map_it != joystick_map.end()) { const auto vec_it = std::find_if(map_it->second.begin(), map_it->second.end(), - [&sdl_joystick](const std::shared_ptr& joystick) { + [&sdl_joystick](const std::shared_ptr& joystick) + { return sdl_joystick == joystick->GetSDLJoystick(); }); if (vec_it != map_it->second.end()) { @@ -166,7 +170,8 @@ std::shared_ptr SDLState::GetSDLJoystickBySDLID(SDL_JoystickID sdl_ // Search for a SDLJoystick without a mapped SDL_Joystick... const auto nullptr_it = std::find_if(map_it->second.begin(), map_it->second.end(), - [](const std::shared_ptr& joystick) { + [](const std::shared_ptr& joystick) + { return !joystick->GetSDLJoystick(); }); if (nullptr_it != map_it->second.end()) { @@ -223,7 +228,8 @@ void SDLState::CloseJoystick(SDL_Joystick* sdl_joystick) { const auto& joystick_guid_list = joystick_map[guid]; const auto joystick_it = std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(), - [&sdl_joystick](const std::shared_ptr& joystick) { + [&sdl_joystick](const std::shared_ptr& joystick) + { return joystick->GetSDLJoystick() == sdl_joystick; }); joystick = *joystick_it; @@ -279,7 +285,8 @@ void SDLState::CloseJoysticks() { class SDLButton final : public Input::ButtonDevice { public: explicit SDLButton(std::shared_ptr joystick_, int button_) - : joystick(std::move(joystick_)), button(button_) {} + : joystick(std::move(joystick_)), button(button_) { + } bool GetStatus() const override { return joystick->GetButton(button); @@ -293,7 +300,8 @@ private: class SDLDirectionButton final : public Input::ButtonDevice { public: explicit SDLDirectionButton(std::shared_ptr joystick_, int hat_, Uint8 direction_) - : joystick(std::move(joystick_)), hat(hat_), direction(direction_) {} + : joystick(std::move(joystick_)), hat(hat_), direction(direction_) { + } bool GetStatus() const override { return joystick->GetHatDirection(hat, direction); @@ -310,7 +318,8 @@ public: explicit SDLAxisButton(std::shared_ptr joystick_, int axis_, float threshold_, bool trigger_if_greater_) : joystick(std::move(joystick_)), axis(axis_), threshold(threshold_), - trigger_if_greater(trigger_if_greater_) {} + trigger_if_greater(trigger_if_greater_) { + } bool GetStatus() const override { const float axis_value = joystick->GetAxis(axis); @@ -330,7 +339,8 @@ private: class SDLAnalog final : public Input::AnalogDevice { public: SDLAnalog(std::shared_ptr joystick_, int axis_x_, int axis_y_, float deadzone_) - : joystick(std::move(joystick_)), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_) {} + : joystick(std::move(joystick_)), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_) { + } std::tuple GetStatus() const override { const auto [x, y] = joystick->GetAnalog(axis_x, axis_y); @@ -368,7 +378,9 @@ private: /// A button device factory that creates button devices from SDL joystick class SDLButtonFactory final : public Input::Factory { public: - explicit SDLButtonFactory(SDLState& state_) : state(state_) {} + explicit SDLButtonFactory(SDLState& state_) + : state(state_) { + } /** * Creates a button device from a joystick button @@ -443,7 +455,10 @@ private: /// An analog device factory that creates analog devices from SDL joystick class SDLAnalogFactory final : public Input::Factory { public: - explicit SDLAnalogFactory(SDLState& state_) : state(state_) {} + explicit SDLAnalogFactory(SDLState& state_) + : state(state_) { + } + /** * Creates analog device from joystick axes * @param params contains parameters for creating the device: @@ -490,7 +505,8 @@ SDLState::SDLState() { initialized = true; if (start_thread) { - poll_thread = std::thread([this] { + poll_thread = std::thread([this] + { using namespace std::chrono_literals; while (initialized) { SDL_PumpEvents(); @@ -576,7 +592,9 @@ namespace Polling { class SDLPoller : public InputCommon::Polling::DevicePoller { public: - explicit SDLPoller(SDLState& state_) : state(state_) {} + explicit SDLPoller(SDLState& state_) + : state(state_) { + } void Start() override { state.event_queue.Clear(); @@ -593,7 +611,9 @@ protected: class SDLButtonPoller final : public SDLPoller { public: - explicit SDLButtonPoller(SDLState& state_) : SDLPoller(state_) {} + explicit SDLButtonPoller(SDLState& state_) + : SDLPoller(state_) { + } Common::ParamPackage GetNextInput() override { SDL_Event event; @@ -602,8 +622,7 @@ public: case SDL_JOYAXISMOTION: if (std::abs(event.jaxis.value / 32767.0) < 0.5) { break; - } - [[fallthrough]]; + }[[fallthrough]]; case SDL_JOYBUTTONUP: case SDL_JOYHATMOTION: return SDLEventToButtonParamPackage(state, event); @@ -615,7 +634,9 @@ public: class SDLAnalogPoller final : public SDLPoller { public: - explicit SDLAnalogPoller(SDLState& state_) : SDLPoller(state_) {} + explicit SDLAnalogPoller(SDLState& state_) + : SDLPoller(state_) { + } void Start() override { SDLPoller::Start(); diff --git a/src/input_common/udp/client.cpp b/src/input_common/udp/client.cpp index da5227058..befa4c86d 100644 --- a/src/input_common/udp/client.cpp +++ b/src/input_common/udp/client.cpp @@ -59,7 +59,8 @@ public: void StartReceive() { socket.async_receive_from( boost::asio::buffer(receive_buffer), receive_endpoint, - [this](const boost::system::error_code& error, std::size_t bytes_transferred) { + [this](const boost::system::error_code& error, std::size_t bytes_transferred) + { HandleReceive(error, bytes_transferred); }); } @@ -211,21 +212,27 @@ void Client::StartCommunication(const std::string& host, u16 port, u8 pad_index, void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id, std::function success_callback, std::function failure_callback) { - std::thread([=] { - Common::Event success_event; - SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {}, - [&](Response::PadData data) { success_event.Set(); }}; - Socket socket{host, port, pad_index, client_id, std::move(callback)}; - std::thread worker_thread{SocketLoop, &socket}; - bool result = success_event.WaitFor(std::chrono::seconds(8)); - socket.Stop(); - worker_thread.join(); - if (result) { - success_callback(); - } else { - failure_callback(); - } - }) + std::thread([=] + { + Common::Event success_event; + SocketCallback callback{[](Response::Version version) + { + }, + [](Response::PortInfo info) + { + }, + [&](Response::PadData data) { success_event.Set(); }}; + Socket socket{host, port, pad_index, client_id, std::move(callback)}; + std::thread worker_thread{SocketLoop, &socket}; + bool result = success_event.WaitFor(std::chrono::seconds(8)); + socket.Stop(); + worker_thread.join(); + if (result) { + success_callback(); + } else { + failure_callback(); + } + }) .detach(); } @@ -234,53 +241,60 @@ CalibrationConfigurationJob::CalibrationConfigurationJob( std::function status_callback, std::function data_callback) { - std::thread([=] { - constexpr u16 CALIBRATION_THRESHOLD = 100; + std::thread([=] + { + constexpr u16 CALIBRATION_THRESHOLD = 100; - u16 min_x{UINT16_MAX}; - u16 min_y{UINT16_MAX}; - u16 max_x{}; - u16 max_y{}; + u16 min_x{UINT16_MAX}; + u16 min_y{UINT16_MAX}; + u16 max_x{}; + u16 max_y{}; - Status current_status{Status::Initialized}; - SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {}, - [&](Response::PadData data) { - if (current_status == Status::Initialized) { - // Receiving data means the communication is ready now - current_status = Status::Ready; - status_callback(current_status); - } - if (!data.touch_1.is_active) { - return; - } - LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x, - data.touch_1.y); - min_x = std::min(min_x, static_cast(data.touch_1.x)); - min_y = std::min(min_y, static_cast(data.touch_1.y)); - if (current_status == Status::Ready) { - // First touch - min data (min_x/min_y) - current_status = Status::Stage1Completed; - status_callback(current_status); - } - if (data.touch_1.x - min_x > CALIBRATION_THRESHOLD && - data.touch_1.y - min_y > CALIBRATION_THRESHOLD) { - // Set the current position as max value and finishes - // configuration - max_x = data.touch_1.x; - max_y = data.touch_1.y; - current_status = Status::Completed; - data_callback(min_x, min_y, max_x, max_y); - status_callback(current_status); + Status current_status{Status::Initialized}; + SocketCallback callback{[](Response::Version version) + { + }, + [](Response::PortInfo info) + { + }, + [&](Response::PadData data) + { + if (current_status == Status::Initialized) { + // Receiving data means the communication is ready now + current_status = Status::Ready; + status_callback(current_status); + } + if (!data.touch_1.is_active) { + return; + } + LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x, + data.touch_1.y); + min_x = std::min(min_x, static_cast(data.touch_1.x)); + min_y = std::min(min_y, static_cast(data.touch_1.y)); + if (current_status == Status::Ready) { + // First touch - min data (min_x/min_y) + current_status = Status::Stage1Completed; + status_callback(current_status); + } + if (data.touch_1.x - min_x > CALIBRATION_THRESHOLD && + data.touch_1.y - min_y > CALIBRATION_THRESHOLD) { + // Set the current position as max value and finishes + // configuration + max_x = data.touch_1.x; + max_y = data.touch_1.y; + current_status = Status::Completed; + data_callback(min_x, min_y, max_x, max_y); + status_callback(current_status); - complete_event.Set(); - } - }}; - Socket socket{host, port, pad_index, client_id, std::move(callback)}; - std::thread worker_thread{SocketLoop, &socket}; - complete_event.Wait(); - socket.Stop(); - worker_thread.join(); - }) + complete_event.Set(); + } + }}; + Socket socket{host, port, pad_index, client_id, std::move(callback)}; + std::thread worker_thread{SocketLoop, &socket}; + complete_event.Wait(); + socket.Stop(); + worker_thread.join(); + }) .detach(); } diff --git a/src/input_common/udp/client.h b/src/input_common/udp/client.h index b8c654755..b58e319b6 100644 --- a/src/input_common/udp/client.h +++ b/src/input_common/udp/client.h @@ -40,6 +40,7 @@ struct DeviceStatus { u16 max_x{}; u16 max_y{}; }; + std::optional touch_calibration; }; @@ -72,6 +73,7 @@ public: Stage1Completed, Completed, }; + /** * Constructs and starts the job with the specified parameter. * diff --git a/src/input_common/udp/protocol.h b/src/input_common/udp/protocol.h index 3ba4d1fc8..2b31846db 100644 --- a/src/input_common/udp/protocol.h +++ b/src/input_common/udp/protocol.h @@ -35,6 +35,7 @@ struct Header { ///> the data Type type{}; }; + static_assert(sizeof(Header) == 20, "UDP Message Header struct has wrong size"); static_assert(std::is_trivially_copyable_v
, "UDP Message Header is not trivially copyable"); @@ -54,7 +55,9 @@ constexpr Type GetMessageType(); namespace Request { -struct Version {}; +struct Version { +}; + /** * Requests the server to send information about what controllers are plugged into the ports * In citra's case, we only have one controller, so for simplicity's sake, we can just send a @@ -62,12 +65,14 @@ struct Version {}; * nice to make this configurable */ constexpr u32 MAX_PORTS = 4; + struct PortInfo { u32_le pad_count{}; ///> Number of ports to request data for std::array port; }; + static_assert(std::is_trivially_copyable_v, - "UDP Request PortInfo is not trivially copyable"); + "UDP Request PortInfo is not trivially copyable"); /** * Request the latest pad information from the server. If the server hasn't received this message @@ -80,6 +85,7 @@ struct PadData { Id, Mac, }; + /// Determines which method will be used as a look up for the controller Flags flags{}; /// Index of the port of the controller to retrieve data about @@ -87,9 +93,10 @@ struct PadData { /// Mac address of the controller to retrieve data about MacAddress mac; }; + static_assert(sizeof(PadData) == 8, "UDP Request PadData struct has wrong size"); static_assert(std::is_trivially_copyable_v, - "UDP Request PadData is not trivially copyable"); + "UDP Request PadData is not trivially copyable"); /** * Creates a message with the proper header data that can be sent to the server. @@ -114,9 +121,10 @@ namespace Response { struct Version { u16_le version{}; }; + static_assert(sizeof(Version) == 2, "UDP Response Version struct has wrong size"); static_assert(std::is_trivially_copyable_v, - "UDP Response Version is not trivially copyable"); + "UDP Response Version is not trivially copyable"); struct PortInfo { u8 id{}; @@ -127,9 +135,10 @@ struct PortInfo { u8 battery{}; u8 is_pad_active{}; }; + static_assert(sizeof(PortInfo) == 12, "UDP Response PortInfo struct has wrong size"); static_assert(std::is_trivially_copyable_v, - "UDP Response PortInfo is not trivially copyable"); + "UDP Response PortInfo is not trivially copyable"); #pragma pack(push, 1) struct PadData { @@ -206,16 +215,16 @@ struct PadData { static_assert(sizeof(PadData) == 80, "UDP Response PadData struct has wrong size "); static_assert(std::is_trivially_copyable_v, - "UDP Response PadData is not trivially copyable"); + "UDP Response PadData is not trivially copyable"); static_assert(sizeof(Message) == MAX_PACKET_SIZE, - "UDP MAX_PACKET_SIZE is no longer larger than Message"); + "UDP MAX_PACKET_SIZE is no longer larger than Message"); static_assert(sizeof(PadData::AnalogButton) == 12, - "UDP Response AnalogButton struct has wrong size "); + "UDP Response AnalogButton struct has wrong size "); static_assert(sizeof(PadData::TouchPad) == 6, "UDP Response TouchPad struct has wrong size "); static_assert(sizeof(PadData::Accelerometer) == 12, - "UDP Response Accelerometer struct has wrong size "); + "UDP Response Accelerometer struct has wrong size "); static_assert(sizeof(PadData::Gyroscope) == 12, "UDP Response Gyroscope struct has wrong size "); /** @@ -232,22 +241,27 @@ template <> constexpr Type GetMessageType() { return Type::Version; } + template <> constexpr Type GetMessageType() { return Type::PortInfo; } + template <> constexpr Type GetMessageType() { return Type::PadData; } + template <> constexpr Type GetMessageType() { return Type::Version; } + template <> constexpr Type GetMessageType() { return Type::PortInfo; } + template <> constexpr Type GetMessageType() { return Type::PadData; diff --git a/src/input_common/udp/udp.cpp b/src/input_common/udp/udp.cpp index 8c6ef1394..343c3985e 100644 --- a/src/input_common/udp/udp.cpp +++ b/src/input_common/udp/udp.cpp @@ -16,7 +16,10 @@ namespace InputCommon::CemuhookUDP { class UDPTouchDevice final : public Input::TouchDevice { public: - explicit UDPTouchDevice(std::shared_ptr status_) : status(std::move(status_)) {} + explicit UDPTouchDevice(std::shared_ptr status_) + : status(std::move(status_)) { + } + std::tuple GetStatus() const override { std::lock_guard guard(status->update_mutex); return status->touch_status; @@ -28,7 +31,10 @@ private: class UDPMotionDevice final : public Input::MotionDevice { public: - explicit UDPMotionDevice(std::shared_ptr status_) : status(std::move(status_)) {} + explicit UDPMotionDevice(std::shared_ptr status_) + : status(std::move(status_)) { + } + std::tuple, Common::Vec3> GetStatus() const override { std::lock_guard guard(status->update_mutex); return status->motion_status; @@ -40,7 +46,9 @@ private: class UDPTouchFactory final : public Input::Factory { public: - explicit UDPTouchFactory(std::shared_ptr status_) : status(std::move(status_)) {} + explicit UDPTouchFactory(std::shared_ptr status_) + : status(std::move(status_)) { + } std::unique_ptr Create(const Common::ParamPackage& params) override { { @@ -61,7 +69,9 @@ private: class UDPMotionFactory final : public Input::Factory { public: - explicit UDPMotionFactory(std::shared_ptr status_) : status(std::move(status_)) {} + explicit UDPMotionFactory(std::shared_ptr status_) + : status(std::move(status_)) { + } std::unique_ptr Create(const Common::ParamPackage& params) override { return std::make_unique(status); diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp index a05fa64ba..81436af1b 100644 --- a/src/yuzu/configuration/configure_input_player.cpp +++ b/src/yuzu/configuration/configure_input_player.cpp @@ -19,13 +19,13 @@ #include "yuzu/configuration/configure_input_player.h" const std::array - ConfigureInputPlayer::analog_sub_buttons{{ - "up", - "down", - "left", - "right", - "modifier", - }}; +ConfigureInputPlayer::analog_sub_buttons{{ + "up", + "down", + "left", + "right", + "modifier", +}}; static void LayerGridElements(QGridLayout* grid, QWidget* item, QWidget* onTopOf) { const int index1 = grid->indexOf(item); @@ -70,6 +70,20 @@ static QString ButtonToText(const Common::ParamPackage& param) { return GetKeyName(param.Get("code", 0)); } + if (param.Get("engine", "") == "gcpad") { + if (param.Has("axis")) { + const QString axis_str = QString::fromStdString(param.Get("axis", "")); + const QString direction_str = QString::fromStdString(param.Get("direction", "")); + + return QObject::tr("Axis %1%2").arg(axis_str, direction_str); + } + if (param.Has("button")) { + const QString button_str = QString::number(int(std::log2(param.Get("button", 0)))); + return QObject::tr("Button %1").arg(button_str); + } + return GetKeyName(param.Get("code", 0)); + } + if (param.Get("engine", "") == "sdl") { if (param.Has("hat")) { const QString hat_str = QString::fromStdString(param.Get("hat", "")); @@ -106,7 +120,7 @@ static QString AnalogToText(const Common::ParamPackage& param, const std::string return ButtonToText(Common::ParamPackage{param.Get(dir, "")}); } - if (param.Get("engine", "") == "sdl") { + if (param.Get("engine", "") == "sdl" || param.Get("engine", "") == "gcpad") { if (dir == "modifier") { return QObject::tr("[unused]"); } @@ -137,13 +151,13 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i setFocusPolicy(Qt::ClickFocus); button_map = { - ui->buttonA, ui->buttonB, ui->buttonX, ui->buttonY, - ui->buttonLStick, ui->buttonRStick, ui->buttonL, ui->buttonR, - ui->buttonZL, ui->buttonZR, ui->buttonPlus, ui->buttonMinus, - ui->buttonDpadLeft, ui->buttonDpadUp, ui->buttonDpadRight, ui->buttonDpadDown, + ui->buttonA, ui->buttonB, ui->buttonX, ui->buttonY, + ui->buttonLStick, ui->buttonRStick, ui->buttonL, ui->buttonR, + ui->buttonZL, ui->buttonZR, ui->buttonPlus, ui->buttonMinus, + ui->buttonDpadLeft, ui->buttonDpadUp, ui->buttonDpadRight, ui->buttonDpadDown, ui->buttonLStickLeft, ui->buttonLStickUp, ui->buttonLStickRight, ui->buttonLStickDown, ui->buttonRStickLeft, ui->buttonRStickUp, ui->buttonRStickRight, ui->buttonRStickDown, - ui->buttonSL, ui->buttonSR, ui->buttonHome, ui->buttonScreenshot, + ui->buttonSL, ui->buttonSR, ui->buttonHome, ui->buttonScreenshot, }; analog_map_buttons = {{ @@ -164,11 +178,11 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i }}; debug_hidden = { - ui->buttonSL, ui->labelSL, - ui->buttonSR, ui->labelSR, - ui->buttonLStick, ui->labelLStickPressed, - ui->buttonRStick, ui->labelRStickPressed, - ui->buttonHome, ui->labelHome, + ui->buttonSL, ui->labelSL, + ui->buttonSR, ui->labelSR, + ui->buttonLStick, ui->labelLStickPressed, + ui->buttonRStick, ui->labelRStickPressed, + ui->buttonHome, ui->labelHome, ui->buttonScreenshot, ui->labelScreenshot, }; @@ -207,12 +221,12 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i case Settings::ControllerType::RightJoycon: layout_hidden = { ui->left_body_button, ui->left_buttons_button, - ui->left_body_label, ui->left_buttons_label, - ui->buttonL, ui->labelL, - ui->buttonZL, ui->labelZL, - ui->labelScreenshot, ui->buttonScreenshot, - ui->buttonMinus, ui->labelMinus, - ui->LStick, ui->Dpad, + ui->left_body_label, ui->left_buttons_label, + ui->buttonL, ui->labelL, + ui->buttonZL, ui->labelZL, + ui->labelScreenshot, ui->buttonScreenshot, + ui->buttonMinus, ui->labelMinus, + ui->LStick, ui->Dpad, }; break; } @@ -247,9 +261,11 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i } button->setContextMenuPolicy(Qt::CustomContextMenu); - connect(button, &QPushButton::clicked, [=] { + connect(button, &QPushButton::clicked, [=] + { HandleClick(button_map[button_id], - [=](Common::ParamPackage params) { + [=](Common::ParamPackage params) + { // Workaround for ZL & ZR for analog triggers like on XBOX controllors. // Analog triggers (from controllers like the XBOX controller) would not // work due to a different range of their signals (from 0 to 255 on @@ -267,13 +283,16 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i }, InputCommon::Polling::DeviceType::Button); }); - connect(button, &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) { + connect(button, &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) + { QMenu context_menu; - context_menu.addAction(tr("Clear"), [&] { + context_menu.addAction(tr("Clear"), [&] + { buttons_param[button_id].Clear(); button_map[button_id]->setText(tr("[not set]")); }); - context_menu.addAction(tr("Restore Default"), [&] { + context_menu.addAction(tr("Restore Default"), [&] + { buttons_param[button_id] = Common::ParamPackage{ InputCommon::GenerateKeyboardParam(Config::default_buttons[button_id])}; button_map[button_id]->setText(ButtonToText(buttons_param[button_id])); @@ -290,22 +309,27 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i } analog_button->setContextMenuPolicy(Qt::CustomContextMenu); - connect(analog_button, &QPushButton::clicked, [=]() { + connect(analog_button, &QPushButton::clicked, [=]() + { HandleClick(analog_map_buttons[analog_id][sub_button_id], - [=](const Common::ParamPackage& params) { + [=](const Common::ParamPackage& params) + { SetAnalogButton(params, analogs_param[analog_id], analog_sub_buttons[sub_button_id]); }, InputCommon::Polling::DeviceType::Button); }); connect(analog_button, &QPushButton::customContextMenuRequested, - [=](const QPoint& menu_location) { + [=](const QPoint& menu_location) + { QMenu context_menu; - context_menu.addAction(tr("Clear"), [&] { + context_menu.addAction(tr("Clear"), [&] + { analogs_param[analog_id].Erase(analog_sub_buttons[sub_button_id]); analog_map_buttons[analog_id][sub_button_id]->setText(tr("[not set]")); }); - context_menu.addAction(tr("Restore Default"), [&] { + context_menu.addAction(tr("Restore Default"), [&] + { Common::ParamPackage params{InputCommon::GenerateKeyboardParam( Config::default_analogs[analog_id][sub_button_id])}; SetAnalogButton(params, analogs_param[analog_id], @@ -317,11 +341,12 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i menu_location)); }); } - connect(analog_map_stick[analog_id], &QPushButton::clicked, [=] { + connect(analog_map_stick[analog_id], &QPushButton::clicked, [=] + { if (QMessageBox::information( this, tr("Information"), tr("After pressing OK, first move your joystick horizontally, " - "and then vertically."), + "and then vertically."), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) { HandleClick( analog_map_stick[analog_id], @@ -330,9 +355,11 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i } }); - connect(analog_map_deadzone_and_modifier_slider[analog_id], &QSlider::valueChanged, [=] { + connect(analog_map_deadzone_and_modifier_slider[analog_id], &QSlider::valueChanged, [=] + { const float slider_value = analog_map_deadzone_and_modifier_slider[analog_id]->value(); - if (analogs_param[analog_id].Get("engine", "") == "sdl") { + if (analogs_param[analog_id].Get("engine", "") == "sdl" || + analogs_param[analog_id].Get("engine", "") == "gcpad") { analog_map_deadzone_and_modifier_slider_label[analog_id]->setText( tr("Deadzone: %1%").arg(slider_value)); analogs_param[analog_id].Set("deadzone", slider_value / 100.0f); @@ -350,8 +377,23 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i timeout_timer->setSingleShot(true); connect(timeout_timer.get(), &QTimer::timeout, [this] { SetPollingResult({}, true); }); - connect(poll_timer.get(), &QTimer::timeout, [this] { + connect(poll_timer.get(), &QTimer::timeout, [this] + { Common::ParamPackage params; + if (InputCommon::GetGCButtons()->IsPolling()) { + params = InputCommon::GetGCButtons()->GetNextInput(); + if (params.Has("engine")) { + SetPollingResult(params, false); + return; + } + } + if (InputCommon::GetGCAnalogs()->IsPolling()) { + params = InputCommon::GetGCAnalogs()->GetNextInput(); + if (params.Has("engine")) { + SetPollingResult(params, false); + return; + } + } for (auto& poller : device_pollers) { params = poller->GetNextInput(); if (params.Has("engine")) { @@ -463,7 +505,7 @@ void ConfigureInputPlayer::LoadConfiguration() { for (std::size_t i = 0; i < colors.size(); ++i) { controller_color_buttons[i]->setStyleSheet( QStringLiteral("QPushButton { background-color: %1 }") - .arg(controller_colors[i].name())); + .arg(controller_colors[i].name())); } } @@ -534,7 +576,7 @@ void ConfigureInputPlayer::UpdateButtonLabels() { analog_map_deadzone_and_modifier_slider_label[analog_id]; if (param.Has("engine")) { - if (param.Get("engine", "") == "sdl") { + if (param.Get("engine", "") == "sdl" || param.Get("engine", "") == "gcpad") { if (!param.Has("deadzone")) { param.Set("deadzone", 0.1f); } @@ -583,6 +625,10 @@ void ConfigureInputPlayer::HandleClick( grabKeyboard(); grabMouse(); + if (type == InputCommon::Polling::DeviceType::Button) + InputCommon::GetGCButtons()->BeginConfiguration(); + else + InputCommon::GetGCAnalogs()->BeginConfiguration(); timeout_timer->start(5000); // Cancel after 5 seconds poll_timer->start(200); // Check for new inputs every 200ms } @@ -596,6 +642,9 @@ void ConfigureInputPlayer::SetPollingResult(const Common::ParamPackage& params, poller->Stop(); } + InputCommon::GetGCButtons()->EndConfiguration(); + InputCommon::GetGCAnalogs()->EndConfiguration(); + if (!abort) { (*input_setter)(params); } diff --git a/src/yuzu/configuration/configure_input_player.h b/src/yuzu/configuration/configure_input_player.h index 95afa5375..dad2a80ec 100644 --- a/src/yuzu/configuration/configure_input_player.h +++ b/src/yuzu/configuration/configure_input_player.h @@ -31,7 +31,7 @@ class ConfigureInputPlayer; } class ConfigureInputPlayer : public QDialog { - Q_OBJECT +Q_OBJECT public: explicit ConfigureInputPlayer(QWidget* parent, std::size_t player_index, bool debug = false); @@ -92,15 +92,15 @@ private: /// A group of five QPushButtons represent one analog input. The buttons each represent up, /// down, left, right, and modifier, respectively. std::array, Settings::NativeAnalog::NumAnalogs> - analog_map_buttons; + analog_map_buttons; /// Analog inputs are also represented each with a single button, used to configure with an /// actual analog stick std::array analog_map_stick; std::array - analog_map_deadzone_and_modifier_slider; + analog_map_deadzone_and_modifier_slider; std::array - analog_map_deadzone_and_modifier_slider_label; + analog_map_deadzone_and_modifier_slider_label; static const std::array analog_sub_buttons;