-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEasyOpenVRSingleton.cs
1432 lines (1235 loc) · 47.4 KB
/
EasyOpenVRSingleton.cs
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.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using EasyOpenVR.Extensions;
using EasyOpenVR.Utils;
using Valve.VR;
namespace EasyOpenVR;
public sealed class EasyOpenVRSingleton
{
/**
* This is a singleton because in my own experience connecting multiple
* times to OpenVR from the same application is a terrible idea.
*/
private static EasyOpenVRSingleton __instance = null;
private EasyOpenVRSingleton()
{
}
private bool _debug = true;
private Random _rnd = new Random();
private EVRApplicationType _appType = EVRApplicationType.VRApplication_Background;
private Action<string> _debugLogAction = null;
public static EasyOpenVRSingleton Instance
{
get
{
if (__instance == null) __instance = new EasyOpenVRSingleton();
return __instance;
}
}
#region setup
public void SetApplicationType(EVRApplicationType appType)
{
_appType = appType;
}
/**
* Will output debug information
*/
public void SetDebug(bool debug)
{
_debug = debug;
}
public void SetDebugLogAction(Action<string> action)
{
_debugLogAction = action;
}
#endregion
#region init
private uint _initState = 0;
public bool Init()
{
EVRInitError error = EVRInitError.Unknown;
try
{
_initState = OpenVR.InitInternal(ref error, _appType);
}
catch (Exception e)
{
DebugLog(e, "You might be building for 32bit with a 64bit .dll, error");
}
DebugLog(error);
return error == EVRInitError.None && _initState > 0;
}
public bool IsInitialized()
{
return _initState > 0;
}
#endregion
#region statistics
public Compositor_CumulativeStats GetCumulativeStats()
{
Compositor_CumulativeStats stats = new Compositor_CumulativeStats();
OpenVR.Compositor.GetCumulativeStats(ref stats, (uint)Marshal.SizeOf(stats));
return stats;
}
public Compositor_FrameTiming GetFrameTiming()
{
Compositor_FrameTiming timing = new Compositor_FrameTiming();
timing.m_nSize = (uint)Marshal.SizeOf(timing);
var success = OpenVR.Compositor.GetFrameTiming(ref timing, 0);
if (!success) DebugLog("Could not get frame timing.");
return timing;
}
public Compositor_FrameTiming[] GetFrameTimings(uint count)
{
Compositor_FrameTiming[] timings = new Compositor_FrameTiming[count];
var resultCount = OpenVR.Compositor.GetFrameTimings(timings);
if (resultCount == 0) DebugLog("Could not get frame timings.");
return timings;
}
#endregion
#region tracking
public TrackedDevicePose_t[] GetDeviceToAbsoluteTrackingPose(
ETrackingUniverseOrigin origin = ETrackingUniverseOrigin.TrackingUniverseStanding)
{
TrackedDevicePose_t[] trackedDevicePoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
OpenVR.System.GetDeviceToAbsoluteTrackingPose(origin, 0.0f, trackedDevicePoses);
return trackedDevicePoses;
}
#endregion
#region chaperone
public HmdQuad_t GetPlayAreaRect()
{
HmdQuad_t rect = new HmdQuad_t();
var success = OpenVR.Chaperone.GetPlayAreaRect(ref rect);
if (!success) DebugLog("Failure getting PlayAreaRect");
return rect;
}
public HmdVector2_t GetPlayAreaSize()
{
var size = new HmdVector2_t();
var success = OpenVR.Chaperone.GetPlayAreaSize(ref size.v0, ref size.v1);
if (!success) DebugLog("Failure getting PlayAreaSize");
return size;
}
public HmdMatrix34_t GetOriginPose()
{
var trackingSpace = OpenVR.Compositor.GetTrackingSpace();
var originPose = new HmdMatrix34_t();
switch(trackingSpace) {
default:
case ETrackingUniverseOrigin.TrackingUniverseRawAndUncalibrated:
break;
case ETrackingUniverseOrigin.TrackingUniverseStanding:
OpenVR.ChaperoneSetup.GetWorkingStandingZeroPoseToRawTrackingPose(ref originPose);
break;
case ETrackingUniverseOrigin.TrackingUniverseSeated: OpenVR.ChaperoneSetup.GetWorkingSeatedZeroPoseToRawTrackingPose(ref originPose);
break;
}
return originPose;
}
/**
* Will move (meters) and rotate (degrees) the working copy of the current ChaperoneSetup after having retrieved the current values.
*/
public void ModifyUniverse(HmdVector3_t offset, float rotate, bool showPreview = true)
{
var originPose = GetOriginPose();
ModifyUniverse(offset, rotate, originPose, originPose, showPreview);
}
/**
* Will move (meters) and rotate (degrees) the working copy of the current ChaperoneSetup based on the provided values.
*/
public void ModifyUniverse(HmdVector3_t offset, float rotate, HmdMatrix34_t originPose, HmdMatrix34_t correctionPose, bool showPreview = true)
{
offset = offset.Rotate(correctionPose);
var trackingSpace = OpenVR.Compositor.GetTrackingSpace();
var pose = originPose.Translate(offset).RotateY(rotate);
switch (trackingSpace)
{
case ETrackingUniverseOrigin.TrackingUniverseStanding:
OpenVR.ChaperoneSetup.SetWorkingStandingZeroPoseToRawTrackingPose(ref pose);
break;
case ETrackingUniverseOrigin.TrackingUniverseSeated:
OpenVR.ChaperoneSetup.SetWorkingSeatedZeroPoseToRawTrackingPose(ref pose);
break;
}
if(showPreview) OpenVR.ChaperoneSetup.ShowWorkingSetPreview();
}
/**
* Will hide the preview and reset the working copy of the ChaperoneSetup to the current live settings.
*/
public void ResetUniverse()
{
OpenVR.ChaperoneSetup.HideWorkingSetPreview();
OpenVR.ChaperoneSetup.RevertWorkingCopy();
}
/**
* Will save the working copy of the ChaperoneSetup to disk.
*/
public bool SaveUniverse(EChaperoneConfigFile file = EChaperoneConfigFile.Live)
{
return OpenVR.ChaperoneSetup.CommitWorkingCopy(file);
}
public bool ModifyChaperoneBounds(HmdVector3_t offset)
{
var success = OpenVR.ChaperoneSetup.GetWorkingCollisionBoundsInfo(out var physQuad);
ModifyChaperoneBounds(offset, physQuad);
if (!success) DebugLog("Failure to load Chaperone bounds.");
return success;
}
public void ModifyChaperoneBounds(HmdVector3_t offset, HmdQuad_t[] physQuad) {
for (var i = 0; i < physQuad.Length; i++)
{
MoveCorner(ref physQuad[i].vCorners0);
MoveCorner(ref physQuad[i].vCorners1);
MoveCorner(ref physQuad[i].vCorners2);
MoveCorner(ref physQuad[i].vCorners3);
}
OpenVR.ChaperoneSetup.SetWorkingCollisionBoundsInfo(physQuad);
return;
void MoveCorner(ref HmdVector3_t corner)
{
// Will not change points at vertical 0, that's the bottom of the Chaperone.
// This as it appears the bottom gets reset to 0 at a regular interval anyway.
corner.v0 += offset.v0;
if (corner.v1 != 0) corner.v1 += offset.v1;
corner.v2 += offset.v2;
}
}
#endregion
#region controller
/*
* Includes things like analogue axes of triggers, pads & sticks
* OBS: Deprecated
*/
public VRControllerState_t GetControllerState(uint index)
{
VRControllerState_t state = new VRControllerState_t();
var success = OpenVR.System.GetControllerState(index, ref state, (uint)Marshal.SizeOf(state));
if (!success) DebugLog("Failure getting ControllerState");
return state;
}
/**
* Will return the index of the role if found
* Useful if you want to know which controller is right or left.
* Note: Will eventually be removed as it has now been deprecated.
*/
public uint GetIndexForControllerRole(ETrackedControllerRole role)
{
return OpenVR.System.GetTrackedDeviceIndexForControllerRole(role);
}
#endregion
#region tracked_device
public uint[] GetIndexesForTrackedDeviceClass(ETrackedDeviceClass _class)
{
// Not sure how this one works, no ref? Skip for now.
// var result = new uint[OpenVR.k_unMaxTrackedDeviceCount];
// var count = OpenVR.System.GetSortedTrackedDeviceIndicesOfClass(_class, result, uint.MaxValue);
var result = new List<uint>();
for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
{
if (GetTrackedDeviceClass(i) == _class) result.Add(i);
}
return result.ToArray();
}
public ETrackedDeviceClass GetTrackedDeviceClass(uint index)
{
return OpenVR.System.GetTrackedDeviceClass(index);
}
/*
* Example of property: ETrackedDeviceProperty.Prop_DeviceBatteryPercentage_Float
*/
public float GetFloatTrackedDeviceProperty(uint index, ETrackedDeviceProperty property)
{
var error = new ETrackedPropertyError();
var result = OpenVR.System.GetFloatTrackedDeviceProperty(index, property, ref error);
DebugLog(error, property);
return result;
}
/*
* Example of property: ETrackedDeviceProperty.Prop_SerialNumber_String
*/
public string GetStringTrackedDeviceProperty(uint index, ETrackedDeviceProperty property)
{
var error = new ETrackedPropertyError();
StringBuilder sb = new StringBuilder((int)OpenVR.k_unMaxPropertyStringSize);
OpenVR.System.GetStringTrackedDeviceProperty(index, property, sb, OpenVR.k_unMaxPropertyStringSize, ref error);
DebugLog(error);
return sb.ToString();
}
/*
* Example of property: ETrackedDeviceProperty.Prop_EdidProductID_Int32
*/
public int GetIntegerTrackedDeviceProperty(uint index, ETrackedDeviceProperty property)
{
var error = new ETrackedPropertyError();
var result = OpenVR.System.GetInt32TrackedDeviceProperty(index, property, ref error);
DebugLog(error);
return result;
}
/*
* Example of property: ETrackedDeviceProperty.Prop_CurrentUniverseId_Uint64
*/
public ulong GetLongTrackedDeviceProperty(uint index, ETrackedDeviceProperty property)
{
var error = new ETrackedPropertyError();
var result = OpenVR.System.GetUint64TrackedDeviceProperty(index, property, ref error);
DebugLog(error);
return result;
}
/*
* Example of property: ETrackedDeviceProperty.Prop_ContainsProximitySensor_Bool
*/
public bool GetBooleanTrackedDeviceProperty(uint index, ETrackedDeviceProperty property)
{
var error = new ETrackedPropertyError();
var result = OpenVR.System.GetBoolTrackedDeviceProperty(index, property, ref error);
DebugLog(error);
return result;
}
// TODO: This has apparently been deprecated, figure out how to do it with the new input system.
public void TriggerHapticPulseInController(ETrackedControllerRole role, ushort durationMicroSec = 10000)
{
var index = GetIndexForControllerRole(role);
OpenVR.System.TriggerHapticPulse(index, 0,
durationMicroSec); // This works: https://github.com/ValveSoftware/openvr/wiki/IVRSystem::TriggerHapticPulse
}
public InputOriginInfo_t GetOriginTrackedDeviceInfo(ulong originHandle)
{
var info = new InputOriginInfo_t();
var error = OpenVR.Input.GetOriginTrackedDeviceInfo(originHandle, ref info, (uint)Marshal.SizeOf(info));
DebugLog(error);
return info;
}
public EDeviceActivityLevel GetTrackedDeviceActivityLevel(uint index)
{
return OpenVR.System.GetTrackedDeviceActivityLevel(index);
}
#endregion
#region events
private Dictionary<EVREventType, List<Action<VREvent_t>>> _events =
new Dictionary<EVREventType, List<Action<VREvent_t>>>();
///<summary>Register an event that should trigger an action, run UpdateEvents() to get new events.</summary>
public void RegisterEvent(EVREventType type, Action<VREvent_t> action)
{
RegisterEvents(new EVREventType[1] { type }, action);
}
/**
* Register multiple events that will trigger the same action.
*/
public void RegisterEvents(EVREventType[] types, Action<VREvent_t> action)
{
foreach (var t in types)
{
if (!_events.ContainsKey(t)) _events.Add(t, new List<Action<VREvent_t>>());
_events[t].Add(action);
}
}
public void UnregisterEvent(EVREventType type)
{
UnregisterEvents([type]);
}
public void UnregisterEvents(EVREventType[] types)
{
foreach (var t in types)
{
if (_events.ContainsKey(t)) _events.Remove(t);
}
}
/// <summary>Load new events and match them against registered events types, trigger actions.</summary>
public void UpdateEvents(bool debugUnhandledEvents = false)
{
var events = GetNewEvents();
foreach (var e in events)
{
var type = (EVREventType)e.eventType;
if (_events.ContainsKey(type))
{
foreach (var action in _events[type]) action.Invoke(e);
}
else if (debugUnhandledEvents) DebugLog((EVREventType)e.eventType, "Unhandled event");
}
}
///<summary>Will get all new events in the queue, note that this will cancel out triggering any registered events when running UpdateEvents().</summary>
public VREvent_t[] GetNewEvents()
{
var vrEvents = new List<VREvent_t>();
var vrEvent = new VREvent_t();
uint eventSize = (uint)Marshal.SizeOf(vrEvent);
try
{
while (OpenVR.System.PollNextEvent(ref vrEvent, eventSize))
{
vrEvents.Add(vrEvent);
}
}
catch (Exception e)
{
DebugLog(e, "Could not get new events");
}
return vrEvents.ToArray();
}
#endregion
#region input
/**
* From the SteamVR Unity Plugin: https://github.com/ValveSoftware/steamvr_unity_plugin/blob/master/Assets/SteamVR/Input/SteamVR_Input_Sources.cs
* Used to get the handle for any specific input source.
*/
public enum InputSource
{
[Description("/unrestricted")] Any,
[Description(OpenVR.k_pchPathDevices)] Devices,
[Description(OpenVR.k_pchPathUserHandLeft)]
LeftHand,
[Description(OpenVR.k_pchPathUserWristLeft)]
LeftWrist,
[Description(OpenVR.k_pchPathUserElbowLeft)]
LeftElbow,
[Description(OpenVR.k_pchPathUserShoulderLeft)]
LeftShoulder,
[Description(OpenVR.k_pchPathUserKneeLeft)]
LeftKnee,
[Description(OpenVR.k_pchPathUserAnkleLeft)]
LeftAnkle,
[Description(OpenVR.k_pchPathUserFootLeft)]
LeftFoot,
[Description(OpenVR.k_pchPathUserHandRight)]
RightHand,
[Description(OpenVR.k_pchPathUserWristRight)]
RightWrist,
[Description(OpenVR.k_pchPathUserElbowRight)]
RightElbow,
[Description(OpenVR.k_pchPathUserShoulderRight)]
RightShoulder,
[Description(OpenVR.k_pchPathUserKneeRight)]
RightKnee,
[Description(OpenVR.k_pchPathUserAnkleRight)]
RightAnkle,
[Description(OpenVR.k_pchPathUserFootRight)]
RightFoot,
[Description(OpenVR.k_pchPathUserHead)]
Head,
[Description(OpenVR.k_pchPathUserChest)]
Chest,
[Description(OpenVR.k_pchPathUserWaist)]
Waist,
[Description(OpenVR.k_pchPathUserGamepad)]
Gamepad,
[Description(OpenVR.k_pchPathUserStylus)]
Stylus,
[Description(OpenVR.k_pchPathUserKeyboard)]
Keyboard,
[Description(OpenVR.k_pchPathUserCamera)]
Camera,
[Description(OpenVR.k_pchPathUserTreadmill)]
Treadmill,
}
public enum InputType
{
Analog,
Digital,
Pose,
SkeletonSummary
}
private class InputAction
{
internal string path;
internal object data;
internal InputType type;
internal object action;
internal ulong handle = 0;
internal string pathEnd = "";
internal bool
isChord = false; // Needed to avoid filtering on the input source handle as Chords can flip their on/off action between sources depending on which button is activated/deactivated first.
internal InputActionInfo getInfo(ulong sourceHandle)
{
return new InputActionInfo
{
handle = handle,
path = path,
pathEnd = pathEnd,
sourceHandle = sourceHandle
};
}
}
public class InputActionInfo
{
public ulong handle;
public string path;
public string pathEnd;
public ulong sourceHandle;
}
private List<InputAction> _inputActions = new List<InputAction>();
private List<VRActiveActionSet_t> _inputActionSets = new List<VRActiveActionSet_t>();
/**
* Load the actions manifest to register actions for the application
* OBS: Make sure the encoding is UTF8 and not UTF8+BOM
*/
public EVRInputError LoadActionManifest(string relativePath)
{
return OpenVR.Input.SetActionManifestPath(Path.GetFullPath(relativePath));
}
public bool RegisterActionSet(string path)
{
ulong handle = 0;
var error = OpenVR.Input.GetActionSetHandle(path, ref handle);
if (handle != 0 && error == EVRInputError.None)
{
var actionSet = new VRActiveActionSet_t
{
ulActionSet = handle,
ulRestrictedToDevice = OpenVR.k_ulInvalidActionSetHandle,
nPriority = 0
};
_inputActionSets.Add(actionSet);
}
return DebugLog(error);
}
private EVRInputError RegisterAction(ref InputAction ia)
{
ulong handle = 0;
var error = OpenVR.Input.GetActionHandle(ia.path, ref handle);
var pathParts = ia.path.Split('/');
if (handle != 0 && error == EVRInputError.None)
{
ia.handle = handle;
ia.pathEnd = pathParts[pathParts.Length - 1];
_inputActions.Add(ia);
}
else DebugLog(error);
return error;
}
public void ClearInputActions()
{
_inputActionSets.Clear();
_inputActions.Clear();
}
/**
* Register an analog action with a callback action
*/
public bool RegisterAnalogAction(string path, Action<InputAnalogActionData_t, InputActionInfo> action,
bool isChord = false)
{
var ia = new InputAction
{
path = path,
type = InputType.Analog,
action = action,
data = new InputAnalogActionData_t(),
isChord = isChord
};
var error = RegisterAction(ref ia);
return DebugLog(error);
}
/**
* Register a skeleton action with a callback action
*/
public bool RegisterSkeletonSummaryAction(string path, Action<VRSkeletalSummaryData_t, InputActionInfo> action)
{
var ia = new InputAction
{
path = path,
type = InputType.SkeletonSummary,
action = action,
data = new VRSkeletalSummaryData_t()
};
var error = RegisterAction(ref ia);
return DebugLog(error);
}
/**
* Register a digital action with a callback action
*/
public bool RegisterDigitalAction(string path, Action<InputDigitalActionData_t, InputActionInfo> action,
bool isChord = false)
{
var inputAction = new InputAction
{
path = path,
type = InputType.Digital,
action = action,
data = new InputDigitalActionData_t(),
isChord = isChord
};
var error = RegisterAction(ref inputAction);
return DebugLog(error);
}
/**
* Register a digital action with a callback action
*/
public bool RegisterPoseAction(string path, Action<InputPoseActionData_t, InputActionInfo> action,
bool isChord = false)
{
var inputAction = new InputAction
{
path = path,
type = InputType.Pose,
action = action,
data = new InputPoseActionData_t(),
isChord = isChord
};
var error = RegisterAction(ref inputAction);
return DebugLog(error);
}
/**
* Retrieve the handle for the input source of a specific input device
*/
public ulong GetInputSourceHandle(InputSource inputSource)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])inputSource
.GetType()
.GetField(inputSource.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
var source = attributes.Length > 0 ? attributes[0].Description : string.Empty;
ulong handle = 0;
var error = OpenVR.Input.GetInputSourceHandle(source, ref handle);
DebugLog(error);
return handle;
}
/**
* Update all action states, this will trigger stored actions if needed.
* Digital actions triggers on change, analog actions every update.
* OBS: Only run this once per update, or you'll get no input data at all.
*/
public bool UpdateActionStates(ulong[] inputSourceHandles, ulong skeletonSummaryInputSourceHandle)
{
if (inputSourceHandles.Length == 0) inputSourceHandles = [OpenVR.k_ulInvalidPathHandle];
var error = OpenVR.Input.UpdateActionState(
_inputActionSets.ToArray(),
(uint)Marshal.SizeOf(typeof(VRActiveActionSet_t))
);
_inputActions.ForEach((InputAction action) =>
{
switch (action.type)
{
case InputType.Analog:
foreach (var handle in inputSourceHandles) GetAnalogAction(action, handle);
break;
case InputType.Digital:
foreach (var handle in inputSourceHandles) GetDigitalAction(action, handle);
break;
case InputType.Pose:
foreach (var handle in inputSourceHandles) GetPoseAction(action, handle);
break;
case InputType.SkeletonSummary:
GetSkeletalSummary(action, skeletonSummaryInputSourceHandle);
break;
}
});
return DebugLog(error);
}
private bool GetSkeletalSummary(InputAction inputAction, ulong inputSourceHandle)
{
var data = (VRSkeletalSummaryData_t)inputAction.data;
var error = OpenVR.Input.GetSkeletalSummaryData(inputAction.handle, EVRSummaryType.FromDevice, ref data);
var action = ((Action<VRSkeletalSummaryData_t, InputActionInfo>)inputAction.action);
action.Invoke(data, inputAction.getInfo(inputSourceHandle));
return true; // DebugLog(error, $"handle: {inputAction.handle}, error"); // This spams continuously when no controllers are connected.
}
private bool GetAnalogAction(InputAction inputAction, ulong inputSourceHandle)
{
if (inputAction.isChord) inputSourceHandle = 0;
var size = (uint)Marshal.SizeOf(typeof(InputAnalogActionData_t));
var data = (InputAnalogActionData_t)inputAction.data;
var error = OpenVR.Input.GetAnalogActionData(inputAction.handle, ref data, size, inputSourceHandle);
var action = ((Action<InputAnalogActionData_t, InputActionInfo>)inputAction.action);
if (data.bActive) action.Invoke(data, inputAction.getInfo(inputSourceHandle));
return DebugLog(error, $"handle: {inputAction.handle}, error");
}
private bool GetDigitalAction(InputAction inputAction, ulong inputSourceHandle)
{
if (inputAction.isChord) inputSourceHandle = 0;
var size = (uint)Marshal.SizeOf(typeof(InputDigitalActionData_t));
var data = (InputDigitalActionData_t)inputAction.data;
var error = OpenVR.Input.GetDigitalActionData(inputAction.handle, ref data, size, inputSourceHandle);
var action = ((Action<InputDigitalActionData_t, InputActionInfo>)inputAction.action);
if (data.bActive && data.bChanged) action.Invoke(data, inputAction.getInfo(inputSourceHandle));
return DebugLog(error, $"handle: {inputAction.handle}, error");
}
private bool GetPoseAction(InputAction inputAction, ulong inputSourceHandle)
{
if (inputAction.isChord) inputSourceHandle = 0;
var size = (uint)Marshal.SizeOf(typeof(InputPoseActionData_t));
var data = (InputPoseActionData_t)inputAction.data;
var error = OpenVR.Input.GetPoseActionDataRelativeToNow(inputAction.handle,
ETrackingUniverseOrigin.TrackingUniverseStanding, 0f, ref data, size, inputSourceHandle);
var action = ((Action<InputPoseActionData_t, InputActionInfo>)inputAction.action);
if (data.bActive) action.Invoke(data, inputAction.getInfo(inputSourceHandle));
return DebugLog(error, $"handle: {inputAction.handle}, error");
}
#endregion
#region screenshots
public class ScreenshotResult
{
public uint handle;
public EVRScreenshotType type;
public string filePath;
public string filePathVR;
}
/*
* Set screenshot path, if not set they will end up in: %programfiles(x86)%\Steam\steamapps\common\SteamVR\bin\
* Returns false if the directory does not exist.
*/
private string _screenshotPath = "";
public bool SetScreenshotOutputFolder(string path)
{
var exists = Directory.Exists(path);
if (exists) _screenshotPath = path;
return exists;
}
/*
* Hooks the screenshot function so it overrides the built in screenshot shortcut in SteamVR!
* Listen to the VREvent_ScreenshotTriggered event to know when to acquire a screenshot.
*/
public bool HookScreenshots()
{
EVRScreenshotType[] arr = { EVRScreenshotType.Stereo };
var error = OpenVR.Screenshots.HookScreenshot(arr);
return DebugLog(error);
}
private Tuple<string, string> GetScreenshotPaths(string prefix, string postfix,
string timestampFormat = "yyyyMMdd_HHmmss_fff")
{
var screenshotPath = _screenshotPath;
if (screenshotPath != string.Empty) screenshotPath = $"{screenshotPath}\\";
if (prefix != string.Empty) prefix = $"{prefix}_";
if (postfix != string.Empty) postfix = $"_{postfix}";
var timestamp = DateTime.Now.ToString(timestampFormat);
var filePath = $"{screenshotPath}{prefix}{timestamp}{postfix}";
var filePathVR = $"{screenshotPath}{prefix}{timestamp}_vr{postfix}";
return new Tuple<string, string>(filePath, filePathVR);
}
/**
* Takes a stereo screenshot, works with all applications as it grabs render output directly.
*
* OBS: Requires a scene application to be running, else screenshot functionality will stop working.
*/
public bool TakeScreenshot(
out ScreenshotResult screenshotResult,
string prefix = "",
string postfix = "")
{
uint handle = 0;
var filePaths = GetScreenshotPaths(prefix, postfix);
var type = EVRScreenshotType.Stereo;
var error = OpenVR.Screenshots.TakeStereoScreenshot(ref handle, filePaths.Item1, filePaths.Item2);
screenshotResult =
error == EVRScreenshotError.None
? new ScreenshotResult
{
handle = handle,
type = type,
filePath = filePaths.Item1,
filePathVR = filePaths.Item2
}
: null;
return DebugLog(error);
}
/**
* Use this to request other types of screenshots.
*
* OBS: This will NOT WORK if you have hooked the system screenshot function,
* it will seemingly leave a screenshot request in limbo preventing future screenshots.
*/
public bool RequestScreenshot(
out ScreenshotResult screenshotResult,
string prefix = "",
string postfix = "",
EVRScreenshotType screenshotType = EVRScreenshotType.Stereo)
{
var filePaths = GetScreenshotPaths(prefix, postfix);
uint handle = 0;
var error = OpenVR.Screenshots.RequestScreenshot(ref handle, screenshotType, filePaths.Item1, filePaths.Item2);
screenshotResult =
error == EVRScreenshotError.None
? new ScreenshotResult
{
handle = handle,
type = screenshotType,
filePath = filePaths.Item1,
filePathVR = filePaths.Item2
}
: null;
return DebugLog(error);
}
/*
* This will attempt to submit the screenshot to Steam to be in the screenshot library for the current scene application.
*/
public bool SubmitScreenshotToSteam(ScreenshotResult screenshotResult)
{
var error = OpenVR.Screenshots.SubmitScreenshot(
screenshotResult.handle,
screenshotResult.type,
$"{screenshotResult.filePath}.png",
$"{screenshotResult.filePathVR}.png"
);
return DebugLog(error);
}
#endregion
#region video
public float GetRenderTargetForCurrentApp()
{
return GetFloatSetting(OpenVR.k_pch_SteamVR_Section, OpenVR.k_pch_SteamVR_SupersampleScale_Float);
}
public bool GetSuperSamplingEnabledForCurrentApp()
{
return GetBoolSetting(OpenVR.k_pch_SteamVR_Section, OpenVR.k_pch_SteamVR_SupersampleManualOverride_Bool);
}
public bool SetSuperSamplingEnabledForCurrentApp(bool enabled)
{
return SetBoolSetting(OpenVR.k_pch_SteamVR_Section, OpenVR.k_pch_SteamVR_SupersampleManualOverride_Bool,
enabled);
}
public float GetSuperSamplingForCurrentApp()
{
return GetFloatSetting(OpenVR.k_pch_SteamVR_Section, OpenVR.k_pch_SteamVR_SupersampleScale_Float);
}
/**
* Will set the render scale for the current app
* scale 1 = 100%
* OBS: Will enable super sampling override if it is not enabled
*/
public bool SetSuperSamplingForCurrentApp(float scale)
{
return SetFloatSetting(OpenVR.k_pch_SteamVR_Section, OpenVR.k_pch_SteamVR_SupersampleScale_Float, scale);
}
#endregion
#region notifications
/*
* Thank you artumino and in extension Marlamin on GitHub for their public code which I referenced for notifications.
* Also thanks to Valve for finally adding the interface for notifications to the C# header file.
*
* In reality I tried implementing notifications back in April 2016, poked Valve about it in October the same year,
* pointed out what was missing in May and December 2017, yet again in January 2019 and boom, now we have it!
*/
private List<uint> _notifications = new List<uint>();
/*
* We initialize an overlay to display notifications with.
* The title will be visible above the notification.
* Returns the handle used to send notifications, 0 on fail.
*/
public ulong InitNotificationOverlay(string notificationTitle)
{
ulong handle = 0;
var key = Guid.NewGuid().ToString();
var error = OpenVR.Overlay.CreateOverlay(key, notificationTitle, ref handle);
if (DebugLog(error)) return handle;
return 0;
}
public uint EnqueueNotification(ulong overlayHandle, string message)
{
return EnqueueNotification(overlayHandle, message, new NotificationBitmap_t());
}
public uint EnqueueNotification(ulong overlayHandle, string message, NotificationBitmap_t bitmap)
{
return EnqueueNotification(overlayHandle, EVRNotificationType.Transient, message,
EVRNotificationStyle.Application, bitmap);
}
/*
* Will enqueue a notification to be displayed in the headset.
* Returns ID for this specific notification.
*/
public uint EnqueueNotification(ulong overlayHandle, EVRNotificationType type, string message,
EVRNotificationStyle style, NotificationBitmap_t bitmap)
{
uint id = 0;
while (id == 0 || _notifications.Contains(id)) id = (uint)_rnd.Next(); // Not sure why we do this
var error = OpenVR.Notifications.CreateNotification(overlayHandle, 0, type, message, style, ref bitmap, ref id);
DebugLog(error);
_notifications.Add(id);
return id;
}
/*
* Used to dismiss a persistent notification.
*/
public bool DismissNotification(uint id, out EVRNotificationError error)
{
error = OpenVR.Notifications.RemoveNotification(id);
if (error == EVRNotificationError.OK) _notifications.Remove(id);
return DebugLog(error);
}
public bool EmptyNotificationsQueue()
{
var error = EVRNotificationError.OK;