input.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. /**************************************************************************/
  2. /* input.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 DEV_ENABLED
  36. #include "core/os/thread.h"
  37. #endif
  38. static const char *_joy_buttons[(size_t)JoyButton::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[(size_t)JoyAxis::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_position) = nullptr;
  73. Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
  74. void (*Input::set_custom_mouse_cursor_func)(const Ref<Resource> &, 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_anything_pressed"), &Input::is_anything_pressed);
  87. ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
  88. ClassDB::bind_method(D_METHOD("is_physical_key_pressed", "keycode"), &Input::is_physical_key_pressed);
  89. ClassDB::bind_method(D_METHOD("is_key_label_pressed", "keycode"), &Input::is_key_label_pressed);
  90. ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
  91. ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
  92. ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
  93. ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
  94. ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
  95. ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
  96. ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
  97. ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
  98. ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
  99. ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
  100. ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
  101. ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
  102. ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
  103. ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
  104. ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
  105. ClassDB::bind_method(D_METHOD("should_ignore_device", "vendor_id", "product_id"), &Input::should_ignore_device);
  106. ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
  107. ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
  108. ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
  109. ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
  110. ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
  111. ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms"), &Input::vibrate_handheld, DEFVAL(500));
  112. ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
  113. ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
  114. ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
  115. ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
  116. ClassDB::bind_method(D_METHOD("set_gravity", "value"), &Input::set_gravity);
  117. ClassDB::bind_method(D_METHOD("set_accelerometer", "value"), &Input::set_accelerometer);
  118. ClassDB::bind_method(D_METHOD("set_magnetometer", "value"), &Input::set_magnetometer);
  119. ClassDB::bind_method(D_METHOD("set_gyroscope", "value"), &Input::set_gyroscope);
  120. ClassDB::bind_method(D_METHOD("get_last_mouse_velocity"), &Input::get_last_mouse_velocity);
  121. ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
  122. ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
  123. ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
  124. ClassDB::bind_method(D_METHOD("warp_mouse", "position"), &Input::warp_mouse);
  125. ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
  126. ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
  127. ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
  128. ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
  129. ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
  130. ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
  131. ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
  132. ClassDB::bind_method(D_METHOD("is_using_accumulated_input"), &Input::is_using_accumulated_input);
  133. ClassDB::bind_method(D_METHOD("flush_buffered_events"), &Input::flush_buffered_events);
  134. ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_mode"), "set_mouse_mode", "get_mouse_mode");
  135. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_accumulated_input"), "set_use_accumulated_input", "is_using_accumulated_input");
  136. BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
  137. BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
  138. BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
  139. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
  140. BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
  141. BIND_ENUM_CONSTANT(CURSOR_ARROW);
  142. BIND_ENUM_CONSTANT(CURSOR_IBEAM);
  143. BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
  144. BIND_ENUM_CONSTANT(CURSOR_CROSS);
  145. BIND_ENUM_CONSTANT(CURSOR_WAIT);
  146. BIND_ENUM_CONSTANT(CURSOR_BUSY);
  147. BIND_ENUM_CONSTANT(CURSOR_DRAG);
  148. BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
  149. BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
  150. BIND_ENUM_CONSTANT(CURSOR_VSIZE);
  151. BIND_ENUM_CONSTANT(CURSOR_HSIZE);
  152. BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
  153. BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
  154. BIND_ENUM_CONSTANT(CURSOR_MOVE);
  155. BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
  156. BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
  157. BIND_ENUM_CONSTANT(CURSOR_HELP);
  158. ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
  159. }
  160. void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  161. String pf = p_function;
  162. if ((p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" || pf == "is_action_just_pressed" || pf == "is_action_just_released" || pf == "get_action_strength" || pf == "get_action_raw_strength")) ||
  163. (p_idx < 2 && pf == "get_axis") ||
  164. (p_idx < 4 && pf == "get_vector")) {
  165. List<PropertyInfo> pinfo;
  166. ProjectSettings::get_singleton()->get_property_list(&pinfo);
  167. for (const PropertyInfo &pi : pinfo) {
  168. if (!pi.name.begins_with("input/")) {
  169. continue;
  170. }
  171. String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
  172. r_options->push_back(name.quote());
  173. }
  174. }
  175. }
  176. void Input::VelocityTrack::update(const Vector2 &p_delta_p) {
  177. uint64_t tick = OS::get_singleton()->get_ticks_usec();
  178. uint32_t tdiff = tick - last_tick;
  179. float delta_t = tdiff / 1000000.0;
  180. last_tick = tick;
  181. if (delta_t > max_ref_frame) {
  182. // First movement in a long time, reset and start again.
  183. velocity = Vector2();
  184. accum = p_delta_p;
  185. accum_t = 0;
  186. return;
  187. }
  188. accum += p_delta_p;
  189. accum_t += delta_t;
  190. if (accum_t < min_ref_frame) {
  191. // Not enough time has passed to calculate speed precisely.
  192. return;
  193. }
  194. velocity = accum / accum_t;
  195. accum = Vector2();
  196. accum_t = 0;
  197. }
  198. void Input::VelocityTrack::reset() {
  199. last_tick = OS::get_singleton()->get_ticks_usec();
  200. velocity = Vector2();
  201. accum = Vector2();
  202. accum_t = 0;
  203. }
  204. Input::VelocityTrack::VelocityTrack() {
  205. min_ref_frame = 0.1;
  206. max_ref_frame = 3.0;
  207. reset();
  208. }
  209. bool Input::is_anything_pressed() const {
  210. _THREAD_SAFE_METHOD_
  211. if (!keys_pressed.is_empty() || !joy_buttons_pressed.is_empty() || !mouse_button_mask.is_empty()) {
  212. return true;
  213. }
  214. for (const KeyValue<StringName, Input::Action> &E : action_state) {
  215. if (E.value.pressed) {
  216. return true;
  217. }
  218. }
  219. return false;
  220. }
  221. bool Input::is_key_pressed(Key p_keycode) const {
  222. _THREAD_SAFE_METHOD_
  223. return keys_pressed.has(p_keycode);
  224. }
  225. bool Input::is_physical_key_pressed(Key p_keycode) const {
  226. _THREAD_SAFE_METHOD_
  227. return physical_keys_pressed.has(p_keycode);
  228. }
  229. bool Input::is_key_label_pressed(Key p_keycode) const {
  230. _THREAD_SAFE_METHOD_
  231. return key_label_pressed.has(p_keycode);
  232. }
  233. bool Input::is_mouse_button_pressed(MouseButton p_button) const {
  234. _THREAD_SAFE_METHOD_
  235. return mouse_button_mask.has_flag(mouse_button_to_mask(p_button));
  236. }
  237. static JoyAxis _combine_device(JoyAxis p_value, int p_device) {
  238. return JoyAxis((int)p_value | (p_device << 20));
  239. }
  240. static JoyButton _combine_device(JoyButton p_value, int p_device) {
  241. return JoyButton((int)p_value | (p_device << 20));
  242. }
  243. bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
  244. _THREAD_SAFE_METHOD_
  245. return joy_buttons_pressed.has(_combine_device(p_button, p_device));
  246. }
  247. bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
  248. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  249. return action_state.has(p_action) && action_state[p_action].pressed && (p_exact ? action_state[p_action].exact : true);
  250. }
  251. bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
  252. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  253. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  254. if (!E) {
  255. return false;
  256. }
  257. if (p_exact && E->value.exact == false) {
  258. return false;
  259. }
  260. // Backward compatibility for legacy behavior, only return true if currently pressed.
  261. bool pressed_requirement = legacy_just_pressed_behavior ? E->value.pressed : true;
  262. if (Engine::get_singleton()->is_in_physics_frame()) {
  263. return pressed_requirement && E->value.pressed_physics_frame == Engine::get_singleton()->get_physics_frames();
  264. } else {
  265. return pressed_requirement && E->value.pressed_process_frame == Engine::get_singleton()->get_process_frames();
  266. }
  267. }
  268. bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
  269. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
  270. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  271. if (!E) {
  272. return false;
  273. }
  274. if (p_exact && E->value.exact == false) {
  275. return false;
  276. }
  277. // Backward compatibility for legacy behavior, only return true if currently released.
  278. bool released_requirement = legacy_just_pressed_behavior ? !E->value.pressed : true;
  279. if (Engine::get_singleton()->is_in_physics_frame()) {
  280. return released_requirement && E->value.released_physics_frame == Engine::get_singleton()->get_physics_frames();
  281. } else {
  282. return released_requirement && E->value.released_process_frame == Engine::get_singleton()->get_process_frames();
  283. }
  284. }
  285. float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
  286. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  287. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  288. if (!E) {
  289. return 0.0f;
  290. }
  291. if (p_exact && E->value.exact == false) {
  292. return 0.0f;
  293. }
  294. return E->value.strength;
  295. }
  296. float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
  297. ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
  298. HashMap<StringName, Action>::ConstIterator E = action_state.find(p_action);
  299. if (!E) {
  300. return 0.0f;
  301. }
  302. if (p_exact && E->value.exact == false) {
  303. return 0.0f;
  304. }
  305. return E->value.raw_strength;
  306. }
  307. float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
  308. return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
  309. }
  310. 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 {
  311. Vector2 vector = Vector2(
  312. get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
  313. get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
  314. if (p_deadzone < 0.0f) {
  315. // If the deadzone isn't specified, get it from the average of the actions.
  316. p_deadzone = 0.25 *
  317. (InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
  318. InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
  319. InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
  320. InputMap::get_singleton()->action_get_deadzone(p_negative_y));
  321. }
  322. // Circular length limiting and deadzone.
  323. float length = vector.length();
  324. if (length <= p_deadzone) {
  325. return Vector2();
  326. } else if (length > 1.0f) {
  327. return vector / length;
  328. } else {
  329. // Inverse lerp length to map (p_deadzone, 1) to (0, 1).
  330. return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
  331. }
  332. }
  333. float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
  334. _THREAD_SAFE_METHOD_
  335. JoyAxis c = _combine_device(p_axis, p_device);
  336. if (_joy_axis.has(c)) {
  337. return _joy_axis[c];
  338. } else {
  339. return 0;
  340. }
  341. }
  342. String Input::get_joy_name(int p_idx) {
  343. _THREAD_SAFE_METHOD_
  344. return joy_names[p_idx].name;
  345. }
  346. Vector2 Input::get_joy_vibration_strength(int p_device) {
  347. if (joy_vibration.has(p_device)) {
  348. return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
  349. } else {
  350. return Vector2(0, 0);
  351. }
  352. }
  353. uint64_t Input::get_joy_vibration_timestamp(int p_device) {
  354. if (joy_vibration.has(p_device)) {
  355. return joy_vibration[p_device].timestamp;
  356. } else {
  357. return 0;
  358. }
  359. }
  360. float Input::get_joy_vibration_duration(int p_device) {
  361. if (joy_vibration.has(p_device)) {
  362. return joy_vibration[p_device].duration;
  363. } else {
  364. return 0.f;
  365. }
  366. }
  367. static String _hex_str(uint8_t p_byte) {
  368. static const char *dict = "0123456789abcdef";
  369. char ret[3];
  370. ret[2] = 0;
  371. ret[0] = dict[p_byte >> 4];
  372. ret[1] = dict[p_byte & 0xf];
  373. return ret;
  374. }
  375. void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) {
  376. _THREAD_SAFE_METHOD_
  377. Joypad js;
  378. js.name = p_connected ? p_name : "";
  379. js.uid = p_connected ? p_guid : "";
  380. if (p_connected) {
  381. String uidname = p_guid;
  382. if (p_guid.is_empty()) {
  383. int uidlen = MIN(p_name.length(), 16);
  384. for (int i = 0; i < uidlen; i++) {
  385. uidname = uidname + _hex_str(p_name[i]);
  386. }
  387. }
  388. js.uid = uidname;
  389. js.connected = true;
  390. int mapping = fallback_mapping;
  391. for (int i = 0; i < map_db.size(); i++) {
  392. if (js.uid == map_db[i].uid) {
  393. mapping = i;
  394. js.name = map_db[i].name;
  395. }
  396. }
  397. js.mapping = mapping;
  398. } else {
  399. js.connected = false;
  400. for (int i = 0; i < (int)JoyButton::MAX; i++) {
  401. JoyButton c = _combine_device((JoyButton)i, p_idx);
  402. joy_buttons_pressed.erase(c);
  403. }
  404. for (int i = 0; i < (int)JoyAxis::MAX; i++) {
  405. set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
  406. }
  407. }
  408. joy_names[p_idx] = js;
  409. // Ensure this signal is emitted on the main thread, as some platforms (e.g. Linux) call this from a different thread.
  410. call_deferred("emit_signal", SNAME("joy_connection_changed"), p_idx, p_connected);
  411. }
  412. Vector3 Input::get_gravity() const {
  413. _THREAD_SAFE_METHOD_
  414. return gravity;
  415. }
  416. Vector3 Input::get_accelerometer() const {
  417. _THREAD_SAFE_METHOD_
  418. return accelerometer;
  419. }
  420. Vector3 Input::get_magnetometer() const {
  421. _THREAD_SAFE_METHOD_
  422. return magnetometer;
  423. }
  424. Vector3 Input::get_gyroscope() const {
  425. _THREAD_SAFE_METHOD_
  426. return gyroscope;
  427. }
  428. void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
  429. // This function does the final delivery of the input event to user land.
  430. // Regardless where the event came from originally, this has to happen on the main thread.
  431. DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
  432. // Notes on mouse-touch emulation:
  433. // - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
  434. // as true mouse events. The only difference is the situation is flagged as emulated so they are not
  435. // emulated back to touch events in an endless loop.
  436. // - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
  437. // require additional handling by this class.
  438. Ref<InputEventKey> k = p_event;
  439. if (k.is_valid() && !k->is_echo() && k->get_keycode() != Key::NONE) {
  440. if (k->is_pressed()) {
  441. keys_pressed.insert(k->get_keycode());
  442. } else {
  443. keys_pressed.erase(k->get_keycode());
  444. }
  445. }
  446. if (k.is_valid() && !k->is_echo() && k->get_physical_keycode() != Key::NONE) {
  447. if (k->is_pressed()) {
  448. physical_keys_pressed.insert(k->get_physical_keycode());
  449. } else {
  450. physical_keys_pressed.erase(k->get_physical_keycode());
  451. }
  452. }
  453. if (k.is_valid() && !k->is_echo() && k->get_key_label() != Key::NONE) {
  454. if (k->is_pressed()) {
  455. key_label_pressed.insert(k->get_key_label());
  456. } else {
  457. key_label_pressed.erase(k->get_key_label());
  458. }
  459. }
  460. Ref<InputEventMouseButton> mb = p_event;
  461. if (mb.is_valid()) {
  462. if (mb->is_pressed()) {
  463. mouse_button_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
  464. } else {
  465. mouse_button_mask.clear_flag(mouse_button_to_mask(mb->get_button_index()));
  466. }
  467. Point2 pos = mb->get_global_position();
  468. if (mouse_pos != pos) {
  469. set_mouse_position(pos);
  470. }
  471. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == MouseButton::LEFT) {
  472. Ref<InputEventScreenTouch> touch_event;
  473. touch_event.instantiate();
  474. touch_event->set_pressed(mb->is_pressed());
  475. touch_event->set_canceled(mb->is_canceled());
  476. touch_event->set_position(mb->get_position());
  477. touch_event->set_double_tap(mb->is_double_click());
  478. touch_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  479. _THREAD_SAFE_UNLOCK_
  480. event_dispatch_function(touch_event);
  481. _THREAD_SAFE_LOCK_
  482. }
  483. }
  484. Ref<InputEventMouseMotion> mm = p_event;
  485. if (mm.is_valid()) {
  486. Point2 position = mm->get_global_position();
  487. if (mouse_pos != position) {
  488. set_mouse_position(position);
  489. }
  490. Vector2 relative = mm->get_relative();
  491. mouse_velocity_track.update(relative);
  492. if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mm->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
  493. Ref<InputEventScreenDrag> drag_event;
  494. drag_event.instantiate();
  495. drag_event->set_position(position);
  496. drag_event->set_relative(relative);
  497. drag_event->set_tilt(mm->get_tilt());
  498. drag_event->set_pen_inverted(mm->get_pen_inverted());
  499. drag_event->set_pressure(mm->get_pressure());
  500. drag_event->set_velocity(get_last_mouse_velocity());
  501. drag_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  502. _THREAD_SAFE_UNLOCK_
  503. event_dispatch_function(drag_event);
  504. _THREAD_SAFE_LOCK_
  505. }
  506. }
  507. Ref<InputEventScreenTouch> st = p_event;
  508. if (st.is_valid()) {
  509. if (st->is_pressed()) {
  510. VelocityTrack &track = touch_velocity_track[st->get_index()];
  511. track.reset();
  512. } else {
  513. // Since a pointer index may not occur again (OSs may or may not reuse them),
  514. // imperatively remove it from the map to keep no fossil entries in it
  515. touch_velocity_track.erase(st->get_index());
  516. }
  517. if (emulate_mouse_from_touch) {
  518. bool translate = false;
  519. if (st->is_pressed()) {
  520. if (mouse_from_touch_index == -1) {
  521. translate = true;
  522. mouse_from_touch_index = st->get_index();
  523. }
  524. } else {
  525. if (st->get_index() == mouse_from_touch_index) {
  526. translate = true;
  527. mouse_from_touch_index = -1;
  528. }
  529. }
  530. if (translate) {
  531. Ref<InputEventMouseButton> button_event;
  532. button_event.instantiate();
  533. button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  534. button_event->set_position(st->get_position());
  535. button_event->set_global_position(st->get_position());
  536. button_event->set_pressed(st->is_pressed());
  537. button_event->set_canceled(st->is_canceled());
  538. button_event->set_button_index(MouseButton::LEFT);
  539. button_event->set_double_click(st->is_double_tap());
  540. BitField<MouseButtonMask> ev_bm = mouse_button_mask;
  541. if (st->is_pressed()) {
  542. ev_bm.set_flag(MouseButtonMask::LEFT);
  543. } else {
  544. ev_bm.clear_flag(MouseButtonMask::LEFT);
  545. }
  546. button_event->set_button_mask(ev_bm);
  547. _parse_input_event_impl(button_event, true);
  548. }
  549. }
  550. }
  551. Ref<InputEventScreenDrag> sd = p_event;
  552. if (sd.is_valid()) {
  553. VelocityTrack &track = touch_velocity_track[sd->get_index()];
  554. track.update(sd->get_relative());
  555. sd->set_velocity(track.velocity);
  556. if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
  557. Ref<InputEventMouseMotion> motion_event;
  558. motion_event.instantiate();
  559. motion_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  560. motion_event->set_tilt(sd->get_tilt());
  561. motion_event->set_pen_inverted(sd->get_pen_inverted());
  562. motion_event->set_pressure(sd->get_pressure());
  563. motion_event->set_position(sd->get_position());
  564. motion_event->set_global_position(sd->get_position());
  565. motion_event->set_relative(sd->get_relative());
  566. motion_event->set_velocity(sd->get_velocity());
  567. motion_event->set_button_mask(mouse_button_mask);
  568. _parse_input_event_impl(motion_event, true);
  569. }
  570. }
  571. Ref<InputEventJoypadButton> jb = p_event;
  572. if (jb.is_valid()) {
  573. JoyButton c = _combine_device(jb->get_button_index(), jb->get_device());
  574. if (jb->is_pressed()) {
  575. joy_buttons_pressed.insert(c);
  576. } else {
  577. joy_buttons_pressed.erase(c);
  578. }
  579. }
  580. Ref<InputEventJoypadMotion> jm = p_event;
  581. if (jm.is_valid()) {
  582. set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
  583. }
  584. Ref<InputEventGesture> ge = p_event;
  585. if (ge.is_valid()) {
  586. if (event_dispatch_function) {
  587. _THREAD_SAFE_UNLOCK_
  588. event_dispatch_function(ge);
  589. _THREAD_SAFE_LOCK_
  590. }
  591. }
  592. for (const KeyValue<StringName, InputMap::Action> &E : InputMap::get_singleton()->get_action_map()) {
  593. if (InputMap::get_singleton()->event_is_action(p_event, E.key)) {
  594. Action &action = action_state[E.key];
  595. // If not echo and action pressed state has changed
  596. if (!p_event->is_echo() && is_action_pressed(E.key, false) != p_event->is_action_pressed(E.key)) {
  597. if (p_event->is_action_pressed(E.key)) {
  598. action.pressed = true;
  599. action.pressed_physics_frame = Engine::get_singleton()->get_physics_frames();
  600. action.pressed_process_frame = Engine::get_singleton()->get_process_frames();
  601. } else {
  602. action.pressed = false;
  603. action.released_physics_frame = Engine::get_singleton()->get_physics_frames();
  604. action.released_process_frame = Engine::get_singleton()->get_process_frames();
  605. }
  606. action.strength = 0.0f;
  607. action.raw_strength = 0.0f;
  608. action.exact = InputMap::get_singleton()->event_is_action(p_event, E.key, true);
  609. }
  610. action.strength = p_event->get_action_strength(E.key);
  611. action.raw_strength = p_event->get_action_raw_strength(E.key);
  612. }
  613. }
  614. if (event_dispatch_function) {
  615. _THREAD_SAFE_UNLOCK_
  616. event_dispatch_function(p_event);
  617. _THREAD_SAFE_LOCK_
  618. }
  619. }
  620. void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  621. _THREAD_SAFE_METHOD_
  622. JoyAxis c = _combine_device(p_axis, p_device);
  623. _joy_axis[c] = p_value;
  624. }
  625. void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
  626. _THREAD_SAFE_METHOD_
  627. if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  628. return;
  629. }
  630. VibrationInfo vibration;
  631. vibration.weak_magnitude = p_weak_magnitude;
  632. vibration.strong_magnitude = p_strong_magnitude;
  633. vibration.duration = p_duration;
  634. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  635. joy_vibration[p_device] = vibration;
  636. }
  637. void Input::stop_joy_vibration(int p_device) {
  638. _THREAD_SAFE_METHOD_
  639. VibrationInfo vibration;
  640. vibration.weak_magnitude = 0;
  641. vibration.strong_magnitude = 0;
  642. vibration.duration = 0;
  643. vibration.timestamp = OS::get_singleton()->get_ticks_usec();
  644. joy_vibration[p_device] = vibration;
  645. }
  646. void Input::vibrate_handheld(int p_duration_ms) {
  647. OS::get_singleton()->vibrate_handheld(p_duration_ms);
  648. }
  649. void Input::set_gravity(const Vector3 &p_gravity) {
  650. _THREAD_SAFE_METHOD_
  651. gravity = p_gravity;
  652. }
  653. void Input::set_accelerometer(const Vector3 &p_accel) {
  654. _THREAD_SAFE_METHOD_
  655. accelerometer = p_accel;
  656. }
  657. void Input::set_magnetometer(const Vector3 &p_magnetometer) {
  658. _THREAD_SAFE_METHOD_
  659. magnetometer = p_magnetometer;
  660. }
  661. void Input::set_gyroscope(const Vector3 &p_gyroscope) {
  662. _THREAD_SAFE_METHOD_
  663. gyroscope = p_gyroscope;
  664. }
  665. void Input::set_mouse_position(const Point2 &p_posf) {
  666. mouse_pos = p_posf;
  667. }
  668. Point2 Input::get_mouse_position() const {
  669. return mouse_pos;
  670. }
  671. Point2 Input::get_last_mouse_velocity() {
  672. mouse_velocity_track.update(Vector2());
  673. return mouse_velocity_track.velocity;
  674. }
  675. BitField<MouseButtonMask> Input::get_mouse_button_mask() const {
  676. return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
  677. }
  678. void Input::warp_mouse(const Vector2 &p_position) {
  679. warp_mouse_func(p_position);
  680. }
  681. Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
  682. // The relative distance reported for the next event after a warp is in the boundaries of the
  683. // size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
  684. // will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
  685. // and the subsequent event, the reported relative distance will be less than the size of the rect
  686. // and thus fmod() will be disabled for handling the situation.
  687. // And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
  688. // detect the warp: if the relative distance is greater than the half of the size of the relevant rect
  689. // (checked per each axis), it will be considered as the consequence of a former pointer warp.
  690. const Point2i rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
  691. const Size2i warp_margin = p_rect.size * 0.5f;
  692. const Point2i rel_warped(
  693. Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
  694. Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
  695. const Point2i pos_local = p_motion->get_global_position() - p_rect.position;
  696. const Point2i pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
  697. if (pos_warped != pos_local) {
  698. warp_mouse(pos_warped + p_rect.position);
  699. }
  700. return rel_warped;
  701. }
  702. void Input::action_press(const StringName &p_action, float p_strength) {
  703. // Create or retrieve existing action.
  704. Action &action = action_state[p_action];
  705. action.pressed_physics_frame = Engine::get_singleton()->get_physics_frames();
  706. action.pressed_process_frame = Engine::get_singleton()->get_process_frames();
  707. action.pressed = true;
  708. action.strength = p_strength;
  709. action.raw_strength = p_strength;
  710. action.exact = true;
  711. }
  712. void Input::action_release(const StringName &p_action) {
  713. // Create or retrieve existing action.
  714. Action &action = action_state[p_action];
  715. action.released_physics_frame = Engine::get_singleton()->get_physics_frames();
  716. action.released_process_frame = Engine::get_singleton()->get_process_frames();
  717. action.pressed = false;
  718. action.strength = 0.0f;
  719. action.raw_strength = 0.0f;
  720. action.exact = true;
  721. }
  722. void Input::set_emulate_touch_from_mouse(bool p_emulate) {
  723. emulate_touch_from_mouse = p_emulate;
  724. }
  725. bool Input::is_emulating_touch_from_mouse() const {
  726. return emulate_touch_from_mouse;
  727. }
  728. // Calling this whenever the game window is focused helps unsticking the "touch mouse"
  729. // if the OS or its abstraction class hasn't properly reported that touch pointers raised
  730. void Input::ensure_touch_mouse_raised() {
  731. _THREAD_SAFE_METHOD_
  732. if (mouse_from_touch_index != -1) {
  733. mouse_from_touch_index = -1;
  734. Ref<InputEventMouseButton> button_event;
  735. button_event.instantiate();
  736. button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
  737. button_event->set_position(mouse_pos);
  738. button_event->set_global_position(mouse_pos);
  739. button_event->set_pressed(false);
  740. button_event->set_button_index(MouseButton::LEFT);
  741. BitField<MouseButtonMask> ev_bm = mouse_button_mask;
  742. ev_bm.clear_flag(MouseButtonMask::LEFT);
  743. button_event->set_button_mask(ev_bm);
  744. _parse_input_event_impl(button_event, true);
  745. }
  746. }
  747. void Input::set_emulate_mouse_from_touch(bool p_emulate) {
  748. emulate_mouse_from_touch = p_emulate;
  749. }
  750. bool Input::is_emulating_mouse_from_touch() const {
  751. return emulate_mouse_from_touch;
  752. }
  753. Input::CursorShape Input::get_default_cursor_shape() const {
  754. return default_shape;
  755. }
  756. void Input::set_default_cursor_shape(CursorShape p_shape) {
  757. if (default_shape == p_shape) {
  758. return;
  759. }
  760. default_shape = p_shape;
  761. // The default shape is set in Viewport::_gui_input_event. To instantly
  762. // see the shape in the viewport we need to trigger a mouse motion event.
  763. Ref<InputEventMouseMotion> mm;
  764. mm.instantiate();
  765. mm->set_position(mouse_pos);
  766. mm->set_global_position(mouse_pos);
  767. mm->set_device(InputEvent::DEVICE_ID_INTERNAL);
  768. parse_input_event(mm);
  769. }
  770. Input::CursorShape Input::get_current_cursor_shape() const {
  771. return get_current_cursor_shape_func();
  772. }
  773. void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  774. if (Engine::get_singleton()->is_editor_hint()) {
  775. return;
  776. }
  777. ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
  778. set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
  779. }
  780. void Input::parse_input_event(const Ref<InputEvent> &p_event) {
  781. _THREAD_SAFE_METHOD_
  782. ERR_FAIL_COND(p_event.is_null());
  783. #ifdef DEBUG_ENABLED
  784. uint64_t curr_frame = Engine::get_singleton()->get_process_frames();
  785. if (curr_frame != last_parsed_frame) {
  786. frame_parsed_events.clear();
  787. last_parsed_frame = curr_frame;
  788. frame_parsed_events.insert(p_event);
  789. } else if (frame_parsed_events.has(p_event)) {
  790. // It would be technically safe to send the same event in cases such as:
  791. // - After an explicit flush.
  792. // - In platforms using buffering when agile flushing is enabled, after one of the mid-frame flushes.
  793. // - If platform doesn't use buffering and event accumulation is disabled.
  794. // - If platform doesn't use buffering and the event type is not accumulable.
  795. // However, it wouldn't be reasonable to ask users to remember the full ruleset and be aware at all times
  796. // of the possibilities of the target platform, project settings and engine internals, which may change
  797. // without prior notice.
  798. // Therefore, the guideline is, "don't send the same event object more than once per frame".
  799. WARN_PRINT_ONCE(
  800. "An input event object is being parsed more than once in the same frame, which is unsafe.\n"
  801. "If you are generating events in a script, you have to instantiate a new event instead of sending the same one more than once, unless the original one was sent on an earlier frame.\n"
  802. "You can call duplicate() on the event to get a new instance with identical values.");
  803. } else {
  804. frame_parsed_events.insert(p_event);
  805. }
  806. #endif
  807. if (use_accumulated_input) {
  808. if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
  809. buffered_events.push_back(p_event);
  810. }
  811. } else if (use_input_buffering) {
  812. buffered_events.push_back(p_event);
  813. } else {
  814. _parse_input_event_impl(p_event, false);
  815. }
  816. }
  817. void Input::flush_buffered_events() {
  818. _THREAD_SAFE_METHOD_
  819. while (buffered_events.front()) {
  820. // The final delivery of the input event involves releasing the lock.
  821. // While the lock is released, another thread may lock it and add new events to the back.
  822. // Therefore, we get each event and pop it while we still have the lock,
  823. // to ensure the list is in a consistent state.
  824. List<Ref<InputEvent>>::Element *E = buffered_events.front();
  825. Ref<InputEvent> e = E->get();
  826. buffered_events.pop_front();
  827. _parse_input_event_impl(e, false);
  828. }
  829. }
  830. bool Input::is_using_input_buffering() {
  831. return use_input_buffering;
  832. }
  833. void Input::set_use_input_buffering(bool p_enable) {
  834. use_input_buffering = p_enable;
  835. }
  836. void Input::set_use_accumulated_input(bool p_enable) {
  837. use_accumulated_input = p_enable;
  838. }
  839. bool Input::is_using_accumulated_input() {
  840. return use_accumulated_input;
  841. }
  842. void Input::release_pressed_events() {
  843. flush_buffered_events(); // this is needed to release actions strengths
  844. keys_pressed.clear();
  845. physical_keys_pressed.clear();
  846. key_label_pressed.clear();
  847. joy_buttons_pressed.clear();
  848. _joy_axis.clear();
  849. for (const KeyValue<StringName, Input::Action> &E : action_state) {
  850. if (E.value.pressed) {
  851. action_release(E.key);
  852. }
  853. }
  854. }
  855. void Input::set_event_dispatch_function(EventDispatchFunc p_function) {
  856. event_dispatch_function = p_function;
  857. }
  858. void Input::joy_button(int p_device, JoyButton p_button, bool p_pressed) {
  859. _THREAD_SAFE_METHOD_;
  860. Joypad &joy = joy_names[p_device];
  861. ERR_FAIL_INDEX((int)p_button, (int)JoyButton::MAX);
  862. if (joy.last_buttons[(size_t)p_button] == p_pressed) {
  863. return;
  864. }
  865. joy.last_buttons[(size_t)p_button] = p_pressed;
  866. if (joy.mapping == -1) {
  867. _button_event(p_device, p_button, p_pressed);
  868. return;
  869. }
  870. JoyEvent map = _get_mapped_button_event(map_db[joy.mapping], p_button);
  871. if (map.type == TYPE_BUTTON) {
  872. _button_event(p_device, (JoyButton)map.index, p_pressed);
  873. return;
  874. }
  875. if (map.type == TYPE_AXIS) {
  876. _axis_event(p_device, (JoyAxis)map.index, p_pressed ? map.value : 0.0);
  877. }
  878. // no event?
  879. }
  880. void Input::joy_axis(int p_device, JoyAxis p_axis, float p_value) {
  881. _THREAD_SAFE_METHOD_;
  882. ERR_FAIL_INDEX((int)p_axis, (int)JoyAxis::MAX);
  883. Joypad &joy = joy_names[p_device];
  884. if (joy.last_axis[(size_t)p_axis] == p_value) {
  885. return;
  886. }
  887. joy.last_axis[(size_t)p_axis] = p_value;
  888. if (joy.mapping == -1) {
  889. _axis_event(p_device, p_axis, p_value);
  890. return;
  891. }
  892. JoyAxisRange range;
  893. JoyEvent map = _get_mapped_axis_event(map_db[joy.mapping], p_axis, p_value, range);
  894. if (map.type == TYPE_BUTTON) {
  895. bool pressed = map.value > 0.5;
  896. if (pressed != joy_buttons_pressed.has(_combine_device((JoyButton)map.index, p_device))) {
  897. _button_event(p_device, (JoyButton)map.index, pressed);
  898. }
  899. // Ensure opposite D-Pad button is also released.
  900. switch ((JoyButton)map.index) {
  901. case JoyButton::DPAD_UP:
  902. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_DOWN, p_device))) {
  903. _button_event(p_device, JoyButton::DPAD_DOWN, false);
  904. }
  905. break;
  906. case JoyButton::DPAD_DOWN:
  907. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_UP, p_device))) {
  908. _button_event(p_device, JoyButton::DPAD_UP, false);
  909. }
  910. break;
  911. case JoyButton::DPAD_LEFT:
  912. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_RIGHT, p_device))) {
  913. _button_event(p_device, JoyButton::DPAD_RIGHT, false);
  914. }
  915. break;
  916. case JoyButton::DPAD_RIGHT:
  917. if (joy_buttons_pressed.has(_combine_device(JoyButton::DPAD_LEFT, p_device))) {
  918. _button_event(p_device, JoyButton::DPAD_LEFT, false);
  919. }
  920. break;
  921. default:
  922. // Nothing to do.
  923. break;
  924. }
  925. return;
  926. }
  927. if (map.type == TYPE_AXIS) {
  928. JoyAxis axis = JoyAxis(map.index);
  929. float value = map.value;
  930. if (range == FULL_AXIS && (axis == JoyAxis::TRIGGER_LEFT || axis == JoyAxis::TRIGGER_RIGHT)) {
  931. // Convert to a value between 0.0f and 1.0f.
  932. value = 0.5f + value / 2.0f;
  933. }
  934. _axis_event(p_device, axis, value);
  935. return;
  936. }
  937. }
  938. void Input::joy_hat(int p_device, BitField<HatMask> p_val) {
  939. _THREAD_SAFE_METHOD_;
  940. const Joypad &joy = joy_names[p_device];
  941. JoyEvent map[(size_t)HatDir::MAX];
  942. map[(size_t)HatDir::UP].type = TYPE_BUTTON;
  943. map[(size_t)HatDir::UP].index = (int)JoyButton::DPAD_UP;
  944. map[(size_t)HatDir::UP].value = 0;
  945. map[(size_t)HatDir::RIGHT].type = TYPE_BUTTON;
  946. map[(size_t)HatDir::RIGHT].index = (int)JoyButton::DPAD_RIGHT;
  947. map[(size_t)HatDir::RIGHT].value = 0;
  948. map[(size_t)HatDir::DOWN].type = TYPE_BUTTON;
  949. map[(size_t)HatDir::DOWN].index = (int)JoyButton::DPAD_DOWN;
  950. map[(size_t)HatDir::DOWN].value = 0;
  951. map[(size_t)HatDir::LEFT].type = TYPE_BUTTON;
  952. map[(size_t)HatDir::LEFT].index = (int)JoyButton::DPAD_LEFT;
  953. map[(size_t)HatDir::LEFT].value = 0;
  954. if (joy.mapping != -1) {
  955. _get_mapped_hat_events(map_db[joy.mapping], (HatDir)0, map);
  956. }
  957. int cur_val = joy_names[p_device].hat_current;
  958. for (int hat_direction = 0, hat_mask = 1; hat_direction < (int)HatDir::MAX; hat_direction++, hat_mask <<= 1) {
  959. if (((int)p_val & hat_mask) != (cur_val & hat_mask)) {
  960. if (map[hat_direction].type == TYPE_BUTTON) {
  961. _button_event(p_device, (JoyButton)map[hat_direction].index, (int)p_val & hat_mask);
  962. }
  963. if (map[hat_direction].type == TYPE_AXIS) {
  964. _axis_event(p_device, (JoyAxis)map[hat_direction].index, ((int)p_val & hat_mask) ? map[hat_direction].value : 0.0);
  965. }
  966. }
  967. }
  968. joy_names[p_device].hat_current = (int)p_val;
  969. }
  970. void Input::_button_event(int p_device, JoyButton p_index, bool p_pressed) {
  971. Ref<InputEventJoypadButton> ievent;
  972. ievent.instantiate();
  973. ievent->set_device(p_device);
  974. ievent->set_button_index(p_index);
  975. ievent->set_pressed(p_pressed);
  976. parse_input_event(ievent);
  977. }
  978. void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) {
  979. Ref<InputEventJoypadMotion> ievent;
  980. ievent.instantiate();
  981. ievent->set_device(p_device);
  982. ievent->set_axis(p_axis);
  983. ievent->set_axis_value(p_value);
  984. parse_input_event(ievent);
  985. }
  986. Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) {
  987. JoyEvent event;
  988. for (int i = 0; i < mapping.bindings.size(); i++) {
  989. const JoyBinding binding = mapping.bindings[i];
  990. if (binding.inputType == TYPE_BUTTON && binding.input.button == p_button) {
  991. event.type = binding.outputType;
  992. switch (binding.outputType) {
  993. case TYPE_BUTTON:
  994. event.index = (int)binding.output.button;
  995. return event;
  996. case TYPE_AXIS:
  997. event.index = (int)binding.output.axis.axis;
  998. switch (binding.output.axis.range) {
  999. case POSITIVE_HALF_AXIS:
  1000. event.value = 1;
  1001. break;
  1002. case NEGATIVE_HALF_AXIS:
  1003. event.value = -1;
  1004. break;
  1005. case FULL_AXIS:
  1006. // It doesn't make sense for a button to map to a full axis,
  1007. // but keeping as a default for a trigger with a positive half-axis.
  1008. event.value = 1;
  1009. break;
  1010. }
  1011. return event;
  1012. default:
  1013. ERR_PRINT_ONCE("Joypad button mapping error.");
  1014. }
  1015. }
  1016. }
  1017. return event;
  1018. }
  1019. Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value, JoyAxisRange &r_range) {
  1020. JoyEvent event;
  1021. for (int i = 0; i < mapping.bindings.size(); i++) {
  1022. const JoyBinding binding = mapping.bindings[i];
  1023. if (binding.inputType == TYPE_AXIS && binding.input.axis.axis == p_axis) {
  1024. float value = p_value;
  1025. if (binding.input.axis.invert) {
  1026. value = -value;
  1027. }
  1028. if (binding.input.axis.range == FULL_AXIS ||
  1029. (binding.input.axis.range == POSITIVE_HALF_AXIS && value >= 0) ||
  1030. (binding.input.axis.range == NEGATIVE_HALF_AXIS && value < 0)) {
  1031. event.type = binding.outputType;
  1032. float shifted_positive_value = 0;
  1033. switch (binding.input.axis.range) {
  1034. case POSITIVE_HALF_AXIS:
  1035. shifted_positive_value = value;
  1036. break;
  1037. case NEGATIVE_HALF_AXIS:
  1038. shifted_positive_value = value + 1;
  1039. break;
  1040. case FULL_AXIS:
  1041. shifted_positive_value = (value + 1) / 2;
  1042. break;
  1043. }
  1044. switch (binding.outputType) {
  1045. case TYPE_BUTTON:
  1046. event.index = (int)binding.output.button;
  1047. switch (binding.input.axis.range) {
  1048. case POSITIVE_HALF_AXIS:
  1049. event.value = shifted_positive_value;
  1050. break;
  1051. case NEGATIVE_HALF_AXIS:
  1052. event.value = 1 - shifted_positive_value;
  1053. break;
  1054. case FULL_AXIS:
  1055. // It doesn't make sense for a full axis to map to a button,
  1056. // but keeping as a default for a trigger with a positive half-axis.
  1057. event.value = (shifted_positive_value * 2) - 1;
  1058. break;
  1059. }
  1060. return event;
  1061. case TYPE_AXIS:
  1062. event.index = (int)binding.output.axis.axis;
  1063. event.value = value;
  1064. r_range = binding.output.axis.range;
  1065. if (binding.output.axis.range != binding.input.axis.range) {
  1066. switch (binding.output.axis.range) {
  1067. case POSITIVE_HALF_AXIS:
  1068. event.value = shifted_positive_value;
  1069. break;
  1070. case NEGATIVE_HALF_AXIS:
  1071. event.value = shifted_positive_value - 1;
  1072. break;
  1073. case FULL_AXIS:
  1074. event.value = (shifted_positive_value * 2) - 1;
  1075. break;
  1076. }
  1077. }
  1078. return event;
  1079. default:
  1080. ERR_PRINT_ONCE("Joypad axis mapping error.");
  1081. }
  1082. }
  1083. }
  1084. }
  1085. return event;
  1086. }
  1087. void Input::_get_mapped_hat_events(const JoyDeviceMapping &mapping, HatDir p_hat, JoyEvent r_events[(size_t)HatDir::MAX]) {
  1088. for (int i = 0; i < mapping.bindings.size(); i++) {
  1089. const JoyBinding binding = mapping.bindings[i];
  1090. if (binding.inputType == TYPE_HAT && binding.input.hat.hat == p_hat) {
  1091. HatDir hat_direction;
  1092. switch (binding.input.hat.hat_mask) {
  1093. case HatMask::UP:
  1094. hat_direction = HatDir::UP;
  1095. break;
  1096. case HatMask::RIGHT:
  1097. hat_direction = HatDir::RIGHT;
  1098. break;
  1099. case HatMask::DOWN:
  1100. hat_direction = HatDir::DOWN;
  1101. break;
  1102. case HatMask::LEFT:
  1103. hat_direction = HatDir::LEFT;
  1104. break;
  1105. default:
  1106. ERR_PRINT_ONCE("Joypad button mapping error.");
  1107. continue;
  1108. }
  1109. r_events[(size_t)hat_direction].type = binding.outputType;
  1110. switch (binding.outputType) {
  1111. case TYPE_BUTTON:
  1112. r_events[(size_t)hat_direction].index = (int)binding.output.button;
  1113. break;
  1114. case TYPE_AXIS:
  1115. r_events[(size_t)hat_direction].index = (int)binding.output.axis.axis;
  1116. switch (binding.output.axis.range) {
  1117. case POSITIVE_HALF_AXIS:
  1118. r_events[(size_t)hat_direction].value = 1;
  1119. break;
  1120. case NEGATIVE_HALF_AXIS:
  1121. r_events[(size_t)hat_direction].value = -1;
  1122. break;
  1123. case FULL_AXIS:
  1124. // It doesn't make sense for a hat direction to map to a full axis,
  1125. // but keeping as a default for a trigger with a positive half-axis.
  1126. r_events[(size_t)hat_direction].value = 1;
  1127. break;
  1128. }
  1129. break;
  1130. default:
  1131. ERR_PRINT_ONCE("Joypad button mapping error.");
  1132. }
  1133. }
  1134. }
  1135. }
  1136. JoyButton Input::_get_output_button(String output) {
  1137. for (int i = 0; i < (int)JoyButton::SDL_MAX; i++) {
  1138. if (output == _joy_buttons[i]) {
  1139. return JoyButton(i);
  1140. }
  1141. }
  1142. return JoyButton::INVALID;
  1143. }
  1144. JoyAxis Input::_get_output_axis(String output) {
  1145. for (int i = 0; i < (int)JoyAxis::SDL_MAX; i++) {
  1146. if (output == _joy_axes[i]) {
  1147. return JoyAxis(i);
  1148. }
  1149. }
  1150. return JoyAxis::INVALID;
  1151. }
  1152. void Input::parse_mapping(String p_mapping) {
  1153. _THREAD_SAFE_METHOD_;
  1154. JoyDeviceMapping mapping;
  1155. Vector<String> entry = p_mapping.split(",");
  1156. if (entry.size() < 2) {
  1157. return;
  1158. }
  1159. CharString uid;
  1160. uid.resize(17);
  1161. mapping.uid = entry[0];
  1162. mapping.name = entry[1];
  1163. int idx = 1;
  1164. while (++idx < entry.size()) {
  1165. if (entry[idx].is_empty()) {
  1166. continue;
  1167. }
  1168. String output = entry[idx].get_slice(":", 0).replace(" ", "");
  1169. String input = entry[idx].get_slice(":", 1).replace(" ", "");
  1170. if (output.length() < 1 || input.length() < 2) {
  1171. continue;
  1172. }
  1173. if (output == "platform" || output == "hint") {
  1174. continue;
  1175. }
  1176. JoyAxisRange output_range = FULL_AXIS;
  1177. if (output[0] == '+' || output[0] == '-') {
  1178. ERR_CONTINUE_MSG(output.length() < 2,
  1179. vformat("Invalid output entry \"%s\" in mapping:\n%s", entry[idx], p_mapping));
  1180. if (output[0] == '+') {
  1181. output_range = POSITIVE_HALF_AXIS;
  1182. } else if (output[0] == '-') {
  1183. output_range = NEGATIVE_HALF_AXIS;
  1184. }
  1185. output = output.substr(1);
  1186. }
  1187. JoyAxisRange input_range = FULL_AXIS;
  1188. if (input[0] == '+') {
  1189. input_range = POSITIVE_HALF_AXIS;
  1190. input = input.substr(1);
  1191. } else if (input[0] == '-') {
  1192. input_range = NEGATIVE_HALF_AXIS;
  1193. input = input.substr(1);
  1194. }
  1195. bool invert_axis = false;
  1196. if (input[input.length() - 1] == '~') {
  1197. invert_axis = true;
  1198. input = input.left(input.length() - 1);
  1199. }
  1200. JoyButton output_button = _get_output_button(output);
  1201. JoyAxis output_axis = _get_output_axis(output);
  1202. if (output_button == JoyButton::INVALID && output_axis == JoyAxis::INVALID) {
  1203. print_verbose(vformat("Unrecognized output string \"%s\" in mapping:\n%s", output, p_mapping));
  1204. }
  1205. ERR_CONTINUE_MSG(output_button != JoyButton::INVALID && output_axis != JoyAxis::INVALID,
  1206. vformat("Output string \"%s\" matched both button and axis in mapping:\n%s", output, p_mapping));
  1207. JoyBinding binding;
  1208. if (output_button != JoyButton::INVALID) {
  1209. binding.outputType = TYPE_BUTTON;
  1210. binding.output.button = output_button;
  1211. } else if (output_axis != JoyAxis::INVALID) {
  1212. binding.outputType = TYPE_AXIS;
  1213. binding.output.axis.axis = output_axis;
  1214. binding.output.axis.range = output_range;
  1215. }
  1216. switch (input[0]) {
  1217. case 'b':
  1218. binding.inputType = TYPE_BUTTON;
  1219. binding.input.button = (JoyButton)input.substr(1).to_int();
  1220. break;
  1221. case 'a':
  1222. binding.inputType = TYPE_AXIS;
  1223. binding.input.axis.axis = (JoyAxis)input.substr(1).to_int();
  1224. binding.input.axis.range = input_range;
  1225. binding.input.axis.invert = invert_axis;
  1226. break;
  1227. case 'h':
  1228. ERR_CONTINUE_MSG(input.length() != 4 || input[2] != '.',
  1229. vformat("Invalid had input \"%s\" in mapping:\n%s", input, p_mapping));
  1230. binding.inputType = TYPE_HAT;
  1231. binding.input.hat.hat = (HatDir)input.substr(1, 1).to_int();
  1232. binding.input.hat.hat_mask = static_cast<HatMask>(input.substr(3).to_int());
  1233. break;
  1234. default:
  1235. ERR_CONTINUE_MSG(true, vformat("Unrecognized input string \"%s\" in mapping:\n%s", input, p_mapping));
  1236. }
  1237. mapping.bindings.push_back(binding);
  1238. }
  1239. map_db.push_back(mapping);
  1240. }
  1241. void Input::add_joy_mapping(String p_mapping, bool p_update_existing) {
  1242. parse_mapping(p_mapping);
  1243. if (p_update_existing) {
  1244. Vector<String> entry = p_mapping.split(",");
  1245. String uid = entry[0];
  1246. for (KeyValue<int, Joypad> &E : joy_names) {
  1247. Joypad &joy = E.value;
  1248. if (joy.uid == uid) {
  1249. joy.mapping = map_db.size() - 1;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. void Input::remove_joy_mapping(String p_guid) {
  1255. for (int i = map_db.size() - 1; i >= 0; i--) {
  1256. if (p_guid == map_db[i].uid) {
  1257. map_db.remove_at(i);
  1258. }
  1259. }
  1260. for (KeyValue<int, Joypad> &E : joy_names) {
  1261. Joypad &joy = E.value;
  1262. if (joy.uid == p_guid) {
  1263. joy.mapping = -1;
  1264. }
  1265. }
  1266. }
  1267. void Input::set_fallback_mapping(String p_guid) {
  1268. for (int i = 0; i < map_db.size(); i++) {
  1269. if (map_db[i].uid == p_guid) {
  1270. fallback_mapping = i;
  1271. return;
  1272. }
  1273. }
  1274. }
  1275. //platforms that use the remapping system can override and call to these ones
  1276. bool Input::is_joy_known(int p_device) {
  1277. if (joy_names.has(p_device)) {
  1278. int mapping = joy_names[p_device].mapping;
  1279. if (mapping != -1 && mapping != fallback_mapping) {
  1280. return true;
  1281. }
  1282. }
  1283. return false;
  1284. }
  1285. String Input::get_joy_guid(int p_device) const {
  1286. ERR_FAIL_COND_V(!joy_names.has(p_device), "");
  1287. return joy_names[p_device].uid;
  1288. }
  1289. bool Input::should_ignore_device(int p_vendor_id, int p_product_id) const {
  1290. uint32_t full_id = (((uint32_t)p_vendor_id) << 16) | ((uint16_t)p_product_id);
  1291. return ignored_device_ids.has(full_id);
  1292. }
  1293. TypedArray<int> Input::get_connected_joypads() {
  1294. TypedArray<int> ret;
  1295. HashMap<int, Joypad>::Iterator elem = joy_names.begin();
  1296. while (elem) {
  1297. if (elem->value.connected) {
  1298. ret.push_back(elem->key);
  1299. }
  1300. ++elem;
  1301. }
  1302. return ret;
  1303. }
  1304. int Input::get_unused_joy_id() {
  1305. for (int i = 0; i < JOYPADS_MAX; i++) {
  1306. if (!joy_names.has(i) || !joy_names[i].connected) {
  1307. return i;
  1308. }
  1309. }
  1310. return -1;
  1311. }
  1312. Input::Input() {
  1313. singleton = this;
  1314. // Parse default mappings.
  1315. {
  1316. int i = 0;
  1317. while (DefaultControllerMappings::mappings[i]) {
  1318. parse_mapping(DefaultControllerMappings::mappings[i++]);
  1319. }
  1320. }
  1321. // If defined, parse SDL_GAMECONTROLLERCONFIG for possible new mappings/overrides.
  1322. String env_mapping = OS::get_singleton()->get_environment("SDL_GAMECONTROLLERCONFIG");
  1323. if (!env_mapping.is_empty()) {
  1324. Vector<String> entries = env_mapping.split("\n");
  1325. for (int i = 0; i < entries.size(); i++) {
  1326. if (entries[i].is_empty()) {
  1327. continue;
  1328. }
  1329. parse_mapping(entries[i]);
  1330. }
  1331. }
  1332. String env_ignore_devices = OS::get_singleton()->get_environment("SDL_GAMECONTROLLER_IGNORE_DEVICES");
  1333. if (!env_ignore_devices.is_empty()) {
  1334. Vector<String> entries = env_ignore_devices.split(",");
  1335. for (int i = 0; i < entries.size(); i++) {
  1336. Vector<String> vid_pid = entries[i].split("/");
  1337. if (vid_pid.size() < 2) {
  1338. continue;
  1339. }
  1340. print_verbose(vformat("Device Ignored -- Vendor: %s Product: %s", vid_pid[0], vid_pid[1]));
  1341. const uint16_t vid_unswapped = vid_pid[0].hex_to_int();
  1342. const uint16_t pid_unswapped = vid_pid[1].hex_to_int();
  1343. const uint16_t vid = BSWAP16(vid_unswapped);
  1344. const uint16_t pid = BSWAP16(pid_unswapped);
  1345. uint32_t full_id = (((uint32_t)vid) << 16) | ((uint16_t)pid);
  1346. ignored_device_ids.insert(full_id);
  1347. }
  1348. }
  1349. legacy_just_pressed_behavior = GLOBAL_DEF("input_devices/compatibility/legacy_just_pressed_behavior", false);
  1350. if (Engine::get_singleton()->is_editor_hint()) {
  1351. // Always use standard behavior in the editor.
  1352. legacy_just_pressed_behavior = false;
  1353. }
  1354. }
  1355. Input::~Input() {
  1356. singleton = nullptr;
  1357. }
  1358. //////////////////////////////////////////////////////////