From 0248614add99c1df1bc7c9ff97091f678ff75aca Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 12:36:28 -0400 Subject: [PATCH 01/27] 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 c55d900e27..d92325cb55 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 a9c2392b15..3bd76dd238 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 6cabdaa3ce..8116fcf9fc 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 0000000000..d42261d619 --- /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 0000000000..9b02d1382f --- /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 0000000000..772bd88904 --- /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 0000000000..d115b1d2a2 --- /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 afb8e6612c..d76791860c 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 95e351e241..be13129afb 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 77a0ce90b2..be2e7a6c4b 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 d4cdf76a3f..b7120311aa 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 675b477fa3..3c1820c4ae 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 da5227058d..befa4c86d7 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 b8c6547554..b58e319b65 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 3ba4d1fc8d..2b31846db4 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 8c6ef13949..343c3985ef 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 a05fa64ba3..81436af1b2 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 95afa53752..dad2a80ecd 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; From 18a42d3815d0ac8dc9ff14538e219496c9cfd159 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 12:39:15 -0400 Subject: [PATCH 02/27] Add libusb dependency --- .gitmodules | 3 +++ externals/libusb | 1 + 2 files changed, 4 insertions(+) create mode 160000 externals/libusb diff --git a/.gitmodules b/.gitmodules index 9ba8fe2072..e3ec628ea3 100644 --- a/.gitmodules +++ b/.gitmodules @@ -34,3 +34,6 @@ [submodule "xbyak"] path = externals/xbyak url = https://github.com/herumi/xbyak.git +[submodule "externals/libusb"] + path = externals/libusb + url = https://github.com/ameerj/libusb diff --git a/externals/libusb b/externals/libusb new file mode 160000 index 0000000000..c5085fc4eb --- /dev/null +++ b/externals/libusb @@ -0,0 +1 @@ +Subproject commit c5085fc4eb1a83e6a8921a43b8d77f162b9e3b41 From 0076a08d04017036b12405bfb933fa9272f8b0cd Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 13:02:43 -0400 Subject: [PATCH 03/27] Cleanup after linter --- src/input_common/analog_from_button.cpp | 3 +- src/input_common/keyboard.cpp | 9 +- src/input_common/main.cpp | 4 - src/input_common/motion_emu.cpp | 5 +- src/input_common/sdl/sdl_impl.cpp | 52 +++------ 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 +--- 9 files changed, 95 insertions(+), 164 deletions(-) diff --git a/src/input_common/analog_from_button.cpp b/src/input_common/analog_from_button.cpp index 8116fcf9fc..6cabdaa3ce 100755 --- a/src/input_common/analog_from_button.cpp +++ b/src/input_common/analog_from_button.cpp @@ -14,8 +14,7 @@ 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/keyboard.cpp b/src/input_common/keyboard.cpp index d76791860c..9138a75630 100644 --- a/src/input_common/keyboard.cpp +++ b/src/input_common/keyboard.cpp @@ -13,8 +13,7 @@ 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; @@ -69,9 +68,7 @@ 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); @@ -81,7 +78,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 std::move(button); + return button; } void Keyboard::PressKey(int key_code) { diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index be13129afb..7fc0e2db4c 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include "common/param_package.h" #include "input_common/analog_from_button.h" #include "input_common/gcadapter/gc_poller.h" @@ -44,10 +43,7 @@ void Init() { #ifdef HAVE_SDL2 sdl = SDL::Init(); #endif - /* - udp = CemuhookUDP::Init(); - */ } void Shutdown() { diff --git a/src/input_common/motion_emu.cpp b/src/input_common/motion_emu.cpp index b7120311aa..d4cdf76a3f 100644 --- a/src/input_common/motion_emu.cpp +++ b/src/input_common/motion_emu.cpp @@ -22,8 +22,7 @@ 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()) { @@ -146,7 +145,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 std::move(device_wrapper); + return 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 3c1820c4ae..6b264f2a6f 100644 --- a/src/input_common/sdl/sdl_impl.cpp +++ b/src/input_common/sdl/sdl_impl.cpp @@ -49,8 +49,7 @@ 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}; @@ -98,7 +97,6 @@ public: std::lock_guard lock{mutex}; return (state.hats.at(hat) & direction) != 0; } - /** * The guid of the joystick */ @@ -127,7 +125,6 @@ private: std::unordered_map axes; std::unordered_map hats; } state; - std::string guid; int port; std::unique_ptr sdl_joystick; @@ -158,8 +155,7 @@ 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()) { @@ -170,8 +166,7 @@ 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()) { @@ -228,8 +223,7 @@ 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; @@ -285,8 +279,7 @@ 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); @@ -300,8 +293,7 @@ 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); @@ -318,8 +310,7 @@ 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); @@ -339,8 +330,7 @@ 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); @@ -378,9 +368,7 @@ 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 @@ -455,9 +443,7 @@ 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 @@ -505,8 +491,7 @@ 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(); @@ -592,9 +577,7 @@ 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(); @@ -611,9 +594,7 @@ 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; @@ -622,7 +603,8 @@ 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); @@ -634,9 +616,7 @@ 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 befa4c86d7..da5227058d 100644 --- a/src/input_common/udp/client.cpp +++ b/src/input_common/udp/client.cpp @@ -59,8 +59,7 @@ 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); }); } @@ -212,27 +211,21 @@ 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(); } @@ -241,60 +234,53 @@ 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 b58e319b65..b8c6547554 100644 --- a/src/input_common/udp/client.h +++ b/src/input_common/udp/client.h @@ -40,7 +40,6 @@ struct DeviceStatus { u16 max_x{}; u16 max_y{}; }; - std::optional touch_calibration; }; @@ -73,7 +72,6 @@ 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 2b31846db4..3ba4d1fc8d 100644 --- a/src/input_common/udp/protocol.h +++ b/src/input_common/udp/protocol.h @@ -35,7 +35,6 @@ 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"); @@ -55,9 +54,7 @@ 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 @@ -65,14 +62,12 @@ 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 @@ -85,7 +80,6 @@ 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 @@ -93,10 +87,9 @@ 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. @@ -121,10 +114,9 @@ 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{}; @@ -135,10 +127,9 @@ 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 { @@ -215,16 +206,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 "); /** @@ -241,27 +232,22 @@ 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 343c3985ef..8c6ef13949 100644 --- a/src/input_common/udp/udp.cpp +++ b/src/input_common/udp/udp.cpp @@ -16,10 +16,7 @@ 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; @@ -31,10 +28,7 @@ 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; @@ -46,9 +40,7 @@ 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 { { @@ -69,9 +61,7 @@ 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); From c94583d867fd909d8731ba50e085352aae0e6885 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 15:31:57 -0400 Subject: [PATCH 04/27] Clang Formatting --- src/core/hle/service/hid/controllers/npad.cpp | 42 ++---- src/input_common/gcadapter/gc_adapter.cpp | 90 ++++++----- src/input_common/gcadapter/gc_adapter.h | 16 +- src/input_common/gcadapter/gc_poller.cpp | 56 +++---- src/input_common/gcadapter/gc_poller.h | 5 +- src/input_common/main.h | 3 +- src/input_common/udp/client.cpp | 6 +- .../configuration/configure_input_player.cpp | 140 ++++++++---------- .../configuration/configure_input_player.h | 8 +- 9 files changed, 184 insertions(+), 182 deletions(-) diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp index d92325cb55..c55d900e27 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,10 +93,7 @@ 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) { @@ -109,7 +106,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); @@ -197,8 +194,7 @@ 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}; }); @@ -242,8 +238,7 @@ 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); @@ -281,31 +276,27 @@ 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()); @@ -372,7 +363,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; @@ -468,9 +459,8 @@ 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/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index d42261d619..dc04116ce7 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -1,7 +1,7 @@ // 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" @@ -45,35 +45,48 @@ GCPadStatus CheckStatus(int port, u8 adapter_payload[37]) { u8 b1 = adapter_payload[1 + (9 * port) + 1]; u8 b2 = adapter_payload[1 + (9 * port) + 2]; - if (b1 & (1 << 0)) + if (b1 & (1 << 0)) { pad.button |= PAD_BUTTON_A; - if (b1 & (1 << 1)) + } + if (b1 & (1 << 1)) { pad.button |= PAD_BUTTON_B; - if (b1 & (1 << 2)) + } + if (b1 & (1 << 2)) { pad.button |= PAD_BUTTON_X; - if (b1 & (1 << 3)) + } + if (b1 & (1 << 3)) { pad.button |= PAD_BUTTON_Y; + } - if (b1 & (1 << 4)) + if (b1 & (1 << 4)) { pad.button |= PAD_BUTTON_LEFT; - if (b1 & (1 << 5)) + } + if (b1 & (1 << 5)) { pad.button |= PAD_BUTTON_RIGHT; - if (b1 & (1 << 6)) + } + if (b1 & (1 << 6)) { pad.button |= PAD_BUTTON_DOWN; - if (b1 & (1 << 7)) + } + if (b1 & (1 << 7)) { pad.button |= PAD_BUTTON_UP; + } - if (b2 & (1 << 0)) + if (b2 & (1 << 0)) { pad.button |= PAD_BUTTON_START; - if (b2 & (1 << 1)) + } + if (b2 & (1 << 1)) { pad.button |= PAD_TRIGGER_Z; - if (b2 & (1 << 2)) + } + if (b2 & (1 << 2)) { pad.button |= PAD_TRIGGER_R; - if (b2 & (1 << 3)) + } + if (b2 & (1 << 3)) { pad.button |= PAD_TRIGGER_L; + } - if (get_origin) + if (get_origin) { pad.button |= PAD_GET_ORIGIN; + } pad.stickX = adapter_payload[1 + (9 * port) + 3]; pad.stickY = adapter_payload[1 + (9 * port) + 4]; @@ -86,7 +99,7 @@ GCPadStatus CheckStatus(int port, u8 adapter_payload[37]) { } void PadToState(GCPadStatus pad, GCState& state) { - //std::lock_guard lock{s_mutex}; + // 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); @@ -125,7 +138,7 @@ static void Read() { 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) { @@ -137,8 +150,9 @@ static void Read() { } for (int port = 0; port < 4; port++) { if (DeviceConnected(port) && configuring) { - if (pad[port].button != PAD_GET_ORIGIN) + 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 || @@ -186,8 +200,9 @@ static void ScanThreadFunc() { void Init() { - if (usb_adapter_handle != nullptr) + if (usb_adapter_handle != nullptr) { return; + } LOG_INFO(Input, "GC Adapter Initialization started"); current_status = NO_ADAPTER_DETECTED; @@ -197,10 +212,12 @@ void Init() { } void StartScanThread() { - if (detect_thread_running) + if (detect_thread_running) { return; - if (!libusb_ctx) + } + if (!libusb_ctx) { return; + } detect_thread_running = true; detect_thread = std::thread(ScanThreadFunc); @@ -212,15 +229,17 @@ void StopScanThread() { static void Setup() { // Reset the error status in case the adapter gets unplugged - if (current_status < 0) + if (current_status < 0) { current_status = NO_ADAPTER_DETECTED; + } - for (int i = 0; i < 4; i++) + 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 + 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])) { @@ -247,9 +266,8 @@ static bool CheckDeviceAccess(libusb_device* device) { 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); + LOG_ERROR(Input, "Yuzu can not gain access to this device: ID %04X:%04X.", desc.idVendor, + desc.idProduct); return false; } if (ret) { @@ -260,8 +278,9 @@ static bool CheckDeviceAccess(libusb_device* device) { 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) + 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) { @@ -290,8 +309,9 @@ static void GetGCEndpoint(libusb_device* device) { 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) + if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) { input_endpoint = endpoint->bEndpointAddress; + } } } } @@ -311,16 +331,20 @@ void Shutdown() { static void Reset() { std::unique_lock lock(initialization_mutex, std::defer_lock); - if (!lock.try_lock()) + if (!lock.try_lock()) { return; - if (current_status != ADAPTER_DETECTED) + } + if (current_status != ADAPTER_DETECTED) { return; + } - if (adapter_thread_running) + if (adapter_thread_running) { adapter_input_thread.join(); + } - for (int i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { adapter_controllers_status[i] = ControllerTypes::CONTROLLER_NONE; + } current_status = NO_ADAPTER_DETECTED; diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 9b02d1382f..05ee73c651 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -1,11 +1,14 @@ +// Copyright 2014 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + #pragma once #include -#include -#include #include +#include +#include #include "common/common_types.h" - enum { PAD_USE_ORIGIN = 0x0080, PAD_GET_ORIGIN = 0x2000, @@ -61,13 +64,8 @@ struct GCState { std::unordered_map axes; }; - namespace GCAdapter { -enum ControllerTypes { - CONTROLLER_NONE = 0, - CONTROLLER_WIRED = 1, - CONTROLLER_WIRELESS = 2 -}; +enum ControllerTypes { CONTROLLER_NONE = 0, CONTROLLER_WIRED = 1, CONTROLLER_WIRELESS = 2 }; enum { NO_ADAPTER_DETECTED = 0, diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index 772bd88904..51b3362d64 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -1,10 +1,14 @@ +// Copyright 2020 yuzu Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + #include #include #include #include -#include "input_common/gcadapter/gc_poller.h" -#include "input_common/gcadapter/gc_adapter.h" #include "common/threadsafe_queue.h" +#include "input_common/gcadapter/gc_adapter.h" +#include "input_common/gcadapter/gc_poller.h" // Using extern as to avoid multply defined symbols. extern Common::SPSCQueue pad_queue[4]; @@ -14,9 +18,7 @@ namespace InputCommon { class GCButton final : public Input::ButtonDevice { public: - explicit GCButton(int port_, int button_, int axis_) - : port(port_), button(button_) { - } + explicit GCButton(int port_, int button_, int axis_) : port(port_), button(button_) {} ~GCButton() override; @@ -31,17 +33,14 @@ private: 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_) { + 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; // TODO(ameerj) : Fix threshold. } return axis_value < -0.10f; } @@ -164,29 +163,30 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { void GCButtonFactory::BeginConfiguration() { polling = true; - for (int i = 0; i < 4; i++) + 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++) + 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_) { - } + : 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] + // 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; } @@ -240,18 +240,16 @@ private: mutable std::mutex mutex; }; - /// An analog device factory that creates analog devices from GC Adapter -GCAnalogFactory::GCAnalogFactory() {}; - +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 -*/ + * 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); @@ -264,15 +262,17 @@ std::unique_ptr GCAnalogFactory::Create(const Common::Param void GCAnalogFactory::BeginConfiguration() { polling = true; - for (int i = 0; i < 4; i++) + 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++) + for (int i = 0; i < 4; i++) { pad_queue[i].Clear(); + } GCAdapter::EndConfiguration(); } diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h index d115b1d2a2..43aa9e93a3 100644 --- a/src/input_common/gcadapter/gc_poller.h +++ b/src/input_common/gcadapter/gc_poller.h @@ -1,3 +1,7 @@ +// Copyright 2020 yuzu Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + #pragma once #include @@ -5,7 +9,6 @@ namespace InputCommon { - /** * A button device factory representing a gcpad. It receives gcpad events and forward them * to all button devices it created. diff --git a/src/input_common/main.h b/src/input_common/main.h index be2e7a6c4b..9e1528c88e 100644 --- a/src/input_common/main.h +++ b/src/input_common/main.h @@ -7,8 +7,8 @@ #include #include #include -#include "input_common/gcadapter/gc_poller.h" #include "input_common/gcadapter/gc_adapter.h" +#include "input_common/gcadapter/gc_poller.h" namespace Common { class ParamPackage; @@ -38,7 +38,6 @@ 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/udp/client.cpp b/src/input_common/udp/client.cpp index da5227058d..4c9794ce2c 100644 --- a/src/input_common/udp/client.cpp +++ b/src/input_common/udp/client.cpp @@ -225,8 +225,7 @@ void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 clie } else { failure_callback(); } - }) - .detach(); + }).detach(); } CalibrationConfigurationJob::CalibrationConfigurationJob( @@ -280,8 +279,7 @@ CalibrationConfigurationJob::CalibrationConfigurationJob( complete_event.Wait(); socket.Stop(); worker_thread.join(); - }) - .detach(); + }).detach(); } CalibrationConfigurationJob::~CalibrationConfigurationJob() { diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp index 81436af1b2..c1a0c423bc 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); @@ -151,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 = {{ @@ -178,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, }; @@ -221,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; } @@ -261,38 +261,34 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i } button->setContextMenuPolicy(Qt::CustomContextMenu); - connect(button, &QPushButton::clicked, [=] - { - HandleClick(button_map[button_id], - [=](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 - // analog triggers instead of -32768 to 32768 on analog joysticks). The - // SDL driver misinterprets analog triggers as analog joysticks. - // TODO: reinterpret the signal range for analog triggers to map the - // values correctly. This is required for the correct emulation of the - // analog triggers of the GameCube controller. - if (button_id == Settings::NativeButton::ZL || - button_id == Settings::NativeButton::ZR) { - params.Set("direction", "+"); - params.Set("threshold", "0.5"); - } - buttons_param[button_id] = std::move(params); - }, - InputCommon::Polling::DeviceType::Button); + connect(button, &QPushButton::clicked, [=] { + HandleClick( + button_map[button_id], + [=](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 + // analog triggers instead of -32768 to 32768 on analog joysticks). The + // SDL driver misinterprets analog triggers as analog joysticks. + // TODO: reinterpret the signal range for analog triggers to map the + // values correctly. This is required for the correct emulation of the + // analog triggers of the GameCube controller. + if (button_id == Settings::NativeButton::ZL || + button_id == Settings::NativeButton::ZR) { + params.Set("direction", "+"); + params.Set("threshold", "0.5"); + } + buttons_param[button_id] = std::move(params); + }, + 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])); @@ -309,27 +305,23 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i } analog_button->setContextMenuPolicy(Qt::CustomContextMenu); - connect(analog_button, &QPushButton::clicked, [=]() - { - HandleClick(analog_map_buttons[analog_id][sub_button_id], - [=](const Common::ParamPackage& params) - { - SetAnalogButton(params, analogs_param[analog_id], - analog_sub_buttons[sub_button_id]); - }, - InputCommon::Polling::DeviceType::Button); + connect(analog_button, &QPushButton::clicked, [=]() { + HandleClick( + analog_map_buttons[analog_id][sub_button_id], + [=](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], @@ -341,12 +333,11 @@ 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], @@ -355,8 +346,7 @@ 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" || analogs_param[analog_id].Get("engine", "") == "gcpad") { @@ -377,8 +367,7 @@ 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(); @@ -505,7 +494,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())); } } @@ -625,10 +614,11 @@ void ConfigureInputPlayer::HandleClick( grabKeyboard(); grabMouse(); - if (type == InputCommon::Polling::DeviceType::Button) + if (type == InputCommon::Polling::DeviceType::Button) { InputCommon::GetGCButtons()->BeginConfiguration(); - else + } else { InputCommon::GetGCAnalogs()->BeginConfiguration(); + } timeout_timer->start(5000); // Cancel after 5 seconds poll_timer->start(200); // Check for new inputs every 200ms } diff --git a/src/yuzu/configuration/configure_input_player.h b/src/yuzu/configuration/configure_input_player.h index dad2a80ecd..95afa53752 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; From 121af3646dad0f80453d2ffffa688dd4435d3acc Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 18:43:01 -0400 Subject: [PATCH 05/27] Singleton GC Adapter class, remove globals, fix naming convention Fix clang formatting Manual fix for configure_input_player formatting Add missing lib usb cmake command --- CMakeLists.txt | 6 + src/input_common/gcadapter/gc_adapter.cpp | 176 +++++++++--------- src/input_common/gcadapter/gc_adapter.h | 143 +++++++++----- src/input_common/gcadapter/gc_poller.cpp | 125 +++++++------ src/input_common/gcadapter/gc_poller.h | 3 + src/input_common/main.cpp | 2 + src/input_common/main.h | 4 +- src/input_common/udp/client.cpp | 6 +- .../configuration/configure_input_player.cpp | 50 +++-- 9 files changed, 288 insertions(+), 227 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b710712711..967968226b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -328,6 +328,12 @@ elseif(SDL2_FOUND) target_link_libraries(SDL2 INTERFACE "${SDL2_LIBRARIES}") endif() +# Ensure libusb is properly configured (based on dolphin libusb include) +find_package(LibUSB) +add_subdirectory(externals/libusb) +set(LIBUSB_LIBRARIES usb) + + # Prefer the -pthread flag on Linux. set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index dc04116ce7..0696a96c7b 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -3,45 +3,41 @@ // 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 { +Adapter* Adapter::adapter_instance{nullptr}; -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}; +Adapter::Adapter() { + if (usb_adapter_handle != nullptr) { + return; + } + LOG_INFO(Input, "GC Adapter Initialization started"); -static std::mutex s_mutex; + current_status = NO_ADAPTER_DETECTED; + libusb_init(&libusb_ctx); -static std::thread adapter_input_thread; -static bool adapter_thread_running; + StartScanThread(); +} -static std::mutex initialization_mutex; -static std::thread detect_thread; -static bool detect_thread_running = false; +Adapter* Adapter::GetInstance() { + if (!adapter_instance) { + adapter_instance = new Adapter; + } + return adapter_instance; +} -static libusb_context* libusb_ctx; - -static u8 input_endpoint = 0; - -static bool configuring = false; - -GCPadStatus CheckStatus(int port, u8 adapter_payload[37]) { +GCPadStatus Adapter::CheckStatus(int port, u8 adapter_payload[37]) { GCPadStatus pad = {}; bool get_origin = false; - u8 type = adapter_payload[1 + (9 * port)] >> 4; - if (type) + ControllerTypes type = ControllerTypes(adapter_payload[1 + (9 * port)] >> 4); + if (type != ControllerTypes::None) get_origin = true; adapter_controllers_status[port] = type; - if (adapter_controllers_status[port] != ControllerTypes::CONTROLLER_NONE) { + if (adapter_controllers_status[port] != ControllerTypes::None) { u8 b1 = adapter_payload[1 + (9 * port) + 1]; u8 b2 = adapter_payload[1 + (9 * port) + 2]; @@ -88,18 +84,17 @@ GCPadStatus CheckStatus(int port, u8 adapter_payload[37]) { 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]; + pad.stick_x = adapter_payload[1 + (9 * port) + 3]; + pad.stick_y = adapter_payload[1 + (9 * port) + 4]; + pad.substick_x = adapter_payload[1 + (9 * port) + 5]; + pad.substick_y = adapter_payload[1 + (9 * port) + 6]; + pad.trigger_left = adapter_payload[1 + (9 * port) + 7]; + pad.trigger_right = adapter_payload[1 + (9 * port) + 8]; } return pad; } -void PadToState(GCPadStatus pad, GCState& state) { - // std::lock_guard lock{s_mutex}; +void Adapter::PadToState(GCPadStatus pad, GCState& state) { 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); @@ -112,15 +107,15 @@ void PadToState(GCPadStatus pad, GCState& state) { 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); + state.axes.insert_or_assign(static_cast(PadAxes::StickX), pad.stick_x); + state.axes.insert_or_assign(static_cast(PadAxes::StickY), pad.stick_y); + state.axes.insert_or_assign(static_cast(PadAxes::SubstickX), pad.substick_x); + state.axes.insert_or_assign(static_cast(PadAxes::SubstickY), pad.substick_y); + state.axes.insert_or_assign(static_cast(PadAxes::TriggerLeft), pad.trigger_left); + state.axes.insert_or_assign(static_cast(PadAxes::TriggerRight), pad.trigger_right); } -static void Read() { +void Adapter::Read() { LOG_INFO(Input, "GC Adapter Read() thread started"); int payload_size_in; @@ -145,8 +140,9 @@ static void Read() { 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++) { + pad[port] = CheckStatus(port, controller_payload_copy); + } } for (int port = 0; port < 4; port++) { if (DeviceConnected(port) && configuring) { @@ -155,28 +151,36 @@ static void Read() { } // 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; + if (pad[port].stick_x > + pad_constants.MAIN_STICK_CENTER_X + pad_constants.THRESHOLD || + pad[port].stick_x < + pad_constants.MAIN_STICK_CENTER_X - pad_constants.THRESHOLD) { + pad[port].axis = GCAdapter::PadAxes::StickX; + pad[port].axis_value = pad[port].stick_x; 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; + if (pad[port].stick_y > + pad_constants.MAIN_STICK_CENTER_Y + pad_constants.THRESHOLD || + pad[port].stick_y < + pad_constants.MAIN_STICK_CENTER_Y - pad_constants.THRESHOLD) { + pad[port].axis = GCAdapter::PadAxes::StickY; + pad[port].axis_value = pad[port].stick_y; 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; + if (pad[port].substick_x > + pad_constants.C_STICK_CENTER_X + pad_constants.THRESHOLD || + pad[port].substick_x < + pad_constants.C_STICK_CENTER_X - pad_constants.THRESHOLD) { + pad[port].axis = GCAdapter::PadAxes::SubstickX; + pad[port].axis_value = pad[port].substick_x; 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; + if (pad[port].substick_y > + pad_constants.C_STICK_CENTER_Y + pad_constants.THRESHOLD || + pad[port].substick_y < + pad_constants.C_STICK_CENTER_Y - pad_constants.THRESHOLD) { + pad[port].axis = GCAdapter::PadAxes::SubstickY; + pad[port].axis_value = pad[port].substick_y; pad_queue[port].Push(pad[port]); } } @@ -186,7 +190,7 @@ static void Read() { } } -static void ScanThreadFunc() { +void Adapter::ScanThreadFunc() { LOG_INFO(Input, "GC Adapter scanning thread started"); while (detect_thread_running) { @@ -198,20 +202,7 @@ static void ScanThreadFunc() { } } -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() { +void Adapter::StartScanThread() { if (detect_thread_running) { return; } @@ -220,21 +211,21 @@ void StartScanThread() { } detect_thread_running = true; - detect_thread = std::thread(ScanThreadFunc); + detect_thread = std::thread([=] { ScanThreadFunc(); }); } -void StopScanThread() { +void Adapter::StopScanThread() { detect_thread.join(); } -static void Setup() { +void Adapter::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; + adapter_controllers_status[i] = ControllerTypes::None; } libusb_device** devs; // pointer to list of connected usb devices @@ -250,7 +241,7 @@ static void Setup() { } } -static bool CheckDeviceAccess(libusb_device* device) { +bool Adapter::CheckDeviceAccess(libusb_device* device) { libusb_device_descriptor desc; int ret = libusb_get_device_descriptor(device, &desc); if (ret) { @@ -300,7 +291,7 @@ static bool CheckDeviceAccess(libusb_device* device) { return true; } -static void GetGCEndpoint(libusb_device* device) { +void Adapter::GetGCEndpoint(libusb_device* device) { libusb_config_descriptor* config = nullptr; libusb_get_config_descriptor(device, 0, &config); for (u8 ic = 0; ic < config->bNumInterfaces; ic++) { @@ -318,18 +309,17 @@ static void GetGCEndpoint(libusb_device* device) { adapter_thread_running = true; current_status = ADAPTER_DETECTED; - - adapter_input_thread = std::thread(Read); // Read input + adapter_input_thread = std::thread([=] { Read(); }); // Read input } -void Shutdown() { +Adapter::~Adapter() { StopScanThread(); Reset(); current_status = NO_ADAPTER_DETECTED; } -static void Reset() { +void Adapter::Reset() { std::unique_lock lock(initialization_mutex, std::defer_lock); if (!lock.try_lock()) { return; @@ -343,7 +333,7 @@ static void Reset() { } for (int i = 0; i < 4; i++) { - adapter_controllers_status[i] = ControllerTypes::CONTROLLER_NONE; + adapter_controllers_status[i] = ControllerTypes::None; } current_status = NO_ADAPTER_DETECTED; @@ -355,20 +345,28 @@ static void Reset() { } } -bool DeviceConnected(int port) { - return adapter_controllers_status[port] != ControllerTypes::CONTROLLER_NONE; +bool Adapter::DeviceConnected(int port) { + return adapter_controllers_status[port] != ControllerTypes::None; } -void ResetDeviceType(int port) { - adapter_controllers_status[port] = ControllerTypes::CONTROLLER_NONE; +void Adapter::ResetDeviceType(int port) { + adapter_controllers_status[port] = ControllerTypes::None; } -void BeginConfiguration() { +void Adapter::BeginConfiguration() { configuring = true; } -void EndConfiguration() { +void Adapter::EndConfiguration() { configuring = false; } +std::array, 4>& Adapter::GetPadQueue() { + return pad_queue; +} + +std::array& Adapter::GetPadState() { + return state; +} + } // end of namespace GCAdapter diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 05ee73c651..3d5c41f9ab 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -8,6 +8,9 @@ #include #include #include "common/common_types.h" +#include "common/threadsafe_queue.h" + +namespace GCAdapter { enum { PAD_USE_ORIGIN = 0x0080, @@ -33,29 +36,38 @@ enum PadButton { }; -enum PadAxes { STICK_X, STICK_Y, SUBSTICK_X, SUBSTICK_Y, TRIGGER_LEFT, TRIGGER_RIGHT }; +enum class PadAxes : u8 { + StickX, + StickY, + SubstickX, + SubstickY, + TriggerLeft, + TriggerRight, + Undefined, +}; +const struct GCPadConstants { + const u8 MAIN_STICK_CENTER_X = 0x80; + const u8 MAIN_STICK_CENTER_Y = 0x80; + const u8 MAIN_STICK_RADIUS = 0x7f; + const u8 C_STICK_CENTER_X = 0x80; + const u8 C_STICK_CENTER_Y = 0x80; + const u8 C_STICK_RADIUS = 0x7f; + + const u8 TRIGGER_CENTER = 20; + const u8 THRESHOLD = 10; +} pad_constants; 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}; + u16 button; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits + u8 stick_x; // 0 <= stick_x <= 255 + u8 stick_y; // 0 <= stick_y <= 255 + u8 substick_x; // 0 <= substick_x <= 255 + u8 substick_y; // 0 <= substick_y <= 255 + u8 trigger_left; // 0 <= trigger_left <= 255 + u8 trigger_right; // 0 <= trigger_right <= 255 - 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; + PadAxes axis = PadAxes::Undefined; u8 axis_value = 255; }; @@ -64,51 +76,88 @@ struct GCState { std::unordered_map axes; }; -namespace GCAdapter { -enum ControllerTypes { CONTROLLER_NONE = 0, CONTROLLER_WIRED = 1, CONTROLLER_WIRELESS = 2 }; +enum class ControllerTypes { None, Wired, Wireless }; 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; +/// Singleton Adapter class +class Adapter { +public: + /// For retreiving the singleton instance + static Adapter* GetInstance(); -GCPadStatus CheckStatus(int port, u8 adapter_payload[37]); -/// Initialize the GC Adapter capture and read sequence -void Init(); + /// Used for polling + void BeginConfiguration(); + void EndConfiguration(); -/// Close the adapter read thread and release the adapter -void Shutdown(); + std::array, 4>& GetPadQueue(); + std::array& GetPadState(); -/// Begin scanning for the GC Adapter. -void StartScanThread(); +private: + /// Singleton instance. + static Adapter* adapter_instance; -/// Stop scanning for the adapter -void StopScanThread(); + /// Initialize the GC Adapter capture and read sequence + Adapter(); -/// Returns true if there is a device connected to port -bool DeviceConnected(int port); + /// Close the adapter read thread and release the adapter + ~Adapter(); -/// Resets status of device connected to port -void ResetDeviceType(int port); + GCPadStatus CheckStatus(int port, u8 adapter_payload[37]); -/// Returns true if we successfully gain access to GC Adapter -bool CheckDeviceAccess(libusb_device* device); + void PadToState(GCPadStatus pad, GCState& state); -/// Captures GC Adapter endpoint address, -void GetGCEndpoint(libusb_device* device); + void Read(); + void ScanThreadFunc(); + /// Begin scanning for the GC Adapter. + void StartScanThread(); -/// For shutting down, clear all data, join all threads, release usb -void Reset(); + /// Stop scanning for the adapter + void StopScanThread(); -/// For use in initialization, querying devices to find the adapter -void Setup(); + /// Returns true if there is a device connected to port + bool DeviceConnected(int port); -/// Used for polling -void BeginConfiguration(); + /// Resets status of device connected to port + void ResetDeviceType(int port); -void EndConfiguration(); + /// 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(); + + int current_status = NO_ADAPTER_DETECTED; + libusb_device_handle* usb_adapter_handle = nullptr; + ControllerTypes adapter_controllers_status[4] = {ControllerTypes::None, ControllerTypes::None, + ControllerTypes::None, ControllerTypes::None}; + + std::mutex s_mutex; + + std::thread adapter_input_thread; + bool adapter_thread_running; + + std::mutex initialization_mutex; + std::thread detect_thread; + bool detect_thread_running = false; + + libusb_context* libusb_ctx; + + u8 input_endpoint = 0; + + bool configuring = false; + + std::array, 4> pad_queue; + std::array state; +}; } // end of namespace GCAdapter diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index 51b3362d64..0e591baca2 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -10,35 +10,34 @@ #include "input_common/gcadapter/gc_adapter.h" #include "input_common/gcadapter/gc_poller.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_) {} + explicit GCButton(int port_, int button_, int axis_, GCAdapter::Adapter* adapter) + : port(port_), button(button_), gcadapter(adapter) {} ~GCButton() override; bool GetStatus() const override { - return state[port].buttons.at(button); + return gcadapter->GetPadState()[port].buttons.at(button); } private: const int port; const int button; + GCAdapter::Adapter* gcadapter; }; 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_) { - } + explicit GCAxisButton(int port_, int axis_, float threshold_, bool trigger_if_greater_, + GCAdapter::Adapter* adapter) + : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_), + gcadapter(adapter) {} bool GetStatus() const override { - const float axis_value = (state[port].axes.at(axis) - 128.0f) / 128.0f; + const float axis_value = (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 128.0f; if (trigger_if_greater) { return axis_value > 0.10f; // TODO(ameerj) : Fix threshold. } @@ -50,14 +49,15 @@ private: const int axis; float threshold; bool trigger_if_greater; + GCAdapter::Adapter* gcadapter; }; GCButtonFactory::GCButtonFactory() { - GCAdapter::Init(); + adapter = GCAdapter::Adapter::GetInstance(); } GCButton::~GCButton() { - GCAdapter::Shutdown(); + // GCAdapter::Shutdown(); } std::unique_ptr GCButtonFactory::Create(const Common::ParamPackage& params) { @@ -77,76 +77,76 @@ std::unique_ptr GCButtonFactory::Create(const Common::Param trigger_if_greater = true; LOG_ERROR(Input, "Unknown direction {}", direction_name); } - return std::make_unique(port, axis, threshold, trigger_if_greater); + return std::make_unique(port, axis, threshold, trigger_if_greater, adapter); } std::unique_ptr button = - std::make_unique(port, button_id, params.Get("axis", 0)); + std::make_unique(port, button_id, params.Get("axis", 0), adapter); return std::move(button); } Common::ParamPackage GCButtonFactory::GetNextInput() { Common::ParamPackage params; - GCPadStatus pad; + GCAdapter::GCPadStatus pad; for (int i = 0; i < 4; i++) { - while (pad_queue[i].Pop(pad)) { + while (adapter->GetPadQueue()[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); + if (pad.button & GCAdapter::PAD_BUTTON_A) { + params.Set("button", GCAdapter::PAD_BUTTON_A); break; } - if (pad.button & PAD_BUTTON_B) { - params.Set("button", PAD_BUTTON_B); + if (pad.button & GCAdapter::PAD_BUTTON_B) { + params.Set("button", GCAdapter::PAD_BUTTON_B); break; } - if (pad.button & PAD_BUTTON_X) { - params.Set("button", PAD_BUTTON_X); + if (pad.button & GCAdapter::PAD_BUTTON_X) { + params.Set("button", GCAdapter::PAD_BUTTON_X); break; } - if (pad.button & PAD_BUTTON_Y) { - params.Set("button", PAD_BUTTON_Y); + if (pad.button & GCAdapter::PAD_BUTTON_Y) { + params.Set("button", GCAdapter::PAD_BUTTON_Y); break; } - if (pad.button & PAD_BUTTON_DOWN) { - params.Set("button", PAD_BUTTON_DOWN); + if (pad.button & GCAdapter::PAD_BUTTON_DOWN) { + params.Set("button", GCAdapter::PAD_BUTTON_DOWN); break; } - if (pad.button & PAD_BUTTON_LEFT) { - params.Set("button", PAD_BUTTON_LEFT); + if (pad.button & GCAdapter::PAD_BUTTON_LEFT) { + params.Set("button", GCAdapter::PAD_BUTTON_LEFT); break; } - if (pad.button & PAD_BUTTON_RIGHT) { - params.Set("button", PAD_BUTTON_RIGHT); + if (pad.button & GCAdapter::PAD_BUTTON_RIGHT) { + params.Set("button", GCAdapter::PAD_BUTTON_RIGHT); break; } - if (pad.button & PAD_BUTTON_UP) { - params.Set("button", PAD_BUTTON_UP); + if (pad.button & GCAdapter::PAD_BUTTON_UP) { + params.Set("button", GCAdapter::PAD_BUTTON_UP); break; } - if (pad.button & PAD_TRIGGER_L) { - params.Set("button", PAD_TRIGGER_L); + if (pad.button & GCAdapter::PAD_TRIGGER_L) { + params.Set("button", GCAdapter::PAD_TRIGGER_L); break; } - if (pad.button & PAD_TRIGGER_R) { - params.Set("button", PAD_TRIGGER_R); + if (pad.button & GCAdapter::PAD_TRIGGER_R) { + params.Set("button", GCAdapter::PAD_TRIGGER_R); break; } - if (pad.button & PAD_TRIGGER_Z) { - params.Set("button", PAD_TRIGGER_Z); + if (pad.button & GCAdapter::PAD_TRIGGER_Z) { + params.Set("button", GCAdapter::PAD_TRIGGER_Z); break; } - if (pad.button & PAD_BUTTON_START) { - params.Set("button", PAD_BUTTON_START); + if (pad.button & GCAdapter::PAD_BUTTON_START) { + params.Set("button", GCAdapter::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 != GCAdapter::PadAxes::Undefined) { + params.Set("axis", static_cast(pad.axis)); + params.Set("button", GCAdapter::PAD_STICK); if (pad.axis_value > 128) { params.Set("direction", "+"); params.Set("threshold", "0.5"); @@ -164,30 +164,30 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { void GCButtonFactory::BeginConfiguration() { polling = true; for (int i = 0; i < 4; i++) { - pad_queue[i].Clear(); + adapter->GetPadQueue()[i].Clear(); } - GCAdapter::BeginConfiguration(); + adapter->BeginConfiguration(); } void GCButtonFactory::EndConfiguration() { polling = false; for (int i = 0; i < 4; i++) { - pad_queue[i].Clear(); + adapter->GetPadQueue()[i].Clear(); } - GCAdapter::EndConfiguration(); + adapter->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_) {} + GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, GCAdapter::Adapter* adapter) + : port(port_), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_), gcadapter(adapter) {} 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; + return (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 95.0f; } std::tuple GetAnalog(int axis_x, int axis_y) const { @@ -238,10 +238,13 @@ private: const int axis_y; const float deadzone; mutable std::mutex mutex; + GCAdapter::Adapter* gcadapter; }; /// An analog device factory that creates analog devices from GC Adapter -GCAnalogFactory::GCAnalogFactory(){}; +GCAnalogFactory::GCAnalogFactory() { + adapter = GCAdapter::Adapter::GetInstance(); +}; /** * Creates analog device from joystick axes @@ -257,35 +260,36 @@ std::unique_ptr GCAnalogFactory::Create(const Common::Param 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); + return std::make_unique(port, axis_x, axis_y, deadzone, adapter); } void GCAnalogFactory::BeginConfiguration() { polling = true; for (int i = 0; i < 4; i++) { - pad_queue[i].Clear(); + adapter->GetPadQueue()[i].Clear(); } - GCAdapter::BeginConfiguration(); + adapter->BeginConfiguration(); } void GCAnalogFactory::EndConfiguration() { polling = false; for (int i = 0; i < 4; i++) { - pad_queue[i].Clear(); + adapter->GetPadQueue()[i].Clear(); } - GCAdapter::EndConfiguration(); + adapter->EndConfiguration(); } Common::ParamPackage GCAnalogFactory::GetNextInput() { - GCPadStatus pad; + GCAdapter::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) { + while (adapter->GetPadQueue()[i].Pop(pad)) { + if (pad.axis == GCAdapter::PadAxes::Undefined || + 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; + const u8 axis = static_cast(pad.axis); if (analog_x_axis == -1) { analog_x_axis = axis; controller_number = i; @@ -307,4 +311,5 @@ Common::ParamPackage GCAnalogFactory::GetNextInput() { } return params; } + } // namespace InputCommon diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h index 43aa9e93a3..29b8c0b7c2 100644 --- a/src/input_common/gcadapter/gc_poller.h +++ b/src/input_common/gcadapter/gc_poller.h @@ -35,6 +35,7 @@ public: } private: + GCAdapter::Adapter* adapter; bool polling = false; }; @@ -54,9 +55,11 @@ public: } private: + GCAdapter::Adapter* adapter; 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/main.cpp b/src/input_common/main.cpp index 7fc0e2db4c..536e5c80a5 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -2,11 +2,13 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include #include #include #include #include "common/param_package.h" #include "input_common/analog_from_button.h" +#include "input_common/gcadapter/gc_adapter.h" #include "input_common/gcadapter/gc_poller.h" #include "input_common/keyboard.h" #include "input_common/main.h" diff --git a/src/input_common/main.h b/src/input_common/main.h index 9e1528c88e..c26222f214 100644 --- a/src/input_common/main.h +++ b/src/input_common/main.h @@ -32,10 +32,8 @@ 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 diff --git a/src/input_common/udp/client.cpp b/src/input_common/udp/client.cpp index 4c9794ce2c..da5227058d 100644 --- a/src/input_common/udp/client.cpp +++ b/src/input_common/udp/client.cpp @@ -225,7 +225,8 @@ void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 clie } else { failure_callback(); } - }).detach(); + }) + .detach(); } CalibrationConfigurationJob::CalibrationConfigurationJob( @@ -279,7 +280,8 @@ CalibrationConfigurationJob::CalibrationConfigurationJob( complete_event.Wait(); socket.Stop(); worker_thread.join(); - }).detach(); + }) + .detach(); } CalibrationConfigurationJob::~CalibrationConfigurationJob() { diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp index c1a0c423bc..c7d3f45105 100644 --- a/src/yuzu/configuration/configure_input_player.cpp +++ b/src/yuzu/configuration/configure_input_player.cpp @@ -262,25 +262,24 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i button->setContextMenuPolicy(Qt::CustomContextMenu); connect(button, &QPushButton::clicked, [=] { - HandleClick( - button_map[button_id], - [=](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 - // analog triggers instead of -32768 to 32768 on analog joysticks). The - // SDL driver misinterprets analog triggers as analog joysticks. - // TODO: reinterpret the signal range for analog triggers to map the - // values correctly. This is required for the correct emulation of the - // analog triggers of the GameCube controller. - if (button_id == Settings::NativeButton::ZL || - button_id == Settings::NativeButton::ZR) { - params.Set("direction", "+"); - params.Set("threshold", "0.5"); - } - buttons_param[button_id] = std::move(params); - }, - InputCommon::Polling::DeviceType::Button); + HandleClick(button_map[button_id], + [=](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 + // analog triggers instead of -32768 to 32768 on analog joysticks). The + // SDL driver misinterprets analog triggers as analog joysticks. + // TODO: reinterpret the signal range for analog triggers to map the + // values correctly. This is required for the correct emulation of the + // analog triggers of the GameCube controller. + if (button_id == Settings::NativeButton::ZL || + button_id == Settings::NativeButton::ZR) { + params.Set("direction", "+"); + params.Set("threshold", "0.5"); + } + buttons_param[button_id] = std::move(params); + }, + InputCommon::Polling::DeviceType::Button); }); connect(button, &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) { QMenu context_menu; @@ -306,13 +305,12 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i analog_button->setContextMenuPolicy(Qt::CustomContextMenu); connect(analog_button, &QPushButton::clicked, [=]() { - HandleClick( - analog_map_buttons[analog_id][sub_button_id], - [=](const Common::ParamPackage& params) { - SetAnalogButton(params, analogs_param[analog_id], - analog_sub_buttons[sub_button_id]); - }, - InputCommon::Polling::DeviceType::Button); + HandleClick(analog_map_buttons[analog_id][sub_button_id], + [=](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) { From 5f0fa4cb8283d61ad2993273fa48b2fd3868a680 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 20:32:43 -0400 Subject: [PATCH 06/27] fix include thread --- src/input_common/gcadapter/gc_adapter.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 3d5c41f9ab..a32ca04649 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include "common/common_types.h" #include "common/threadsafe_queue.h" From 968d631aa59a0a4e51e219eaa143d2b95593c3e7 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 21:15:58 -0400 Subject: [PATCH 07/27] std::arrays where appropriate, clear q in adapter class, other touch ups --- src/input_common/gcadapter/gc_adapter.cpp | 16 +++++++++------- src/input_common/gcadapter/gc_adapter.h | 5 +++-- src/input_common/gcadapter/gc_poller.cpp | 16 +--------------- src/input_common/gcadapter/gc_poller.h | 4 ++-- src/input_common/main.cpp | 1 - 5 files changed, 15 insertions(+), 27 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 0696a96c7b..498bd0d6e8 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -134,7 +134,7 @@ void Adapter::Read() { payload_size = payload_size_in; } - GCPadStatus pad[4]; + std::array pad; 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, @@ -224,9 +224,7 @@ void Adapter::Setup() { current_status = NO_ADAPTER_DETECTED; } - for (int i = 0; i < 4; i++) { - adapter_controllers_status[i] = ControllerTypes::None; - } + adapter_controllers_status.fill(ControllerTypes::None); libusb_device** devs; // pointer to list of connected usb devices @@ -332,9 +330,7 @@ void Adapter::Reset() { adapter_input_thread.join(); } - for (int i = 0; i < 4; i++) { - adapter_controllers_status[i] = ControllerTypes::None; - } + adapter_controllers_status.fill(ControllerTypes::None); current_status = NO_ADAPTER_DETECTED; @@ -354,10 +350,16 @@ void Adapter::ResetDeviceType(int port) { } void Adapter::BeginConfiguration() { + for (auto& pq : pad_queue) { + pq.Clear(); + } configuring = true; } void Adapter::EndConfiguration() { + for (auto& pq : pad_queue) { + pq.Clear(); + } configuring = false; } diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index a32ca04649..cb0dd0ab13 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -96,6 +96,8 @@ public: std::array, 4>& GetPadQueue(); std::array& GetPadState(); + std::array, 4>& GetPadQueue() const; + std::array& GetPadState() const; private: /// Singleton instance. @@ -139,8 +141,7 @@ private: int current_status = NO_ADAPTER_DETECTED; libusb_device_handle* usb_adapter_handle = nullptr; - ControllerTypes adapter_controllers_status[4] = {ControllerTypes::None, ControllerTypes::None, - ControllerTypes::None, ControllerTypes::None}; + std::array adapter_controllers_status{}; std::mutex s_mutex; diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index 0e591baca2..ac4126cb62 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -56,9 +56,7 @@ GCButtonFactory::GCButtonFactory() { adapter = GCAdapter::Adapter::GetInstance(); } -GCButton::~GCButton() { - // GCAdapter::Shutdown(); -} +GCButton::~GCButton() = default; std::unique_ptr GCButtonFactory::Create(const Common::ParamPackage& params) { int button_id = params.Get("button", 0); @@ -163,17 +161,11 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { void GCButtonFactory::BeginConfiguration() { polling = true; - for (int i = 0; i < 4; i++) { - adapter->GetPadQueue()[i].Clear(); - } adapter->BeginConfiguration(); } void GCButtonFactory::EndConfiguration() { polling = false; - for (int i = 0; i < 4; i++) { - adapter->GetPadQueue()[i].Clear(); - } adapter->EndConfiguration(); } @@ -265,17 +257,11 @@ std::unique_ptr GCAnalogFactory::Create(const Common::Param void GCAnalogFactory::BeginConfiguration() { polling = true; - for (int i = 0; i < 4; i++) { - adapter->GetPadQueue()[i].Clear(); - } adapter->BeginConfiguration(); } void GCAnalogFactory::EndConfiguration() { polling = false; - for (int i = 0; i < 4; i++) { - adapter->GetPadQueue()[i].Clear(); - } adapter->EndConfiguration(); } diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h index 29b8c0b7c2..31ff1c1237 100644 --- a/src/input_common/gcadapter/gc_poller.h +++ b/src/input_common/gcadapter/gc_poller.h @@ -30,7 +30,7 @@ public: void BeginConfiguration(); void EndConfiguration(); - bool IsPolling() { + bool IsPolling() const { return polling; } @@ -50,7 +50,7 @@ public: void BeginConfiguration(); void EndConfiguration(); - bool IsPolling() { + bool IsPolling() const { return polling; } diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index 536e5c80a5..89dddf7cf7 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -2,7 +2,6 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include #include #include #include From 46b4461fbb0514dd50c096ef896b1752d81079d0 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 21:50:58 -0400 Subject: [PATCH 08/27] shared_ptr for the GC adapter class, constexpr constants --- src/input_common/gcadapter/gc_adapter.cpp | 40 ++++++++------------ src/input_common/gcadapter/gc_adapter.h | 46 ++++++++++------------- src/input_common/gcadapter/gc_poller.cpp | 24 ++++++------ src/input_common/gcadapter/gc_poller.h | 8 ++-- src/input_common/main.cpp | 6 ++- 5 files changed, 55 insertions(+), 69 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 498bd0d6e8..db72d76334 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -6,7 +6,6 @@ #include "input_common/gcadapter/gc_adapter.h" namespace GCAdapter { -Adapter* Adapter::adapter_instance{nullptr}; Adapter::Adapter() { if (usb_adapter_handle != nullptr) { @@ -20,13 +19,6 @@ Adapter::Adapter() { StartScanThread(); } -Adapter* Adapter::GetInstance() { - if (!adapter_instance) { - adapter_instance = new Adapter; - } - return adapter_instance; -} - GCPadStatus Adapter::CheckStatus(int port, u8 adapter_payload[37]) { GCPadStatus pad = {}; bool get_origin = false; @@ -151,34 +143,26 @@ void Adapter::Read() { } // Accounting for a threshold here because of some controller variance - if (pad[port].stick_x > - pad_constants.MAIN_STICK_CENTER_X + pad_constants.THRESHOLD || - pad[port].stick_x < - pad_constants.MAIN_STICK_CENTER_X - pad_constants.THRESHOLD) { + if (pad[port].stick_x > pad[port].MAIN_STICK_CENTER_X + pad[port].THRESHOLD || + pad[port].stick_x < pad[port].MAIN_STICK_CENTER_X - pad[port].THRESHOLD) { pad[port].axis = GCAdapter::PadAxes::StickX; pad[port].axis_value = pad[port].stick_x; pad_queue[port].Push(pad[port]); } - if (pad[port].stick_y > - pad_constants.MAIN_STICK_CENTER_Y + pad_constants.THRESHOLD || - pad[port].stick_y < - pad_constants.MAIN_STICK_CENTER_Y - pad_constants.THRESHOLD) { + if (pad[port].stick_y > pad[port].MAIN_STICK_CENTER_Y + pad[port].THRESHOLD || + pad[port].stick_y < pad[port].MAIN_STICK_CENTER_Y - pad[port].THRESHOLD) { pad[port].axis = GCAdapter::PadAxes::StickY; pad[port].axis_value = pad[port].stick_y; pad_queue[port].Push(pad[port]); } - if (pad[port].substick_x > - pad_constants.C_STICK_CENTER_X + pad_constants.THRESHOLD || - pad[port].substick_x < - pad_constants.C_STICK_CENTER_X - pad_constants.THRESHOLD) { + if (pad[port].substick_x > pad[port].C_STICK_CENTER_X + pad[port].THRESHOLD || + pad[port].substick_x < pad[port].C_STICK_CENTER_X - pad[port].THRESHOLD) { pad[port].axis = GCAdapter::PadAxes::SubstickX; pad[port].axis_value = pad[port].substick_x; pad_queue[port].Push(pad[port]); } - if (pad[port].substick_y > - pad_constants.C_STICK_CENTER_Y + pad_constants.THRESHOLD || - pad[port].substick_y < - pad_constants.C_STICK_CENTER_Y - pad_constants.THRESHOLD) { + if (pad[port].substick_y > pad[port].C_STICK_CENTER_Y + pad[port].THRESHOLD || + pad[port].substick_y < pad[port].C_STICK_CENTER_Y - pad[port].THRESHOLD) { pad[port].axis = GCAdapter::PadAxes::SubstickY; pad[port].axis_value = pad[port].substick_y; pad_queue[port].Push(pad[port]); @@ -367,8 +351,16 @@ std::array, 4>& Adapter::GetPadQueue() { return pad_queue; } +const std::array, 4>& Adapter::GetPadQueue() const { + return pad_queue; +} + std::array& Adapter::GetPadState() { return state; } +const std::array& Adapter::GetPadState() const { + return state; +} + } // end of namespace GCAdapter diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index cb0dd0ab13..d7a57e7b71 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -46,17 +46,6 @@ enum class PadAxes : u8 { TriggerRight, Undefined, }; -const struct GCPadConstants { - const u8 MAIN_STICK_CENTER_X = 0x80; - const u8 MAIN_STICK_CENTER_Y = 0x80; - const u8 MAIN_STICK_RADIUS = 0x7f; - const u8 C_STICK_CENTER_X = 0x80; - const u8 C_STICK_CENTER_Y = 0x80; - const u8 C_STICK_RADIUS = 0x7f; - - const u8 TRIGGER_CENTER = 20; - const u8 THRESHOLD = 10; -} pad_constants; struct GCPadStatus { u16 button; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits @@ -67,6 +56,15 @@ struct GCPadStatus { u8 trigger_left; // 0 <= trigger_left <= 255 u8 trigger_right; // 0 <= trigger_right <= 255 + static constexpr u8 MAIN_STICK_CENTER_X = 0x80; + static constexpr u8 MAIN_STICK_CENTER_Y = 0x80; + static constexpr u8 MAIN_STICK_RADIUS = 0x7f; + static constexpr u8 C_STICK_CENTER_X = 0x80; + static constexpr u8 C_STICK_CENTER_Y = 0x80; + static constexpr u8 C_STICK_RADIUS = 0x7f; + static constexpr u8 TRIGGER_CENTER = 20; + static constexpr u8 THRESHOLD = 10; + u8 port; PadAxes axis = PadAxes::Undefined; u8 axis_value = 255; @@ -87,28 +85,22 @@ enum { /// Singleton Adapter class class Adapter { public: - /// For retreiving the singleton instance - static Adapter* GetInstance(); - - /// Used for polling - void BeginConfiguration(); - void EndConfiguration(); - - std::array, 4>& GetPadQueue(); - std::array& GetPadState(); - std::array, 4>& GetPadQueue() const; - std::array& GetPadState() const; - -private: - /// Singleton instance. - static Adapter* adapter_instance; - /// Initialize the GC Adapter capture and read sequence Adapter(); /// Close the adapter read thread and release the adapter ~Adapter(); + /// Used for polling + void BeginConfiguration(); + void EndConfiguration(); + std::array, 4>& GetPadQueue(); + const std::array, 4>& GetPadQueue() const; + + std::array& GetPadState(); + const std::array& GetPadState() const; + +private: GCPadStatus CheckStatus(int port, u8 adapter_payload[37]); void PadToState(GCPadStatus pad, GCState& state); diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index ac4126cb62..ad8b4b431b 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -14,7 +14,8 @@ namespace InputCommon { class GCButton final : public Input::ButtonDevice { public: - explicit GCButton(int port_, int button_, int axis_, GCAdapter::Adapter* adapter) + explicit GCButton(int port_, int button_, int axis_, + std::shared_ptr adapter) : port(port_), button(button_), gcadapter(adapter) {} ~GCButton() override; @@ -26,13 +27,13 @@ public: private: const int port; const int button; - GCAdapter::Adapter* gcadapter; + std::shared_ptr gcadapter; }; class GCAxisButton final : public Input::ButtonDevice { public: explicit GCAxisButton(int port_, int axis_, float threshold_, bool trigger_if_greater_, - GCAdapter::Adapter* adapter) + std::shared_ptr adapter) : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_), gcadapter(adapter) {} @@ -49,12 +50,11 @@ private: const int axis; float threshold; bool trigger_if_greater; - GCAdapter::Adapter* gcadapter; + std::shared_ptr gcadapter; }; -GCButtonFactory::GCButtonFactory() { - adapter = GCAdapter::Adapter::GetInstance(); -} +GCButtonFactory::GCButtonFactory(std::shared_ptr adapter_) + : adapter(adapter_) {} GCButton::~GCButton() = default; @@ -171,7 +171,8 @@ void GCButtonFactory::EndConfiguration() { class GCAnalog final : public Input::AnalogDevice { public: - GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, GCAdapter::Adapter* adapter) + GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, + std::shared_ptr adapter) : port(port_), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_), gcadapter(adapter) {} float GetAxis(int axis) const { @@ -230,13 +231,12 @@ private: const int axis_y; const float deadzone; mutable std::mutex mutex; - GCAdapter::Adapter* gcadapter; + std::shared_ptr gcadapter; }; /// An analog device factory that creates analog devices from GC Adapter -GCAnalogFactory::GCAnalogFactory() { - adapter = GCAdapter::Adapter::GetInstance(); -}; +GCAnalogFactory::GCAnalogFactory(std::shared_ptr adapter_) + : adapter(adapter_) {} /** * Creates analog device from joystick axes diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h index 31ff1c1237..d3a56da5be 100644 --- a/src/input_common/gcadapter/gc_poller.h +++ b/src/input_common/gcadapter/gc_poller.h @@ -15,7 +15,7 @@ namespace InputCommon { */ class GCButtonFactory final : public Input::Factory { public: - GCButtonFactory(); + GCButtonFactory(std::shared_ptr adapter_); /** * Creates a button device from a button press @@ -35,14 +35,14 @@ public: } private: - GCAdapter::Adapter* adapter; + std::shared_ptr adapter; bool polling = false; }; /// An analog device factory that creates analog devices from GC Adapter class GCAnalogFactory final : public Input::Factory { public: - GCAnalogFactory(); + GCAnalogFactory(std::shared_ptr adapter_); std::unique_ptr Create(const Common::ParamPackage& params) override; Common::ParamPackage GetNextInput(); @@ -55,7 +55,7 @@ public: } private: - GCAdapter::Adapter* adapter; + std::shared_ptr adapter; int analog_x_axis = -1; int analog_y_axis = -1; int controller_number = -1; diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index 89dddf7cf7..fc399db7e9 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -25,13 +25,15 @@ static std::shared_ptr motion_emu; static std::unique_ptr sdl; #endif static std::unique_ptr udp; +static std::shared_ptr gcadapter; static std::shared_ptr gcbuttons; static std::shared_ptr gcanalog; void Init() { - gcbuttons = std::make_shared(); + gcadapter = std::make_shared(); + gcbuttons = std::make_shared(gcadapter); Input::RegisterFactory("gcpad", gcbuttons); - gcanalog = std::make_shared(); + gcanalog = std::make_shared(gcadapter); Input::RegisterFactory("gcpad", gcanalog); keyboard = std::make_shared(); From 0f729ef0785eba2a2bd8e9581da4050209c2611d Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 22:58:53 -0400 Subject: [PATCH 09/27] fix for sleep using stl --- src/input_common/gcadapter/gc_adapter.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index db72d76334..e3bcb24f6a 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -2,6 +2,8 @@ // Licensed under GPLv2+ // Refer to the license.txt file included. +#include +#include #include "common/logging/log.h" #include "input_common/gcadapter/gc_adapter.h" @@ -182,7 +184,7 @@ void Adapter::ScanThreadFunc() { std::lock_guard lk(initialization_mutex); Setup(); } - Sleep(500); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } From 28046ae3a9cd5e32c7cae1cf64aa005502bf1749 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sun, 21 Jun 2020 23:56:56 -0400 Subject: [PATCH 10/27] Tidy up the pointers, use pair over tuple where appropriate --- src/input_common/gcadapter/gc_poller.cpp | 36 +++++++++++------------- src/input_common/gcadapter/gc_poller.h | 6 ++-- src/input_common/main.cpp | 3 +- src/input_common/main.h | 1 - 4 files changed, 22 insertions(+), 24 deletions(-) diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index ad8b4b431b..be7c600a26 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -14,8 +14,7 @@ namespace InputCommon { class GCButton final : public Input::ButtonDevice { public: - explicit GCButton(int port_, int button_, int axis_, - std::shared_ptr adapter) + explicit GCButton(int port_, int button_, int axis_, GCAdapter::Adapter* adapter) : port(port_), button(button_), gcadapter(adapter) {} ~GCButton() override; @@ -27,13 +26,13 @@ public: private: const int port; const int button; - std::shared_ptr gcadapter; + GCAdapter::Adapter* gcadapter; }; class GCAxisButton final : public Input::ButtonDevice { public: explicit GCAxisButton(int port_, int axis_, float threshold_, bool trigger_if_greater_, - std::shared_ptr adapter) + GCAdapter::Adapter* adapter) : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_), gcadapter(adapter) {} @@ -50,11 +49,11 @@ private: const int axis; float threshold; bool trigger_if_greater; - std::shared_ptr gcadapter; + GCAdapter::Adapter* gcadapter; }; GCButtonFactory::GCButtonFactory(std::shared_ptr adapter_) - : adapter(adapter_) {} + : adapter(std::move(adapter_)) {} GCButton::~GCButton() = default; @@ -75,11 +74,12 @@ std::unique_ptr GCButtonFactory::Create(const Common::Param trigger_if_greater = true; LOG_ERROR(Input, "Unknown direction {}", direction_name); } - return std::make_unique(port, axis, threshold, trigger_if_greater, adapter); + return std::make_unique(port, axis, threshold, trigger_if_greater, + adapter.get()); } std::unique_ptr button = - std::make_unique(port, button_id, params.Get("axis", 0), adapter); + std::make_unique(port, button_id, params.Get("axis", 0), adapter.get()); return std::move(button); } @@ -171,8 +171,7 @@ void GCButtonFactory::EndConfiguration() { class GCAnalog final : public Input::AnalogDevice { public: - GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, - std::shared_ptr adapter) + GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, GCAdapter::Adapter* adapter) : port(port_), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_), gcadapter(adapter) {} float GetAxis(int axis) const { @@ -183,7 +182,7 @@ public: return (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 95.0f; } - std::tuple GetAnalog(int axis_x, int axis_y) const { + std::pair GetAnalog(int axis_x, int axis_y) const { float x = GetAxis(axis_x); float y = GetAxis(axis_y); @@ -196,17 +195,17 @@ public: y /= r; } - return std::make_tuple(x, y); + return {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 {x / r * (r - deadzone) / (1 - deadzone), + y / r * (r - deadzone) / (1 - deadzone)}; } - return std::make_tuple(0.0f, 0.0f); + return {0.0f, 0.0f}; } bool GetAnalogDirectionStatus(Input::AnalogDirection direction) const override { @@ -231,12 +230,12 @@ private: const int axis_y; const float deadzone; mutable std::mutex mutex; - std::shared_ptr gcadapter; + GCAdapter::Adapter* gcadapter; }; /// An analog device factory that creates analog devices from GC Adapter GCAnalogFactory::GCAnalogFactory(std::shared_ptr adapter_) - : adapter(adapter_) {} + : adapter(std::move(adapter_)) {} /** * Creates analog device from joystick axes @@ -246,13 +245,12 @@ GCAnalogFactory::GCAnalogFactory(std::shared_ptr adapter_) * - "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, adapter); + return std::make_unique(port, axis_x, axis_y, deadzone, adapter.get()); } void GCAnalogFactory::BeginConfiguration() { diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h index d3a56da5be..e96af7d51a 100644 --- a/src/input_common/gcadapter/gc_poller.h +++ b/src/input_common/gcadapter/gc_poller.h @@ -6,6 +6,7 @@ #include #include "core/frontend/input.h" +#include "input_common/gcadapter/gc_adapter.h" namespace InputCommon { @@ -15,7 +16,7 @@ namespace InputCommon { */ class GCButtonFactory final : public Input::Factory { public: - GCButtonFactory(std::shared_ptr adapter_); + explicit GCButtonFactory(std::shared_ptr adapter_); /** * Creates a button device from a button press @@ -42,7 +43,8 @@ private: /// An analog device factory that creates analog devices from GC Adapter class GCAnalogFactory final : public Input::Factory { public: - GCAnalogFactory(std::shared_ptr adapter_); + explicit GCAnalogFactory(std::shared_ptr adapter_); + std::unique_ptr Create(const Common::ParamPackage& params) override; Common::ParamPackage GetNextInput(); diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index fc399db7e9..827a1a30c1 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -25,12 +25,11 @@ static std::shared_ptr motion_emu; static std::unique_ptr sdl; #endif static std::unique_ptr udp; -static std::shared_ptr gcadapter; static std::shared_ptr gcbuttons; static std::shared_ptr gcanalog; void Init() { - gcadapter = std::make_shared(); + std::shared_ptr gcadapter = std::make_shared(); gcbuttons = std::make_shared(gcadapter); Input::RegisterFactory("gcpad", gcbuttons); gcanalog = std::make_shared(gcadapter); diff --git a/src/input_common/main.h b/src/input_common/main.h index c26222f214..0e32856f6d 100644 --- a/src/input_common/main.h +++ b/src/input_common/main.h @@ -7,7 +7,6 @@ #include #include #include -#include "input_common/gcadapter/gc_adapter.h" #include "input_common/gcadapter/gc_poller.h" namespace Common { From f5d2a1e8bdb334a0354689a8da471b7f7525e61f Mon Sep 17 00:00:00 2001 From: ameerj <52414509+ameerj@users.noreply.github.com> Date: Mon, 22 Jun 2020 10:40:27 -0400 Subject: [PATCH 11/27] Update src/input_common/main.cpp Co-authored-by: LC update libusb submodule (hopefully windows build error fixed) --- externals/libusb | 2 +- src/input_common/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/externals/libusb b/externals/libusb index c5085fc4eb..71c3083fdd 160000 --- a/externals/libusb +++ b/externals/libusb @@ -1 +1 @@ -Subproject commit c5085fc4eb1a83e6a8921a43b8d77f162b9e3b41 +Subproject commit 71c3083fdd07a5a8c30a469800563bfbd9f9d4ad diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index 827a1a30c1..a9572c23cf 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -29,7 +29,7 @@ static std::shared_ptr gcbuttons; static std::shared_ptr gcanalog; void Init() { - std::shared_ptr gcadapter = std::make_shared(); + auto gcadapter = std::make_shared(); gcbuttons = std::make_shared(gcadapter); Input::RegisterFactory("gcpad", gcbuttons); gcanalog = std::make_shared(gcadapter); From 8ccc8cb2528c31c1ebff2831874dc7256946096b Mon Sep 17 00:00:00 2001 From: Ameer Date: Mon, 22 Jun 2020 17:05:23 -0400 Subject: [PATCH 12/27] update libusb dependency --- externals/libusb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/externals/libusb b/externals/libusb index 71c3083fdd..3406d72cda 160000 --- a/externals/libusb +++ b/externals/libusb @@ -1 +1 @@ -Subproject commit 71c3083fdd07a5a8c30a469800563bfbd9f9d4ad +Subproject commit 3406d72cda879f8792a88bf5f6bd0b7a65636f72 From fcc23139f622963c86e7f53c8b96f6f214294032 Mon Sep 17 00:00:00 2001 From: Ameer Date: Mon, 22 Jun 2020 18:11:59 -0400 Subject: [PATCH 13/27] std::array and const reference passing of non-trivial objects --- src/input_common/gcadapter/gc_adapter.cpp | 21 ++++++++++----------- src/input_common/gcadapter/gc_adapter.h | 6 +++--- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index e3bcb24f6a..745f1be276 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -21,7 +21,7 @@ Adapter::Adapter() { StartScanThread(); } -GCPadStatus Adapter::CheckStatus(int port, u8 adapter_payload[37]) { +GCPadStatus Adapter::CheckStatus(int port, const std::array& adapter_payload) { GCPadStatus pad = {}; bool get_origin = false; @@ -88,7 +88,7 @@ GCPadStatus Adapter::CheckStatus(int port, u8 adapter_payload[37]) { return pad; } -void Adapter::PadToState(GCPadStatus pad, GCState& state) { +void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { 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); @@ -112,15 +112,15 @@ void Adapter::PadToState(GCPadStatus pad, GCState& state) { void Adapter::Read() { LOG_INFO(Input, "GC Adapter Read() thread started"); - int payload_size_in; - u8 adapter_payload[37]; + int payload_size_in, payload_size; + std::array adapter_payload; + std::array controller_payload_copy; + std::array pad; + while (adapter_thread_running) { - libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload, + libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(), sizeof(adapter_payload), &payload_size_in, 32); - - int payload_size = 0; - u8 controller_payload_copy[37]; - + payload_size = 0; { std::lock_guard lk(s_mutex); std::copy(std::begin(adapter_payload), std::end(adapter_payload), @@ -128,7 +128,6 @@ void Adapter::Read() { payload_size = payload_size_in; } - std::array pad; 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, @@ -365,4 +364,4 @@ const std::array& Adapter::GetPadState() const { return state; } -} // end of namespace GCAdapter +} // namespace GCAdapter diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index d7a57e7b71..ff0202e3ba 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -101,9 +101,9 @@ public: const std::array& GetPadState() const; private: - GCPadStatus CheckStatus(int port, u8 adapter_payload[37]); + GCPadStatus CheckStatus(int port, const std::array& adapter_payload); - void PadToState(GCPadStatus pad, GCState& state); + void PadToState(const GCPadStatus& pad, GCState& state); void Read(); void ScanThreadFunc(); @@ -154,4 +154,4 @@ private: std::array state; }; -} // end of namespace GCAdapter +} // namespace GCAdapter From 901bc09dd7ee1ae90e2cbbc454cd039a1825b80d Mon Sep 17 00:00:00 2001 From: Ameer Date: Mon, 22 Jun 2020 22:02:50 -0400 Subject: [PATCH 14/27] Small quality of life indication that mapped button is GC --- src/yuzu/configuration/configure_input_player.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp index c7d3f45105..1d7418122f 100644 --- a/src/yuzu/configuration/configure_input_player.cpp +++ b/src/yuzu/configuration/configure_input_player.cpp @@ -75,11 +75,11 @@ static QString ButtonToText(const Common::ParamPackage& param) { 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); + return QObject::tr("GC 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 QObject::tr("GC Button %1").arg(button_str); } return GetKeyName(param.Get("code", 0)); } From d4e07fd95e999e34562428c628985a6eb1fb532d Mon Sep 17 00:00:00 2001 From: Ameer Date: Tue, 23 Jun 2020 12:47:58 -0400 Subject: [PATCH 15/27] Fix deallocation of GC Adapter --- src/input_common/gcadapter/gc_adapter.cpp | 10 +++++++--- src/input_common/gcadapter/gc_adapter.h | 1 - src/input_common/main.cpp | 3 +++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 745f1be276..887cde263e 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -130,6 +130,7 @@ void Adapter::Read() { if (payload_size != sizeof(controller_payload_copy) || controller_payload_copy[0] != LIBUSB_DT_HID) { + // TODO: It might be worthwhile to Shutdown GC Adapter if we encounter errors here LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size, controller_payload_copy[0]); } else { @@ -200,6 +201,7 @@ void Adapter::StartScanThread() { } void Adapter::StopScanThread() { + detect_thread_running = false; detect_thread.join(); } @@ -298,8 +300,6 @@ void Adapter::GetGCEndpoint(libusb_device* device) { Adapter::~Adapter() { StopScanThread(); Reset(); - - current_status = NO_ADAPTER_DETECTED; } void Adapter::Reset() { @@ -312,11 +312,11 @@ void Adapter::Reset() { } if (adapter_thread_running) { + adapter_thread_running = false; adapter_input_thread.join(); } adapter_controllers_status.fill(ControllerTypes::None); - current_status = NO_ADAPTER_DETECTED; if (usb_adapter_handle) { @@ -324,6 +324,10 @@ void Adapter::Reset() { libusb_close(usb_adapter_handle); usb_adapter_handle = nullptr; } + + if (libusb_ctx) { + libusb_exit(libusb_ctx); + } } bool Adapter::DeviceConnected(int port) { diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index ff0202e3ba..7aed0b4809 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -82,7 +82,6 @@ enum { ADAPTER_DETECTED = 1, }; -/// Singleton Adapter class class Adapter { public: /// Initialize the GC Adapter capture and read sequence diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index a9572c23cf..f13420b38f 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -59,7 +59,10 @@ void Shutdown() { #endif udp.reset(); Input::UnregisterFactory("gcpad"); + Input::UnregisterFactory("gcpad"); + gcbuttons.reset(); + gcanalog.reset(); } Keyboard* GetKeyboard() { From 743e1f02a06187164d55f4208b8e85742abd4498 Mon Sep 17 00:00:00 2001 From: Ameer Date: Tue, 23 Jun 2020 17:37:15 -0400 Subject: [PATCH 16/27] cleanup check access, read, and factory GetNextInput funcs. Use size rather than magic number --- src/input_common/gcadapter/gc_adapter.cpp | 169 ++++++++++------------ src/input_common/gcadapter/gc_adapter.h | 8 +- src/input_common/gcadapter/gc_poller.cpp | 74 +++------- src/input_common/keyboard.cpp | 1 - 4 files changed, 101 insertions(+), 151 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 887cde263e..9437d628fc 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -21,57 +21,38 @@ Adapter::Adapter() { StartScanThread(); } -GCPadStatus Adapter::CheckStatus(int port, const std::array& adapter_payload) { +GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_payload) { GCPadStatus pad = {}; bool get_origin = false; ControllerTypes type = ControllerTypes(adapter_payload[1 + (9 * port)] >> 4); - if (type != ControllerTypes::None) + if (type != ControllerTypes::None) { get_origin = true; + } adapter_controllers_status[port] = type; + constexpr std::array b1_buttons{ + PAD_BUTTON_A, PAD_BUTTON_B, PAD_BUTTON_X, PAD_BUTTON_Y, + PAD_BUTTON_LEFT, PAD_BUTTON_RIGHT, PAD_BUTTON_DOWN, PAD_BUTTON_UP}; + + constexpr std::array b2_buttons{PAD_BUTTON_START, PAD_TRIGGER_Z, PAD_TRIGGER_R, + PAD_TRIGGER_L}; + if (adapter_controllers_status[port] != ControllerTypes::None) { - u8 b1 = adapter_payload[1 + (9 * port) + 1]; - u8 b2 = adapter_payload[1 + (9 * port) + 2]; + const u8 b1 = adapter_payload[1 + (9 * port) + 1]; + const 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; + for (int i = 0; i < b1_buttons.size(); i++) { + if (b1 & (1 << i)) { + pad.button |= b1_buttons[i]; + } } - 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; + for (int j = 0; j < b2_buttons.size(); j++) { + if (b2 & (1 << j)) { + pad.button |= b2_buttons[j]; + } } if (get_origin) { @@ -112,65 +93,65 @@ void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { void Adapter::Read() { LOG_INFO(Input, "GC Adapter Read() thread started"); - int payload_size_in, payload_size; + int payload_size_in, payload_size_copy; std::array adapter_payload; - std::array controller_payload_copy; - std::array pad; + std::array adapter_payload_copy; + std::array pads; while (adapter_thread_running) { libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(), sizeof(adapter_payload), &payload_size_in, 32); - payload_size = 0; + payload_size_copy = 0; { 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; + std::begin(adapter_payload_copy)); + payload_size_copy = payload_size_in; } - if (payload_size != sizeof(controller_payload_copy) || - controller_payload_copy[0] != LIBUSB_DT_HID) { + if (payload_size_copy != sizeof(adapter_payload_copy) || + adapter_payload_copy[0] != LIBUSB_DT_HID) { // TODO: It might be worthwhile to Shutdown GC Adapter if we encounter errors here - LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size, - controller_payload_copy[0]); + LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size_copy, + adapter_payload_copy[0]); } else { - for (int port = 0; port < 4; port++) { - pad[port] = CheckStatus(port, controller_payload_copy); + for (int port = 0; port < pads.size(); port++) { + pads[port] = GetPadStatus(port, adapter_payload_copy); } } - for (int port = 0; port < 4; port++) { + for (int port = 0; port < pads.size(); port++) { if (DeviceConnected(port) && configuring) { - if (pad[port].button != PAD_GET_ORIGIN) { - pad_queue[port].Push(pad[port]); + if (pads[port].button != PAD_GET_ORIGIN) { + pad_queue[port].Push(pads[port]); } // Accounting for a threshold here because of some controller variance - if (pad[port].stick_x > pad[port].MAIN_STICK_CENTER_X + pad[port].THRESHOLD || - pad[port].stick_x < pad[port].MAIN_STICK_CENTER_X - pad[port].THRESHOLD) { - pad[port].axis = GCAdapter::PadAxes::StickX; - pad[port].axis_value = pad[port].stick_x; - pad_queue[port].Push(pad[port]); + if (pads[port].stick_x > pads[port].MAIN_STICK_CENTER_X + pads[port].THRESHOLD || + pads[port].stick_x < pads[port].MAIN_STICK_CENTER_X - pads[port].THRESHOLD) { + pads[port].axis = GCAdapter::PadAxes::StickX; + pads[port].axis_value = pads[port].stick_x; + pad_queue[port].Push(pads[port]); } - if (pad[port].stick_y > pad[port].MAIN_STICK_CENTER_Y + pad[port].THRESHOLD || - pad[port].stick_y < pad[port].MAIN_STICK_CENTER_Y - pad[port].THRESHOLD) { - pad[port].axis = GCAdapter::PadAxes::StickY; - pad[port].axis_value = pad[port].stick_y; - pad_queue[port].Push(pad[port]); + if (pads[port].stick_y > pads[port].MAIN_STICK_CENTER_Y + pads[port].THRESHOLD || + pads[port].stick_y < pads[port].MAIN_STICK_CENTER_Y - pads[port].THRESHOLD) { + pads[port].axis = GCAdapter::PadAxes::StickY; + pads[port].axis_value = pads[port].stick_y; + pad_queue[port].Push(pads[port]); } - if (pad[port].substick_x > pad[port].C_STICK_CENTER_X + pad[port].THRESHOLD || - pad[port].substick_x < pad[port].C_STICK_CENTER_X - pad[port].THRESHOLD) { - pad[port].axis = GCAdapter::PadAxes::SubstickX; - pad[port].axis_value = pad[port].substick_x; - pad_queue[port].Push(pad[port]); + if (pads[port].substick_x > pads[port].C_STICK_CENTER_X + pads[port].THRESHOLD || + pads[port].substick_x < pads[port].C_STICK_CENTER_X - pads[port].THRESHOLD) { + pads[port].axis = GCAdapter::PadAxes::SubstickX; + pads[port].axis_value = pads[port].substick_x; + pad_queue[port].Push(pads[port]); } - if (pad[port].substick_y > pad[port].C_STICK_CENTER_Y + pad[port].THRESHOLD || - pad[port].substick_y < pad[port].C_STICK_CENTER_Y - pad[port].THRESHOLD) { - pad[port].axis = GCAdapter::PadAxes::SubstickY; - pad[port].axis_value = pad[port].substick_y; - pad_queue[port].Push(pad[port]); + if (pads[port].substick_y > pads[port].C_STICK_CENTER_Y + pads[port].THRESHOLD || + pads[port].substick_y < pads[port].C_STICK_CENTER_Y - pads[port].THRESHOLD) { + pads[port].axis = GCAdapter::PadAxes::SubstickY; + pads[port].axis_value = pads[port].substick_y; + pad_queue[port].Push(pads[port]); } } - PadToState(pad[port], state[port]); + PadToState(pads[port], state[port]); } std::this_thread::yield(); } @@ -215,11 +196,11 @@ void Adapter::Setup() { libusb_device** devs; // pointer to list of connected usb devices - int cnt = libusb_get_device_list(libusb_ctx, &devs); // get the list of devices + const 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 + // GC Adapter found and accessible, registering it GetGCEndpoint(devs[i]); break; } @@ -228,10 +209,11 @@ void Adapter::Setup() { bool Adapter::CheckDeviceAccess(libusb_device* device) { libusb_device_descriptor desc; - int ret = libusb_get_device_descriptor(device, &desc); - if (ret) { + const int get_descriptor_error = libusb_get_device_descriptor(device, &desc); + if (get_descriptor_error) { // could not acquire the descriptor, no point in trying to use it. - LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: %d", ret); + LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: %d", + get_descriptor_error); return false; } @@ -239,35 +221,36 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { // This isn’t the device we are looking for. return false; } - ret = libusb_open(device, &usb_adapter_handle); + const int open_error = libusb_open(device, &usb_adapter_handle); - if (ret == LIBUSB_ERROR_ACCESS) { + if (open_error == 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); + if (open_error) { + LOG_ERROR(Input, "libusb_open failed to open device with error = %d", open_error); 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); + int kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle, 0); + if (kernel_driver_error == 1) { + kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0); + if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) { + LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = %d", + kernel_driver_error); } } - if (ret != 0 && ret != LIBUSB_ERROR_NOT_SUPPORTED) { + if (kernel_driver_error && kernel_driver_error != 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); + const int interface_claim_error = libusb_claim_interface(usb_adapter_handle, 0); + if (interface_claim_error) { + LOG_ERROR(Input, "libusb_claim_interface failed with error = %d", interface_claim_error); libusb_close(usb_adapter_handle); usb_adapter_handle = nullptr; return false; diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 7aed0b4809..abfe0d7b30 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -37,6 +37,12 @@ enum PadButton { }; +/// Used to loop through the and assign button in poller +static constexpr std::array PadButtonArray{ + PAD_BUTTON_LEFT, PAD_BUTTON_RIGHT, PAD_BUTTON_DOWN, PAD_BUTTON_UP, + PAD_TRIGGER_Z, PAD_TRIGGER_R, PAD_TRIGGER_L, PAD_BUTTON_A, + PAD_BUTTON_B, PAD_BUTTON_X, PAD_BUTTON_Y, PAD_BUTTON_START}; + enum class PadAxes : u8 { StickX, StickY, @@ -100,7 +106,7 @@ public: const std::array& GetPadState() const; private: - GCPadStatus CheckStatus(int port, const std::array& adapter_payload); + GCPadStatus GetPadStatus(int port, const std::array& adapter_payload); void PadToState(const GCPadStatus& pad, GCState& state); diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index be7c600a26..9772618844 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -58,8 +58,8 @@ GCButtonFactory::GCButtonFactory(std::shared_ptr adapter_) GCButton::~GCButton() = default; std::unique_ptr GCButtonFactory::Create(const Common::ParamPackage& params) { - int button_id = params.Get("button", 0); - int port = params.Get("port", 0); + const int button_id = params.Get("button", 0); + const 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); @@ -86,61 +86,22 @@ std::unique_ptr GCButtonFactory::Create(const Common::Param Common::ParamPackage GCButtonFactory::GetNextInput() { Common::ParamPackage params; GCAdapter::GCPadStatus pad; - for (int i = 0; i < 4; i++) { - while (adapter->GetPadQueue()[i].Pop(pad)) { + auto& queue = adapter->GetPadQueue(); + for (int port = 0; port < queue.size(); port++) { + while (queue[port].Pop(pad)) { // This while loop will break on the earliest detected button params.Set("engine", "gcpad"); - params.Set("port", i); + params.Set("port", port); // 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 & GCAdapter::PAD_BUTTON_A) { - params.Set("button", GCAdapter::PAD_BUTTON_A); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_B) { - params.Set("button", GCAdapter::PAD_BUTTON_B); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_X) { - params.Set("button", GCAdapter::PAD_BUTTON_X); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_Y) { - params.Set("button", GCAdapter::PAD_BUTTON_Y); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_DOWN) { - params.Set("button", GCAdapter::PAD_BUTTON_DOWN); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_LEFT) { - params.Set("button", GCAdapter::PAD_BUTTON_LEFT); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_RIGHT) { - params.Set("button", GCAdapter::PAD_BUTTON_RIGHT); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_UP) { - params.Set("button", GCAdapter::PAD_BUTTON_UP); - break; - } - if (pad.button & GCAdapter::PAD_TRIGGER_L) { - params.Set("button", GCAdapter::PAD_TRIGGER_L); - break; - } - if (pad.button & GCAdapter::PAD_TRIGGER_R) { - params.Set("button", GCAdapter::PAD_TRIGGER_R); - break; - } - if (pad.button & GCAdapter::PAD_TRIGGER_Z) { - params.Set("button", GCAdapter::PAD_TRIGGER_Z); - break; - } - if (pad.button & GCAdapter::PAD_BUTTON_START) { - params.Set("button", GCAdapter::PAD_BUTTON_START); - break; + + for (auto button : GCAdapter::PadButtonArray) { + if (pad.button & button) { + params.Set("button", button); + break; + } } + // For Axis button implementation if (pad.axis != GCAdapter::PadAxes::Undefined) { params.Set("axis", static_cast(pad.axis)); @@ -265,8 +226,9 @@ void GCAnalogFactory::EndConfiguration() { Common::ParamPackage GCAnalogFactory::GetNextInput() { GCAdapter::GCPadStatus pad; - for (int i = 0; i < 4; i++) { - while (adapter->GetPadQueue()[i].Pop(pad)) { + auto& queue = adapter->GetPadQueue(); + for (int port = 0; port < queue.size(); port++) { + while (queue[port].Pop(pad)) { if (pad.axis == GCAdapter::PadAxes::Undefined || std::abs((pad.axis_value - 128.0f) / 128.0f) < 0.1) { continue; @@ -276,8 +238,8 @@ Common::ParamPackage GCAnalogFactory::GetNextInput() { const u8 axis = static_cast(pad.axis); 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) { + controller_number = port; + } else if (analog_y_axis == -1 && analog_x_axis != axis && controller_number == port) { analog_y_axis = axis; } } diff --git a/src/input_common/keyboard.cpp b/src/input_common/keyboard.cpp index 9138a75630..eb6c3112b8 100644 --- a/src/input_common/keyboard.cpp +++ b/src/input_common/keyboard.cpp @@ -51,7 +51,6 @@ public: for (const KeyButtonPair& pair : list) { if (pair.key_code == key_code) { pair.key_button->status.store(pressed); - break; } } } From c18dc9c707235d7ba6fe230cb3045f2c13d04e62 Mon Sep 17 00:00:00 2001 From: Ameer Date: Wed, 24 Jun 2020 11:39:30 -0400 Subject: [PATCH 17/27] padbutton enum class and struct initiailization --- src/input_common/gcadapter/gc_adapter.cpp | 31 ++++++++++------------- src/input_common/gcadapter/gc_adapter.h | 30 +++++++++++----------- src/input_common/gcadapter/gc_poller.cpp | 7 ++--- 3 files changed, 32 insertions(+), 36 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 9437d628fc..bba9bcc698 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -33,11 +33,13 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa adapter_controllers_status[port] = type; constexpr std::array b1_buttons{ - PAD_BUTTON_A, PAD_BUTTON_B, PAD_BUTTON_X, PAD_BUTTON_Y, - PAD_BUTTON_LEFT, PAD_BUTTON_RIGHT, PAD_BUTTON_DOWN, PAD_BUTTON_UP}; + PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, PadButton::PAD_BUTTON_X, + PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, + PadButton::PAD_BUTTON_DOWN, PadButton::PAD_BUTTON_UP}; - constexpr std::array b2_buttons{PAD_BUTTON_START, PAD_TRIGGER_Z, PAD_TRIGGER_R, - PAD_TRIGGER_L}; + constexpr std::array b2_buttons{ + PadButton::PAD_BUTTON_START, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R, + PadButton::PAD_TRIGGER_L}; if (adapter_controllers_status[port] != ControllerTypes::None) { const u8 b1 = adapter_payload[1 + (9 * port) + 1]; @@ -45,13 +47,13 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa for (int i = 0; i < b1_buttons.size(); i++) { if (b1 & (1 << i)) { - pad.button |= b1_buttons[i]; + pad.button |= static_cast(b1_buttons[i]); } } for (int j = 0; j < b2_buttons.size(); j++) { if (b2 & (1 << j)) { - pad.button |= b2_buttons[j]; + pad.button |= static_cast(b2_buttons[j]); } } @@ -70,18 +72,11 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa } void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { - 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); + for (auto button : PadButtonArray) { + u16 button_value = static_cast(button); + state.buttons.insert_or_assign(button_value, pad.button & button_value); + } + state.axes.insert_or_assign(static_cast(PadAxes::StickX), pad.stick_x); state.axes.insert_or_assign(static_cast(PadAxes::StickY), pad.stick_y); state.axes.insert_or_assign(static_cast(PadAxes::SubstickX), pad.substick_x); diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index abfe0d7b30..91aa9622bc 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -19,7 +19,7 @@ enum { PAD_ERR_STATUS = 0x8000, }; -enum PadButton { +enum class PadButton { PAD_BUTTON_LEFT = 0x0001, PAD_BUTTON_RIGHT = 0x0002, PAD_BUTTON_DOWN = 0x0004, @@ -34,14 +34,14 @@ enum PadButton { PAD_BUTTON_START = 0x1000, // Below is for compatibility with "AxisButton" type PAD_STICK = 0x2000, - }; /// Used to loop through the and assign button in poller static constexpr std::array PadButtonArray{ - PAD_BUTTON_LEFT, PAD_BUTTON_RIGHT, PAD_BUTTON_DOWN, PAD_BUTTON_UP, - PAD_TRIGGER_Z, PAD_TRIGGER_R, PAD_TRIGGER_L, PAD_BUTTON_A, - PAD_BUTTON_B, PAD_BUTTON_X, PAD_BUTTON_Y, PAD_BUTTON_START}; + PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, PadButton::PAD_BUTTON_DOWN, + PadButton::PAD_BUTTON_UP, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R, + PadButton::PAD_TRIGGER_L, PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, + PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_START}; enum class PadAxes : u8 { StickX, @@ -54,13 +54,13 @@ enum class PadAxes : u8 { }; struct GCPadStatus { - u16 button; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits - u8 stick_x; // 0 <= stick_x <= 255 - u8 stick_y; // 0 <= stick_y <= 255 - u8 substick_x; // 0 <= substick_x <= 255 - u8 substick_y; // 0 <= substick_y <= 255 - u8 trigger_left; // 0 <= trigger_left <= 255 - u8 trigger_right; // 0 <= trigger_right <= 255 + u16 button{}; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits + u8 stick_x{}; // 0 <= stick_x <= 255 + u8 stick_y{}; // 0 <= stick_y <= 255 + u8 substick_x{}; // 0 <= substick_x <= 255 + u8 substick_y{}; // 0 <= substick_y <= 255 + u8 trigger_left{}; // 0 <= trigger_left <= 255 + u8 trigger_right{}; // 0 <= trigger_right <= 255 static constexpr u8 MAIN_STICK_CENTER_X = 0x80; static constexpr u8 MAIN_STICK_CENTER_Y = 0x80; @@ -71,9 +71,9 @@ struct GCPadStatus { static constexpr u8 TRIGGER_CENTER = 20; static constexpr u8 THRESHOLD = 10; - u8 port; - PadAxes axis = PadAxes::Undefined; - u8 axis_value = 255; + u8 port{}; + PadAxes axis{PadAxes::Undefined}; + u8 axis_value{255}; }; struct GCState { diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index 9772618844..06e16880f3 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -96,8 +96,9 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { // or to use a while loop shifting the bits to test and set the value. for (auto button : GCAdapter::PadButtonArray) { - if (pad.button & button) { - params.Set("button", button); + u16 button_value = static_cast(button); + if (pad.button & button_value) { + params.Set("button", button_value); break; } } @@ -105,7 +106,7 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { // For Axis button implementation if (pad.axis != GCAdapter::PadAxes::Undefined) { params.Set("axis", static_cast(pad.axis)); - params.Set("button", GCAdapter::PAD_STICK); + params.Set("button", static_cast(GCAdapter::PadButton::PAD_STICK)); if (pad.axis_value > 128) { params.Set("direction", "+"); params.Set("threshold", "0.5"); From 3f739514e3fa5f3e5c64fa8172c796bd686f6e7d Mon Sep 17 00:00:00 2001 From: Ameer Date: Thu, 25 Jun 2020 19:31:51 -0400 Subject: [PATCH 18/27] Stop reading loop if error is encountered --- src/input_common/gcadapter/gc_adapter.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index bba9bcc698..173b5c3254 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -95,7 +95,7 @@ void Adapter::Read() { while (adapter_thread_running) { libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(), - sizeof(adapter_payload), &payload_size_in, 32); + sizeof(adapter_payload), &payload_size_in, 16); payload_size_copy = 0; { std::lock_guard lk(s_mutex); @@ -106,9 +106,9 @@ void Adapter::Read() { if (payload_size_copy != sizeof(adapter_payload_copy) || adapter_payload_copy[0] != LIBUSB_DT_HID) { - // TODO: It might be worthwhile to Shutdown GC Adapter if we encounter errors here LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size_copy, adapter_payload_copy[0]); + adapter_thread_running = false; // error reading from adapter, stop reading. } else { for (int port = 0; port < pads.size(); port++) { pads[port] = GetPadStatus(port, adapter_payload_copy); @@ -291,14 +291,14 @@ void Adapter::Reset() { if (adapter_thread_running) { adapter_thread_running = false; - adapter_input_thread.join(); } + adapter_input_thread.join(); adapter_controllers_status.fill(ControllerTypes::None); current_status = NO_ADAPTER_DETECTED; if (usb_adapter_handle) { - libusb_release_interface(usb_adapter_handle, 0); + libusb_release_interface(usb_adapter_handle, 1); libusb_close(usb_adapter_handle); usb_adapter_handle = nullptr; } From ecbc8137117d6d37b231fc2745b281b6e7077e16 Mon Sep 17 00:00:00 2001 From: Ameer J <52414509+ameerj@users.noreply.github.com> Date: Thu, 25 Jun 2020 19:46:50 -0400 Subject: [PATCH 19/27] const& to button in button array Co-authored-by: VolcaEM <63682805+VolcaEM@users.noreply.github.com> --- src/input_common/gcadapter/gc_adapter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 173b5c3254..80355a40d6 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -72,7 +72,7 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa } void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { - for (auto button : PadButtonArray) { + for (auto const& button : PadButtonArray) { u16 button_value = static_cast(button); state.buttons.insert_or_assign(button_value, pad.button & button_value); } @@ -213,7 +213,7 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { } if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) { - // This isn’t the device we are looking for. + // This isnÂ’t the device we are looking for. return false; } const int open_error = libusb_open(device, &usb_adapter_handle); From bd697bef039ddf307ed7ddf3d9daf0fd7ec1ee8f Mon Sep 17 00:00:00 2001 From: Ameer J <52414509+ameerj@users.noreply.github.com> Date: Fri, 26 Jun 2020 23:46:49 -0400 Subject: [PATCH 20/27] left const auto&, comment punctuation. Co-authored-by: Morph <39850852+Morph1984@users.noreply.github.com> --- src/input_common/gcadapter/gc_adapter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 80355a40d6..774246bdfb 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -72,7 +72,7 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa } void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { - for (auto const& button : PadButtonArray) { + for (const auto& button : PadButtonArray) { u16 button_value = static_cast(button); state.buttons.insert_or_assign(button_value, pad.button & button_value); } @@ -213,7 +213,7 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { } if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) { - // This isnÂ’t the device we are looking for. + // This isn't the device we are looking for. return false; } const int open_error = libusb_open(device, &usb_adapter_handle); From dfdf87d844de6226fd043bb840de8525d8fbc0d1 Mon Sep 17 00:00:00 2001 From: Ameer Date: Tue, 30 Jun 2020 11:44:55 -0400 Subject: [PATCH 21/27] fix implicit conversion of size_t type to int --- src/input_common/gcadapter/gc_adapter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 774246bdfb..b509b3e46f 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -191,7 +191,7 @@ void Adapter::Setup() { libusb_device** devs; // pointer to list of connected usb devices - const int cnt = libusb_get_device_list(libusb_ctx, &devs); // get the list of devices + const std::size_t cnt = libusb_get_device_list(libusb_ctx, &devs); // get the list of devices for (int i = 0; i < cnt; i++) { if (CheckDeviceAccess(devs[i])) { From a76e11e7f0c97222388bede03325aa71f1434510 Mon Sep 17 00:00:00 2001 From: Ameer Date: Tue, 30 Jun 2020 17:28:02 -0400 Subject: [PATCH 22/27] Address feedback regarding increments, const vars, and general cleanup --- src/input_common/gcadapter/gc_adapter.cpp | 28 +++++++++++------------ src/input_common/gcadapter/gc_poller.cpp | 17 ++++++-------- 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index b509b3e46f..b98b85441b 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -45,13 +45,13 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa const u8 b1 = adapter_payload[1 + (9 * port) + 1]; const u8 b2 = adapter_payload[1 + (9 * port) + 2]; - for (int i = 0; i < b1_buttons.size(); i++) { + for (std::size_t i = 0; i < b1_buttons.size(); ++i) { if (b1 & (1 << i)) { pad.button |= static_cast(b1_buttons[i]); } } - for (int j = 0; j < b2_buttons.size(); j++) { + for (std::size_t j = 0; j < b2_buttons.size(); ++j) { if (b2 & (1 << j)) { pad.button |= static_cast(b2_buttons[j]); } @@ -73,7 +73,7 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { for (const auto& button : PadButtonArray) { - u16 button_value = static_cast(button); + const u16 button_value = static_cast(button); state.buttons.insert_or_assign(button_value, pad.button & button_value); } @@ -86,7 +86,7 @@ void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { } void Adapter::Read() { - LOG_INFO(Input, "GC Adapter Read() thread started"); + LOG_DEBUG(Input, "GC Adapter Read() thread started"); int payload_size_in, payload_size_copy; std::array adapter_payload; @@ -109,12 +109,10 @@ void Adapter::Read() { LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size_copy, adapter_payload_copy[0]); adapter_thread_running = false; // error reading from adapter, stop reading. - } else { - for (int port = 0; port < pads.size(); port++) { - pads[port] = GetPadStatus(port, adapter_payload_copy); - } + break; } - for (int port = 0; port < pads.size(); port++) { + for (std::size_t port = 0; port < pads.size(); ++port) { + pads[port] = GetPadStatus(port, adapter_payload_copy); if (DeviceConnected(port) && configuring) { if (pads[port].button != PAD_GET_ORIGIN) { pad_queue[port].Push(pads[port]); @@ -189,14 +187,16 @@ void Adapter::Setup() { adapter_controllers_status.fill(ControllerTypes::None); - libusb_device** devs; // pointer to list of connected usb devices + // pointer to list of connected usb devices + libusb_device** devices; - const std::size_t cnt = libusb_get_device_list(libusb_ctx, &devs); // get the list of devices + // populate the list of devices, get the count + const std::size_t device_count = libusb_get_device_list(libusb_ctx, &devices); - for (int i = 0; i < cnt; i++) { - if (CheckDeviceAccess(devs[i])) { + for (std::size_t index = 0; index < device_count; ++index) { + if (CheckDeviceAccess(devices[index])) { // GC Adapter found and accessible, registering it - GetGCEndpoint(devs[i]); + GetGCEndpoint(devices[index]); break; } } diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index 06e16880f3..a9de9fedf6 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -39,9 +39,9 @@ public: bool GetStatus() const override { const float axis_value = (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 128.0f; if (trigger_if_greater) { - return axis_value > 0.10f; // TODO(ameerj) : Fix threshold. + return axis_value > threshold; // TODO(ameerj) : Fix threshold. } - return axis_value < -0.10f; + return axis_value < -threshold; } private: @@ -87,16 +87,13 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { Common::ParamPackage params; GCAdapter::GCPadStatus pad; auto& queue = adapter->GetPadQueue(); - for (int port = 0; port < queue.size(); port++) { + for (std::size_t port = 0; port < queue.size(); ++port) { while (queue[port].Pop(pad)) { // This while loop will break on the earliest detected button params.Set("engine", "gcpad"); - params.Set("port", port); - // 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. - - for (auto button : GCAdapter::PadButtonArray) { - u16 button_value = static_cast(button); + params.Set("port", static_cast(port)); + for (const auto& button : GCAdapter::PadButtonArray) { + const u16 button_value = static_cast(button); if (pad.button & button_value) { params.Set("button", button_value); break; @@ -228,7 +225,7 @@ void GCAnalogFactory::EndConfiguration() { Common::ParamPackage GCAnalogFactory::GetNextInput() { GCAdapter::GCPadStatus pad; auto& queue = adapter->GetPadQueue(); - for (int port = 0; port < queue.size(); port++) { + for (std::size_t port = 0; port < queue.size(); ++port) { while (queue[port].Pop(pad)) { if (pad.axis == GCAdapter::PadAxes::Undefined || std::abs((pad.axis_value - 128.0f) / 128.0f) < 0.1) { From 34a590e50966341cec5f1874410931decbce284f Mon Sep 17 00:00:00 2001 From: Ameer Date: Wed, 1 Jul 2020 12:52:50 -0400 Subject: [PATCH 23/27] Reset adapter state on init, fixes errors relating driver hang from unexpected unplug --- src/input_common/gcadapter/gc_adapter.cpp | 8 ++++++++ src/input_common/gcadapter/gc_adapter.h | 1 + 2 files changed, 9 insertions(+) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index b98b85441b..1ddb9cdb42 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -97,6 +97,7 @@ void Adapter::Read() { libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(), sizeof(adapter_payload), &payload_size_in, 16); payload_size_copy = 0; + // this mutex might be redundant? { std::lock_guard lk(s_mutex); std::copy(std::begin(adapter_payload), std::end(adapter_payload), @@ -265,10 +266,17 @@ void Adapter::GetGCEndpoint(libusb_device* device) { const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e]; if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) { input_endpoint = endpoint->bEndpointAddress; + } else { + output_endpoint = endpoint->bEndpointAddress; } } } } + // This transfer seems to be responsible for clearing the state of the adapter + // Used to clear the "busy" state of when the device is unexpectedly unplugged + unsigned char clear_payload = 0x13; + libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, &clear_payload, + sizeof(clear_payload), nullptr, 16); adapter_thread_running = true; current_status = ADAPTER_DETECTED; diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 91aa9622bc..4a8e2644c2 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -152,6 +152,7 @@ private: libusb_context* libusb_ctx; u8 input_endpoint = 0; + u8 output_endpoint = 0; bool configuring = false; From 6b7c8e469b2d7943cd7771648659bc362e5d1ddd Mon Sep 17 00:00:00 2001 From: Ameer Date: Thu, 2 Jul 2020 15:54:44 -0400 Subject: [PATCH 24/27] Add LR triggers as axes, half press to initiate a press, add GC axis id in config, clarify some code blocks for better readability --- src/input_common/gcadapter/gc_adapter.cpp | 12 ++++ src/input_common/gcadapter/gc_poller.cpp | 32 ++++++--- .../configuration/configure_input_player.cpp | 71 ++++++++++++------- 3 files changed, 80 insertions(+), 35 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 1ddb9cdb42..82f97572f3 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -144,6 +144,18 @@ void Adapter::Read() { pads[port].axis_value = pads[port].substick_y; pad_queue[port].Push(pads[port]); } + if (pads[port].trigger_left > pads[port].TRIGGER_CENTER + pads[port].THRESHOLD || + pads[port].trigger_left < pads[port].TRIGGER_CENTER - pads[port].THRESHOLD) { + pads[port].axis = GCAdapter::PadAxes::TriggerLeft; + pads[port].axis_value = pads[port].trigger_left; + pad_queue[port].Push(pads[port]); + } + if (pads[port].trigger_right > pads[port].TRIGGER_CENTER + pads[port].THRESHOLD || + pads[port].trigger_right < pads[port].TRIGGER_CENTER - pads[port].THRESHOLD) { + pads[port].axis = GCAdapter::PadAxes::TriggerRight; + pads[port].axis_value = pads[port].trigger_right; + pad_queue[port].Push(pads[port]); + } } PadToState(pads[port], state[port]); } diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index a9de9fedf6..a04c507b84 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -34,7 +34,13 @@ public: explicit GCAxisButton(int port_, int axis_, float threshold_, bool trigger_if_greater_, GCAdapter::Adapter* adapter) : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_), - gcadapter(adapter) {} + gcadapter(adapter) { + // L/R triggers range is only in positive direction beginning near 0 + // 0.0 threshold equates to near half trigger press, but threshold accounts for variability. + if (axis > 3) { + threshold *= -0.5; + } + } bool GetStatus() const override { const float axis_value = (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 128.0f; @@ -60,10 +66,20 @@ GCButton::~GCButton() = default; std::unique_ptr GCButtonFactory::Create(const Common::ParamPackage& params) { const int button_id = params.Get("button", 0); const int port = params.Get("port", 0); + + constexpr int PAD_STICK_ID = static_cast(GCAdapter::PadButton::PAD_STICK); + + // button is not an axis/stick button + if (button_id != PAD_STICK_ID) { + std::unique_ptr button = + std::make_unique(port, button_id, params.Get("axis", 0), adapter.get()); + return std::move(button); + } + // For Axis buttons, used by the binary sticks. - if (params.Has("axis")) { + if (button_id == PAD_STICK_ID) { const int axis = params.Get("axis", 0); - const float threshold = params.Get("threshold", 0.5f); + const float threshold = params.Get("threshold", 0.25f); const std::string direction_name = params.Get("direction", ""); bool trigger_if_greater; if (direction_name == "+") { @@ -77,10 +93,6 @@ std::unique_ptr GCButtonFactory::Create(const Common::Param return std::make_unique(port, axis, threshold, trigger_if_greater, adapter.get()); } - - std::unique_ptr button = - std::make_unique(port, button_id, params.Get("axis", 0), adapter.get()); - return std::move(button); } Common::ParamPackage GCButtonFactory::GetNextInput() { @@ -106,10 +118,10 @@ Common::ParamPackage GCButtonFactory::GetNextInput() { params.Set("button", static_cast(GCAdapter::PadButton::PAD_STICK)); if (pad.axis_value > 128) { params.Set("direction", "+"); - params.Set("threshold", "0.5"); + params.Set("threshold", "0.25"); } else { params.Set("direction", "-"); - params.Set("threshold", "-0.5"); + params.Set("threshold", "-0.25"); } break; } @@ -232,7 +244,7 @@ Common::ParamPackage GCAnalogFactory::GetNextInput() { 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. + // a second input event. The axes also must be from the same joystick. const u8 axis = static_cast(pad.axis); if (analog_x_axis == -1) { analog_x_axis = axis; diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp index 1d7418122f..49b8c8386a 100644 --- a/src/yuzu/configuration/configure_input_player.cpp +++ b/src/yuzu/configuration/configure_input_player.cpp @@ -120,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" || param.Get("engine", "") == "gcpad") { + if (param.Get("engine", "") == "sdl") { if (dir == "modifier") { return QObject::tr("[unused]"); } @@ -140,6 +140,25 @@ static QString AnalogToText(const Common::ParamPackage& param, const std::string return {}; } + if (param.Get("engine", "") == "gcpad") { + if (dir == "modifier") { + return QObject::tr("[unused]"); + } + + if (dir == "left" || dir == "right") { + const QString axis_x_str = QString::fromStdString(param.Get("axis_x", "")); + + return QObject::tr("GC Axis %1").arg(axis_x_str); + } + + if (dir == "up" || dir == "down") { + const QString axis_y_str = QString::fromStdString(param.Get("axis_y", "")); + + return QObject::tr("GC Axis %1").arg(axis_y_str); + } + + return {}; + } return QObject::tr("[unknown]"); } @@ -262,24 +281,25 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i button->setContextMenuPolicy(Qt::CustomContextMenu); connect(button, &QPushButton::clicked, [=] { - HandleClick(button_map[button_id], - [=](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 - // analog triggers instead of -32768 to 32768 on analog joysticks). The - // SDL driver misinterprets analog triggers as analog joysticks. - // TODO: reinterpret the signal range for analog triggers to map the - // values correctly. This is required for the correct emulation of the - // analog triggers of the GameCube controller. - if (button_id == Settings::NativeButton::ZL || - button_id == Settings::NativeButton::ZR) { - params.Set("direction", "+"); - params.Set("threshold", "0.5"); - } - buttons_param[button_id] = std::move(params); - }, - InputCommon::Polling::DeviceType::Button); + HandleClick( + button_map[button_id], + [=](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 + // analog triggers instead of -32768 to 32768 on analog joysticks). The + // SDL driver misinterprets analog triggers as analog joysticks. + // TODO: reinterpret the signal range for analog triggers to map the + // values correctly. This is required for the correct emulation of the + // analog triggers of the GameCube controller. + if (button_id == Settings::NativeButton::ZL || + button_id == Settings::NativeButton::ZR) { + params.Set("direction", "+"); + params.Set("threshold", "0.5"); + } + buttons_param[button_id] = std::move(params); + }, + InputCommon::Polling::DeviceType::Button); }); connect(button, &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) { QMenu context_menu; @@ -305,12 +325,13 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i analog_button->setContextMenuPolicy(Qt::CustomContextMenu); connect(analog_button, &QPushButton::clicked, [=]() { - HandleClick(analog_map_buttons[analog_id][sub_button_id], - [=](const Common::ParamPackage& params) { - SetAnalogButton(params, analogs_param[analog_id], - analog_sub_buttons[sub_button_id]); - }, - InputCommon::Polling::DeviceType::Button); + HandleClick( + analog_map_buttons[analog_id][sub_button_id], + [=](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) { From 6e1639c7b004d13aba77549131ecee793fcc4065 Mon Sep 17 00:00:00 2001 From: Ameer Date: Thu, 2 Jul 2020 16:51:16 -0400 Subject: [PATCH 25/27] Fix unnecessary diffs --- src/input_common/keyboard.cpp | 3 +- src/input_common/main.cpp | 2 + src/input_common/sdl/sdl_impl.cpp | 1 - .../configuration/configure_input_player.cpp | 50 +++++++++---------- 4 files changed, 27 insertions(+), 29 deletions(-) diff --git a/src/input_common/keyboard.cpp b/src/input_common/keyboard.cpp index eb6c3112b8..afb8e6612c 100644 --- a/src/input_common/keyboard.cpp +++ b/src/input_common/keyboard.cpp @@ -49,9 +49,8 @@ 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); - } } } diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp index f13420b38f..fd0af10193 100644 --- a/src/input_common/main.cpp +++ b/src/input_common/main.cpp @@ -45,6 +45,7 @@ void Init() { #ifdef HAVE_SDL2 sdl = SDL::Init(); #endif + udp = CemuhookUDP::Init(); } @@ -111,6 +112,7 @@ std::vector> GetPollers(DeviceType type) { #ifdef HAVE_SDL2 pollers = sdl->GetPollers(type); #endif + return pollers; } diff --git a/src/input_common/sdl/sdl_impl.cpp b/src/input_common/sdl/sdl_impl.cpp index 6b264f2a6f..675b477fa3 100644 --- a/src/input_common/sdl/sdl_impl.cpp +++ b/src/input_common/sdl/sdl_impl.cpp @@ -444,7 +444,6 @@ private: class SDLAnalogFactory final : public Input::Factory { public: explicit SDLAnalogFactory(SDLState& state_) : state(state_) {} - /** * Creates analog device from joystick axes * @param params contains parameters for creating the device: diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp index 49b8c8386a..00433926d3 100644 --- a/src/yuzu/configuration/configure_input_player.cpp +++ b/src/yuzu/configuration/configure_input_player.cpp @@ -281,25 +281,24 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i button->setContextMenuPolicy(Qt::CustomContextMenu); connect(button, &QPushButton::clicked, [=] { - HandleClick( - button_map[button_id], - [=](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 - // analog triggers instead of -32768 to 32768 on analog joysticks). The - // SDL driver misinterprets analog triggers as analog joysticks. - // TODO: reinterpret the signal range for analog triggers to map the - // values correctly. This is required for the correct emulation of the - // analog triggers of the GameCube controller. - if (button_id == Settings::NativeButton::ZL || - button_id == Settings::NativeButton::ZR) { - params.Set("direction", "+"); - params.Set("threshold", "0.5"); - } - buttons_param[button_id] = std::move(params); - }, - InputCommon::Polling::DeviceType::Button); + HandleClick(button_map[button_id], + [=](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 + // analog triggers instead of -32768 to 32768 on analog joysticks). The + // SDL driver misinterprets analog triggers as analog joysticks. + // TODO: reinterpret the signal range for analog triggers to map the + // values correctly. This is required for the correct emulation of the + // analog triggers of the GameCube controller. + if (button_id == Settings::NativeButton::ZL || + button_id == Settings::NativeButton::ZR) { + params.Set("direction", "+"); + params.Set("threshold", "0.5"); + } + buttons_param[button_id] = std::move(params); + }, + InputCommon::Polling::DeviceType::Button); }); connect(button, &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) { QMenu context_menu; @@ -325,13 +324,12 @@ ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_i analog_button->setContextMenuPolicy(Qt::CustomContextMenu); connect(analog_button, &QPushButton::clicked, [=]() { - HandleClick( - analog_map_buttons[analog_id][sub_button_id], - [=](const Common::ParamPackage& params) { - SetAnalogButton(params, analogs_param[analog_id], - analog_sub_buttons[sub_button_id]); - }, - InputCommon::Polling::DeviceType::Button); + HandleClick(analog_map_buttons[analog_id][sub_button_id], + [=](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) { From e69d715e3d42aaa5e99ebe8e578e64242d049a8c Mon Sep 17 00:00:00 2001 From: Ameer Date: Fri, 3 Jul 2020 11:52:07 -0400 Subject: [PATCH 26/27] Address lioncash feedback: Log formatting, extern const PadButtonArray, little touch ups --- src/input_common/gcadapter/gc_adapter.cpp | 40 +++++++++++++++-------- src/input_common/gcadapter/gc_adapter.h | 7 +--- src/input_common/gcadapter/gc_poller.cpp | 9 ++--- 3 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index 82f97572f3..f58b0e11c1 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -9,6 +9,14 @@ namespace GCAdapter { +/// Used to loop through and assign button in poller +constexpr std::array PadButtonArray{ + PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, PadButton::PAD_BUTTON_DOWN, + PadButton::PAD_BUTTON_UP, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R, + PadButton::PAD_TRIGGER_L, PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, + PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_START, +}; + Adapter::Adapter() { if (usb_adapter_handle != nullptr) { return; @@ -32,27 +40,31 @@ GCPadStatus Adapter::GetPadStatus(int port, const std::array& adapter_pa adapter_controllers_status[port] = type; - constexpr std::array b1_buttons{ + static constexpr std::array b1_buttons{ PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, - PadButton::PAD_BUTTON_DOWN, PadButton::PAD_BUTTON_UP}; + PadButton::PAD_BUTTON_DOWN, PadButton::PAD_BUTTON_UP, + }; - constexpr std::array b2_buttons{ - PadButton::PAD_BUTTON_START, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R, - PadButton::PAD_TRIGGER_L}; + static constexpr std::array b2_buttons{ + PadButton::PAD_BUTTON_START, + PadButton::PAD_TRIGGER_Z, + PadButton::PAD_TRIGGER_R, + PadButton::PAD_TRIGGER_L, + }; if (adapter_controllers_status[port] != ControllerTypes::None) { const u8 b1 = adapter_payload[1 + (9 * port) + 1]; const u8 b2 = adapter_payload[1 + (9 * port) + 2]; for (std::size_t i = 0; i < b1_buttons.size(); ++i) { - if (b1 & (1 << i)) { + if ((b1 & (1U << i)) != 0) { pad.button |= static_cast(b1_buttons[i]); } } for (std::size_t j = 0; j < b2_buttons.size(); ++j) { - if (b2 & (1 << j)) { + if ((b2 & (1U << j)) != 0) { pad.button |= static_cast(b2_buttons[j]); } } @@ -107,7 +119,7 @@ void Adapter::Read() { if (payload_size_copy != sizeof(adapter_payload_copy) || adapter_payload_copy[0] != LIBUSB_DT_HID) { - LOG_ERROR(Input, "error reading payload (size: %d, type: %02x)", payload_size_copy, + LOG_ERROR(Input, "error reading payload (size: {}, type: {:02x})", payload_size_copy, adapter_payload_copy[0]); adapter_thread_running = false; // error reading from adapter, stop reading. break; @@ -220,7 +232,7 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { const int get_descriptor_error = libusb_get_device_descriptor(device, &desc); if (get_descriptor_error) { // could not acquire the descriptor, no point in trying to use it. - LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: %d", + LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: {}", get_descriptor_error); return false; } @@ -232,12 +244,12 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { const int open_error = libusb_open(device, &usb_adapter_handle); if (open_error == LIBUSB_ERROR_ACCESS) { - LOG_ERROR(Input, "Yuzu can not gain access to this device: ID %04X:%04X.", desc.idVendor, - desc.idProduct); + LOG_ERROR(Input, "Yuzu can not gain access to this device: ID {:04X}:{:04X}.", + desc.idVendor, desc.idProduct); return false; } if (open_error) { - LOG_ERROR(Input, "libusb_open failed to open device with error = %d", open_error); + LOG_ERROR(Input, "libusb_open failed to open device with error = {}", open_error); return false; } @@ -245,7 +257,7 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { if (kernel_driver_error == 1) { kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0); if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) { - LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = %d", + LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}", kernel_driver_error); } } @@ -258,7 +270,7 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) { const int interface_claim_error = libusb_claim_interface(usb_adapter_handle, 0); if (interface_claim_error) { - LOG_ERROR(Input, "libusb_claim_interface failed with error = %d", interface_claim_error); + LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error); libusb_close(usb_adapter_handle); usb_adapter_handle = nullptr; return false; diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 4a8e2644c2..161d522ac3 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -36,12 +36,7 @@ enum class PadButton { PAD_STICK = 0x2000, }; -/// Used to loop through the and assign button in poller -static constexpr std::array PadButtonArray{ - PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, PadButton::PAD_BUTTON_DOWN, - PadButton::PAD_BUTTON_UP, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R, - PadButton::PAD_TRIGGER_L, PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, - PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_START}; +extern const std::array PadButtonArray; enum class PadAxes : u8 { StickX, diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp index a04c507b84..385ce84301 100644 --- a/src/input_common/gcadapter/gc_poller.cpp +++ b/src/input_common/gcadapter/gc_poller.cpp @@ -14,7 +14,7 @@ namespace InputCommon { class GCButton final : public Input::ButtonDevice { public: - explicit GCButton(int port_, int button_, int axis_, GCAdapter::Adapter* adapter) + explicit GCButton(int port_, int button_, GCAdapter::Adapter* adapter) : port(port_), button(button_), gcadapter(adapter) {} ~GCButton() override; @@ -45,7 +45,9 @@ public: bool GetStatus() const override { const float axis_value = (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 128.0f; if (trigger_if_greater) { - return axis_value > threshold; // TODO(ameerj) : Fix threshold. + // TODO: Might be worthwile to set a slider for the trigger threshold. It is currently + // always set to 0.5 in configure_input_player.cpp ZL/ZR HandleClick + return axis_value > threshold; } return axis_value < -threshold; } @@ -71,8 +73,7 @@ std::unique_ptr GCButtonFactory::Create(const Common::Param // button is not an axis/stick button if (button_id != PAD_STICK_ID) { - std::unique_ptr button = - std::make_unique(port, button_id, params.Get("axis", 0), adapter.get()); + auto button = std::make_unique(port, button_id, adapter.get()); return std::move(button); } From d00972fce1fe5f2eb13c7e5d7e4e56036cb6bc91 Mon Sep 17 00:00:00 2001 From: Ameer Date: Sat, 4 Jul 2020 00:40:48 -0400 Subject: [PATCH 27/27] Fix for always firing triggers on some controllers, trigger threshold more universal --- src/input_common/gcadapter/gc_adapter.cpp | 6 ++---- src/input_common/gcadapter/gc_adapter.h | 4 +++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp index f58b0e11c1..b39d2a3fb4 100644 --- a/src/input_common/gcadapter/gc_adapter.cpp +++ b/src/input_common/gcadapter/gc_adapter.cpp @@ -156,14 +156,12 @@ void Adapter::Read() { pads[port].axis_value = pads[port].substick_y; pad_queue[port].Push(pads[port]); } - if (pads[port].trigger_left > pads[port].TRIGGER_CENTER + pads[port].THRESHOLD || - pads[port].trigger_left < pads[port].TRIGGER_CENTER - pads[port].THRESHOLD) { + if (pads[port].trigger_left > pads[port].TRIGGER_THRESHOLD) { pads[port].axis = GCAdapter::PadAxes::TriggerLeft; pads[port].axis_value = pads[port].trigger_left; pad_queue[port].Push(pads[port]); } - if (pads[port].trigger_right > pads[port].TRIGGER_CENTER + pads[port].THRESHOLD || - pads[port].trigger_right < pads[port].TRIGGER_CENTER - pads[port].THRESHOLD) { + if (pads[port].trigger_right > pads[port].TRIGGER_THRESHOLD) { pads[port].axis = GCAdapter::PadAxes::TriggerRight; pads[port].axis_value = pads[port].trigger_right; pad_queue[port].Push(pads[port]); diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h index 161d522ac3..0ea6263ebd 100644 --- a/src/input_common/gcadapter/gc_adapter.h +++ b/src/input_common/gcadapter/gc_adapter.h @@ -63,9 +63,11 @@ struct GCPadStatus { static constexpr u8 C_STICK_CENTER_X = 0x80; static constexpr u8 C_STICK_CENTER_Y = 0x80; static constexpr u8 C_STICK_RADIUS = 0x7f; - static constexpr u8 TRIGGER_CENTER = 20; static constexpr u8 THRESHOLD = 10; + // 256/4, at least a quarter press to count as a press. For polling mostly + static constexpr u8 TRIGGER_THRESHOLD = 64; + u8 port{}; PadAxes axis{PadAxes::Undefined}; u8 axis_value{255};