joypad_windows.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /**************************************************************************/
  2. /* joypad_windows.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "joypad_windows.h"
  31. #include <oleauto.h>
  32. #include <wbemidl.h>
  33. #if defined(__GNUC__)
  34. // Workaround GCC warning from -Wcast-function-type.
  35. #define GetProcAddress (void *)GetProcAddress
  36. #endif
  37. DWORD WINAPI _xinput_get_state(DWORD dwUserIndex, XINPUT_STATE *pState) {
  38. return ERROR_DEVICE_NOT_CONNECTED;
  39. }
  40. DWORD WINAPI _xinput_set_state(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration) {
  41. return ERROR_DEVICE_NOT_CONNECTED;
  42. }
  43. MMRESULT WINAPI _winmm_get_joycaps(UINT uJoyID, LPJOYCAPSW pjc, UINT cbjc) {
  44. return MMSYSERR_NODRIVER;
  45. }
  46. JoypadWindows::JoypadWindows() {
  47. }
  48. JoypadWindows::JoypadWindows(HWND *hwnd) {
  49. input = Input::get_singleton();
  50. hWnd = hwnd;
  51. x_joypad_probe_count = 0;
  52. d_joypad_count = 0;
  53. dinput = nullptr;
  54. xinput_dll = nullptr;
  55. xinput_get_state = nullptr;
  56. xinput_set_state = nullptr;
  57. winmm_get_joycaps = nullptr;
  58. load_xinput();
  59. for (int i = 0; i < JOYPADS_MAX; i++) {
  60. attached_joypads[i] = false;
  61. }
  62. HRESULT result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, nullptr);
  63. if (result == DI_OK) {
  64. probe_joypads();
  65. } else {
  66. ERR_PRINT("Couldn't initialize DirectInput. Error: " + itos(result));
  67. if (result == DIERR_OUTOFMEMORY) {
  68. ERR_PRINT("The Windows DirectInput subsystem could not allocate sufficient memory.");
  69. ERR_PRINT("Rebooting your PC may solve this issue.");
  70. }
  71. // Ensure dinput is still a nullptr.
  72. dinput = nullptr;
  73. }
  74. }
  75. JoypadWindows::~JoypadWindows() {
  76. close_d_joypad();
  77. if (dinput) {
  78. dinput->Release();
  79. }
  80. unload_winmm();
  81. unload_xinput();
  82. }
  83. bool JoypadWindows::is_d_joypad_known(const GUID &p_guid) {
  84. for (int i = 0; i < JOYPADS_MAX; i++) {
  85. if (d_joypads[i].guid == p_guid) {
  86. d_joypads[i].confirmed = true;
  87. return true;
  88. }
  89. }
  90. return false;
  91. }
  92. // adapted from SDL2, works a lot better than the MSDN version
  93. bool JoypadWindows::is_xinput_joypad(const GUID *p_guid) {
  94. static GUID IID_ValveStreamingGamepad = { MAKELONG(0x28DE, 0x11FF), 0x28DE, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  95. static GUID IID_X360WiredGamepad = { MAKELONG(0x045E, 0x02A1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  96. static GUID IID_X360WirelessGamepad = { MAKELONG(0x045E, 0x028E), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  97. static GUID IID_XSWirelessGamepad = { MAKELONG(0x045E, 0x0B13), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  98. static GUID IID_XEliteWirelessGamepad = { MAKELONG(0x045E, 0x0B05), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  99. static GUID IID_XOneWiredGamepad = { MAKELONG(0x045E, 0x02FF), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  100. static GUID IID_XOneWirelessGamepad = { MAKELONG(0x045E, 0x02DD), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  101. static GUID IID_XOneNewWirelessGamepad = { MAKELONG(0x045E, 0x02D1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  102. static GUID IID_XOneSWirelessGamepad = { MAKELONG(0x045E, 0x02EA), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  103. static GUID IID_XOneSBluetoothGamepad = { MAKELONG(0x045E, 0x02E0), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  104. static GUID IID_XOneEliteWirelessGamepad = { MAKELONG(0x045E, 0x02E3), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  105. static GUID IID_XOneElite2WirelessGamepad = { MAKELONG(0x045E, 0x0B22), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } };
  106. if (memcmp(p_guid, &IID_ValveStreamingGamepad, sizeof(*p_guid)) == 0 ||
  107. memcmp(p_guid, &IID_X360WiredGamepad, sizeof(*p_guid)) == 0 ||
  108. memcmp(p_guid, &IID_X360WirelessGamepad, sizeof(*p_guid)) == 0 ||
  109. memcmp(p_guid, &IID_XSWirelessGamepad, sizeof(*p_guid)) == 0 ||
  110. memcmp(p_guid, &IID_XEliteWirelessGamepad, sizeof(*p_guid)) == 0 ||
  111. memcmp(p_guid, &IID_XOneWiredGamepad, sizeof(*p_guid)) == 0 ||
  112. memcmp(p_guid, &IID_XOneWirelessGamepad, sizeof(*p_guid)) == 0 ||
  113. memcmp(p_guid, &IID_XOneNewWirelessGamepad, sizeof(*p_guid)) == 0 ||
  114. memcmp(p_guid, &IID_XOneSWirelessGamepad, sizeof(*p_guid)) == 0 ||
  115. memcmp(p_guid, &IID_XOneSBluetoothGamepad, sizeof(*p_guid)) == 0 ||
  116. memcmp(p_guid, &IID_XOneEliteWirelessGamepad, sizeof(*p_guid)) == 0 ||
  117. memcmp(p_guid, &IID_XOneElite2WirelessGamepad, sizeof(*p_guid)) == 0) {
  118. return true;
  119. }
  120. PRAWINPUTDEVICELIST dev_list = nullptr;
  121. unsigned int dev_list_count = 0;
  122. if (GetRawInputDeviceList(nullptr, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
  123. return false;
  124. }
  125. dev_list = (PRAWINPUTDEVICELIST)memalloc(sizeof(RAWINPUTDEVICELIST) * dev_list_count);
  126. ERR_FAIL_NULL_V_MSG(dev_list, false, "Out of memory.");
  127. if (GetRawInputDeviceList(dev_list, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) {
  128. memfree(dev_list);
  129. return false;
  130. }
  131. for (unsigned int i = 0; i < dev_list_count; i++) {
  132. RID_DEVICE_INFO rdi;
  133. char dev_name[128];
  134. UINT rdiSize = sizeof(rdi);
  135. UINT nameSize = sizeof(dev_name);
  136. rdi.cbSize = rdiSize;
  137. if ((dev_list[i].dwType == RIM_TYPEHID) &&
  138. (GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != (UINT)-1) &&
  139. (MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == (LONG)p_guid->Data1) &&
  140. (GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICENAME, &dev_name, &nameSize) != (UINT)-1) &&
  141. (strstr(dev_name, "IG_") != nullptr)) {
  142. memfree(dev_list);
  143. return true;
  144. }
  145. }
  146. memfree(dev_list);
  147. return false;
  148. }
  149. void JoypadWindows::probe_xinput_joypad(const String &name) {
  150. if (x_joypad_probe_count >= XUSER_MAX_COUNT) {
  151. return;
  152. }
  153. int i = x_joypad_probe_count;
  154. x_joypad_probe_count++;
  155. ZeroMemory(&x_joypads[i].state, sizeof(XINPUT_STATE));
  156. DWORD dwResult = xinput_get_state(i, &x_joypads[i].state);
  157. if (dwResult == ERROR_SUCCESS) {
  158. int id = input->get_unused_joy_id();
  159. if (id != -1 && !x_joypads[i].attached) {
  160. x_joypads[i].attached = true;
  161. x_joypads[i].id = id;
  162. x_joypads[i].ff_timestamp = 0;
  163. x_joypads[i].ff_end_timestamp = 0;
  164. x_joypads[i].vibrating = false;
  165. attached_joypads[id] = true;
  166. Dictionary joypad_info;
  167. String joypad_name;
  168. joypad_info["xinput_index"] = (int)i;
  169. JOYCAPSW jc;
  170. memset(&jc, 0, sizeof(JOYCAPSW));
  171. MMRESULT jcResult = winmm_get_joycaps((UINT)id, &jc, sizeof(JOYCAPSW));
  172. if (jcResult == JOYERR_NOERROR) {
  173. joypad_info["vendor_id"] = itos(jc.wMid);
  174. joypad_info["product_id"] = itos(jc.wPid);
  175. if (!name.is_empty()) {
  176. joypad_name = name.trim_prefix("Controller (").trim_suffix(")");
  177. }
  178. }
  179. input->joy_connection_changed(id, true, joypad_name, "__XINPUT_DEVICE__", joypad_info);
  180. }
  181. } else if (x_joypads[i].attached) {
  182. x_joypads[i].attached = false;
  183. attached_joypads[x_joypads[i].id] = false;
  184. input->joy_connection_changed(x_joypads[i].id, false, "");
  185. }
  186. }
  187. bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) {
  188. ERR_FAIL_NULL_V_MSG(dinput, false, "DirectInput not initialized. Rebooting your PC may solve this issue.");
  189. HRESULT hr;
  190. int num = input->get_unused_joy_id();
  191. if (is_d_joypad_known(instance->guidInstance) || num == -1) {
  192. return false;
  193. }
  194. d_joypads[num] = dinput_gamepad();
  195. dinput_gamepad *joy = &d_joypads[num];
  196. const DWORD devtype = (instance->dwDevType & 0xFF);
  197. if ((devtype != DI8DEVTYPE_JOYSTICK) && (devtype != DI8DEVTYPE_GAMEPAD) && (devtype != DI8DEVTYPE_1STPERSON) && (devtype != DI8DEVTYPE_DRIVING)) {
  198. return false;
  199. }
  200. hr = dinput->CreateDevice(instance->guidInstance, &joy->di_joy, nullptr);
  201. if (FAILED(hr)) {
  202. return false;
  203. }
  204. const GUID &guid = instance->guidProduct;
  205. char uid[128];
  206. ERR_FAIL_COND_V_MSG(memcmp(&guid.Data4[2], "PIDVID", 6), false, "DirectInput device not recognized.");
  207. WORD type = BSWAP16(0x03);
  208. WORD vendor = BSWAP16(LOWORD(guid.Data1));
  209. WORD product = BSWAP16(HIWORD(guid.Data1));
  210. WORD version = 0;
  211. sprintf_s(uid, "%04x%04x%04x%04x%04x%04x%04x%04x", type, 0, vendor, 0, product, 0, version, 0);
  212. Dictionary joypad_info;
  213. joypad_info["vendor_id"] = itos(vendor);
  214. joypad_info["product_id"] = itos(product);
  215. id_to_change = num;
  216. slider_count = 0;
  217. joy->di_joy->SetDataFormat(&c_dfDIJoystick2);
  218. joy->di_joy->SetCooperativeLevel(*hWnd, DISCL_FOREGROUND);
  219. joy->di_joy->EnumObjects(objectsCallback, this, 0);
  220. joy->joy_axis.sort();
  221. joy->guid = instance->guidInstance;
  222. const String &name = String(instance->tszProductName).trim_prefix("Controller (").trim_suffix(")");
  223. input->joy_connection_changed(num, true, name, uid, joypad_info);
  224. joy->attached = true;
  225. joy->id = num;
  226. attached_joypads[num] = true;
  227. joy->confirmed = true;
  228. d_joypad_count++;
  229. return true;
  230. }
  231. void JoypadWindows::setup_d_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_joy_id) {
  232. if (ob->dwType & DIDFT_AXIS) {
  233. HRESULT res;
  234. DIPROPRANGE prop_range;
  235. DIPROPDWORD dilong;
  236. LONG ofs;
  237. if (ob->guidType == GUID_XAxis) {
  238. ofs = DIJOFS_X;
  239. } else if (ob->guidType == GUID_YAxis) {
  240. ofs = DIJOFS_Y;
  241. } else if (ob->guidType == GUID_ZAxis) {
  242. ofs = DIJOFS_Z;
  243. } else if (ob->guidType == GUID_RxAxis) {
  244. ofs = DIJOFS_RX;
  245. } else if (ob->guidType == GUID_RyAxis) {
  246. ofs = DIJOFS_RY;
  247. } else if (ob->guidType == GUID_RzAxis) {
  248. ofs = DIJOFS_RZ;
  249. } else if (ob->guidType == GUID_Slider) {
  250. if (slider_count < 2) {
  251. ofs = DIJOFS_SLIDER(slider_count);
  252. slider_count++;
  253. } else {
  254. return;
  255. }
  256. } else {
  257. return;
  258. }
  259. prop_range.diph.dwSize = sizeof(DIPROPRANGE);
  260. prop_range.diph.dwHeaderSize = sizeof(DIPROPHEADER);
  261. prop_range.diph.dwObj = ob->dwType;
  262. prop_range.diph.dwHow = DIPH_BYID;
  263. prop_range.lMin = -MAX_JOY_AXIS;
  264. prop_range.lMax = +MAX_JOY_AXIS;
  265. dinput_gamepad &joy = d_joypads[p_joy_id];
  266. res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_RANGE, &prop_range.diph);
  267. if (FAILED(res)) {
  268. return;
  269. }
  270. dilong.diph.dwSize = sizeof(dilong);
  271. dilong.diph.dwHeaderSize = sizeof(dilong.diph);
  272. dilong.diph.dwObj = ob->dwType;
  273. dilong.diph.dwHow = DIPH_BYID;
  274. dilong.dwData = 0;
  275. res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_DEADZONE, &dilong.diph);
  276. if (FAILED(res)) {
  277. return;
  278. }
  279. joy.joy_axis.push_back(ofs);
  280. }
  281. }
  282. BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE *p_instance, void *p_context) {
  283. JoypadWindows *self = static_cast<JoypadWindows *>(p_context);
  284. if (self->is_xinput_joypad(&p_instance->guidProduct)) {
  285. self->probe_xinput_joypad(p_instance->tszProductName);
  286. return DIENUM_CONTINUE;
  287. }
  288. self->setup_dinput_joypad(p_instance);
  289. return DIENUM_CONTINUE;
  290. }
  291. BOOL CALLBACK JoypadWindows::objectsCallback(const DIDEVICEOBJECTINSTANCE *p_instance, void *p_context) {
  292. JoypadWindows *self = static_cast<JoypadWindows *>(p_context);
  293. self->setup_d_joypad_object(p_instance, self->id_to_change);
  294. return DIENUM_CONTINUE;
  295. }
  296. void JoypadWindows::close_d_joypad(int id) {
  297. if (id == -1) {
  298. for (int i = 0; i < JOYPADS_MAX; i++) {
  299. close_d_joypad(i);
  300. }
  301. return;
  302. }
  303. if (!d_joypads[id].attached) {
  304. return;
  305. }
  306. d_joypads[id].di_joy->Unacquire();
  307. d_joypads[id].di_joy->Release();
  308. d_joypads[id].attached = false;
  309. attached_joypads[d_joypads[id].id] = false;
  310. d_joypads[id].guid.Data1 = d_joypads[id].guid.Data2 = d_joypads[id].guid.Data3 = 0;
  311. input->joy_connection_changed(d_joypads[id].id, false, "");
  312. d_joypad_count--;
  313. }
  314. void JoypadWindows::probe_joypads() {
  315. ERR_FAIL_NULL_MSG(dinput, "DirectInput not initialized. Rebooting your PC may solve this issue.");
  316. for (int i = 0; i < d_joypad_count; i++) {
  317. d_joypads[i].confirmed = false; // Flag DirectInput devices for re-checking their availability.
  318. }
  319. x_joypad_probe_count = 0;
  320. // Probe _all attached_ joypad devices.
  321. dinput->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback, this, DIEDFL_ATTACHEDONLY);
  322. for (int i = x_joypad_probe_count; i < XUSER_MAX_COUNT; i++) {
  323. // Handle disconnect of XInput devices.
  324. // And act as a fallback, just in case DirectInput could not find the device.
  325. probe_xinput_joypad();
  326. }
  327. for (int i = 0; i < d_joypad_count; i++) {
  328. if (!d_joypads[i].confirmed) {
  329. close_d_joypad(i); // Any DirectInput device not found during probing is considered as disconnected.
  330. }
  331. }
  332. }
  333. void JoypadWindows::process_joypads() {
  334. HRESULT hr;
  335. // Handle XInput joypads.
  336. for (int i = 0; i < XUSER_MAX_COUNT; i++) {
  337. xinput_gamepad &joy = x_joypads[i];
  338. if (!joy.attached) {
  339. continue;
  340. }
  341. ZeroMemory(&joy.state, sizeof(XINPUT_STATE));
  342. xinput_get_state(i, &joy.state);
  343. if (joy.state.dwPacketNumber != joy.last_packet) {
  344. int button_mask = XINPUT_GAMEPAD_DPAD_UP;
  345. for (int j = 0; j <= 16; j++) {
  346. input->joy_button(joy.id, (JoyButton)j, joy.state.Gamepad.wButtons & button_mask);
  347. button_mask = button_mask * 2;
  348. }
  349. input->joy_axis(joy.id, JoyAxis::LEFT_X, axis_correct(joy.state.Gamepad.sThumbLX, true));
  350. input->joy_axis(joy.id, JoyAxis::LEFT_Y, axis_correct(joy.state.Gamepad.sThumbLY, true, false, true));
  351. input->joy_axis(joy.id, JoyAxis::RIGHT_X, axis_correct(joy.state.Gamepad.sThumbRX, true));
  352. input->joy_axis(joy.id, JoyAxis::RIGHT_Y, axis_correct(joy.state.Gamepad.sThumbRY, true, false, true));
  353. input->joy_axis(joy.id, JoyAxis::TRIGGER_LEFT, axis_correct(joy.state.Gamepad.bLeftTrigger, true, true));
  354. input->joy_axis(joy.id, JoyAxis::TRIGGER_RIGHT, axis_correct(joy.state.Gamepad.bRightTrigger, true, true));
  355. joy.last_packet = joy.state.dwPacketNumber;
  356. }
  357. uint64_t timestamp = input->get_joy_vibration_timestamp(joy.id);
  358. if (timestamp > joy.ff_timestamp) {
  359. Vector2 strength = input->get_joy_vibration_strength(joy.id);
  360. float duration = input->get_joy_vibration_duration(joy.id);
  361. if (strength.x == 0 && strength.y == 0) {
  362. joypad_vibration_stop_xinput(i, timestamp);
  363. } else {
  364. joypad_vibration_start_xinput(i, strength.x, strength.y, duration, timestamp);
  365. }
  366. } else if (joy.vibrating && joy.ff_end_timestamp != 0) {
  367. uint64_t current_time = OS::get_singleton()->get_ticks_usec();
  368. if (current_time >= joy.ff_end_timestamp) {
  369. joypad_vibration_stop_xinput(i, current_time);
  370. }
  371. }
  372. }
  373. // Handle DirectIndput joypads.
  374. for (int i = 0; i < JOYPADS_MAX; i++) {
  375. dinput_gamepad *joy = &d_joypads[i];
  376. if (!joy->attached) {
  377. continue;
  378. }
  379. DIJOYSTATE2 js;
  380. hr = joy->di_joy->Poll();
  381. if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) {
  382. IDirectInputDevice8_Acquire(joy->di_joy);
  383. joy->di_joy->Poll();
  384. }
  385. hr = joy->di_joy->GetDeviceState(sizeof(DIJOYSTATE2), &js);
  386. if (FAILED(hr)) {
  387. continue;
  388. }
  389. post_hat(joy->id, js.rgdwPOV[0]);
  390. for (int j = 0; j < 128; j++) {
  391. if (js.rgbButtons[j] & 0x80) {
  392. if (!joy->last_buttons[j]) {
  393. input->joy_button(joy->id, (JoyButton)j, true);
  394. joy->last_buttons[j] = true;
  395. }
  396. } else {
  397. if (joy->last_buttons[j]) {
  398. input->joy_button(joy->id, (JoyButton)j, false);
  399. joy->last_buttons[j] = false;
  400. }
  401. }
  402. }
  403. // on mingw, these constants are not constants
  404. int count = 8;
  405. const LONG axes[] = { DIJOFS_X, DIJOFS_Y, DIJOFS_Z, DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ, (LONG)DIJOFS_SLIDER(0), (LONG)DIJOFS_SLIDER(1) };
  406. int values[] = { js.lX, js.lY, js.lZ, js.lRx, js.lRy, js.lRz, js.rglSlider[0], js.rglSlider[1] };
  407. for (uint32_t j = 0; j < joy->joy_axis.size(); j++) {
  408. for (int k = 0; k < count; k++) {
  409. if (joy->joy_axis[j] == axes[k]) {
  410. input->joy_axis(joy->id, (JoyAxis)j, axis_correct(values[k]));
  411. break;
  412. }
  413. }
  414. }
  415. }
  416. return;
  417. }
  418. void JoypadWindows::post_hat(int p_device, DWORD p_dpad) {
  419. BitField<HatMask> dpad_val;
  420. // Should be -1 when centered, but according to docs:
  421. // "Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:
  422. // BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);"
  423. // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee416628(v%3Dvs.85)#remarks
  424. if (LOWORD(p_dpad) == 0xFFFF) {
  425. // Do nothing.
  426. // dpad_val.set_flag(HatMask::CENTER);
  427. }
  428. if (p_dpad == 0) {
  429. dpad_val.set_flag(HatMask::UP);
  430. } else if (p_dpad == 4500) {
  431. dpad_val.set_flag(HatMask::UP);
  432. dpad_val.set_flag(HatMask::RIGHT);
  433. } else if (p_dpad == 9000) {
  434. dpad_val.set_flag(HatMask::RIGHT);
  435. } else if (p_dpad == 13500) {
  436. dpad_val.set_flag(HatMask::RIGHT);
  437. dpad_val.set_flag(HatMask::DOWN);
  438. } else if (p_dpad == 18000) {
  439. dpad_val.set_flag(HatMask::DOWN);
  440. } else if (p_dpad == 22500) {
  441. dpad_val.set_flag(HatMask::DOWN);
  442. dpad_val.set_flag(HatMask::LEFT);
  443. } else if (p_dpad == 27000) {
  444. dpad_val.set_flag(HatMask::LEFT);
  445. } else if (p_dpad == 31500) {
  446. dpad_val.set_flag(HatMask::LEFT);
  447. dpad_val.set_flag(HatMask::UP);
  448. }
  449. input->joy_hat(p_device, dpad_val);
  450. }
  451. float JoypadWindows::axis_correct(int p_val, bool p_xinput, bool p_trigger, bool p_negate) const {
  452. if (Math::abs(p_val) < MIN_JOY_AXIS) {
  453. return p_trigger ? -1.0f : 0.0f;
  454. }
  455. if (!p_xinput) {
  456. return (float)p_val / MAX_JOY_AXIS;
  457. }
  458. if (p_trigger) {
  459. // Convert to a value between -1.0f and 1.0f.
  460. return 2.0f * p_val / MAX_TRIGGER - 1.0f;
  461. }
  462. float value;
  463. if (p_val < 0) {
  464. value = (float)p_val / MAX_JOY_AXIS;
  465. } else {
  466. value = (float)p_val / (MAX_JOY_AXIS - 1);
  467. }
  468. if (p_negate) {
  469. value = -value;
  470. }
  471. return value;
  472. }
  473. void JoypadWindows::joypad_vibration_start_xinput(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
  474. xinput_gamepad &joy = x_joypads[p_device];
  475. if (joy.attached) {
  476. XINPUT_VIBRATION effect;
  477. effect.wLeftMotorSpeed = (65535 * p_strong_magnitude);
  478. effect.wRightMotorSpeed = (65535 * p_weak_magnitude);
  479. if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) {
  480. joy.ff_timestamp = p_timestamp;
  481. joy.ff_end_timestamp = p_duration == 0 ? 0 : p_timestamp + (uint64_t)(p_duration * 1000000.0);
  482. joy.vibrating = true;
  483. }
  484. }
  485. }
  486. void JoypadWindows::joypad_vibration_stop_xinput(int p_device, uint64_t p_timestamp) {
  487. xinput_gamepad &joy = x_joypads[p_device];
  488. if (joy.attached) {
  489. XINPUT_VIBRATION effect;
  490. effect.wLeftMotorSpeed = 0;
  491. effect.wRightMotorSpeed = 0;
  492. if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) {
  493. joy.ff_timestamp = p_timestamp;
  494. joy.vibrating = false;
  495. }
  496. }
  497. }
  498. void JoypadWindows::load_xinput() {
  499. xinput_get_state = &_xinput_get_state;
  500. xinput_set_state = &_xinput_set_state;
  501. winmm_get_joycaps = &_winmm_get_joycaps;
  502. bool legacy_xinput = false;
  503. xinput_dll = LoadLibrary("XInput1_4.dll");
  504. if (!xinput_dll) {
  505. xinput_dll = LoadLibrary("XInput1_3.dll");
  506. if (!xinput_dll) {
  507. xinput_dll = LoadLibrary("XInput9_1_0.dll");
  508. legacy_xinput = true;
  509. }
  510. }
  511. if (!xinput_dll) {
  512. print_verbose("Could not find XInput, using DirectInput only");
  513. return;
  514. }
  515. // (LPCSTR)100 is the magic number to get XInputGetStateEx, which also provides the state for the guide button
  516. LPCSTR get_state_func_name = legacy_xinput ? "XInputGetState" : (LPCSTR)100;
  517. XInputGetState_t func = (XInputGetState_t)GetProcAddress((HMODULE)xinput_dll, get_state_func_name);
  518. XInputSetState_t set_func = (XInputSetState_t)GetProcAddress((HMODULE)xinput_dll, "XInputSetState");
  519. if (!func || !set_func) {
  520. unload_xinput();
  521. return;
  522. }
  523. xinput_get_state = func;
  524. xinput_set_state = set_func;
  525. winmm_dll = LoadLibrary("Winmm.dll");
  526. if (winmm_dll) {
  527. joyGetDevCaps_t caps_func = (joyGetDevCaps_t)GetProcAddress((HMODULE)winmm_dll, "joyGetDevCapsW");
  528. if (caps_func) {
  529. winmm_get_joycaps = caps_func;
  530. } else {
  531. unload_winmm();
  532. }
  533. }
  534. }
  535. void JoypadWindows::unload_xinput() {
  536. if (xinput_dll) {
  537. FreeLibrary((HMODULE)xinput_dll);
  538. }
  539. }
  540. void JoypadWindows::unload_winmm() {
  541. if (winmm_dll) {
  542. FreeLibrary((HMODULE)winmm_dll);
  543. }
  544. }