-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathHID.cs
More file actions
1436 lines (1265 loc) · 62.9 KB
/
HID.cs
File metadata and controls
1436 lines (1265 loc) · 62.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
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Profiling;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.Scripting;
using UnityEngine.Pool;
////REVIEW: there will probably be lots of cases where the HID device creation process just needs a little tweaking; we should
//// have better mechanism to do that without requiring to replace the entire process wholesale
////TODO: expose the layout builder so that other layout builders can use it for their own purposes
////REVIEW: how are we dealing with multiple different input reports on the same device?
////REVIEW: move the enums and structs out of here and into UnityEngine.InputSystem.HID? Or remove the "HID" name prefixes from them?
////TODO: add blacklist for devices we really don't want to use (like apple's internal trackpad)
////TODO: add a way to mark certain layouts (such as HID layouts) as fallbacks; ideally, affect the layout matching score
////TODO: enable this to handle devices that split their input into multiple reports
#pragma warning disable CS0649, CS0219
namespace UnityEngine.InputSystem.HID
{
/// <summary>
/// A generic HID input device.
/// </summary>
/// <remarks>
/// This class represents a best effort to mirror the control setup of a HID
/// discovered in the system. It is used only as a fallback where we cannot
/// match the device to a specific product we know of. Wherever possible we
/// construct more specific device representations such as Gamepad.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public class HID : InputDevice
{
internal const string kHIDInterface = "HID";
internal const string kHIDNamespace = "HID";
/// <summary>
/// Command code for querying the HID report descriptor from a device.
/// </summary>
/// <seealso cref="InputDevice.ExecuteCommand{TCommand}"/>
public static FourCC QueryHIDReportDescriptorDeviceCommandType { get { return new FourCC('H', 'I', 'D', 'D'); } }
/// <summary>
/// Command code for querying the HID report descriptor size in bytes from a device.
/// </summary>
/// <seealso cref="InputDevice.ExecuteCommand{TCommand}"/>
public static FourCC QueryHIDReportDescriptorSizeDeviceCommandType { get { return new FourCC('H', 'I', 'D', 'S'); } }
public static FourCC QueryHIDParsedReportDescriptorDeviceCommandType { get { return new FourCC('H', 'I', 'D', 'P'); } }
/// <summary>
/// The HID device descriptor as received from the system.
/// </summary>
public HIDDeviceDescriptor hidDescriptor
{
get
{
if (!m_HaveParsedHIDDescriptor)
{
if (!string.IsNullOrEmpty(description.capabilities))
m_HIDDescriptor = JsonUtility.FromJson<HIDDeviceDescriptor>(description.capabilities);
m_HaveParsedHIDDescriptor = true;
}
return m_HIDDescriptor;
}
}
private bool m_HaveParsedHIDDescriptor;
private HIDDeviceDescriptor m_HIDDescriptor;
private static readonly ProfilerMarker k_HIDParseDescriptorFallback = new ProfilerMarker("HIDParseDescriptorFallback");
// This is the workhorse for figuring out fallback options for HIDs attached to the system.
// If the system cannot find a more specific layout for a given HID, this method will try
// to produce a layout builder on the fly based on the HID descriptor received from
// the device.
internal static string OnFindLayoutForDevice(ref InputDeviceDescription description, string matchedLayout,
InputDeviceExecuteCommandDelegate executeDeviceCommand)
{
// If the system found a matching layout, there's nothing for us to do.
if (!string.IsNullOrEmpty(matchedLayout))
return null;
// If the device isn't a HID, we're not interested.
if (description.interfaceName != kHIDInterface)
return null;
// Read HID descriptor.
var hidDeviceDescriptor = ReadHIDDeviceDescriptor(ref description, executeDeviceCommand);
if (!HIDSupport.supportedHIDUsages.Contains(new HIDSupport.HIDPageUsage(hidDeviceDescriptor.usagePage, hidDeviceDescriptor.usage)))
return null;
// Determine if there's any usable elements on the device.
var hasUsableElements = false;
if (hidDeviceDescriptor.elements != null)
{
foreach (var element in hidDeviceDescriptor.elements)
{
if (element.IsUsableElement())
{
hasUsableElements = true;
break;
}
}
}
// If not, there's nothing we can do with the device.
if (!hasUsableElements)
return null;
////TODO: we should be able to differentiate a HID joystick from other joysticks in bindings alone
// Determine base layout.
var baseType = typeof(HID);
var baseLayout = "HID";
if (hidDeviceDescriptor.usagePage == UsagePage.GenericDesktop)
{
if (hidDeviceDescriptor.usage == (int)GenericDesktop.Joystick || hidDeviceDescriptor.usage == (int)GenericDesktop.Gamepad)
{
baseLayout = "Joystick";
baseType = typeof(Joystick);
}
}
// A HID may implement the HID interface arbitrary many times, each time with a different
// usage page + usage combination. In a OS, this will typically come out as multiple separate
// devices. Thus, to make layout names unique, we have to take usages into account. What we do
// is we tag the usage name onto the layout name *except* if it's a joystick or gamepad. This
// gives us nicer names for joysticks while still disambiguating other devices correctly.
var usageName = "";
if (baseLayout != "Joystick")
{
usageName = hidDeviceDescriptor.usagePage == UsagePage.GenericDesktop
? $" {(GenericDesktop) hidDeviceDescriptor.usage}"
: $" {hidDeviceDescriptor.usagePage}-{hidDeviceDescriptor.usage}";
}
////REVIEW: these layout names are impossible to bind to; come up with a better way
////TODO: match HID layouts by vendor and product ID
////REVIEW: this probably works fine for most products out there but I'm not sure it works reliably for all cases
// Come up with a unique template name. HIDs are required to have product and vendor IDs.
// We go with the string versions if we have them and with the numeric versions if we don't.
string layoutName;
var deviceMatcher = InputDeviceMatcher.FromDeviceDescription(description);
if (!string.IsNullOrEmpty(description.product) && !string.IsNullOrEmpty(description.manufacturer))
{
layoutName = $"{kHIDNamespace}::{description.manufacturer} {description.product}{usageName}";
}
else if (!string.IsNullOrEmpty(description.product))
{
layoutName = $"{kHIDNamespace}::{description.product}{usageName}";
}
else
{
// Sanity check to make sure we really have the data we expect.
if (hidDeviceDescriptor.vendorId == 0)
return null;
layoutName =
$"{kHIDNamespace}::{hidDeviceDescriptor.vendorId:X}-{hidDeviceDescriptor.productId:X}{usageName}";
deviceMatcher = deviceMatcher
.WithCapability("productId", hidDeviceDescriptor.productId)
.WithCapability("vendorId", hidDeviceDescriptor.vendorId);
}
// Also match by usage. See comment above about multiple HID interfaces on the same device.
deviceMatcher = deviceMatcher
.WithCapability("usage", hidDeviceDescriptor.usage)
.WithCapability("usagePage", hidDeviceDescriptor.usagePage);
// Register layout builder that will turn the HID descriptor into an
// InputControlLayout instance.
var layout = new HIDLayoutBuilder
{
displayName = description.product,
hidDescriptor = hidDeviceDescriptor,
parentLayout = baseLayout,
deviceType = baseType ?? typeof(HID)
};
InputSystem.RegisterLayoutBuilder(() => layout.Build(),
layoutName, baseLayout, deviceMatcher);
return layoutName;
}
internal static unsafe HIDDeviceDescriptor ReadHIDDeviceDescriptor(ref InputDeviceDescription deviceDescription,
InputDeviceExecuteCommandDelegate executeCommandDelegate)
{
if (deviceDescription.interfaceName != kHIDInterface)
throw new ArgumentException(
$"Device '{deviceDescription}' is not a HID");
// See if we have to request a HID descriptor from the device.
// We support having the descriptor directly as a JSON string in the `capabilities`
// field of the device description.
var needToRequestDescriptor = true;
var hidDeviceDescriptor = new HIDDeviceDescriptor();
if (!string.IsNullOrEmpty(deviceDescription.capabilities))
{
try
{
hidDeviceDescriptor = HIDDeviceDescriptor.FromJson(deviceDescription.capabilities);
// If there's elements in the descriptor, we're good with the descriptor. If there aren't,
// we go and ask the device for a full descriptor.
if (hidDeviceDescriptor.elements != null && hidDeviceDescriptor.elements.Length > 0)
needToRequestDescriptor = false;
}
catch (Exception exception)
{
Debug.LogError($"Could not parse HID descriptor of device '{deviceDescription}'");
Debug.LogException(exception);
}
}
////REVIEW: we *could* switch to a single path here that supports *only* parsed descriptors but it'd
//// mean having to switch *every* platform supporting HID to the hack we currently have to do
//// on Windows
// Request descriptor, if necessary.
if (needToRequestDescriptor)
{
// Try to get the size of the HID descriptor from the device.
var sizeOfDescriptorCommand = new InputDeviceCommand(QueryHIDReportDescriptorSizeDeviceCommandType);
var sizeOfDescriptorInBytes = executeCommandDelegate(ref sizeOfDescriptorCommand);
if (sizeOfDescriptorInBytes > 0)
{
// Now try to fetch the HID descriptor.
using (var buffer =
InputDeviceCommand.AllocateNative(QueryHIDReportDescriptorDeviceCommandType, (int)sizeOfDescriptorInBytes))
{
var commandPtr = (InputDeviceCommand*)buffer.GetUnsafePtr();
if (executeCommandDelegate(ref *commandPtr) != sizeOfDescriptorInBytes)
return new HIDDeviceDescriptor();
// Try to parse the HID report descriptor.
if (!HIDParser.ParseReportDescriptor((byte*)commandPtr->payloadPtr, (int)sizeOfDescriptorInBytes, ref hidDeviceDescriptor))
return new HIDDeviceDescriptor();
}
// Update the descriptor on the device with the information we got.
deviceDescription.capabilities = hidDeviceDescriptor.ToJson();
}
else
{
// The device may not support binary descriptors but may support parsed descriptors so
// try the IOCTL for parsed descriptors next.
//
// This path exists pretty much only for the sake of Windows where it is not possible to get
// unparsed/binary descriptors from the device (and where getting element offsets is only possible
// with some dirty hacks we're performing in the native runtime).
const int kMaxDescriptorBufferSize = 2 * 1024 * 1024; ////TODO: switch to larger buffer based on return code if request fails
using (var buffer =
InputDeviceCommand.AllocateNative(QueryHIDParsedReportDescriptorDeviceCommandType, kMaxDescriptorBufferSize))
{
var commandPtr = (InputDeviceCommand*)buffer.GetUnsafePtr();
var utf8Length = executeCommandDelegate(ref *commandPtr);
if (utf8Length < 0)
return new HIDDeviceDescriptor();
// Turn UTF-8 buffer into string.
////TODO: is there a way to not have to copy here?
var utf8 = new byte[utf8Length];
fixed(byte* utf8Ptr = utf8)
{
UnsafeUtility.MemCpy(utf8Ptr, commandPtr->payloadPtr, utf8Length);
}
var descriptorJson = Encoding.UTF8.GetString(utf8, 0, (int)utf8Length);
// Try to parse the HID report descriptor.
try
{
hidDeviceDescriptor = HIDDeviceDescriptor.FromJson(descriptorJson);
}
catch (Exception exception)
{
Debug.LogError($"Could not parse HID descriptor of device '{deviceDescription}'");
Debug.LogException(exception);
return new HIDDeviceDescriptor();
}
// Update the descriptor on the device with the information we got.
deviceDescription.capabilities = descriptorJson;
}
}
}
return hidDeviceDescriptor;
}
public static string UsagePageToString(UsagePage usagePage)
{
return (int)usagePage >= 0xFF00 ? "Vendor-Defined" : usagePage.ToString();
}
public static string UsageToString(UsagePage usagePage, int usage)
{
switch (usagePage)
{
case UsagePage.GenericDesktop:
return ((GenericDesktop)usage).ToString();
case UsagePage.Simulation:
return ((Simulation)usage).ToString();
default:
return null;
}
}
[Serializable]
private class HIDLayoutBuilder
{
public string displayName;
public HIDDeviceDescriptor hidDescriptor;
public string parentLayout;
public Type deviceType;
public InputControlLayout Build()
{
var builder = new InputControlLayout.Builder
{
displayName = displayName,
type = deviceType,
extendsLayout = parentLayout,
stateFormat = new FourCC('H', 'I', 'D')
};
var xElement = Array.Find(hidDescriptor.elements,
element => element.usagePage == UsagePage.GenericDesktop &&
element.usage == (int)GenericDesktop.X);
var yElement = Array.Find(hidDescriptor.elements,
element => element.usagePage == UsagePage.GenericDesktop &&
element.usage == (int)GenericDesktop.Y);
////REVIEW: in case the X and Y control are non-contiguous, should we even turn them into a stick
////REVIEW: there *has* to be an X and a Y for us to be able to successfully create a joystick
// If GenericDesktop.X and GenericDesktop.Y are both present, turn the controls
// into a stick.
var haveStick = xElement.usage == (int)GenericDesktop.X && yElement.usage == (int)GenericDesktop.Y;
if (haveStick)
{
int bitOffset, byteOffset, sizeInBits;
if (xElement.reportOffsetInBits <= yElement.reportOffsetInBits)
{
bitOffset = xElement.reportOffsetInBits % 8;
byteOffset = xElement.reportOffsetInBits / 8;
sizeInBits = (yElement.reportOffsetInBits + yElement.reportSizeInBits) -
xElement.reportOffsetInBits;
}
else
{
bitOffset = yElement.reportOffsetInBits % 8;
byteOffset = yElement.reportOffsetInBits / 8;
sizeInBits = (xElement.reportOffsetInBits + xElement.reportSizeInBits) -
yElement.reportSizeInBits;
}
const string stickName = "stick";
builder.AddControl(stickName)
.WithDisplayName("Stick")
.WithLayout("Stick")
.WithBitOffset((uint)bitOffset)
.WithByteOffset((uint)byteOffset)
.WithSizeInBits((uint)sizeInBits)
.WithUsages(CommonUsages.Primary2DMotion);
var xElementParameters = xElement.DetermineParameters();
var yElementParameters = yElement.DetermineParameters();
builder.AddControl(stickName + "/x")
.WithFormat(xElement.DetermineFormat())
.WithByteOffset((uint)(xElement.reportOffsetInBits / 8 - byteOffset))
.WithBitOffset((uint)(xElement.reportOffsetInBits % 8))
.WithSizeInBits((uint)xElement.reportSizeInBits)
.WithParameters(xElementParameters)
.WithDefaultState(xElement.DetermineDefaultState())
.WithProcessors(xElement.DetermineProcessors());
builder.AddControl(stickName + "/y")
.WithFormat(yElement.DetermineFormat())
.WithByteOffset((uint)(yElement.reportOffsetInBits / 8 - byteOffset))
.WithBitOffset((uint)(yElement.reportOffsetInBits % 8))
.WithSizeInBits((uint)yElement.reportSizeInBits)
.WithParameters(yElementParameters)
.WithDefaultState(yElement.DetermineDefaultState())
.WithProcessors(yElement.DetermineProcessors());
// Propagate parameters needed on x and y to the four button controls.
builder.AddControl(stickName + "/up")
.WithParameters(
StringHelpers.Join(",", yElementParameters, "clamp=2,clampMin=-1,clampMax=0,invert=true"));
builder.AddControl(stickName + "/down")
.WithParameters(
StringHelpers.Join(",", yElementParameters, "clamp=2,clampMin=0,clampMax=1,invert=false"));
builder.AddControl(stickName + "/left")
.WithParameters(
StringHelpers.Join(",", xElementParameters, "clamp=2,clampMin=-1,clampMax=0,invert"));
builder.AddControl(stickName + "/right")
.WithParameters(
StringHelpers.Join(",", xElementParameters, "clamp=2,clampMin=0,clampMax=1"));
}
// Process HID descriptor.
var elements = hidDescriptor.elements;
var elementCount = elements.Length;
for (var i = 0; i < elementCount; ++i)
{
ref var element = ref elements[i];
if (element.reportType != HIDReportType.Input)
continue;
// Skip X and Y if we already turned them into a stick.
if (haveStick && (element.Is(UsagePage.GenericDesktop, (int)GenericDesktop.X) ||
element.Is(UsagePage.GenericDesktop, (int)GenericDesktop.Y)))
continue;
var layout = element.DetermineLayout();
if (layout != null)
{
// Assign unique name.
var name = element.DetermineName();
Debug.Assert(!string.IsNullOrEmpty(name));
name = StringHelpers.MakeUniqueName(name, builder.controls, x => x.name);
// Add control.
var control =
builder.AddControl(name)
.WithDisplayName(element.DetermineDisplayName())
.WithLayout(layout)
.WithByteOffset((uint)element.reportOffsetInBits / 8)
.WithBitOffset((uint)element.reportOffsetInBits % 8)
.WithSizeInBits((uint)element.reportSizeInBits)
.WithFormat(element.DetermineFormat())
.WithDefaultState(element.DetermineDefaultState())
.WithProcessors(element.DetermineProcessors());
var parameters = element.DetermineParameters();
if (!string.IsNullOrEmpty(parameters))
control.WithParameters(parameters);
var usages = element.DetermineUsages();
if (usages != null)
control.WithUsages(usages);
element.AddChildControls(ref element, name, ref builder);
}
}
return builder.Build();
}
}
public enum HIDReportType
{
Unknown,
Input,
Output,
Feature
}
public enum HIDCollectionType
{
Physical = 0x00,
Application = 0x01,
Logical = 0x02,
Report = 0x03,
NamedArray = 0x04,
UsageSwitch = 0x05,
UsageModifier = 0x06
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "No better term for underlying data.")]
[Flags]
public enum HIDElementFlags
{
Constant = 1 << 0,
Variable = 1 << 1,
Relative = 1 << 2,
Wrap = 1 << 3,
NonLinear = 1 << 4,
NoPreferred = 1 << 5,
NullState = 1 << 6,
Volatile = 1 << 7,
BufferedBytes = 1 << 8
}
/// <summary>
/// Descriptor for a single report element.
/// </summary>
[Serializable]
public struct HIDElementDescriptor
{
public int usage;
public UsagePage usagePage;
public int unit;
public int unitExponent;
public int logicalMin;
public int logicalMax;
public int physicalMin;
public int physicalMax;
public HIDReportType reportType;
public int collectionIndex;
public int reportId;
public int reportSizeInBits;
public int reportOffsetInBits;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags", Justification = "No better term for underlying data.")]
public HIDElementFlags flags;
// Fields only relevant to arrays.
public int? usageMin;
public int? usageMax;
public bool hasNullState => (flags & HIDElementFlags.NullState) == HIDElementFlags.NullState;
public bool hasPreferredState => (flags & HIDElementFlags.NoPreferred) != HIDElementFlags.NoPreferred;
public bool isArray => (flags & HIDElementFlags.Variable) != HIDElementFlags.Variable;
public bool isNonLinear => (flags & HIDElementFlags.NonLinear) == HIDElementFlags.NonLinear;
public bool isRelative => (flags & HIDElementFlags.Relative) == HIDElementFlags.Relative;
public bool isConstant => (flags & HIDElementFlags.Constant) == HIDElementFlags.Constant;
public bool isWrapping => (flags & HIDElementFlags.Wrap) == HIDElementFlags.Wrap;
internal bool isSigned => logicalMin < 0;
internal float minFloatValue
{
get
{
if (isSigned)
{
var minValue = (int)-(long)(1UL << (reportSizeInBits - 1));
var maxValue = (int)((1UL << (reportSizeInBits - 1)) - 1);
return NumberHelpers.IntToNormalizedFloat(logicalMin, minValue, maxValue) * 2.0f - 1.0f;
}
else
{
Debug.Assert(logicalMin >= 0, $"Expected logicalMin to be unsigned");
var maxValue = (uint)((1UL << reportSizeInBits) - 1);
return NumberHelpers.UIntToNormalizedFloat((uint)logicalMin, 0, maxValue);
}
}
}
internal float maxFloatValue
{
get
{
if (isSigned)
{
var minValue = (int)-(long)(1UL << (reportSizeInBits - 1));
var maxValue = (int)((1UL << (reportSizeInBits - 1)) - 1);
return NumberHelpers.IntToNormalizedFloat(logicalMax, minValue, maxValue) * 2.0f - 1.0f;
}
else
{
Debug.Assert(logicalMax >= 0, $"Expected logicalMax to be unsigned");
var maxValue = (uint)((1UL << reportSizeInBits) - 1);
return NumberHelpers.UIntToNormalizedFloat((uint)logicalMax, 0, maxValue);
}
}
}
public bool Is(UsagePage usagePage, int usage)
{
return usagePage == this.usagePage && usage == this.usage;
}
internal string DetermineName()
{
// It's rare for HIDs to declare string names for items and HID drivers may report weird strings
// plus there's no guarantee that these names are unique per item. So, we don't bother here with
// device/driver-supplied names at all but rather do our own naming.
switch (usagePage)
{
case UsagePage.Button:
if (usage == 1)
return "trigger";
return $"button{usage}";
case UsagePage.GenericDesktop:
if (usage == (int)GenericDesktop.HatSwitch)
return "hat";
var text = ((GenericDesktop)usage).ToString();
// Lower-case first letter.
text = char.ToLowerInvariant(text[0]) + text.Substring(1);
return text;
}
// Fallback that generates a somewhat useless but at least very informative name.
return $"UsagePage({usagePage:X}) Usage({usage:X})";
}
internal string DetermineDisplayName()
{
switch (usagePage)
{
case UsagePage.Button:
if (usage == 1)
return "Trigger";
return $"Button {usage}";
case UsagePage.GenericDesktop:
return ((GenericDesktop)usage).ToString();
}
return null;
}
internal bool IsUsableElement()
{
switch (usage)
{
case (int)GenericDesktop.X:
case (int)GenericDesktop.Y:
return usagePage == UsagePage.GenericDesktop;
default:
return DetermineLayout() != null;
}
}
internal string DetermineLayout()
{
if (reportType != HIDReportType.Input)
return null;
////TODO: deal with arrays
switch (usagePage)
{
case UsagePage.Button:
return "Button";
case UsagePage.GenericDesktop:
switch (usage)
{
case (int)GenericDesktop.X:
case (int)GenericDesktop.Y:
case (int)GenericDesktop.Z:
case (int)GenericDesktop.Rx:
case (int)GenericDesktop.Ry:
case (int)GenericDesktop.Rz:
case (int)GenericDesktop.Vx:
case (int)GenericDesktop.Vy:
case (int)GenericDesktop.Vz:
case (int)GenericDesktop.Vbrx:
case (int)GenericDesktop.Vbry:
case (int)GenericDesktop.Vbrz:
case (int)GenericDesktop.Slider:
case (int)GenericDesktop.Dial:
case (int)GenericDesktop.Wheel:
return "Axis";
case (int)GenericDesktop.Select:
case (int)GenericDesktop.Start:
case (int)GenericDesktop.DpadUp:
case (int)GenericDesktop.DpadDown:
case (int)GenericDesktop.DpadLeft:
case (int)GenericDesktop.DpadRight:
return "Button";
case (int)GenericDesktop.HatSwitch:
// Only support hat switches with 8 directions.
if (logicalMax - logicalMin + 1 == 8)
return "Dpad";
break;
}
break;
}
return null;
}
internal FourCC DetermineFormat()
{
switch (reportSizeInBits)
{
case 8:
return isSigned ? InputStateBlock.FormatSByte : InputStateBlock.FormatByte;
case 16:
return isSigned ? InputStateBlock.FormatShort : InputStateBlock.FormatUShort;
case 32:
return isSigned ? InputStateBlock.FormatInt : InputStateBlock.FormatUInt;
default:
// Generic bitfield value.
return InputStateBlock.FormatBit;
}
}
internal InternedString[] DetermineUsages()
{
if (usagePage == UsagePage.Button && usage == 1)
return new[] {CommonUsages.PrimaryTrigger, CommonUsages.PrimaryAction};
if (usagePage == UsagePage.Button && usage == 2)
return new[] {CommonUsages.SecondaryTrigger, CommonUsages.SecondaryAction};
if (usagePage == UsagePage.GenericDesktop && usage == (int)GenericDesktop.Rz)
return new[] { CommonUsages.Twist };
////TODO: assign hatswitch usage to first and only to first hatswitch element
return null;
}
internal string DetermineParameters()
{
if (usagePage == UsagePage.GenericDesktop)
{
switch (usage)
{
case (int)GenericDesktop.X:
case (int)GenericDesktop.Z:
case (int)GenericDesktop.Rx:
case (int)GenericDesktop.Rz:
case (int)GenericDesktop.Vx:
case (int)GenericDesktop.Vz:
case (int)GenericDesktop.Vbrx:
case (int)GenericDesktop.Vbrz:
case (int)GenericDesktop.Slider:
case (int)GenericDesktop.Dial:
case (int)GenericDesktop.Wheel:
return DetermineAxisNormalizationParameters();
// Our Ys tend to be the opposite of what most HIDs do. We can't be sure and may well
// end up inverting a value here when we shouldn't but as always with the HID fallback,
// let's try to do what *seems* to work with the majority of devices.
case (int)GenericDesktop.Y:
case (int)GenericDesktop.Ry:
case (int)GenericDesktop.Vy:
case (int)GenericDesktop.Vbry:
return StringHelpers.Join(",", "invert", DetermineAxisNormalizationParameters());
}
}
return null;
}
private string DetermineAxisNormalizationParameters()
{
// If we have min/max bounds on the axis values, set up normalization on the axis.
// NOTE: We put the center in the middle between min/max as we can't know where the
// resting point of the axis is (may be on min if it's a trigger, for example).
if (logicalMin == 0 && logicalMax == 0)
return "normalize,normalizeMin=0,normalizeMax=1,normalizeZero=0.5";
var min = minFloatValue;
var max = maxFloatValue;
// Do nothing if result of floating-point conversion is already normalized.
if (Mathf.Approximately(0f, min) && Mathf.Approximately(0f, max))
return null;
var zero = min + (max - min) / 2.0f;
return string.Format(CultureInfo.InvariantCulture, "normalize,normalizeMin={0},normalizeMax={1},normalizeZero={2}", min, max, zero);
}
internal string DetermineProcessors()
{
switch (usagePage)
{
case UsagePage.GenericDesktop:
switch (usage)
{
case (int)GenericDesktop.X:
case (int)GenericDesktop.Y:
case (int)GenericDesktop.Z:
case (int)GenericDesktop.Rx:
case (int)GenericDesktop.Ry:
case (int)GenericDesktop.Rz:
case (int)GenericDesktop.Vx:
case (int)GenericDesktop.Vy:
case (int)GenericDesktop.Vz:
case (int)GenericDesktop.Vbrx:
case (int)GenericDesktop.Vbry:
case (int)GenericDesktop.Vbrz:
case (int)GenericDesktop.Slider:
case (int)GenericDesktop.Dial:
case (int)GenericDesktop.Wheel:
return "axisDeadzone";
}
break;
}
return null;
}
internal PrimitiveValue DetermineDefaultState()
{
switch (usagePage)
{
case UsagePage.GenericDesktop:
switch (usage)
{
case (int)GenericDesktop.HatSwitch:
// Figure out null state for hat switches.
if (hasNullState)
{
// We're looking for a value that is out-of-range with respect to the
// logical min and max but in range with respect to what we can store
// in the bits we have.
// Test lower bound, we can store >= 0.
if (logicalMin >= 1)
return new PrimitiveValue(logicalMin - 1);
// Test upper bound, we can store <= maxValue.
var maxValue = (1UL << reportSizeInBits) - 1;
if ((ulong)logicalMax < maxValue)
return new PrimitiveValue(logicalMax + 1);
}
break;
case (int)GenericDesktop.X:
case (int)GenericDesktop.Y:
case (int)GenericDesktop.Z:
case (int)GenericDesktop.Rx:
case (int)GenericDesktop.Ry:
case (int)GenericDesktop.Rz:
case (int)GenericDesktop.Vx:
case (int)GenericDesktop.Vy:
case (int)GenericDesktop.Vz:
case (int)GenericDesktop.Vbrx:
case (int)GenericDesktop.Vbry:
case (int)GenericDesktop.Vbrz:
case (int)GenericDesktop.Slider:
case (int)GenericDesktop.Dial:
case (int)GenericDesktop.Wheel:
// For axes that are *NOT* stored as signed values (which we assume are
// centered on 0), put the default state in the middle between the min and max.
if (!isSigned)
{
var defaultValue = logicalMin + (logicalMax - logicalMin) / 2;
if (defaultValue != 0)
return new PrimitiveValue(defaultValue);
}
break;
}
break;
}
return new PrimitiveValue();
}
internal void AddChildControls(ref HIDElementDescriptor element, string controlName, ref InputControlLayout.Builder builder)
{
if (usagePage == UsagePage.GenericDesktop && usage == (int)GenericDesktop.HatSwitch)
{
// There doesn't seem to be enough specificity in the HID spec to reliably figure this case out.
// Albeit detail is scarce, we could probably make some inferences based on the unit setting
// of the hat switch but even then it seems there's much left to the whims of a hardware manufacturer.
// Even if we know values go clockwise (HID spec doesn't really say; probably can be inferred from unit),
// which direction do we start with? Is 0 degrees up or right?
//
// What we do here is simply make the assumption that we're dealing with degrees here, that we go clockwise,
// and that 0 degrees is up (which is actually the opposite of the coordinate system suggested in 5.9 of
// of the HID spec but seems to be what manufacturers are actually using in practice). Of course, if the
// device we're looking at actually sets things up differently, then we end up with either an incorrectly
// oriented or (worse) a non-functional hat switch.
var nullValue = DetermineDefaultState();
if (nullValue.isEmpty)
return;
////REVIEW: this probably only works with hatswitches that have their null value at logicalMax+1
builder.AddControl(controlName + "/up")
.WithFormat(InputStateBlock.FormatBit)
.WithLayout("DiscreteButton")
.WithParameters(string.Format(CultureInfo.InvariantCulture,
"minValue={0},maxValue={1},nullValue={2},wrapAtValue={3}",
logicalMax, logicalMin + 1, nullValue.ToString(), logicalMax))
.WithBitOffset((uint)element.reportOffsetInBits % 8)
.WithSizeInBits((uint)reportSizeInBits);
builder.AddControl(controlName + "/right")
.WithFormat(InputStateBlock.FormatBit)
.WithLayout("DiscreteButton")
.WithParameters(string.Format(CultureInfo.InvariantCulture,
"minValue={0},maxValue={1}",
logicalMin + 1, logicalMin + 3))
.WithBitOffset((uint)element.reportOffsetInBits % 8)
.WithSizeInBits((uint)reportSizeInBits);
builder.AddControl(controlName + "/down")
.WithFormat(InputStateBlock.FormatBit)
.WithLayout("DiscreteButton")
.WithParameters(string.Format(CultureInfo.InvariantCulture,
"minValue={0},maxValue={1}",
logicalMin + 3, logicalMin + 5))
.WithBitOffset((uint)element.reportOffsetInBits % 8)
.WithSizeInBits((uint)reportSizeInBits);
builder.AddControl(controlName + "/left")
.WithFormat(InputStateBlock.FormatBit)
.WithLayout("DiscreteButton")
.WithParameters(string.Format(CultureInfo.InvariantCulture,
"minValue={0},maxValue={1}",
logicalMin + 5, logicalMin + 7))
.WithBitOffset((uint)element.reportOffsetInBits % 8)
.WithSizeInBits((uint)reportSizeInBits);
}
}
}
/// <summary>
/// Descriptor for a collection of HID elements.
/// </summary>
[Serializable]
public struct HIDCollectionDescriptor
{
public HIDCollectionType type;
public int usage;
public UsagePage usagePage;
public int parent; // -1 if no parent.
public int childCount;
public int firstChild;
}
/// <summary>
/// HID descriptor for a HID class device.
/// </summary>
/// <remarks>
/// This is a processed view of the combined descriptors provided by a HID as defined
/// in the HID specification, i.e. it's a combination of information from the USB device
/// descriptor, HID class descriptor, and HID report descriptor.
/// </remarks>
[Serializable]
public struct HIDDeviceDescriptor
{
/// <summary>
/// USB vendor ID.
/// </summary>
/// <remarks>
/// To get the string version of the vendor ID, see <see cref="InputDeviceDescription.manufacturer"/>
/// on <see cref="InputDevice.description"/>.
/// </remarks>
public int vendorId;
/// <summary>
/// USB product ID.
/// </summary>
public int productId;
public int usage;
public UsagePage usagePage;
/// <summary>
/// Maximum size of individual input reports sent by the device.
/// </summary>
public int inputReportSize;
/// <summary>
/// Maximum size of individual output reports sent to the device.
/// </summary>
public int outputReportSize;
/// <summary>
/// Maximum size of individual feature reports exchanged with the device.
/// </summary>
public int featureReportSize;
public HIDElementDescriptor[] elements;
public HIDCollectionDescriptor[] collections;
public string ToJson()
{
return JsonUtility.ToJson(this, true);
}
public static HIDDeviceDescriptor FromJson(string json)
{
try
{
// HID descriptors, when formatted correctly, are always json strings with no whitespace and a
// predictable order of elements, so we can try and use this simple predictive parser to extract
// the data. If for any reason the data is not formatted correctly, we'll automatically fall back
// to Unity's default json parser.
var descriptor = new HIDDeviceDescriptor();
var jsonSpan = json.AsSpan();
var parser = new PredictiveParser();
parser.ExpectSingleChar(jsonSpan, '{');
parser.AcceptString(jsonSpan, out _);
parser.ExpectSingleChar(jsonSpan, ':');
descriptor.vendorId = parser.ExpectInt(jsonSpan);
parser.AcceptSingleChar(jsonSpan, ',');
parser.AcceptString(jsonSpan, out _);
parser.ExpectSingleChar(jsonSpan, ':');
descriptor.productId = parser.ExpectInt(jsonSpan);
parser.AcceptSingleChar(jsonSpan, ',');
parser.AcceptString(jsonSpan, out _);
parser.ExpectSingleChar(jsonSpan, ':');
descriptor.usage = parser.ExpectInt(jsonSpan);