-
-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathgamepad_device.cpp
More file actions
952 lines (877 loc) · 24.9 KB
/
gamepad_device.cpp
File metadata and controls
952 lines (877 loc) · 24.9 KB
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
/*
Copyright 2019 flyinghead
This file is part of reicast.
reicast 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.
reicast 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 reicast. If not, see <https://www.gnu.org/licenses/>.
*/
#include "gamepad_device.h"
#include "cfg/cfg.h"
#include "stdclass.h"
#include "ui/gui.h"
#include "emulator.h"
#include "hw/maple/maple_devs.h"
#include "mouse.h"
#include <algorithm>
#include <mutex>
#include <vector>
#define MAPLE_PORT_CFG_PREFIX "maple_"
// Gamepads
u32 kcode[4] = { ~0u, ~0u, ~0u, ~0u };
s16 joyx[4];
s16 joyy[4];
s16 joyrx[4];
s16 joyry[4];
s16 joy3x[4];
s16 joy3y[4];
u16 rt[4];
u16 lt[4];
u16 lt2[4];
u16 rt2[4];
// Keyboards
u8 kb_shift[MAPLE_PORTS]; // shift keys pressed (bitmask)
u8 kb_key[MAPLE_PORTS][6]; // normal keys pressed
std::vector<std::shared_ptr<GamepadDevice>> GamepadDevice::_gamepads;
std::mutex GamepadDevice::_gamepads_mutex;
#ifdef TEST_AUTOMATION
#include "hw/sh4/sh4_sched.h"
#include <cstdio>
static FILE *record_input;
#endif
GamepadDevice::GamepadDevice(int maple_port, const char *api_name, bool remappable)
: _api_name(api_name), _maple_port(maple_port), _remappable(remappable),
digitalToAnalogState{}
{
EventManager::listen(Event::LocaleChange, emuEvent, this);
// Initialize pressedButtons sets
currentInputs.clear();
}
GamepadDevice::~GamepadDevice() {
EventManager::unlisten(Event::LocaleChange, emuEvent, this);
}
void GamepadDevice::emuEvent(Event event, void *arg) {
((GamepadDevice *)arg)->refreshName();
}
bool GamepadDevice::handleButtonInput(int port, DreamcastKey key, bool pressed)
{
if (key == EMU_BTN_NONE)
return false;
if (buttonListener != nullptr)
buttonListener(port, key, pressed);
DEBUG_LOG(INPUT, "%d: BUTTON %s %d. kcode=%x", port, pressed ? "down" : "up", key, port >= 0 ? kcode[port] : 0);
if (key <= DC_BTN_BITMAPPED_LAST)
{
if (port < 0)
return false;
if (pressed)
kcode[port] &= ~key;
else
kcode[port] |= key;
#ifdef TEST_AUTOMATION
if (record_input != NULL)
fprintf(record_input, "%ld button %x %04x\n", sh4_sched_now64(), port, kcode[port]);
#endif
}
else
{
switch (key)
{
case EMU_BTN_ESCAPE:
if (pressed)
dc_exit();
break;
case EMU_BTN_MENU:
if (pressed)
gui_open_settings();
break;
case EMU_BTN_FFORWARD:
if (pressed && !gui_is_open())
settings.input.fastForwardMode = !settings.input.fastForwardMode && !settings.network.online && !settings.naomi.multiboard;
break;
case EMU_BTN_LOADSTATE:
if (pressed)
gui_loadState();
break;
case EMU_BTN_SAVESTATE:
if (pressed)
gui_saveState();
break;
case EMU_BTN_NEXTSLOT:
if (pressed)
gui_cycleSaveStateSlot(1);
break;
case EMU_BTN_PREVSLOT:
if (pressed)
gui_cycleSaveStateSlot(-1);
break;
case EMU_BTN_LOADSTATE_RAM:
if (pressed)
gui_loadState(true);
break;
case EMU_BTN_SAVESTATE_RAM:
if (pressed)
gui_saveState(false, true);
break;
case EMU_BTN_SCREENSHOT:
if (pressed)
gui_takeScreenshot();
break;
case DC_AXIS_LT:
if (port >= 0)
lt[port] = pressed ? 0xffff : 0;
break;
case DC_AXIS_RT:
if (port >= 0)
rt[port] = pressed ? 0xffff : 0;
break;
case DC_AXIS_LT2:
if (port >= 0)
lt2[port] = pressed ? 0xffff : 0;
break;
case DC_AXIS_RT2:
if (port >= 0)
rt2[port] = pressed ? 0xffff : 0;
break;
case DC_AXIS_UP:
case DC_AXIS_DOWN:
buttonToAnalogInput<DC_AXIS_UP, DIGANA_UP, DIGANA_DOWN>(port, key, pressed, joyy[port]);
break;
case DC_AXIS_LEFT:
case DC_AXIS_RIGHT:
buttonToAnalogInput<DC_AXIS_LEFT, DIGANA_LEFT, DIGANA_RIGHT>(port, key, pressed, joyx[port]);
break;
case DC_AXIS2_UP:
case DC_AXIS2_DOWN:
buttonToAnalogInput<DC_AXIS2_UP, DIGANA2_UP, DIGANA2_DOWN>(port, key, pressed, joyry[port]);
break;
case DC_AXIS2_LEFT:
case DC_AXIS2_RIGHT:
buttonToAnalogInput<DC_AXIS2_LEFT, DIGANA2_LEFT, DIGANA2_RIGHT>(port, key, pressed, joyrx[port]);
break;
case DC_AXIS3_UP:
case DC_AXIS3_DOWN:
buttonToAnalogInput<DC_AXIS3_UP, DIGANA3_UP, DIGANA3_DOWN>(port, key, pressed, joy3y[port]);
break;
case DC_AXIS3_LEFT:
case DC_AXIS3_RIGHT:
buttonToAnalogInput<DC_AXIS3_LEFT, DIGANA3_LEFT, DIGANA3_RIGHT>(port, key, pressed, joy3x[port]);
break;
default:
return false;
}
}
return true;
}
bool GamepadDevice::handleButtonInputDef(const InputMapping::InputDef& inputDef, bool pressed)
{
if (!input_mapper || _maple_port > (int)std::size(kcode))
return false;
// Update button press tracking
std::list<DreamcastKey> mappedKeys;
if (pressed)
{
// Add to triggered inputs
if (currentInputs.insert_back(inputDef))
{
// Handle keys activated by this new input
DreamcastKey mappedKey = input_mapper->get_button_id(0, currentInputs);
if (mappedKey != EMU_BTN_NONE) {
mappedKeys.push_back(mappedKey);
currentKeys.push_back(mappedKey);
}
}
}
else
{
// Remove from triggered inputs
if (currentInputs.remove(inputDef) > 0)
{
// Handle keys deactivated by this new input
mappedKeys = input_mapper->get_button_released_ids(0, currentKeys, inputDef);
for (const DreamcastKey& mappedKey : mappedKeys)
currentKeys.remove(mappedKey);
}
}
bool rc = false;
for (const DreamcastKey& mappedKey : mappedKeys)
rc = handleButtonInput(_maple_port == 4 ? 0 : _maple_port, mappedKey, pressed) || rc;
// Handle inputs for ports 1 to 3 in all-ports mode
// Combos are only detected on port 0 in this mode
if (_maple_port == 4)
{
const InputMapping::InputSet simpleInput{inputDef};
for (int port = 1; port < 4; port++) {
DreamcastKey mappedKey = input_mapper->get_button_id(port, simpleInput);
rc = handleButtonInput(port, mappedKey, pressed) || rc;
}
}
return rc;
}
bool GamepadDevice::gamepad_btn_input(u32 code, bool pressed)
{
const InputMapping::InputDef inputDef = InputMapping::InputDef::from_button(code);
// When detecting input for button mapping
if (_input_detected != nullptr && getTimeMs() >= _detection_start_time)
{
if (pressed)
{
// Button pressed - add to mapping and tracking
_input_detected(code, false, false);
detectionInputs.insert_back(inputDef);
// If we're not in combo detection mode, stop detecting after first button
if (!_detecting_combo)
{
_input_detected = nullptr;
detectionInputs.clear();
}
}
else if (_detecting_combo && detectionInputs.contains(inputDef))
{
// Button released - if this is a button we pressed during detection, end detection
_input_detected = nullptr;
detectionInputs.clear();
DEBUG_LOG(INPUT, "Ending combo detection on button release: %d", code);
}
return true;
}
return handleButtonInputDef(inputDef, pressed);
}
static DreamcastKey getOppositeAxis(DreamcastKey key)
{
switch (key)
{
case DC_AXIS_RIGHT: return DC_AXIS_LEFT;
case DC_AXIS_LEFT: return DC_AXIS_RIGHT;
case DC_AXIS_UP: return DC_AXIS_DOWN;
case DC_AXIS_DOWN: return DC_AXIS_UP;
case DC_AXIS2_RIGHT: return DC_AXIS2_LEFT;
case DC_AXIS2_LEFT: return DC_AXIS2_RIGHT;
case DC_AXIS2_UP: return DC_AXIS2_DOWN;
case DC_AXIS2_DOWN: return DC_AXIS2_UP;
case DC_AXIS3_RIGHT: return DC_AXIS3_LEFT;
case DC_AXIS3_LEFT: return DC_AXIS3_RIGHT;
case DC_AXIS3_UP: return DC_AXIS3_DOWN;
case DC_AXIS3_DOWN: return DC_AXIS3_UP;
default: return key;
}
}
bool GamepadDevice::detectAxis(u32 code, int value)
{
if (_input_detected == nullptr || getTimeMs() < _detection_start_time)
return false;
const auto& r = detectingAxes.try_emplace(code, value);
DetectingAxis& axis = r.first->second;
if (!r.second)
axis.setValue(value);
if (!axis.detected)
return false;
const bool isTrigger = axis.start != DetectingAxis::Zero;
const bool positive = isTrigger || axis.end == DetectingAxis::Positive;
const InputMapping::InputDef inputDef = InputMapping::InputDef::from_axis(code, positive);
// When in combo detection, track button releases for axes too
if (_detecting_combo && axis.released)
{
// If this is an axis we previously detected as pressed, end detection
if (detectionInputs.contains(inputDef))
{
_input_detected = nullptr;
detectionInputs.clear();
DEBUG_LOG(INPUT, "Ending combo detection on axis release: %d", code);
}
return false;
}
if (input_mapper != nullptr)
{
if (!isTrigger)
input_mapper->deleteTrigger(code);
else
input_mapper->addTrigger(code, axis.start == DetectingAxis::Positive);
}
// If we're in combo detection mode, add this axis to tracking but don't end detection
if (_detecting_combo)
{
// Track this axis as a "button" for combo detection
if (detectionInputs.insert_back(inputDef))
_input_detected(code, true, positive);
}
else
{
_input_detected(code, true, positive);
_input_detected = nullptr;
}
return true;
}
//
// value must be >= -32768 and <= 32767 for all axes
//
bool GamepadDevice::gamepad_axis_input(u32 code, int value)
{
if (detectAxis(code, value))
return true;
if (!input_mapper || _maple_port < 0 || _maple_port > 4)
return false;
const bool positive = input_mapper->isTrigger(code) || value >= 0;
const InputMapping::InputDef inputDef = InputMapping::InputDef::from_axis(code, positive);
auto handle_axis = [&](u32 port, DreamcastKey key, int v, u32 code)
{
if ((key & DC_BTN_GROUP_MASK) == DC_AXIS_TRIGGERS) // Triggers
{
int mv;
if (input_mapper->isTrigger(code))
{
mv = v + 32768;
if (input_mapper->isReverseTrigger(code))
mv = 65535 - mv;
}
else {
mv = std::min(std::abs(v) * 2, 0xffff);
}
//printf("T-AXIS %d Mapped to %d -> %d\n", key, v, mv);
if (key == DC_AXIS_LT)
lt[port] = mv;
else if (key == DC_AXIS_RT)
rt[port] = mv;
else if (key == DC_AXIS_LT2)
lt2[port] = mv;
else if (key == DC_AXIS_RT2)
rt2[port] = mv;
else
return false;
}
else if ((key & DC_BTN_GROUP_MASK) == DC_AXIS_STICKS) // Analog axes
{
//printf("AXIS %d Mapped to %d -> %d\n", key, value, v);
s16 *this_axis;
int otherAxisValue;
int axisDirection = -1;
switch (key)
{
case DC_AXIS_RIGHT:
axisDirection = 1;
[[fallthrough]];
case DC_AXIS_LEFT:
this_axis = &joyx[port];
otherAxisValue = lastAxisValue[port][DC_AXIS_UP];
break;
case DC_AXIS_DOWN:
axisDirection = 1;
[[fallthrough]];
case DC_AXIS_UP:
this_axis = &joyy[port];
otherAxisValue = lastAxisValue[port][DC_AXIS_LEFT];
break;
case DC_AXIS2_RIGHT:
axisDirection = 1;
[[fallthrough]];
case DC_AXIS2_LEFT:
this_axis = &joyrx[port];
otherAxisValue = lastAxisValue[port][DC_AXIS2_UP];
break;
case DC_AXIS2_DOWN:
axisDirection = 1;
[[fallthrough]];
case DC_AXIS2_UP:
this_axis = &joyry[port];
otherAxisValue = lastAxisValue[port][DC_AXIS2_LEFT];
break;
case DC_AXIS3_RIGHT:
axisDirection = 1;
[[fallthrough]];
case DC_AXIS3_LEFT:
this_axis = &joy3x[port];
otherAxisValue = lastAxisValue[port][DC_AXIS3_UP];
break;
case DC_AXIS3_DOWN:
axisDirection = 1;
[[fallthrough]];
case DC_AXIS3_UP:
this_axis = &joy3y[port];
otherAxisValue = lastAxisValue[port][DC_AXIS3_LEFT];
break;
default:
return false;
}
int& lastValue = lastAxisValue[port][key];
int& lastOpValue = lastAxisValue[port][getOppositeAxis(key)];
if (lastValue != v || lastOpValue != v)
{
lastValue = lastOpValue = v;
// Lightgun with left analog stick
if (key == DC_AXIS_RIGHT || key == DC_AXIS_LEFT)
mo_x_abs[port] = (std::abs(v) * axisDirection + 32768) * 639 / 65535;
else if (key == DC_AXIS_UP || key == DC_AXIS_DOWN)
mo_y_abs[port] = (std::abs(v) * axisDirection + 32768) * 479 / 65535;
}
// Radial dead zone
// FIXME compute both axes at the same time
const float nv = std::abs(v) / 32768.f;
const float r2 = nv * nv + otherAxisValue * otherAxisValue / 32768.f / 32768.f;
if (r2 < input_mapper->dead_zone * input_mapper->dead_zone || r2 == 0.f)
{
*this_axis = 0;
}
else
{
float pdz = nv * input_mapper->dead_zone / std::sqrt(r2);
// there's a dead angular zone at 45° with saturation > 1 (both axes are saturated)
v = std::round((nv - pdz) / (1 - pdz) * 32768.f * input_mapper->saturation);
*this_axis = std::clamp(v * axisDirection, -32768, 32767);
}
}
else if (key != EMU_BTN_NONE && key <= DC_BTN_BITMAPPED_LAST) // Map triggers to digital buttons
{
//printf("B-AXIS %d Mapped to %d -> %d\n", key, value, v);
// TODO hysteresis?
bool pressed = false;
if (input_mapper->isTrigger(code))
{
if (!input_mapper->isReverseTrigger(code))
pressed = v >= -32768 + 100; // positive range -32768 -> 32767
else
pressed = v <= 32767 - 100; // negative range 32767 -> -32768
}
else {
pressed = std::abs(v) >= AXIS_ACTIVATION_VALUE;
}
if (pressed)
kcode[port] &= ~key; // button pressed
else
kcode[port] |= key; // button released
}
else if ((key & DC_BTN_GROUP_MASK) == EMU_BUTTONS) // Map triggers to emu buttons
{
int lastValue = lastAxisValue[port][key];
if (input_mapper->isTrigger(code))
{
// 0 is the midpoint for half axes
if ((v >= 0) != (lastValue >= 0))
handleButtonInput(port, key, input_mapper->isReverseTrigger(code) == (v < 0));
}
else
{
lastValue = std::abs(lastValue);
int newValue = std::abs(v);
if ((lastValue < AXIS_ACTIVATION_VALUE && newValue >= AXIS_ACTIVATION_VALUE) || (lastValue >= AXIS_ACTIVATION_VALUE && newValue < AXIS_ACTIVATION_VALUE))
handleButtonInput(port, key, newValue >= AXIS_ACTIVATION_VALUE);
}
lastAxisValue[port][key] = v;
}
else
return false;
return true;
};
bool rc = false;
if (_maple_port == 4)
{
for (u32 port = 0; port < 4; port++)
{
if (!input_mapper->isTrigger(code)) {
DreamcastKey key = input_mapper->get_axis_id(port, code, !positive);
// Reset opposite axis to 0
handle_axis(port, key, 0, code);
}
DreamcastKey key = input_mapper->get_axis_id(port, code, positive);
rc = handle_axis(port, key, value, code) || rc;
}
}
else
{
if (!input_mapper->isTrigger(code)) {
DreamcastKey key = input_mapper->get_axis_id(0, code, !positive);
// Reset opposite axis to 0
handle_axis(_maple_port, key, 0, code);
}
DreamcastKey key = input_mapper->get_axis_id(0, code, positive);
rc = handle_axis(_maple_port, key, value, code);
}
// Update axis press tracking for button combinations
bool pressed = false;
bool released = false;
if (input_mapper->isTrigger(code))
{
if (!input_mapper->isReverseTrigger(code))
pressed = value >= -32768 + 100; // normal range -32768 -> 32767
else
pressed = value <= 32767 - 100; // reverse range 32767 -> -32768
released = !pressed;
}
else {
pressed = std::abs(value) >= AXIS_ACTIVATION_VALUE;
released = std::abs(value) < AXIS_ACTIVATION_VALUE;
}
if (pressed || released)
{
// Reset opposite axis to 0
if (!input_mapper->isTrigger(code)) {
const InputMapping::InputDef inverseInputDef = InputMapping::InputDef::from_axis(code, !positive);
rc = handleButtonInputDef(inverseInputDef, false) || rc;
}
rc = handleButtonInputDef(inputDef, pressed) || rc;
}
return rc;
}
void GamepadDevice::load_system_mappings()
{
for (int i = 0; i < GetGamepadCount(); i++)
{
std::shared_ptr<GamepadDevice> gamepad = GetGamepad(i);
if (gamepad != nullptr && !gamepad->find_mapping())
gamepad->resetMappingToDefault(settings.platform.isArcade(), true);
}
}
std::string GamepadDevice::make_mapping_filename(bool instance, int system, bool perGame /* = false */)
{
std::string mapping_file = api_name() + "_" + name();
if (instance)
mapping_file += "-" + _unique_id;
if (perGame && !settings.content.gameId.empty())
mapping_file += "_" + settings.content.gameId;
if (system != DC_PLATFORM_DREAMCAST)
mapping_file += "_arcade";
std::replace(mapping_file.begin(), mapping_file.end(), '/', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '\\', '-');
std::replace(mapping_file.begin(), mapping_file.end(), ':', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '?', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '*', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '|', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '"', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '<', '-');
std::replace(mapping_file.begin(), mapping_file.end(), '>', '-');
mapping_file += ".cfg";
return mapping_file;
}
bool GamepadDevice::find_mapping(int system /* = settings.platform.system */)
{
// FIXME this is called on Event::Start in the game loader thread
// race condition with the UI thread?
if (!_remappable)
return true;
instanceMapping = false;
bool cloneMapping = false;
while (true)
{
bool perGame = !settings.content.gameId.empty();
while (true)
{
std::string mapping_file = make_mapping_filename(true, system, perGame);
input_mapper = InputMapping::LoadMapping(mapping_file);
if (!input_mapper)
{
mapping_file = make_mapping_filename(false, system, perGame);
input_mapper = InputMapping::LoadMapping(mapping_file);
}
else
{
instanceMapping = true;
}
if (!!input_mapper)
{
if (cloneMapping)
input_mapper = std::make_shared<InputMapping>(*input_mapper);
perGameMapping = perGame;
rumblePower = input_mapper->rumblePower;
return true;
}
if (!perGame)
break;
perGame = false;
}
if (system == DC_PLATFORM_DREAMCAST)
break;
system = DC_PLATFORM_DREAMCAST;
cloneMapping = true;
}
return false;
}
int GamepadDevice::GetGamepadCount() {
Lock _(_gamepads_mutex);
return _gamepads.size();
}
std::shared_ptr<GamepadDevice> GamepadDevice::GetGamepad(int index)
{
Lock _(_gamepads_mutex);
if (index >= 0 && index < (int)_gamepads.size())
return _gamepads[index];
else
return nullptr;
}
void GamepadDevice::save_mapping(int system /* = settings.platform.system */)
{
if (!input_mapper)
return;
std::string filename = make_mapping_filename(instanceMapping, system, perGameMapping);
InputMapping::SaveMapping(filename, input_mapper);
}
void GamepadDevice::setPerGameMapping(bool enabled)
{
perGameMapping = enabled;
if (enabled)
input_mapper = std::make_shared<InputMapping>(*input_mapper);
else
{
auto deleteMapping = [this](bool instance, int system) {
std::string filename = make_mapping_filename(instance, system, true);
InputMapping::DeleteMapping(filename);
};
deleteMapping(false, DC_PLATFORM_DREAMCAST);
deleteMapping(false, DC_PLATFORM_NAOMI);
deleteMapping(true, DC_PLATFORM_DREAMCAST);
deleteMapping(true, DC_PLATFORM_NAOMI);
}
}
void GamepadDevice::clearButtonMapping(u32 port, DreamcastKey key)
{
if (input_mapper == nullptr)
return;
// Release the button
if (key <= DC_BTN_BITMAPPED_LAST && port >= 0 && port < std::size(kcode))
kcode[port] |= key;
input_mapper->clear_button(port, key);
}
void GamepadDevice::clearAxisMapping(u32 port, DreamcastKey key)
{
if (input_mapper == nullptr)
return;
// Reset the axis value
if (port >= 0 && port < MAPLE_PORTS)
{
switch (key)
{
case DC_AXIS_UP:
case DC_AXIS_DOWN:
joyy[port] = 0;
break;
case DC_AXIS_LEFT:
case DC_AXIS_RIGHT:
joyx[port] = 0;
break;
case DC_AXIS2_UP:
case DC_AXIS2_DOWN:
joyry[port] = 0;
break;
case DC_AXIS2_LEFT:
case DC_AXIS2_RIGHT:
joyrx[port] = 0;
break;
case DC_AXIS3_UP:
case DC_AXIS3_DOWN:
joy3y[port] = 0;
break;
case DC_AXIS3_LEFT:
case DC_AXIS3_RIGHT:
joy3x[port] = 0;
break;
case DC_AXIS_RT:
rt[port] = 0;
break;
case DC_AXIS_LT:
lt[port] = 0;
break;
case DC_AXIS_RT2:
rt2[port] = 0;
break;
case DC_AXIS_LT2:
lt2[port] = 0;
break;
default:
break;
}
}
input_mapper->clear_axis(port, key);
}
static void updateVibration(u32 port, float power, float inclination, u32 duration_ms)
{
int i = GamepadDevice::GetGamepadCount() - 1;
for ( ; i >= 0; i--)
{
std::shared_ptr<GamepadDevice> gamepad = GamepadDevice::GetGamepad(i);
if (gamepad != NULL && gamepad->maple_port() == (int)port && gamepad->is_rumble_enabled())
gamepad->rumble(power, inclination, duration_ms);
}
}
void GamepadDevice::detectInput(bool combo, input_detected_cb input_changed)
{
_input_detected = input_changed;
_detecting_combo = combo;
_detection_start_time = getTimeMs() + 200;
detectionInputs.clear();
detectingAxes.clear();
}
#ifdef TEST_AUTOMATION
static FILE *get_record_input(bool write)
{
if (write && !config::loadBool("record", "record_input", false))
return NULL;
if (!write && !config::loadBool("record", "replay_input", false))
return NULL;
std::string game_dir = settings.content.path;
size_t slash = game_dir.find_last_of("/");
size_t dot = game_dir.find_last_of(".");
std::string input_file = "scripts/" + game_dir.substr(slash + 1, dot - slash) + "input";
return nowide::fopen(input_file.c_str(), write ? "w" : "r");
}
#endif
void GamepadDevice::Register(const std::shared_ptr<GamepadDevice>& gamepad)
{
int maple_port = config::loadInt("input",
MAPLE_PORT_CFG_PREFIX + gamepad->unique_id(), 12345);
if (maple_port != 12345)
gamepad->set_maple_port(maple_port);
#ifdef TEST_AUTOMATION
if (record_input == NULL)
{
record_input = get_record_input(true);
if (record_input != NULL)
setbuf(record_input, NULL);
}
#endif
Lock _(_gamepads_mutex);
_gamepads.push_back(gamepad);
MapleConfigMap::UpdateVibration = updateVibration;
gamepad->_is_registered = true;
gamepad->registered();
}
void GamepadDevice::Unregister(const std::shared_ptr<GamepadDevice>& gamepad)
{
Lock _(_gamepads_mutex);
for (auto it = _gamepads.begin(); it != _gamepads.end(); it++)
if (*it == gamepad) {
_gamepads.erase(it);
break;
}
}
void GamepadDevice::SaveMaplePorts()
{
for (int i = 0; i < GamepadDevice::GetGamepadCount(); i++)
{
std::shared_ptr<GamepadDevice> gamepad = GamepadDevice::GetGamepad(i);
if (gamepad != NULL && !gamepad->unique_id().empty())
config::saveInt("input", MAPLE_PORT_CFG_PREFIX + gamepad->unique_id(), gamepad->maple_port());
}
}
s16 (&GamepadDevice::getTargetArray(DigAnalog axis))[4]
{
switch (axis)
{
case DIGANA_LEFT:
case DIGANA_RIGHT:
return joyx;
case DIGANA_UP:;
case DIGANA_DOWN:
return joyy;
case DIGANA2_LEFT:
case DIGANA2_RIGHT:
return joyrx;
case DIGANA2_UP:
case DIGANA2_DOWN:
return joyry;
case DIGANA3_LEFT:
case DIGANA3_RIGHT:
return joy3x;
case DIGANA3_UP:
case DIGANA3_DOWN:
return joy3y;
default:
die("unknown axis");
}
}
void GamepadDevice::rampAnalog()
{
Lock _(rampMutex);
if (lastAnalogUpdate == 0)
// also used as a flag that no analog ramping is needed on this device (yet)
return;
const u64 now = getTimeMs();
const int delta = std::round(static_cast<float>(now - lastAnalogUpdate) * AnalogRamp);
lastAnalogUpdate = now;
for (unsigned port = 0; port < std::size(digitalToAnalogState); port++)
{
for (int axis = 0; axis < 12; axis += 2) // 3 sticks with 2 axes each
{
DigAnalog negDir = static_cast<DigAnalog>(1 << axis);
if ((rampAnalogState[port] & negDir) == 0)
// axis not active
continue;
DigAnalog posDir = static_cast<DigAnalog>(1 << (axis + 1));
const int socd = digitalToAnalogState[port] & (negDir | posDir);
s16& axisValue = getTargetArray(negDir)[port];
if (socd != 0 && socd != (negDir | posDir))
{
// One axis is pressed => ramp up
if (socd == posDir)
axisValue = std::min(32767, axisValue + delta);
else
axisValue = std::max(-32768, axisValue - delta);
}
else
{
// No axis is pressed (or both) => ramp down
if (axisValue > 0)
axisValue = std::max(0, axisValue - delta);
else if (axisValue < 0)
axisValue = std::min(0, axisValue + delta);
else
rampAnalogState[port] &= ~negDir;
}
}
}
}
void GamepadDevice::RampAnalog()
{
Lock _(_gamepads_mutex);
for (auto& gamepad : _gamepads)
gamepad->rampAnalog();
}
#ifdef TEST_AUTOMATION
#include "cfg/option.h"
static bool replay_inited;
FILE *replay_file;
u64 next_event;
u32 next_port;
u32 next_kcode;
bool do_screenshot;
void replay_input()
{
if (!replay_inited)
{
replay_file = get_record_input(false);
replay_inited = true;
}
u64 now = sh4_sched_now64();
if (config::UseReios)
{
// Account for the swirl time
if (config::Broadcast == 0)
now = std::max((int64_t)now - 2152626532L, 0L);
else
now = std::max((int64_t)now - 2191059108L, 0L);
}
if (replay_file == NULL)
{
if (next_event > 0 && now - next_event > SH4_MAIN_CLOCK * 5)
die("Automation time-out after 5 s\n");
return;
}
while (next_event <= now)
{
if (next_event > 0)
kcode[next_port] = next_kcode;
char action[32];
if (fscanf(replay_file, "%ld %s %x %x\n", &next_event, action, &next_port, &next_kcode) != 4)
{
fclose(replay_file);
replay_file = NULL;
NOTICE_LOG(INPUT, "Input replay terminated");
do_screenshot = true;
break;
}
}
}
#endif