input.cpp 45 KB

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