joypad_linux.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /**************************************************************************/
  2. /* joypad_linux.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. #ifdef JOYDEV_ENABLED
  31. #include "joypad_linux.h"
  32. #include <dirent.h>
  33. #include <errno.h>
  34. #include <fcntl.h>
  35. #include <linux/input.h>
  36. #include <unistd.h>
  37. #ifdef UDEV_ENABLED
  38. #ifdef SOWRAP_ENABLED
  39. #include "libudev-so_wrap.h"
  40. #else
  41. #include <libudev.h>
  42. #endif
  43. #endif
  44. #define LONG_BITS (sizeof(long) * 8)
  45. #define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
  46. #define NBITS(x) ((((x)-1) / LONG_BITS) + 1)
  47. #ifdef UDEV_ENABLED
  48. static const char *ignore_str = "/dev/input/js";
  49. #endif
  50. JoypadLinux::Joypad::~Joypad() {
  51. for (int i = 0; i < MAX_ABS; i++) {
  52. if (abs_info[i]) {
  53. memdelete(abs_info[i]);
  54. }
  55. }
  56. }
  57. void JoypadLinux::Joypad::reset() {
  58. dpad = 0;
  59. fd = -1;
  60. for (int i = 0; i < MAX_ABS; i++) {
  61. abs_map[i] = -1;
  62. curr_axis[i] = 0;
  63. }
  64. events.clear();
  65. }
  66. JoypadLinux::JoypadLinux(Input *in) {
  67. #ifdef UDEV_ENABLED
  68. #ifdef SOWRAP_ENABLED
  69. #ifdef DEBUG_ENABLED
  70. int dylibloader_verbose = 1;
  71. #else
  72. int dylibloader_verbose = 0;
  73. #endif
  74. use_udev = initialize_libudev(dylibloader_verbose) == 0;
  75. if (use_udev) {
  76. print_verbose("JoypadLinux: udev enabled and loaded successfully.");
  77. } else {
  78. print_verbose("JoypadLinux: udev enabled, but couldn't be loaded. Falling back to /dev/input to detect joypads.");
  79. }
  80. #endif
  81. #else
  82. print_verbose("JoypadLinux: udev disabled, parsing /dev/input to detect joypads.");
  83. #endif
  84. input = in;
  85. monitor_joypads_thread.start(monitor_joypads_thread_func, this);
  86. joypad_events_thread.start(joypad_events_thread_func, this);
  87. }
  88. JoypadLinux::~JoypadLinux() {
  89. monitor_joypads_exit.set();
  90. joypad_events_exit.set();
  91. monitor_joypads_thread.wait_to_finish();
  92. joypad_events_thread.wait_to_finish();
  93. close_joypads();
  94. }
  95. void JoypadLinux::monitor_joypads_thread_func(void *p_user) {
  96. if (p_user) {
  97. JoypadLinux *joy = static_cast<JoypadLinux *>(p_user);
  98. joy->monitor_joypads_thread_run();
  99. }
  100. }
  101. void JoypadLinux::monitor_joypads_thread_run() {
  102. #ifdef UDEV_ENABLED
  103. if (use_udev) {
  104. udev *_udev = udev_new();
  105. if (!_udev) {
  106. use_udev = false;
  107. ERR_PRINT("Failed getting an udev context, falling back to parsing /dev/input.");
  108. monitor_joypads();
  109. } else {
  110. enumerate_joypads(_udev);
  111. monitor_joypads(_udev);
  112. udev_unref(_udev);
  113. }
  114. } else {
  115. monitor_joypads();
  116. }
  117. #else
  118. monitor_joypads();
  119. #endif
  120. }
  121. #ifdef UDEV_ENABLED
  122. void JoypadLinux::enumerate_joypads(udev *p_udev) {
  123. udev_enumerate *enumerate;
  124. udev_list_entry *devices, *dev_list_entry;
  125. udev_device *dev;
  126. enumerate = udev_enumerate_new(p_udev);
  127. udev_enumerate_add_match_subsystem(enumerate, "input");
  128. udev_enumerate_scan_devices(enumerate);
  129. devices = udev_enumerate_get_list_entry(enumerate);
  130. udev_list_entry_foreach(dev_list_entry, devices) {
  131. const char *path = udev_list_entry_get_name(dev_list_entry);
  132. dev = udev_device_new_from_syspath(p_udev, path);
  133. const char *devnode = udev_device_get_devnode(dev);
  134. if (devnode) {
  135. String devnode_str = devnode;
  136. if (devnode_str.find(ignore_str) == -1) {
  137. open_joypad(devnode);
  138. }
  139. }
  140. udev_device_unref(dev);
  141. }
  142. udev_enumerate_unref(enumerate);
  143. }
  144. void JoypadLinux::monitor_joypads(udev *p_udev) {
  145. udev_device *dev = nullptr;
  146. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  147. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr);
  148. udev_monitor_enable_receiving(mon);
  149. int fd = udev_monitor_get_fd(mon);
  150. while (!monitor_joypads_exit.is_set()) {
  151. fd_set fds;
  152. struct timeval tv;
  153. int ret;
  154. FD_ZERO(&fds);
  155. FD_SET(fd, &fds);
  156. tv.tv_sec = 0;
  157. tv.tv_usec = 0;
  158. ret = select(fd + 1, &fds, nullptr, nullptr, &tv);
  159. /* Check if our file descriptor has received data. */
  160. if (ret > 0 && FD_ISSET(fd, &fds)) {
  161. /* Make the call to receive the device.
  162. select() ensured that this will not block. */
  163. dev = udev_monitor_receive_device(mon);
  164. if (dev && udev_device_get_devnode(dev) != nullptr) {
  165. String action = udev_device_get_action(dev);
  166. const char *devnode = udev_device_get_devnode(dev);
  167. if (devnode) {
  168. String devnode_str = devnode;
  169. if (devnode_str.find(ignore_str) == -1) {
  170. if (action == "add") {
  171. open_joypad(devnode);
  172. } else if (String(action) == "remove") {
  173. close_joypad(devnode);
  174. }
  175. }
  176. }
  177. udev_device_unref(dev);
  178. }
  179. }
  180. usleep(50000);
  181. }
  182. udev_monitor_unref(mon);
  183. }
  184. #endif
  185. void JoypadLinux::monitor_joypads() {
  186. while (!monitor_joypads_exit.is_set()) {
  187. DIR *input_directory;
  188. input_directory = opendir("/dev/input");
  189. if (input_directory) {
  190. struct dirent *current;
  191. char fname[64];
  192. while ((current = readdir(input_directory)) != nullptr) {
  193. if (strncmp(current->d_name, "event", 5) != 0) {
  194. continue;
  195. }
  196. sprintf(fname, "/dev/input/%.*s", 16, current->d_name);
  197. if (attached_devices.find(fname) == -1) {
  198. open_joypad(fname);
  199. }
  200. }
  201. }
  202. closedir(input_directory);
  203. usleep(1000000); // 1s
  204. }
  205. }
  206. void JoypadLinux::close_joypads() {
  207. for (int i = 0; i < JOYPADS_MAX; i++) {
  208. MutexLock lock(joypads_mutex[i]);
  209. Joypad &joypad = joypads[i];
  210. close_joypad(joypad, i);
  211. }
  212. }
  213. void JoypadLinux::close_joypad(const char *p_devpath) {
  214. for (int i = 0; i < JOYPADS_MAX; i++) {
  215. MutexLock lock(joypads_mutex[i]);
  216. Joypad &joypad = joypads[i];
  217. if (joypads[i].devpath == p_devpath) {
  218. close_joypad(joypad, i);
  219. }
  220. }
  221. }
  222. void JoypadLinux::close_joypad(Joypad &p_joypad, int p_id) {
  223. if (p_joypad.fd != -1) {
  224. close(p_joypad.fd);
  225. p_joypad.fd = -1;
  226. attached_devices.erase(p_joypad.devpath);
  227. input->joy_connection_changed(p_id, false, "");
  228. }
  229. p_joypad.events.clear();
  230. }
  231. static String _hex_str(uint8_t p_byte) {
  232. static const char *dict = "0123456789abcdef";
  233. char ret[3];
  234. ret[2] = 0;
  235. ret[0] = dict[p_byte >> 4];
  236. ret[1] = dict[p_byte & 0xF];
  237. return ret;
  238. }
  239. void JoypadLinux::setup_joypad_properties(Joypad &p_joypad) {
  240. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  241. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  242. int num_buttons = 0;
  243. int num_axes = 0;
  244. if ((ioctl(p_joypad.fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  245. (ioctl(p_joypad.fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  246. return;
  247. }
  248. for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  249. if (test_bit(i, keybit)) {
  250. p_joypad.key_map[i] = num_buttons++;
  251. }
  252. }
  253. for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
  254. if (test_bit(i, keybit)) {
  255. p_joypad.key_map[i] = num_buttons++;
  256. }
  257. }
  258. for (int i = 0; i < ABS_MISC; ++i) {
  259. /* Skip hats */
  260. if (i == ABS_HAT0X) {
  261. i = ABS_HAT3Y;
  262. continue;
  263. }
  264. if (test_bit(i, absbit)) {
  265. p_joypad.abs_map[i] = num_axes++;
  266. p_joypad.abs_info[i] = memnew(input_absinfo);
  267. if (ioctl(p_joypad.fd, EVIOCGABS(i), p_joypad.abs_info[i]) < 0) {
  268. memdelete(p_joypad.abs_info[i]);
  269. p_joypad.abs_info[i] = nullptr;
  270. }
  271. }
  272. }
  273. p_joypad.force_feedback = false;
  274. p_joypad.ff_effect_timestamp = 0;
  275. unsigned long ffbit[NBITS(FF_CNT)];
  276. if (ioctl(p_joypad.fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) {
  277. if (test_bit(FF_RUMBLE, ffbit)) {
  278. p_joypad.force_feedback = true;
  279. }
  280. }
  281. }
  282. void JoypadLinux::open_joypad(const char *p_path) {
  283. int joy_num = input->get_unused_joy_id();
  284. int fd = open(p_path, O_RDWR | O_NONBLOCK);
  285. if (fd != -1 && joy_num != -1) {
  286. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  287. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  288. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  289. // add to attached devices so we don't try to open it again
  290. attached_devices.push_back(String(p_path));
  291. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  292. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  293. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  294. close(fd);
  295. return;
  296. }
  297. // Check if the device supports basic gamepad events
  298. bool has_abs_left = (test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit));
  299. bool has_abs_right = (test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit));
  300. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && (has_abs_left || has_abs_right))) {
  301. close(fd);
  302. return;
  303. }
  304. char uid[128];
  305. char namebuf[128];
  306. String name = "";
  307. input_id inpid;
  308. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  309. name = namebuf;
  310. }
  311. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  312. close(fd);
  313. return;
  314. }
  315. MutexLock lock(joypads_mutex[joy_num]);
  316. Joypad &joypad = joypads[joy_num];
  317. joypad.reset();
  318. joypad.fd = fd;
  319. joypad.devpath = String(p_path);
  320. setup_joypad_properties(joypad);
  321. sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0);
  322. if (inpid.vendor && inpid.product && inpid.version) {
  323. uint16_t vendor = BSWAP16(inpid.vendor);
  324. uint16_t product = BSWAP16(inpid.product);
  325. uint16_t version = BSWAP16(inpid.version);
  326. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
  327. input->joy_connection_changed(joy_num, true, name, uid);
  328. } else {
  329. String uidname = uid;
  330. int uidlen = MIN(name.length(), 11);
  331. for (int i = 0; i < uidlen; i++) {
  332. uidname = uidname + _hex_str(name[i]);
  333. }
  334. uidname += "00";
  335. input->joy_connection_changed(joy_num, true, name, uidname);
  336. }
  337. }
  338. }
  339. void JoypadLinux::joypad_vibration_start(Joypad &p_joypad, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
  340. if (!p_joypad.force_feedback || p_joypad.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  341. return;
  342. }
  343. if (p_joypad.ff_effect_id != -1) {
  344. joypad_vibration_stop(p_joypad, p_timestamp);
  345. }
  346. struct ff_effect effect;
  347. effect.type = FF_RUMBLE;
  348. effect.id = -1;
  349. effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
  350. effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
  351. effect.replay.length = floor(p_duration * 1000);
  352. effect.replay.delay = 0;
  353. if (ioctl(p_joypad.fd, EVIOCSFF, &effect) < 0) {
  354. return;
  355. }
  356. struct input_event play;
  357. play.type = EV_FF;
  358. play.code = effect.id;
  359. play.value = 1;
  360. if (write(p_joypad.fd, (const void *)&play, sizeof(play)) == -1) {
  361. print_verbose("Couldn't write to Joypad device.");
  362. }
  363. p_joypad.ff_effect_id = effect.id;
  364. p_joypad.ff_effect_timestamp = p_timestamp;
  365. }
  366. void JoypadLinux::joypad_vibration_stop(Joypad &p_joypad, uint64_t p_timestamp) {
  367. if (!p_joypad.force_feedback || p_joypad.fd == -1 || p_joypad.ff_effect_id == -1) {
  368. return;
  369. }
  370. if (ioctl(p_joypad.fd, EVIOCRMFF, p_joypad.ff_effect_id) < 0) {
  371. return;
  372. }
  373. p_joypad.ff_effect_id = -1;
  374. p_joypad.ff_effect_timestamp = p_timestamp;
  375. }
  376. float JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  377. int min = p_abs->minimum;
  378. int max = p_abs->maximum;
  379. // Convert to a value between -1.0f and 1.0f.
  380. return 2.0f * (p_value - min) / (max - min) - 1.0f;
  381. }
  382. void JoypadLinux::joypad_events_thread_func(void *p_user) {
  383. if (p_user) {
  384. JoypadLinux *joy = (JoypadLinux *)p_user;
  385. joy->joypad_events_thread_run();
  386. }
  387. }
  388. void JoypadLinux::joypad_events_thread_run() {
  389. while (!joypad_events_exit.is_set()) {
  390. bool no_events = true;
  391. for (int i = 0; i < JOYPADS_MAX; i++) {
  392. MutexLock lock(joypads_mutex[i]);
  393. Joypad &joypad = joypads[i];
  394. if (joypad.fd == -1) {
  395. continue;
  396. }
  397. input_event event;
  398. while (read(joypad.fd, &event, sizeof(event)) > 0) {
  399. no_events = false;
  400. JoypadEvent joypad_event;
  401. joypad_event.type = event.type;
  402. joypad_event.code = event.code;
  403. joypad_event.value = event.value;
  404. joypad.events.push_back(joypad_event);
  405. }
  406. if (errno != EAGAIN) {
  407. close_joypad(joypad, i);
  408. }
  409. }
  410. if (no_events) {
  411. usleep(10000); // 10ms
  412. }
  413. }
  414. }
  415. void JoypadLinux::process_joypads() {
  416. for (int i = 0; i < JOYPADS_MAX; i++) {
  417. MutexLock lock(joypads_mutex[i]);
  418. Joypad &joypad = joypads[i];
  419. if (joypad.fd == -1) {
  420. continue;
  421. }
  422. for (uint32_t j = 0; j < joypad.events.size(); j++) {
  423. const JoypadEvent &joypad_event = joypad.events[j];
  424. // joypad_event may be tainted and out of MAX_KEY range, which will cause
  425. // joypad.key_map[joypad_event.code] to crash
  426. if (joypad_event.code >= MAX_KEY) {
  427. return;
  428. }
  429. switch (joypad_event.type) {
  430. case EV_KEY:
  431. input->joy_button(i, (JoyButton)joypad.key_map[joypad_event.code], joypad_event.value);
  432. break;
  433. case EV_ABS:
  434. switch (joypad_event.code) {
  435. case ABS_HAT0X:
  436. if (joypad_event.value != 0) {
  437. if (joypad_event.value < 0) {
  438. joypad.dpad.set_flag(HatMask::LEFT);
  439. joypad.dpad.clear_flag(HatMask::RIGHT);
  440. } else {
  441. joypad.dpad.set_flag(HatMask::RIGHT);
  442. joypad.dpad.clear_flag(HatMask::LEFT);
  443. }
  444. } else {
  445. joypad.dpad.clear_flag(HatMask::LEFT);
  446. joypad.dpad.clear_flag(HatMask::RIGHT);
  447. }
  448. input->joy_hat(i, joypad.dpad);
  449. break;
  450. case ABS_HAT0Y:
  451. if (joypad_event.value != 0) {
  452. if (joypad_event.value < 0) {
  453. joypad.dpad.set_flag(HatMask::UP);
  454. joypad.dpad.clear_flag(HatMask::DOWN);
  455. } else {
  456. joypad.dpad.set_flag(HatMask::DOWN);
  457. joypad.dpad.clear_flag(HatMask::UP);
  458. }
  459. } else {
  460. joypad.dpad.clear_flag(HatMask::UP);
  461. joypad.dpad.clear_flag(HatMask::DOWN);
  462. }
  463. input->joy_hat(i, joypad.dpad);
  464. break;
  465. default:
  466. if (joypad_event.code >= MAX_ABS) {
  467. return;
  468. }
  469. if (joypad.abs_map[joypad_event.code] != -1 && joypad.abs_info[joypad_event.code]) {
  470. float value = axis_correct(joypad.abs_info[joypad_event.code], joypad_event.value);
  471. joypad.curr_axis[joypad.abs_map[joypad_event.code]] = value;
  472. }
  473. break;
  474. }
  475. break;
  476. }
  477. }
  478. joypad.events.clear();
  479. for (int j = 0; j < MAX_ABS; j++) {
  480. int index = joypad.abs_map[j];
  481. if (index != -1) {
  482. input->joy_axis(i, (JoyAxis)index, joypad.curr_axis[index]);
  483. }
  484. }
  485. if (joypad.force_feedback) {
  486. uint64_t timestamp = input->get_joy_vibration_timestamp(i);
  487. if (timestamp > joypad.ff_effect_timestamp) {
  488. Vector2 strength = input->get_joy_vibration_strength(i);
  489. float duration = input->get_joy_vibration_duration(i);
  490. if (strength.x == 0 && strength.y == 0) {
  491. joypad_vibration_stop(joypad, timestamp);
  492. } else {
  493. joypad_vibration_start(joypad, strength.x, strength.y, duration, timestamp);
  494. }
  495. }
  496. }
  497. }
  498. }
  499. #endif // JOYDEV_ENABLED