SDL_hidapi_steam.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_JOYSTICK_HIDAPI
  20. #include "../SDL_sysjoystick.h"
  21. #include "SDL_hidapijoystick_c.h"
  22. #ifdef SDL_JOYSTICK_HIDAPI_STEAM
  23. /*****************************************************************************************************/
  24. #include <stdint.h>
  25. #define bool SDL_bool
  26. #define true SDL_TRUE
  27. #define false SDL_FALSE
  28. typedef uint32_t uint32;
  29. typedef uint64_t uint64;
  30. #include "steam/controller_constants.h"
  31. #include "steam/controller_structs.h"
  32. typedef struct SteamControllerStateInternal_t
  33. {
  34. // Controller Type for this Controller State
  35. uint32 eControllerType;
  36. // If packet num matches that on your prior call, then the controller state hasn't been changed since
  37. // your last call and there is no need to process it
  38. uint32 unPacketNum;
  39. // bit flags for each of the buttons
  40. uint64 ulButtons;
  41. // Left pad coordinates
  42. short sLeftPadX;
  43. short sLeftPadY;
  44. // Right pad coordinates
  45. short sRightPadX;
  46. short sRightPadY;
  47. // Center pad coordinates
  48. short sCenterPadX;
  49. short sCenterPadY;
  50. // Left analog stick coordinates
  51. short sLeftStickX;
  52. short sLeftStickY;
  53. // Right analog stick coordinates
  54. short sRightStickX;
  55. short sRightStickY;
  56. unsigned short sTriggerL;
  57. unsigned short sTriggerR;
  58. short sAccelX;
  59. short sAccelY;
  60. short sAccelZ;
  61. short sGyroX;
  62. short sGyroY;
  63. short sGyroZ;
  64. float sGyroQuatW;
  65. float sGyroQuatX;
  66. float sGyroQuatY;
  67. float sGyroQuatZ;
  68. short sGyroSteeringAngle;
  69. unsigned short sBatteryLevel;
  70. // Pressure sensor data.
  71. unsigned short sPressurePadLeft;
  72. unsigned short sPressurePadRight;
  73. unsigned short sPressureBumperLeft;
  74. unsigned short sPressureBumperRight;
  75. // Internal state data
  76. short sPrevLeftPad[2];
  77. short sPrevLeftStick[2];
  78. } SteamControllerStateInternal_t;
  79. /* Defines for ulButtons in SteamControllerStateInternal_t */
  80. #define STEAM_RIGHT_TRIGGER_MASK 0x00000001
  81. #define STEAM_LEFT_TRIGGER_MASK 0x00000002
  82. #define STEAM_RIGHT_BUMPER_MASK 0x00000004
  83. #define STEAM_LEFT_BUMPER_MASK 0x00000008
  84. #define STEAM_BUTTON_0_MASK 0x00000010 /* Y */
  85. #define STEAM_BUTTON_1_MASK 0x00000020 /* B */
  86. #define STEAM_BUTTON_2_MASK 0x00000040 /* X */
  87. #define STEAM_BUTTON_3_MASK 0x00000080 /* A */
  88. #define STEAM_TOUCH_0_MASK 0x00000100 /* DPAD UP */
  89. #define STEAM_TOUCH_1_MASK 0x00000200 /* DPAD RIGHT */
  90. #define STEAM_TOUCH_2_MASK 0x00000400 /* DPAD LEFT */
  91. #define STEAM_TOUCH_3_MASK 0x00000800 /* DPAD DOWN */
  92. #define STEAM_BUTTON_MENU_MASK 0x00001000 /* SELECT */
  93. #define STEAM_BUTTON_STEAM_MASK 0x00002000 /* GUIDE */
  94. #define STEAM_BUTTON_ESCAPE_MASK 0x00004000 /* START */
  95. #define STEAM_BUTTON_BACK_LEFT_MASK 0x00008000
  96. #define STEAM_BUTTON_BACK_RIGHT_MASK 0x00010000
  97. #define STEAM_BUTTON_LEFTPAD_CLICKED_MASK 0x00020000
  98. #define STEAM_BUTTON_RIGHTPAD_CLICKED_MASK 0x00040000
  99. #define STEAM_LEFTPAD_FINGERDOWN_MASK 0x00080000
  100. #define STEAM_RIGHTPAD_FINGERDOWN_MASK 0x00100000
  101. #define STEAM_JOYSTICK_BUTTON_MASK 0x00400000
  102. #define STEAM_LEFTPAD_AND_JOYSTICK_MASK 0x00800000
  103. // Look for report version 0x0001, type WIRELESS (3), length >= 1 byte
  104. #define D0G_IS_VALID_WIRELESS_EVENT(data, len) ((len) >= 5 && (data)[0] == 1 && (data)[1] == 0 && (data)[2] == 3 && (data)[3] >= 1)
  105. #define D0G_GET_WIRELESS_EVENT_TYPE(data) ((data)[4])
  106. #define D0G_WIRELESS_DISCONNECTED 1
  107. #define D0G_WIRELESS_ESTABLISHED 2
  108. #define D0G_WIRELESS_NEWLYPAIRED 3
  109. #define D0G_IS_WIRELESS_DISCONNECT(data, len) (D0G_IS_VALID_WIRELESS_EVENT(data, len) && D0G_GET_WIRELESS_EVENT_TYPE(data) == D0G_WIRELESS_DISCONNECTED)
  110. #define MAX_REPORT_SEGMENT_PAYLOAD_SIZE 18
  111. /*
  112. * SteamControllerPacketAssembler has to be used when reading output repots from controllers.
  113. */
  114. typedef struct
  115. {
  116. uint8_t uBuffer[MAX_REPORT_SEGMENT_PAYLOAD_SIZE * 8 + 1];
  117. int nExpectedSegmentNumber;
  118. bool bIsBle;
  119. } SteamControllerPacketAssembler;
  120. #undef clamp
  121. #define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val)))
  122. #undef offsetof
  123. #define offsetof(s, m) (size_t) & (((s *)0)->m)
  124. #ifdef DEBUG_STEAM_CONTROLLER
  125. #define DPRINTF(format, ...) printf(format, ##__VA_ARGS__)
  126. #define HEXDUMP(ptr, len) hexdump(ptr, len)
  127. #else
  128. #define DPRINTF(format, ...)
  129. #define HEXDUMP(ptr, len)
  130. #endif
  131. #define printf SDL_Log
  132. #define MAX_REPORT_SEGMENT_SIZE (MAX_REPORT_SEGMENT_PAYLOAD_SIZE + 2)
  133. #define CALC_REPORT_SEGMENT_NUM(index) ((index / MAX_REPORT_SEGMENT_PAYLOAD_SIZE) & 0x07)
  134. #define REPORT_SEGMENT_DATA_FLAG 0x80
  135. #define REPORT_SEGMENT_LAST_FLAG 0x40
  136. #define BLE_REPORT_NUMBER 0x03
  137. #define STEAMCONTROLLER_TRIGGER_MAX_ANALOG 26000
  138. // Enable mouse mode when using the Steam Controller locally
  139. #undef ENABLE_MOUSE_MODE
  140. // Wireless firmware quirk: the firmware intentionally signals "failure" when performing
  141. // SET_FEATURE / GET_FEATURE when it actually means "pending radio roundtrip". The only
  142. // way to make SET_FEATURE / GET_FEATURE work is to loop several times with a sleep. If
  143. // it takes more than 50ms to get the response for SET_FEATURE / GET_FEATURE, we assume
  144. // that the controller has failed.
  145. #define RADIO_WORKAROUND_SLEEP_ATTEMPTS 50
  146. #define RADIO_WORKAROUND_SLEEP_DURATION_US 500
  147. // This was defined by experimentation. 2000 seemed to work but to give that extra bit of margin, set to 3ms.
  148. #define CONTROLLER_CONFIGURATION_DELAY_US 3000
  149. static uint8_t GetSegmentHeader(int nSegmentNumber, bool bLastPacket)
  150. {
  151. uint8_t header = REPORT_SEGMENT_DATA_FLAG;
  152. header |= nSegmentNumber;
  153. if (bLastPacket) {
  154. header |= REPORT_SEGMENT_LAST_FLAG;
  155. }
  156. return header;
  157. }
  158. static void hexdump(const uint8_t *ptr, int len)
  159. {
  160. int i;
  161. for (i = 0; i < len; ++i) {
  162. printf("%02x ", ptr[i]);
  163. }
  164. printf("\n");
  165. }
  166. static void ResetSteamControllerPacketAssembler(SteamControllerPacketAssembler *pAssembler)
  167. {
  168. SDL_memset(pAssembler->uBuffer, 0, sizeof(pAssembler->uBuffer));
  169. pAssembler->nExpectedSegmentNumber = 0;
  170. }
  171. static void InitializeSteamControllerPacketAssembler(SteamControllerPacketAssembler *pAssembler)
  172. {
  173. /* We only support BLE devices right now */
  174. pAssembler->bIsBle = true;
  175. ResetSteamControllerPacketAssembler(pAssembler);
  176. }
  177. // Returns:
  178. // <0 on error
  179. // 0 on not ready
  180. // Complete packet size on completion
  181. static int WriteSegmentToSteamControllerPacketAssembler(SteamControllerPacketAssembler *pAssembler, const uint8_t *pSegment, int nSegmentLength)
  182. {
  183. if (pAssembler->bIsBle) {
  184. uint8_t uSegmentHeader = pSegment[1];
  185. int nSegmentNumber = uSegmentHeader & 0x07;
  186. HEXDUMP(pSegment, nSegmentLength);
  187. if (pSegment[0] != BLE_REPORT_NUMBER) {
  188. // We may get keyboard/mouse input events until controller stops sending them
  189. return 0;
  190. }
  191. if (nSegmentLength != MAX_REPORT_SEGMENT_SIZE) {
  192. printf("Bad segment size! %d\n", nSegmentLength);
  193. hexdump(pSegment, nSegmentLength);
  194. ResetSteamControllerPacketAssembler(pAssembler);
  195. return -1;
  196. }
  197. DPRINTF("GOT PACKET HEADER = 0x%x\n", uSegmentHeader);
  198. if (!(uSegmentHeader & REPORT_SEGMENT_DATA_FLAG)) {
  199. // We get empty segments, just ignore them
  200. return 0;
  201. }
  202. if (nSegmentNumber != pAssembler->nExpectedSegmentNumber) {
  203. ResetSteamControllerPacketAssembler(pAssembler);
  204. if (nSegmentNumber) {
  205. // This happens occasionally
  206. DPRINTF("Bad segment number, got %d, expected %d\n",
  207. nSegmentNumber, pAssembler->nExpectedSegmentNumber);
  208. return -1;
  209. }
  210. }
  211. SDL_memcpy(pAssembler->uBuffer + nSegmentNumber * MAX_REPORT_SEGMENT_PAYLOAD_SIZE,
  212. pSegment + 2, // ignore header and report number
  213. MAX_REPORT_SEGMENT_PAYLOAD_SIZE);
  214. if (uSegmentHeader & REPORT_SEGMENT_LAST_FLAG) {
  215. pAssembler->nExpectedSegmentNumber = 0;
  216. return (nSegmentNumber + 1) * MAX_REPORT_SEGMENT_PAYLOAD_SIZE;
  217. }
  218. pAssembler->nExpectedSegmentNumber++;
  219. } else {
  220. // Just pass through
  221. SDL_memcpy(pAssembler->uBuffer,
  222. pSegment,
  223. nSegmentLength);
  224. return nSegmentLength;
  225. }
  226. return 0;
  227. }
  228. #define BLE_MAX_READ_RETRIES 8
  229. static int SetFeatureReport(SDL_hid_device *dev, unsigned char uBuffer[65], int nActualDataLen)
  230. {
  231. int nRet = -1;
  232. bool bBle = true; // only wireless/BLE for now, though macOS could do wired in the future
  233. DPRINTF("SetFeatureReport %p %p %d\n", dev, uBuffer, nActualDataLen);
  234. if (bBle) {
  235. int nSegmentNumber = 0;
  236. uint8_t uPacketBuffer[MAX_REPORT_SEGMENT_SIZE];
  237. unsigned char *pBufferPtr = uBuffer + 1;
  238. if (nActualDataLen < 1) {
  239. return -1;
  240. }
  241. // Skip report number in data
  242. nActualDataLen--;
  243. while (nActualDataLen > 0) {
  244. int nBytesInPacket = nActualDataLen > MAX_REPORT_SEGMENT_PAYLOAD_SIZE ? MAX_REPORT_SEGMENT_PAYLOAD_SIZE : nActualDataLen;
  245. nActualDataLen -= nBytesInPacket;
  246. // Construct packet
  247. SDL_memset(uPacketBuffer, 0, sizeof(uPacketBuffer));
  248. uPacketBuffer[0] = BLE_REPORT_NUMBER;
  249. uPacketBuffer[1] = GetSegmentHeader(nSegmentNumber, nActualDataLen == 0);
  250. SDL_memcpy(&uPacketBuffer[2], pBufferPtr, nBytesInPacket);
  251. pBufferPtr += nBytesInPacket;
  252. nSegmentNumber++;
  253. nRet = SDL_hid_send_feature_report(dev, uPacketBuffer, sizeof(uPacketBuffer));
  254. DPRINTF("SetFeatureReport() ret = %d\n", nRet);
  255. }
  256. }
  257. return nRet;
  258. }
  259. static int GetFeatureReport(SDL_hid_device *dev, unsigned char uBuffer[65])
  260. {
  261. int nRet = -1;
  262. bool bBle = true;
  263. DPRINTF("GetFeatureReport( %p %p )\n", dev, uBuffer);
  264. if (bBle) {
  265. int nRetries = 0;
  266. uint8_t uSegmentBuffer[MAX_REPORT_SEGMENT_SIZE + 1];
  267. uint8_t ucBytesToRead = MAX_REPORT_SEGMENT_SIZE;
  268. uint8_t ucDataStartOffset = 0;
  269. SteamControllerPacketAssembler assembler;
  270. InitializeSteamControllerPacketAssembler(&assembler);
  271. // On Windows and macOS, BLE devices get 2 copies of the feature report ID, one that is removed by ReadFeatureReport,
  272. // and one that's included in the buffer we receive. We pad the bytes to read and skip over the report ID
  273. // if necessary.
  274. #if defined(__WIN32__) || defined(__MACOS__)
  275. ++ucBytesToRead;
  276. ++ucDataStartOffset;
  277. #endif
  278. while (nRetries < BLE_MAX_READ_RETRIES) {
  279. SDL_memset(uSegmentBuffer, 0, sizeof(uSegmentBuffer));
  280. uSegmentBuffer[0] = BLE_REPORT_NUMBER;
  281. nRet = SDL_hid_get_feature_report(dev, uSegmentBuffer, ucBytesToRead);
  282. DPRINTF("GetFeatureReport ble ret=%d\n", nRet);
  283. HEXDUMP(uSegmentBuffer, nRet);
  284. // Zero retry counter if we got data
  285. if (nRet > 2 && (uSegmentBuffer[ucDataStartOffset + 1] & REPORT_SEGMENT_DATA_FLAG)) {
  286. nRetries = 0;
  287. } else {
  288. nRetries++;
  289. }
  290. if (nRet > 0) {
  291. int nPacketLength = WriteSegmentToSteamControllerPacketAssembler(&assembler,
  292. uSegmentBuffer + ucDataStartOffset,
  293. nRet - ucDataStartOffset);
  294. if (nPacketLength > 0 && nPacketLength < 65) {
  295. // Leave space for "report number"
  296. uBuffer[0] = 0;
  297. SDL_memcpy(uBuffer + 1, assembler.uBuffer, nPacketLength);
  298. return nPacketLength;
  299. }
  300. }
  301. }
  302. printf("Could not get a full ble packet after %d retries\n", nRetries);
  303. return -1;
  304. }
  305. return nRet;
  306. }
  307. static int ReadResponse(SDL_hid_device *dev, uint8_t uBuffer[65], int nExpectedResponse)
  308. {
  309. int nRet = GetFeatureReport(dev, uBuffer);
  310. DPRINTF("ReadResponse( %p %p %d )\n", dev, uBuffer, nExpectedResponse);
  311. if (nRet < 0) {
  312. return nRet;
  313. }
  314. DPRINTF("ReadResponse got %d bytes of data: ", nRet);
  315. HEXDUMP(uBuffer, nRet);
  316. if (uBuffer[1] != nExpectedResponse) {
  317. return -1;
  318. }
  319. return nRet;
  320. }
  321. //---------------------------------------------------------------------------
  322. // Reset steam controller (unmap buttons and pads) and re-fetch capability bits
  323. //---------------------------------------------------------------------------
  324. static bool ResetSteamController(SDL_hid_device *dev, bool bSuppressErrorSpew, uint32_t *punUpdateRateUS)
  325. {
  326. // Firmware quirk: Set Feature and Get Feature requests always require a 65-byte buffer.
  327. unsigned char buf[65];
  328. unsigned int i;
  329. int res = -1;
  330. int nSettings = 0;
  331. int nAttributesLength;
  332. FeatureReportMsg *msg;
  333. uint32_t unUpdateRateUS = 9000; // Good default rate
  334. DPRINTF("ResetSteamController hid=%p\n", dev);
  335. buf[0] = 0;
  336. buf[1] = ID_GET_ATTRIBUTES_VALUES;
  337. res = SetFeatureReport(dev, buf, 2);
  338. if (res < 0) {
  339. if (!bSuppressErrorSpew) {
  340. printf("GET_ATTRIBUTES_VALUES failed for controller %p\n", dev);
  341. }
  342. return false;
  343. }
  344. // Retrieve GET_ATTRIBUTES_VALUES result
  345. // Wireless controller endpoints without a connected controller will return nAttrs == 0
  346. res = ReadResponse(dev, buf, ID_GET_ATTRIBUTES_VALUES);
  347. if (res < 0 || buf[1] != ID_GET_ATTRIBUTES_VALUES) {
  348. HEXDUMP(buf, res);
  349. if (!bSuppressErrorSpew) {
  350. printf("Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev);
  351. }
  352. return false;
  353. }
  354. nAttributesLength = buf[2];
  355. if (nAttributesLength > res) {
  356. if (!bSuppressErrorSpew) {
  357. printf("Bad GET_ATTRIBUTES_VALUES response for controller %p\n", dev);
  358. }
  359. return false;
  360. }
  361. msg = (FeatureReportMsg *)&buf[1];
  362. for (i = 0; i < (int)msg->header.length / sizeof(ControllerAttribute); ++i) {
  363. uint8_t unAttribute = msg->payload.getAttributes.attributes[i].attributeTag;
  364. uint32_t unValue = msg->payload.getAttributes.attributes[i].attributeValue;
  365. switch (unAttribute) {
  366. case ATTRIB_UNIQUE_ID:
  367. break;
  368. case ATTRIB_PRODUCT_ID:
  369. break;
  370. case ATTRIB_CAPABILITIES:
  371. break;
  372. case ATTRIB_CONNECTION_INTERVAL_IN_US:
  373. unUpdateRateUS = unValue;
  374. break;
  375. default:
  376. break;
  377. }
  378. }
  379. if (punUpdateRateUS) {
  380. *punUpdateRateUS = unUpdateRateUS;
  381. }
  382. // Clear digital button mappings
  383. buf[0] = 0;
  384. buf[1] = ID_CLEAR_DIGITAL_MAPPINGS;
  385. res = SetFeatureReport(dev, buf, 2);
  386. if (res < 0) {
  387. if (!bSuppressErrorSpew) {
  388. printf("CLEAR_DIGITAL_MAPPINGS failed for controller %p\n", dev);
  389. }
  390. return false;
  391. }
  392. // Reset the default settings
  393. SDL_memset(buf, 0, 65);
  394. buf[1] = ID_LOAD_DEFAULT_SETTINGS;
  395. buf[2] = 0;
  396. res = SetFeatureReport(dev, buf, 3);
  397. if (res < 0) {
  398. if (!bSuppressErrorSpew) {
  399. printf("LOAD_DEFAULT_SETTINGS failed for controller %p\n", dev);
  400. }
  401. return false;
  402. }
  403. // Apply custom settings - clear trackpad modes (cancel mouse emulation), etc
  404. #define ADD_SETTING(SETTING, VALUE) \
  405. buf[3 + nSettings * 3] = SETTING; \
  406. buf[3 + nSettings * 3 + 1] = ((uint16_t)VALUE) & 0xFF; \
  407. buf[3 + nSettings * 3 + 2] = ((uint16_t)VALUE) >> 8; \
  408. ++nSettings;
  409. SDL_memset(buf, 0, 65);
  410. buf[1] = ID_SET_SETTINGS_VALUES;
  411. ADD_SETTING(SETTING_WIRELESS_PACKET_VERSION, 2);
  412. ADD_SETTING(SETTING_LEFT_TRACKPAD_MODE, TRACKPAD_NONE);
  413. #ifdef ENABLE_MOUSE_MODE
  414. ADD_SETTING(SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE);
  415. ADD_SETTING(SETTING_SMOOTH_ABSOLUTE_MOUSE, 1);
  416. ADD_SETTING(SETTING_MOMENTUM_MAXIMUM_VELOCITY, 20000); // [0-20000] default 8000
  417. ADD_SETTING(SETTING_MOMENTUM_DECAY_AMMOUNT, 50); // [0-50] default 5
  418. #else
  419. ADD_SETTING(SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_NONE);
  420. ADD_SETTING(SETTING_SMOOTH_ABSOLUTE_MOUSE, 0);
  421. #endif
  422. buf[2] = (unsigned char)(nSettings * 3);
  423. res = SetFeatureReport(dev, buf, 3 + nSettings * 3);
  424. if (res < 0) {
  425. if (!bSuppressErrorSpew) {
  426. printf("SET_SETTINGS failed for controller %p\n", dev);
  427. }
  428. return false;
  429. }
  430. #ifdef ENABLE_MOUSE_MODE
  431. // Wait for ID_CLEAR_DIGITAL_MAPPINGS to be processed on the controller
  432. bool bMappingsCleared = false;
  433. int iRetry;
  434. for (iRetry = 0; iRetry < 2; ++iRetry) {
  435. SDL_memset(buf, 0, 65);
  436. buf[1] = ID_GET_DIGITAL_MAPPINGS;
  437. buf[2] = 1; // one byte - requesting from index 0
  438. buf[3] = 0;
  439. res = SetFeatureReport(dev, buf, 4);
  440. if (res < 0) {
  441. printf("GET_DIGITAL_MAPPINGS failed for controller %p\n", dev);
  442. return false;
  443. }
  444. res = ReadResponse(dev, buf, ID_GET_DIGITAL_MAPPINGS);
  445. if (res < 0 || buf[1] != ID_GET_DIGITAL_MAPPINGS) {
  446. printf("Bad GET_DIGITAL_MAPPINGS response for controller %p\n", dev);
  447. return false;
  448. }
  449. // If the length of the digital mappings result is not 1 (index byte, no mappings) then clearing hasn't executed
  450. if (buf[2] == 1 && buf[3] == 0xFF) {
  451. bMappingsCleared = true;
  452. break;
  453. }
  454. usleep(CONTROLLER_CONFIGURATION_DELAY_US);
  455. }
  456. if (!bMappingsCleared && !bSuppressErrorSpew) {
  457. printf("Warning: CLEAR_DIGITAL_MAPPINGS never completed for controller %p\n", dev);
  458. }
  459. // Set our new mappings
  460. SDL_memset(buf, 0, 65);
  461. buf[1] = ID_SET_DIGITAL_MAPPINGS;
  462. buf[2] = 6; // 2 settings x 3 bytes
  463. buf[3] = IO_DIGITAL_BUTTON_RIGHT_TRIGGER;
  464. buf[4] = DEVICE_MOUSE;
  465. buf[5] = MOUSE_BTN_LEFT;
  466. buf[6] = IO_DIGITAL_BUTTON_LEFT_TRIGGER;
  467. buf[7] = DEVICE_MOUSE;
  468. buf[8] = MOUSE_BTN_RIGHT;
  469. res = SetFeatureReport(dev, buf, 9);
  470. if (res < 0) {
  471. if (!bSuppressErrorSpew) {
  472. printf("SET_DIGITAL_MAPPINGS failed for controller %p\n", dev);
  473. }
  474. return false;
  475. }
  476. #endif // ENABLE_MOUSE_MODE
  477. return true;
  478. }
  479. //---------------------------------------------------------------------------
  480. // Read from a Steam Controller
  481. //---------------------------------------------------------------------------
  482. static int ReadSteamController(SDL_hid_device *dev, uint8_t *pData, int nDataSize)
  483. {
  484. SDL_memset(pData, 0, nDataSize);
  485. pData[0] = BLE_REPORT_NUMBER; // hid_read will also overwrite this with the same value, 0x03
  486. return SDL_hid_read(dev, pData, nDataSize);
  487. }
  488. //---------------------------------------------------------------------------
  489. // Close a Steam Controller
  490. //---------------------------------------------------------------------------
  491. static void CloseSteamController(SDL_hid_device *dev)
  492. {
  493. // Switch the Steam Controller back to lizard mode so it works with the OS
  494. unsigned char buf[65];
  495. int nSettings = 0;
  496. // Reset digital button mappings
  497. SDL_memset(buf, 0, 65);
  498. buf[1] = ID_SET_DEFAULT_DIGITAL_MAPPINGS;
  499. SetFeatureReport(dev, buf, 2);
  500. // Reset the default settings
  501. SDL_memset(buf, 0, 65);
  502. buf[1] = ID_LOAD_DEFAULT_SETTINGS;
  503. buf[2] = 0;
  504. SetFeatureReport(dev, buf, 3);
  505. // Reset mouse mode for lizard mode
  506. SDL_memset(buf, 0, 65);
  507. buf[1] = ID_SET_SETTINGS_VALUES;
  508. ADD_SETTING(SETTING_RIGHT_TRACKPAD_MODE, TRACKPAD_ABSOLUTE_MOUSE);
  509. buf[2] = (unsigned char)(nSettings * 3);
  510. SetFeatureReport(dev, buf, 3 + nSettings * 3);
  511. }
  512. //---------------------------------------------------------------------------
  513. // Scale and clamp values to a range
  514. //---------------------------------------------------------------------------
  515. static float RemapValClamped(float val, float A, float B, float C, float D)
  516. {
  517. if (A == B) {
  518. return (val - B) >= 0.0f ? D : C;
  519. } else {
  520. float cVal = (val - A) / (B - A);
  521. cVal = clamp(cVal, 0.0f, 1.0f);
  522. return C + (D - C) * cVal;
  523. }
  524. }
  525. //---------------------------------------------------------------------------
  526. // Rotate the pad coordinates
  527. //---------------------------------------------------------------------------
  528. static void RotatePad(int *pX, int *pY, float flAngleInRad)
  529. {
  530. int origX = *pX, origY = *pY;
  531. *pX = (int)(SDL_cosf(flAngleInRad) * origX - SDL_sinf(flAngleInRad) * origY);
  532. *pY = (int)(SDL_sinf(flAngleInRad) * origX + SDL_cosf(flAngleInRad) * origY);
  533. }
  534. static void RotatePadShort(short *pX, short *pY, float flAngleInRad)
  535. {
  536. int origX = *pX, origY = *pY;
  537. *pX = (short)(SDL_cosf(flAngleInRad) * origX - SDL_sinf(flAngleInRad) * origY);
  538. *pY = (short)(SDL_sinf(flAngleInRad) * origX + SDL_cosf(flAngleInRad) * origY);
  539. }
  540. //---------------------------------------------------------------------------
  541. // Format the first part of the state packet
  542. //---------------------------------------------------------------------------
  543. static void FormatStatePacketUntilGyro(SteamControllerStateInternal_t *pState, ValveControllerStatePacket_t *pStatePacket)
  544. {
  545. int nLeftPadX;
  546. int nLeftPadY;
  547. int nRightPadX;
  548. int nRightPadY;
  549. int nPadOffset;
  550. // 15 degrees in rad
  551. const float flRotationAngle = 0.261799f;
  552. SDL_memset(pState, 0, offsetof(SteamControllerStateInternal_t, sBatteryLevel));
  553. // pState->eControllerType = m_eControllerType;
  554. pState->eControllerType = 2; // k_eControllerType_SteamController;
  555. pState->unPacketNum = pStatePacket->unPacketNum;
  556. // We have a chunk of trigger data in the packet format here, so zero it out afterwards
  557. SDL_memcpy(&pState->ulButtons, &pStatePacket->ButtonTriggerData.ulButtons, 8);
  558. pState->ulButtons &= ~0xFFFF000000LL;
  559. // The firmware uses this bit to tell us what kind of data is packed into the left two axises
  560. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) {
  561. // Finger-down bit not set; "left pad" is actually trackpad
  562. pState->sLeftPadX = pState->sPrevLeftPad[0] = pStatePacket->sLeftPadX;
  563. pState->sLeftPadY = pState->sPrevLeftPad[1] = pStatePacket->sLeftPadY;
  564. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) {
  565. // The controller is interleaving both stick and pad data, both are active
  566. pState->sLeftStickX = pState->sPrevLeftStick[0];
  567. pState->sLeftStickY = pState->sPrevLeftStick[1];
  568. } else {
  569. // The stick is not active
  570. pState->sPrevLeftStick[0] = 0;
  571. pState->sPrevLeftStick[1] = 0;
  572. }
  573. } else {
  574. // Finger-down bit not set; "left pad" is actually joystick
  575. // XXX there's a firmware bug where sometimes padX is 0 and padY is a large number (acutally the battery voltage)
  576. // If that happens skip this packet and report last frames stick
  577. /*
  578. if ( m_eControllerType == k_eControllerType_SteamControllerV2 && pStatePacket->sLeftPadY > 900 ) {
  579. pState->sLeftStickX = pState->sPrevLeftStick[0];
  580. pState->sLeftStickY = pState->sPrevLeftStick[1];
  581. } else
  582. */
  583. {
  584. pState->sPrevLeftStick[0] = pState->sLeftStickX = pStatePacket->sLeftPadX;
  585. pState->sPrevLeftStick[1] = pState->sLeftStickY = pStatePacket->sLeftPadY;
  586. }
  587. /*
  588. if (m_eControllerType == k_eControllerType_SteamControllerV2) {
  589. UpdateV2JoystickCap(&state);
  590. }
  591. */
  592. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) {
  593. // The controller is interleaving both stick and pad data, both are active
  594. pState->sLeftPadX = pState->sPrevLeftPad[0];
  595. pState->sLeftPadY = pState->sPrevLeftPad[1];
  596. } else {
  597. // The trackpad is not active
  598. pState->sPrevLeftPad[0] = 0;
  599. pState->sPrevLeftPad[1] = 0;
  600. // Old controllers send trackpad click for joystick button when trackpad is not active
  601. if (pState->ulButtons & STEAM_BUTTON_LEFTPAD_CLICKED_MASK) {
  602. pState->ulButtons &= ~STEAM_BUTTON_LEFTPAD_CLICKED_MASK;
  603. pState->ulButtons |= STEAM_JOYSTICK_BUTTON_MASK;
  604. }
  605. }
  606. }
  607. // Fingerdown bit indicates if the packed left axis data was joystick or pad,
  608. // but if we are interleaving both, the left finger is definitely on the pad.
  609. if (pStatePacket->ButtonTriggerData.ulButtons & STEAM_LEFTPAD_AND_JOYSTICK_MASK) {
  610. pState->ulButtons |= STEAM_LEFTPAD_FINGERDOWN_MASK;
  611. }
  612. pState->sRightPadX = pStatePacket->sRightPadX;
  613. pState->sRightPadY = pStatePacket->sRightPadY;
  614. nLeftPadX = pState->sLeftPadX;
  615. nLeftPadY = pState->sLeftPadY;
  616. nRightPadX = pState->sRightPadX;
  617. nRightPadY = pState->sRightPadY;
  618. RotatePad(&nLeftPadX, &nLeftPadY, -flRotationAngle);
  619. RotatePad(&nRightPadX, &nRightPadY, flRotationAngle);
  620. if (pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) {
  621. nPadOffset = 1000;
  622. } else {
  623. nPadOffset = 0;
  624. }
  625. pState->sLeftPadX = (short)clamp(nLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  626. pState->sLeftPadY = (short)clamp(nLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  627. nPadOffset = 0;
  628. if (pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK) {
  629. nPadOffset = 1000;
  630. } else {
  631. nPadOffset = 0;
  632. }
  633. pState->sRightPadX = (short)clamp(nRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  634. pState->sRightPadY = (short)clamp(nRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  635. pState->sTriggerL = (unsigned short)RemapValClamped((float)((pStatePacket->ButtonTriggerData.Triggers.nLeft << 7) | pStatePacket->ButtonTriggerData.Triggers.nLeft), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16);
  636. pState->sTriggerR = (unsigned short)RemapValClamped((float)((pStatePacket->ButtonTriggerData.Triggers.nRight << 7) | pStatePacket->ButtonTriggerData.Triggers.nRight), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16);
  637. }
  638. //---------------------------------------------------------------------------
  639. // Update Steam Controller state from a BLE data packet, returns true if it parsed data
  640. //---------------------------------------------------------------------------
  641. static bool UpdateBLESteamControllerState(const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState)
  642. {
  643. const float flRotationAngle = 0.261799f;
  644. uint32_t ucOptionDataMask;
  645. pState->unPacketNum++;
  646. ucOptionDataMask = (*pData++ & 0xF0);
  647. ucOptionDataMask |= (uint32_t)(*pData++) << 8;
  648. if (ucOptionDataMask & k_EBLEButtonChunk1) {
  649. SDL_memcpy(&pState->ulButtons, pData, 3);
  650. pData += 3;
  651. }
  652. if (ucOptionDataMask & k_EBLEButtonChunk2) {
  653. // The middle 2 bytes of the button bits over the wire are triggers when over the wire and non-SC buttons in the internal controller state packet
  654. pState->sTriggerL = (unsigned short)RemapValClamped((float)((pData[0] << 7) | pData[0]), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16);
  655. pState->sTriggerR = (unsigned short)RemapValClamped((float)((pData[1] << 7) | pData[1]), 0, STEAMCONTROLLER_TRIGGER_MAX_ANALOG, 0, SDL_MAX_SINT16);
  656. pData += 2;
  657. }
  658. if (ucOptionDataMask & k_EBLEButtonChunk3) {
  659. uint8_t *pButtonByte = (uint8_t *)&pState->ulButtons;
  660. pButtonByte[5] = *pData++;
  661. pButtonByte[6] = *pData++;
  662. pButtonByte[7] = *pData++;
  663. }
  664. if (ucOptionDataMask & k_EBLELeftJoystickChunk) {
  665. // This doesn't handle any of the special headcrab stuff for raw joystick which is OK for now since that FW doesn't support
  666. // this protocol yet either
  667. int nLength = sizeof(pState->sLeftStickX) + sizeof(pState->sLeftStickY);
  668. SDL_memcpy(&pState->sLeftStickX, pData, nLength);
  669. pData += nLength;
  670. }
  671. if (ucOptionDataMask & k_EBLELeftTrackpadChunk) {
  672. int nLength = sizeof(pState->sLeftPadX) + sizeof(pState->sLeftPadY);
  673. int nPadOffset;
  674. SDL_memcpy(&pState->sLeftPadX, pData, nLength);
  675. if (pState->ulButtons & STEAM_LEFTPAD_FINGERDOWN_MASK) {
  676. nPadOffset = 1000;
  677. } else {
  678. nPadOffset = 0;
  679. }
  680. RotatePadShort(&pState->sLeftPadX, &pState->sLeftPadY, -flRotationAngle);
  681. pState->sLeftPadX = (short)clamp(pState->sLeftPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  682. pState->sLeftPadY = (short)clamp(pState->sLeftPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  683. pData += nLength;
  684. }
  685. if (ucOptionDataMask & k_EBLERightTrackpadChunk) {
  686. int nLength = sizeof(pState->sRightPadX) + sizeof(pState->sRightPadY);
  687. int nPadOffset = 0;
  688. SDL_memcpy(&pState->sRightPadX, pData, nLength);
  689. if (pState->ulButtons & STEAM_RIGHTPAD_FINGERDOWN_MASK) {
  690. nPadOffset = 1000;
  691. } else {
  692. nPadOffset = 0;
  693. }
  694. RotatePadShort(&pState->sRightPadX, &pState->sRightPadY, flRotationAngle);
  695. pState->sRightPadX = (short)clamp(pState->sRightPadX + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  696. pState->sRightPadY = (short)clamp(pState->sRightPadY + nPadOffset, SDL_MIN_SINT16, SDL_MAX_SINT16);
  697. pData += nLength;
  698. }
  699. if (ucOptionDataMask & k_EBLEIMUAccelChunk) {
  700. int nLength = sizeof(pState->sAccelX) + sizeof(pState->sAccelY) + sizeof(pState->sAccelZ);
  701. SDL_memcpy(&pState->sAccelX, pData, nLength);
  702. pData += nLength;
  703. }
  704. if (ucOptionDataMask & k_EBLEIMUGyroChunk) {
  705. int nLength = sizeof(pState->sAccelX) + sizeof(pState->sAccelY) + sizeof(pState->sAccelZ);
  706. SDL_memcpy(&pState->sGyroX, pData, nLength);
  707. pData += nLength;
  708. }
  709. if (ucOptionDataMask & k_EBLEIMUQuatChunk) {
  710. int nLength = sizeof(pState->sGyroQuatW) + sizeof(pState->sGyroQuatX) + sizeof(pState->sGyroQuatY) + sizeof(pState->sGyroQuatZ);
  711. SDL_memcpy(&pState->sGyroQuatW, pData, nLength);
  712. pData += nLength;
  713. }
  714. return true;
  715. }
  716. //---------------------------------------------------------------------------
  717. // Update Steam Controller state from a data packet, returns true if it parsed data
  718. //---------------------------------------------------------------------------
  719. static bool UpdateSteamControllerState(const uint8_t *pData, int nDataSize, SteamControllerStateInternal_t *pState)
  720. {
  721. ValveInReport_t *pInReport = (ValveInReport_t *)pData;
  722. if (pInReport->header.unReportVersion != k_ValveInReportMsgVersion) {
  723. if ((pData[0] & 0x0F) == k_EBLEReportState) {
  724. return UpdateBLESteamControllerState(pData, nDataSize, pState);
  725. }
  726. return false;
  727. }
  728. if ((pInReport->header.ucType != ID_CONTROLLER_STATE) &&
  729. (pInReport->header.ucType != ID_CONTROLLER_BLE_STATE)) {
  730. return false;
  731. }
  732. if (pInReport->header.ucType == ID_CONTROLLER_STATE) {
  733. ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState;
  734. // No new data to process; indicate that we received a state packet, but otherwise do nothing.
  735. if (pState->unPacketNum == pStatePacket->unPacketNum) {
  736. return true;
  737. }
  738. FormatStatePacketUntilGyro(pState, pStatePacket);
  739. pState->sAccelX = pStatePacket->sAccelX;
  740. pState->sAccelY = pStatePacket->sAccelY;
  741. pState->sAccelZ = pStatePacket->sAccelZ;
  742. pState->sGyroQuatW = pStatePacket->sGyroQuatW;
  743. pState->sGyroQuatX = pStatePacket->sGyroQuatX;
  744. pState->sGyroQuatY = pStatePacket->sGyroQuatY;
  745. pState->sGyroQuatZ = pStatePacket->sGyroQuatZ;
  746. pState->sGyroX = pStatePacket->sGyroX;
  747. pState->sGyroY = pStatePacket->sGyroY;
  748. pState->sGyroZ = pStatePacket->sGyroZ;
  749. } else if (pInReport->header.ucType == ID_CONTROLLER_BLE_STATE) {
  750. ValveControllerBLEStatePacket_t *pBLEStatePacket = &pInReport->payload.controllerBLEState;
  751. ValveControllerStatePacket_t *pStatePacket = &pInReport->payload.controllerState;
  752. // No new data to process; indicate that we received a state packet, but otherwise do nothing.
  753. if (pState->unPacketNum == pStatePacket->unPacketNum) {
  754. return true;
  755. }
  756. FormatStatePacketUntilGyro(pState, pStatePacket);
  757. switch (pBLEStatePacket->ucGyroDataType) {
  758. case 1:
  759. pState->sGyroQuatW = ((float)pBLEStatePacket->sGyro[0]);
  760. pState->sGyroQuatX = ((float)pBLEStatePacket->sGyro[1]);
  761. pState->sGyroQuatY = ((float)pBLEStatePacket->sGyro[2]);
  762. pState->sGyroQuatZ = ((float)pBLEStatePacket->sGyro[3]);
  763. break;
  764. case 2:
  765. pState->sAccelX = pBLEStatePacket->sGyro[0];
  766. pState->sAccelY = pBLEStatePacket->sGyro[1];
  767. pState->sAccelZ = pBLEStatePacket->sGyro[2];
  768. break;
  769. case 3:
  770. pState->sGyroX = pBLEStatePacket->sGyro[0];
  771. pState->sGyroY = pBLEStatePacket->sGyro[1];
  772. pState->sGyroZ = pBLEStatePacket->sGyro[2];
  773. break;
  774. default:
  775. break;
  776. }
  777. }
  778. return true;
  779. }
  780. /*****************************************************************************************************/
  781. typedef struct
  782. {
  783. SDL_bool report_sensors;
  784. uint32_t update_rate_in_us;
  785. Uint64 sensor_timestamp;
  786. SteamControllerPacketAssembler m_assembler;
  787. SteamControllerStateInternal_t m_state;
  788. SteamControllerStateInternal_t m_last_state;
  789. } SDL_DriverSteam_Context;
  790. static void HIDAPI_DriverSteam_RegisterHints(SDL_HintCallback callback, void *userdata)
  791. {
  792. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM, callback, userdata);
  793. }
  794. static void HIDAPI_DriverSteam_UnregisterHints(SDL_HintCallback callback, void *userdata)
  795. {
  796. SDL_DelHintCallback(SDL_HINT_JOYSTICK_HIDAPI_STEAM, callback, userdata);
  797. }
  798. static SDL_bool HIDAPI_DriverSteam_IsEnabled(void)
  799. {
  800. return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_STEAM, SDL_FALSE);
  801. }
  802. static SDL_bool HIDAPI_DriverSteam_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  803. {
  804. return SDL_IsJoystickSteamController(vendor_id, product_id);
  805. }
  806. static SDL_bool HIDAPI_DriverSteam_InitDevice(SDL_HIDAPI_Device *device)
  807. {
  808. SDL_DriverSteam_Context *ctx;
  809. ctx = (SDL_DriverSteam_Context *)SDL_calloc(1, sizeof(*ctx));
  810. if (ctx == NULL) {
  811. SDL_OutOfMemory();
  812. return SDL_FALSE;
  813. }
  814. device->context = ctx;
  815. #ifdef __WIN32__
  816. if (device->serial) {
  817. /* We get a garbage serial number on Windows */
  818. SDL_free(device->serial);
  819. device->serial = NULL;
  820. }
  821. #endif /* __WIN32__ */
  822. HIDAPI_SetDeviceName(device, "Steam Controller");
  823. return HIDAPI_JoystickConnected(device, NULL);
  824. }
  825. static int HIDAPI_DriverSteam_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id)
  826. {
  827. return -1;
  828. }
  829. static void HIDAPI_DriverSteam_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index)
  830. {
  831. }
  832. static SDL_bool HIDAPI_DriverSteam_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  833. {
  834. SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context;
  835. float update_rate_in_hz = 0.0f;
  836. SDL_AssertJoysticksLocked();
  837. ctx->report_sensors = SDL_FALSE;
  838. SDL_zero(ctx->m_assembler);
  839. SDL_zero(ctx->m_state);
  840. SDL_zero(ctx->m_last_state);
  841. if (!ResetSteamController(device->dev, false, &ctx->update_rate_in_us)) {
  842. SDL_SetError("Couldn't reset controller");
  843. return SDL_FALSE;
  844. }
  845. if (ctx->update_rate_in_us > 0) {
  846. update_rate_in_hz = 1000000.0f / ctx->update_rate_in_us;
  847. }
  848. InitializeSteamControllerPacketAssembler(&ctx->m_assembler);
  849. /* Initialize the joystick capabilities */
  850. joystick->nbuttons = 17;
  851. joystick->naxes = SDL_GAMEPAD_AXIS_MAX;
  852. SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, update_rate_in_hz);
  853. SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, update_rate_in_hz);
  854. return SDL_TRUE;
  855. }
  856. static int HIDAPI_DriverSteam_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  857. {
  858. /* You should use the full Steam Input API for rumble support */
  859. return SDL_Unsupported();
  860. }
  861. static int HIDAPI_DriverSteam_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  862. {
  863. return SDL_Unsupported();
  864. }
  865. static Uint32 HIDAPI_DriverSteam_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  866. {
  867. /* You should use the full Steam Input API for extended capabilities */
  868. return 0;
  869. }
  870. static int HIDAPI_DriverSteam_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  871. {
  872. /* You should use the full Steam Input API for LED support */
  873. return SDL_Unsupported();
  874. }
  875. static int HIDAPI_DriverSteam_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size)
  876. {
  877. return SDL_Unsupported();
  878. }
  879. static int HIDAPI_DriverSteam_SetSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, SDL_bool enabled)
  880. {
  881. SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context;
  882. unsigned char buf[65];
  883. int nSettings = 0;
  884. SDL_memset(buf, 0, 65);
  885. buf[1] = ID_SET_SETTINGS_VALUES;
  886. if (enabled) {
  887. ADD_SETTING(SETTING_GYRO_MODE, 0x18 /* SETTING_GYRO_SEND_RAW_ACCEL | SETTING_GYRO_MODE_SEND_RAW_GYRO */);
  888. } else {
  889. ADD_SETTING(SETTING_GYRO_MODE, 0x00 /* SETTING_GYRO_MODE_OFF */);
  890. }
  891. buf[2] = (unsigned char)(nSettings * 3);
  892. if (SetFeatureReport(device->dev, buf, 3 + nSettings * 3) < 0) {
  893. return SDL_SetError("Couldn't write feature report");
  894. }
  895. ctx->report_sensors = enabled;
  896. return 0;
  897. }
  898. static SDL_bool HIDAPI_DriverSteam_UpdateDevice(SDL_HIDAPI_Device *device)
  899. {
  900. SDL_DriverSteam_Context *ctx = (SDL_DriverSteam_Context *)device->context;
  901. SDL_Joystick *joystick = NULL;
  902. if (device->num_joysticks > 0) {
  903. joystick = SDL_GetJoystickFromInstanceID(device->joysticks[0]);
  904. } else {
  905. return SDL_FALSE;
  906. }
  907. for (;;) {
  908. uint8_t data[128];
  909. int r, nPacketLength;
  910. const Uint8 *pPacket;
  911. r = ReadSteamController(device->dev, data, sizeof(data));
  912. if (r == 0) {
  913. break;
  914. }
  915. if (joystick == NULL) {
  916. continue;
  917. }
  918. nPacketLength = 0;
  919. if (r > 0) {
  920. nPacketLength = WriteSegmentToSteamControllerPacketAssembler(&ctx->m_assembler, data, r);
  921. }
  922. pPacket = ctx->m_assembler.uBuffer;
  923. if (nPacketLength > 0 && UpdateSteamControllerState(pPacket, nPacketLength, &ctx->m_state)) {
  924. Uint64 timestamp = SDL_GetTicksNS();
  925. if (ctx->m_state.ulButtons != ctx->m_last_state.ulButtons) {
  926. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_A,
  927. (ctx->m_state.ulButtons & STEAM_BUTTON_3_MASK) ? SDL_PRESSED : SDL_RELEASED);
  928. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_B,
  929. (ctx->m_state.ulButtons & STEAM_BUTTON_1_MASK) ? SDL_PRESSED : SDL_RELEASED);
  930. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_X,
  931. (ctx->m_state.ulButtons & STEAM_BUTTON_2_MASK) ? SDL_PRESSED : SDL_RELEASED);
  932. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_Y,
  933. (ctx->m_state.ulButtons & STEAM_BUTTON_0_MASK) ? SDL_PRESSED : SDL_RELEASED);
  934. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER,
  935. (ctx->m_state.ulButtons & STEAM_LEFT_BUMPER_MASK) ? SDL_PRESSED : SDL_RELEASED);
  936. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER,
  937. (ctx->m_state.ulButtons & STEAM_RIGHT_BUMPER_MASK) ? SDL_PRESSED : SDL_RELEASED);
  938. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK,
  939. (ctx->m_state.ulButtons & STEAM_BUTTON_MENU_MASK) ? SDL_PRESSED : SDL_RELEASED);
  940. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START,
  941. (ctx->m_state.ulButtons & STEAM_BUTTON_ESCAPE_MASK) ? SDL_PRESSED : SDL_RELEASED);
  942. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE,
  943. (ctx->m_state.ulButtons & STEAM_BUTTON_STEAM_MASK) ? SDL_PRESSED : SDL_RELEASED);
  944. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK,
  945. (ctx->m_state.ulButtons & STEAM_JOYSTICK_BUTTON_MASK) ? SDL_PRESSED : SDL_RELEASED);
  946. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_MISC1 + 0,
  947. (ctx->m_state.ulButtons & STEAM_BUTTON_BACK_LEFT_MASK) ? SDL_PRESSED : SDL_RELEASED);
  948. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_MISC1 + 1,
  949. (ctx->m_state.ulButtons & STEAM_BUTTON_BACK_RIGHT_MASK) ? SDL_PRESSED : SDL_RELEASED);
  950. }
  951. {
  952. /* Minimum distance from center of pad to register a direction */
  953. const int kPadDeadZone = 10000;
  954. /* Pad coordinates are like math grid coordinates: negative is bottom left */
  955. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_DPAD_UP,
  956. (ctx->m_state.sLeftPadY > kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  957. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_DPAD_DOWN,
  958. (ctx->m_state.sLeftPadY < -kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  959. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_DPAD_LEFT,
  960. (ctx->m_state.sLeftPadX < -kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  961. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_DPAD_RIGHT,
  962. (ctx->m_state.sLeftPadX > kPadDeadZone) ? SDL_PRESSED : SDL_RELEASED);
  963. }
  964. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, (int)ctx->m_state.sTriggerL * 2 - 32768);
  965. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, (int)ctx->m_state.sTriggerR * 2 - 32768);
  966. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, ctx->m_state.sLeftStickX);
  967. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~ctx->m_state.sLeftStickY);
  968. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, ctx->m_state.sRightPadX);
  969. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~ctx->m_state.sRightPadY);
  970. if (ctx->report_sensors) {
  971. float values[3];
  972. ctx->sensor_timestamp += SDL_US_TO_NS(ctx->update_rate_in_us);
  973. values[0] = (ctx->m_state.sGyroX / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f));
  974. values[1] = (ctx->m_state.sGyroZ / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f));
  975. values[2] = (ctx->m_state.sGyroY / 32768.0f) * (2000.0f * (SDL_PI_F / 180.0f));
  976. SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_GYRO, ctx->sensor_timestamp, values, 3);
  977. values[0] = (ctx->m_state.sAccelX / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY;
  978. values[1] = (ctx->m_state.sAccelZ / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY;
  979. values[2] = (-ctx->m_state.sAccelY / 32768.0f) * 2.0f * SDL_STANDARD_GRAVITY;
  980. SDL_SendJoystickSensor(timestamp, joystick, SDL_SENSOR_ACCEL, ctx->sensor_timestamp, values, 3);
  981. }
  982. ctx->m_last_state = ctx->m_state;
  983. }
  984. if (r <= 0) {
  985. /* Failed to read from controller */
  986. HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
  987. return SDL_FALSE;
  988. }
  989. }
  990. return SDL_TRUE;
  991. }
  992. static void HIDAPI_DriverSteam_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  993. {
  994. CloseSteamController(device->dev);
  995. }
  996. static void HIDAPI_DriverSteam_FreeDevice(SDL_HIDAPI_Device *device)
  997. {
  998. }
  999. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSteam = {
  1000. SDL_HINT_JOYSTICK_HIDAPI_STEAM,
  1001. SDL_TRUE,
  1002. HIDAPI_DriverSteam_RegisterHints,
  1003. HIDAPI_DriverSteam_UnregisterHints,
  1004. HIDAPI_DriverSteam_IsEnabled,
  1005. HIDAPI_DriverSteam_IsSupportedDevice,
  1006. HIDAPI_DriverSteam_InitDevice,
  1007. HIDAPI_DriverSteam_GetDevicePlayerIndex,
  1008. HIDAPI_DriverSteam_SetDevicePlayerIndex,
  1009. HIDAPI_DriverSteam_UpdateDevice,
  1010. HIDAPI_DriverSteam_OpenJoystick,
  1011. HIDAPI_DriverSteam_RumbleJoystick,
  1012. HIDAPI_DriverSteam_RumbleJoystickTriggers,
  1013. HIDAPI_DriverSteam_GetJoystickCapabilities,
  1014. HIDAPI_DriverSteam_SetJoystickLED,
  1015. HIDAPI_DriverSteam_SendJoystickEffect,
  1016. HIDAPI_DriverSteam_SetSensorsEnabled,
  1017. HIDAPI_DriverSteam_CloseJoystick,
  1018. HIDAPI_DriverSteam_FreeDevice,
  1019. };
  1020. #endif /* SDL_JOYSTICK_HIDAPI_STEAM */
  1021. #endif /* SDL_JOYSTICK_HIDAPI */