🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

976 lines
34 KiB

  1. /*
  2. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely.
  9. */
  10. /* Simple program to test the SDL game controller routines */
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include "SDL.h"
  15. #include "testutils.h"
  16. #ifdef __EMSCRIPTEN__
  17. #include <emscripten/emscripten.h>
  18. #endif
  19. #ifndef SDL_JOYSTICK_DISABLED
  20. #define SCREEN_WIDTH 512
  21. #define SCREEN_HEIGHT 320
  22. #define BUTTON_SIZE 50
  23. #define AXIS_SIZE 50
  24. /* This is indexed by SDL_GameControllerButton. */
  25. static const struct { int x; int y; } button_positions[] = {
  26. {387, 167}, /* SDL_CONTROLLER_BUTTON_A */
  27. {431, 132}, /* SDL_CONTROLLER_BUTTON_B */
  28. {342, 132}, /* SDL_CONTROLLER_BUTTON_X */
  29. {389, 101}, /* SDL_CONTROLLER_BUTTON_Y */
  30. {174, 132}, /* SDL_CONTROLLER_BUTTON_BACK */
  31. {232, 128}, /* SDL_CONTROLLER_BUTTON_GUIDE */
  32. {289, 132}, /* SDL_CONTROLLER_BUTTON_START */
  33. {75, 154}, /* SDL_CONTROLLER_BUTTON_LEFTSTICK */
  34. {305, 230}, /* SDL_CONTROLLER_BUTTON_RIGHTSTICK */
  35. {77, 40}, /* SDL_CONTROLLER_BUTTON_LEFTSHOULDER */
  36. {396, 36}, /* SDL_CONTROLLER_BUTTON_RIGHTSHOULDER */
  37. {154, 188}, /* SDL_CONTROLLER_BUTTON_DPAD_UP */
  38. {154, 249}, /* SDL_CONTROLLER_BUTTON_DPAD_DOWN */
  39. {116, 217}, /* SDL_CONTROLLER_BUTTON_DPAD_LEFT */
  40. {186, 217}, /* SDL_CONTROLLER_BUTTON_DPAD_RIGHT */
  41. {232, 174}, /* SDL_CONTROLLER_BUTTON_MISC1 */
  42. {132, 135}, /* SDL_CONTROLLER_BUTTON_PADDLE1 */
  43. {330, 135}, /* SDL_CONTROLLER_BUTTON_PADDLE2 */
  44. {132, 175}, /* SDL_CONTROLLER_BUTTON_PADDLE3 */
  45. {330, 175}, /* SDL_CONTROLLER_BUTTON_PADDLE4 */
  46. {0, 0}, /* SDL_CONTROLLER_BUTTON_TOUCHPAD */
  47. };
  48. SDL_COMPILE_TIME_ASSERT(button_positions, SDL_arraysize(button_positions) == SDL_CONTROLLER_BUTTON_MAX);
  49. /* This is indexed by SDL_GameControllerAxis. */
  50. static const struct { int x; int y; double angle; } axis_positions[] = {
  51. {74, 153, 270.0}, /* LEFTX */
  52. {74, 153, 0.0}, /* LEFTY */
  53. {306, 231, 270.0}, /* RIGHTX */
  54. {306, 231, 0.0}, /* RIGHTY */
  55. {91, -20, 0.0}, /* TRIGGERLEFT */
  56. {375, -20, 0.0}, /* TRIGGERRIGHT */
  57. };
  58. SDL_COMPILE_TIME_ASSERT(axis_positions, SDL_arraysize(axis_positions) == SDL_CONTROLLER_AXIS_MAX);
  59. /* This is indexed by SDL_JoystickPowerLevel + 1. */
  60. static const char* power_level_strings[] = {
  61. "unknown", /* SDL_JOYSTICK_POWER_UNKNOWN */
  62. "empty", /* SDL_JOYSTICK_POWER_EMPTY */
  63. "low", /* SDL_JOYSTICK_POWER_LOW */
  64. "medium", /* SDL_JOYSTICK_POWER_MEDIUM */
  65. "full", /* SDL_JOYSTICK_POWER_FULL */
  66. "wired", /* SDL_JOYSTICK_POWER_WIRED */
  67. };
  68. SDL_COMPILE_TIME_ASSERT(power_level_strings, SDL_arraysize(power_level_strings) == SDL_JOYSTICK_POWER_MAX + 1);
  69. static SDL_Window *window = NULL;
  70. static SDL_Renderer *screen = NULL;
  71. static SDL_bool retval = SDL_FALSE;
  72. static SDL_bool done = SDL_FALSE;
  73. static SDL_bool set_LED = SDL_FALSE;
  74. static int trigger_effect = 0;
  75. static SDL_Texture *background_front, *background_back, *button_texture, *axis_texture;
  76. static SDL_GameController *gamecontroller;
  77. static SDL_GameController **gamecontrollers;
  78. static int num_controllers = 0;
  79. static SDL_Joystick *virtual_joystick = NULL;
  80. static SDL_GameControllerAxis virtual_axis_active = SDL_CONTROLLER_AXIS_INVALID;
  81. static int virtual_axis_start_x;
  82. static int virtual_axis_start_y;
  83. static SDL_GameControllerButton virtual_button_active = SDL_CONTROLLER_BUTTON_INVALID;
  84. static void UpdateWindowTitle()
  85. {
  86. if (!window) {
  87. return;
  88. }
  89. if (gamecontroller) {
  90. const char *name = SDL_GameControllerName(gamecontroller);
  91. const char *serial = SDL_GameControllerGetSerial(gamecontroller);
  92. const char *basetitle = "Game Controller Test: ";
  93. const size_t titlelen = SDL_strlen(basetitle) + (name ? SDL_strlen(name) : 0) + (serial ? 3 + SDL_strlen(serial) : 0) + 1;
  94. char *title = (char *)SDL_malloc(titlelen);
  95. retval = SDL_FALSE;
  96. done = SDL_FALSE;
  97. if (title) {
  98. SDL_strlcpy(title, basetitle, titlelen);
  99. if (name) {
  100. SDL_strlcat(title, name, titlelen);
  101. }
  102. if (serial) {
  103. SDL_strlcat(title, " (", titlelen);
  104. SDL_strlcat(title, serial, titlelen);
  105. SDL_strlcat(title, ")", titlelen);
  106. }
  107. SDL_SetWindowTitle(window, title);
  108. SDL_free(title);
  109. }
  110. } else {
  111. SDL_SetWindowTitle(window, "Waiting for controller...");
  112. }
  113. }
  114. static const char *GetSensorName(SDL_SensorType sensor)
  115. {
  116. switch (sensor) {
  117. case SDL_SENSOR_ACCEL:
  118. return "accelerometer";
  119. case SDL_SENSOR_GYRO:
  120. return "gyro";
  121. case SDL_SENSOR_ACCEL_L:
  122. return "accelerometer (L)";
  123. case SDL_SENSOR_GYRO_L:
  124. return "gyro (L)";
  125. case SDL_SENSOR_ACCEL_R:
  126. return "accelerometer (R)";
  127. case SDL_SENSOR_GYRO_R:
  128. return "gyro (R)";
  129. default:
  130. return "UNKNOWN";
  131. }
  132. }
  133. static int FindController(SDL_JoystickID controller_id)
  134. {
  135. int i;
  136. for (i = 0; i < num_controllers; ++i) {
  137. if (controller_id == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontrollers[i]))) {
  138. return i;
  139. }
  140. }
  141. return -1;
  142. }
  143. static void AddController(int device_index, SDL_bool verbose)
  144. {
  145. SDL_JoystickID controller_id = SDL_JoystickGetDeviceInstanceID(device_index);
  146. SDL_GameController *controller;
  147. SDL_GameController **controllers;
  148. Uint16 firmware_version;
  149. SDL_SensorType sensors[] = {
  150. SDL_SENSOR_ACCEL,
  151. SDL_SENSOR_GYRO,
  152. SDL_SENSOR_ACCEL_L,
  153. SDL_SENSOR_GYRO_L,
  154. SDL_SENSOR_ACCEL_R,
  155. SDL_SENSOR_GYRO_R
  156. };
  157. unsigned int i;
  158. controller_id = SDL_JoystickGetDeviceInstanceID(device_index);
  159. if (controller_id < 0) {
  160. SDL_Log("Couldn't get controller ID: %s\n", SDL_GetError());
  161. return;
  162. }
  163. if (FindController(controller_id) >= 0) {
  164. /* We already have this controller */
  165. return;
  166. }
  167. controller = SDL_GameControllerOpen(device_index);
  168. if (!controller) {
  169. SDL_Log("Couldn't open controller: %s\n", SDL_GetError());
  170. return;
  171. }
  172. controllers = (SDL_GameController **)SDL_realloc(gamecontrollers, (num_controllers + 1) * sizeof(*controllers));
  173. if (!controllers) {
  174. SDL_GameControllerClose(controller);
  175. return;
  176. }
  177. controllers[num_controllers++] = controller;
  178. gamecontrollers = controllers;
  179. gamecontroller = controller;
  180. trigger_effect = 0;
  181. if (verbose) {
  182. const char *name = SDL_GameControllerName(gamecontroller);
  183. const char *path = SDL_GameControllerPath(gamecontroller);
  184. SDL_Log("Opened game controller %s%s%s\n", name, path ? ", " : "", path ? path : "");
  185. }
  186. firmware_version = SDL_GameControllerGetFirmwareVersion(gamecontroller);
  187. if (firmware_version) {
  188. if (verbose) {
  189. SDL_Log("Firmware version: 0x%x (%d)\n", firmware_version, firmware_version);
  190. }
  191. }
  192. for (i = 0; i < SDL_arraysize(sensors); ++i) {
  193. SDL_SensorType sensor = sensors[i];
  194. if (SDL_GameControllerHasSensor(gamecontroller, sensor)) {
  195. if (verbose) {
  196. SDL_Log("Enabling %s at %.2f Hz\n", GetSensorName(sensor), SDL_GameControllerGetSensorDataRate(gamecontroller, sensor));
  197. }
  198. SDL_GameControllerSetSensorEnabled(gamecontroller, sensor, SDL_TRUE);
  199. }
  200. }
  201. if (SDL_GameControllerHasRumble(gamecontroller)) {
  202. SDL_Log("Rumble supported");
  203. }
  204. if (SDL_GameControllerHasRumbleTriggers(gamecontroller)) {
  205. SDL_Log("Trigger rumble supported");
  206. }
  207. UpdateWindowTitle();
  208. }
  209. static void SetController(SDL_JoystickID controller)
  210. {
  211. int i = FindController(controller);
  212. if (i < 0) {
  213. return;
  214. }
  215. if (gamecontroller != gamecontrollers[i]) {
  216. gamecontroller = gamecontrollers[i];
  217. UpdateWindowTitle();
  218. }
  219. }
  220. static void DelController(SDL_JoystickID controller)
  221. {
  222. int i = FindController(controller);
  223. if (i < 0) {
  224. return;
  225. }
  226. SDL_GameControllerClose(gamecontrollers[i]);
  227. --num_controllers;
  228. if (i < num_controllers) {
  229. SDL_memcpy(&gamecontrollers[i], &gamecontrollers[i+1], (num_controllers - i) * sizeof(*gamecontrollers));
  230. }
  231. if (num_controllers > 0) {
  232. gamecontroller = gamecontrollers[0];
  233. } else {
  234. gamecontroller = NULL;
  235. }
  236. UpdateWindowTitle();
  237. }
  238. static Uint16 ConvertAxisToRumble(Sint16 axisval)
  239. {
  240. /* Only start rumbling if the axis is past the halfway point */
  241. const Sint16 half_axis = (Sint16)SDL_ceil(SDL_JOYSTICK_AXIS_MAX / 2.0f);
  242. if (axisval > half_axis) {
  243. return (Uint16)(axisval - half_axis) * 4;
  244. } else {
  245. return 0;
  246. }
  247. }
  248. /* PS5 trigger effect documentation:
  249. https://controllers.fandom.com/wiki/Sony_DualSense#FFB_Trigger_Modes
  250. */
  251. typedef struct
  252. {
  253. Uint8 ucEnableBits1; /* 0 */
  254. Uint8 ucEnableBits2; /* 1 */
  255. Uint8 ucRumbleRight; /* 2 */
  256. Uint8 ucRumbleLeft; /* 3 */
  257. Uint8 ucHeadphoneVolume; /* 4 */
  258. Uint8 ucSpeakerVolume; /* 5 */
  259. Uint8 ucMicrophoneVolume; /* 6 */
  260. Uint8 ucAudioEnableBits; /* 7 */
  261. Uint8 ucMicLightMode; /* 8 */
  262. Uint8 ucAudioMuteBits; /* 9 */
  263. Uint8 rgucRightTriggerEffect[11]; /* 10 */
  264. Uint8 rgucLeftTriggerEffect[11]; /* 21 */
  265. Uint8 rgucUnknown1[6]; /* 32 */
  266. Uint8 ucLedFlags; /* 38 */
  267. Uint8 rgucUnknown2[2]; /* 39 */
  268. Uint8 ucLedAnim; /* 41 */
  269. Uint8 ucLedBrightness; /* 42 */
  270. Uint8 ucPadLights; /* 43 */
  271. Uint8 ucLedRed; /* 44 */
  272. Uint8 ucLedGreen; /* 45 */
  273. Uint8 ucLedBlue; /* 46 */
  274. } DS5EffectsState_t;
  275. static void CyclePS5TriggerEffect()
  276. {
  277. DS5EffectsState_t state;
  278. Uint8 effects[3][11] =
  279. {
  280. /* Clear trigger effect */
  281. { 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  282. /* Constant resistance across entire trigger pull */
  283. { 0x01, 0, 110, 0, 0, 0, 0, 0, 0, 0, 0 },
  284. /* Resistance and vibration when trigger is pulled */
  285. { 0x06, 15, 63, 128, 0, 0, 0, 0, 0, 0, 0 },
  286. };
  287. trigger_effect = (trigger_effect + 1) % SDL_arraysize(effects);
  288. SDL_zero(state);
  289. state.ucEnableBits1 |= (0x04 | 0x08); /* Modify right and left trigger effect respectively */
  290. SDL_memcpy(state.rgucRightTriggerEffect, effects[trigger_effect], sizeof(effects[trigger_effect]));
  291. SDL_memcpy(state.rgucLeftTriggerEffect, effects[trigger_effect], sizeof(effects[trigger_effect]));
  292. SDL_GameControllerSendEffect(gamecontroller, &state, sizeof(state));
  293. }
  294. static SDL_bool ShowingFront()
  295. {
  296. SDL_bool showing_front = SDL_TRUE;
  297. int i;
  298. if (gamecontroller) {
  299. /* Show the back of the controller if the paddles are being held */
  300. for (i = SDL_CONTROLLER_BUTTON_PADDLE1; i <= SDL_CONTROLLER_BUTTON_PADDLE4; ++i) {
  301. if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
  302. showing_front = SDL_FALSE;
  303. break;
  304. }
  305. }
  306. }
  307. if ((SDL_GetModState() & KMOD_SHIFT) != 0) {
  308. showing_front = SDL_FALSE;
  309. }
  310. return showing_front;
  311. }
  312. static void SDLCALL VirtualControllerSetPlayerIndex(void *userdata, int player_index)
  313. {
  314. SDL_Log("Virtual Controller: player index set to %d\n", player_index);
  315. }
  316. static int SDLCALL VirtualControllerRumble(void *userdata, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  317. {
  318. SDL_Log("Virtual Controller: rumble set to %d/%d\n", low_frequency_rumble, high_frequency_rumble);
  319. return 0;
  320. }
  321. static int SDLCALL VirtualControllerRumbleTriggers(void *userdata, Uint16 left_rumble, Uint16 right_rumble)
  322. {
  323. SDL_Log("Virtual Controller: trigger rumble set to %d/%d\n", left_rumble, right_rumble);
  324. return 0;
  325. }
  326. static int SDLCALL VirtualControllerSetLED(void *userdata, Uint8 red, Uint8 green, Uint8 blue)
  327. {
  328. SDL_Log("Virtual Controller: LED set to RGB %d,%d,%d\n", red, green, blue);
  329. return 0;
  330. }
  331. static void OpenVirtualController()
  332. {
  333. SDL_VirtualJoystickDesc desc;
  334. int virtual_index;
  335. SDL_zero(desc);
  336. desc.version = SDL_VIRTUAL_JOYSTICK_DESC_VERSION;
  337. desc.type = SDL_JOYSTICK_TYPE_GAMECONTROLLER;
  338. desc.naxes = SDL_CONTROLLER_AXIS_MAX;
  339. desc.nbuttons = SDL_CONTROLLER_BUTTON_MAX;
  340. desc.SetPlayerIndex = VirtualControllerSetPlayerIndex;
  341. desc.Rumble = VirtualControllerRumble;
  342. desc.RumbleTriggers = VirtualControllerRumbleTriggers;
  343. desc.SetLED = VirtualControllerSetLED;
  344. virtual_index = SDL_JoystickAttachVirtualEx(&desc);
  345. if (virtual_index < 0) {
  346. SDL_Log("Couldn't open virtual device: %s\n", SDL_GetError());
  347. } else {
  348. virtual_joystick = SDL_JoystickOpen(virtual_index);
  349. if (!virtual_joystick) {
  350. SDL_Log("Couldn't open virtual device: %s\n", SDL_GetError());
  351. }
  352. }
  353. }
  354. static void CloseVirtualController()
  355. {
  356. int i;
  357. for (i = SDL_NumJoysticks(); i--; ) {
  358. if (SDL_JoystickIsVirtual(i)) {
  359. SDL_JoystickDetachVirtual(i);
  360. }
  361. }
  362. if (virtual_joystick) {
  363. SDL_JoystickClose(virtual_joystick);
  364. virtual_joystick = NULL;
  365. }
  366. }
  367. static SDL_GameControllerButton FindButtonAtPosition(int x, int y)
  368. {
  369. SDL_Point point;
  370. int i;
  371. SDL_bool showing_front = ShowingFront();
  372. point.x = x;
  373. point.y = y;
  374. for (i = 0; i < SDL_CONTROLLER_BUTTON_TOUCHPAD; ++i) {
  375. SDL_bool on_front = (i < SDL_CONTROLLER_BUTTON_PADDLE1 || i > SDL_CONTROLLER_BUTTON_PADDLE4);
  376. if (on_front == showing_front) {
  377. SDL_Rect rect;
  378. rect.x = button_positions[i].x;
  379. rect.y = button_positions[i].y;
  380. rect.w = BUTTON_SIZE;
  381. rect.h = BUTTON_SIZE;
  382. if (SDL_PointInRect(&point, &rect)) {
  383. return (SDL_GameControllerButton)i;
  384. }
  385. }
  386. }
  387. return SDL_CONTROLLER_BUTTON_INVALID;
  388. }
  389. static SDL_GameControllerAxis FindAxisAtPosition(int x, int y)
  390. {
  391. SDL_Point point;
  392. int i;
  393. SDL_bool showing_front = ShowingFront();
  394. point.x = x;
  395. point.y = y;
  396. for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) {
  397. if (showing_front) {
  398. SDL_Rect rect;
  399. rect.x = axis_positions[i].x;
  400. rect.y = axis_positions[i].y;
  401. rect.w = AXIS_SIZE;
  402. rect.h = AXIS_SIZE;
  403. if (SDL_PointInRect(&point, &rect)) {
  404. return (SDL_GameControllerAxis)i;
  405. }
  406. }
  407. }
  408. return SDL_CONTROLLER_AXIS_INVALID;
  409. }
  410. static void VirtualControllerMouseMotion(int x, int y)
  411. {
  412. if (virtual_button_active != SDL_CONTROLLER_BUTTON_INVALID) {
  413. if (virtual_axis_active != SDL_CONTROLLER_AXIS_INVALID) {
  414. const int MOVING_DISTANCE = 2;
  415. if (SDL_abs(x - virtual_axis_start_x) >= MOVING_DISTANCE ||
  416. SDL_abs(y - virtual_axis_start_y) >= MOVING_DISTANCE) {
  417. SDL_JoystickSetVirtualButton(virtual_joystick, virtual_button_active, SDL_RELEASED);
  418. virtual_button_active = SDL_CONTROLLER_BUTTON_INVALID;
  419. }
  420. }
  421. }
  422. if (virtual_axis_active != SDL_CONTROLLER_AXIS_INVALID) {
  423. if (virtual_axis_active == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
  424. virtual_axis_active == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) {
  425. int range = (SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN);
  426. float distance = SDL_clamp(((float)y - virtual_axis_start_y) / AXIS_SIZE, 0.0f, 1.0f);
  427. Sint16 value = (Sint16)(SDL_JOYSTICK_AXIS_MIN + (distance * range));
  428. SDL_JoystickSetVirtualAxis(virtual_joystick, virtual_axis_active, value);
  429. } else {
  430. float distanceX = SDL_clamp(((float)x - virtual_axis_start_x) / AXIS_SIZE, -1.0f, 1.0f);
  431. float distanceY = SDL_clamp(((float)y - virtual_axis_start_y) / AXIS_SIZE, -1.0f, 1.0f);
  432. Sint16 valueX, valueY;
  433. if (distanceX >= 0) {
  434. valueX = (Sint16)(distanceX * SDL_JOYSTICK_AXIS_MAX);
  435. } else {
  436. valueX = (Sint16)(distanceX * -SDL_JOYSTICK_AXIS_MIN);
  437. }
  438. if (distanceY >= 0) {
  439. valueY = (Sint16)(distanceY * SDL_JOYSTICK_AXIS_MAX);
  440. } else {
  441. valueY = (Sint16)(distanceY * -SDL_JOYSTICK_AXIS_MIN);
  442. }
  443. SDL_JoystickSetVirtualAxis(virtual_joystick, virtual_axis_active, valueX);
  444. SDL_JoystickSetVirtualAxis(virtual_joystick, virtual_axis_active+1, valueY);
  445. }
  446. }
  447. }
  448. static void VirtualControllerMouseDown(int x, int y)
  449. {
  450. SDL_GameControllerButton button;
  451. SDL_GameControllerAxis axis;
  452. button = FindButtonAtPosition(x, y);
  453. if (button != SDL_CONTROLLER_BUTTON_INVALID) {
  454. virtual_button_active = button;
  455. SDL_JoystickSetVirtualButton(virtual_joystick, virtual_button_active, SDL_PRESSED);
  456. }
  457. axis = FindAxisAtPosition(x, y);
  458. if (axis != SDL_CONTROLLER_AXIS_INVALID) {
  459. virtual_axis_active = axis;
  460. virtual_axis_start_x = x;
  461. virtual_axis_start_y = y;
  462. }
  463. }
  464. static void VirtualControllerMouseUp(int x, int y)
  465. {
  466. if (virtual_button_active != SDL_CONTROLLER_BUTTON_INVALID) {
  467. SDL_JoystickSetVirtualButton(virtual_joystick, virtual_button_active, SDL_RELEASED);
  468. virtual_button_active = SDL_CONTROLLER_BUTTON_INVALID;
  469. }
  470. if (virtual_axis_active != SDL_CONTROLLER_AXIS_INVALID) {
  471. if (virtual_axis_active == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
  472. virtual_axis_active == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) {
  473. SDL_JoystickSetVirtualAxis(virtual_joystick, virtual_axis_active, SDL_JOYSTICK_AXIS_MIN);
  474. } else {
  475. SDL_JoystickSetVirtualAxis(virtual_joystick, virtual_axis_active, 0);
  476. SDL_JoystickSetVirtualAxis(virtual_joystick, virtual_axis_active+1, 0);
  477. }
  478. virtual_axis_active = SDL_CONTROLLER_AXIS_INVALID;
  479. }
  480. }
  481. void
  482. loop(void *arg)
  483. {
  484. SDL_Event event;
  485. int i;
  486. SDL_bool showing_front;
  487. /* Update to get the current event state */
  488. SDL_PumpEvents();
  489. /* Process all currently pending events */
  490. while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) == 1) {
  491. switch (event.type) {
  492. case SDL_CONTROLLERDEVICEADDED:
  493. SDL_Log("Game controller device %d added.\n", (int) SDL_JoystickGetDeviceInstanceID(event.cdevice.which));
  494. AddController(event.cdevice.which, SDL_TRUE);
  495. break;
  496. case SDL_CONTROLLERDEVICEREMOVED:
  497. SDL_Log("Game controller device %d removed.\n", (int) event.cdevice.which);
  498. DelController(event.cdevice.which);
  499. break;
  500. case SDL_CONTROLLERTOUCHPADDOWN:
  501. case SDL_CONTROLLERTOUCHPADMOTION:
  502. case SDL_CONTROLLERTOUCHPADUP:
  503. SDL_Log("Controller %" SDL_PRIs32 " touchpad %" SDL_PRIs32 " finger %" SDL_PRIs32 " %s %.2f, %.2f, %.2f\n",
  504. event.ctouchpad.which,
  505. event.ctouchpad.touchpad,
  506. event.ctouchpad.finger,
  507. (event.type == SDL_CONTROLLERTOUCHPADDOWN ? "pressed at" : (event.type == SDL_CONTROLLERTOUCHPADUP ? "released at" : "moved to")),
  508. event.ctouchpad.x,
  509. event.ctouchpad.y,
  510. event.ctouchpad.pressure);
  511. break;
  512. #define VERBOSE_SENSORS
  513. #ifdef VERBOSE_SENSORS
  514. case SDL_CONTROLLERSENSORUPDATE:
  515. SDL_Log("Controller %" SDL_PRIs32 " sensor %s: %.2f, %.2f, %.2f (%" SDL_PRIu64 ")\n",
  516. event.csensor.which,
  517. GetSensorName((SDL_SensorType) event.csensor.sensor),
  518. event.csensor.data[0],
  519. event.csensor.data[1],
  520. event.csensor.data[2],
  521. event.csensor.timestamp_us);
  522. break;
  523. #endif /* VERBOSE_SENSORS */
  524. #define VERBOSE_AXES
  525. #ifdef VERBOSE_AXES
  526. case SDL_CONTROLLERAXISMOTION:
  527. if (event.caxis.value <= (-SDL_JOYSTICK_AXIS_MAX / 2) || event.caxis.value >= (SDL_JOYSTICK_AXIS_MAX / 2)) {
  528. SetController(event.caxis.which);
  529. }
  530. SDL_Log("Controller %" SDL_PRIs32 " axis %s changed to %d\n", event.caxis.which, SDL_GameControllerGetStringForAxis((SDL_GameControllerAxis) event.caxis.axis), event.caxis.value);
  531. break;
  532. #endif /* VERBOSE_AXES */
  533. case SDL_CONTROLLERBUTTONDOWN:
  534. case SDL_CONTROLLERBUTTONUP:
  535. if (event.type == SDL_CONTROLLERBUTTONDOWN) {
  536. SetController(event.cbutton.which);
  537. }
  538. SDL_Log("Controller %" SDL_PRIs32 " button %s %s\n", event.cbutton.which, SDL_GameControllerGetStringForButton((SDL_GameControllerButton) event.cbutton.button), event.cbutton.state ? "pressed" : "released");
  539. /* Cycle PS5 trigger effects when the microphone button is pressed */
  540. if (event.type == SDL_CONTROLLERBUTTONDOWN &&
  541. event.cbutton.button == SDL_CONTROLLER_BUTTON_MISC1 &&
  542. SDL_GameControllerGetType(gamecontroller) == SDL_CONTROLLER_TYPE_PS5) {
  543. CyclePS5TriggerEffect();
  544. }
  545. break;
  546. case SDL_JOYBATTERYUPDATED:
  547. SDL_Log("Controller %" SDL_PRIs32 " battery state changed to %s\n", event.jbattery.which, power_level_strings[event.jbattery.level + 1]);
  548. break;
  549. case SDL_MOUSEBUTTONDOWN:
  550. if (virtual_joystick) {
  551. VirtualControllerMouseDown(event.button.x, event.button.y);
  552. }
  553. break;
  554. case SDL_MOUSEBUTTONUP:
  555. if (virtual_joystick) {
  556. VirtualControllerMouseUp(event.button.x, event.button.y);
  557. }
  558. break;
  559. case SDL_MOUSEMOTION:
  560. if (virtual_joystick) {
  561. VirtualControllerMouseMotion(event.motion.x, event.motion.y);
  562. }
  563. break;
  564. case SDL_KEYDOWN:
  565. if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) {
  566. if (gamecontroller) {
  567. int player_index = (event.key.keysym.sym - SDLK_0);
  568. SDL_GameControllerSetPlayerIndex(gamecontroller, player_index);
  569. }
  570. break;
  571. }
  572. if (event.key.keysym.sym == SDLK_a) {
  573. OpenVirtualController();
  574. break;
  575. }
  576. if (event.key.keysym.sym == SDLK_d) {
  577. CloseVirtualController();
  578. break;
  579. }
  580. if (event.key.keysym.sym != SDLK_ESCAPE) {
  581. break;
  582. }
  583. SDL_FALLTHROUGH;
  584. case SDL_QUIT:
  585. done = SDL_TRUE;
  586. break;
  587. default:
  588. break;
  589. }
  590. }
  591. showing_front = ShowingFront();
  592. /* blank screen, set up for drawing this frame. */
  593. SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
  594. SDL_RenderClear(screen);
  595. SDL_RenderCopy(screen, showing_front ? background_front : background_back, NULL, NULL);
  596. if (gamecontroller) {
  597. /* Update visual controller state */
  598. for (i = 0; i < SDL_CONTROLLER_BUTTON_TOUCHPAD; ++i) {
  599. if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
  600. SDL_bool on_front = (i < SDL_CONTROLLER_BUTTON_PADDLE1 || i > SDL_CONTROLLER_BUTTON_PADDLE4);
  601. if (on_front == showing_front) {
  602. SDL_Rect dst;
  603. dst.x = button_positions[i].x;
  604. dst.y = button_positions[i].y;
  605. dst.w = BUTTON_SIZE;
  606. dst.h = BUTTON_SIZE;
  607. SDL_RenderCopyEx(screen, button_texture, NULL, &dst, 0, NULL, SDL_FLIP_NONE);
  608. }
  609. }
  610. }
  611. if (showing_front) {
  612. for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) {
  613. const Sint16 deadzone = 8000; /* !!! FIXME: real deadzone */
  614. const Sint16 value = SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i));
  615. if (value < -deadzone) {
  616. const double angle = axis_positions[i].angle;
  617. SDL_Rect dst;
  618. dst.x = axis_positions[i].x;
  619. dst.y = axis_positions[i].y;
  620. dst.w = AXIS_SIZE;
  621. dst.h = AXIS_SIZE;
  622. SDL_RenderCopyEx(screen, axis_texture, NULL, &dst, angle, NULL, SDL_FLIP_NONE);
  623. } else if (value > deadzone) {
  624. const double angle = axis_positions[i].angle + 180.0;
  625. SDL_Rect dst;
  626. dst.x = axis_positions[i].x;
  627. dst.y = axis_positions[i].y;
  628. dst.w = AXIS_SIZE;
  629. dst.h = AXIS_SIZE;
  630. SDL_RenderCopyEx(screen, axis_texture, NULL, &dst, angle, NULL, SDL_FLIP_NONE);
  631. }
  632. }
  633. }
  634. /* Update LED based on left thumbstick position */
  635. {
  636. Sint16 x = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_LEFTX);
  637. Sint16 y = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_LEFTY);
  638. if (!set_LED) {
  639. set_LED = (x < -8000 || x > 8000 || y > 8000);
  640. }
  641. if (set_LED) {
  642. Uint8 r, g, b;
  643. if (x < 0) {
  644. r = (Uint8)(((int)(~x) * 255) / 32767);
  645. b = 0;
  646. } else {
  647. r = 0;
  648. b = (Uint8)(((int)(x) * 255) / 32767);
  649. }
  650. if (y > 0) {
  651. g = (Uint8)(((int)(y) * 255) / 32767);
  652. } else {
  653. g = 0;
  654. }
  655. SDL_GameControllerSetLED(gamecontroller, r, g, b);
  656. }
  657. }
  658. if (trigger_effect == 0) {
  659. /* Update rumble based on trigger state */
  660. {
  661. Sint16 left = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
  662. Sint16 right = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);
  663. Uint16 low_frequency_rumble = ConvertAxisToRumble(left);
  664. Uint16 high_frequency_rumble = ConvertAxisToRumble(right);
  665. SDL_GameControllerRumble(gamecontroller, low_frequency_rumble, high_frequency_rumble, 250);
  666. }
  667. /* Update trigger rumble based on thumbstick state */
  668. {
  669. Sint16 left = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_LEFTY);
  670. Sint16 right = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_RIGHTY);
  671. Uint16 left_rumble = ConvertAxisToRumble(~left);
  672. Uint16 right_rumble = ConvertAxisToRumble(~right);
  673. SDL_GameControllerRumbleTriggers(gamecontroller, left_rumble, right_rumble, 250);
  674. }
  675. }
  676. }
  677. SDL_Delay(16);
  678. SDL_RenderPresent(screen);
  679. #ifdef __EMSCRIPTEN__
  680. if (done) {
  681. emscripten_cancel_main_loop();
  682. }
  683. #endif
  684. }
  685. int
  686. main(int argc, char *argv[])
  687. {
  688. int i;
  689. int controller_count = 0;
  690. int controller_index = 0;
  691. char guid[64];
  692. SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
  693. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, "1");
  694. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE, "1");
  695. SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_STEAM, "1");
  696. SDL_SetHint(SDL_HINT_JOYSTICK_ROG_CHAKRAM, "1");
  697. SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
  698. SDL_SetHint(SDL_HINT_LINUX_JOYSTICK_DEADZONES, "1");
  699. /* Enable standard application logging */
  700. SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
  701. /* Initialize SDL (Note: video is required to start event loop) */
  702. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER ) < 0) {
  703. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
  704. return 1;
  705. }
  706. SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");
  707. /* Print information about the mappings */
  708. if (argv[1] && SDL_strcmp(argv[1], "--mappings") == 0) {
  709. SDL_Log("Supported mappings:\n");
  710. for (i = 0; i < SDL_GameControllerNumMappings(); ++i) {
  711. char *mapping = SDL_GameControllerMappingForIndex(i);
  712. if (mapping) {
  713. SDL_Log("\t%s\n", mapping);
  714. SDL_free(mapping);
  715. }
  716. }
  717. SDL_Log("\n");
  718. }
  719. /* Print information about the controller */
  720. for (i = 0; i < SDL_NumJoysticks(); ++i) {
  721. const char *name;
  722. const char *path;
  723. const char *description;
  724. SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i),
  725. guid, sizeof (guid));
  726. if (SDL_IsGameController(i)) {
  727. controller_count++;
  728. name = SDL_GameControllerNameForIndex(i);
  729. path = SDL_GameControllerPathForIndex(i);
  730. switch (SDL_GameControllerTypeForIndex(i)) {
  731. case SDL_CONTROLLER_TYPE_AMAZON_LUNA:
  732. description = "Amazon Luna Controller";
  733. break;
  734. case SDL_CONTROLLER_TYPE_GOOGLE_STADIA:
  735. description = "Google Stadia Controller";
  736. break;
  737. case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT:
  738. case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT:
  739. case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR:
  740. description = "Nintendo Switch Joy-Con";
  741. break;
  742. case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO:
  743. description = "Nintendo Switch Pro Controller";
  744. break;
  745. case SDL_CONTROLLER_TYPE_PS3:
  746. description = "PS3 Controller";
  747. break;
  748. case SDL_CONTROLLER_TYPE_PS4:
  749. description = "PS4 Controller";
  750. break;
  751. case SDL_CONTROLLER_TYPE_PS5:
  752. description = "PS5 Controller";
  753. break;
  754. case SDL_CONTROLLER_TYPE_XBOX360:
  755. description = "XBox 360 Controller";
  756. break;
  757. case SDL_CONTROLLER_TYPE_XBOXONE:
  758. description = "XBox One Controller";
  759. break;
  760. case SDL_CONTROLLER_TYPE_VIRTUAL:
  761. description = "Virtual Game Controller";
  762. break;
  763. default:
  764. description = "Game Controller";
  765. break;
  766. }
  767. AddController(i, SDL_FALSE);
  768. } else {
  769. name = SDL_JoystickNameForIndex(i);
  770. path = SDL_JoystickPathForIndex(i);
  771. description = "Joystick";
  772. }
  773. SDL_Log("%s %d: %s%s%s (guid %s, VID 0x%.4x, PID 0x%.4x, player index = %d)\n",
  774. description, i, name ? name : "Unknown", path ? ", " : "", path ? path : "", guid,
  775. SDL_JoystickGetDeviceVendor(i), SDL_JoystickGetDeviceProduct(i), SDL_JoystickGetDevicePlayerIndex(i));
  776. }
  777. SDL_Log("There are %d game controller(s) attached (%d joystick(s))\n", controller_count, SDL_NumJoysticks());
  778. /* Create a window to display controller state */
  779. window = SDL_CreateWindow("Game Controller Test", SDL_WINDOWPOS_CENTERED,
  780. SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
  781. SCREEN_HEIGHT, 0);
  782. if (window == NULL) {
  783. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
  784. return 2;
  785. }
  786. screen = SDL_CreateRenderer(window, -1, 0);
  787. if (screen == NULL) {
  788. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
  789. SDL_DestroyWindow(window);
  790. return 2;
  791. }
  792. SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
  793. SDL_RenderClear(screen);
  794. SDL_RenderPresent(screen);
  795. /* scale for platforms that don't give you the window size you asked for. */
  796. SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);
  797. background_front = LoadTexture(screen, "controllermap.bmp", SDL_FALSE, NULL, NULL);
  798. background_back = LoadTexture(screen, "controllermap_back.bmp", SDL_FALSE, NULL, NULL);
  799. button_texture = LoadTexture(screen, "button.bmp", SDL_TRUE, NULL, NULL);
  800. axis_texture = LoadTexture(screen, "axis.bmp", SDL_TRUE, NULL, NULL);
  801. if (!background_front || !background_back || !button_texture || !axis_texture) {
  802. SDL_DestroyRenderer(screen);
  803. SDL_DestroyWindow(window);
  804. return 2;
  805. }
  806. SDL_SetTextureColorMod(button_texture, 10, 255, 21);
  807. SDL_SetTextureColorMod(axis_texture, 10, 255, 21);
  808. /* !!! FIXME: */
  809. /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/
  810. for (i = 1; i < argc; ++i) {
  811. if (SDL_strcmp(argv[i], "--virtual") == 0) {
  812. OpenVirtualController();
  813. }
  814. if (argv[i] && *argv[i] != '-') {
  815. controller_index = SDL_atoi(argv[i]);
  816. break;
  817. }
  818. }
  819. if (controller_index < num_controllers) {
  820. gamecontroller = gamecontrollers[controller_index];
  821. } else {
  822. gamecontroller = NULL;
  823. }
  824. UpdateWindowTitle();
  825. /* Loop, getting controller events! */
  826. #ifdef __EMSCRIPTEN__
  827. emscripten_set_main_loop_arg(loop, NULL, 0, 1);
  828. #else
  829. while (!done) {
  830. loop(NULL);
  831. }
  832. #endif
  833. /* Reset trigger state */
  834. if (trigger_effect != 0) {
  835. trigger_effect = -1;
  836. CyclePS5TriggerEffect();
  837. }
  838. CloseVirtualController();
  839. SDL_DestroyRenderer(screen);
  840. SDL_DestroyWindow(window);
  841. SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
  842. return 0;
  843. }
  844. #else
  845. int
  846. main(int argc, char *argv[])
  847. {
  848. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
  849. return 1;
  850. }
  851. #endif
  852. /* vi: set ts=4 sw=4 expandtab: */