summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar german772021-09-20 17:22:07 -0500
committerGravatar Narr the Reg2021-11-24 20:30:22 -0600
commit395e9a449d338e56ade9ea88ffeed297a7d86b10 (patch)
tree74b7257d84bbb368d180fd230293501535509da1
parentinput_common: Rewrite touch (diff)
downloadyuzu-395e9a449d338e56ade9ea88ffeed297a7d86b10.tar.gz
yuzu-395e9a449d338e56ade9ea88ffeed297a7d86b10.tar.xz
yuzu-395e9a449d338e56ade9ea88ffeed297a7d86b10.zip
input_common: Rewrite gc_adapter
-rw-r--r--src/input_common/CMakeLists.txt6
-rw-r--r--src/input_common/drivers/gc_adapter.cpp (renamed from src/input_common/gcadapter/gc_adapter.cpp)419
-rw-r--r--src/input_common/drivers/gc_adapter.h128
-rw-r--r--src/input_common/drivers/tas_input.cpp320
-rw-r--r--src/input_common/drivers/tas_input.h200
-rw-r--r--src/input_common/gcadapter/gc_adapter.h168
-rw-r--r--src/input_common/gcadapter/gc_poller.cpp356
-rw-r--r--src/input_common/gcadapter/gc_poller.h78
8 files changed, 848 insertions, 827 deletions
diff --git a/src/input_common/CMakeLists.txt b/src/input_common/CMakeLists.txt
index 71091767d..c8871513c 100644
--- a/src/input_common/CMakeLists.txt
+++ b/src/input_common/CMakeLists.txt
@@ -1,4 +1,6 @@
1add_library(input_common STATIC 1add_library(input_common STATIC
2 drivers/gc_adapter.cpp
3 drivers/gc_adapter.h
2 drivers/keyboard.cpp 4 drivers/keyboard.cpp
3 drivers/keyboard.h 5 drivers/keyboard.h
4 drivers/mouse.cpp 6 drivers/mouse.cpp
@@ -23,10 +25,6 @@ add_library(input_common STATIC
23 motion_from_button.h 25 motion_from_button.h
24 motion_input.cpp 26 motion_input.cpp
25 motion_input.h 27 motion_input.h
26 gcadapter/gc_adapter.cpp
27 gcadapter/gc_adapter.h
28 gcadapter/gc_poller.cpp
29 gcadapter/gc_poller.h
30 sdl/sdl.cpp 28 sdl/sdl.cpp
31 sdl/sdl.h 29 sdl/sdl.h
32 tas/tas_input.cpp 30 tas/tas_input.cpp
diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/drivers/gc_adapter.cpp
index a2f1bb67c..6721ba4f7 100644
--- a/src/input_common/gcadapter/gc_adapter.cpp
+++ b/src/input_common/drivers/gc_adapter.cpp
@@ -2,47 +2,103 @@
2// Licensed under GPLv2+ 2// Licensed under GPLv2+
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <chrono> 5#include <fmt/format.h>
6#include <thread>
7
8#include <libusb.h> 6#include <libusb.h>
9 7
10#include "common/logging/log.h" 8#include "common/logging/log.h"
11#include "common/param_package.h" 9#include "common/param_package.h"
12#include "common/settings_input.h" 10#include "common/settings_input.h"
13#include "input_common/gcadapter/gc_adapter.h" 11#include "common/thread.h"
12#include "input_common/drivers/gc_adapter.h"
13
14namespace InputCommon {
15
16class LibUSBContext {
17public:
18 explicit LibUSBContext() {
19 init_result = libusb_init(&ctx);
20 }
21
22 ~LibUSBContext() {
23 libusb_exit(ctx);
24 }
25
26 LibUSBContext& operator=(const LibUSBContext&) = delete;
27 LibUSBContext(const LibUSBContext&) = delete;
28
29 LibUSBContext& operator=(LibUSBContext&&) noexcept = delete;
30 LibUSBContext(LibUSBContext&&) noexcept = delete;
31
32 [[nodiscard]] int InitResult() const noexcept {
33 return init_result;
34 }
35
36 [[nodiscard]] libusb_context* get() noexcept {
37 return ctx;
38 }
39
40private:
41 libusb_context* ctx;
42 int init_result{};
43};
44
45class LibUSBDeviceHandle {
46public:
47 explicit LibUSBDeviceHandle(libusb_context* ctx, uint16_t vid, uint16_t pid) noexcept {
48 handle = libusb_open_device_with_vid_pid(ctx, vid, pid);
49 }
50
51 ~LibUSBDeviceHandle() noexcept {
52 if (handle) {
53 libusb_release_interface(handle, 1);
54 libusb_close(handle);
55 }
56 }
14 57
15namespace GCAdapter { 58 LibUSBDeviceHandle& operator=(const LibUSBDeviceHandle&) = delete;
59 LibUSBDeviceHandle(const LibUSBDeviceHandle&) = delete;
16 60
17Adapter::Adapter() { 61 LibUSBDeviceHandle& operator=(LibUSBDeviceHandle&&) noexcept = delete;
18 if (usb_adapter_handle != nullptr) { 62 LibUSBDeviceHandle(LibUSBDeviceHandle&&) noexcept = delete;
63
64 [[nodiscard]] libusb_device_handle* get() noexcept {
65 return handle;
66 }
67
68private:
69 libusb_device_handle* handle{};
70};
71
72GCAdapter::GCAdapter(const std::string input_engine_) : InputEngine(input_engine_) {
73 if (usb_adapter_handle) {
19 return; 74 return;
20 } 75 }
21 LOG_INFO(Input, "GC Adapter Initialization started"); 76 LOG_INFO(Input, "GC Adapter Initialization started");
22 77
23 const int init_res = libusb_init(&libusb_ctx); 78 libusb_ctx = std::make_unique<LibUSBContext>();
79 const int init_res = libusb_ctx->InitResult();
24 if (init_res == LIBUSB_SUCCESS) { 80 if (init_res == LIBUSB_SUCCESS) {
25 adapter_scan_thread = std::thread(&Adapter::AdapterScanThread, this); 81 adapter_scan_thread =
82 std::jthread([this](std::stop_token stop_token) { AdapterScanThread(stop_token); });
26 } else { 83 } else {
27 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res); 84 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res);
28 } 85 }
29} 86}
30 87
31Adapter::~Adapter() { 88GCAdapter::~GCAdapter() {
32 Reset(); 89 Reset();
33} 90}
34 91
35void Adapter::AdapterInputThread() { 92void GCAdapter::AdapterInputThread(std::stop_token stop_token) {
36 LOG_DEBUG(Input, "GC Adapter input thread started"); 93 LOG_DEBUG(Input, "GC Adapter input thread started");
94 Common::SetCurrentThreadName("yuzu:input:GCAdapter");
37 s32 payload_size{}; 95 s32 payload_size{};
38 AdapterPayload adapter_payload{}; 96 AdapterPayload adapter_payload{};
39 97
40 if (adapter_scan_thread.joinable()) { 98 adapter_scan_thread = {};
41 adapter_scan_thread.join();
42 }
43 99
44 while (adapter_input_thread_running) { 100 while (!stop_token.stop_requested()) {
45 libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(), 101 libusb_interrupt_transfer(usb_adapter_handle->get(), input_endpoint, adapter_payload.data(),
46 static_cast<s32>(adapter_payload.size()), &payload_size, 16); 102 static_cast<s32>(adapter_payload.size()), &payload_size, 16);
47 if (IsPayloadCorrect(adapter_payload, payload_size)) { 103 if (IsPayloadCorrect(adapter_payload, payload_size)) {
48 UpdateControllers(adapter_payload); 104 UpdateControllers(adapter_payload);
@@ -52,19 +108,20 @@ void Adapter::AdapterInputThread() {
52 } 108 }
53 109
54 if (restart_scan_thread) { 110 if (restart_scan_thread) {
55 adapter_scan_thread = std::thread(&Adapter::AdapterScanThread, this); 111 adapter_scan_thread =
112 std::jthread([this](std::stop_token token) { AdapterScanThread(token); });
56 restart_scan_thread = false; 113 restart_scan_thread = false;
57 } 114 }
58} 115}
59 116
60bool Adapter::IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size) { 117bool GCAdapter::IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size) {
61 if (payload_size != static_cast<s32>(adapter_payload.size()) || 118 if (payload_size != static_cast<s32>(adapter_payload.size()) ||
62 adapter_payload[0] != LIBUSB_DT_HID) { 119 adapter_payload[0] != LIBUSB_DT_HID) {
63 LOG_DEBUG(Input, "Error reading payload (size: {}, type: {:02x})", payload_size, 120 LOG_DEBUG(Input, "Error reading payload (size: {}, type: {:02x})", payload_size,
64 adapter_payload[0]); 121 adapter_payload[0]);
65 if (input_error_counter++ > 20) { 122 if (input_error_counter++ > 20) {
66 LOG_ERROR(Input, "GC adapter timeout, Is the adapter connected?"); 123 LOG_ERROR(Input, "GC adapter timeout, Is the adapter connected?");
67 adapter_input_thread_running = false; 124 adapter_input_thread.request_stop();
68 restart_scan_thread = true; 125 restart_scan_thread = true;
69 } 126 }
70 return false; 127 return false;
@@ -74,7 +131,7 @@ bool Adapter::IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payloa
74 return true; 131 return true;
75} 132}
76 133
77void Adapter::UpdateControllers(const AdapterPayload& adapter_payload) { 134void GCAdapter::UpdateControllers(const AdapterPayload& adapter_payload) {
78 for (std::size_t port = 0; port < pads.size(); ++port) { 135 for (std::size_t port = 0; port < pads.size(); ++port) {
79 const std::size_t offset = 1 + (9 * port); 136 const std::size_t offset = 1 + (9 * port);
80 const auto type = static_cast<ControllerTypes>(adapter_payload[offset] >> 4); 137 const auto type = static_cast<ControllerTypes>(adapter_payload[offset] >> 4);
@@ -84,23 +141,21 @@ void Adapter::UpdateControllers(const AdapterPayload& adapter_payload) {
84 const u8 b2 = adapter_payload[offset + 2]; 141 const u8 b2 = adapter_payload[offset + 2];
85 UpdateStateButtons(port, b1, b2); 142 UpdateStateButtons(port, b1, b2);
86 UpdateStateAxes(port, adapter_payload); 143 UpdateStateAxes(port, adapter_payload);
87 if (configuring) {
88 UpdateYuzuSettings(port);
89 }
90 } 144 }
91 } 145 }
92} 146}
93 147
94void Adapter::UpdatePadType(std::size_t port, ControllerTypes pad_type) { 148void GCAdapter::UpdatePadType(std::size_t port, ControllerTypes pad_type) {
95 if (pads[port].type == pad_type) { 149 if (pads[port].type == pad_type) {
96 return; 150 return;
97 } 151 }
98 // Device changed reset device and set new type 152 // Device changed reset device and set new type
99 ResetDevice(port); 153 pads[port] = {};
100 pads[port].type = pad_type; 154 pads[port].type = pad_type;
101} 155}
102 156
103void Adapter::UpdateStateButtons(std::size_t port, u8 b1, u8 b2) { 157void GCAdapter::UpdateStateButtons(std::size_t port, [[maybe_unused]] u8 b1,
158 [[maybe_unused]] u8 b2) {
104 if (port >= pads.size()) { 159 if (port >= pads.size()) {
105 return; 160 return;
106 } 161 }
@@ -116,25 +171,21 @@ void Adapter::UpdateStateButtons(std::size_t port, u8 b1, u8 b2) {
116 PadButton::TriggerR, 171 PadButton::TriggerR,
117 PadButton::TriggerL, 172 PadButton::TriggerL,
118 }; 173 };
119 pads[port].buttons = 0; 174
120 for (std::size_t i = 0; i < b1_buttons.size(); ++i) { 175 for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
121 if ((b1 & (1U << i)) != 0) { 176 const bool button_status = (b1 & (1U << i)) != 0;
122 pads[port].buttons = 177 const int button = static_cast<int>(b1_buttons[i]);
123 static_cast<u16>(pads[port].buttons | static_cast<u16>(b1_buttons[i])); 178 SetButton(pads[port].identifier, button, button_status);
124 pads[port].last_button = b1_buttons[i];
125 }
126 } 179 }
127 180
128 for (std::size_t j = 0; j < b2_buttons.size(); ++j) { 181 for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
129 if ((b2 & (1U << j)) != 0) { 182 const bool button_status = (b2 & (1U << j)) != 0;
130 pads[port].buttons = 183 const int button = static_cast<int>(b2_buttons[j]);
131 static_cast<u16>(pads[port].buttons | static_cast<u16>(b2_buttons[j])); 184 SetButton(pads[port].identifier, button, button_status);
132 pads[port].last_button = b2_buttons[j];
133 }
134 } 185 }
135} 186}
136 187
137void Adapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload) { 188void GCAdapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload) {
138 if (port >= pads.size()) { 189 if (port >= pads.size()) {
139 return; 190 return;
140 } 191 }
@@ -155,134 +206,70 @@ void Adapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_pa
155 pads[port].axis_origin[index] = axis_value; 206 pads[port].axis_origin[index] = axis_value;
156 pads[port].reset_origin_counter++; 207 pads[port].reset_origin_counter++;
157 } 208 }
158 pads[port].axis_values[index] = 209 const f32 axis_status = (axis_value - pads[port].axis_origin[index]) / 110.0f;
159 static_cast<s16>(axis_value - pads[port].axis_origin[index]); 210 SetAxis(pads[port].identifier, static_cast<int>(index), axis_status);
160 }
161}
162
163void Adapter::UpdateYuzuSettings(std::size_t port) {
164 if (port >= pads.size()) {
165 return;
166 }
167
168 constexpr u8 axis_threshold = 50;
169 GCPadStatus pad_status = {.port = port};
170
171 if (pads[port].buttons != 0) {
172 pad_status.button = pads[port].last_button;
173 pad_queue.Push(pad_status);
174 }
175
176 // Accounting for a threshold here to ensure an intentional press
177 for (std::size_t i = 0; i < pads[port].axis_values.size(); ++i) {
178 const s16 value = pads[port].axis_values[i];
179
180 if (value > axis_threshold || value < -axis_threshold) {
181 pad_status.axis = static_cast<PadAxes>(i);
182 pad_status.axis_value = value;
183 pad_status.axis_threshold = axis_threshold;
184 pad_queue.Push(pad_status);
185 }
186 }
187}
188
189void Adapter::UpdateVibrations() {
190 // Use 8 states to keep the switching between on/off fast enough for
191 // a human to not notice the difference between switching from on/off
192 // More states = more rumble strengths = slower update time
193 constexpr u8 vibration_states = 8;
194
195 vibration_counter = (vibration_counter + 1) % vibration_states;
196
197 for (GCController& pad : pads) {
198 const bool vibrate = pad.rumble_amplitude > vibration_counter;
199 vibration_changed |= vibrate != pad.enable_vibration;
200 pad.enable_vibration = vibrate;
201 }
202 SendVibrations();
203}
204
205void Adapter::SendVibrations() {
206 if (!rumble_enabled || !vibration_changed) {
207 return;
208 }
209 s32 size{};
210 constexpr u8 rumble_command = 0x11;
211 const u8 p1 = pads[0].enable_vibration;
212 const u8 p2 = pads[1].enable_vibration;
213 const u8 p3 = pads[2].enable_vibration;
214 const u8 p4 = pads[3].enable_vibration;
215 std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
216 const int err = libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, payload.data(),
217 static_cast<s32>(payload.size()), &size, 16);
218 if (err) {
219 LOG_DEBUG(Input, "Adapter libusb write failed: {}", libusb_error_name(err));
220 if (output_error_counter++ > 5) {
221 LOG_ERROR(Input, "GC adapter output timeout, Rumble disabled");
222 rumble_enabled = false;
223 }
224 return;
225 } 211 }
226 output_error_counter = 0;
227 vibration_changed = false;
228}
229
230bool Adapter::RumblePlay(std::size_t port, u8 amplitude) {
231 pads[port].rumble_amplitude = amplitude;
232
233 return rumble_enabled;
234} 212}
235 213
236void Adapter::AdapterScanThread() { 214void GCAdapter::AdapterScanThread(std::stop_token stop_token) {
237 adapter_scan_thread_running = true; 215 Common::SetCurrentThreadName("yuzu:input:ScanGCAdapter");
238 adapter_input_thread_running = false; 216 usb_adapter_handle = nullptr;
239 if (adapter_input_thread.joinable()) { 217 pads = {};
240 adapter_input_thread.join(); 218 while (!stop_token.stop_requested() && !Setup()) {
241 } 219 std::this_thread::sleep_for(std::chrono::seconds(2));
242 ClearLibusbHandle();
243 ResetDevices();
244 while (adapter_scan_thread_running && !adapter_input_thread_running) {
245 Setup();
246 std::this_thread::sleep_for(std::chrono::seconds(1));
247 } 220 }
248} 221}
249 222
250void Adapter::Setup() { 223bool GCAdapter::Setup() {
251 usb_adapter_handle = libusb_open_device_with_vid_pid(libusb_ctx, 0x057e, 0x0337); 224 constexpr u16 nintendo_vid = 0x057e;
252 225 constexpr u16 gc_adapter_pid = 0x0337;
253 if (usb_adapter_handle == NULL) { 226 usb_adapter_handle =
254 return; 227 std::make_unique<LibUSBDeviceHandle>(libusb_ctx->get(), nintendo_vid, gc_adapter_pid);
228 if (!usb_adapter_handle->get()) {
229 return false;
255 } 230 }
256 if (!CheckDeviceAccess()) { 231 if (!CheckDeviceAccess()) {
257 ClearLibusbHandle(); 232 usb_adapter_handle = nullptr;
258 return; 233 return false;
259 } 234 }
260 235
261 libusb_device* device = libusb_get_device(usb_adapter_handle); 236 libusb_device* const device = libusb_get_device(usb_adapter_handle->get());
262 237
263 LOG_INFO(Input, "GC adapter is now connected"); 238 LOG_INFO(Input, "GC adapter is now connected");
264 // GC Adapter found and accessible, registering it 239 // GC Adapter found and accessible, registering it
265 if (GetGCEndpoint(device)) { 240 if (GetGCEndpoint(device)) {
266 adapter_scan_thread_running = false;
267 adapter_input_thread_running = true;
268 rumble_enabled = true; 241 rumble_enabled = true;
269 input_error_counter = 0; 242 input_error_counter = 0;
270 output_error_counter = 0; 243 output_error_counter = 0;
271 adapter_input_thread = std::thread(&Adapter::AdapterInputThread, this); 244
245 std::size_t port = 0;
246 for (GCController& pad : pads) {
247 pad.identifier = {
248 .guid = Common::UUID{""},
249 .port = port++,
250 .pad = 0,
251 };
252 PreSetController(pad.identifier);
253 }
254
255 adapter_input_thread =
256 std::jthread([this](std::stop_token stop_token) { AdapterInputThread(stop_token); });
257 return true;
272 } 258 }
259 return false;
273} 260}
274 261
275bool Adapter::CheckDeviceAccess() { 262bool GCAdapter::CheckDeviceAccess() {
276 // This fixes payload problems from offbrand GCAdapters 263 // This fixes payload problems from offbrand GCAdapters
277 const s32 control_transfer_error = 264 const s32 control_transfer_error =
278 libusb_control_transfer(usb_adapter_handle, 0x21, 11, 0x0001, 0, nullptr, 0, 1000); 265 libusb_control_transfer(usb_adapter_handle->get(), 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
279 if (control_transfer_error < 0) { 266 if (control_transfer_error < 0) {
280 LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error); 267 LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error);
281 } 268 }
282 269
283 s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle, 0); 270 s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle->get(), 0);
284 if (kernel_driver_error == 1) { 271 if (kernel_driver_error == 1) {
285 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0); 272 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle->get(), 0);
286 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) { 273 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
287 LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}", 274 LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
288 kernel_driver_error); 275 kernel_driver_error);
@@ -290,15 +277,13 @@ bool Adapter::CheckDeviceAccess() {
290 } 277 }
291 278
292 if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) { 279 if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
293 libusb_close(usb_adapter_handle);
294 usb_adapter_handle = nullptr; 280 usb_adapter_handle = nullptr;
295 return false; 281 return false;
296 } 282 }
297 283
298 const int interface_claim_error = libusb_claim_interface(usb_adapter_handle, 0); 284 const int interface_claim_error = libusb_claim_interface(usb_adapter_handle->get(), 0);
299 if (interface_claim_error) { 285 if (interface_claim_error) {
300 LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error); 286 LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
301 libusb_close(usb_adapter_handle);
302 usb_adapter_handle = nullptr; 287 usb_adapter_handle = nullptr;
303 return false; 288 return false;
304 } 289 }
@@ -306,7 +291,7 @@ bool Adapter::CheckDeviceAccess() {
306 return true; 291 return true;
307} 292}
308 293
309bool Adapter::GetGCEndpoint(libusb_device* device) { 294bool GCAdapter::GetGCEndpoint(libusb_device* device) {
310 libusb_config_descriptor* config = nullptr; 295 libusb_config_descriptor* config = nullptr;
311 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config); 296 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
312 if (config_descriptor_return != LIBUSB_SUCCESS) { 297 if (config_descriptor_return != LIBUSB_SUCCESS) {
@@ -332,68 +317,83 @@ bool Adapter::GetGCEndpoint(libusb_device* device) {
332 // This transfer seems to be responsible for clearing the state of the adapter 317 // This transfer seems to be responsible for clearing the state of the adapter
333 // Used to clear the "busy" state of when the device is unexpectedly unplugged 318 // Used to clear the "busy" state of when the device is unexpectedly unplugged
334 unsigned char clear_payload = 0x13; 319 unsigned char clear_payload = 0x13;
335 libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, &clear_payload, 320 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, &clear_payload,
336 sizeof(clear_payload), nullptr, 16); 321 sizeof(clear_payload), nullptr, 16);
337 return true; 322 return true;
338} 323}
339 324
340void Adapter::JoinThreads() { 325bool GCAdapter::SetRumble(const PadIdentifier& identifier, const Input::VibrationStatus vibration) {
341 restart_scan_thread = false; 326 const auto mean_amplitude = (vibration.low_amplitude + vibration.high_amplitude) * 0.5f;
342 adapter_input_thread_running = false; 327 const auto processed_amplitude =
343 adapter_scan_thread_running = false; 328 static_cast<u8>((mean_amplitude + std::pow(mean_amplitude, 0.3f)) * 0.5f * 0x8);
344
345 if (adapter_scan_thread.joinable()) {
346 adapter_scan_thread.join();
347 }
348 329
349 if (adapter_input_thread.joinable()) { 330 pads[identifier.port].rumble_amplitude = processed_amplitude;
350 adapter_input_thread.join(); 331 return rumble_enabled;
351 }
352} 332}
353 333
354void Adapter::ClearLibusbHandle() { 334void GCAdapter::UpdateVibrations() {
355 if (usb_adapter_handle) { 335 // Use 8 states to keep the switching between on/off fast enough for
356 libusb_release_interface(usb_adapter_handle, 1); 336 // a human to feel different vibration strenght
357 libusb_close(usb_adapter_handle); 337 // More states == more rumble strengths == slower update time
358 usb_adapter_handle = nullptr; 338 constexpr u8 vibration_states = 8;
339
340 vibration_counter = (vibration_counter + 1) % vibration_states;
341
342 for (GCController& pad : pads) {
343 const bool vibrate = pad.rumble_amplitude > vibration_counter;
344 vibration_changed |= vibrate != pad.enable_vibration;
345 pad.enable_vibration = vibrate;
359 } 346 }
347 SendVibrations();
360} 348}
361 349
362void Adapter::ResetDevices() { 350void GCAdapter::SendVibrations() {
363 for (std::size_t i = 0; i < pads.size(); ++i) { 351 if (!rumble_enabled || !vibration_changed) {
364 ResetDevice(i); 352 return;
353 }
354 s32 size{};
355 constexpr u8 rumble_command = 0x11;
356 const u8 p1 = pads[0].enable_vibration;
357 const u8 p2 = pads[1].enable_vibration;
358 const u8 p3 = pads[2].enable_vibration;
359 const u8 p4 = pads[3].enable_vibration;
360 std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
361 const int err =
362 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, payload.data(),
363 static_cast<s32>(payload.size()), &size, 16);
364 if (err) {
365 LOG_DEBUG(Input, "Adapter libusb write failed: {}", libusb_error_name(err));
366 if (output_error_counter++ > 5) {
367 LOG_ERROR(Input, "GC adapter output timeout, Rumble disabled");
368 rumble_enabled = false;
369 }
370 return;
365 } 371 }
372 output_error_counter = 0;
373 vibration_changed = false;
366} 374}
367 375
368void Adapter::ResetDevice(std::size_t port) { 376bool GCAdapter::DeviceConnected(std::size_t port) const {
369 pads[port].type = ControllerTypes::None; 377 return pads[port].type != ControllerTypes::None;
370 pads[port].enable_vibration = false;
371 pads[port].rumble_amplitude = 0;
372 pads[port].buttons = 0;
373 pads[port].last_button = PadButton::Undefined;
374 pads[port].axis_values.fill(0);
375 pads[port].reset_origin_counter = 0;
376} 378}
377 379
378void Adapter::Reset() { 380void GCAdapter::Reset() {
379 JoinThreads(); 381 adapter_scan_thread = {};
380 ClearLibusbHandle(); 382 adapter_input_thread = {};
381 ResetDevices(); 383 usb_adapter_handle = nullptr;
382 384 pads = {};
383 if (libusb_ctx) { 385 libusb_ctx = nullptr;
384 libusb_exit(libusb_ctx);
385 }
386} 386}
387 387
388std::vector<Common::ParamPackage> Adapter::GetInputDevices() const { 388std::vector<Common::ParamPackage> GCAdapter::GetInputDevices() const {
389 std::vector<Common::ParamPackage> devices; 389 std::vector<Common::ParamPackage> devices;
390 for (std::size_t port = 0; port < pads.size(); ++port) { 390 for (std::size_t port = 0; port < pads.size(); ++port) {
391 if (!DeviceConnected(port)) { 391 if (!DeviceConnected(port)) {
392 continue; 392 continue;
393 } 393 }
394 std::string name = fmt::format("Gamecube Controller {}", port + 1); 394 const std::string name = fmt::format("Gamecube Controller {}", port + 1);
395 devices.emplace_back(Common::ParamPackage{ 395 devices.emplace_back(Common::ParamPackage{
396 {"class", "gcpad"}, 396 {"engine", "gcpad"},
397 {"display", std::move(name)}, 397 {"display", std::move(name)},
398 {"port", std::to_string(port)}, 398 {"port", std::to_string(port)},
399 }); 399 });
@@ -401,8 +401,7 @@ std::vector<Common::ParamPackage> Adapter::GetInputDevices() const {
401 return devices; 401 return devices;
402} 402}
403 403
404InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice( 404ButtonMapping GCAdapter::GetButtonMappingForDevice(const Common::ParamPackage& params) {
405 const Common::ParamPackage& params) const {
406 // This list is missing ZL/ZR since those are not considered buttons. 405 // This list is missing ZL/ZR since those are not considered buttons.
407 // We will add those afterwards 406 // We will add those afterwards
408 // This list also excludes any button that can't be really mapped 407 // This list also excludes any button that can't be really mapped
@@ -425,7 +424,7 @@ InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice(
425 return {}; 424 return {};
426 } 425 }
427 426
428 InputCommon::ButtonMapping mapping{}; 427 ButtonMapping mapping{};
429 for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) { 428 for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) {
430 Common::ParamPackage button_params({{"engine", "gcpad"}}); 429 Common::ParamPackage button_params({{"engine", "gcpad"}});
431 button_params.Set("port", params.Get("port", 0)); 430 button_params.Set("port", params.Get("port", 0));
@@ -434,30 +433,30 @@ InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice(
434 } 433 }
435 434
436 // Add the missing bindings for ZL/ZR 435 // Add the missing bindings for ZL/ZR
437 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadAxes>, 2> 436 static constexpr std::array<std::tuple<Settings::NativeButton::Values, PadButton, PadAxes>, 2>
438 switch_to_gcadapter_axis = { 437 switch_to_gcadapter_axis = {
439 std::pair{Settings::NativeButton::ZL, PadAxes::TriggerLeft}, 438 std::tuple{Settings::NativeButton::ZL, PadButton::TriggerL, PadAxes::TriggerLeft},
440 {Settings::NativeButton::ZR, PadAxes::TriggerRight}, 439 {Settings::NativeButton::ZR, PadButton::TriggerR, PadAxes::TriggerRight},
441 }; 440 };
442 for (const auto& [switch_button, gcadapter_axis] : switch_to_gcadapter_axis) { 441 for (const auto& [switch_button, gcadapter_buton, gcadapter_axis] : switch_to_gcadapter_axis) {
443 Common::ParamPackage button_params({{"engine", "gcpad"}}); 442 Common::ParamPackage button_params({{"engine", "gcpad"}});
444 button_params.Set("port", params.Get("port", 0)); 443 button_params.Set("port", params.Get("port", 0));
445 button_params.Set("button", static_cast<s32>(PadButton::Stick)); 444 button_params.Set("button", static_cast<s32>(gcadapter_buton));
446 button_params.Set("axis", static_cast<s32>(gcadapter_axis)); 445 button_params.Set("axis", static_cast<s32>(gcadapter_axis));
447 button_params.Set("threshold", 0.5f); 446 button_params.Set("threshold", 0.5f);
447 button_params.Set("range", 1.9f);
448 button_params.Set("direction", "+"); 448 button_params.Set("direction", "+");
449 mapping.insert_or_assign(switch_button, std::move(button_params)); 449 mapping.insert_or_assign(switch_button, std::move(button_params));
450 } 450 }
451 return mapping; 451 return mapping;
452} 452}
453 453
454InputCommon::AnalogMapping Adapter::GetAnalogMappingForDevice( 454AnalogMapping GCAdapter::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
455 const Common::ParamPackage& params) const {
456 if (!params.Has("port")) { 455 if (!params.Has("port")) {
457 return {}; 456 return {};
458 } 457 }
459 458
460 InputCommon::AnalogMapping mapping = {}; 459 AnalogMapping mapping = {};
461 Common::ParamPackage left_analog_params; 460 Common::ParamPackage left_analog_params;
462 left_analog_params.Set("engine", "gcpad"); 461 left_analog_params.Set("engine", "gcpad");
463 left_analog_params.Set("port", params.Get("port", 0)); 462 left_analog_params.Set("port", params.Get("port", 0));
@@ -473,34 +472,12 @@ InputCommon::AnalogMapping Adapter::GetAnalogMappingForDevice(
473 return mapping; 472 return mapping;
474} 473}
475 474
476bool Adapter::DeviceConnected(std::size_t port) const { 475std::string GCAdapter::GetUIName(const Common::ParamPackage& params) const {
477 return pads[port].type != ControllerTypes::None; 476 if (params.Has("button")) {
478} 477 return fmt::format("Button {}", params.Get("button", 0));
479 478 }
480void Adapter::BeginConfiguration() {
481 pad_queue.Clear();
482 configuring = true;
483}
484
485void Adapter::EndConfiguration() {
486 pad_queue.Clear();
487 configuring = false;
488}
489
490Common::SPSCQueue<GCPadStatus>& Adapter::GetPadQueue() {
491 return pad_queue;
492}
493
494const Common::SPSCQueue<GCPadStatus>& Adapter::GetPadQueue() const {
495 return pad_queue;
496}
497
498GCController& Adapter::GetPadState(std::size_t port) {
499 return pads.at(port);
500}
501 479
502const GCController& Adapter::GetPadState(std::size_t port) const { 480 return "Bad GC Adapter";
503 return pads.at(port);
504} 481}
505 482
506} // namespace GCAdapter 483} // namespace InputCommon
diff --git a/src/input_common/drivers/gc_adapter.h b/src/input_common/drivers/gc_adapter.h
new file mode 100644
index 000000000..c0bf1ed7a
--- /dev/null
+++ b/src/input_common/drivers/gc_adapter.h
@@ -0,0 +1,128 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <mutex>
8#include <stop_token>
9#include <thread>
10
11#include "input_common/input_engine.h"
12
13struct libusb_context;
14struct libusb_device;
15struct libusb_device_handle;
16
17namespace InputCommon {
18
19class LibUSBContext;
20class LibUSBDeviceHandle;
21
22class GCAdapter : public InputCommon::InputEngine {
23public:
24 explicit GCAdapter(const std::string input_engine_);
25 ~GCAdapter();
26
27 bool SetRumble(const PadIdentifier& identifier,
28 const Input::VibrationStatus vibration) override;
29
30 /// Used for automapping features
31 std::vector<Common::ParamPackage> GetInputDevices() const override;
32 ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) override;
33 AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) override;
34 std::string GetUIName(const Common::ParamPackage& params) const override;
35
36private:
37 enum class PadButton {
38 Undefined = 0x0000,
39 ButtonLeft = 0x0001,
40 ButtonRight = 0x0002,
41 ButtonDown = 0x0004,
42 ButtonUp = 0x0008,
43 TriggerZ = 0x0010,
44 TriggerR = 0x0020,
45 TriggerL = 0x0040,
46 ButtonA = 0x0100,
47 ButtonB = 0x0200,
48 ButtonX = 0x0400,
49 ButtonY = 0x0800,
50 ButtonStart = 0x1000,
51 };
52
53 enum class PadAxes : u8 {
54 StickX,
55 StickY,
56 SubstickX,
57 SubstickY,
58 TriggerLeft,
59 TriggerRight,
60 Undefined,
61 };
62
63 enum class ControllerTypes {
64 None,
65 Wired,
66 Wireless,
67 };
68
69 struct GCController {
70 ControllerTypes type = ControllerTypes::None;
71 PadIdentifier identifier{};
72 bool enable_vibration = false;
73 u8 rumble_amplitude{};
74 std::array<u8, 6> axis_origin{};
75 u8 reset_origin_counter{};
76 };
77
78 using AdapterPayload = std::array<u8, 37>;
79
80 void UpdatePadType(std::size_t port, ControllerTypes pad_type);
81 void UpdateControllers(const AdapterPayload& adapter_payload);
82 void UpdateStateButtons(std::size_t port, u8 b1, u8 b2);
83 void UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload);
84
85 void AdapterInputThread(std::stop_token stop_token);
86
87 void AdapterScanThread(std::stop_token stop_token);
88
89 bool IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size);
90
91 /// For use in initialization, querying devices to find the adapter
92 bool Setup();
93
94 /// Returns true if we successfully gain access to GC Adapter
95 bool CheckDeviceAccess();
96
97 /// Captures GC Adapter endpoint address
98 /// Returns true if the endpoint was set correctly
99 bool GetGCEndpoint(libusb_device* device);
100
101 /// Returns true if there is a device connected to port
102 bool DeviceConnected(std::size_t port) const;
103
104 /// For shutting down, clear all data, join all threads, release usb
105 void Reset();
106
107 void UpdateVibrations();
108 // Updates vibration state of all controllers
109 void SendVibrations();
110 std::unique_ptr<LibUSBDeviceHandle> usb_adapter_handle;
111 std::array<GCController, 4> pads;
112
113 std::jthread adapter_input_thread;
114 std::jthread adapter_scan_thread;
115 bool restart_scan_thread{};
116
117 std::unique_ptr<LibUSBContext> libusb_ctx;
118
119 u8 input_endpoint{0};
120 u8 output_endpoint{0};
121 u8 input_error_counter{0};
122 u8 output_error_counter{0};
123 int vibration_counter{0};
124
125 bool rumble_enabled{true};
126 bool vibration_changed{true};
127};
128} // namespace InputCommon
diff --git a/src/input_common/drivers/tas_input.cpp b/src/input_common/drivers/tas_input.cpp
new file mode 100644
index 000000000..5e2101b27
--- /dev/null
+++ b/src/input_common/drivers/tas_input.cpp
@@ -0,0 +1,320 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#include <cstring>
6#include <regex>
7#include <fmt/format.h>
8
9#include "common/fs/file.h"
10#include "common/fs/fs_types.h"
11#include "common/fs/path_util.h"
12#include "common/logging/log.h"
13#include "common/settings.h"
14#include "input_common/drivers/tas_input.h"
15
16namespace InputCommon::TasInput {
17
18enum TasAxes : u8 {
19 StickX,
20 StickY,
21 SubstickX,
22 SubstickY,
23 Undefined,
24};
25
26// Supported keywords and buttons from a TAS file
27constexpr std::array<std::pair<std::string_view, TasButton>, 20> text_to_tas_button = {
28 std::pair{"KEY_A", TasButton::BUTTON_A},
29 {"KEY_B", TasButton::BUTTON_B},
30 {"KEY_X", TasButton::BUTTON_X},
31 {"KEY_Y", TasButton::BUTTON_Y},
32 {"KEY_LSTICK", TasButton::STICK_L},
33 {"KEY_RSTICK", TasButton::STICK_R},
34 {"KEY_L", TasButton::TRIGGER_L},
35 {"KEY_R", TasButton::TRIGGER_R},
36 {"KEY_PLUS", TasButton::BUTTON_PLUS},
37 {"KEY_MINUS", TasButton::BUTTON_MINUS},
38 {"KEY_DLEFT", TasButton::BUTTON_LEFT},
39 {"KEY_DUP", TasButton::BUTTON_UP},
40 {"KEY_DRIGHT", TasButton::BUTTON_RIGHT},
41 {"KEY_DDOWN", TasButton::BUTTON_DOWN},
42 {"KEY_SL", TasButton::BUTTON_SL},
43 {"KEY_SR", TasButton::BUTTON_SR},
44 {"KEY_CAPTURE", TasButton::BUTTON_CAPTURE},
45 {"KEY_HOME", TasButton::BUTTON_HOME},
46 {"KEY_ZL", TasButton::TRIGGER_ZL},
47 {"KEY_ZR", TasButton::TRIGGER_ZR},
48};
49
50Tas::Tas(const std::string input_engine_) : InputCommon::InputEngine(input_engine_) {
51 for (size_t player_index = 0; player_index < PLAYER_NUMBER; player_index++) {
52 PadIdentifier identifier{
53 .guid = Common::UUID{},
54 .port = player_index,
55 .pad = 0,
56 };
57 PreSetController(identifier);
58 }
59 ClearInput();
60 if (!Settings::values.tas_enable) {
61 needs_reset = true;
62 return;
63 }
64 LoadTasFiles();
65}
66
67Tas::~Tas() {
68 Stop();
69};
70
71void Tas::LoadTasFiles() {
72 script_length = 0;
73 for (size_t i = 0; i < commands.size(); i++) {
74 LoadTasFile(i);
75 if (commands[i].size() > script_length) {
76 script_length = commands[i].size();
77 }
78 }
79}
80
81void Tas::LoadTasFile(size_t player_index) {
82 if (!commands[player_index].empty()) {
83 commands[player_index].clear();
84 }
85 std::string file =
86 Common::FS::ReadStringFromFile(Common::FS::GetYuzuPath(Common::FS::YuzuPath::TASDir) /
87 fmt::format("script0-{}.txt", player_index + 1),
88 Common::FS::FileType::BinaryFile);
89 std::stringstream command_line(file);
90 std::string line;
91 int frame_no = 0;
92 while (std::getline(command_line, line, '\n')) {
93 if (line.empty()) {
94 continue;
95 }
96 std::smatch m;
97
98 std::stringstream linestream(line);
99 std::string segment;
100 std::vector<std::string> seglist;
101
102 while (std::getline(linestream, segment, ' ')) {
103 seglist.push_back(segment);
104 }
105
106 if (seglist.size() < 4) {
107 continue;
108 }
109
110 while (frame_no < std::stoi(seglist.at(0))) {
111 commands[player_index].push_back({});
112 frame_no++;
113 }
114
115 TASCommand command = {
116 .buttons = ReadCommandButtons(seglist.at(1)),
117 .l_axis = ReadCommandAxis(seglist.at(2)),
118 .r_axis = ReadCommandAxis(seglist.at(3)),
119 };
120 commands[player_index].push_back(command);
121 frame_no++;
122 }
123 LOG_INFO(Input, "TAS file loaded! {} frames", frame_no);
124}
125
126void Tas::WriteTasFile(std::u8string file_name) {
127 std::string output_text;
128 for (size_t frame = 0; frame < record_commands.size(); frame++) {
129 const TASCommand& line = record_commands[frame];
130 output_text += fmt::format("{} {} {} {} {}\n", frame, WriteCommandButtons(line.buttons),
131 WriteCommandAxis(line.l_axis), WriteCommandAxis(line.r_axis));
132 }
133 const auto bytes_written = Common::FS::WriteStringToFile(
134 Common::FS::GetYuzuPath(Common::FS::YuzuPath::TASDir) / file_name,
135 Common::FS::FileType::TextFile, output_text);
136 if (bytes_written == output_text.size()) {
137 LOG_INFO(Input, "TAS file written to file!");
138 } else {
139 LOG_ERROR(Input, "Writing the TAS-file has failed! {} / {} bytes written", bytes_written,
140 output_text.size());
141 }
142}
143
144void Tas::RecordInput(u32 buttons, TasAnalog left_axis, TasAnalog right_axis) {
145 last_input = {
146 .buttons = buttons,
147 .l_axis = FlipAxisY(left_axis),
148 .r_axis = FlipAxisY(right_axis),
149 };
150}
151
152TasAnalog Tas::FlipAxisY(TasAnalog old) {
153 return {
154 .x = old.x,
155 .y = -old.y,
156 };
157}
158
159std::tuple<TasState, size_t, size_t> Tas::GetStatus() const {
160 TasState state;
161 if (is_recording) {
162 return {TasState::Recording, 0, record_commands.size()};
163 }
164
165 if (is_running) {
166 state = TasState::Running;
167 } else {
168 state = TasState::Stopped;
169 }
170
171 return {state, current_command, script_length};
172}
173
174void Tas::UpdateThread() {
175 if (!Settings::values.tas_enable) {
176 if (is_running) {
177 Stop();
178 }
179 return;
180 }
181
182 if (is_recording) {
183 record_commands.push_back(last_input);
184 }
185 if (needs_reset) {
186 current_command = 0;
187 needs_reset = false;
188 LoadTasFiles();
189 LOG_DEBUG(Input, "tas_reset done");
190 }
191
192 if (!is_running) {
193 ClearInput();
194 return;
195 }
196 if (current_command < script_length) {
197 LOG_DEBUG(Input, "Playing TAS {}/{}", current_command, script_length);
198 size_t frame = current_command++;
199 for (size_t player_index = 0; player_index < commands.size(); player_index++) {
200 TASCommand command{};
201 if (frame < commands[player_index].size()) {
202 command = commands[player_index][frame];
203 }
204
205 PadIdentifier identifier{
206 .guid = Common::UUID{},
207 .port = player_index,
208 .pad = 0,
209 };
210 for (std::size_t i = 0; i < sizeof(command.buttons); ++i) {
211 const bool button_status = (command.buttons & (1U << i)) != 0;
212 const int button = static_cast<int>(i);
213 SetButton(identifier, button, button_status);
214 }
215 SetAxis(identifier, TasAxes::StickX, command.l_axis.x);
216 SetAxis(identifier, TasAxes::StickY, command.l_axis.y);
217 SetAxis(identifier, TasAxes::SubstickX, command.r_axis.x);
218 SetAxis(identifier, TasAxes::SubstickY, command.r_axis.y);
219 }
220 } else {
221 is_running = Settings::values.tas_loop.GetValue();
222 current_command = 0;
223 ClearInput();
224 }
225}
226
227void Tas::ClearInput() {
228 ResetButtonState();
229 ResetAnalogState();
230}
231
232TasAnalog Tas::ReadCommandAxis(const std::string& line) const {
233 std::stringstream linestream(line);
234 std::string segment;
235 std::vector<std::string> seglist;
236
237 while (std::getline(linestream, segment, ';')) {
238 seglist.push_back(segment);
239 }
240
241 const float x = std::stof(seglist.at(0)) / 32767.0f;
242 const float y = std::stof(seglist.at(1)) / 32767.0f;
243
244 return {x, y};
245}
246
247u32 Tas::ReadCommandButtons(const std::string& data) const {
248 std::stringstream button_text(data);
249 std::string line;
250 u32 buttons = 0;
251 while (std::getline(button_text, line, ';')) {
252 for (auto [text, tas_button] : text_to_tas_button) {
253 if (text == line) {
254 buttons |= static_cast<u32>(tas_button);
255 break;
256 }
257 }
258 }
259 return buttons;
260}
261
262std::string Tas::WriteCommandButtons(u32 buttons) const {
263 std::string returns = "";
264 for (auto [text_button, tas_button] : text_to_tas_button) {
265 if ((buttons & static_cast<u32>(tas_button)) != 0)
266 returns += fmt::format("{};", text_button.substr(4));
267 }
268 return returns.empty() ? "NONE" : returns.substr(2);
269}
270
271std::string Tas::WriteCommandAxis(TasAnalog analog) const {
272 return fmt::format("{};{}", analog.x * 32767, analog.y * 32767);
273}
274
275void Tas::StartStop() {
276 if (!Settings::values.tas_enable) {
277 return;
278 }
279 if (is_running) {
280 Stop();
281 } else {
282 is_running = true;
283 }
284}
285
286void Tas::Stop() {
287 is_running = false;
288}
289
290void Tas::Reset() {
291 if (!Settings::values.tas_enable) {
292 return;
293 }
294 needs_reset = true;
295}
296
297bool Tas::Record() {
298 if (!Settings::values.tas_enable) {
299 return true;
300 }
301 is_recording = !is_recording;
302 return is_recording;
303}
304
305void Tas::SaveRecording(bool overwrite_file) {
306 if (is_recording) {
307 return;
308 }
309 if (record_commands.empty()) {
310 return;
311 }
312 WriteTasFile(u8"record.txt");
313 if (overwrite_file) {
314 WriteTasFile(u8"script0-1.txt");
315 }
316 needs_reset = true;
317 record_commands.clear();
318}
319
320} // namespace InputCommon::TasInput
diff --git a/src/input_common/drivers/tas_input.h b/src/input_common/drivers/tas_input.h
new file mode 100644
index 000000000..9fadc118b
--- /dev/null
+++ b/src/input_common/drivers/tas_input.h
@@ -0,0 +1,200 @@
1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8
9#include "common/common_types.h"
10#include "common/settings_input.h"
11#include "input_common/input_engine.h"
12#include "input_common/main.h"
13
14/*
15To play back TAS scripts on Yuzu, select the folder with scripts in the configuration menu below
16Tools -> Configure TAS. The file itself has normal text format and has to be called script0-1.txt
17for controller 1, script0-2.txt for controller 2 and so forth (with max. 8 players).
18
19A script file has the same format as TAS-nx uses, so final files will look like this:
20
211 KEY_B 0;0 0;0
226 KEY_ZL 0;0 0;0
2341 KEY_ZL;KEY_Y 0;0 0;0
2443 KEY_X;KEY_A 32767;0 0;0
2544 KEY_A 32767;0 0;0
2645 KEY_A 32767;0 0;0
2746 KEY_A 32767;0 0;0
2847 KEY_A 32767;0 0;0
29
30After placing the file at the correct location, it can be read into Yuzu with the (default) hotkey
31CTRL+F6 (refresh). In the bottom left corner, it will display the amount of frames the script file
32has. Playback can be started or stopped using CTRL+F5.
33
34However, for playback to actually work, the correct input device has to be selected: In the Controls
35menu, select TAS from the device list for the controller that the script should be played on.
36
37Recording a new script file is really simple: Just make sure that the proper device (not TAS) is
38connected on P1, and press CTRL+F7 to start recording. When done, just press the same keystroke
39again (CTRL+F7). The new script will be saved at the location previously selected, as the filename
40record.txt.
41
42For debugging purposes, the common controller debugger can be used (View -> Debugging -> Controller
43P1).
44*/
45
46namespace InputCommon::TasInput {
47
48constexpr size_t PLAYER_NUMBER = 10;
49
50enum class TasButton : u32 {
51 BUTTON_A = 1U << 0,
52 BUTTON_B = 1U << 1,
53 BUTTON_X = 1U << 2,
54 BUTTON_Y = 1U << 3,
55 STICK_L = 1U << 4,
56 STICK_R = 1U << 5,
57 TRIGGER_L = 1U << 6,
58 TRIGGER_R = 1U << 7,
59 TRIGGER_ZL = 1U << 8,
60 TRIGGER_ZR = 1U << 9,
61 BUTTON_PLUS = 1U << 10,
62 BUTTON_MINUS = 1U << 11,
63 BUTTON_LEFT = 1U << 12,
64 BUTTON_UP = 1U << 13,
65 BUTTON_RIGHT = 1U << 14,
66 BUTTON_DOWN = 1U << 15,
67 BUTTON_SL = 1U << 16,
68 BUTTON_SR = 1U << 17,
69 BUTTON_HOME = 1U << 18,
70 BUTTON_CAPTURE = 1U << 19,
71};
72
73struct TasAnalog {
74 float x{};
75 float y{};
76};
77
78enum class TasState {
79 Running,
80 Recording,
81 Stopped,
82};
83
84class Tas final : public InputCommon::InputEngine {
85public:
86 explicit Tas(const std::string input_engine_);
87 ~Tas();
88
89 /**
90 * Changes the input status that will be stored in each frame
91 * @param buttons: bitfield with the status of the buttons
92 * @param left_axis: value of the left axis
93 * @param right_axis: value of the right axis
94 */
95 void RecordInput(u32 buttons, TasAnalog left_axis, TasAnalog right_axis);
96
97 // Main loop that records or executes input
98 void UpdateThread();
99
100 // Sets the flag to start or stop the TAS command excecution and swaps controllers profiles
101 void StartStop();
102
103 // Stop the TAS and reverts any controller profile
104 void Stop();
105
106 // Sets the flag to reload the file and start from the begining in the next update
107 void Reset();
108
109 /**
110 * Sets the flag to enable or disable recording of inputs
111 * @return Returns true if the current recording status is enabled
112 */
113 bool Record();
114
115 /**
116 * Saves contents of record_commands on a file
117 * @param overwrite_file: Indicates if player 1 should be overwritten
118 */
119 void SaveRecording(bool overwrite_file);
120
121 /**
122 * Returns the current status values of TAS playback/recording
123 * @return Tuple of
124 * TasState indicating the current state out of Running ;
125 * Current playback progress ;
126 * Total length of script file currently loaded or being recorded
127 */
128 std::tuple<TasState, size_t, size_t> GetStatus() const;
129
130private:
131 struct TASCommand {
132 u32 buttons{};
133 TasAnalog l_axis{};
134 TasAnalog r_axis{};
135 };
136
137 /// Loads TAS files from all players
138 void LoadTasFiles();
139
140 /** Loads TAS file from the specified player
141 * @param player_index: player number where data is going to be stored
142 */
143 void LoadTasFile(size_t player_index);
144
145 /** Writes a TAS file from the recorded commands
146 * @param file_name: name of the file to be written
147 */
148 void WriteTasFile(std::u8string file_name);
149
150 /** Inverts the Y axis polarity
151 * @param old: value of the axis
152 * @return new value of the axis
153 */
154 TasAnalog FlipAxisY(TasAnalog old);
155
156 /**
157 * Parses a string containing the axis values. X and Y have a range from -32767 to 32767
158 * @param line: string containing axis values with the following format "x;y"
159 * @return Returns a TAS analog object with axis values with range from -1.0 to 1.0
160 */
161 TasAnalog ReadCommandAxis(const std::string& line) const;
162
163 /**
164 * Parses a string containing the button values. Each button is represented by it's text format
165 * specified in text_to_tas_button array
166 * @param line: string containing button name with the following format "a;b;c;d..."
167 * @return Returns a u32 with each bit representing the status of a button
168 */
169 u32 ReadCommandButtons(const std::string& line) const;
170
171 /**
172 * Reset state of all players
173 */
174 void ClearInput();
175
176 /**
177 * Converts an u32 containing the button status into the text equivalent
178 * @param buttons: bitfield with the status of the buttons
179 * @return Returns a string with the name of the buttons to be written to the file
180 */
181 std::string WriteCommandButtons(u32 buttons) const;
182
183 /**
184 * Converts an TAS analog object containing the axis status into the text equivalent
185 * @param data: value of the axis
186 * @return A string with the value of the axis to be written to the file
187 */
188 std::string WriteCommandAxis(TasAnalog data) const;
189
190 size_t script_length{0};
191 bool is_old_input_saved{false};
192 bool is_recording{false};
193 bool is_running{false};
194 bool needs_reset{false};
195 std::array<std::vector<TASCommand>, PLAYER_NUMBER> commands{};
196 std::vector<TASCommand> record_commands{};
197 size_t current_command{0};
198 TASCommand last_input{}; // only used for recording
199};
200} // namespace InputCommon::TasInput
diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h
deleted file mode 100644
index e5de5e94f..000000000
--- a/src/input_common/gcadapter/gc_adapter.h
+++ /dev/null
@@ -1,168 +0,0 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#pragma once
6#include <algorithm>
7#include <functional>
8#include <mutex>
9#include <thread>
10#include <unordered_map>
11#include "common/common_types.h"
12#include "common/threadsafe_queue.h"
13#include "input_common/main.h"
14
15struct libusb_context;
16struct libusb_device;
17struct libusb_device_handle;
18
19namespace GCAdapter {
20
21enum class PadButton {
22 Undefined = 0x0000,
23 ButtonLeft = 0x0001,
24 ButtonRight = 0x0002,
25 ButtonDown = 0x0004,
26 ButtonUp = 0x0008,
27 TriggerZ = 0x0010,
28 TriggerR = 0x0020,
29 TriggerL = 0x0040,
30 ButtonA = 0x0100,
31 ButtonB = 0x0200,
32 ButtonX = 0x0400,
33 ButtonY = 0x0800,
34 ButtonStart = 0x1000,
35 // Below is for compatibility with "AxisButton" type
36 Stick = 0x2000,
37};
38
39enum class PadAxes : u8 {
40 StickX,
41 StickY,
42 SubstickX,
43 SubstickY,
44 TriggerLeft,
45 TriggerRight,
46 Undefined,
47};
48
49enum class ControllerTypes {
50 None,
51 Wired,
52 Wireless,
53};
54
55struct GCPadStatus {
56 std::size_t port{};
57
58 PadButton button{PadButton::Undefined}; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits
59
60 PadAxes axis{PadAxes::Undefined};
61 s16 axis_value{};
62 u8 axis_threshold{50};
63};
64
65struct GCController {
66 ControllerTypes type{};
67 bool enable_vibration{};
68 u8 rumble_amplitude{};
69 u16 buttons{};
70 PadButton last_button{};
71 std::array<s16, 6> axis_values{};
72 std::array<u8, 6> axis_origin{};
73 u8 reset_origin_counter{};
74};
75
76class Adapter {
77public:
78 Adapter();
79 ~Adapter();
80
81 /// Request a vibration for a controller
82 bool RumblePlay(std::size_t port, u8 amplitude);
83
84 /// Used for polling
85 void BeginConfiguration();
86 void EndConfiguration();
87
88 Common::SPSCQueue<GCPadStatus>& GetPadQueue();
89 const Common::SPSCQueue<GCPadStatus>& GetPadQueue() const;
90
91 GCController& GetPadState(std::size_t port);
92 const GCController& GetPadState(std::size_t port) const;
93
94 /// Returns true if there is a device connected to port
95 bool DeviceConnected(std::size_t port) const;
96
97 /// Used for automapping features
98 std::vector<Common::ParamPackage> GetInputDevices() const;
99 InputCommon::ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) const;
100 InputCommon::AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) const;
101
102private:
103 using AdapterPayload = std::array<u8, 37>;
104
105 void UpdatePadType(std::size_t port, ControllerTypes pad_type);
106 void UpdateControllers(const AdapterPayload& adapter_payload);
107 void UpdateYuzuSettings(std::size_t port);
108 void UpdateStateButtons(std::size_t port, u8 b1, u8 b2);
109 void UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload);
110 void UpdateVibrations();
111
112 void AdapterInputThread();
113
114 void AdapterScanThread();
115
116 bool IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size);
117
118 // Updates vibration state of all controllers
119 void SendVibrations();
120
121 /// For use in initialization, querying devices to find the adapter
122 void Setup();
123
124 /// Resets status of all GC controller devices to a disconnected state
125 void ResetDevices();
126
127 /// Resets status of device connected to a disconnected state
128 void ResetDevice(std::size_t port);
129
130 /// Returns true if we successfully gain access to GC Adapter
131 bool CheckDeviceAccess();
132
133 /// Captures GC Adapter endpoint address
134 /// Returns true if the endpoint was set correctly
135 bool GetGCEndpoint(libusb_device* device);
136
137 /// For shutting down, clear all data, join all threads, release usb
138 void Reset();
139
140 // Join all threads
141 void JoinThreads();
142
143 // Release usb handles
144 void ClearLibusbHandle();
145
146 libusb_device_handle* usb_adapter_handle = nullptr;
147 std::array<GCController, 4> pads;
148 Common::SPSCQueue<GCPadStatus> pad_queue;
149
150 std::thread adapter_input_thread;
151 std::thread adapter_scan_thread;
152 bool adapter_input_thread_running;
153 bool adapter_scan_thread_running;
154 bool restart_scan_thread;
155
156 libusb_context* libusb_ctx;
157
158 u8 input_endpoint{0};
159 u8 output_endpoint{0};
160 u8 input_error_counter{0};
161 u8 output_error_counter{0};
162 int vibration_counter{0};
163
164 bool configuring{false};
165 bool rumble_enabled{true};
166 bool vibration_changed{true};
167};
168} // namespace GCAdapter
diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp
deleted file mode 100644
index 1b6ded8d6..000000000
--- a/src/input_common/gcadapter/gc_poller.cpp
+++ /dev/null
@@ -1,356 +0,0 @@
1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <atomic>
6#include <list>
7#include <mutex>
8#include <utility>
9#include "common/assert.h"
10#include "common/threadsafe_queue.h"
11#include "input_common/gcadapter/gc_adapter.h"
12#include "input_common/gcadapter/gc_poller.h"
13
14namespace InputCommon {
15
16class GCButton final : public Input::ButtonDevice {
17public:
18 explicit GCButton(u32 port_, s32 button_, const GCAdapter::Adapter* adapter)
19 : port(port_), button(button_), gcadapter(adapter) {}
20
21 ~GCButton() override;
22
23 bool GetStatus() const override {
24 if (gcadapter->DeviceConnected(port)) {
25 return (gcadapter->GetPadState(port).buttons & button) != 0;
26 }
27 return false;
28 }
29
30private:
31 const u32 port;
32 const s32 button;
33 const GCAdapter::Adapter* gcadapter;
34};
35
36class GCAxisButton final : public Input::ButtonDevice {
37public:
38 explicit GCAxisButton(u32 port_, u32 axis_, float threshold_, bool trigger_if_greater_,
39 const GCAdapter::Adapter* adapter)
40 : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_),
41 gcadapter(adapter) {}
42
43 bool GetStatus() const override {
44 if (gcadapter->DeviceConnected(port)) {
45 const float current_axis_value = gcadapter->GetPadState(port).axis_values.at(axis);
46 const float axis_value = current_axis_value / 128.0f;
47 if (trigger_if_greater) {
48 // TODO: Might be worthwile to set a slider for the trigger threshold. It is
49 // currently always set to 0.5 in configure_input_player.cpp ZL/ZR HandleClick
50 return axis_value > threshold;
51 }
52 return axis_value < -threshold;
53 }
54 return false;
55 }
56
57private:
58 const u32 port;
59 const u32 axis;
60 float threshold;
61 bool trigger_if_greater;
62 const GCAdapter::Adapter* gcadapter;
63};
64
65GCButtonFactory::GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
66 : adapter(std::move(adapter_)) {}
67
68GCButton::~GCButton() = default;
69
70std::unique_ptr<Input::ButtonDevice> GCButtonFactory::Create(const Common::ParamPackage& params) {
71 const auto button_id = params.Get("button", 0);
72 const auto port = static_cast<u32>(params.Get("port", 0));
73
74 constexpr s32 PAD_STICK_ID = static_cast<s32>(GCAdapter::PadButton::Stick);
75
76 // button is not an axis/stick button
77 if (button_id != PAD_STICK_ID) {
78 return std::make_unique<GCButton>(port, button_id, adapter.get());
79 }
80
81 // For Axis buttons, used by the binary sticks.
82 if (button_id == PAD_STICK_ID) {
83 const int axis = params.Get("axis", 0);
84 const float threshold = params.Get("threshold", 0.25f);
85 const std::string direction_name = params.Get("direction", "");
86 bool trigger_if_greater;
87 if (direction_name == "+") {
88 trigger_if_greater = true;
89 } else if (direction_name == "-") {
90 trigger_if_greater = false;
91 } else {
92 trigger_if_greater = true;
93 LOG_ERROR(Input, "Unknown direction {}", direction_name);
94 }
95 return std::make_unique<GCAxisButton>(port, axis, threshold, trigger_if_greater,
96 adapter.get());
97 }
98
99 return nullptr;
100}
101
102Common::ParamPackage GCButtonFactory::GetNextInput() const {
103 Common::ParamPackage params;
104 GCAdapter::GCPadStatus pad;
105 auto& queue = adapter->GetPadQueue();
106 while (queue.Pop(pad)) {
107 // This while loop will break on the earliest detected button
108 params.Set("engine", "gcpad");
109 params.Set("port", static_cast<s32>(pad.port));
110 if (pad.button != GCAdapter::PadButton::Undefined) {
111 params.Set("button", static_cast<u16>(pad.button));
112 }
113
114 // For Axis button implementation
115 if (pad.axis != GCAdapter::PadAxes::Undefined) {
116 params.Set("axis", static_cast<u8>(pad.axis));
117 params.Set("button", static_cast<u16>(GCAdapter::PadButton::Stick));
118 params.Set("threshold", "0.25");
119 if (pad.axis_value > 0) {
120 params.Set("direction", "+");
121 } else {
122 params.Set("direction", "-");
123 }
124 break;
125 }
126 }
127 return params;
128}
129
130void GCButtonFactory::BeginConfiguration() {
131 polling = true;
132 adapter->BeginConfiguration();
133}
134
135void GCButtonFactory::EndConfiguration() {
136 polling = false;
137 adapter->EndConfiguration();
138}
139
140class GCAnalog final : public Input::AnalogDevice {
141public:
142 explicit GCAnalog(u32 port_, u32 axis_x_, u32 axis_y_, bool invert_x_, bool invert_y_,
143 float deadzone_, float range_, const GCAdapter::Adapter* adapter)
144 : port(port_), axis_x(axis_x_), axis_y(axis_y_), invert_x(invert_x_), invert_y(invert_y_),
145 deadzone(deadzone_), range(range_), gcadapter(adapter) {}
146
147 float GetAxis(u32 axis) const {
148 if (gcadapter->DeviceConnected(port)) {
149 std::lock_guard lock{mutex};
150 const auto axis_value =
151 static_cast<float>(gcadapter->GetPadState(port).axis_values.at(axis));
152 return (axis_value) / (100.0f * range);
153 }
154 return 0.0f;
155 }
156
157 std::pair<float, float> GetAnalog(u32 analog_axis_x, u32 analog_axis_y) const {
158 float x = GetAxis(analog_axis_x);
159 float y = GetAxis(analog_axis_y);
160 if (invert_x) {
161 x = -x;
162 }
163 if (invert_y) {
164 y = -y;
165 }
166 // Make sure the coordinates are in the unit circle,
167 // otherwise normalize it.
168 float r = x * x + y * y;
169 if (r > 1.0f) {
170 r = std::sqrt(r);
171 x /= r;
172 y /= r;
173 }
174
175 return {x, y};
176 }
177
178 std::tuple<float, float> GetStatus() const override {
179 const auto [x, y] = GetAnalog(axis_x, axis_y);
180 const float r = std::sqrt((x * x) + (y * y));
181 if (r > deadzone) {
182 return {x / r * (r - deadzone) / (1 - deadzone),
183 y / r * (r - deadzone) / (1 - deadzone)};
184 }
185 return {0.0f, 0.0f};
186 }
187
188 std::tuple<float, float> GetRawStatus() const override {
189 const float x = GetAxis(axis_x);
190 const float y = GetAxis(axis_y);
191 return {x, y};
192 }
193
194 Input::AnalogProperties GetAnalogProperties() const override {
195 return {deadzone, range, 0.5f};
196 }
197
198 bool GetAnalogDirectionStatus(Input::AnalogDirection direction) const override {
199 const auto [x, y] = GetStatus();
200 const float directional_deadzone = 0.5f;
201 switch (direction) {
202 case Input::AnalogDirection::RIGHT:
203 return x > directional_deadzone;
204 case Input::AnalogDirection::LEFT:
205 return x < -directional_deadzone;
206 case Input::AnalogDirection::UP:
207 return y > directional_deadzone;
208 case Input::AnalogDirection::DOWN:
209 return y < -directional_deadzone;
210 }
211 return false;
212 }
213
214private:
215 const u32 port;
216 const u32 axis_x;
217 const u32 axis_y;
218 const bool invert_x;
219 const bool invert_y;
220 const float deadzone;
221 const float range;
222 const GCAdapter::Adapter* gcadapter;
223 mutable std::mutex mutex;
224};
225
226/// An analog device factory that creates analog devices from GC Adapter
227GCAnalogFactory::GCAnalogFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
228 : adapter(std::move(adapter_)) {}
229
230/**
231 * Creates analog device from joystick axes
232 * @param params contains parameters for creating the device:
233 * - "port": the nth gcpad on the adapter
234 * - "axis_x": the index of the axis to be bind as x-axis
235 * - "axis_y": the index of the axis to be bind as y-axis
236 */
237std::unique_ptr<Input::AnalogDevice> GCAnalogFactory::Create(const Common::ParamPackage& params) {
238 const auto port = static_cast<u32>(params.Get("port", 0));
239 const auto axis_x = static_cast<u32>(params.Get("axis_x", 0));
240 const auto axis_y = static_cast<u32>(params.Get("axis_y", 1));
241 const auto deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, 1.0f);
242 const auto range = std::clamp(params.Get("range", 1.0f), 0.50f, 1.50f);
243 const std::string invert_x_value = params.Get("invert_x", "+");
244 const std::string invert_y_value = params.Get("invert_y", "+");
245 const bool invert_x = invert_x_value == "-";
246 const bool invert_y = invert_y_value == "-";
247
248 return std::make_unique<GCAnalog>(port, axis_x, axis_y, invert_x, invert_y, deadzone, range,
249 adapter.get());
250}
251
252void GCAnalogFactory::BeginConfiguration() {
253 polling = true;
254 adapter->BeginConfiguration();
255}
256
257void GCAnalogFactory::EndConfiguration() {
258 polling = false;
259 adapter->EndConfiguration();
260}
261
262Common::ParamPackage GCAnalogFactory::GetNextInput() {
263 GCAdapter::GCPadStatus pad;
264 Common::ParamPackage params;
265 auto& queue = adapter->GetPadQueue();
266 while (queue.Pop(pad)) {
267 if (pad.button != GCAdapter::PadButton::Undefined) {
268 params.Set("engine", "gcpad");
269 params.Set("port", static_cast<s32>(pad.port));
270 params.Set("button", static_cast<u16>(pad.button));
271 return params;
272 }
273 if (pad.axis == GCAdapter::PadAxes::Undefined ||
274 std::abs(static_cast<float>(pad.axis_value) / 128.0f) < 0.1f) {
275 continue;
276 }
277 // An analog device needs two axes, so we need to store the axis for later and wait for
278 // a second input event. The axes also must be from the same joystick.
279 const u8 axis = static_cast<u8>(pad.axis);
280 if (axis == 0 || axis == 1) {
281 analog_x_axis = 0;
282 analog_y_axis = 1;
283 controller_number = static_cast<s32>(pad.port);
284 break;
285 }
286 if (axis == 2 || axis == 3) {
287 analog_x_axis = 2;
288 analog_y_axis = 3;
289 controller_number = static_cast<s32>(pad.port);
290 break;
291 }
292
293 if (analog_x_axis == -1) {
294 analog_x_axis = axis;
295 controller_number = static_cast<s32>(pad.port);
296 } else if (analog_y_axis == -1 && analog_x_axis != axis &&
297 controller_number == static_cast<s32>(pad.port)) {
298 analog_y_axis = axis;
299 break;
300 }
301 }
302 if (analog_x_axis != -1 && analog_y_axis != -1) {
303 params.Set("engine", "gcpad");
304 params.Set("port", controller_number);
305 params.Set("axis_x", analog_x_axis);
306 params.Set("axis_y", analog_y_axis);
307 params.Set("invert_x", "+");
308 params.Set("invert_y", "+");
309 analog_x_axis = -1;
310 analog_y_axis = -1;
311 controller_number = -1;
312 return params;
313 }
314 return params;
315}
316
317class GCVibration final : public Input::VibrationDevice {
318public:
319 explicit GCVibration(u32 port_, GCAdapter::Adapter* adapter)
320 : port(port_), gcadapter(adapter) {}
321
322 u8 GetStatus() const override {
323 return gcadapter->RumblePlay(port, 0);
324 }
325
326 bool SetRumblePlay(f32 amp_low, [[maybe_unused]] f32 freq_low, f32 amp_high,
327 [[maybe_unused]] f32 freq_high) const override {
328 const auto mean_amplitude = (amp_low + amp_high) * 0.5f;
329 const auto processed_amplitude =
330 static_cast<u8>((mean_amplitude + std::pow(mean_amplitude, 0.3f)) * 0.5f * 0x8);
331
332 return gcadapter->RumblePlay(port, processed_amplitude);
333 }
334
335private:
336 const u32 port;
337 GCAdapter::Adapter* gcadapter;
338};
339
340/// An vibration device factory that creates vibration devices from GC Adapter
341GCVibrationFactory::GCVibrationFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
342 : adapter(std::move(adapter_)) {}
343
344/**
345 * Creates a vibration device from a joystick
346 * @param params contains parameters for creating the device:
347 * - "port": the nth gcpad on the adapter
348 */
349std::unique_ptr<Input::VibrationDevice> GCVibrationFactory::Create(
350 const Common::ParamPackage& params) {
351 const auto port = static_cast<u32>(params.Get("port", 0));
352
353 return std::make_unique<GCVibration>(port, adapter.get());
354}
355
356} // namespace InputCommon
diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h
deleted file mode 100644
index d1271e3ea..000000000
--- a/src/input_common/gcadapter/gc_poller.h
+++ /dev/null
@@ -1,78 +0,0 @@
1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <memory>
8#include "core/frontend/input.h"
9#include "input_common/gcadapter/gc_adapter.h"
10
11namespace InputCommon {
12
13/**
14 * A button device factory representing a gcpad. It receives gcpad events and forward them
15 * to all button devices it created.
16 */
17class GCButtonFactory final : public Input::Factory<Input::ButtonDevice> {
18public:
19 explicit GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_);
20
21 /**
22 * Creates a button device from a button press
23 * @param params contains parameters for creating the device:
24 * - "code": the code of the key to bind with the button
25 */
26 std::unique_ptr<Input::ButtonDevice> Create(const Common::ParamPackage& params) override;
27
28 Common::ParamPackage GetNextInput() const;
29
30 /// For device input configuration/polling
31 void BeginConfiguration();
32 void EndConfiguration();
33
34 bool IsPolling() const {
35 return polling;
36 }
37
38private:
39 std::shared_ptr<GCAdapter::Adapter> adapter;
40 bool polling = false;
41};
42
43/// An analog device factory that creates analog devices from GC Adapter
44class GCAnalogFactory final : public Input::Factory<Input::AnalogDevice> {
45public:
46 explicit GCAnalogFactory(std::shared_ptr<GCAdapter::Adapter> adapter_);
47
48 std::unique_ptr<Input::AnalogDevice> Create(const Common::ParamPackage& params) override;
49 Common::ParamPackage GetNextInput();
50
51 /// For device input configuration/polling
52 void BeginConfiguration();
53 void EndConfiguration();
54
55 bool IsPolling() const {
56 return polling;
57 }
58
59private:
60 std::shared_ptr<GCAdapter::Adapter> adapter;
61 int analog_x_axis = -1;
62 int analog_y_axis = -1;
63 int controller_number = -1;
64 bool polling = false;
65};
66
67/// A vibration device factory creates vibration devices from GC Adapter
68class GCVibrationFactory final : public Input::Factory<Input::VibrationDevice> {
69public:
70 explicit GCVibrationFactory(std::shared_ptr<GCAdapter::Adapter> adapter_);
71
72 std::unique_ptr<Input::VibrationDevice> Create(const Common::ParamPackage& params) override;
73
74private:
75 std::shared_ptr<GCAdapter::Adapter> adapter;
76};
77
78} // namespace InputCommon