/
inputsystem.cpp
1820 lines (1533 loc) · 51.8 KB
/
inputsystem.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
/** @file inputsystem.cpp Input subsystem.
*
* @authors Copyright © 2003-2014 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2014 Daniel Swanson <danij@dengine.net>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#define DENG_NO_API_MACROS_BINDING
#include "de_platform.h" // strdup macro
#include "ui/inputsystem.h"
#include <QList>
#include <QtAlgorithms>
#include <de/timer.h> // SECONDSPERTIC
#include <de/Record>
#include <de/NumberValue>
#include <doomsday/console/cmd.h>
#include <doomsday/console/var.h>
#include <doomsday/console/exec.h>
#include "clientapp.h"
#include "dd_def.h" // MAXEVENTS, ASSERT_NOT_64BIT
#include "dd_main.h" // App_GameLoaded()
#include "dd_loop.h" // DD_IsFrameTimeAdvancing()
#include "m_misc.h" // M_WriteTextEsc
#include "render/vr.h"
#include "world/p_players.h"
#include "BindContext"
#include "CommandBinding"
#include "ImpulseBinding"
#include "ui/ddevent.h"
#include "ui/b_util.h"
#include "ui/clientwindow.h"
#include "ui/clientwindowsystem.h"
#include "ui/inputdebug.h" // Debug visualization.
#include "ui/inputdevice.h"
#include "ui/inputdeviceaxiscontrol.h"
#include "ui/inputdevicebuttoncontrol.h"
#include "ui/inputdevicehatcontrol.h"
#include "ui/playerimpulse.h"
#include "ui/sys_input.h"
#include "sys_system.h" // novideo
using namespace de;
#define DEFAULT_JOYSTICK_DEADZONE .05f ///< 5%
#define MAX_AXIS_FILTER 40
static InputDevice *makeKeyboard(String const &name, String const &title = "")
{
InputDevice *keyboard = new InputDevice(name);
keyboard->setTitle(title);
// DDKEYs are used as button indices.
for(int i = 0; i < 256; ++i)
{
keyboard->addButton(new InputDeviceButtonControl);
}
return keyboard;
}
static InputDevice *makeMouse(String const &name, String const &title = "")
{
InputDevice *mouse = new InputDevice(name);
mouse->setTitle(title);
for(int i = 0; i < IMB_MAXBUTTONS; ++i)
{
mouse->addButton(new InputDeviceButtonControl);
}
// Some of the mouse buttons have symbolic names.
mouse->button(IMB_LEFT ).setName("left");
mouse->button(IMB_MIDDLE ).setName("middle");
mouse->button(IMB_RIGHT ).setName("right");
mouse->button(IMB_MWHEELUP ).setName("wheelup");
mouse->button(IMB_MWHEELDOWN ).setName("wheeldown");
mouse->button(IMB_MWHEELLEFT ).setName("wheelleft");
mouse->button(IMB_MWHEELRIGHT).setName("wheelright");
// The mouse wheel is translated to keys, so there is no need to
// create an axis for it.
InputDeviceAxisControl *axis;
mouse->addAxis(axis = new InputDeviceAxisControl("x", InputDeviceAxisControl::Pointer));
//axis->setFilter(1); // On by default.
axis->setScale(1.f/1000);
mouse->addAxis(axis = new InputDeviceAxisControl("y", InputDeviceAxisControl::Pointer));
//axis->setFilter(1); // On by default.
axis->setScale(1.f/1000);
return mouse;
}
static InputDevice *makeJoystick(String const &name, String const &title = "")
{
InputDevice *joy = new InputDevice(name);
joy->setTitle(title);
for(int i = 0; i < IJOY_MAXBUTTONS; ++i)
{
joy->addButton(new InputDeviceButtonControl);
}
for(int i = 0; i < IJOY_MAXAXES; ++i)
{
char name[32];
if(i < 4)
{
strcpy(name, i == 0? "x" : i == 1? "y" : i == 2? "z" : "w");
}
else
{
sprintf(name, "axis%02i", i + 1);
}
auto *axis = new InputDeviceAxisControl(name, InputDeviceAxisControl::Stick);
joy->addAxis(axis);
axis->setScale(1.0f / IJOY_AXISMAX);
axis->setDeadZone(DEFAULT_JOYSTICK_DEADZONE);
}
for(int i = 0; i < IJOY_MAXHATS; ++i)
{
joy->addHat(new InputDeviceHatControl);
}
return joy;
}
static InputDevice *makeHeadTracker(String const &name, String const &title)
{
InputDevice *head = new InputDevice(name);
head->setTitle(title);
auto *axis = new InputDeviceAxisControl("yaw", InputDeviceAxisControl::Stick);
head->addAxis(axis);
axis->setRawInput();
head->addAxis(axis = new InputDeviceAxisControl("pitch", InputDeviceAxisControl::Stick));
axis->setRawInput();
head->addAxis(axis = new InputDeviceAxisControl("roll", InputDeviceAxisControl::Stick));
axis->setRawInput();
return head;
}
static Value *Function_InputSystem_BindEvent(Context &, Function::ArgumentValues const &args)
{
String eventDesc = args[0]->asText();
String command = args[1]->asText();
if(ClientApp::inputSystem().bindCommand(eventDesc.toLatin1(), command.toLatin1()))
{
// Success.
return new NumberValue(true);
}
// Failed to create the binding...
return new NumberValue(false);
}
#if 0
struct repeater_t
{
int key; ///< The DDKEY code (@c 0 if not in use).
int native; ///< Used to determine which key is repeating.
char text[8]; ///< Text to insert.
timespan_t timer; ///< How's the time?
int count; ///< How many times has been repeated?
};
// The initial and secondary repeater delays (tics).
int repWait1 = 15;
int repWait2 = 3;
#endif
bool shiftDown;
bool altDown;
#ifdef OLD_FILTER
static uint mouseFreq;
#endif
static float oldPOV = IJOY_POV_CENTER;
static char *eventStrings[MAXEVENTS];
/**
* Returns a copy of the string @a str. The caller does not get ownership of
* the string. The string is valid until it gets overwritten by a new
* allocation. There are at most MAXEVENTS strings allocated at a time.
*
* These are intended for strings in ddevent_t that are valid during the
* processing of an event.
*/
static char const *allocEventString(char const *str)
{
DENG2_ASSERT(str);
static int eventStringRover = 0;
DENG2_ASSERT(eventStringRover >= 0 && eventStringRover < MAXEVENTS);
M_Free(eventStrings[eventStringRover]);
char const *returnValue = eventStrings[eventStringRover] = strdup(str);
if(++eventStringRover >= MAXEVENTS)
{
eventStringRover = 0;
}
return returnValue;
}
static void clearEventStrings()
{
for(int i = 0; i < MAXEVENTS; ++i)
{
M_Free(eventStrings[i]); eventStrings[i] = nullptr;
}
}
struct eventqueue_t
{
ddevent_t events[MAXEVENTS];
int head;
int tail;
};
/**
* Gets the next event from an input event queue.
* @param q Event queue.
* @return @c NULL if no more events are available.
*/
static ddevent_t *nextFromQueue(eventqueue_t *q)
{
DENG2_ASSERT(q);
if(q->head == q->tail)
return nullptr;
ddevent_t *ev = &q->events[q->tail];
q->tail = (q->tail + 1) & (MAXEVENTS - 1);
return ev;
}
static void clearQueue(eventqueue_t *q)
{
DENG2_ASSERT(q);
q->head = q->tail;
}
static void postToQueue(eventqueue_t *q, ddevent_t *ev)
{
DENG2_ASSERT(q && ev);
q->events[q->head] = *ev;
if(ev->type == E_SYMBOLIC)
{
// Allocate a throw-away string from our buffer.
q->events[q->head].symbolic.name = allocEventString(ev->symbolic.name);
}
q->head++;
q->head &= MAXEVENTS - 1;
}
static eventqueue_t queue;
static eventqueue_t sharpQueue;
static byte useSharpInputEvents = true; ///< cvar
DENG2_PIMPL(InputSystem)
, DENG2_OBSERVES(BindContext, ActiveChange)
, DENG2_OBSERVES(BindContext, AcquireDeviceChange)
, DENG2_OBSERVES(BindContext, BindingAddition)
{
bool ignoreInput = false;
SettingsRegister settings;
Binder binder;
Record *scriptBindings = nullptr;
typedef QList<InputDevice *> Devices;
Devices devices;
typedef QList<BindContext *> BindContexts;
BindContexts contexts; ///< Ordered from highest to lowest priority.
Instance(Public *i) : Base(i)
{
// Initialize settings.
settings.define(SettingsRegister::ConfigVariable, "input.mouse.syncSensitivity")
.define(SettingsRegister::FloatCVar, "input-mouse-x-scale", 1.f/1000.f)
.define(SettingsRegister::FloatCVar, "input-mouse-y-scale", 1.f/1000.f)
.define(SettingsRegister::IntCVar, "input-mouse-x-flags", 0)
.define(SettingsRegister::IntCVar, "input-mouse-y-flags", 0)
.define(SettingsRegister::IntCVar, "input-joy", 1)
.define(SettingsRegister::IntCVar, "input-sharp", 1);
// Initialize script bindings.
binder.initNew()
<< DENG2_FUNC(InputSystem_BindEvent, "bindEvent", "event" << "command");
App::scriptSystem().addNativeModule("Input", binder.module());
// Initialize system APIs.
I_InitInterfaces();
}
~Instance()
{
self.clearAllContexts();
clearAllDevices();
// Shutdown system APIs.
I_ShutdownInterfaces();
}
void clearAllDevices()
{
qDeleteAll(devices);
devices.clear();
}
/**
* @param device InputDevice to add.
* @return Same as @a device for caller convenience.
*/
InputDevice *addDevice(InputDevice *device)
{
if(device)
{
if(!devices.contains(device))
{
// Ensure the name is unique.
for(InputDevice *otherDevice : devices)
{
if(!otherDevice->name().compareWithoutCase(device->name()))
{
throw Error("InputSystem::addDevice", "Multiple devices with name:" + device->name() + " cannot coexist");
}
}
// Add this device to the collection.
devices.append(device);
}
}
return device;
}
void echoSymbolicEvent(ddevent_t const &ev)
{
DENG2_ASSERT(symbolicEchoMode);
// Some event types are never echoed.
if(ev.type == E_SYMBOLIC || ev.type == E_FOCUS) return;
// Input device axis controls can be pretty sensitive (or misconfigured)
// so we need to do some filtering to determine if the motion is strong
// enough for an echo.
if(ev.type == E_AXIS)
{
InputDevice const &device = self.device(ev.device);
float const pos = device.axis(ev.axis.id).translateRealPosition(ev.axis.pos);
if((ev.axis.type == EAXIS_ABSOLUTE && fabs(pos) < .5f) ||
(ev.axis.type == EAXIS_RELATIVE && fabs(pos) < .02f))
{
return; // Not significant enough.
}
}
// Echo the event.
String name = "echo-" + B_EventToString(ev);
Block const nameUtf8 = name.toUtf8();
ddevent_t echo; de::zap(echo);
echo.device = uint(-1);
echo.type = E_SYMBOLIC;
echo.symbolic.id = 0;
echo.symbolic.name = nameUtf8.constData();
LOG_INPUT_XVERBOSE("Symbolic echo: %s") << name;
self.postEvent(&echo);
}
/**
* Send all the events of the given timestamp down the responder chain.
*/
void dispatchEvents(eventqueue_t *q, timespan_t ticLength, bool updateAxes = true)
{
bool const callGameResponders = App_GameLoaded();
ddevent_t *ddev;
while((ddev = nextFromQueue(q)))
{
// Update the state of the input device tracking table.
self.trackEvent(*ddev);
if(ignoreInput && ddev->type != E_FOCUS)
continue;
event_t ev;
bool validGameEvent = false;
if(callGameResponders)
{
// Events must first be converted for the game responders.
validGameEvent = self.convertEvent(*ddev, ev);
}
if(callGameResponders && validGameEvent && gx.PrivilegedResponder)
{
// Does the game's special responder use this event? This is
// intended for grabbing events when creating bindings in the
// Controls menu.
if(gx.PrivilegedResponder(&ev))
{
continue;
}
}
if(symbolicEchoMode)
{
echoSymbolicEvent(*ddev);
continue;
}
// Try the binding system to see if we need to respond to the event
// and if so, trigger any associated actions.
if(self.tryEvent(*ddev))
{
continue;
}
// Try the "fallback" responder, which, gets the event if no one else
// is interested.
if(callGameResponders && validGameEvent && gx.FallbackResponder)
{
gx.FallbackResponder(&ev);
}
}
if(updateAxes)
{
// An event may have modified device-control state: update the axis positions.
for(InputDevice *device : devices)
{
device->forAllControls([&ticLength] (InputDeviceControl &ctrl)
{
if(auto *axis = ctrl.maybeAs<InputDeviceAxisControl>())
{
axis->update(ticLength);
}
return LoopContinue;
});
}
}
}
/**
* Poll all event sources (i.e., input devices) and post events.
*/
void postEventsForAllDevices()
{
readKeyboard();
readMouse();
readJoystick();
readHeadTracker();
}
/**
* Check the current keyboard state, generate input events based on pressed/held
* keys and poss them.
*
* @todo Does not belong at this level.
*/
void readKeyboard()
{
#define QUEUESIZE 32
if(novideo) return;
ddevent_t ev; de::zap(ev);
ev.device = IDEV_KEYBOARD;
ev.type = E_TOGGLE;
ev.toggle.state = ETOG_REPEAT;
// Read the new keyboard events, convert to ddevents and post them.
keyevent_t keyevs[QUEUESIZE];
size_t const numkeyevs = Keyboard_GetEvents(keyevs, QUEUESIZE);
for(size_t n = 0; n < numkeyevs; ++n)
{
keyevent_t *ke = &keyevs[n];
// Check the type of the event.
switch(ke->type)
{
case IKE_DOWN: ev.toggle.state = ETOG_DOWN; break;
case IKE_REPEAT: ev.toggle.state = ETOG_REPEAT; break;
case IKE_UP: ev.toggle.state = ETOG_UP; break;
default: break;
}
ev.toggle.id = ke->ddkey;
// Text content to insert?
DENG2_ASSERT(sizeof(ev.toggle.text) == sizeof(ke->text));
std::memcpy(ev.toggle.text, ke->text, sizeof(ev.toggle.text));
LOG_INPUT_XVERBOSE("toggle.id: %i/%c [%s:%u]")
<< ev.toggle.id << char(ev.toggle.id)
<< ev.toggle.text << strlen(ev.toggle.text);
self.postEvent(&ev);
}
#undef QUEUESIZE
}
/**
* Check the current mouse state (axis, buttons and wheel).
* Generates events and mickeys and posts them.
*
* @todo Does not belong at this level.
*/
void readMouse()
{
if(!Mouse_IsPresent())
return;
mousestate_t mouse;
#ifdef OLD_FILTER
// Should we test the mouse input frequency?
if(mouseFreq > 0)
{
static uint lastTime = 0;
uint nowTime = Timer_RealMilliseconds();
if(nowTime - lastTime < 1000 / mouseFreq)
{
// Don't ask yet.
std::memset(&mouse, 0, sizeof(mouse));
}
else
{
lastTime = nowTime;
Mouse_GetState(&mouse);
}
}
else
#endif
{
// Get the mouse state.
Mouse_GetState(&mouse);
}
ddevent_t ev; de::zap(ev);
ev.device = IDEV_MOUSE;
ev.type = E_AXIS;
float xpos = mouse.axis[IMA_POINTER].x;
float ypos = mouse.axis[IMA_POINTER].y;
/*if(uiMouseMode)
{
ev.axis.type = EAXIS_ABSOLUTE;
}
else*/
{
ev.axis.type = EAXIS_RELATIVE;
ypos = -ypos;
}
// Post an event per axis.
// Don't post empty events.
if(xpos)
{
ev.axis.id = 0;
ev.axis.pos = xpos;
self.postEvent(&ev);
}
if(ypos)
{
ev.axis.id = 1;
ev.axis.pos = ypos;
self.postEvent(&ev);
}
// Some very verbose output about mouse buttons.
int i = 0;
for(; i < IMB_MAXBUTTONS; ++i)
{
if(mouse.buttonDowns[i] || mouse.buttonUps[i])
break;
}
if(i < IMB_MAXBUTTONS)
{
for(i = 0; i < IMB_MAXBUTTONS; ++i)
{
LOGDEV_INPUT_XVERBOSE("[%02i] %i/%i")
<< i << mouse.buttonDowns[i] << mouse.buttonUps[i];
}
}
// Post mouse button up and down events.
ev.type = E_TOGGLE;
for(i = 0; i < IMB_MAXBUTTONS; ++i)
{
ev.toggle.id = i;
while(mouse.buttonDowns[i] > 0 || mouse.buttonUps[i] > 0)
{
if(mouse.buttonDowns[i]-- > 0)
{
ev.toggle.state = ETOG_DOWN;
LOG_INPUT_XVERBOSE("Mouse button %i down") << i;
self.postEvent(&ev);
}
if(mouse.buttonUps[i]-- > 0)
{
ev.toggle.state = ETOG_UP;
LOG_INPUT_XVERBOSE("Mouse button %i up") << i;
self.postEvent(&ev);
}
}
}
}
/**
* Check the current joystick state (axis, sliders, hat and buttons).
* Generates events and posts them. Axis clamps and dead zone is done
* here.
*
* @todo Does not belong at this level.
*/
void readJoystick()
{
if(!Joystick_IsPresent())
return;
joystate_t state;
Joystick_GetState(&state);
// Joystick buttons.
ddevent_t ev; de::zap(ev);
ev.device = IDEV_JOY1;
ev.type = E_TOGGLE;
for(int i = 0; i < state.numButtons; ++i)
{
ev.toggle.id = i;
while(state.buttonDowns[i] > 0 || state.buttonUps[i] > 0)
{
if(state.buttonDowns[i]-- > 0)
{
ev.toggle.state = ETOG_DOWN;
self.postEvent(&ev);
LOG_INPUT_XVERBOSE("Joy button %i down") << i;
}
if(state.buttonUps[i]-- > 0)
{
ev.toggle.state = ETOG_UP;
self.postEvent(&ev);
LOG_INPUT_XVERBOSE("Joy button %i up") << i;
}
}
}
if(state.numHats > 0)
{
// Check for a POV change.
/// @todo: Some day it would be nice to support multiple hats here. -jk
if(state.hatAngle[0] != oldPOV)
{
ev.type = E_ANGLE;
ev.angle.id = 0;
if(state.hatAngle[0] < 0)
{
ev.angle.pos = -1;
}
else
{
// The new angle becomes active.
ev.angle.pos = ROUND(state.hatAngle[0] / 45);
}
self.postEvent(&ev);
oldPOV = state.hatAngle[0];
}
}
// Send joystick axis events, one per axis.
ev.type = E_AXIS;
for(int i = 0; i < state.numAxes; ++i)
{
ev.axis.id = i;
ev.axis.pos = state.axis[i];
ev.axis.type = EAXIS_ABSOLUTE;
self.postEvent(&ev);
}
}
/// @todo Does not belong at this level.
void readHeadTracker()
{
// These values are for the input subsystem and gameplay. The renderer will
// check the head orientation independently, with as little latency as possible.
// If a head tracking device is connected, the device is marked active.
if(!DD_GetInteger(DD_USING_HEAD_TRACKING))
{
self.device(IDEV_HEAD_TRACKER).deactivate();
return;
}
self.device(IDEV_HEAD_TRACKER).activate();
// Get the latest values.
//vrCfg().oculusRift().allowUpdate();
//vrCfg().oculusRift().update();
ddevent_t ev; de::zap(ev);
ev.device = IDEV_HEAD_TRACKER;
ev.type = E_AXIS;
ev.axis.type = EAXIS_ABSOLUTE;
Vector3f const pry = vrCfg().oculusRift().headOrientation();
// Yaw (1.0 means 180 degrees).
ev.axis.id = 0; // Yaw.
ev.axis.pos = de::radianToDegree(pry[2]) * 1.0 / 180.0;
self.postEvent(&ev);
ev.axis.id = 1; // Pitch (1.0 means 85 degrees).
ev.axis.pos = de::radianToDegree(pry[0]) * 1.0 / 85.0;
self.postEvent(&ev);
// So I'll assume that if roll ever gets used, 1.0 will mean 180 degrees there too.
ev.axis.id = 2; // Roll.
ev.axis.pos = de::radianToDegree(pry[1]) * 1.0 / 180.0;
self.postEvent(&ev);
}
/**
* Mark all device states with the highest-priority binding context to which they
* have a connection via device bindings. This ensures that if a high-priority context
* is using a particular device state, lower-priority contexts will not be using the
* same state for their own controls.
*
* Called automatically whenever a context is activated or deactivated.
*/
void updateAllDeviceStateAssociations()
{
auto &_self = self;
// Clear all existing associations.
for(InputDevice *device : devices)
{
device->forAllControls([] (InputDeviceControl &ctrl)
{
ctrl.clearBindContextAssociation();
return LoopContinue;
});
}
// Mark all bindings in all contexts.
for(BindContext *context : contexts)
{
// Skip inactive contexts.
if(!context->isActive())
continue;
context->forAllCommandBindings([&_self, &context] (Record &rec)
{
CommandBinding bind(rec);
InputDeviceControl *ctrl = nullptr;
switch(bind.geti("type"))
{
case E_AXIS: ctrl = &_self.device(bind.geti("deviceId")).axis (bind.geti("controlId")); break;
case E_TOGGLE: ctrl = &_self.device(bind.geti("deviceId")).button(bind.geti("controlId")); break;
case E_ANGLE: ctrl = &_self.device(bind.geti("deviceId")).hat (bind.geti("controlId")); break;
case E_SYMBOLIC: break;
default:
DENG2_ASSERT(!"InputSystem::updateAllDeviceStateAssociations: Invalid bind.type");
break;
}
if(ctrl && !ctrl->hasBindContext())
{
ctrl->setBindContext(context);
}
return LoopContinue;
});
// Associate all the device bindings.
context->forAllImpulseBindings([&_self, &context] (Record &rec)
{
ImpulseBinding bind(rec);
InputDevice &dev = _self.device(bind.geti("deviceId"));
InputDeviceControl *ctrl = nullptr;
switch(bind.geti("type"))
{
case IBD_AXIS: ctrl = &dev.axis (bind.geti("controlId")); break;
case IBD_TOGGLE: ctrl = &dev.button(bind.geti("controlId")); break;
case IBD_ANGLE: ctrl = &dev.hat (bind.geti("controlId")); break;
default:
DENG2_ASSERT(!"InputSystem::updateAllDeviceStateAssociations: Invalid bind.type");
break;
}
if(ctrl && !ctrl->hasBindContext())
{
ctrl->setBindContext(context);
}
return LoopContinue;
});
// If the context have made a broad device acquisition, mark all relevant states.
for(int i = 0; i < devices.count(); ++i)
{
InputDevice *device = devices.at(i);
int const deviceId = i;
if(device->isActive() && context->willAcquire(deviceId))
{
device->forAllControls([&context] (InputDeviceControl &ctrl)
{
if(!ctrl.hasBindContext())
{
ctrl.setBindContext(context);
}
return LoopContinue;
});
}
};
}
// Now that we know what are the updated context associations, let's check
// the devices and see if any of the states need to be expired.
for(InputDevice *device : devices)
{
device->forAllControls([] (InputDeviceControl &ctrl)
{
if(!ctrl.inDefaultState())
{
ctrl.expireBindContextAssociationIfChanged();
}
return LoopContinue;
});
};
}
/**
* When the active state of a binding context changes we'll re-evaluate the
* effective bindings to avoid wasting time by looking them up repeatedly.
*/
void bindContextActiveChanged(BindContext &context)
{
updateAllDeviceStateAssociations();
for(int i = 0; i < devices.count(); ++i)
{
InputDevice *device = devices.at(i);
int const deviceId = i;
if(context.willAcquire(deviceId))
{
device->reset();
}
}
}
void bindContextAcquireDeviceChanged(BindContext &)
{
updateAllDeviceStateAssociations();
}
void bindContextBindingAdded(BindContext &, Record & /*binding*/, bool /*isCommand*/)
{
updateAllDeviceStateAssociations();
}
};
InputSystem::InputSystem() : d(new Instance(this))
{
initAllDevices();
}
void InputSystem::timeChanged(Clock const &)
{}
SettingsRegister &InputSystem::settings()
{
return d->settings;
}
InputDevice &InputSystem::device(int id) const
{
if(id >= 0 && id < d->devices.count())
{
return *d->devices.at(id);
}
/// @throw MissingDeviceError Given id is not valid.
throw MissingDeviceError("InputSystem::device", "Unknown id:" + String::number(id));
}
InputDevice *InputSystem::devicePtr(int id) const
{
if(id >= 0 && id < d->devices.count())
{
return d->devices.at(id);
}
return nullptr;
}
LoopResult InputSystem::forAllDevices(std::function<LoopResult (InputDevice &)> func) const
{
for(InputDevice *device : d->devices)
{
if(auto result = func(*device)) return result;
}
return LoopContinue;
}
int InputSystem::deviceCount() const
{
return d->devices.count();
}
void InputSystem::initAllDevices()
{
d->clearAllDevices();
// Initialize devices.
d->addDevice(makeKeyboard("key", "Keyboard"))->activate(); // A keyboard is assumed to always be present.
d->addDevice(makeMouse("mouse", "Mouse"))->activate(Mouse_IsPresent()); // A mouse may not be present.
d->addDevice(makeJoystick("joy", "Joystick"))->activate(Joystick_IsPresent()); // A joystick may not be present.
/// @todo: Add support for multiple joysticks (just some generics, for now).
d->addDevice(new InputDevice("joy2"));
d->addDevice(new InputDevice("joy3"));
d->addDevice(new InputDevice("joy4"));
d->addDevice(makeHeadTracker("head", "Head Tracker")); // Head trackers are activated later.
// Register console variables for the controls of all devices.
for(InputDevice *device : d->devices) device->consoleRegister();
}
bool InputSystem::ignoreEvents(bool yes)
{
LOG_AS("InputSystem");
bool const oldIgnoreInput = d->ignoreInput;
d->ignoreInput = yes;
LOG_INPUT_VERBOSE("Ignoring events: %b") << yes;
if(!yes)
{
// Clear all the event buffers.
d->postEventsForAllDevices();
clearEvents();
}
return oldIgnoreInput;
}
void InputSystem::clearEvents()
{
clearQueue(&queue);