joypad_windows.cpp 21 KB

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