joypad_linux.cpp 15 KB

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