input.cpp 44 KB

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