forked from ToadKing/wii-u-gc-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwii-u-gc-adapter.c
1966 lines (1728 loc) · 71.3 KB
/
wii-u-gc-adapter.c
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
// See LICENSE for license
#define _XOPEN_SOURCE 600
#include <time.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <ctype.h>
#include <getopt.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <libudev.h>
#include <libusb.h>
#include <pthread.h>
#if (!defined(LIBUSBX_API_VERSION) || LIBUSBX_API_VERSION < 0x01000102) && (!defined(LIBUSB_API_VERSION) || LIBUSB_API_VERSION < 0x01000102)
#error libusb(x) 1.0.16 or higher is required
#endif
// see here https://gist.github.com/nondebug/aec93dff7f0f1969f4cc2291b24a3171
enum VendorId {
USB_NINTENDO_VENDOR = 0x057e,
USB_MICROSOFT_VENDOR = 0x045e,
};
enum ProductId {
USB_ID_PRODUCT = 0x0337,
USB_XBOX360_PRODUCT = 0x028e,
USB_XBOX360_WIRELESS_PRODUCT = 0x02a1,
USB_XBOX_WIRELESS_USB_PRODUCT = 0x0b12,
//USB_XBOX_WIRELESS_BLUETOOTH_PRODUCT = 0x0b13,
//USB_XBOX_USA_PRODUCT = 0x0202,
//USB_XBOX_USA_2_PRODUCT = 0x0289,
//USB_XBOX_JAPAN_PRODUCT = 0x0285,
USB_XBOX_S_PRODUCT = 0x0287,
//USB_XBOX_S_2_PRODUCT = 0x0288,
USB_XBOX_ONE_PRODUCT = 0x02d1,
USB_XBOX_ONE_2_PRODUCT = 0x02dd,
USB_XBOX_ONE_S_USB_PRODUCT = 0x02ea,
//USB_XBOX_ONE_S_BLUETOOTH_PRODUCT = 0x02e0,
//USB_XBOX_ONE_S_BLUETOOTH_2_PRODUCT = 0x02fd,
USB_XBOX_ONE_ELITE_PRODUCT = 0x02e3,
//USB_XBOX_ONE_ELITE_2_PRODUCT = 0x02ff,
USB_XBOX_ONE_ELITE_SERIES_2_USB_PRODUCT = 0x0b00,
USB_XBOX_ONE_ELITE_SERIES_2_PRODUCT = 0x0b05,
//USB_XBOX_ONE_ELITE_SERIES_2_2_PRODUCT = 0x0b22,
};
#define EP_IN 0x81
#define EP_OUT 0x02
#define STATE_NORMAL 0x10
#define STATE_WAVEBIRD 0x20
#define MAX_FF_EVENTS 4
enum ButtonCodeIndex {
start_button_index = 0,
z_button_index = 1,
r_button_index = 2,
l_button_index = 3,
a_button_index = 8,
b_button_index = 9,
x_button_index = 10,
y_button_index = 11,
left_button_index = 12,
right_button_index = 13,
down_button_index = 14,
up_button_index = 15,
};
const int BUTTON_XBOX_VALUES[16] = {
BTN_START,
BTN_THUMBL,
BTN_TR2,
BTN_TL2,
-1,
-1,
-1,
-1,
BTN_SOUTH,
BTN_WEST,
BTN_EAST,
BTN_NORTH,
BTN_DPAD_LEFT,
BTN_DPAD_RIGHT,
BTN_DPAD_DOWN,
BTN_DPAD_UP,
};
const int BUTTON_LITERAL_VALUES[16] = {
BTN_START,
BTN_THUMBL,
BTN_TR2,
BTN_TL2,
-1,
-1,
-1,
-1,
BTN_A,
BTN_B,
BTN_X,
BTN_Y,
BTN_DPAD_LEFT,
BTN_DPAD_RIGHT,
BTN_DPAD_DOWN,
BTN_DPAD_UP,
};
const int REMAPPED_DPAD_DEFAULTS[4] = {
BTN_TL,
BTN_TR,
BTN_THUMBR,
BTN_SELECT,
};
static int dpad_button_codes[] = {
BTN_DPAD_LEFT, BTN_DPAD_RIGHT, BTN_DPAD_DOWN, BTN_DPAD_UP,
};
#define BUTTON_COUNT 16
static int button_code_values[BUTTON_COUNT];
enum AxisInputIndex {
thumbl_x_index,
thumbl_y_index,
thumbr_x_index,
thumbr_y_index,
trigger_l_index,
trigger_r_index,
};
// also see opt_default_axes_map
#define AXIS_COUNT 6
static struct AxisCode {
int lo;
int hi;
} axis_code_values[AXIS_COUNT] = {
{ -1, ABS_X, },
{ -1, ABS_Y, },
{ -1, ABS_RX, },
{ -1, ABS_RY, },
{ -1, ABS_Z, },
{ -1, ABS_RZ, },
};
enum AxisDivision {
lower_half_axis = -1,
full_axis = 0,
upper_half_axis = 1,
};
// remembers the controller's actual value ranges from each analog input
// each controller likely varies in which values it reaches so this values are wider than my platinum controller
static struct AxisRange {
int min;
int max;
} axis_natural_ranges[AXIS_COUNT] = {
{ 35, 218 },
{ 35, 218 },
{ 40, 215 },
{ 40, 215 },
{ 35, 230 }, // 230 is the maximum when fully depressed, 200 is reached by triggers before hitting the shoulder button
{ 35, 230 },
};
static int trigger_buttons[] = {
BTN_TL2, BTN_TR2,
};
struct ff_event
{
bool in_use;
bool forever;
int duration;
int delay;
int repetitions;
struct timespec start_time;
struct timespec end_time;
};
struct ports
{
bool connected;
bool extra_power;
int uinput;
unsigned char type;
uint16_t buttons;
uint8_t axis[6];
struct ff_event ff_events[MAX_FF_EVENTS];
};
struct adapter
{
volatile bool quitting;
struct libusb_device *device;
struct libusb_device_handle *handle;
pthread_t thread;
unsigned char rumble[5];
struct ports controllers[4];
struct adapter *next;
};
// parsed from command line options
static enum ShoulderButtonMode {
shoulder_button_none,
shoulder_button_nand,
shoulder_button_and,
} uses_shoulder_button = shoulder_button_none;
static enum ThumbstickMode {
thumbstick_none,
thumbstick_normal,
thumbstick_dpad,
thumbstick_dpad_sensitive,
thumbstick_analog_dpad,
thumbstick_analog_dpad_flipped,
} uses_thumbstick_left = thumbstick_normal,
uses_thumbstick_right = thumbstick_normal;
static enum TriggerMode {
trigger_none,
trigger_normal,
trigger_binary,
} uses_trigger_left = trigger_normal,
uses_trigger_right = trigger_normal;
static bool uses_explicit_libusb_claim = false;
static bool uses_raw_mode = false;
static bool flips_y_axis = true;
static bool uses_remapped_dpad = false;
static bool uses_foreign_buttons = false;
static bool quits_on_interrupt = false;
#define DEFAULT_Z_CODE BTN_THUMBL
static int z_code = DEFAULT_Z_CODE;
static volatile int quitting;
static struct adapter adapters;
static const char *uinput_path;
static uint16_t vendor_id = 0;
static uint16_t product_id = 0;
static const char *device_name = NULL;
enum ControllerId {
gcn_adapter_index,
xbox_360_index,
xbox_360_wireless_index,
xbox_wireless_index,
xbox_s_index,
xobx_one_index,
xbox_one_2_index,
xbox_one_s_index,
xbox_one_elite_index,
xobx_one_elite_series_2_index,
xobx_one_elite_series_2_2_index,
no_controller_index,
} controller_index = gcn_adapter_index;
// see PCGamingWiki, e.g. https://www.pcgamingwiki.com/wiki/Controller:Xbox_Wireless_Controller
static struct DeviceInfo {
uint16_t vendor_id;
uint16_t product_id;
const char *device_name;
bool flips_y_axis;
} device_data[] = {
[gcn_adapter_index] = { .vendor_id = USB_NINTENDO_VENDOR, .product_id = USB_ID_PRODUCT, .device_name = "Wii U GameCube Adapter Port %d", .flips_y_axis = true },
[xbox_360_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX360_PRODUCT, .device_name = "Microsoft X-Box 360 pad", .flips_y_axis = false },
[xbox_360_wireless_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX360_WIRELESS_PRODUCT, .device_name = "Xbox 360 Wireless Receiver", .flips_y_axis = false },
[xbox_wireless_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_WIRELESS_USB_PRODUCT, .device_name = "Xbox Wireless Controller", .flips_y_axis = false },
//[xbox_wireless_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_WIRELESS_BLUETOOTH_PRODUCT, .device_name = "Xbox Wireless Controller", .flips_y_axis = false },
[xbox_s_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_S_PRODUCT, .device_name = "Microsoft Xbox Controller", .flips_y_axis = false }, // from xone driver
[xbox_one_s_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_S_USB_PRODUCT, .device_name = "Xbox Wireless Controller", .flips_y_axis = false },
//[xbox_one_s_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_S_BLUETOOTH_PRODUCT, .device_name = "Xbox Wireless Controller", .flips_y_axis = false },
//[xbox_one_s_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_S_BLUETOOTH_2_PRODUCT, .device_name = "Xbox Wireless Controller", .flips_y_axis = false },
[xobx_one_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_PRODUCT, .device_name = "Xbox One Controller", .flips_y_axis = false },
[xbox_one_2_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_2_PRODUCT, .device_name = "Xbox One Controller", .flips_y_axis = false },
[xbox_one_elite_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_ELITE_PRODUCT, .device_name = "Xbox One Elite Controller", .flips_y_axis = false },
//[xbox_one_elite_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_ELITE_2_PRODUCT, .device_name = "Xbox One Elite Controller", .flips_y_axis = false },
[xobx_one_elite_series_2_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_ELITE_SERIES_2_USB_PRODUCT, .device_name = "Xbox One Elite Controller", .flips_y_axis = false },
[xobx_one_elite_series_2_2_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_ELITE_SERIES_2_PRODUCT, .device_name = "Xbox One Elite Controller", .flips_y_axis = false },
//[xbox_one_elite_series_2_index] = { .vendor_id = USB_MICROSOFT_VENDOR, .product_id = USB_XBOX_ONE_ELITE_SERIES_2_2_PRODUCT, .device_name = "Xbox One Elite Controller", .flips_y_axis = false },
};
static unsigned char connected_type(unsigned char status)
{
unsigned char type = status & (STATE_NORMAL | STATE_WAVEBIRD);
switch (type)
{
case STATE_NORMAL:
case STATE_WAVEBIRD:
return type;
default:
return 0;
}
}
struct AxisScale {
int end_value;
int start_value;
bool uses_start_value;
} *axis_scales[ABS_CNT] = {NULL, NULL, NULL, NULL, NULL, NULL};
static void init_AxisTransform()
{
for (int i=0; i<ABS_CNT; i++)
axis_scales[i] = NULL;
}
static void parse_AxisScale(struct AxisScale *this, const char descriptor_[])
{
char *descriptor = strdup(descriptor_);
int split_index = strcspn(descriptor, ":");
char *end_descriptor = &descriptor[split_index];
if ( (this->uses_start_value= *end_descriptor != '\0') )
{
*end_descriptor++ = '\0';
this->start_value = (int)strtol(descriptor, NULL, 0);
}
else
end_descriptor = descriptor;
this->end_value = (int)strtol(end_descriptor, NULL, 0);
free(descriptor);
}
static void add_AxisScale(int axis_code, const char descriptor[])
{
if (axis_code < 0) return;
struct AxisScale *axis_scale = NULL;
int whitespace_end = strspn(descriptor, " \n\r\t\f\v");
if (descriptor[whitespace_end] != '\0')
{
axis_scale = malloc(sizeof(struct AxisScale));
if (axis_scale == NULL) { fprintf(stderr, "out of memory"); exit(-ENOMEM); }
parse_AxisScale(axis_scale, descriptor);
}
if (axis_scales[axis_code] != NULL)
free(axis_scales[axis_code]);
axis_scales[axis_code] = axis_scale;
}
#define AxisName_none_index 7
const struct AxisName {
const char *name;
int code;
} sorted_axis_names[] = {
{"brake", ABS_BRAKE},
{"dpadx", ABS_HAT0X},
{"dpady", ABS_HAT0Y},
{"gas", ABS_GAS},
{"lx", ABS_X},
{"ly", ABS_Y},
{"lz", ABS_Z},
{"none", -1},
{"rudder", ABS_RUDDER},
{"rx", ABS_RX},
{"ry", ABS_RY},
{"rz", ABS_RZ},
{"throttle", ABS_THROTTLE},
{"wheel", ABS_WHEEL},
{"x", ABS_X},
{"y", ABS_Y},
{"z", ABS_Z},
};
// length > 0, finds the index of the name or the next bigger name
static int search_axis_name(const char test_name[], int start_index, size_t length)
{
int name_index = start_index + length/2;
struct AxisName name = sorted_axis_names[name_index];
int comparison = strcmp(test_name, name.name);
if (comparison == 0)
return name_index;
if (comparison < 0)
{
length = name_index - start_index;
if (length < 1)
return name_index;
return search_axis_name(test_name, start_index, length);
}
length += start_index;
start_index = name_index+1;
length -= start_index;
if (length < 1)
return name_index+1;
return search_axis_name(test_name, start_index, length);
}
static struct AxisName parse_axis_name(const char descriptor[], const char **remainder)
{
if (descriptor[0] == '\0') {
*remainder = descriptor;
return sorted_axis_names[AxisName_none_index];
}
char *compressed = strdup(descriptor);
// remove non-alphanumeric characters
int src_i=0, dest_i=0;
char current_character;
while ( (current_character= descriptor[src_i]) != '\0')
{
if (isalnum(current_character))
{
compressed[dest_i++] = current_character | 0x20; // to lower case
}
else if (!isspace(current_character) && current_character != '-' && current_character != '_')
{
break;
}
src_i++;
}
if (remainder != NULL) *remainder = &descriptor[src_i];
compressed[dest_i] = '\0';
int names_count = sizeof(sorted_axis_names) / sizeof(sorted_axis_names[0]);
int i = search_axis_name(compressed, 0, names_count);
free(compressed);
return (i < names_count)? sorted_axis_names[i] : sorted_axis_names[AxisName_none_index];
}
static void set_axes_scales(const char scales_string[])
{
if (scales_string[0] == '\0') return;
char *key_value_pairs = strdup(scales_string);
for (char *key_value_string = strtok(key_value_pairs, ","); key_value_string != NULL; key_value_string = strtok(NULL, ","))
{
int delimiter_index = strcspn(key_value_string, "=");
if (key_value_string[delimiter_index] == '\0')
{
fprintf(stderr, "argument error: invalid argument \"%s\" given to --axes-scale\n", key_value_string);
continue;
}
key_value_string[delimiter_index] = '\0';
char *key_string = key_value_string;
char *value_string = &key_value_string[delimiter_index+1];
int axis_code = parse_axis_name(key_string, NULL).code;
add_AxisScale(axis_code, value_string);
}
free(key_value_pairs);
}
static struct uinput_user_dev default_udev_settings = {
.absmin[ABS_X] = 35, .absmax[ABS_X] = 218, .absfuzz[ABS_X] = 1, .absflat[ABS_X] = 0,
.absmin[ABS_Y] = 35, .absmax[ABS_Y] = 218, .absfuzz[ABS_Y] = 1, .absflat[ABS_Y] = 0, // flippying the Y axis will change its range ends slightly
.absmin[ABS_RX] = 43, .absmax[ABS_RX] = 215, .absfuzz[ABS_RX] = 1, .absflat[ABS_RX] = 0,
.absmin[ABS_RY] = 43, .absmax[ABS_RY] = 215, .absfuzz[ABS_RY] = 1, .absflat[ABS_RY] = 0,
.absmin[ABS_HAT0X] = 43, .absmax[ABS_HAT0X] = 215, .absfuzz[ABS_HAT0X] = 1, .absflat[ABS_HAT0X] = 0,
.absmin[ABS_HAT0Y] = 43, .absmax[ABS_HAT0Y] = 215, .absfuzz[ABS_HAT0Y] = 1, .absflat[ABS_HAT0Y] = 0,
.absmin[ABS_Z] = 40, .absmax[ABS_Z] = 190, .absfuzz[ABS_Z] = 4, .absflat[ABS_Z] = 0,
.absmin[ABS_RZ] = 40, .absmax[ABS_RZ] = 190, .absfuzz[ABS_RZ] = 4, .absflat[ABS_RZ] = 0,
.absmin[ABS_THROTTLE] = 43, .absmax[ABS_THROTTLE] = 215, .absfuzz[ABS_THROTTLE] = 4, .absflat[ABS_THROTTLE] = 0, // if used with triggers, 210 or more means fully depressed
.absmin[ABS_RUDDER] = 43, .absmax[ABS_RUDDER] = 215, .absfuzz[ABS_RUDDER] = 4, .absflat[ABS_RUDDER] = 0,
.absmin[ABS_WHEEL] = 35, .absmax[ABS_WHEEL] = 218, .absfuzz[ABS_WHEEL] = 1, .absflat[ABS_WHEEL] = 0,
.absmin[ABS_BRAKE] = 35, .absmax[ABS_BRAKE] = 218, .absfuzz[ABS_BRAKE] = 4, .absflat[ABS_BRAKE] = 0,
.absmin[ABS_GAS] = 35, .absmax[ABS_GAS] = 218, .absfuzz[ABS_GAS] = 4, .absflat[ABS_GAS] = 0,
};
static struct uinput_user_dev uinput_dev;
static void flip_axis_bounds(struct uinput_user_dev* udev, int axis_code)
{
if (axis_code < 0) return;
int old_max = udev->absmax[axis_code];
udev->absmax[axis_code] = udev->absmin[axis_code] ^ 0xff;
udev->absmin[axis_code] = old_max ^ 0xff;
}
static void use_axis_normally(int axis_index)
{
if (axis_index < 2)
uses_thumbstick_left = thumbstick_normal;
else if (axis_index < 4)
uses_thumbstick_right = thumbstick_normal;
else if (axis_index == 4)
uses_trigger_left = trigger_normal;
else
uses_trigger_right = trigger_normal;
}
static void combine_axes(__attribute_maybe_unused__ struct uinput_user_dev *device_settings, int lower_axis, int upper_axis, int axis_index)
{
if (lower_axis >= 0)
{
use_axis_normally(axis_index);
if (axis_index >= 0)
axis_code_values[axis_index].lo = lower_axis;
}
if (upper_axis >= 0)
{
use_axis_normally(axis_index);
if (axis_index >= 0)
axis_code_values[axis_index].hi = upper_axis;
}
}
static void uncombine_axis(__attribute_maybe_unused__ struct uinput_user_dev *device_settings, int axis_code, int axis_index)
{
if (axis_code < 0) return;
if (axis_index >= 0)
{
use_axis_normally(axis_index);
axis_code_values[axis_index].hi = axis_code;
axis_code_values[axis_index].lo = -1;
}
}
static void clear_axis(struct uinput_user_dev *device_settings, int axis_index)
{
uncombine_axis(device_settings, axis_code_values[axis_index].lo, -1);
uncombine_axis(device_settings, axis_code_values[axis_index].hi, -1);
axis_code_values[axis_index] = (struct AxisCode){ -1, -1 };
}
static int get_axis_index(const char axis_string[])
{
switch(axis_string[0] | 0x20)
{
case 'x': return thumbl_x_index;
case 'y': return thumbl_y_index;
case 'z': return trigger_l_index;
case 'l':
switch(axis_string[1] | 0x20)
{
case 'x': return thumbl_x_index;
case 'y': return thumbl_y_index;
case 'z':
default: return trigger_l_index;
}
case 'r':
switch(axis_string[1] | 0x20)
{
case 'x': return thumbr_x_index;
case 'y': return thumbr_y_index;
case 'z':
default: return trigger_r_index;
}
default:
fprintf(stderr, "argument error: unsupported analog input \"%s\" for --axes-map\n", axis_string);
return -1;
}
}
const char *axis_names[] = {
"Thumb Left X",
"Thumb Left Y",
"Thumb Right X",
"Thumb Right Y",
"Trigger L",
"Trigger R",
};
static void set_single_axis_map(int axis_index, char axis_name_expression[])
{
const char *upper_axis_name;
struct AxisName axis_name = parse_axis_name(axis_name_expression, &upper_axis_name);
if (upper_axis_name[0] != '+')
{
fprintf(stdout, "map %s to %s\n", axis_names[axis_index], axis_name.name);
uncombine_axis(&uinput_dev, axis_name.code, axis_index);
return;
}
((char*)upper_axis_name++)[0] = '\0';
struct AxisName axis_name_hi = parse_axis_name(&upper_axis_name[0], NULL);
fprintf(stdout, "map %s (low half) to %s, %s (high half) to %s\n", axis_names[axis_index], axis_name.name, axis_names[axis_index], axis_name_hi.name);
combine_axes(&uinput_dev, axis_name.code, axis_name_hi.code, axis_index);
}
static void set_axes_map(const char mappings_string_[])
{
if (mappings_string_[0] == '\0') return;
char *mappings_string = strdup(mappings_string_);
for (char *key_value_string = strtok(mappings_string, ","); key_value_string != NULL; key_value_string = strtok(NULL, ","))
{
int delimiter_index = strcspn(key_value_string, "=");
if (key_value_string[delimiter_index] == '\0')
{
fprintf(stderr, "argument error: invalid argument \"%s\" was passed to --axes-map.\n", key_value_string);
continue;
}
key_value_string[delimiter_index] = '\0';
char *key_string = key_value_string;
char *value_string = &key_value_string[delimiter_index+1];
int axis_index = get_axis_index(key_string);
set_single_axis_map(axis_index, value_string);
}
free(mappings_string);
}
static void set_raw_absinfo()
{
uses_raw_mode = true;
int axis_codes[] = {ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_Z, ABS_RZ, ABS_HAT0X, ABS_HAT0Y, ABS_THROTTLE, ABS_RUDDER, ABS_GAS, ABS_BRAKE, ABS_WHEEL};
int axes_number = sizeof(axis_codes) / sizeof(axis_codes[0]);
for (int i=0; i<axes_number; i++)
{
int axis_code = axis_codes[i];
uinput_dev.absmin[axis_code] = 0; uinput_dev.absmax[axis_code] = 255;
}
}
/** Expects the command line settings to a comma separated list of assignments. The allowed variables are LX, LY, L, RX, RY, R and the allowed values are unsigned integer literals.
* The array_offset must be the offsetof(struct uinput_user_dev, …) of an array member field.
*/
static void set_axis_absinfo(ptrdiff_t array_offset, const char command_line_settings_[])
{
if (command_line_settings_[0] == '\0') return;
signed int *absinfo_array = (signed int*)((char*) &uinput_dev + array_offset);
char *command_line_settings = strdup(command_line_settings_);
for ( char *next_item = strtok(command_line_settings, ","); next_item != NULL; next_item = strtok(NULL, ",") )
{
int axis_name_length = strcspn(next_item, "=");
if (next_item[axis_name_length] == '\0')
{
continue;
}
next_item[axis_name_length] = '\0';
char *axis_value_string = &next_item[axis_name_length + 1];
int axis_value = (int)strtoul(axis_value_string, NULL, 0);
int axis_code = parse_axis_name(next_item, NULL).code;
if (axis_code < 0)
{
continue;
}
absinfo_array[axis_code] = axis_value;
}
free(command_line_settings);
}
static bool uinput_create(int i, struct ports *port, unsigned char type)
{
fprintf(stderr, "connecting on port %d\n", i);
port->uinput = open(uinput_path, O_RDWR | O_NONBLOCK);
// buttons
ioctl(port->uinput, UI_SET_EVBIT, EV_KEY);
int length = sizeof(button_code_values) / sizeof(button_code_values[0]);
for (int j=0; j < length; j++)
{
int button_code = button_code_values[j];
if (button_code != -1)
ioctl(port->uinput, UI_SET_KEYBIT, button_code);
}
if (uses_trigger_left == trigger_binary)
ioctl(port->uinput, UI_SET_KEYBIT, trigger_buttons[0]);
if (uses_trigger_right == trigger_binary)
ioctl(port->uinput, UI_SET_KEYBIT, trigger_buttons[1]);
if (uses_thumbstick_left == thumbstick_dpad || uses_thumbstick_left == thumbstick_dpad_sensitive || uses_thumbstick_right == thumbstick_dpad || uses_thumbstick_right == thumbstick_dpad_sensitive)
{
int length = sizeof(dpad_button_codes) / sizeof(dpad_button_codes[0]);
for (int j=0; j < length; j++)
{
ioctl(port->uinput, UI_SET_KEYBIT, dpad_button_codes[j]);
}
}
// axis
ioctl(port->uinput, UI_SET_EVBIT, EV_ABS); // do we need to toggle this off when no axes are used?
for (int i=0; i < AXIS_COUNT; i++)
{
int code = axis_code_values[i].lo;
if (code >= 0)
ioctl(port->uinput, UI_SET_ABSBIT, code);
code = axis_code_values[i].hi;
if (code >= 0)
ioctl(port->uinput, UI_SET_ABSBIT, code);
}
// rumble
ioctl(port->uinput, UI_SET_EVBIT, EV_FF);
ioctl(port->uinput, UI_SET_FFBIT, FF_PERIODIC);
ioctl(port->uinput, UI_SET_FFBIT, FF_SQUARE);
ioctl(port->uinput, UI_SET_FFBIT, FF_TRIANGLE);
ioctl(port->uinput, UI_SET_FFBIT, FF_SINE);
ioctl(port->uinput, UI_SET_FFBIT, FF_RUMBLE);
uinput_dev.ff_effects_max = MAX_FF_EVENTS;
snprintf(uinput_dev.name, sizeof(uinput_dev.name), device_name, i+1);
uinput_dev.name[sizeof(uinput_dev.name)-1] = 0;
uinput_dev.id.bustype = BUS_USB;
uinput_dev.id.vendor = vendor_id;
uinput_dev.id.product = product_id;
size_t to_write = sizeof(uinput_dev);
size_t written = 0;
while (written < to_write)
{
ssize_t write_ret = write(port->uinput, (const char*)&uinput_dev + written, to_write - written);
if (write_ret < 0)
{
perror("error writing uinput device settings");
close(port->uinput);
return false;
}
written += write_ret;
}
if (ioctl(port->uinput, UI_DEV_CREATE) != 0)
{
perror("error creating uinput device");
close(port->uinput);
return false;
}
port->type = type;
port->connected = true;
return true;
}
static void uinput_destroy(int i, struct ports *port)
{
fprintf(stderr, "disconnecting on port %d\n", i);
ioctl(port->uinput, UI_DEV_DESTROY);
close(port->uinput);
port->connected = false;
}
static struct timespec ts_add(struct timespec *start, int milliseconds)
{
struct timespec ret = *start;
int s = milliseconds / 1000;
int ns = (milliseconds % 1000) * 1000000;
ret.tv_sec += s ;
ret.tv_nsec += ns ;
if (ret.tv_nsec >= 1000000000L)
{
ret.tv_sec++;
ret.tv_nsec -= 1000000000L;
}
return ret;
}
static bool ts_greaterthan(struct timespec *first, struct timespec *second)
{
return (first->tv_sec >= second->tv_sec || (first->tv_sec == second->tv_sec && first->tv_nsec >= second->tv_nsec));
}
static bool ts_lessthan(struct timespec *first, struct timespec *second)
{
return (first->tv_sec <= second->tv_sec || (first->tv_sec == second->tv_sec && first->tv_nsec <= second->tv_nsec));
}
static void update_ff_start_stop(struct ff_event *e, struct timespec *current_time)
{
e->repetitions--;
if (e->repetitions < 0)
{
e->repetitions = 0;
e->start_time.tv_sec = 0;
e->start_time.tv_nsec = 0;
e->end_time.tv_sec = 0;
e->end_time.tv_nsec = 0;
}
else
{
e->start_time = ts_add(current_time, e->delay);
if (e->forever)
{
e->end_time.tv_sec = INT_MAX;
e->end_time.tv_nsec = 999999999L;
}
else
{
e->end_time = ts_add(&e->start_time, e->duration);
}
}
}
static int create_ff_event(struct ports *port, struct uinput_ff_upload *upload)
{
bool stop = false;
switch (upload->effect.type)
{
case FF_PERIODIC:
stop = upload->effect.u.periodic.magnitude == 0;
break;
case FF_RUMBLE:
stop = upload->effect.u.rumble.strong_magnitude == 0 && upload->effect.u.rumble.weak_magnitude == 0;
break;
}
if (upload->old.type != 0)
{
if (stop)
{
port->ff_events[upload->old.id].forever = false;
port->ff_events[upload->old.id].duration = 0;
}
else
{
// events with length 0 last forever
port->ff_events[upload->old.id].forever = (upload->effect.replay.length == 0);
port->ff_events[upload->old.id].duration = upload->effect.replay.length;
}
port->ff_events[upload->old.id].delay = upload->effect.replay.delay;
port->ff_events[upload->old.id].repetitions = 0;
return upload->old.id;
}
for (int i = 0; i < MAX_FF_EVENTS; i++)
{
if (!port->ff_events[i].in_use)
{
port->ff_events[i].in_use = true;
if (stop)
{
port->ff_events[i].forever = false;
port->ff_events[i].duration = 0;
}
else
{
port->ff_events[i].forever = (upload->effect.replay.length == 0);
port->ff_events[i].duration = upload->effect.replay.length;
}
port->ff_events[i].delay = upload->effect.replay.delay;
port->ff_events[i].repetitions = 0;
return i;
}
}
return -1;
}
static void add_button_event(struct input_event events[], int *events_count, uint16_t previous_button_state, uint16_t *result_button_state, const int button_codes[], uint16_t button_pressed_mask, int tested_button_id)
{
int button_code = button_codes[tested_button_id];
if (button_code == -1)
return;
uint16_t single_button_mask = (1 << tested_button_id);
uint16_t single_button_pressed_mask = button_pressed_mask & single_button_mask;
if ((previous_button_state & single_button_mask) != single_button_pressed_mask)
{
bool ignores_button = (uses_trigger_left == trigger_binary && button_code == trigger_buttons[0]) || (uses_trigger_right == trigger_binary && button_code == trigger_buttons[1]);
if (!ignores_button)
{
int e_count = *events_count;
events[e_count].type = EV_KEY;
events[e_count].code = button_code;
events[e_count].value = (single_button_pressed_mask != 0);
e_count++;
*events_count = e_count;
}
previous_button_state &= ~single_button_mask;
previous_button_state |= single_button_pressed_mask;
*result_button_state = previous_button_state;
}
}
#define TAN_PI_8 0.414213562373095 // (sqrt(2.0) - 1.0)
#define TAN_3PI_8 (1.0 / TAN_PI_8)
#define HORIZONTAL_THRESHOLD (int)(250 * TAN_3PI_8)
static bool is_dpad_pressed(int axis_value, int perpendicular_value, int min_axis_value)
{
if (axis_value < 0)
axis_value = -axis_value;
if (axis_value < min_axis_value || axis_value == 0)
return false;
int slope = perpendicular_value * 250 / axis_value;
if (slope < 0)
slope = -slope;
return slope <= HORIZONTAL_THRESHOLD;
}
#define DPAD_FILTER_LENGTH 4 // 2 * filter length -1 = number of available duty cycles
static struct DeltaModulator {
unsigned char unit_duration; // time duration of a unit of equal return values
signed char duty_cycle_units; // keydown to keyup ratio = 1:-n or +n:1, 1 complement, negative values represent duty cycles of keyup
unsigned char time;
} thumbstick_filter[AXIS_COUNT] = {
{ .unit_duration = 4, .duty_cycle_units = 0, .time = 0, },
{ .unit_duration = 4, .duty_cycle_units = 0, .time = 0, },
{ .unit_duration = 4, .duty_cycle_units = 0, .time = 0, },
{ .unit_duration = 4, .duty_cycle_units = 0, .time = 0, },
};
int step_levels[] = {
15 * 15, // 0
37 * 37, // 1/4
50 * 50, // 1/3
64 * 64, // 1/2
75 * 75, // 2/3
87 * 87, // 3/4
99 * 99, // 1
};
static signed char get_duty_cycle(int percent_squared)
{
if (percent_squared <= step_levels[0]) return 0;
if (percent_squared > step_levels[4])
{
if (percent_squared > step_levels[5])
return ~0;
return 3;
}
if (percent_squared <= step_levels[2])
{
if (percent_squared <= step_levels[1])
return ~3;
else
return ~2;
}
else
{
if (percent_squared <= step_levels[3])
return 1;
else
return 2;
}
}
static void update_thumbstick_filter(struct DeltaModulator *filter, int percent_squared)
{
signed char chosen_duty_cycle = get_duty_cycle(percent_squared);
filter->duty_cycle_units = chosen_duty_cycle;
unsigned unit_duration = filter->unit_duration;
unsigned reset_time = ((chosen_duty_cycle < 0 ? ~chosen_duty_cycle : chosen_duty_cycle) + 1) * unit_duration;
if (filter->time >= reset_time)
filter->time = 0;
}
static bool read_thumbstick_filter(struct DeltaModulator *filter)
{
bool is_inversed = filter->duty_cycle_units < 0;
unsigned duty_cycle_units = (is_inversed? 1 : filter->duty_cycle_units);
unsigned threshold = duty_cycle_units * filter->unit_duration;
bool bit_value = filter->time < threshold;
filter->time++;
//if (filter == &thumbstick_filter[2])
//{
// putc(bit_value ? '*' : ' ', stderr);
//}
return bit_value;
}
#define axis_value_to_signed(axis_value) ((int)(axis_value) + SCHAR_MIN)
static int signed_to_axis_value(int signed_value, int axis_index, enum AxisDivision axis_division)
{
if (axis_division == full_axis)
return signed_value - SCHAR_MIN;
int start_value, end_value;
if (axis_division == upper_half_axis)
{
start_value = axis_natural_ranges[axis_index].min;
end_value = axis_natural_ranges[axis_index].max;