input_default.cpp 41 KB

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