input.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. /*************************************************************************/
  2. /* input.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "input.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/default_controller_mappings.h"
  33. #include "core/input/input_map.h"
  34. #include "core/os/os.h"
  35. #ifdef TOOLS_ENABLED
  36. #include "editor/editor_settings.h"
  37. #endif
  38. static const char *_joy_buttons[JOY_BUTTON_SDL_MAX] = {
  39. "a",
  40. "b",
  41. "x",
  42. "y",
  43. "back",
  44. "guide",
  45. "start",
  46. "leftstick",
  47. "rightstick",
  48. "leftshoulder",
  49. "rightshoulder",
  50. "dpup",
  51. "dpdown",
  52. "dpleft",
  53. "dpright",
  54. "misc1",
  55. "paddle1",
  56. "paddle2",
  57. "paddle3",
  58. "paddle4",
  59. "touchpad",
  60. };
  61. static const char *_joy_axes[JOY_AXIS_SDL_MAX] = {
  62. "leftx",
  63. "lefty",
  64. "rightx",
  65. "righty",
  66. "lefttrigger",
  67. "righttrigger",
  68. };
  69. Input *Input::singleton = nullptr;
  70. void (*Input::set_mouse_mode_func)(Input::MouseMode) = nullptr;
  71. Input::MouseMode (*Input::get_mouse_mode_func)() = nullptr;
  72. void (*Input::warp_mouse_func)(const Vector2 &p_to_pos) = nullptr;
  73. Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
  74. void (*Input::set_custom_mouse_cursor_func)(const RES &, Input::CursorShape, const Vector2 &) = nullptr;
  75. Input *Input::get_singleton() {
  76. return singleton;
  77. }
  78. void Input::set_mouse_mode(MouseMode p_mode) {
  79. ERR_FAIL_INDEX((int)p_mode, 5);
  80. set_mouse_mode_func(p_mode);
  81. }
  82. Input::MouseMode Input::get_mouse_mode() const {
  83. return get_mouse_mode_func();
  84. }
  85. void Input::_bind_methods() {
  86. ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
  87. ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
  88. ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
  89. ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
  90. ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
  91. ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
  92. ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
  93. ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
  94. ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
  95. ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
  96. ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
  97. ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
  98. ClassDB::bind_method(D_METHOD("joy_connection_changed", "device", "connected", "name", "guid"), &Input::joy_connection_changed);
  99. ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
  100. ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
  101. ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
  102. ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
  103. ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
  104. ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
  105. ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
  106. ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
  107. ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
  108. ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms"), &Input::vibrate_handheld, DEFVAL(500));
  109. ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
  110. ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
  111. ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
  112. ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
  113. ClassDB::bind_method(D_METHOD("get_last_mouse_speed"), &Input::get_last_mouse_speed);
  114. ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
  115. ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
  116. ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
  117. ClassDB::bind_method(D_METHOD("warp_mouse_position", "to"), &Input::warp_mouse_position);
  118. ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
  119. ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
  120. ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
  121. ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
  122. ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
  123. ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
  124. ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
  125. BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
  126. BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
  127. BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
  128. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
  129. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
  130. BIND_ENUM_CONSTANT(CURSOR_ARROW);
  131. BIND_ENUM_CONSTANT(CURSOR_IBEAM);
  132. BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
  133. BIND_ENUM_CONSTANT(CURSOR_CROSS);
  134. BIND_ENUM_CONSTANT(CURSOR_WAIT);
  135. BIND_ENUM_CONSTANT(CURSOR_BUSY);
  136. BIND_ENUM_CONSTANT(CURSOR_DRAG);
  137. BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
  138. BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
  139. BIND_ENUM_CONSTANT(CURSOR_VSIZE);
  140. BIND_ENUM_CONSTANT(CURSOR_HSIZE);
  141. BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
  142. BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
  143. BIND_ENUM_CONSTANT(CURSOR_MOVE);
  144. BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
  145. BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
  146. BIND_ENUM_CONSTANT(CURSOR_HELP);
  147. ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
  148. }
  149. void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  150. #ifdef TOOLS_ENABLED
  151. const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", 0) ? "'" : "\"";
  152. String pf = p_function;
  153. if (p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" ||
  154. pf == "is_action_just_pressed" || pf == "is_action_just_released" ||
  155. pf == "get_action_strength" || pf == "get_action_raw_strength" ||
  156. pf == "get_axis" || pf == "get_vector")) {
  157. List<PropertyInfo> pinfo;
  158. ProjectSettings::get_singleton()->get_property_list(&pinfo);
  159. for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
  160. const PropertyInfo &pi = E->get();
  161. if (!pi.name.begins_with("input/")) {
  162. continue;
  163. }
  164. String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
  165. r_options->push_back(quote_style + name + quote_style);
  166. }
  167. }
  168. #endif
  169. }
  170. void Input::SpeedTrack::update(const Vector2 &p_delta_p) {
  171. uint64_t tick = OS::get_singleton()->get_ticks_usec();
  172. uint32_t tdiff = tick - last_tick;
  173. float delta_t = tdiff / 1000000.0;
  174. last_tick = tick;
  175. accum += p_delta_p;
  176. accum_t += delta_t;
  177. if (accum_t > max_ref_frame * 10) {
  178. accum_t = max_ref_frame * 10;
  179. }
  180. while (accum_t >= min_ref_frame) {
  181. float slice_t = min_ref_frame / accum_t;
  182. Vector2 slice = accum * slice_t;
  183. accum = accum - slice;
  184. accum_t -= min_ref_frame;
  185. speed = (slice / min_ref_frame).lerp(speed, min_ref_frame / max_ref_frame);
  186. }
  187. }
  188. void Input::SpeedTrack::reset() {
  189. last_tick = OS::get_singleton()->get_ticks_usec();
  190. speed = Vector2();
  191. accum_t = 0;
  192. }
  193. Input::SpeedTrack::SpeedTrack() {
  194. min_ref_frame = 0.1;
  195. max_ref_frame = 0.3;
  196. reset();
  197. }
  198. bool Input::is_key_pressed(int p_keycode) const {
  199. _THREAD_SAFE_METHOD_
  200. return keys_pressed.has(p_keycode);
  201. }
  202. bool Input::is_mouse_button_pressed(MouseButton p_button) const {
  203. _THREAD_SAFE_METHOD_
  204. return (mouse_button_mask & (1 << (p_button - 1))) != 0;
  205. }
  206. static int _combine_device(int p_value, int p_device) {
  207. return p_value | (p_device << 20);
  208. }
  209. bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
  210. _THREAD_SAFE_METHOD_
  211. return joy_buttons_pressed.has(_combine_device(p_button, p_device));
  212. }
  213. bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
  214. #ifdef DEBUG_ENABLED
  215. bool has_action = InputMap::get_singleton()->has_action(p_action);
  216. ERR_FAIL_COND_V_MSG(!has_action, false, "Request for nonexistent InputMap action '" + String(p_action) + "'.");
  217. #endif
  218. return action_state.has(p_action) && action_state[p_action].pressed && (p_exact ? action_state[p_action].exact : true);
  219. }
  220. bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
  221. #ifdef DEBUG_ENABLED
  222. bool has_action = InputMap::get_singleton()->has_action(p_action);
  223. ERR_FAIL_COND_V_MSG(!has_action, false, "Request for nonexistent InputMap action '" + String(p_action) + "'.");
  224. #endif
  225. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  226. if (!E) {
  227. return false;
  228. }
  229. if (p_exact && E->get().exact == false) {
  230. return false;
  231. }
  232. if (Engine::get_singleton()->is_in_physics_frame()) {
  233. return E->get().pressed && E->get().physics_frame == Engine::get_singleton()->get_physics_frames();
  234. } else {
  235. return E->get().pressed && E->get().process_frame == Engine::get_singleton()->get_process_frames();
  236. }
  237. }
  238. bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
  239. #ifdef DEBUG_ENABLED
  240. bool has_action = InputMap::get_singleton()->has_action(p_action);
  241. ERR_FAIL_COND_V_MSG(!has_action, false, "Request for nonexistent InputMap action '" + String(p_action) + "'.");
  242. #endif
  243. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  244. if (!E) {
  245. return false;
  246. }
  247. if (p_exact && E->get().exact == false) {
  248. return false;
  249. }
  250. if (Engine::get_singleton()->is_in_physics_frame()) {
  251. return !E->get().pressed && E->get().physics_frame == Engine::get_singleton()->get_physics_frames();
  252. } else {
  253. return !E->get().pressed && E->get().process_frame == Engine::get_singleton()->get_process_frames();
  254. }
  255. }
  256. float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
  257. #ifdef DEBUG_ENABLED
  258. bool has_action = InputMap::get_singleton()->has_action(p_action);
  259. ERR_FAIL_COND_V_MSG(!has_action, false, "Request for nonexistent InputMap action '" + String(p_action) + "'.");
  260. #endif
  261. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  262. if (!E) {
  263. return 0.0f;
  264. }
  265. if (p_exact && E->get().exact == false) {
  266. return 0.0f;
  267. }
  268. return E->get().strength;
  269. }
  270. float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
  271. const Map<StringName, Action>::Element *E = action_state.find(p_action);
  272. if (!E) {
  273. return 0.0f;
  274. }
  275. if (p_exact && E->get().exact == false) {
  276. return 0.0f;
  277. }
  278. return E->get().raw_strength;
  279. }
  280. float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
  281. return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
  282. }
  283. Vector2 Input::get_vector(const StringName &p_negative_x, const StringName &p_positive_x, const StringName &p_negative_y, const StringName &p_positive_y, float p_deadzone) const {
  284. Vector2 vector = Vector2(
  285. get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
  286. get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
  287. if (p_deadzone < 0.0f) {
  288. // If the deadzone isn't specified, get it from the average of the actions.
  289. p_deadzone = (InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
  290. InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
  291. InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
  292. InputMap::get_singleton()->action_get_deadzone(p_negative_y)) /
  293. 4;
  294. }
  295. // Circular length limiting and deadzone.
  296. float length = vector.length();
  297. if (length <= p_deadzone) {
  298. return Vector2();
  299. } else if (length > 1.0f) {
  300. return vector / length;
  301. } else {
  302. // Inverse lerp length to map (p_deadzone, 1) to (0, 1).
  303. return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
  304. }
  305. return vector;
  306. }
  307. float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
  308. _THREAD_SAFE_METHOD_
  309. int c = _combine_device(p_axis, p_device);
  310. if (_joy_axis.has(c)) {
  311. return _joy_axis[c];
  312. } else {
  313. return 0;
  314. }
  315. }
  316. String Input::get_joy_name(int p_idx) {
  317. _THREAD_SAFE_METHOD_
  318. return joy_names[p_idx].name;
  319. }
  320. Vector2 Input::get_joy_vibration_strength(int p_device) {
  321. if (joy_vibration.has(p_device)) {
  322. return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
  323. } else {
  324. return Vector2(0, 0);
  325. }
  326. }
  327. uint64_t Input::get_joy_vibration_timestamp(int p_device) {
  328. if (joy_vibration.has(p_device)) {
  329. return joy_vibration[p_device].timestamp;
  330. } else {
  331. return 0;
  332. }
  333. }
  334. float Input::get_joy_vibration_duration(int p_device) {
  335. if (joy_vibration.has(p_device)) {
  336. return joy_vibration[p_device].duration;
  337. } else {
  338. return 0.f;
  339. }
  340. }
  341. static String _hex_str(uint8_t p_byte) {
  342. static const char *dict = "0123456789abcdef";
  343. char ret[3];
  344. ret[2] = 0;
  345. ret[0] = dict[p_byte >> 4];
  346. ret[1] = dict[p_byte & 0xf];
  347. return ret;
  348. }
  349. void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) {
  350. _THREAD_SAFE_METHOD_
  351. Joypad js;
  352. js.name = p_connected ? p_name : "";
  353. js.uid = p_connected ? p_guid : "";
  354. if (p_connected) {
  355. String uidname = p_guid;
  356. if (p_guid == "") {
  357. int uidlen = MIN(p_name.length(), 16);
  358. for (int i = 0; i < uidlen; i++) {
  359. uidname = uidname + _hex_str(p_name[i]);
  360. }
  361. }
  362. js.uid = uidname;
  363. js.connected = true;
  364. int mapping = fallback_mapping;
  365. for (int i = 0; i < map_db.size(); i++) {
  366. if (js.uid == map_db[i].uid) {
  367. mapping = i;
  368. js.name = map_db[i].name;
  369. }
  370. }
  371. js.mapping = mapping;
  372. } else {
  373. js.connected = false;
  374. for (int i = 0; i < JOY_BUTTON_MAX; i++) {
  375. int c = _combine_device(i, p_idx);
  376. joy_buttons_pressed.erase(c);
  377. }
  378. for (int i = 0; i < JOY_AXIS_MAX; i++) {
  379. set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
  380. }
  381. }
  382. joy_names[p_idx] = js;
  383. emit_signal(SNAME("joy_connection_changed"), p_idx, p_connected);
  384. }
  385. Vector3 Input::get_gravity() const {
  386. _THREAD_SAFE_METHOD_
  387. return gravity;
  388. }
  389. Vector3 Input::get_accelerometer() const {
  390. _THREAD_SAFE_METHOD_
  391. return accelerometer;
  392. }
  393. Vector3 Input::get_magnetometer() const {
  394. _THREAD_SAFE_METHOD_
  395. return magnetometer;
  396. }
  397. Vector3 Input::get_gyroscope() const {
  398. _THREAD_SAFE_METHOD_
  399. return gyroscope;
  400. }
  401. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  402. _parse_input_event_impl(p_event, false);
  403. }
  404. void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
  405. // Notes on mouse-touch emulation:
  406. // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
  407. // as true mouse events. The only difference is the situation is flagged as emulated so they are not
  408. // emulated back to touch events in an endless loop.
  409. // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
  410. // require additional handling by this class.
  411. _THREAD_SAFE_METHOD_
  412. Ref<InputEventKey> k = p_event;
  413. if (k.is_valid() && !k->is_echo() && k->get_keycode() != 0) {
  414. if (k->is_pressed()) {
  415. keys_pressed.insert(k->get_keycode());
  416. } else {
  417. keys_pressed.erase(k->get_keycode());
  418. }
  419. }
  420. Ref<InputEventMouseButton> mb = p_event;
  421. if (mb.is_valid()) {
  422. if (mb->is_pressed()) {
  423. mouse_button_mask |= (MouseButton)(1 << (mb->get_button_index() - 1));
  424. } else {
  425. mouse_button_mask &= (MouseButton) ~(1 << (mb->get_button_index() - 1));
  426. }
  427. Point2 pos = mb->get_global_position();
  428. if (mouse_pos != pos) {
  429. set_mouse_position(pos);
  430. }
  431. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == 1) {
  432. Ref<InputEventScreenTouch> touch_event;
  433. touch_event.instantiate();
  434. touch_event->set_pressed(mb->is_pressed());
  435. touch_event->set_position(mb->get_position());
  436. event_dispatch_function(touch_event);
  437. }
  438. }
  439. Ref<InputEventMouseMotion> mm = p_event;
  440. if (mm.is_valid()) {
  441. Point2 pos = mm->get_global_position();
  442. if (mouse_pos != pos) {
  443. set_mouse_position(pos);
  444. }
  445. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mm->get_button_mask() & 1) {
  446. Ref<InputEventScreenDrag> drag_event;
  447. drag_event.instantiate();
  448. drag_event->set_position(mm->get_position());
  449. drag_event->set_relative(mm->get_relative());
  450. drag_event->set_speed(mm->get_speed());
  451. event_dispatch_function(drag_event);
  452. }
  453. }
  454. Ref<InputEventScreenTouch> st = p_event;
  455. if (st.is_valid()) {
  456. if (st->is_pressed()) {
  457. SpeedTrack &track = touch_speed_track[st->get_index()];
  458. track.reset();
  459. } else {
  460. // Since a pointer index may not occur again (OSs may or may not reuse them),
  461. // imperatively remove it from the map to keep no fossil entries in it
  462. touch_speed_track.erase(st->get_index());
  463. }
  464. if (emulate_mouse_from_touch) {
  465. bool translate = false;
  466. if (st->is_pressed()) {
  467. if (mouse_from_touch_index == -1) {
  468. translate = true;
  469. mouse_from_touch_index = st->get_index();
  470. }
  471. } else {
  472. if (st->get_index() == mouse_from_touch_index) {
  473. translate = true;
  474. mouse_from_touch_index = -1;
  475. }
  476. }
  477. if (translate) {
  478. Ref<InputEventMouseButton> button_event;
  479. button_event.instantiate();
  480. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  481. button_event->set_position(st->get_position());
  482. button_event->set_global_position(st->get_position());
  483. button_event->set_pressed(st->is_pressed());
  484. button_event->set_button_index(MOUSE_BUTTON_LEFT);
  485. if (st->is_pressed()) {
  486. button_event->set_button_mask(MouseButton(mouse_button_mask | MOUSE_BUTTON_MASK_LEFT));
  487. } else {
  488. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MOUSE_BUTTON_MASK_LEFT));
  489. }
  490. _parse_input_event_impl(button_event, true);
  491. }
  492. }
  493. }
  494. Ref<InputEventScreenDrag> sd = p_event;
  495. if (sd.is_valid()) {
  496. SpeedTrack &track = touch_speed_track[sd->get_index()];
  497. track.update(sd->get_relative());
  498. sd->set_speed(track.speed);
  499. if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
  500. Ref<InputEventMouseMotion> motion_event;
  501. motion_event.instantiate();
  502. motion_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  503. motion_event->set_position(sd->get_position());
  504. motion_event->set_global_position(sd->get_position());
  505. motion_event->set_relative(sd->get_relative());
  506. motion_event->set_speed(sd->get_speed());
  507. motion_event->set_button_mask(mouse_button_mask);
  508. _parse_input_event_impl(motion_event, true);
  509. }
  510. }
  511. Ref<InputEventJoypadButton> jb = p_event;
  512. if (jb.is_valid()) {
  513. int c = _combine_device(jb->get_button_index(), jb->get_device());
  514. if (jb->is_pressed()) {
  515. joy_buttons_pressed.insert(c);
  516. } else {
  517. joy_buttons_pressed.erase(c);
  518. }
  519. }
  520. Ref<InputEventJoypadMotion> jm = p_event;
  521. if (jm.is_valid()) {
  522. set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
  523. }
  524. Ref<InputEventGesture> ge = p_event;
  525. if (ge.is_valid()) {
  526. if (event_dispatch_function) {
  527. event_dispatch_function(ge);
  528. }
  529. }
  530. for (OrderedHashMap<StringName, InputMap::Action>::ConstElement E = InputMap::get_singleton()->get_action_map().front(); E; E = E.next()) {
  531. if (InputMap::get_singleton()->event_is_action(p_event, E.key())) {
  532. // If not echo and action pressed state has changed
  533. if (!p_event->is_echo() && is_action_pressed(E.key(), false) != p_event->is_action_pressed(E.key())) {
  534. Action action;
  535. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  536. action.process_frame = Engine::get_singleton()->get_process_frames();
  537. action.pressed = p_event->is_action_pressed(E.key());
  538. action.strength = 0.0f;
  539. action.raw_strength = 0.0f;
  540. action.exact = InputMap::get_singleton()->event_is_action(p_event, E.key(), true);
  541. action_state[E.key()] = action;
  542. }
  543. action_state[E.key()].strength = p_event->get_action_strength(E.key());
  544. action_state[E.key()].raw_strength = p_event->get_action_raw_strength(E.key());
  545. }
  546. }
  547. if (event_dispatch_function) {
  548. event_dispatch_function(p_event);
  549. }
  550. }
  551. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  552. _THREAD_SAFE_METHOD_
  553. int c = _combine_device(p_axis, p_device);
  554. _joy_axis[c] = p_value;
  555. }
  556. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  557. _THREAD_SAFE_METHOD_
  558. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  559. return;
  560. }
  561. VibrationInfo vibration;
  562. vibration.weak_magnitude = p_weak_magnitude;
  563. vibration.strong_magnitude = p_strong_magnitude;
  564. vibration.duration = p_duration;
  565. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  566. joy_vibration[p_device] = vibration;
  567. }
  568. void Input::stop_joy_vibration(int p_device) {
  569. _THREAD_SAFE_METHOD_
  570. VibrationInfo vibration;
  571. vibration.weak_magnitude = 0;
  572. vibration.strong_magnitude = 0;
  573. vibration.duration = 0;
  574. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  575. joy_vibration[p_device] = vibration;
  576. }
  577. void Input::vibrate_handheld(int p_duration_ms) {
  578. OS::get_singleton()->vibrate_handheld(p_duration_ms);
  579. }
  580. void Input::set_gravity(const Vector3 &p_gravity) {
  581. _THREAD_SAFE_METHOD_
  582. gravity = p_gravity;
  583. }
  584. void Input::set_accelerometer(const Vector3 &p_accel) {
  585. _THREAD_SAFE_METHOD_
  586. accelerometer = p_accel;
  587. }
  588. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  589. _THREAD_SAFE_METHOD_
  590. magnetometer = p_magnetometer;
  591. }
  592. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  593. _THREAD_SAFE_METHOD_
  594. gyroscope = p_gyroscope;
  595. }
  596. void Input::set_mouse_position(const Point2 &p_posf) {
  597. mouse_speed_track.update(p_posf - mouse_pos);
  598. mouse_pos = p_posf;
  599. }
  600. Point2 Input::get_mouse_position() const {
  601. return mouse_pos;
  602. }
  603. Point2 Input::get_last_mouse_speed() const {
  604. return mouse_speed_track.speed;
  605. }
  606. int Input::get_mouse_button_mask() const {
  607. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  608. }
  609. void Input::warp_mouse_position(const Vector2 &p_to) {
  610. warp_mouse_func(p_to);
  611. }
  612. Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  613. // The relative distance reported for the next event after a warp is in the boundaries of the
  614. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  615. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  616. // and the subsequent event, the reported relative distance will be less than the size of the rect
  617. // and thus fmod() will be disabled for handling the situation.
  618. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  619. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  620. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  621. const Point2i rel_sgn(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  622. const Size2i warp_margin = p_rect.size * 0.5f;
  623. const Point2i rel_warped(
  624. Math::fmod(p_motion->get_relative().x + rel_sgn.x * warp_margin.x, p_rect.size.x) - rel_sgn.x * warp_margin.x,
  625. Math::fmod(p_motion->get_relative().y + rel_sgn.y * warp_margin.y, p_rect.size.y) - rel_sgn.y * warp_margin.y);
  626. const Point2i pos_local = p_motion->get_global_position() - p_rect.position;
  627. const Point2i pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  628. if (pos_warped != pos_local) {
  629. warp_mouse_position(pos_warped + p_rect.position);
  630. }
  631. return rel_warped;
  632. }
  633. void Input::iteration(float p_step) {
  634. }
  635. void Input::action_press(const StringName &p_action, float p_strength) {
  636. Action action;
  637. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  638. action.process_frame = Engine::get_singleton()->get_process_frames();
  639. action.pressed = true;
  640. action.strength = p_strength;
  641. action_state[p_action] = action;
  642. }
  643. void Input::action_release(const StringName &p_action) {
  644. Action action;
  645. action.physics_frame = Engine::get_singleton()->get_physics_frames();
  646. action.process_frame = Engine::get_singleton()->get_process_frames();
  647. action.pressed = false;
  648. action.strength = 0.f;
  649. action_state[p_action] = action;
  650. }
  651. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  652. emulate_touch_from_mouse = p_emulate;
  653. }
  654. bool Input::is_emulating_touch_from_mouse() const {
  655. return emulate_touch_from_mouse;
  656. }
  657. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  658. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  659. void Input::ensure_touch_mouse_raised() {
  660. if (mouse_from_touch_index != -1) {
  661. mouse_from_touch_index = -1;
  662. Ref<InputEventMouseButton> button_event;
  663. button_event.instantiate();
  664. button_event->set_device(InputEvent::DEVICE_ID_TOUCH_MOUSE);
  665. button_event->set_position(mouse_pos);
  666. button_event->set_global_position(mouse_pos);
  667. button_event->set_pressed(false);
  668. button_event->set_button_index(MOUSE_BUTTON_LEFT);
  669. button_event->set_button_mask(MouseButton(mouse_button_mask & ~MOUSE_BUTTON_MASK_LEFT));
  670. _parse_input_event_impl(button_event, true);
  671. }
  672. }
  673. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  674. emulate_mouse_from_touch = p_emulate;
  675. }
  676. bool Input::is_emulating_mouse_from_touch() const {
  677. return emulate_mouse_from_touch;
  678. }
  679. Input::CursorShape Input::get_default_cursor_shape() const {
  680. return default_shape;
  681. }
  682. void Input::set_default_cursor_shape(CursorShape p_shape) {
  683. if (default_shape == p_shape) {
  684. return;
  685. }
  686. default_shape = p_shape;
  687. // The default shape is set in Viewport::_gui_input_event. To instantly
  688. // see the shape in the viewport we need to trigger a mouse motion event.
  689. Ref<InputEventMouseMotion> mm;
  690. mm.instantiate();
  691. mm->set_position(mouse_pos);
  692. mm->set_global_position(mouse_pos);
  693. parse_input_event(mm);
  694. }
  695. Input::CursorShape Input::get_current_cursor_shape() const {
  696. return get_current_cursor_shape_func();
  697. }
  698. void Input::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  699. if (Engine::get_singleton()->is_editor_hint()) {
  700. return;
  701. }
  702. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  703. }
  704. void Input::accumulate_input_event(const Ref<InputEvent> &p_event) {
  705. ERR_FAIL_COND(p_event.is_null());
  706. if (!use_accumulated_input) {
  707. parse_input_event(p_event);
  708. return;
  709. }
  710. if (!accumulated_events.is_empty() && accumulated_events.back()->get()->accumulate(p_event)) {
  711. return; //event was accumulated, exit
  712. }
  713. accumulated_events.push_back(p_event);
  714. }
  715. void Input::flush_accumulated_events() {
  716. while (accumulated_events.front()) {
  717. parse_input_event(accumulated_events.front()->get());
  718. accumulated_events.pop_front();
  719. }
  720. }
  721. void Input::set_use_accumulated_input(bool p_enable) {
  722. use_accumulated_input = p_enable;
  723. }
  724. void Input::release_pressed_events() {
  725. flush_accumulated_events(); // this is needed to release actions strengths
  726. keys_pressed.clear();
  727. joy_buttons_pressed.clear();
  728. _joy_axis.clear();
  729. for (Map<StringName, Input::Action>::Element *E = action_state.front(); E; E = E->next()) {
  730. if (E->get().pressed) {
  731. action_release(E->key());
  732. }
  733. }
  734. }
  735. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  736. event_dispatch_function = p_function;
  737. }
  738. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  739. _THREAD_SAFE_METHOD_;
  740. Joypad &joy = joy_names[p_device];
  741. //printf("got button %i, mapping is %i\n", p_button, joy.mapping);
  742. if (joy.last_buttons[p_button] == p_pressed) {
  743. return;
  744. }
  745. joy.last_buttons[p_button] = p_pressed;
  746. if (joy.mapping == -1) {
  747. _button_event(p_device, p_button, p_pressed);
  748. return;
  749. }
  750. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  751. if (map.type == TYPE_BUTTON) {
  752. _button_event(p_device, (JoyButton)map.index, p_pressed);
  753. return;
  754. }
  755. if (map.type == TYPE_AXIS) {
  756. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  757. }
  758. // no event?
  759. }
  760. void Input::joy_axis(int p_device, JoyAxis p_axis, const JoyAxisValue &p_value) {
  761. _THREAD_SAFE_METHOD_;
  762. ERR_FAIL_INDEX(p_axis, JOY_AXIS_MAX);
  763. Joypad &joy = joy_names[p_device];
  764. if (joy.last_axis[p_axis] == p_value.value) {
  765. return;
  766. }
  767. //when changing direction quickly, insert fake event to release pending inputmap actions
  768. float last = joy.last_axis[p_axis];
  769. if (p_value.min == 0 && (last < 0.25 || last > 0.75) && (last - 0.5) * (p_value.value - 0.5) < 0) {
  770. JoyAxisValue jx;
  771. jx.min = p_value.min;
  772. jx.value = p_value.value < 0.5 ? 0.6 : 0.4;
  773. joy_axis(p_device, p_axis, jx);
  774. } else if (ABS(last) > 0.5 && last * p_value.value <= 0) {
  775. JoyAxisValue jx;
  776. jx.min = p_value.min;
  777. jx.value = last > 0 ? 0.1 : -0.1;
  778. joy_axis(p_device, p_axis, jx);
  779. }
  780. joy.last_axis[p_axis] = p_value.value;
  781. float val = p_value.min == 0 ? -1.0f + 2.0f * p_value.value : p_value.value;
  782. if (joy.mapping == -1) {
  783. _axis_event(p_device, p_axis, val);
  784. return;
  785. }
  786. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, val);
  787. if (map.type == TYPE_BUTTON) {
  788. bool pressed = map.value > 0.5;
  789. if (pressed == joy_buttons_pressed.has(_combine_device(map.index, p_device))) {
  790. // Button already pressed or released; so ignore.
  791. return;
  792. }
  793. _button_event(p_device, (JoyButton)map.index, pressed);
  794. // Ensure opposite D-Pad button is also released.
  795. switch (map.index) {
  796. case JOY_BUTTON_DPAD_UP:
  797. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_DOWN, p_device))) {
  798. _button_event(p_device, JOY_BUTTON_DPAD_DOWN, false);
  799. }
  800. break;
  801. case JOY_BUTTON_DPAD_DOWN:
  802. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_UP, p_device))) {
  803. _button_event(p_device, JOY_BUTTON_DPAD_UP, false);
  804. }
  805. break;
  806. case JOY_BUTTON_DPAD_LEFT:
  807. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_RIGHT, p_device))) {
  808. _button_event(p_device, JOY_BUTTON_DPAD_RIGHT, false);
  809. }
  810. break;
  811. case JOY_BUTTON_DPAD_RIGHT:
  812. if (joy_buttons_pressed.has(_combine_device(JOY_BUTTON_DPAD_LEFT, p_device))) {
  813. _button_event(p_device, JOY_BUTTON_DPAD_LEFT, false);
  814. }
  815. break;
  816. default:
  817. // Nothing to do.
  818. break;
  819. }
  820. return;
  821. }
  822. if (map.type == TYPE_AXIS) {
  823. _axis_event(p_device, (JoyAxis)map.index, map.value);
  824. return;
  825. }
  826. //printf("invalid mapping\n");
  827. }
  828. void Input::joy_hat(int p_device, int p_val) {
  829. _THREAD_SAFE_METHOD_;
  830. const Joypad &joy = joy_names[p_device];
  831. JoyEvent map[HAT_MAX];
  832. map[HatDir::HAT_UP].type = TYPE_BUTTON;
  833. map[HatDir::HAT_UP].index = JOY_BUTTON_DPAD_UP;
  834. map[HatDir::HAT_UP].value = 0;
  835. map[HatDir::HAT_RIGHT].type = TYPE_BUTTON;
  836. map[HatDir::HAT_RIGHT].index = JOY_BUTTON_DPAD_RIGHT;
  837. map[HatDir::HAT_RIGHT].value = 0;
  838. map[HatDir::HAT_DOWN].type = TYPE_BUTTON;
  839. map[HatDir::HAT_DOWN].index = JOY_BUTTON_DPAD_DOWN;
  840. map[HatDir::HAT_DOWN].value = 0;
  841. map[HatDir::HAT_LEFT].type = TYPE_BUTTON;
  842. map[HatDir::HAT_LEFT].index = JOY_BUTTON_DPAD_LEFT;
  843. map[HatDir::HAT_LEFT].value = 0;
  844. if (joy.mapping != -1) {
  845. _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
  846. }
  847. int cur_val = joy_names[p_device].hat_current;
  848. for (int hat_direction = 0, hat_mask = 1; hat_direction < HAT_MAX; hat_direction++, hat_mask <<= 1) {
  849. if ((p_val & hat_mask) != (cur_val & hat_mask)) {
  850. if (map[hat_direction].type == TYPE_BUTTON) {
  851. _button_event(p_device, (JoyButton)map[hat_direction].index, p_val & hat_mask);
  852. }
  853. if (map[hat_direction].type == TYPE_AXIS) {
  854. _axis_event(p_device, (JoyAxis)map[hat_direction].index, (p_val & hat_mask) ? map[hat_direction].value : 0.0);
  855. }
  856. }
  857. }
  858. joy_names[p_device].hat_current = p_val;
  859. }
  860. void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
  861. Ref<InputEventJoypadButton> ievent;
  862. ievent.instantiate();
  863. ievent->set_device(p_device);
  864. ievent->set_button_index(p_index);
  865. ievent->set_pressed(p_pressed);
  866. parse_input_event(ievent);
  867. }
  868. void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
  869. Ref<InputEventJoypadMotion> ievent;
  870. ievent.instantiate();
  871. ievent->set_device(p_device);
  872. ievent->set_axis(p_axis);
  873. ievent->set_axis_value(p_value);
  874. parse_input_event(ievent);
  875. }
  876. Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
  877. JoyEvent event;
  878. event.type = TYPE_MAX;
  879. for (int i = 0; i < mapping.bindings.size(); i++) {
  880. const JoyBinding binding = mapping.bindings[i];
  881. if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
  882. event.type = binding.outputType;
  883. switch (binding.outputType) {
  884. case TYPE_BUTTON:
  885. event.index = binding.output.button;
  886. return event;
  887. case TYPE_AXIS:
  888. event.index = binding.output.axis.axis;
  889. switch (binding.output.axis.range) {
  890. case POSITIVE_HALF_AXIS:
  891. event.value = 1;
  892. break;
  893. case NEGATIVE_HALF_AXIS:
  894. event.value = -1;
  895. break;
  896. case FULL_AXIS:
  897. // It doesn't make sense for a button to map to a full axis,
  898. // but keeping as a default for a trigger with a positive half-axis.
  899. event.value = 1;
  900. break;
  901. }
  902. return event;
  903. default:
  904. ERR_PRINT_ONCE("Joypad button mapping error.");
  905. }
  906. }
  907. }
  908. return event;
  909. }
  910. Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value) {
  911. JoyEvent event;
  912. event.type = TYPE_MAX;
  913. for (int i = 0; i < mapping.bindings.size(); i++) {
  914. const JoyBinding binding = mapping.bindings[i];
  915. if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
  916. float value = p_value;
  917. if (binding.input.axis.invert) {
  918. value = -value;
  919. }
  920. if (binding.input.axis.range == FULL_AXIS ||
  921. (binding.input.axis.range == POSITIVE_HALF_AXIS && value > 0) ||
  922. (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
  923. event.type = binding.outputType;
  924. float shifted_positive_value = 0;
  925. switch (binding.input.axis.range) {
  926. case POSITIVE_HALF_AXIS:
  927. shifted_positive_value = value;
  928. break;
  929. case NEGATIVE_HALF_AXIS:
  930. shifted_positive_value = value + 1;
  931. break;
  932. case FULL_AXIS:
  933. shifted_positive_value = (value + 1) / 2;
  934. break;
  935. }
  936. switch (binding.outputType) {
  937. case TYPE_BUTTON:
  938. event.index = binding.output.button;
  939. switch (binding.input.axis.range) {
  940. case POSITIVE_HALF_AXIS:
  941. event.value = shifted_positive_value;
  942. break;
  943. case NEGATIVE_HALF_AXIS:
  944. event.value = 1 - shifted_positive_value;
  945. break;
  946. case FULL_AXIS:
  947. // It doesn't make sense for a full axis to map to a button,
  948. // but keeping as a default for a trigger with a positive half-axis.
  949. event.value = (shifted_positive_value * 2) - 1;
  950. ;
  951. break;
  952. }
  953. return event;
  954. case TYPE_AXIS:
  955. event.index = binding.output.axis.axis;
  956. event.value = value;
  957. if (binding.output.axis.range != binding.input.axis.range) {
  958. switch (binding.output.axis.range) {
  959. case POSITIVE_HALF_AXIS:
  960. event.value = shifted_positive_value;
  961. break;
  962. case NEGATIVE_HALF_AXIS:
  963. event.value = shifted_positive_value - 1;
  964. break;
  965. case FULL_AXIS:
  966. event.value = (shifted_positive_value * 2) - 1;
  967. break;
  968. }
  969. }
  970. return event;
  971. default:
  972. ERR_PRINT_ONCE("Joypad axis mapping error.");
  973. }
  974. }
  975. }
  976. }
  977. return event;
  978. }
  979. void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[]) {
  980. for (int i = 0; i < mapping.bindings.size(); i++) {
  981. const JoyBinding binding = mapping.bindings[i];
  982. if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
  983. int hat_direction;
  984. switch (binding.input.hat.hat_mask) {
  985. case HatMask::HAT_MASK_UP:
  986. hat_direction = HatDir::HAT_UP;
  987. break;
  988. case HatMask::HAT_MASK_RIGHT:
  989. hat_direction = HatDir::HAT_RIGHT;
  990. break;
  991. case HatMask::HAT_MASK_DOWN:
  992. hat_direction = HatDir::HAT_DOWN;
  993. break;
  994. case HatMask::HAT_MASK_LEFT:
  995. hat_direction = HatDir::HAT_LEFT;
  996. break;
  997. default:
  998. ERR_PRINT_ONCE("Joypad button mapping error.");
  999. continue;
  1000. }
  1001. r_events[hat_direction].type = binding.outputType;
  1002. switch (binding.outputType) {
  1003. case TYPE_BUTTON:
  1004. r_events[hat_direction].index = binding.output.button;
  1005. break;
  1006. case TYPE_AXIS:
  1007. r_events[hat_direction].index = binding.output.axis.axis;
  1008. switch (binding.output.axis.range) {
  1009. case POSITIVE_HALF_AXIS:
  1010. r_events[hat_direction].value = 1;
  1011. break;
  1012. case NEGATIVE_HALF_AXIS:
  1013. r_events[hat_direction].value = -1;
  1014. break;
  1015. case FULL_AXIS:
  1016. // It doesn't make sense for a hat direction to map to a full axis,
  1017. // but keeping as a default for a trigger with a positive half-axis.
  1018. r_events[hat_direction].value = 1;
  1019. break;
  1020. }
  1021. break;
  1022. default:
  1023. ERR_PRINT_ONCE("Joypad button mapping error.");
  1024. }
  1025. }
  1026. }
  1027. }
  1028. JoyButton Input::_get_output_button(String output) {
  1029. for (int i = 0; i < JOY_BUTTON_SDL_MAX; i++) {
  1030. if (output == _joy_buttons[i]) {
  1031. return JoyButton(i);
  1032. }
  1033. }
  1034. return JoyButton::JOY_BUTTON_INVALID;
  1035. }
  1036. JoyAxis Input::_get_output_axis(String output) {
  1037. for (int i = 0; i < JOY_AXIS_SDL_MAX; i++) {
  1038. if (output == _joy_axes[i]) {
  1039. return JoyAxis(i);
  1040. }
  1041. }
  1042. return JoyAxis::JOY_AXIS_INVALID;
  1043. }
  1044. void Input::parse_mapping(String p_mapping) {
  1045. _THREAD_SAFE_METHOD_;
  1046. JoyDeviceMapping mapping;
  1047. Vector<String> entry = p_mapping.split(",");
  1048. if (entry.size() < 2) {
  1049. return;
  1050. }
  1051. CharString uid;
  1052. uid.resize(17);
  1053. mapping.uid = entry[0];
  1054. mapping.name = entry[1];
  1055. int idx = 1;
  1056. while (++idx < entry.size()) {
  1057. if (entry[idx] == "") {
  1058. continue;
  1059. }
  1060. String output = entry[idx].get_slice(":", 0).replace(" ", "");
  1061. String input = entry[idx].get_slice(":", 1).replace(" ", "");
  1062. ERR_CONTINUE_MSG(output.length() < 1 || input.length() < 2,
  1063. String(entry[idx] + "\nInvalid device mapping entry: " + entry[idx]));
  1064. if (output == "platform" || output == "hint") {
  1065. continue;
  1066. }
  1067. JoyAxisRange output_range = FULL_AXIS;
  1068. if (output[0] == '+' || output[0] == '-') {
  1069. ERR_CONTINUE_MSG(output.length() < 2, String(entry[idx] + "\nInvalid output: " + entry[idx]));
  1070. if (output[0] == '+') {
  1071. output_range = POSITIVE_HALF_AXIS;
  1072. } else if (output[0] == '-') {
  1073. output_range = NEGATIVE_HALF_AXIS;
  1074. }
  1075. output = output.substr(1);
  1076. }
  1077. JoyAxisRange input_range = FULL_AXIS;
  1078. if (input[0] == '+') {
  1079. input_range = POSITIVE_HALF_AXIS;
  1080. input = input.substr(1);
  1081. } else if (input[0] == '-') {
  1082. input_range = NEGATIVE_HALF_AXIS;
  1083. input = input.substr(1);
  1084. }
  1085. bool invert_axis = false;
  1086. if (input[input.length() - 1] == '~') {
  1087. invert_axis = true;
  1088. input = input.left(input.length() - 1);
  1089. }
  1090. JoyButton output_button = _get_output_button(output);
  1091. JoyAxis output_axis = _get_output_axis(output);
  1092. ERR_CONTINUE_MSG(output_button == JOY_BUTTON_INVALID && output_axis == JOY_AXIS_INVALID,
  1093. String(entry[idx] + "\nUnrecognised output string: " + output));
  1094. ERR_CONTINUE_MSG(output_button != JOY_BUTTON_INVALID && output_axis != JOY_AXIS_INVALID,
  1095. String("BUG: Output string matched both button and axis: " + output));
  1096. JoyBinding binding;
  1097. if (output_button != JOY_BUTTON_INVALID) {
  1098. binding.outputType = TYPE_BUTTON;
  1099. binding.output.button = output_button;
  1100. } else if (output_axis != JOY_AXIS_INVALID) {
  1101. binding.outputType = TYPE_AXIS;
  1102. binding.output.axis.axis = output_axis;
  1103. binding.output.axis.range = output_range;
  1104. }
  1105. switch (input[0]) {
  1106. case 'b':
  1107. binding.inputType = TYPE_BUTTON;
  1108. binding.input.button = (JoyButton)input.substr(1).to_int();
  1109. break;
  1110. case 'a':
  1111. binding.inputType = TYPE_AXIS;
  1112. binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
  1113. binding.input.axis.range = input_range;
  1114. binding.input.axis.invert = invert_axis;
  1115. break;
  1116. case 'h':
  1117. ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
  1118. String(entry[idx] + "\nInvalid hat input: " + input));
  1119. binding.inputType = TYPE_HAT;
  1120. binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
  1121. binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
  1122. break;
  1123. default:
  1124. ERR_CONTINUE_MSG(true, String(entry[idx] + "\nUnrecognised input string: " + input));
  1125. }
  1126. mapping.bindings.push_back(binding);
  1127. }
  1128. map_db.push_back(mapping);
  1129. }
  1130. void Input::add_joy_mapping(String p_mapping, bool p_update_existing) {
  1131. parse_mapping(p_mapping);
  1132. if (p_update_existing) {
  1133. Vector<String> entry = p_mapping.split(",");
  1134. String uid = entry[0];
  1135. for (Map<int, Joypad>::Element *E = joy_names.front(); E; E = E->next()) {
  1136. Joypad &joy = E->get();
  1137. if (joy.uid == uid) {
  1138. joy.mapping = map_db.size() - 1;
  1139. }
  1140. }
  1141. }
  1142. }
  1143. void Input::remove_joy_mapping(String p_guid) {
  1144. for (int i = map_db.size() - 1; i >= 0; i--) {
  1145. if (p_guid == map_db[i].uid) {
  1146. map_db.remove(i);
  1147. }
  1148. }
  1149. for (Map<int, Joypad>::Element *E = joy_names.front(); E; E = E->next()) {
  1150. Joypad &joy = E->get();
  1151. if (joy.uid == p_guid) {
  1152. joy.mapping = -1;
  1153. }
  1154. }
  1155. }
  1156. void Input::set_fallback_mapping(String p_guid) {
  1157. for (int i = 0; i < map_db.size(); i++) {
  1158. if (map_db[i].uid == p_guid) {
  1159. fallback_mapping = i;
  1160. return;
  1161. }
  1162. }
  1163. }
  1164. //platforms that use the remapping system can override and call to these ones
  1165. bool Input::is_joy_known(int p_device) {
  1166. if (joy_names.has(p_device)) {
  1167. int mapping = joy_names[p_device].mapping;
  1168. if (mapping != -1 && mapping != fallback_mapping) {
  1169. return true;
  1170. }
  1171. }
  1172. return false;
  1173. }
  1174. String Input::get_joy_guid(int p_device) const {
  1175. ERR_FAIL_COND_V(!joy_names.has(p_device), "");
  1176. return joy_names[p_device].uid;
  1177. }
  1178. Array Input::get_connected_joypads() {
  1179. Array ret;
  1180. Map<int, Joypad>::Element *elem = joy_names.front();
  1181. while (elem) {
  1182. if (elem->get().connected) {
  1183. ret.push_back(elem->key());
  1184. }
  1185. elem = elem->next();
  1186. }
  1187. return ret;
  1188. }
  1189. int Input::get_unused_joy_id() {
  1190. for (int i = 0; i < JOYPADS_MAX; i++) {
  1191. if (!joy_names.has(i) || !joy_names[i].connected) {
  1192. return i;
  1193. }
  1194. }
  1195. return -1;
  1196. }
  1197. Input::Input() {
  1198. singleton = this;
  1199. // Parse default mappings.
  1200. {
  1201. int i = 0;
  1202. while (DefaultControllerMappings::mappings[i]) {
  1203. parse_mapping(DefaultControllerMappings::mappings[i++]);
  1204. }
  1205. }
  1206. // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
  1207. String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
  1208. if (env_mapping != "") {
  1209. Vector<String> entries = env_mapping.split("\n");
  1210. for (int i = 0; i < entries.size(); i++) {
  1211. if (entries[i] == "") {
  1212. continue;
  1213. }
  1214. parse_mapping(entries[i]);
  1215. }
  1216. }
  1217. }
  1218. //////////////////////////////////////////////////////////