sdlInputManager.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "console/console.h"
  23. #include "console/consoleTypes.h"
  24. #include "console/engineAPI.h"
  25. #include "sim/actionMap.h"
  26. #include "sdlInputManager.h"
  27. typedef SDL_JoystickType SDLJoystickType;
  28. DefineEnumType(SDLJoystickType);
  29. ImplementEnumType(SDLJoystickType,
  30. "The type of device connected.\n\n"
  31. "@ingroup Input")
  32. { SDL_JOYSTICK_TYPE_UNKNOWN, "Unknown"},
  33. { SDL_JOYSTICK_TYPE_GAMECONTROLLER, "Game Controller" },
  34. { SDL_JOYSTICK_TYPE_WHEEL, "Wheel" },
  35. { SDL_JOYSTICK_TYPE_ARCADE_STICK, "Arcade Stick" },
  36. { SDL_JOYSTICK_TYPE_FLIGHT_STICK, "Flight Stick" },
  37. { SDL_JOYSTICK_TYPE_DANCE_PAD, "Dance Pad" },
  38. { SDL_JOYSTICK_TYPE_GUITAR, "Guitar" },
  39. { SDL_JOYSTICK_TYPE_DRUM_KIT, "Drum Kit" },
  40. { SDL_JOYSTICK_TYPE_ARCADE_PAD, "Arcade Pad" },
  41. { SDL_JOYSTICK_TYPE_THROTTLE, "Throttle" },
  42. EndImplementEnumType;
  43. typedef SDL_JoystickPowerLevel SDLPowerEnum;
  44. DefineEnumType(SDLPowerEnum);
  45. ImplementEnumType(SDLPowerEnum,
  46. "An enumeration of battery levels of a joystick.\n\n"
  47. "@ingroup Input")
  48. { SDL_JOYSTICK_POWER_UNKNOWN, "Unknown" },
  49. { SDL_JOYSTICK_POWER_EMPTY, "Empty" },
  50. { SDL_JOYSTICK_POWER_LOW, "Low" },
  51. { SDL_JOYSTICK_POWER_MEDIUM, "Medium" },
  52. { SDL_JOYSTICK_POWER_FULL, "Full" },
  53. { SDL_JOYSTICK_POWER_WIRED, "Wired" },
  54. { SDL_JOYSTICK_POWER_MAX, "Max" },
  55. EndImplementEnumType;
  56. IMPLEMENT_STATIC_CLASS(SDLInputManager, ,
  57. "@brief Static class exposing the SDL_Joystick and SDL_GameController APIs to Torque Script.\n"
  58. "SDLInputManager provides access to the functions of these APIs through static class "
  59. "functions.These functions are not required to bind or process events.By setting "
  60. "pref::Input::JoystickEnabled or pref::Input::sdlControllerEnabled to true, all connected "
  61. "devices will automatically be opened.All of the joystick and controller events defined "
  62. "in event.h can then be bound. For complete API documentation see the Joystick and Game "
  63. "Controller section of https ://wiki.libsdl.org/APIByCategory#Input_Events.\n\n"
  64. "@tsexample\n"
  65. "// Get the name and device type for all connected devices\n"
  66. "%sdlDevices = SDLInputManager::numJoysticks();\n"
  67. "for (%i = 0; %i < %sdlDevices; %i++)\n"
  68. "{\n"
  69. " %deviceName = SDLInputManager::JoystickNameForIndex(%i);\n"
  70. " %deviceType = SDLInputManager::GetDeviceType(%i);\n"
  71. "}\n"
  72. "\n"
  73. "// List all installed controller mappings\n"
  74. "%numMappings = SDLInputManager::GameControllerNumMappings();\n"
  75. "for (%i = 0; %i < %numMappings; %i++)\n"
  76. " echo(SDLInputManager::GameControllerMappingForIndex(%i));\n"
  77. "@endtsexample\n\n");
  78. IMPLEMENT_GLOBAL_CALLBACK(onSDLDeviceConnected, void, (S32 sdlIndex, const char* deviceName, const char* deviceType),
  79. (sdlIndex, deviceName, deviceType),
  80. "Callback that occurs when an input device is connected to the system.\n\n"
  81. "@param sdlIndex The index that will be used by sdl to refer to the device.\n"
  82. "@param deviceName The name that the device reports. This will be the return "
  83. "value of SDL_JoystickNameForIndex or SDL_GameControllerNameForIndex depending on the device type.\n"
  84. "@param deviceType The type of device connected. See SDLInputManager::getDeviceType() "
  85. "for possible string values.\n\n");
  86. IMPLEMENT_GLOBAL_CALLBACK(onSDLDeviceDisconnected, void, (S32 sdlIndex), (sdlIndex),
  87. "Callback that occurs when an input device is disconnected from the system.\n\n"
  88. "@param sdlIndex The index of the device that was removed.\n");
  89. //------------------------------------------------------------------------------
  90. // Static class variables:
  91. bool SDLInputManager::smJoystickEnabled = true;
  92. bool SDLInputManager::smJoystickSplitAxesLR = true;
  93. bool SDLInputManager::smControllerEnabled = true;
  94. bool SDLInputManager::smPOVButtonEvents = true;
  95. bool SDLInputManager::smPOVMaskEvents = false;
  96. // Map SDL controller Axis to torque input event
  97. // Commented text from map_StringForControllerAxis[] in SDL_gamecontroller.c
  98. S32 SDLInputManager::map_EventForControllerAxis[] = {
  99. SI_XAXIS, //"leftx",
  100. SI_YAXIS, //"lefty",
  101. SI_RXAXIS, //"rightx",
  102. SI_RYAXIS, //"righty",
  103. SI_ZAXIS, //"lefttrigger",
  104. SI_RZAXIS, //"righttrigger",
  105. -1 // NULL
  106. };
  107. // Map SDL controller button ID to torque input event
  108. // Commented text from map_StringForControllerButton[] in SDL_gamecontroller.c
  109. S32 SDLInputManager::map_EventForControllerButton[] = {
  110. XI_A, //"a",
  111. XI_B, //"b",
  112. XI_X, //"x",
  113. XI_Y, //"y",
  114. XI_BACK, //"back",
  115. XI_GUIDE, //"guide",
  116. XI_START, //"start",
  117. XI_LEFT_THUMB, //"leftstick",
  118. XI_RIGHT_THUMB, //"rightstick",
  119. XI_LEFT_SHOULDER, //"leftshoulder",
  120. XI_RIGHT_SHOULDER, //"rightshoulder",
  121. SI_UPOV, //"dpup",
  122. SI_DPOV, //"dpdown",
  123. SI_LPOV, //"dpleft",
  124. SI_RPOV, //"dpright",
  125. -1 // NULL
  126. };
  127. //------------------------------------------------------------------------------
  128. void SDLInputManager::joystickState::reset()
  129. {
  130. sdlInstID = -1;
  131. inputDevice = NULL;
  132. numAxes = 0;
  133. lastHatState[0] = 0;
  134. lastHatState[1] = 0;
  135. }
  136. //------------------------------------------------------------------------------
  137. SDLInputManager::SDLInputManager()
  138. {
  139. mEnabled = true;
  140. mJoystickActive = true;
  141. for (S32 i = 0; i < MaxJoysticks; ++i)
  142. {
  143. mJoysticks[i].reset();
  144. mJoysticks[i].torqueInstID = i;
  145. }
  146. for (S32 i = 0; i < MaxControllers; ++i)
  147. {
  148. mControllers[i].sdlInstID = -1;
  149. mControllers[i].torqueInstID = i;
  150. mControllers[i].inputDevice = NULL;
  151. }
  152. }
  153. //------------------------------------------------------------------------------
  154. void SDLInputManager::init()
  155. {
  156. Con::addVariable( "pref::Input::JoystickEnabled", TypeBool, &smJoystickEnabled,
  157. "If true, Joystick devices will be automatically opened.\n\n"
  158. "@ingroup Input");
  159. Con::addVariable("pref::Input::JoystickSplitAxesLR", TypeBool, &smJoystickSplitAxesLR,
  160. "Split axis inputs on 4 axis joysticks. This has no effect on any other device.\n\n"
  161. "4 Axis joysticks use IDs 0-3 which get mapped to xaxis, yaxis, zaxis and rxaxis. "
  162. "When true, this will increment IDs 2 and 3 so the inputs map to xaxis, yaxis, rxaxis and ryaxis.\n"
  163. "@ingroup Input");
  164. Con::addVariable("pref::Input::sdlControllerEnabled", TypeBool, &smControllerEnabled,
  165. "If true, any Joystick device that SDL recognizes as a Game Controller will be automatically opened as a game controller.\n\n"
  166. "@ingroup Input");
  167. Con::addVariable("pref::Input::JoystickPOVButtons", TypeBool, &smPOVButtonEvents,
  168. "If true, the pov hat will be treated as 4 buttons and make/break events will be generated for "
  169. "upov, dpov, lpov and rpov.\n"
  170. "@ingroup Input");
  171. Con::addVariable("pref::Input::JoystickPOVMask", TypeBool, &smPOVMaskEvents,
  172. "If true, the pov hat will be treated as a single input with a 4 bit mask value. The povmask "
  173. "event will be generated with the current mask every time the mask value changes.\n"
  174. "@ingroup Input");
  175. // POV Hat mask bits
  176. Con::setIntVariable("$SDLMask::HatUp", SDL_HAT_UP);
  177. Con::setIntVariable("$SDLMask::HatRight", SDL_HAT_RIGHT);
  178. Con::setIntVariable("$SDLMask::HatDown", SDL_HAT_DOWN);
  179. Con::setIntVariable("$SDLMask::HatLeft", SDL_HAT_LEFT);
  180. }
  181. //------------------------------------------------------------------------------
  182. bool SDLInputManager::enable()
  183. {
  184. disable();
  185. if (smControllerEnabled || smJoystickEnabled)
  186. {
  187. for (S32 i = 0; i < SDL_NumJoysticks(); ++i)
  188. {
  189. if (smControllerEnabled && SDL_IsGameController(i))
  190. openController(i, 0);
  191. else if (smJoystickEnabled)
  192. openJoystick(i, 0);
  193. }
  194. }
  195. mEnabled = true;
  196. return true;
  197. }
  198. //------------------------------------------------------------------------------
  199. void SDLInputManager::disable()
  200. {
  201. // Close any open devices
  202. for (S32 i = 0; i < MaxControllers; ++i)
  203. closeControllerByIndex(i);
  204. for (S32 i = 0; i < MaxJoysticks; ++i)
  205. closeJoystickByIndex(i);
  206. mEnabled = false;
  207. }
  208. //------------------------------------------------------------------------------
  209. void SDLInputManager::process()
  210. {
  211. }
  212. //------------------------------------------------------------------------------
  213. void SDLInputManager::processEvent(SDL_Event &evt)
  214. {
  215. switch (evt.type)
  216. {
  217. case SDL_JOYAXISMOTION:
  218. {
  219. joystickState* torqueMapping;
  220. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jaxis.which, torqueMapping))
  221. break;
  222. // SDL axis value inputs are in (range: -32768 to 32767)
  223. // Torque axis values are -1.0 to 1.0
  224. F32 value = ((F32)evt.jaxis.value) / (F32) (evt.jaxis.value > 0 ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  225. S32 mapAxis = SI_XAXIS + evt.jaxis.axis;
  226. if (evt.jaxis.axis > 1 && torqueMapping->numAxes == 4 && smJoystickSplitAxesLR)
  227. mapAxis += 1; // On a 4 axis, we'll shift the second two so we use LX LY RX RY instead of LX LY LZ RX
  228. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_AXIS, mapAxis, SI_MOVE, value);
  229. break;
  230. }
  231. case SDL_JOYBALLMOTION:
  232. {
  233. joystickState* torqueMapping;
  234. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jball.which, torqueMapping) || evt.jball.ball >= MaxBalls)
  235. break;
  236. if (evt.jball.xrel != 0)
  237. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_INT, evt.jball.ball ? SI_XBALL2 : SI_XBALL, SI_MOVE, (S32) evt.jball.xrel);
  238. if (evt.jball.yrel != 0)
  239. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_INT, evt.jball.ball ? SI_YBALL2 : SI_YBALL, SI_MOVE, (S32) evt.jball.yrel);
  240. break;
  241. }
  242. case SDL_JOYHATMOTION:
  243. {
  244. joystickState* torqueMapping;
  245. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jball.which, torqueMapping) || evt.jhat.hat >= MaxHats)
  246. break;
  247. if (torqueMapping->lastHatState[evt.jhat.hat] != evt.jhat.value)
  248. {
  249. buildHatEvents(JoystickDeviceType, torqueMapping->torqueInstID, torqueMapping->lastHatState[evt.jhat.hat], evt.jhat.value, evt.jhat.hat);
  250. torqueMapping->lastHatState[evt.jhat.hat] = evt.jhat.value;
  251. }
  252. break;
  253. }
  254. case SDL_JOYBUTTONDOWN:
  255. case SDL_JOYBUTTONUP:
  256. {
  257. joystickState* torqueMapping;
  258. if (mJoystickMap.isEmpty() || !mJoystickMap.find(evt.jbutton.which, torqueMapping))
  259. break;
  260. buildInputEvent(JoystickDeviceType, torqueMapping->torqueInstID, SI_BUTTON, KEY_BUTTON0 + evt.jbutton.button,
  261. evt.cbutton.state == SDL_PRESSED ? SI_MAKE : SI_BREAK, evt.cbutton.state == SDL_PRESSED ? 1.0f : 0.0f);
  262. break;
  263. }
  264. case SDL_JOYDEVICEADDED:
  265. {
  266. deviceConnectedCallback(evt.jdevice.which);
  267. if (smControllerEnabled && SDL_IsGameController(evt.jdevice.which))
  268. break; // This device will be added as a controller
  269. if (smJoystickEnabled)
  270. openJoystick(evt.jdevice.which, 0);
  271. break;
  272. }
  273. case SDL_JOYDEVICEREMOVED:
  274. {
  275. onSDLDeviceDisconnected_callback(evt.jdevice.which);
  276. closeJoystick(evt.jdevice.which);
  277. break;
  278. }
  279. case SDL_CONTROLLERAXISMOTION:
  280. {
  281. controllerState* torqueMapping;
  282. if (mControllerMap.isEmpty() || !mControllerMap.find(evt.caxis.which, torqueMapping))
  283. break;
  284. // SDL axis value inputs are in (range: -32768 to 32767)
  285. // Torque axis values are -1.0 to 1.0
  286. F32 value = ((F32)evt.caxis.value) / (F32) (evt.caxis.value > 0 ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  287. buildInputEvent(GamepadDeviceType, torqueMapping->torqueInstID, SI_AXIS, map_EventForControllerAxis[evt.caxis.axis], SI_MOVE, value);
  288. break;
  289. }
  290. case SDL_CONTROLLERBUTTONDOWN:
  291. case SDL_CONTROLLERBUTTONUP:
  292. {
  293. controllerState* torqueMapping;
  294. if (mControllerMap.isEmpty() || !mControllerMap.find(evt.cbutton.which, torqueMapping))
  295. break;
  296. buildInputEvent(GamepadDeviceType, torqueMapping->torqueInstID, SI_BUTTON, map_EventForControllerButton[evt.cbutton.button],
  297. evt.cbutton.state == SDL_PRESSED ? SI_MAKE : SI_BREAK, evt.cbutton.state == SDL_PRESSED ? 1.0f : 0.0f);
  298. break;
  299. }
  300. case SDL_CONTROLLERDEVICEADDED:
  301. {
  302. if (smControllerEnabled)
  303. openController(evt.cdevice.which, 0);
  304. break;
  305. }
  306. case SDL_CONTROLLERDEVICEREMOVED:
  307. {
  308. closeController(evt.cdevice.which);
  309. break;
  310. }
  311. case SDL_CONTROLLERDEVICEREMAPPED:
  312. break;
  313. default:
  314. #ifdef TORQUE_DEBUG
  315. Con::warnf("Unhandled SDL input event: 0x%04x", evt.type);
  316. #endif
  317. break;
  318. }
  319. }
  320. //------------------------------------------------------------------------------
  321. void SDLInputManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, S32 iValue)
  322. {
  323. InputEventInfo newEvent;
  324. newEvent.deviceType = deviceType;
  325. newEvent.deviceInst = deviceInst;
  326. newEvent.objType = objType;
  327. newEvent.objInst = objInst;
  328. newEvent.action = action;
  329. newEvent.iValue = iValue;
  330. newEvent.postToSignal(Input::smInputEvent);
  331. }
  332. //------------------------------------------------------------------------------
  333. void SDLInputManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, F32 fValue)
  334. {
  335. InputEventInfo newEvent;
  336. newEvent.deviceType = deviceType;
  337. newEvent.deviceInst = deviceInst;
  338. newEvent.objType = objType;
  339. newEvent.objInst = objInst;
  340. newEvent.action = action;
  341. newEvent.fValue = fValue;
  342. newEvent.postToSignal(Input::smInputEvent);
  343. }
  344. //------------------------------------------------------------------------------
  345. void SDLInputManager::buildHatEvents(U32 deviceType, U32 deviceInst, U8 lastState, U8 currentState, S32 hatIndex)
  346. {
  347. if (smPOVButtonEvents)
  348. {
  349. if ((lastState & SDL_HAT_UP) != (currentState & SDL_HAT_UP))
  350. {
  351. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_UPOV2 : SI_UPOV,
  352. (currentState & SDL_HAT_UP) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_UP) ? 1.0f : 0.0f);
  353. }
  354. if ((lastState & SDL_HAT_DOWN) != (currentState & SDL_HAT_DOWN))
  355. {
  356. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_DPOV2 : SI_DPOV,
  357. (currentState & SDL_HAT_DOWN) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_DOWN) ? 1.0f : 0.0f);
  358. }
  359. if ((lastState & SDL_HAT_LEFT) != (currentState & SDL_HAT_LEFT))
  360. {
  361. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_LPOV2 : SI_LPOV,
  362. (currentState & SDL_HAT_LEFT) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_LEFT) ? 1.0f : 0.0f);
  363. }
  364. if ((lastState & SDL_HAT_RIGHT) != (currentState & SDL_HAT_RIGHT))
  365. {
  366. buildInputEvent(deviceType, deviceInst, SI_POV, hatIndex ? SI_RPOV2 : SI_RPOV,
  367. (currentState & SDL_HAT_RIGHT) ? SI_MAKE : SI_BREAK, (currentState & SDL_HAT_RIGHT) ? 1.0f : 0.0f);
  368. }
  369. }
  370. if (smPOVMaskEvents)
  371. {
  372. buildInputEvent(deviceType, deviceInst, SI_INT, hatIndex ? SI_POVMASK2 : SI_POVMASK, SI_VALUE, (S32) currentState);
  373. }
  374. }
  375. //------------------------------------------------------------------------------
  376. S32 SDLInputManager::openController(S32 sdlIndex, S32 requestedTID)
  377. {
  378. if ((sdlIndex < 0) || (sdlIndex >= SDL_NumJoysticks()) || (requestedTID < 0) || (requestedTID >= MaxControllers))
  379. return -1;
  380. if (SDL_IsGameController(sdlIndex))
  381. {
  382. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  383. if (inputDevice)
  384. {
  385. SDL_JoystickID sdlId = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(inputDevice));
  386. // See if the device is already open as a joystick
  387. for (S32 i = 0; i < MaxJoysticks; ++i)
  388. {
  389. if (mJoysticks[i].sdlInstID == sdlId)
  390. {
  391. if (!closeJoystickByIndex(i))
  392. {
  393. SDL_GameControllerClose(inputDevice);
  394. return -1;
  395. }
  396. }
  397. }
  398. controllerState* torqueMapping = NULL;
  399. if (mControllerMap.find(sdlId, torqueMapping))
  400. {
  401. if (torqueMapping->torqueInstID == (U32) requestedTID)
  402. {
  403. SDL_GameControllerClose(inputDevice);
  404. return requestedTID; // Already open at the requested ID
  405. }
  406. closeControllerByIndex(torqueMapping->torqueInstID);
  407. }
  408. S32 gamepadSlot = -1;
  409. if (!mControllers[requestedTID].inputDevice)
  410. gamepadSlot = requestedTID;
  411. else
  412. {
  413. // Find the first available gamepad device slot
  414. for (S32 i = 0; i < MaxControllers; ++i)
  415. {
  416. if (!mControllers[i].inputDevice)
  417. {
  418. gamepadSlot = i;
  419. break;
  420. }
  421. }
  422. }
  423. if (gamepadSlot == -1)
  424. {
  425. Con::errorf("Unable to open Game Controller %s. Too many devices present.", SDL_GameControllerName(inputDevice));
  426. SDL_GameControllerClose(inputDevice);
  427. return -1;
  428. }
  429. mControllers[gamepadSlot].inputDevice = inputDevice;
  430. mControllers[gamepadSlot].sdlInstID = sdlId;
  431. mControllerMap.insertUnique(sdlId, &mControllers[gamepadSlot]);
  432. return gamepadSlot;
  433. }
  434. }
  435. return -1;
  436. }
  437. //------------------------------------------------------------------------------
  438. void SDLInputManager::closeController(SDL_JoystickID sdlId)
  439. {
  440. controllerState* torqueMapping = NULL;
  441. if (mControllerMap.find(sdlId, torqueMapping))
  442. closeControllerByIndex(torqueMapping->torqueInstID);
  443. }
  444. //------------------------------------------------------------------------------
  445. bool SDLInputManager::closeControllerByIndex(S32 index)
  446. {
  447. if (index < 0 || index >= MaxControllers)
  448. return false;
  449. if (mControllers[index].inputDevice && mControllers[index].sdlInstID != -1)
  450. {
  451. SDL_GameControllerClose(mControllers[index].inputDevice);
  452. mControllerMap.erase(mControllers[index].sdlInstID);
  453. mControllers[index].sdlInstID = -1;
  454. mControllers[index].inputDevice = NULL;
  455. return true;
  456. }
  457. return false;
  458. }
  459. //------------------------------------------------------------------------------
  460. S32 SDLInputManager::openJoystick(S32 sdlIndex, S32 requestedTID)
  461. {
  462. if ((sdlIndex < 0) || (sdlIndex >= SDL_NumJoysticks()) || (requestedTID < 0) || (requestedTID >= MaxJoysticks))
  463. return -1;
  464. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  465. if (inputDevice)
  466. {
  467. SDL_JoystickID sdlId = SDL_JoystickInstanceID(inputDevice);
  468. // See if the device is already open as a controller
  469. for (S32 i = 0; i < MaxControllers; ++i)
  470. {
  471. if (mControllers[i].sdlInstID == sdlId)
  472. {
  473. if (!closeControllerByIndex(i))
  474. {
  475. SDL_JoystickClose(inputDevice);
  476. return -1;
  477. }
  478. }
  479. }
  480. joystickState* torqueMapping = NULL;
  481. if (mJoystickMap.find(sdlId, torqueMapping))
  482. {
  483. if (torqueMapping->torqueInstID == (U32) requestedTID)
  484. {
  485. SDL_JoystickClose(inputDevice);
  486. return requestedTID; // Already open at the requested ID
  487. }
  488. closeJoystickByIndex(torqueMapping->torqueInstID);
  489. }
  490. S32 joystickSlot = -1;
  491. if (!mJoysticks[requestedTID].inputDevice)
  492. joystickSlot = requestedTID;
  493. else
  494. {
  495. // Find the first available joystick device slot
  496. for (S32 i = 0; i < MaxJoysticks; ++i)
  497. {
  498. if (!mJoysticks[i].inputDevice)
  499. {
  500. joystickSlot = i;
  501. break;
  502. }
  503. }
  504. }
  505. if (joystickSlot == -1)
  506. {
  507. Con::errorf("Unable to open Joystick %s. Too many devices present.", SDL_JoystickName(inputDevice));
  508. SDL_JoystickClose(inputDevice);
  509. return -1;
  510. }
  511. mJoysticks[joystickSlot].inputDevice = inputDevice;
  512. mJoysticks[joystickSlot].sdlInstID = sdlId;
  513. mJoysticks[joystickSlot].numAxes = SDL_JoystickNumAxes(inputDevice);
  514. mJoystickMap.insertUnique(sdlId, &mJoysticks[joystickSlot]);
  515. return joystickSlot;
  516. }
  517. return -1;
  518. }
  519. //------------------------------------------------------------------------------
  520. void SDLInputManager::closeJoystick(SDL_JoystickID sdlId)
  521. {
  522. joystickState* torqueMapping = NULL;
  523. if (mJoystickMap.find(sdlId, torqueMapping))
  524. closeJoystickByIndex(torqueMapping->torqueInstID);
  525. }
  526. //------------------------------------------------------------------------------
  527. bool SDLInputManager::closeJoystickByIndex(S32 index)
  528. {
  529. if (index < 0 || index >= MaxJoysticks)
  530. return false;
  531. if (mJoysticks[index].inputDevice && mJoysticks[index].sdlInstID != -1)
  532. {
  533. SDL_JoystickClose(mJoysticks[index].inputDevice);
  534. mJoystickMap.erase(mJoysticks[index].sdlInstID);
  535. mJoysticks[index].reset();
  536. return true;
  537. }
  538. return false;
  539. }
  540. //------------------------------------------------------------------------------
  541. void SDLInputManager::closeDevice(S32 sdlIndex)
  542. {
  543. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  544. return;
  545. SDL_JoystickID sdlId = -1;
  546. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  547. if (inputDevice)
  548. {
  549. sdlId = SDL_JoystickInstanceID(inputDevice);
  550. SDL_JoystickClose(inputDevice);
  551. }
  552. if (sdlId < 0)
  553. return;
  554. for (S32 i = 0; i < MaxControllers; ++i)
  555. {
  556. if (mControllers[i].sdlInstID == sdlId)
  557. {
  558. closeControllerByIndex(i);
  559. return;
  560. }
  561. }
  562. for (S32 i = 0; i < MaxJoysticks; ++i)
  563. {
  564. if (mJoysticks[i].sdlInstID == sdlId)
  565. {
  566. closeJoystickByIndex(i);
  567. return;
  568. }
  569. }
  570. }
  571. //------------------------------------------------------------------------------
  572. void SDLInputManager::deviceConnectedCallback(S32 index)
  573. {
  574. // This will generate the script callback:
  575. // onSDLDeviceConnected(%sdlIndex, %isController, %deviceName)
  576. bool isController = SDL_IsGameController(index);
  577. const char *deviceName = isController ? SDL_GameControllerNameForIndex(index) : SDL_JoystickNameForIndex(index);
  578. SDL_JoystickType deviceType = SDL_JoystickGetDeviceType(index);
  579. onSDLDeviceConnected_callback(index, deviceName, castConsoleTypeToString(deviceType));
  580. }
  581. //------------------------------------------------------------------------------
  582. // Console interface
  583. //------------------------------------------------------------------------------
  584. // Get the N'th SDL device state -1=doesn't exist, 0=closed, 1=open joystick, 2=open controller
  585. S32 SDLInputManager::getJoystickOpenState(S32 sdlIndex)
  586. {
  587. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  588. return -1;
  589. S32 currentState = 0;
  590. // We need to open the joystick to get the sdl instanceID
  591. // This will increase the refcount on the joystick if it was already open.
  592. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  593. if (inputDevice)
  594. {
  595. SDL_JoystickID sdlId = SDL_JoystickInstanceID(inputDevice);
  596. controllerState* controllerMapping = NULL;
  597. joystickState* joystickMapping = NULL;
  598. if (!mControllerMap.isEmpty() && mControllerMap.find(sdlId, controllerMapping))
  599. currentState = 2;
  600. else if (!mJoystickMap.isEmpty() && mJoystickMap.find(sdlId, joystickMapping))
  601. currentState = 1;
  602. // Close the joystick to return the refcount to the previouse state
  603. SDL_JoystickClose(inputDevice);
  604. }
  605. return currentState;
  606. }
  607. //------------------------------------------------------------------------------
  608. // Fills in the torque device instance string from an sdl joystick index number
  609. void SDLInputManager::getJoystickTorqueInst(S32 sdlIndex, char* instBuffer)
  610. {
  611. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  612. return;
  613. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  614. if (inputDevice)
  615. {
  616. SDL_JoystickID sdlId = SDL_JoystickInstanceID(inputDevice);
  617. controllerState* controllerMapping = NULL;
  618. joystickState* joystickMapping = NULL;
  619. if (!mControllerMap.isEmpty() && mControllerMap.find(sdlId, controllerMapping))
  620. ActionMap::getDeviceName(GamepadDeviceType, controllerMapping->torqueInstID, instBuffer);
  621. else if (!mJoystickMap.isEmpty() && mJoystickMap.find(sdlId, joystickMapping))
  622. ActionMap::getDeviceName(JoystickDeviceType, joystickMapping->torqueInstID, instBuffer);
  623. SDL_JoystickClose(inputDevice);
  624. }
  625. }
  626. //------------------------------------------------------------------------------
  627. DefineEngineStaticMethod(SDLInputManager, numJoysticks, S32, (), ,
  628. "@brief Returns the number of currently connected joystick devices.\n\n"
  629. "Game Controllers are a sub-set of joysticks and are included in the joystick count. "
  630. "See https://wiki.libsdl.org/SDL_NumJoysticks for more details.\n"
  631. "@ingroup Input")
  632. {
  633. return SDL_NumJoysticks();
  634. }
  635. //------------------------------------------------------------------------------
  636. DefineEngineStaticMethod(SDLInputManager, getDeviceOpenState, S32, ( S32 sdlIndex ), ( 0 ),
  637. "@brief Used to determine the current state of the N'th item in the SDL device list.\n\n"
  638. "@param sdlIndex The SDL index for this device.\n"
  639. "@return values:\n"
  640. "-1 if the device does not exist (invalid sdlIndex passed)\n"
  641. "0 The device is closed\n"
  642. "1 The device is open as a Joystick\n"
  643. "2 The device is open as a Game Controller\n"
  644. "@ingroup Input")
  645. {
  646. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  647. if (mgr && mgr->isEnabled())
  648. return mgr->getJoystickOpenState(sdlIndex);
  649. return -1;
  650. }
  651. //------------------------------------------------------------------------------
  652. DefineEngineStaticMethod(SDLInputManager, openAsJoystick, S32, ( S32 sdlIndex, S32 torqueInstId ), ( 0, 0 ),
  653. "@brief Used to open the device as a Joystick.\n\n"
  654. "If the device is currently open as a Game Controller, it will be closed and opened as "
  655. "a Joystick. If it is currently opened as a Joystick with a different T3D instance ID, "
  656. "it will be changed to the requested ID if that ID is available.\n"
  657. "@param sdlIndex The SDL index for this device.\n"
  658. "@param torqueInstId Is the requested T3D device instance ID. If there is already an open Joystick with "
  659. "the requested ID, The first available ID will be assigned.\n"
  660. "@return The T3D device instance ID assigned, or -1 if the device could not be opened.")
  661. {
  662. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  663. if (mgr && mgr->isEnabled())
  664. return mgr->openJoystick(sdlIndex, torqueInstId);
  665. return -1;
  666. }
  667. //------------------------------------------------------------------------------
  668. DefineEngineStaticMethod(SDLInputManager, openAsController, S32, (S32 sdlIndex, S32 torqueInstId), (0, 0),
  669. "@brief Used to open the device as a Game Controller.\n\n"
  670. "If the device is currently open as a Joystick, it will be closed and opened as "
  671. "a Game Controller. If it is currently opened as a Game Controller with a different "
  672. "T3D instance ID, it will be changed to the requested ID if that ID is available.\n"
  673. "@param sdlIndex The SDL index for this device.\n"
  674. "@param torqueInstId Is the requested T3D device instance ID. If there is already an "
  675. "open Game Controller with the requested ID, The first available ID will be assigned.\n"
  676. "@return The T3D device instance ID assigned, or -1 if the device could not be opened.")
  677. {
  678. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  679. if (mgr && mgr->isEnabled())
  680. return mgr->openController(sdlIndex, torqueInstId);
  681. return -1;
  682. }
  683. //------------------------------------------------------------------------------
  684. DefineEngineStaticMethod(SDLInputManager, closeDevice, void, (S32 sdlIndex), (0),
  685. "@brief Used to close the N'th item in the SDL device list.\n\n"
  686. "This will close a Joystick or Game Controller.\n"
  687. "@param sdlIndex The SDL index for this device.\n")
  688. {
  689. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  690. if (mgr && mgr->isEnabled())
  691. mgr->closeDevice(sdlIndex);
  692. return;
  693. }
  694. //------------------------------------------------------------------------------
  695. DefineEngineStaticMethod(SDLInputManager, getTorqueInstFromDevice, const char *, (S32 sdlIndex), (0),
  696. "@brief Gets the T3D instance identifier for an open SDL joystick.\n\n"
  697. "@param sdlIndex The SDL index for this device.\n"
  698. "@return Returns the T3D instance ID used for mapping this device or Null if it does not exist.\n"
  699. "@ingroup Input")
  700. {
  701. SDLInputManager* mgr = dynamic_cast<SDLInputManager*>(Input::getManager());
  702. if (mgr && mgr->isEnabled())
  703. {
  704. char* deviceInst = Con::getReturnBuffer(32);
  705. deviceInst[0] = '\0';
  706. mgr->getJoystickTorqueInst(sdlIndex, deviceInst);
  707. return deviceInst;
  708. }
  709. return NULL;
  710. }
  711. //------------------------------------------------------------------------------
  712. DefineEngineStaticMethod(SDLInputManager, JoystickNameForIndex, const char *, (S32 sdlIndex), (0),
  713. "@brief Exposes SDL_JoystickNameForIndex() to script.\n\n"
  714. "@param sdlIndex The SDL index for this device.\n"
  715. "@return Returns the name of the selected joystick or Null if it does not exist.\n"
  716. "@see https://wiki.libsdl.org/SDL_JoystickNameForIndex \n"
  717. "@ingroup Input")
  718. {
  719. if (sdlIndex >= 0 && sdlIndex < SDL_NumJoysticks())
  720. return SDL_JoystickNameForIndex(sdlIndex);
  721. return NULL;
  722. }
  723. //------------------------------------------------------------------------------
  724. DefineEngineStaticMethod(SDLInputManager, ControllerNameForIndex, const char *, (S32 sdlIndex), (0),
  725. "@brief Exposes SDL_GameControllerNameForIndex() to script.\n\n"
  726. "@param sdlIndex The SDL index for this device.\n"
  727. "@return Returns the implementation dependent name for the game controller, "
  728. "or NULL if there is no name or the index is invalid.\n"
  729. "@see https://wiki.libsdl.org/SDL_GameControllerNameForIndex \n"
  730. "@ingroup Input")
  731. {
  732. if (sdlIndex >= 0 && sdlIndex < SDL_NumJoysticks() || !SDL_IsGameController(sdlIndex))
  733. return SDL_GameControllerNameForIndex(sdlIndex);
  734. return NULL;
  735. }
  736. //------------------------------------------------------------------------------
  737. DefineEngineStaticMethod(SDLInputManager, JoystickGetGUID, const char *, (S32 sdlIndex), (0),
  738. "@brief Exposes SDL_JoystickGetDeviceGUID() to script.\n\n"
  739. "@param sdlIndex The SDL index for this device.\n"
  740. "@return GUID for the indexed device or Null if it does not exist.\n"
  741. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceGUID \n"
  742. "@ingroup Input")
  743. {
  744. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  745. return NULL;
  746. SDL_JoystickGUID guidVal = SDL_JoystickGetDeviceGUID(sdlIndex);
  747. char *guidStr = Con::getReturnBuffer(64);
  748. SDL_JoystickGetGUIDString(guidVal, guidStr, 64);
  749. return guidStr;
  750. }
  751. //------------------------------------------------------------------------------
  752. DefineEngineStaticMethod(SDLInputManager, GetVendor, S32, (S32 sdlIndex), (0),
  753. "Gets the USB vendor ID of a joystick device, if available.\n\n"
  754. "@param sdlIndex The SDL index for this device.\n"
  755. "@return The USB vendor ID. If the vendor ID isn't available this function returns 0.\n"
  756. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceVendor \n"
  757. "@see https://wiki.libsdl.org/SDL_JoystickGetVendor \n"
  758. "@see https://wiki.libsdl.org/SDL_GameControllerGetVendor \n"
  759. "@ingroup Input")
  760. {
  761. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  762. return 0;
  763. return (S32) SDL_JoystickGetDeviceVendor(sdlIndex);
  764. }
  765. //------------------------------------------------------------------------------
  766. DefineEngineStaticMethod(SDLInputManager, GetProduct, S32, (S32 sdlIndex), (0),
  767. "Gets the USB product ID of a joystick device, if available.\n\n"
  768. "@param sdlIndex The SDL index for this device.\n"
  769. "@return The USB product ID. If the product ID isn't available this function returns 0.\n"
  770. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceProduct \n"
  771. "@see https://wiki.libsdl.org/SDL_JoystickGetProduct \n"
  772. "@see https://wiki.libsdl.org/SDL_GameControllerGetProduct \n"
  773. "@ingroup Input")
  774. {
  775. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  776. return 0;
  777. return (S32)SDL_JoystickGetDeviceProduct(sdlIndex);
  778. }
  779. //------------------------------------------------------------------------------
  780. DefineEngineStaticMethod(SDLInputManager, GetProductVersion, S32, (S32 sdlIndex), (0),
  781. "Gets the product version of a joystick device, if available.\n\n"
  782. "@param sdlIndex The SDL index for this device.\n"
  783. "@return The product version. If the product version isn't available this function returns 0.\n"
  784. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceProductVersion \n"
  785. "@see https://wiki.libsdl.org/SDL_JoystickGetProductVersion \n"
  786. "@see https://wiki.libsdl.org/SDL_GameControllerGetProductVersion \n"
  787. "@ingroup Input")
  788. {
  789. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  790. return 0;
  791. return (S32)SDL_JoystickGetDeviceProductVersion(sdlIndex);
  792. }
  793. //------------------------------------------------------------------------------
  794. DefineEngineStaticMethod(SDLInputManager, GetDeviceType, SDLJoystickType, (S32 sdlIndex), (0),
  795. "@brief Exposes SDL_JoystickGetDeviceType() to script.\n\n"
  796. "@param sdlIndex The SDL index for this device.\n"
  797. "@return The type of device connected. Possible return strings are: \"Unknown\", "
  798. "\"Game Controller\", \"Wheel\", \"Arcade Stick\", \"Flight Stick\", \"Dance Pad\", "
  799. "\"Guitar\", \"Drum Kit\", \"Arcade Pad\" and \"Throttle\"\n"
  800. "@see https://wiki.libsdl.org/SDL_JoystickGetDeviceType \n"
  801. "@ingroup Input")
  802. {
  803. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  804. return SDL_JOYSTICK_TYPE_UNKNOWN;
  805. return SDL_JoystickGetDeviceType(sdlIndex);
  806. }
  807. //------------------------------------------------------------------------------
  808. DefineEngineStaticMethod(SDLInputManager, JoystickNumAxes, S32, (S32 sdlIndex), (0),
  809. "@brief Exposes SDL_JoystickNumAxes() to script.\n\n"
  810. "@param sdlIndex The SDL index for this device.\n"
  811. "@return Returns the number of axis controls/number of axes on success or zero on failure.\n"
  812. "@see https://wiki.libsdl.org/SDL_JoystickNumAxes \n"
  813. "@ingroup Input")
  814. {
  815. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  816. return 0;
  817. S32 numAxes = 0;
  818. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  819. if (inputDevice)
  820. {
  821. numAxes = SDL_JoystickNumAxes(inputDevice);
  822. if (numAxes < 0)
  823. {
  824. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  825. numAxes = 0;
  826. }
  827. SDL_JoystickClose(inputDevice);
  828. }
  829. return numAxes;
  830. }
  831. //------------------------------------------------------------------------------
  832. DefineEngineStaticMethod(SDLInputManager, JoystickNumBalls, S32, (S32 sdlIndex), (0),
  833. "@brief Exposes SDL_JoystickNumBalls() to script.\n\n"
  834. "@param sdlIndex The SDL index for this device.\n"
  835. "@return Returns the number of trackballs on success or zero on failure.\n"
  836. "@see https://wiki.libsdl.org/SDL_JoystickNumBalls \n"
  837. "@ingroup Input")
  838. {
  839. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  840. return 0;
  841. S32 numBalls = 0;
  842. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  843. if (inputDevice)
  844. {
  845. numBalls = SDL_JoystickNumBalls(inputDevice);
  846. if (numBalls < 0)
  847. {
  848. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  849. numBalls = 0;
  850. }
  851. SDL_JoystickClose(inputDevice);
  852. }
  853. return numBalls;
  854. }
  855. //------------------------------------------------------------------------------
  856. DefineEngineStaticMethod(SDLInputManager, JoystickNumButtons, S32, (S32 sdlIndex), (0),
  857. "@brief Exposes SDL_JoystickNumButtons() to script.\n\n"
  858. "@param sdlIndex The SDL index for this device.\n"
  859. "@return Returns the number of buttons on success or zero on failure.\n"
  860. "@see https://wiki.libsdl.org/SDL_JoystickNumButtons \n"
  861. "@ingroup Input")
  862. {
  863. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  864. return 0;
  865. S32 numButtons = 0;
  866. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  867. if (inputDevice)
  868. {
  869. numButtons = SDL_JoystickNumButtons(inputDevice);
  870. if (numButtons < 0)
  871. {
  872. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  873. numButtons = 0;
  874. }
  875. SDL_JoystickClose(inputDevice);
  876. }
  877. return numButtons;
  878. }
  879. //------------------------------------------------------------------------------
  880. DefineEngineStaticMethod(SDLInputManager, JoystickNumHats, S32, (S32 sdlIndex), (0),
  881. "@brief Exposes SDL_JoystickNumHats() to script.\n\n"
  882. "@param sdlIndex The SDL index for this device.\n"
  883. "@return Returns the number of POV hats on success or zero on failure.\n"
  884. "@see https://wiki.libsdl.org/SDL_JoystickNumHats \n"
  885. "@ingroup Input")
  886. {
  887. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  888. return 0;
  889. S32 numHats = 0;
  890. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  891. if (inputDevice)
  892. {
  893. numHats = SDL_JoystickNumHats(inputDevice);
  894. if (numHats < 0)
  895. {
  896. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  897. numHats = 0;
  898. }
  899. SDL_JoystickClose(inputDevice);
  900. }
  901. return numHats;
  902. }
  903. //------------------------------------------------------------------------------
  904. DefineEngineStaticMethod(SDLInputManager, IsGameController, bool, (S32 sdlIndex), (0),
  905. "@brief Exposes SDL_IsGameController() to script.\n\n"
  906. "@param sdlIndex The SDL index for this device.\n"
  907. "@return Returns true if the given joystick is supported by the game controller "
  908. "interface, false if it isn't or it's an invalid index.\n"
  909. "@see https://wiki.libsdl.org/SDL_IsGameController \n"
  910. "@ingroup Input")
  911. {
  912. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks() || !SDL_IsGameController(sdlIndex))
  913. return false;
  914. return true;
  915. }
  916. //------------------------------------------------------------------------------
  917. DefineEngineStaticMethod(SDLInputManager, JoystickIsHaptic, bool, (S32 sdlIndex), (0),
  918. "@brief Exposes SDL_JoystickIsHaptic() to script.\n\n"
  919. "@param sdlIndex The SDL index for this device.\n"
  920. "@return Returns true if the joystick is haptic.\n"
  921. "@see https://wiki.libsdl.org/SDL_JoystickIsHaptic \n"
  922. "@ingroup Input")
  923. {
  924. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  925. return false;
  926. bool isHaptic = false;
  927. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  928. if (inputDevice)
  929. {
  930. isHaptic = (SDL_JoystickIsHaptic(inputDevice) == SDL_TRUE);
  931. SDL_JoystickClose(inputDevice);
  932. }
  933. return isHaptic;
  934. }
  935. //------------------------------------------------------------------------------
  936. DefineEngineStaticMethod(SDLInputManager, JoystickPowerLevel, SDLPowerEnum, (S32 sdlIndex), (0),
  937. "@brief Exposes SDL_JoystickCurrentPowerLevel() to script.\n\n"
  938. "@param sdlIndex The SDL index for this device.\n"
  939. "@return Returns the current battery level or \"Wired\" if it's a connected device.\n"
  940. "@see https://wiki.libsdl.org/SDL_JoystickCurrentPowerLevel \n"
  941. "@ingroup Input")
  942. {
  943. SDL_JoystickPowerLevel powerLevel = SDL_JOYSTICK_POWER_UNKNOWN;
  944. if (sdlIndex >= 0 && sdlIndex < SDL_NumJoysticks())
  945. {
  946. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  947. if (inputDevice)
  948. {
  949. powerLevel = SDL_JoystickCurrentPowerLevel(inputDevice);
  950. SDL_JoystickClose(inputDevice);
  951. }
  952. }
  953. return powerLevel;
  954. }
  955. //------------------------------------------------------------------------------
  956. DefineEngineStaticMethod(SDLInputManager, JoystickGetSpecs, String, (S32 sdlIndex), (0),
  957. "@brief A convenience function to reurn all of the data for a Joystick/Game Controller "
  958. " packed as fields in a tab separated string.\n\n"
  959. "There is overhead involved in querying joystick data, especially if the device is not open. "
  960. "If more than one field is required, it is more efficient to call JoystickGetSpecs() and "
  961. "parse the data out of the return string than to call the console method for each.\n"
  962. "@param sdlIndex The SDL index for this device.\n"
  963. "@return A tab separated string that can be parsed from script with getField()/getFields().\n\n"
  964. "Field 0: Number of Axes\n"
  965. " 1: Number of Buttons\n"
  966. " 2: Number of POV Hats\n"
  967. " 3: Number of Trackballs\n"
  968. " 4: SDL_IsGameController() (Boolean)\n"
  969. " 5: SDL_JoystickIsHaptic() (Boolean)\n"
  970. " 6: Power Level (String)\n"
  971. " 7: Device Type (String)\n"
  972. "@ingroup Input")
  973. {
  974. String specStr;
  975. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  976. return specStr;
  977. bool isController = SDL_IsGameController(sdlIndex);
  978. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  979. if (inputDevice)
  980. {
  981. SDL_JoystickPowerLevel powerLevel = SDL_JoystickCurrentPowerLevel(inputDevice);
  982. SDL_JoystickType deviceType = SDL_JoystickGetDeviceType(sdlIndex);
  983. specStr = String::ToString("%d\t%d\t%d\t%d\t%d\t%d\t%s\t%s\t",
  984. SDL_JoystickNumAxes(inputDevice), SDL_JoystickNumButtons(inputDevice),
  985. SDL_JoystickNumHats(inputDevice), SDL_JoystickNumBalls(inputDevice),
  986. isController ? 1 : 0, (SDL_JoystickIsHaptic(inputDevice) == SDL_TRUE) ? 1 : 0,
  987. castConsoleTypeToString(powerLevel), castConsoleTypeToString(deviceType));
  988. SDL_JoystickClose(inputDevice);
  989. }
  990. return specStr;
  991. }
  992. //------------------------------------------------------------------------------
  993. DefineEngineStaticMethod(SDLInputManager, JoystickGetAxes, String, (S32 sdlIndex), (0),
  994. "@brief Gets the current value for all joystick axes.\n\n"
  995. "@param sdlIndex The SDL index for this device.\n"
  996. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  997. "Each axis is one field, so a 4 axis device will have 4 fields.\n\n"
  998. "@ingroup Input")
  999. {
  1000. String axesStr;
  1001. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1002. return axesStr;
  1003. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  1004. if (inputDevice)
  1005. {
  1006. S32 numAxes = SDL_JoystickNumAxes(inputDevice);
  1007. for (S32 i = 0; i < numAxes; i++)
  1008. {
  1009. F32 axisVal = (F32) SDL_JoystickGetAxis(inputDevice, i);
  1010. F32 value = axisVal / (F32)(axisVal > 0.0f ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  1011. axesStr += String::ToString("%0.3f\t", value);
  1012. }
  1013. SDL_JoystickClose(inputDevice);
  1014. }
  1015. return axesStr;
  1016. }
  1017. //------------------------------------------------------------------------------
  1018. DefineEngineStaticMethod(SDLInputManager, JoystickGetButtons, String, (S32 sdlIndex), (0),
  1019. "@brief Gets the current value for all joystick buttons.\n\n"
  1020. "@param sdlIndex The SDL index for this device.\n"
  1021. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1022. "Each button is one field. 0 - SDL_JoystickNumButtons() fields.\n\n"
  1023. "@ingroup Input")
  1024. {
  1025. String buttonStr;
  1026. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1027. return buttonStr;
  1028. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  1029. if (inputDevice)
  1030. {
  1031. S32 numbuttons = SDL_JoystickNumButtons(inputDevice);
  1032. for (S32 i = 0; i < numbuttons; i++)
  1033. {
  1034. buttonStr += String::ToString("%d\t", (S32) SDL_JoystickGetButton(inputDevice, i));
  1035. }
  1036. SDL_JoystickClose(inputDevice);
  1037. }
  1038. return buttonStr;
  1039. }
  1040. //------------------------------------------------------------------------------
  1041. DefineEngineStaticMethod(SDLInputManager, JoystickGetHats, String, (S32 sdlIndex), (0),
  1042. "@brief Gets the current value for all POV hats.\n\n"
  1043. "@param sdlIndex The SDL index for this device.\n"
  1044. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1045. "Each hat is one field. 0 - SDL_JoystickNumHats() fields. The value is a 4 bit bitmask. "
  1046. "If no bits are set, the hat is centered. Bit 0 is up, 1 is right, 2 is down and 3 is left.\n\n"
  1047. "@ingroup Input")
  1048. {
  1049. String hatStr;
  1050. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1051. return hatStr;
  1052. SDL_Joystick *inputDevice = SDL_JoystickOpen(sdlIndex);
  1053. if (inputDevice)
  1054. {
  1055. S32 numHats = SDL_JoystickNumHats(inputDevice);
  1056. for (S32 i = 0; i < numHats; i++)
  1057. {
  1058. hatStr += String::ToString("%d\t", (S32)SDL_JoystickGetHat(inputDevice, i));
  1059. }
  1060. SDL_JoystickClose(inputDevice);
  1061. }
  1062. return hatStr;
  1063. }
  1064. //------------------------------------------------------------------------------
  1065. DefineEngineStaticMethod(SDLInputManager, ControllerGetAxes, String, (S32 sdlIndex), (0),
  1066. "@brief Gets the current value for all controller axes.\n\n"
  1067. "@param sdlIndex The SDL index for this device.\n"
  1068. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1069. "Game controllers always have 6 axes in the following order: 0-LX, 1-LY, 2-RX, 3-RY, 4-LT, 5-RT.\n\n"
  1070. "@ingroup Input")
  1071. {
  1072. String axesStr;
  1073. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1074. return axesStr;
  1075. bool isController = SDL_IsGameController(sdlIndex);
  1076. if (!isController)
  1077. return axesStr;
  1078. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  1079. if (inputDevice)
  1080. {
  1081. for (S32 i = SDL_CONTROLLER_AXIS_LEFTX; i < SDL_CONTROLLER_AXIS_MAX; i++)
  1082. {
  1083. F32 axisVal = (F32)SDL_GameControllerGetAxis(inputDevice, (SDL_GameControllerAxis) i);
  1084. F32 value = axisVal / (F32)(axisVal > 0.0f ? SDL_JOYSTICK_AXIS_MAX : -SDL_JOYSTICK_AXIS_MIN);
  1085. axesStr += String::ToString("%0.3f\t", value);
  1086. }
  1087. SDL_GameControllerClose(inputDevice);
  1088. }
  1089. return axesStr;
  1090. }
  1091. //------------------------------------------------------------------------------
  1092. DefineEngineStaticMethod(SDLInputManager, ControllerGetButtons, String, (S32 sdlIndex), (0),
  1093. "@brief Gets the current value for all controller buttons.\n\n"
  1094. "@param sdlIndex The SDL index for this device.\n"
  1095. "@return A tab separated string that can be parsed from script with getField()/getFields(). "
  1096. "Game controllers always have 15 buttons in the following order: 0-A, 1-B, 2-X, 3-Y, 4-Back, "
  1097. "5-Guide, 6-Start, 7-Left Stick, 8-Right Stick, 9-Left Shoulder, 10-Right Shoulder, "
  1098. "11-DPad Up, 12-DPad Down, 13-DPad Left, 14-DPad Right.\n\n"
  1099. "@ingroup Input")
  1100. {
  1101. String buttonStr;
  1102. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1103. return buttonStr;
  1104. bool isController = SDL_IsGameController(sdlIndex);
  1105. if (!isController)
  1106. return buttonStr;
  1107. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  1108. if (inputDevice)
  1109. {
  1110. for (S32 i = SDL_CONTROLLER_BUTTON_A; i < SDL_CONTROLLER_BUTTON_MAX; i++)
  1111. {
  1112. buttonStr += String::ToString("%d\t", (S32)SDL_GameControllerGetButton(inputDevice, (SDL_GameControllerButton) i));
  1113. }
  1114. SDL_GameControllerClose(inputDevice);
  1115. }
  1116. return buttonStr;
  1117. }
  1118. //------------------------------------------------------------------------------
  1119. DefineEngineStaticMethod(SDLInputManager, GameControllerMapping, String, (S32 sdlIndex), (0),
  1120. "@brief Exposes SDL_GameControllerMapping() to script.\n\n"
  1121. "@param sdlIndex The SDL index for this device.\n"
  1122. "@return Returns a string that has the controller's mapping or NULL if no mapping "
  1123. "is available or it does not exist.\n"
  1124. "@see https://wiki.libsdl.org/SDL_JoystickNameForIndex \n"
  1125. "@ingroup Input")
  1126. {
  1127. String mapping;
  1128. if (sdlIndex < 0 || sdlIndex >= SDL_NumJoysticks())
  1129. return mapping;
  1130. SDL_GameController *inputDevice = SDL_GameControllerOpen(sdlIndex);
  1131. if (inputDevice)
  1132. {
  1133. char* sdlStr = SDL_GameControllerMapping(inputDevice);
  1134. if (sdlStr)
  1135. {
  1136. mapping = sdlStr;
  1137. SDL_free(sdlStr);
  1138. }
  1139. else
  1140. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  1141. SDL_GameControllerClose(inputDevice);
  1142. }
  1143. return mapping;
  1144. }
  1145. //------------------------------------------------------------------------------
  1146. DefineEngineStaticMethod(SDLInputManager, GameControllerMappingForGUID, String, (const char* guidStr), ,
  1147. "@brief Exposes SDL_GameControllerMappingForGUID() to script.\n\n"
  1148. "@param guidStr The GUID for which a mapping is desired.\n"
  1149. "@return Returns a mapping string or NULL on error.\n"
  1150. "@see https://wiki.libsdl.org/SDL_GameControllerMappingForGUID \n"
  1151. "@ingroup Input")
  1152. {
  1153. String mapping;
  1154. SDL_JoystickGUID guid = SDL_JoystickGetGUIDFromString(guidStr);
  1155. char* sdlStr = SDL_GameControllerMappingForGUID(guid);
  1156. if (sdlStr)
  1157. {
  1158. mapping = sdlStr;
  1159. SDL_free(sdlStr);
  1160. }
  1161. return mapping;
  1162. }
  1163. //------------------------------------------------------------------------------
  1164. DefineEngineStaticMethod(SDLInputManager, GameControllerAddMapping, S32, (const char* mappingString), ,
  1165. "@brief Exposes SDL_GameControllerAddMapping() to script.\n\n"
  1166. "Use this function to add support for controllers that SDL is unaware of or "
  1167. "to cause an existing controller to have a different binding.\n"
  1168. "@param mappingString The new mapping string to apply. Full details on the format of this "
  1169. "string are available at the linked SDL wiki page.\n"
  1170. "@return Returns 1 if a new mapping is added, 0 if an existing mapping is updated, -1 on error.\n"
  1171. "@see https://wiki.libsdl.org/SDL_GameControllerAddMapping \n"
  1172. "@ingroup Input")
  1173. {
  1174. S32 retVal = SDL_GameControllerAddMapping(mappingString);
  1175. if (retVal == -1)
  1176. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  1177. return retVal;
  1178. }
  1179. //------------------------------------------------------------------------------
  1180. DefineEngineStaticMethod(SDLInputManager, GameControllerAddMappingsFromFile, S32, (const char* fileName), ,
  1181. "@brief Exposes SDL_GameControllerAddMappingsFromFile() to script.\n\n"
  1182. "Use this function to load a set of Game Controller mappings from a file, filtered by the "
  1183. "current SDL_GetPlatform(). A community sourced database of controllers is available at "
  1184. "https://raw.githubusercontent.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt \n"
  1185. "@param fileName The file to load mappings from.\n"
  1186. "@return Returns the number of mappings added or -1 on error.\n"
  1187. "@see https://wiki.libsdl.org/SDL_GameControllerAddMappingsFromFile \n"
  1188. "@ingroup Input")
  1189. {
  1190. char torquePath[1024];
  1191. Con::expandScriptFilename(torquePath, sizeof(torquePath), fileName);
  1192. S32 retVal = SDL_GameControllerAddMappingsFromFile(torquePath);
  1193. if (retVal == -1)
  1194. Con::errorf("SDL Joystick error: %s", SDL_GetError());
  1195. return retVal;
  1196. }
  1197. //------------------------------------------------------------------------------
  1198. DefineEngineStaticMethod(SDLInputManager, GameControllerNumMappings, S32, (), ,
  1199. "Get the number of mappings installed. Used with GameControllerMappingForIndex "
  1200. "to iterate through all installed mappings.\n\n"
  1201. "@ingroup Input")
  1202. {
  1203. return SDL_GameControllerNumMappings();
  1204. }
  1205. //------------------------------------------------------------------------------
  1206. DefineEngineStaticMethod(SDLInputManager, GameControllerMappingForIndex, String, (S32 mappingIndex), ,
  1207. "Get the mapping at a particular index.\n\n"
  1208. "@param mappingIndex The index for which a mapping is desired.\n"
  1209. "@return Returns a mapping string or NULL if the index is out of range.\n"
  1210. "@ingroup Input")
  1211. {
  1212. String mapping;
  1213. char* sdlStr = SDL_GameControllerMappingForIndex(mappingIndex);
  1214. if (sdlStr)
  1215. {
  1216. mapping = sdlStr;
  1217. SDL_free(sdlStr);
  1218. }
  1219. return mapping;
  1220. }