/
input.cpp
837 lines (739 loc) · 22.2 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
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <SDL.h>
#include <base/system.h>
#include <engine/console.h>
#include <engine/graphics.h>
#include <engine/input.h>
#include <engine/keys.h>
#include <engine/shared/config.h>
#include "input.h"
// this header is protected so you don't include it from anywhere
#define KEYS_INCLUDE
#include "keynames.h"
#undef KEYS_INCLUDE
// support older SDL version (pre 2.0.6)
#ifndef SDL_JOYSTICK_AXIS_MIN
#define SDL_JOYSTICK_AXIS_MIN (-32768)
#endif
#ifndef SDL_JOYSTICK_AXIS_MAX
#define SDL_JOYSTICK_AXIS_MAX 32767
#endif
#if defined(CONF_FAMILY_WINDOWS)
#include <windows.h>
// windows.h must be included before imm.h, but clang-format requires includes to be sorted alphabetically, hence this comment.
#include <imm.h>
#endif
// for platform specific features that aren't available or are broken in SDL
#include <SDL_syswm.h>
void CInput::AddEvent(char *pText, int Key, int Flags)
{
if(m_NumEvents != INPUT_BUFFER_SIZE)
{
m_aInputEvents[m_NumEvents].m_Key = Key;
m_aInputEvents[m_NumEvents].m_Flags = Flags;
if(pText == nullptr)
m_aInputEvents[m_NumEvents].m_aText[0] = '\0';
else
str_copy(m_aInputEvents[m_NumEvents].m_aText, pText);
m_aInputEvents[m_NumEvents].m_InputCount = m_InputCounter;
m_NumEvents++;
}
}
CInput::CInput()
{
mem_zero(m_aInputCount, sizeof(m_aInputCount));
mem_zero(m_aInputState, sizeof(m_aInputState));
m_LastUpdate = 0;
m_UpdateTime = 0.0f;
m_InputCounter = 1;
m_InputGrabbed = false;
m_MouseDoubleClick = false;
m_NumEvents = 0;
m_MouseFocus = true;
m_pClipboardText = nullptr;
m_CompositionLength = COMP_LENGTH_INACTIVE;
m_CompositionCursor = 0;
m_CandidateSelectedIndex = -1;
m_aDropFile[0] = '\0';
}
void CInput::Init()
{
StopTextInput();
m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();
m_pConsole = Kernel()->RequestInterface<IConsole>();
MouseModeRelative();
InitJoysticks();
}
void CInput::Shutdown()
{
SDL_free(m_pClipboardText);
CloseJoysticks();
}
void CInput::InitJoysticks()
{
if(!SDL_WasInit(SDL_INIT_JOYSTICK))
{
if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
{
dbg_msg("joystick", "Unable to init SDL joystick system: %s", SDL_GetError());
return;
}
}
const int NumJoysticks = SDL_NumJoysticks();
dbg_msg("joystick", "%d joystick(s) found", NumJoysticks);
for(int i = 0; i < NumJoysticks; i++)
OpenJoystick(i);
UpdateActiveJoystick();
Console()->Chain("inp_controller_guid", ConchainJoystickGuidChanged, this);
}
bool CInput::OpenJoystick(int JoystickIndex)
{
SDL_Joystick *pJoystick = SDL_JoystickOpen(JoystickIndex);
if(!pJoystick)
{
dbg_msg("joystick", "Could not open joystick %d: '%s'", JoystickIndex, SDL_GetError());
return false;
}
if(std::find_if(m_vJoysticks.begin(), m_vJoysticks.end(), [pJoystick](const CJoystick &Joystick) -> bool { return Joystick.m_pDelegate == pJoystick; }) != m_vJoysticks.end())
{
// Joystick has already been added
return false;
}
m_vJoysticks.emplace_back(this, m_vJoysticks.size(), pJoystick);
const CJoystick &Joystick = m_vJoysticks[m_vJoysticks.size() - 1];
dbg_msg("joystick", "Opened joystick %d '%s' (%d axes, %d buttons, %d balls, %d hats)", JoystickIndex, Joystick.GetName(),
Joystick.GetNumAxes(), Joystick.GetNumButtons(), Joystick.GetNumBalls(), Joystick.GetNumHats());
return true;
}
void CInput::UpdateActiveJoystick()
{
m_pActiveJoystick = nullptr;
if(m_vJoysticks.empty())
return;
for(auto &Joystick : m_vJoysticks)
{
if(str_comp(Joystick.GetGUID(), g_Config.m_InpControllerGUID) == 0)
{
m_pActiveJoystick = &Joystick;
return;
}
}
// Fall back to first joystick if no match was found
if(!m_pActiveJoystick)
m_pActiveJoystick = &m_vJoysticks.front();
}
void CInput::ConchainJoystickGuidChanged(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
{
pfnCallback(pResult, pCallbackUserData);
if(pResult->NumArguments() == 1)
{
static_cast<CInput *>(pUserData)->UpdateActiveJoystick();
}
}
float CInput::GetJoystickDeadzone()
{
return minimum(g_Config.m_InpControllerTolerance / 50.0f, 0.995f);
}
CInput::CJoystick::CJoystick(CInput *pInput, int Index, SDL_Joystick *pDelegate)
{
m_pInput = pInput;
m_Index = Index;
m_pDelegate = pDelegate;
m_NumAxes = SDL_JoystickNumAxes(pDelegate);
m_NumButtons = SDL_JoystickNumButtons(pDelegate);
m_NumBalls = SDL_JoystickNumBalls(pDelegate);
m_NumHats = SDL_JoystickNumHats(pDelegate);
str_copy(m_aName, SDL_JoystickName(pDelegate));
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(pDelegate), m_aGUID, sizeof(m_aGUID));
m_InstanceId = SDL_JoystickInstanceID(pDelegate);
}
void CInput::CloseJoysticks()
{
if(SDL_WasInit(SDL_INIT_JOYSTICK))
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
m_vJoysticks.clear();
m_pActiveJoystick = nullptr;
}
void CInput::SetActiveJoystick(size_t Index)
{
m_pActiveJoystick = &m_vJoysticks[Index];
str_copy(g_Config.m_InpControllerGUID, m_pActiveJoystick->GetGUID());
}
float CInput::CJoystick::GetAxisValue(int Axis)
{
return (SDL_JoystickGetAxis(m_pDelegate, Axis) - SDL_JOYSTICK_AXIS_MIN) / (float)(SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN) * 2.0f - 1.0f;
}
void CInput::CJoystick::GetJoystickHatKeys(int Hat, int HatValue, int (&HatKeys)[2])
{
if(HatValue & SDL_HAT_UP)
HatKeys[0] = KEY_JOY_HAT0_UP + Hat * NUM_JOYSTICK_BUTTONS_PER_HAT;
else if(HatValue & SDL_HAT_DOWN)
HatKeys[0] = KEY_JOY_HAT0_DOWN + Hat * NUM_JOYSTICK_BUTTONS_PER_HAT;
else
HatKeys[0] = KEY_UNKNOWN;
if(HatValue & SDL_HAT_LEFT)
HatKeys[1] = KEY_JOY_HAT0_LEFT + Hat * NUM_JOYSTICK_BUTTONS_PER_HAT;
else if(HatValue & SDL_HAT_RIGHT)
HatKeys[1] = KEY_JOY_HAT0_RIGHT + Hat * NUM_JOYSTICK_BUTTONS_PER_HAT;
else
HatKeys[1] = KEY_UNKNOWN;
}
void CInput::CJoystick::GetHatValue(int Hat, int (&HatKeys)[2])
{
return GetJoystickHatKeys(Hat, SDL_JoystickGetHat(m_pDelegate, Hat), HatKeys);
}
bool CInput::CJoystick::Relative(float *pX, float *pY)
{
if(!Input()->m_MouseFocus || !Input()->m_InputGrabbed || !g_Config.m_InpControllerEnable)
return false;
const vec2 RawJoystickPos = vec2(GetAxisValue(g_Config.m_InpControllerX), GetAxisValue(g_Config.m_InpControllerY));
const float Len = length(RawJoystickPos);
const float DeadZone = Input()->GetJoystickDeadzone();
if(Len > DeadZone)
{
const float Factor = 2500.0f * Input()->GetUpdateTime() * maximum((Len - DeadZone) / (1.0f - DeadZone), 0.001f) / Len;
*pX = RawJoystickPos.x * Factor;
*pY = RawJoystickPos.y * Factor;
return true;
}
return false;
}
bool CInput::CJoystick::Absolute(float *pX, float *pY)
{
if(!Input()->m_MouseFocus || !Input()->m_InputGrabbed || !g_Config.m_InpControllerEnable)
return false;
const vec2 RawJoystickPos = vec2(GetAxisValue(g_Config.m_InpControllerX), GetAxisValue(g_Config.m_InpControllerY));
const float DeadZone = Input()->GetJoystickDeadzone();
if(dot(RawJoystickPos, RawJoystickPos) > DeadZone * DeadZone)
{
*pX = RawJoystickPos.x;
*pY = RawJoystickPos.y;
return true;
}
return false;
}
bool CInput::MouseRelative(float *pX, float *pY)
{
if(!m_MouseFocus || !m_InputGrabbed)
return false;
ivec2 Relative;
#if defined(CONF_PLATFORM_ANDROID) // No relative mouse on Android
ivec2 CurrentPos;
SDL_GetMouseState(&CurrentPos.x, &CurrentPos.y);
Relative = CurrentPos - m_LastMousePos;
m_LastMousePos = CurrentPos;
#else
SDL_GetRelativeMouseState(&Relative.x, &Relative.y);
#endif
*pX = Relative.x;
*pY = Relative.y;
return *pX != 0.0f || *pY != 0.0f;
}
void CInput::MouseModeAbsolute()
{
m_InputGrabbed = false;
SDL_SetRelativeMouseMode(SDL_FALSE);
Graphics()->SetWindowGrab(false);
}
void CInput::MouseModeRelative()
{
m_InputGrabbed = true;
#if !defined(CONF_PLATFORM_ANDROID) // No relative mouse on Android
SDL_SetRelativeMouseMode(SDL_TRUE);
#endif
Graphics()->SetWindowGrab(true);
// Clear pending relative mouse motion
SDL_GetRelativeMouseState(nullptr, nullptr);
}
void CInput::NativeMousePos(int *pX, int *pY) const
{
SDL_GetMouseState(pX, pY);
}
bool CInput::NativeMousePressed(int Index)
{
int i = SDL_GetMouseState(nullptr, nullptr);
return (i & SDL_BUTTON(Index)) != 0;
}
bool CInput::MouseDoubleClick()
{
if(m_MouseDoubleClick)
{
m_MouseDoubleClick = false;
return true;
}
return false;
}
const char *CInput::GetClipboardText()
{
SDL_free(m_pClipboardText);
m_pClipboardText = SDL_GetClipboardText();
return m_pClipboardText;
}
void CInput::SetClipboardText(const char *pText)
{
SDL_SetClipboardText(pText);
}
void CInput::StartTextInput()
{
// enable system messages for IME
SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);
SDL_StartTextInput();
}
void CInput::StopTextInput()
{
SDL_StopTextInput();
// disable system messages for performance
SDL_EventState(SDL_SYSWMEVENT, SDL_DISABLE);
m_CompositionLength = COMP_LENGTH_INACTIVE;
m_CompositionCursor = 0;
m_aComposition[0] = '\0';
m_vCandidates.clear();
}
void CInput::Clear()
{
mem_zero(m_aInputState, sizeof(m_aInputState));
mem_zero(m_aInputCount, sizeof(m_aInputCount));
m_NumEvents = 0;
}
bool CInput::KeyState(int Key) const
{
if(Key < KEY_FIRST || Key >= KEY_LAST)
return false;
return m_aInputState[Key];
}
void CInput::UpdateMouseState()
{
const int MouseState = SDL_GetMouseState(nullptr, nullptr);
if(MouseState & SDL_BUTTON(SDL_BUTTON_LEFT))
m_aInputState[KEY_MOUSE_1] = 1;
if(MouseState & SDL_BUTTON(SDL_BUTTON_RIGHT))
m_aInputState[KEY_MOUSE_2] = 1;
if(MouseState & SDL_BUTTON(SDL_BUTTON_MIDDLE))
m_aInputState[KEY_MOUSE_3] = 1;
if(MouseState & SDL_BUTTON(SDL_BUTTON_X1))
m_aInputState[KEY_MOUSE_4] = 1;
if(MouseState & SDL_BUTTON(SDL_BUTTON_X2))
m_aInputState[KEY_MOUSE_5] = 1;
if(MouseState & SDL_BUTTON(6))
m_aInputState[KEY_MOUSE_6] = 1;
if(MouseState & SDL_BUTTON(7))
m_aInputState[KEY_MOUSE_7] = 1;
if(MouseState & SDL_BUTTON(8))
m_aInputState[KEY_MOUSE_8] = 1;
if(MouseState & SDL_BUTTON(9))
m_aInputState[KEY_MOUSE_9] = 1;
}
void CInput::UpdateJoystickState()
{
if(!g_Config.m_InpControllerEnable)
return;
IJoystick *pJoystick = GetActiveJoystick();
if(!pJoystick)
return;
const float DeadZone = GetJoystickDeadzone();
for(int Axis = 0; Axis < pJoystick->GetNumAxes(); Axis++)
{
const float Value = pJoystick->GetAxisValue(Axis);
const int LeftKey = KEY_JOY_AXIS_0_LEFT + 2 * Axis;
const int RightKey = LeftKey + 1;
m_aInputState[LeftKey] = Value <= -DeadZone;
m_aInputState[RightKey] = Value >= DeadZone;
}
for(int Hat = 0; Hat < pJoystick->GetNumHats(); Hat++)
{
int HatKeys[2];
pJoystick->GetHatValue(Hat, HatKeys);
for(int Key = KEY_JOY_HAT0_UP + Hat * NUM_JOYSTICK_BUTTONS_PER_HAT; Key <= KEY_JOY_HAT0_DOWN + Hat * NUM_JOYSTICK_BUTTONS_PER_HAT; Key++)
m_aInputState[Key] = HatKeys[0] == Key || HatKeys[1] == Key;
}
}
void CInput::HandleJoystickAxisMotionEvent(const SDL_JoyAxisEvent &Event)
{
if(!g_Config.m_InpControllerEnable)
return;
CJoystick *pJoystick = GetActiveJoystick();
if(!pJoystick || pJoystick->GetInstanceId() != Event.which)
return;
if(Event.axis >= NUM_JOYSTICK_AXES)
return;
const int LeftKey = KEY_JOY_AXIS_0_LEFT + 2 * Event.axis;
const int RightKey = LeftKey + 1;
const float DeadZone = GetJoystickDeadzone();
if(Event.value <= SDL_JOYSTICK_AXIS_MIN * DeadZone && !m_aInputState[LeftKey])
{
m_aInputState[LeftKey] = true;
m_aInputCount[LeftKey] = m_InputCounter;
AddEvent(nullptr, LeftKey, IInput::FLAG_PRESS);
}
else if(Event.value > SDL_JOYSTICK_AXIS_MIN * DeadZone && m_aInputState[LeftKey])
{
m_aInputState[LeftKey] = false;
AddEvent(nullptr, LeftKey, IInput::FLAG_RELEASE);
}
if(Event.value >= SDL_JOYSTICK_AXIS_MAX * DeadZone && !m_aInputState[RightKey])
{
m_aInputState[RightKey] = true;
m_aInputCount[RightKey] = m_InputCounter;
AddEvent(nullptr, RightKey, IInput::FLAG_PRESS);
}
else if(Event.value < SDL_JOYSTICK_AXIS_MAX * DeadZone && m_aInputState[RightKey])
{
m_aInputState[RightKey] = false;
AddEvent(nullptr, RightKey, IInput::FLAG_RELEASE);
}
}
void CInput::HandleJoystickButtonEvent(const SDL_JoyButtonEvent &Event)
{
if(!g_Config.m_InpControllerEnable)
return;
CJoystick *pJoystick = GetActiveJoystick();
if(!pJoystick || pJoystick->GetInstanceId() != Event.which)
return;
if(Event.button >= NUM_JOYSTICK_BUTTONS)
return;
const int Key = Event.button + KEY_JOYSTICK_BUTTON_0;
if(Event.type == SDL_JOYBUTTONDOWN)
{
m_aInputState[Key] = true;
m_aInputCount[Key] = m_InputCounter;
AddEvent(nullptr, Key, IInput::FLAG_PRESS);
}
else if(Event.type == SDL_JOYBUTTONUP)
{
m_aInputState[Key] = false;
AddEvent(nullptr, Key, IInput::FLAG_RELEASE);
}
}
void CInput::HandleJoystickHatMotionEvent(const SDL_JoyHatEvent &Event)
{
if(!g_Config.m_InpControllerEnable)
return;
CJoystick *pJoystick = GetActiveJoystick();
if(!pJoystick || pJoystick->GetInstanceId() != Event.which)
return;
if(Event.hat >= NUM_JOYSTICK_HATS)
return;
int HatKeys[2];
CJoystick::GetJoystickHatKeys(Event.hat, Event.value, HatKeys);
for(int Key = KEY_JOY_HAT0_UP + Event.hat * NUM_JOYSTICK_BUTTONS_PER_HAT; Key <= KEY_JOY_HAT0_DOWN + Event.hat * NUM_JOYSTICK_BUTTONS_PER_HAT; Key++)
{
if(Key != HatKeys[0] && Key != HatKeys[1] && m_aInputState[Key])
{
m_aInputState[Key] = false;
AddEvent(nullptr, Key, IInput::FLAG_RELEASE);
}
}
for(int CurrentKey : HatKeys)
{
if(CurrentKey != KEY_UNKNOWN && !m_aInputState[CurrentKey])
{
m_aInputState[CurrentKey] = true;
m_aInputCount[CurrentKey] = m_InputCounter;
AddEvent(nullptr, CurrentKey, IInput::FLAG_PRESS);
}
}
}
void CInput::HandleJoystickAddedEvent(const SDL_JoyDeviceEvent &Event)
{
if(OpenJoystick(Event.which))
{
UpdateActiveJoystick();
}
}
void CInput::HandleJoystickRemovedEvent(const SDL_JoyDeviceEvent &Event)
{
auto RemovedJoystick = std::find_if(m_vJoysticks.begin(), m_vJoysticks.end(), [Event](const CJoystick &Joystick) -> bool { return Joystick.GetInstanceId() == Event.which; });
if(RemovedJoystick != m_vJoysticks.end())
{
dbg_msg("joystick", "Closed joystick %d '%s'", (*RemovedJoystick).GetIndex(), (*RemovedJoystick).GetName());
auto NextJoystick = m_vJoysticks.erase(RemovedJoystick);
// Adjust indices of following joysticks
while(NextJoystick != m_vJoysticks.end())
{
(*NextJoystick).m_Index--;
++NextJoystick;
}
UpdateActiveJoystick();
}
}
void CInput::SetCompositionWindowPosition(float X, float Y, float H)
{
SDL_Rect Rect;
Rect.x = X / m_pGraphics->ScreenHiDPIScale();
Rect.y = Y / m_pGraphics->ScreenHiDPIScale();
Rect.h = H / m_pGraphics->ScreenHiDPIScale();
Rect.w = 0;
SDL_SetTextInputRect(&Rect);
}
int CInput::Update()
{
const int64_t Now = time_get();
if(m_LastUpdate != 0)
{
const float Diff = (Now - m_LastUpdate) / (float)time_freq();
m_UpdateTime = m_UpdateTime == 0.0f ? Diff : (m_UpdateTime * 0.8f + Diff * 0.2f);
}
m_LastUpdate = Now;
// keep the counter between 1..0xFFFF, 0 means not pressed
m_InputCounter = (m_InputCounter % 0xFFFF) + 1;
// Ensure that we have the latest keyboard, mouse and joystick state
SDL_PumpEvents();
int NumKeyStates;
const Uint8 *pState = SDL_GetKeyboardState(&NumKeyStates);
if(NumKeyStates >= KEY_MOUSE_1)
NumKeyStates = KEY_MOUSE_1;
mem_copy(m_aInputState, pState, NumKeyStates);
mem_zero(m_aInputState + NumKeyStates, KEY_LAST - NumKeyStates);
// these states must always be updated manually because they are not in the SDL_GetKeyboardState from SDL
UpdateMouseState();
UpdateJoystickState();
SDL_Event Event;
bool IgnoreKeys = false;
while(SDL_PollEvent(&Event))
{
int Scancode = 0;
int Action = IInput::FLAG_PRESS;
switch(Event.type)
{
case SDL_SYSWMEVENT:
ProcessSystemMessage(Event.syswm.msg);
break;
case SDL_TEXTEDITING:
{
m_CompositionLength = str_length(Event.edit.text);
if(m_CompositionLength)
{
str_copy(m_aComposition, Event.edit.text);
m_CompositionCursor = 0;
for(int i = 0; i < Event.edit.start; i++)
m_CompositionCursor = str_utf8_forward(m_aComposition, m_CompositionCursor);
// Event.edit.length is currently unused on Windows and will always be 0, so we don't support selecting composition text
AddEvent(nullptr, KEY_UNKNOWN, IInput::FLAG_TEXT);
}
else
{
m_aComposition[0] = '\0';
m_CompositionLength = 0;
m_CompositionCursor = 0;
}
break;
}
case SDL_TEXTINPUT:
m_aComposition[0] = '\0';
m_CompositionLength = COMP_LENGTH_INACTIVE;
m_CompositionCursor = 0;
AddEvent(Event.text.text, KEY_UNKNOWN, IInput::FLAG_TEXT);
break;
// handle keys
case SDL_KEYDOWN:
// See SDL_Keymod for possible modifiers:
// NONE = 0
// LSHIFT = 1
// RSHIFT = 2
// LCTRL = 64
// RCTRL = 128
// LALT = 256
// RALT = 512
// LGUI = 1024
// RGUI = 2048
// NUM = 4096
// CAPS = 8192
// MODE = 16384
// Sum if you want to ignore multiple modifiers.
if(!(Event.key.keysym.mod & g_Config.m_InpIgnoredModifiers))
{
Scancode = g_Config.m_InpTranslatedKeys ? SDL_GetScancodeFromKey(Event.key.keysym.sym) : Event.key.keysym.scancode;
}
break;
case SDL_KEYUP:
Action = IInput::FLAG_RELEASE;
Scancode = g_Config.m_InpTranslatedKeys ? SDL_GetScancodeFromKey(Event.key.keysym.sym) : Event.key.keysym.scancode;
break;
// handle the joystick events
case SDL_JOYAXISMOTION:
HandleJoystickAxisMotionEvent(Event.jaxis);
break;
case SDL_JOYBUTTONUP:
case SDL_JOYBUTTONDOWN:
HandleJoystickButtonEvent(Event.jbutton);
break;
case SDL_JOYHATMOTION:
HandleJoystickHatMotionEvent(Event.jhat);
break;
case SDL_JOYDEVICEADDED:
HandleJoystickAddedEvent(Event.jdevice);
break;
case SDL_JOYDEVICEREMOVED:
HandleJoystickRemovedEvent(Event.jdevice);
break;
// handle mouse buttons
case SDL_MOUSEBUTTONUP:
Action = IInput::FLAG_RELEASE;
[[fallthrough]];
case SDL_MOUSEBUTTONDOWN:
if(Event.button.button == SDL_BUTTON_LEFT)
Scancode = KEY_MOUSE_1;
if(Event.button.button == SDL_BUTTON_RIGHT)
Scancode = KEY_MOUSE_2;
if(Event.button.button == SDL_BUTTON_MIDDLE)
Scancode = KEY_MOUSE_3;
if(Event.button.button == SDL_BUTTON_X1)
Scancode = KEY_MOUSE_4;
if(Event.button.button == SDL_BUTTON_X2)
Scancode = KEY_MOUSE_5;
if(Event.button.button == 6)
Scancode = KEY_MOUSE_6;
if(Event.button.button == 7)
Scancode = KEY_MOUSE_7;
if(Event.button.button == 8)
Scancode = KEY_MOUSE_8;
if(Event.button.button == 9)
Scancode = KEY_MOUSE_9;
if(Event.button.button == SDL_BUTTON_LEFT)
{
if(Event.button.clicks % 2 == 0)
m_MouseDoubleClick = true;
if(Event.button.clicks == 1)
m_MouseDoubleClick = false;
}
break;
case SDL_MOUSEWHEEL:
if(Event.wheel.y > 0)
Scancode = KEY_MOUSE_WHEEL_UP;
if(Event.wheel.y < 0)
Scancode = KEY_MOUSE_WHEEL_DOWN;
if(Event.wheel.x > 0)
Scancode = KEY_MOUSE_WHEEL_LEFT;
if(Event.wheel.x < 0)
Scancode = KEY_MOUSE_WHEEL_RIGHT;
Action |= IInput::FLAG_RELEASE;
break;
case SDL_WINDOWEVENT:
// Ignore keys following a focus gain as they may be part of global
// shortcuts
switch(Event.window.event)
{
case SDL_WINDOWEVENT_MOVED:
Graphics()->Move(Event.window.data1, Event.window.data2);
break;
// listen to size changes, this includes our manual changes and the ones by the window manager
case SDL_WINDOWEVENT_SIZE_CHANGED:
Graphics()->GotResized(Event.window.data1, Event.window.data2, -1);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
if(m_InputGrabbed)
{
MouseModeRelative();
// Clear pending relative mouse motion
SDL_GetRelativeMouseState(nullptr, nullptr);
}
m_MouseFocus = true;
IgnoreKeys = true;
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
m_MouseFocus = false;
IgnoreKeys = true;
if(m_InputGrabbed)
{
MouseModeAbsolute();
// Remember that we had relative mouse
m_InputGrabbed = true;
}
break;
case SDL_WINDOWEVENT_MINIMIZED:
Graphics()->WindowDestroyNtf(Event.window.windowID);
break;
case SDL_WINDOWEVENT_MAXIMIZED:
#if defined(CONF_PLATFORM_MACOS) // Todo: remove this when fixed in SDL
MouseModeAbsolute();
MouseModeRelative();
#endif
[[fallthrough]];
case SDL_WINDOWEVENT_RESTORED:
Graphics()->WindowCreateNtf(Event.window.windowID);
break;
}
break;
// other messages
case SDL_QUIT:
return 1;
case SDL_DROPFILE:
str_copy(m_aDropFile, Event.drop.file);
SDL_free(Event.drop.file);
break;
}
if(Scancode > KEY_FIRST && Scancode < g_MaxKeys && !IgnoreKeys && !HasComposition())
{
if(Action & IInput::FLAG_PRESS)
{
m_aInputState[Scancode] = 1;
m_aInputCount[Scancode] = m_InputCounter;
}
AddEvent(nullptr, Scancode, Action);
}
}
if(m_CompositionLength == 0)
m_CompositionLength = COMP_LENGTH_INACTIVE;
return 0;
}
void CInput::ProcessSystemMessage(SDL_SysWMmsg *pMsg)
{
#if defined(CONF_FAMILY_WINDOWS)
// Todo SDL: remove this after SDL2 supports IME candidates
if(pMsg->subsystem == SDL_SYSWM_WINDOWS && pMsg->msg.win.msg == WM_IME_NOTIFY)
{
switch(pMsg->msg.win.wParam)
{
case IMN_OPENCANDIDATE:
case IMN_CHANGECANDIDATE:
{
HWND WindowHandle = pMsg->msg.win.hwnd;
HIMC ImeContext = ImmGetContext(WindowHandle);
DWORD Size = ImmGetCandidateListW(ImeContext, 0, nullptr, 0);
LPCANDIDATELIST pCandidateList = nullptr;
if(Size > 0)
{
pCandidateList = (LPCANDIDATELIST)malloc(Size);
Size = ImmGetCandidateListW(ImeContext, 0, pCandidateList, Size);
}
m_vCandidates.clear();
if(pCandidateList && Size > 0)
{
for(DWORD i = pCandidateList->dwPageStart; i < pCandidateList->dwCount && (int)m_vCandidates.size() < (int)pCandidateList->dwPageSize; i++)
{
LPCWSTR pCandidate = (LPCWSTR)((DWORD_PTR)pCandidateList + pCandidateList->dwOffset[i]);
m_vCandidates.push_back(std::move(windows_wide_to_utf8(pCandidate).value_or("<invalid candidate>")));
}
m_CandidateSelectedIndex = pCandidateList->dwSelection - pCandidateList->dwPageStart;
}
else
{
m_CandidateSelectedIndex = -1;
}
free(pCandidateList);
ImmReleaseContext(WindowHandle, ImeContext);
break;
}
case IMN_CLOSECANDIDATE:
m_vCandidates.clear();
m_CandidateSelectedIndex = -1;
break;
}
}
#endif
}
bool CInput::GetDropFile(char *aBuf, int Len)
{
if(m_aDropFile[0] != '\0')
{
str_copy(aBuf, m_aDropFile, Len);
m_aDropFile[0] = '\0';
return true;
}
return false;
}
IEngineInput *CreateEngineInput()
{
return new CInput;
}