-
-
Notifications
You must be signed in to change notification settings - Fork 21.2k
/
input.cpp
1657 lines (1419 loc) · 55.5 KB
/
input.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/* input.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "input.h"
#include "core/config/project_settings.h"
#include "core/input/default_controller_mappings.h"
#include "core/input/input_map.h"
#include "core/os/os.h"
#ifdef DEV_ENABLED
#include "core/os/thread.h"
#endif
static const char *_joy_buttons[(size_t)JoyButton::SDL_MAX] = {
"a",
"b",
"x",
"y",
"back",
"guide",
"start",
"leftstick",
"rightstick",
"leftshoulder",
"rightshoulder",
"dpup",
"dpdown",
"dpleft",
"dpright",
"misc1",
"paddle1",
"paddle2",
"paddle3",
"paddle4",
"touchpad",
};
static const char *_joy_axes[(size_t)JoyAxis::SDL_MAX] = {
"leftx",
"lefty",
"rightx",
"righty",
"lefttrigger",
"righttrigger",
};
Input *Input::singleton = nullptr;
void (*Input::set_mouse_mode_func)(Input::MouseMode) = nullptr;
Input::MouseMode (*Input::get_mouse_mode_func)() = nullptr;
void (*Input::warp_mouse_func)(const Vector2 &p_position) = nullptr;
Input::CursorShape (*Input::get_current_cursor_shape_func)() = nullptr;
void (*Input::set_custom_mouse_cursor_func)(const Ref<Resource> &, Input::CursorShape, const Vector2 &) = nullptr;
Input *Input::get_singleton() {
return singleton;
}
void Input::set_mouse_mode(MouseMode p_mode) {
ERR_FAIL_INDEX((int)p_mode, 5);
set_mouse_mode_func(p_mode);
}
Input::MouseMode Input::get_mouse_mode() const {
return get_mouse_mode_func();
}
void Input::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_anything_pressed"), &Input::is_anything_pressed);
ClassDB::bind_method(D_METHOD("is_key_pressed", "keycode"), &Input::is_key_pressed);
ClassDB::bind_method(D_METHOD("is_physical_key_pressed", "keycode"), &Input::is_physical_key_pressed);
ClassDB::bind_method(D_METHOD("is_key_label_pressed", "keycode"), &Input::is_key_label_pressed);
ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
ClassDB::bind_method(D_METHOD("is_action_pressed", "action", "exact_match"), &Input::is_action_pressed, DEFVAL(false));
ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action", "exact_match"), &Input::is_action_just_pressed, DEFVAL(false));
ClassDB::bind_method(D_METHOD("is_action_just_released", "action", "exact_match"), &Input::is_action_just_released, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_action_strength", "action", "exact_match"), &Input::get_action_strength, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_action_raw_strength", "action", "exact_match"), &Input::get_action_raw_strength, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_axis", "negative_action", "positive_action"), &Input::get_axis);
ClassDB::bind_method(D_METHOD("get_vector", "negative_x", "positive_x", "negative_y", "positive_y", "deadzone"), &Input::get_vector, DEFVAL(-1.0f));
ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
ClassDB::bind_method(D_METHOD("get_joy_info", "device"), &Input::get_joy_info);
ClassDB::bind_method(D_METHOD("should_ignore_device", "vendor_id", "product_id"), &Input::should_ignore_device);
ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
ClassDB::bind_method(D_METHOD("vibrate_handheld", "duration_ms"), &Input::vibrate_handheld, DEFVAL(500));
ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
ClassDB::bind_method(D_METHOD("set_gravity", "value"), &Input::set_gravity);
ClassDB::bind_method(D_METHOD("set_accelerometer", "value"), &Input::set_accelerometer);
ClassDB::bind_method(D_METHOD("set_magnetometer", "value"), &Input::set_magnetometer);
ClassDB::bind_method(D_METHOD("set_gyroscope", "value"), &Input::set_gyroscope);
ClassDB::bind_method(D_METHOD("get_last_mouse_velocity"), &Input::get_last_mouse_velocity);
ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
ClassDB::bind_method(D_METHOD("warp_mouse", "position"), &Input::warp_mouse);
ClassDB::bind_method(D_METHOD("action_press", "action", "strength"), &Input::action_press, DEFVAL(1.f));
ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Input::set_default_cursor_shape, DEFVAL(CURSOR_ARROW));
ClassDB::bind_method(D_METHOD("get_current_cursor_shape"), &Input::get_current_cursor_shape);
ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image", "shape", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(CURSOR_ARROW), DEFVAL(Vector2()));
ClassDB::bind_method(D_METHOD("parse_input_event", "event"), &Input::parse_input_event);
ClassDB::bind_method(D_METHOD("set_use_accumulated_input", "enable"), &Input::set_use_accumulated_input);
ClassDB::bind_method(D_METHOD("is_using_accumulated_input"), &Input::is_using_accumulated_input);
ClassDB::bind_method(D_METHOD("flush_buffered_events"), &Input::flush_buffered_events);
ClassDB::bind_method(D_METHOD("set_emulate_mouse_from_touch", "enable"), &Input::set_emulate_mouse_from_touch);
ClassDB::bind_method(D_METHOD("is_emulating_mouse_from_touch"), &Input::is_emulating_mouse_from_touch);
ClassDB::bind_method(D_METHOD("set_emulate_touch_from_mouse", "enable"), &Input::set_emulate_touch_from_mouse);
ClassDB::bind_method(D_METHOD("is_emulating_touch_from_mouse"), &Input::is_emulating_touch_from_mouse);
ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_mode"), "set_mouse_mode", "get_mouse_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_accumulated_input"), "set_use_accumulated_input", "is_using_accumulated_input");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emulate_mouse_from_touch"), "set_emulate_mouse_from_touch", "is_emulating_mouse_from_touch");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emulate_touch_from_mouse"), "set_emulate_touch_from_mouse", "is_emulating_touch_from_mouse");
BIND_ENUM_CONSTANT(MOUSE_MODE_VISIBLE);
BIND_ENUM_CONSTANT(MOUSE_MODE_HIDDEN);
BIND_ENUM_CONSTANT(MOUSE_MODE_CAPTURED);
BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED);
BIND_ENUM_CONSTANT(MOUSE_MODE_CONFINED_HIDDEN);
BIND_ENUM_CONSTANT(CURSOR_ARROW);
BIND_ENUM_CONSTANT(CURSOR_IBEAM);
BIND_ENUM_CONSTANT(CURSOR_POINTING_HAND);
BIND_ENUM_CONSTANT(CURSOR_CROSS);
BIND_ENUM_CONSTANT(CURSOR_WAIT);
BIND_ENUM_CONSTANT(CURSOR_BUSY);
BIND_ENUM_CONSTANT(CURSOR_DRAG);
BIND_ENUM_CONSTANT(CURSOR_CAN_DROP);
BIND_ENUM_CONSTANT(CURSOR_FORBIDDEN);
BIND_ENUM_CONSTANT(CURSOR_VSIZE);
BIND_ENUM_CONSTANT(CURSOR_HSIZE);
BIND_ENUM_CONSTANT(CURSOR_BDIAGSIZE);
BIND_ENUM_CONSTANT(CURSOR_FDIAGSIZE);
BIND_ENUM_CONSTANT(CURSOR_MOVE);
BIND_ENUM_CONSTANT(CURSOR_VSPLIT);
BIND_ENUM_CONSTANT(CURSOR_HSPLIT);
BIND_ENUM_CONSTANT(CURSOR_HELP);
ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "device"), PropertyInfo(Variant::BOOL, "connected")));
}
void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
String pf = p_function;
if ((p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" || pf == "is_action_just_pressed" || pf == "is_action_just_released" || pf == "get_action_strength" || pf == "get_action_raw_strength")) ||
(p_idx < 2 && pf == "get_axis") ||
(p_idx < 4 && pf == "get_vector")) {
List<PropertyInfo> pinfo;
ProjectSettings::get_singleton()->get_property_list(&pinfo);
for (const PropertyInfo &pi : pinfo) {
if (!pi.name.begins_with("input/")) {
continue;
}
String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
r_options->push_back(name.quote());
}
}
Object::get_argument_options(p_function, p_idx, r_options);
}
void Input::VelocityTrack::update(const Vector2 &p_delta_p) {
uint64_t tick = OS::get_singleton()->get_ticks_usec();
uint32_t tdiff = tick - last_tick;
float delta_t = tdiff / 1000000.0;
last_tick = tick;
if (delta_t > max_ref_frame) {
// First movement in a long time, reset and start again.
velocity = Vector2();
accum = p_delta_p;
accum_t = 0;
return;
}
accum += p_delta_p;
accum_t += delta_t;
if (accum_t < min_ref_frame) {
// Not enough time has passed to calculate speed precisely.
return;
}
velocity = accum / accum_t;
accum = Vector2();
accum_t = 0;
}
void Input::VelocityTrack::reset() {
last_tick = OS::get_singleton()->get_ticks_usec();
velocity = Vector2();
accum = Vector2();
accum_t = 0;
}
Input::VelocityTrack::VelocityTrack() {
min_ref_frame = 0.1;
max_ref_frame = 3.0;
reset();
}
bool Input::is_anything_pressed() const {
_THREAD_SAFE_METHOD_
if (!keys_pressed.is_empty() || !joy_buttons_pressed.is_empty() || !mouse_button_mask.is_empty()) {
return true;
}
for (const KeyValue<StringName, Input::ActionState> &E : action_states) {
if (E.value.cache.pressed) {
return true;
}
}
return false;
}
bool Input::is_key_pressed(Key p_keycode) const {
_THREAD_SAFE_METHOD_
return keys_pressed.has(p_keycode);
}
bool Input::is_physical_key_pressed(Key p_keycode) const {
_THREAD_SAFE_METHOD_
return physical_keys_pressed.has(p_keycode);
}
bool Input::is_key_label_pressed(Key p_keycode) const {
_THREAD_SAFE_METHOD_
return key_label_pressed.has(p_keycode);
}
bool Input::is_mouse_button_pressed(MouseButton p_button) const {
_THREAD_SAFE_METHOD_
return mouse_button_mask.has_flag(mouse_button_to_mask(p_button));
}
static JoyAxis _combine_device(JoyAxis p_value, int p_device) {
return JoyAxis((int)p_value | (p_device << 20));
}
static JoyButton _combine_device(JoyButton p_value, int p_device) {
return JoyButton((int)p_value | (p_device << 20));
}
bool Input::is_joy_button_pressed(int p_device, JoyButton p_button) const {
_THREAD_SAFE_METHOD_
return joy_buttons_pressed.has(_combine_device(p_button, p_device));
}
bool Input::is_action_pressed(const StringName &p_action, bool p_exact) const {
ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
if (!E) {
return false;
}
return E->value.cache.pressed && (p_exact ? E->value.exact : true);
}
bool Input::is_action_just_pressed(const StringName &p_action, bool p_exact) const {
ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
if (!E) {
return false;
}
if (p_exact && E->value.exact == false) {
return false;
}
// Backward compatibility for legacy behavior, only return true if currently pressed.
bool pressed_requirement = legacy_just_pressed_behavior ? E->value.cache.pressed : true;
if (Engine::get_singleton()->is_in_physics_frame()) {
return pressed_requirement && E->value.pressed_physics_frame == Engine::get_singleton()->get_physics_frames();
} else {
return pressed_requirement && E->value.pressed_process_frame == Engine::get_singleton()->get_process_frames();
}
}
bool Input::is_action_just_released(const StringName &p_action, bool p_exact) const {
ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), false, InputMap::get_singleton()->suggest_actions(p_action));
HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
if (!E) {
return false;
}
if (p_exact && E->value.exact == false) {
return false;
}
// Backward compatibility for legacy behavior, only return true if currently released.
bool released_requirement = legacy_just_pressed_behavior ? !E->value.cache.pressed : true;
if (Engine::get_singleton()->is_in_physics_frame()) {
return released_requirement && E->value.released_physics_frame == Engine::get_singleton()->get_physics_frames();
} else {
return released_requirement && E->value.released_process_frame == Engine::get_singleton()->get_process_frames();
}
}
float Input::get_action_strength(const StringName &p_action, bool p_exact) const {
ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
if (!E) {
return 0.0f;
}
if (p_exact && E->value.exact == false) {
return 0.0f;
}
return E->value.cache.strength;
}
float Input::get_action_raw_strength(const StringName &p_action, bool p_exact) const {
ERR_FAIL_COND_V_MSG(!InputMap::get_singleton()->has_action(p_action), 0.0, InputMap::get_singleton()->suggest_actions(p_action));
HashMap<StringName, ActionState>::ConstIterator E = action_states.find(p_action);
if (!E) {
return 0.0f;
}
if (p_exact && E->value.exact == false) {
return 0.0f;
}
return E->value.cache.raw_strength;
}
float Input::get_axis(const StringName &p_negative_action, const StringName &p_positive_action) const {
return get_action_strength(p_positive_action) - get_action_strength(p_negative_action);
}
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 {
Vector2 vector = Vector2(
get_action_raw_strength(p_positive_x) - get_action_raw_strength(p_negative_x),
get_action_raw_strength(p_positive_y) - get_action_raw_strength(p_negative_y));
if (p_deadzone < 0.0f) {
// If the deadzone isn't specified, get it from the average of the actions.
p_deadzone = 0.25 *
(InputMap::get_singleton()->action_get_deadzone(p_positive_x) +
InputMap::get_singleton()->action_get_deadzone(p_negative_x) +
InputMap::get_singleton()->action_get_deadzone(p_positive_y) +
InputMap::get_singleton()->action_get_deadzone(p_negative_y));
}
// Circular length limiting and deadzone.
float length = vector.length();
if (length <= p_deadzone) {
return Vector2();
} else if (length > 1.0f) {
return vector / length;
} else {
// Inverse lerp length to map (p_deadzone, 1) to (0, 1).
return vector * (Math::inverse_lerp(p_deadzone, 1.0f, length) / length);
}
}
float Input::get_joy_axis(int p_device, JoyAxis p_axis) const {
_THREAD_SAFE_METHOD_
JoyAxis c = _combine_device(p_axis, p_device);
if (_joy_axis.has(c)) {
return _joy_axis[c];
} else {
return 0;
}
}
String Input::get_joy_name(int p_idx) {
_THREAD_SAFE_METHOD_
return joy_names[p_idx].name;
}
Vector2 Input::get_joy_vibration_strength(int p_device) {
if (joy_vibration.has(p_device)) {
return Vector2(joy_vibration[p_device].weak_magnitude, joy_vibration[p_device].strong_magnitude);
} else {
return Vector2(0, 0);
}
}
uint64_t Input::get_joy_vibration_timestamp(int p_device) {
if (joy_vibration.has(p_device)) {
return joy_vibration[p_device].timestamp;
} else {
return 0;
}
}
float Input::get_joy_vibration_duration(int p_device) {
if (joy_vibration.has(p_device)) {
return joy_vibration[p_device].duration;
} else {
return 0.f;
}
}
static String _hex_str(uint8_t p_byte) {
static const char *dict = "0123456789abcdef";
char ret[3];
ret[2] = 0;
ret[0] = dict[p_byte >> 4];
ret[1] = dict[p_byte & 0xf];
return ret;
}
void Input::joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid, Dictionary p_joypad_info) {
_THREAD_SAFE_METHOD_
// Clear the pressed status if a Joypad gets disconnected.
if (!p_connected) {
for (KeyValue<StringName, ActionState> &E : action_states) {
HashMap<int, ActionState::DeviceState>::Iterator it = E.value.device_states.find(p_idx);
if (it) {
E.value.device_states.remove(it);
_update_action_cache(E.key, E.value);
}
}
}
Joypad js;
js.name = p_connected ? p_name : "";
js.uid = p_connected ? p_guid : "";
js.info = p_connected ? p_joypad_info : Dictionary();
if (p_connected) {
String uidname = p_guid;
if (p_guid.is_empty()) {
int uidlen = MIN(p_name.length(), 16);
for (int i = 0; i < uidlen; i++) {
uidname = uidname + _hex_str(p_name[i]);
}
}
js.uid = uidname;
js.connected = true;
int mapping = fallback_mapping;
for (int i = 0; i < map_db.size(); i++) {
if (js.uid == map_db[i].uid) {
mapping = i;
js.name = map_db[i].name;
}
}
js.mapping = mapping;
} else {
js.connected = false;
for (int i = 0; i < (int)JoyButton::MAX; i++) {
JoyButton c = _combine_device((JoyButton)i, p_idx);
joy_buttons_pressed.erase(c);
}
for (int i = 0; i < (int)JoyAxis::MAX; i++) {
set_joy_axis(p_idx, (JoyAxis)i, 0.0f);
}
}
joy_names[p_idx] = js;
// Ensure this signal is emitted on the main thread, as some platforms (e.g. Linux) call this from a different thread.
call_deferred("emit_signal", SNAME("joy_connection_changed"), p_idx, p_connected);
}
Vector3 Input::get_gravity() const {
_THREAD_SAFE_METHOD_
return gravity;
}
Vector3 Input::get_accelerometer() const {
_THREAD_SAFE_METHOD_
return accelerometer;
}
Vector3 Input::get_magnetometer() const {
_THREAD_SAFE_METHOD_
return magnetometer;
}
Vector3 Input::get_gyroscope() const {
_THREAD_SAFE_METHOD_
return gyroscope;
}
void Input::_parse_input_event_impl(const Ref<InputEvent> &p_event, bool p_is_emulated) {
// This function does the final delivery of the input event to user land.
// Regardless where the event came from originally, this has to happen on the main thread.
DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id());
// Notes on mouse-touch emulation:
// - Emulated mouse events are parsed, that is, re-routed to this method, so they make the same effects
// as true mouse events. The only difference is the situation is flagged as emulated so they are not
// emulated back to touch events in an endless loop.
// - Emulated touch events are handed right to the main loop (i.e., the SceneTree) because they don't
// require additional handling by this class.
Ref<InputEventKey> k = p_event;
if (k.is_valid() && !k->is_echo() && k->get_keycode() != Key::NONE) {
if (k->is_pressed()) {
keys_pressed.insert(k->get_keycode());
} else {
keys_pressed.erase(k->get_keycode());
}
}
if (k.is_valid() && !k->is_echo() && k->get_physical_keycode() != Key::NONE) {
if (k->is_pressed()) {
physical_keys_pressed.insert(k->get_physical_keycode());
} else {
physical_keys_pressed.erase(k->get_physical_keycode());
}
}
if (k.is_valid() && !k->is_echo() && k->get_key_label() != Key::NONE) {
if (k->is_pressed()) {
key_label_pressed.insert(k->get_key_label());
} else {
key_label_pressed.erase(k->get_key_label());
}
}
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
if (mb->is_pressed()) {
mouse_button_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
} else {
mouse_button_mask.clear_flag(mouse_button_to_mask(mb->get_button_index()));
}
Point2 pos = mb->get_global_position();
if (mouse_pos != pos) {
set_mouse_position(pos);
}
if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mb->get_button_index() == MouseButton::LEFT) {
Ref<InputEventScreenTouch> touch_event;
touch_event.instantiate();
touch_event->set_pressed(mb->is_pressed());
touch_event->set_canceled(mb->is_canceled());
touch_event->set_position(mb->get_position());
touch_event->set_double_tap(mb->is_double_click());
touch_event->set_device(InputEvent::DEVICE_ID_EMULATION);
_THREAD_SAFE_UNLOCK_
event_dispatch_function(touch_event);
_THREAD_SAFE_LOCK_
}
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid()) {
Point2 position = mm->get_global_position();
if (mouse_pos != position) {
set_mouse_position(position);
}
Vector2 relative = mm->get_relative();
mouse_velocity_track.update(relative);
if (event_dispatch_function && emulate_touch_from_mouse && !p_is_emulated && mm->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
Ref<InputEventScreenDrag> drag_event;
drag_event.instantiate();
drag_event->set_position(position);
drag_event->set_relative(relative);
drag_event->set_tilt(mm->get_tilt());
drag_event->set_pen_inverted(mm->get_pen_inverted());
drag_event->set_pressure(mm->get_pressure());
drag_event->set_velocity(get_last_mouse_velocity());
drag_event->set_device(InputEvent::DEVICE_ID_EMULATION);
_THREAD_SAFE_UNLOCK_
event_dispatch_function(drag_event);
_THREAD_SAFE_LOCK_
}
}
Ref<InputEventScreenTouch> st = p_event;
if (st.is_valid()) {
if (st->is_pressed()) {
VelocityTrack &track = touch_velocity_track[st->get_index()];
track.reset();
} else {
// Since a pointer index may not occur again (OSs may or may not reuse them),
// imperatively remove it from the map to keep no fossil entries in it
touch_velocity_track.erase(st->get_index());
}
if (emulate_mouse_from_touch) {
bool translate = false;
if (st->is_pressed()) {
if (mouse_from_touch_index == -1) {
translate = true;
mouse_from_touch_index = st->get_index();
}
} else {
if (st->get_index() == mouse_from_touch_index) {
translate = true;
mouse_from_touch_index = -1;
}
}
if (translate) {
Ref<InputEventMouseButton> button_event;
button_event.instantiate();
button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
button_event->set_position(st->get_position());
button_event->set_global_position(st->get_position());
button_event->set_pressed(st->is_pressed());
button_event->set_canceled(st->is_canceled());
button_event->set_button_index(MouseButton::LEFT);
button_event->set_double_click(st->is_double_tap());
BitField<MouseButtonMask> ev_bm = mouse_button_mask;
if (st->is_pressed()) {
ev_bm.set_flag(MouseButtonMask::LEFT);
} else {
ev_bm.clear_flag(MouseButtonMask::LEFT);
}
button_event->set_button_mask(ev_bm);
_parse_input_event_impl(button_event, true);
}
}
}
Ref<InputEventScreenDrag> sd = p_event;
if (sd.is_valid()) {
VelocityTrack &track = touch_velocity_track[sd->get_index()];
track.update(sd->get_relative());
sd->set_velocity(track.velocity);
if (emulate_mouse_from_touch && sd->get_index() == mouse_from_touch_index) {
Ref<InputEventMouseMotion> motion_event;
motion_event.instantiate();
motion_event->set_device(InputEvent::DEVICE_ID_EMULATION);
motion_event->set_tilt(sd->get_tilt());
motion_event->set_pen_inverted(sd->get_pen_inverted());
motion_event->set_pressure(sd->get_pressure());
motion_event->set_position(sd->get_position());
motion_event->set_global_position(sd->get_position());
motion_event->set_relative(sd->get_relative());
motion_event->set_velocity(sd->get_velocity());
motion_event->set_button_mask(mouse_button_mask);
_parse_input_event_impl(motion_event, true);
}
}
Ref<InputEventJoypadButton> jb = p_event;
if (jb.is_valid()) {
JoyButton c = _combine_device(jb->get_button_index(), jb->get_device());
if (jb->is_pressed()) {
joy_buttons_pressed.insert(c);
} else {
joy_buttons_pressed.erase(c);
}
}
Ref<InputEventJoypadMotion> jm = p_event;
if (jm.is_valid()) {
set_joy_axis(jm->get_device(), jm->get_axis(), jm->get_axis_value());
}
Ref<InputEventGesture> ge = p_event;
if (ge.is_valid()) {
if (event_dispatch_function) {
_THREAD_SAFE_UNLOCK_
event_dispatch_function(ge);
_THREAD_SAFE_LOCK_
}
}
for (const KeyValue<StringName, InputMap::Action> &E : InputMap::get_singleton()->get_action_map()) {
const int event_index = InputMap::get_singleton()->event_get_index(p_event, E.key);
if (event_index == -1) {
continue;
}
ERR_FAIL_COND_MSG(event_index >= (int)MAX_EVENT, vformat("Input singleton does not support more than %d events assigned to an action.", MAX_EVENT));
int device_id = p_event->get_device();
bool is_pressed = p_event->is_action_pressed(E.key, true);
ActionState &action_state = action_states[E.key];
// Update the action's per-device state.
ActionState::DeviceState &device_state = action_state.device_states[device_id];
device_state.pressed[event_index] = is_pressed;
device_state.strength[event_index] = p_event->get_action_strength(E.key);
device_state.raw_strength[event_index] = p_event->get_action_raw_strength(E.key);
// Update the action's global state and cache.
if (!is_pressed) {
action_state.api_pressed = false; // Always release the event from action_press() method.
action_state.api_strength = 0.0;
}
action_state.exact = InputMap::get_singleton()->event_is_action(p_event, E.key, true);
bool was_pressed = action_state.cache.pressed;
_update_action_cache(E.key, action_state);
if (action_state.cache.pressed && !was_pressed) {
action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames();
action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
}
if (!action_state.cache.pressed && was_pressed) {
action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames();
action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
}
}
if (event_dispatch_function) {
_THREAD_SAFE_UNLOCK_
event_dispatch_function(p_event);
_THREAD_SAFE_LOCK_
}
}
void Input::set_joy_axis(int p_device, JoyAxis p_axis, float p_value) {
_THREAD_SAFE_METHOD_
JoyAxis c = _combine_device(p_axis, p_device);
_joy_axis[c] = p_value;
}
void Input::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
_THREAD_SAFE_METHOD_
if (p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
return;
}
VibrationInfo vibration;
vibration.weak_magnitude = p_weak_magnitude;
vibration.strong_magnitude = p_strong_magnitude;
vibration.duration = p_duration;
vibration.timestamp = OS::get_singleton()->get_ticks_usec();
joy_vibration[p_device] = vibration;
}
void Input::stop_joy_vibration(int p_device) {
_THREAD_SAFE_METHOD_
VibrationInfo vibration;
vibration.weak_magnitude = 0;
vibration.strong_magnitude = 0;
vibration.duration = 0;
vibration.timestamp = OS::get_singleton()->get_ticks_usec();
joy_vibration[p_device] = vibration;
}
void Input::vibrate_handheld(int p_duration_ms) {
OS::get_singleton()->vibrate_handheld(p_duration_ms);
}
void Input::set_gravity(const Vector3 &p_gravity) {
_THREAD_SAFE_METHOD_
gravity = p_gravity;
}
void Input::set_accelerometer(const Vector3 &p_accel) {
_THREAD_SAFE_METHOD_
accelerometer = p_accel;
}
void Input::set_magnetometer(const Vector3 &p_magnetometer) {
_THREAD_SAFE_METHOD_
magnetometer = p_magnetometer;
}
void Input::set_gyroscope(const Vector3 &p_gyroscope) {
_THREAD_SAFE_METHOD_
gyroscope = p_gyroscope;
}
void Input::set_mouse_position(const Point2 &p_posf) {
mouse_pos = p_posf;
}
Point2 Input::get_mouse_position() const {
return mouse_pos;
}
Point2 Input::get_last_mouse_velocity() {
mouse_velocity_track.update(Vector2());
return mouse_velocity_track.velocity;
}
BitField<MouseButtonMask> Input::get_mouse_button_mask() const {
return mouse_button_mask; // do not trust OS implementation, should remove it - OS::get_singleton()->get_mouse_button_state();
}
void Input::warp_mouse(const Vector2 &p_position) {
warp_mouse_func(p_position);
}
Point2i Input::warp_mouse_motion(const Ref<InputEventMouseMotion> &p_motion, const Rect2 &p_rect) {
// The relative distance reported for the next event after a warp is in the boundaries of the
// size of the rect on that axis, but it may be greater, in which case there's no problem as fmod()
// will warp it, but if the pointer has moved in the opposite direction between the pointer relocation
// and the subsequent event, the reported relative distance will be less than the size of the rect
// and thus fmod() will be disabled for handling the situation.
// And due to this mouse warping mechanism being stateless, we need to apply some heuristics to
// detect the warp: if the relative distance is greater than the half of the size of the relevant rect
// (checked per each axis), it will be considered as the consequence of a former pointer warp.
const Point2i rel_sign(p_motion->get_relative().x >= 0.0f ? 1 : -1, p_motion->get_relative().y >= 0.0 ? 1 : -1);
const Size2i warp_margin = p_rect.size * 0.5f;
const Point2i rel_warped(
Math::fmod(p_motion->get_relative().x + rel_sign.x * warp_margin.x, p_rect.size.x) - rel_sign.x * warp_margin.x,
Math::fmod(p_motion->get_relative().y + rel_sign.y * warp_margin.y, p_rect.size.y) - rel_sign.y * warp_margin.y);
const Point2i pos_local = p_motion->get_global_position() - p_rect.position;
const Point2i pos_warped(Math::fposmod(pos_local.x, p_rect.size.x), Math::fposmod(pos_local.y, p_rect.size.y));
if (pos_warped != pos_local) {
warp_mouse(pos_warped + p_rect.position);
}
return rel_warped;
}
void Input::action_press(const StringName &p_action, float p_strength) {
// Create or retrieve existing action.
ActionState &action_state = action_states[p_action];
if (!action_state.cache.pressed) {
action_state.pressed_physics_frame = Engine::get_singleton()->get_physics_frames();
action_state.pressed_process_frame = Engine::get_singleton()->get_process_frames();
}
action_state.exact = true;
action_state.api_pressed = true;
action_state.api_strength = p_strength;
_update_action_cache(p_action, action_state);
}
void Input::action_release(const StringName &p_action) {
// Create or retrieve existing action.
ActionState &action_state = action_states[p_action];
action_state.cache.pressed = 0;
action_state.cache.strength = 0.0;
action_state.cache.raw_strength = 0.0;
action_state.released_physics_frame = Engine::get_singleton()->get_physics_frames();
action_state.released_process_frame = Engine::get_singleton()->get_process_frames();
action_state.device_states.clear();
action_state.exact = true;
action_state.api_pressed = false;
action_state.api_strength = 0.0;
}
void Input::set_emulate_touch_from_mouse(bool p_emulate) {
emulate_touch_from_mouse = p_emulate;
}
bool Input::is_emulating_touch_from_mouse() const {
return emulate_touch_from_mouse;
}
// Calling this whenever the game window is focused helps unsticking the "touch mouse"
// if the OS or its abstraction class hasn't properly reported that touch pointers raised
void Input::ensure_touch_mouse_raised() {
_THREAD_SAFE_METHOD_
if (mouse_from_touch_index != -1) {
mouse_from_touch_index = -1;
Ref<InputEventMouseButton> button_event;
button_event.instantiate();
button_event->set_device(InputEvent::DEVICE_ID_EMULATION);
button_event->set_position(mouse_pos);
button_event->set_global_position(mouse_pos);
button_event->set_pressed(false);
button_event->set_button_index(MouseButton::LEFT);
BitField<MouseButtonMask> ev_bm = mouse_button_mask;
ev_bm.clear_flag(MouseButtonMask::LEFT);
button_event->set_button_mask(ev_bm);
_parse_input_event_impl(button_event, true);
}
}
void Input::set_emulate_mouse_from_touch(bool p_emulate) {
emulate_mouse_from_touch = p_emulate;
}
bool Input::is_emulating_mouse_from_touch() const {
return emulate_mouse_from_touch;
}
Input::CursorShape Input::get_default_cursor_shape() const {
return default_shape;
}
void Input::set_default_cursor_shape(CursorShape p_shape) {
if (default_shape == p_shape) {
return;
}
default_shape = p_shape;
// The default shape is set in Viewport::_gui_input_event. To instantly
// see the shape in the viewport we need to trigger a mouse motion event.
Ref<InputEventMouseMotion> mm;
mm.instantiate();
mm->set_position(mouse_pos);
mm->set_global_position(mouse_pos);
mm->set_device(InputEvent::DEVICE_ID_INTERNAL);
parse_input_event(mm);
}
Input::CursorShape Input::get_current_cursor_shape() const {
return get_current_cursor_shape_func();
}
void Input::set_custom_mouse_cursor(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
if (Engine::get_singleton()->is_editor_hint()) {
return;
}
ERR_FAIL_INDEX(p_shape, CursorShape::CURSOR_MAX);
set_custom_mouse_cursor_func(p_cursor, p_shape, p_hotspot);
}
void Input::parse_input_event(const Ref<InputEvent> &p_event) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(p_event.is_null());
#ifdef DEBUG_ENABLED
uint64_t curr_frame = Engine::get_singleton()->get_process_frames();
if (curr_frame != last_parsed_frame) {
frame_parsed_events.clear();
last_parsed_frame = curr_frame;
frame_parsed_events.insert(p_event);
} else if (frame_parsed_events.has(p_event)) {
// It would be technically safe to send the same event in cases such as:
// - After an explicit flush.
// - In platforms using buffering when agile flushing is enabled, after one of the mid-frame flushes.
// - If platform doesn't use buffering and event accumulation is disabled.
// - If platform doesn't use buffering and the event type is not accumulable.
// However, it wouldn't be reasonable to ask users to remember the full ruleset and be aware at all times
// of the possibilities of the target platform, project settings and engine internals, which may change
// without prior notice.
// Therefore, the guideline is, "don't send the same event object more than once per frame".
WARN_PRINT_ONCE(
"An input event object is being parsed more than once in the same frame, which is unsafe.\n"
"If you are generating events in a script, you have to instantiate a new event instead of sending the same one more than once, unless the original one was sent on an earlier frame.\n"
"You can call duplicate() on the event to get a new instance with identical values.");
} else {
frame_parsed_events.insert(p_event);
}
#endif
if (use_accumulated_input) {
if (buffered_events.is_empty() || !buffered_events.back()->get()->accumulate(p_event)) {
buffered_events.push_back(p_event);