joypad_linux.cpp 15 KB

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