IpdInfo.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using UnityEngine;
  3. using Valve.VR;
  4. namespace SicknessReduction.Visual
  5. {
  6. public class IpdInfo : MonoBehaviour
  7. {
  8. private SteamVR_Events.Action ipdChangedAction;
  9. public delegate void OnIpdChangedEvent(float ipdMeters);
  10. public event OnIpdChangedEvent onIpdChanged; // data event
  11. private void OnEnable()
  12. {
  13. SteamVR_Events.DeviceConnected.Listen(OnDeviceConnected);
  14. ipdChangedAction = SteamVR_Events.SystemAction(EVREventType.VREvent_IpdChanged, OnIpdChanged);
  15. ipdChangedAction.enabled = true;
  16. }
  17. private void OnIpdChanged(VREvent_t vrEvent)
  18. {
  19. var ipdMeters = vrEvent.data.ipd.ipdMeters;
  20. onIpdChanged?.Invoke(ipdMeters);
  21. Debug.Log($"IPD changed to {ipdMeters}");
  22. }
  23. private void OnDisable()
  24. {
  25. ipdChangedAction.enabled = false;
  26. }
  27. private void OnDeviceConnected(int index, bool connected)
  28. {
  29. if (index < 0) return;
  30. if (!connected || OpenVR.System == null) return;
  31. var deviceClass = OpenVR.System.GetTrackedDeviceClass((uint) index);
  32. if (deviceClass != ETrackedDeviceClass.HMD) return;
  33. var error = ETrackedPropertyError.TrackedProp_Success;
  34. var ipdMeters = OpenVR.System.GetFloatTrackedDeviceProperty((uint) index,
  35. ETrackedDeviceProperty.Prop_UserIpdMeters_Float, ref error);
  36. if (error != ETrackedPropertyError.TrackedProp_Success)
  37. {
  38. Debug.LogError($"Could not get ipd for HMD at index {index}");
  39. }
  40. else
  41. {
  42. onIpdChanged?.Invoke(ipdMeters);
  43. Debug.Log($"Initial IPD = {ipdMeters}");
  44. }
  45. Debug.Log("Controller got connected at index:" + index);
  46. }
  47. }
  48. }