input.cpp 60 KB

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