Search Unity

Question I want to get the button inputs of Vive Trackers in this script

Discussion in 'VR' started by studioplay, Apr 11, 2023.

  1. studioplay

    studioplay

    Joined:
    Aug 28, 2019
    Posts:
    2
    Hi group,

    My C# skills are a bit limited so here is my question:
    I am using the Vive Trackers without the HMD, which works great. I am getting the Position of the Trackers fine with these scripts:
    https://github.com/ebadier/ViveTrackers

    But I also want to get button input from the Trackers. But I don't know how to do it

    This is what I understand:
    In the ViveManager.cs the device is being recognised, and the position is being passed on to the ViveTracker.cs script


    Code (CSharp):
    1.        
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using System.Text;
    5. using UnityEngine;
    6. using Valve.VR;
    7. namespace ViveTrackers
    8. {
    9.     /// <summary>
    10.     /// This class is used to manage Vive Tracker devices using OpenVR API.
    11.     /// To run correctly, this class needs SteamVR application to run on the same computer.
    12.     /// 1) To create the trackers, call the RefreshTrackers() method. This method can be called multiple times during runtime.
    13.     /// - You can define a restricted set of Vive Tracker to create during runtime using the config file ViveTrackers.csv.
    14.     /// - Using the config file or not, only the available connected devices in SteamVR are instantiated during runtime.
    15.     /// 2) Once the trackers are created, you can update trackers'transforms using the UpdateTrackers() method.
    16.     /// Example of config file content (# is used to comment):
    17.     /// SerialNumber;Name;
    18.     /// LHR-5850D511;A;
    19.     /// LHR-9F7F5582;B;
    20.     /// #LHR-3CECF391;C;
    21.     /// #LHR-D5918492;D;
    22.     /// #LHR-AC3ABE2E;E;
    23.     /// </summary>
    24.     public sealed class ViveTrackersManager : ViveTrackersManagerBase
    25.     {
    26.         [Tooltip("The path of the file containing the list of the restricted set of trackers to use")]
    27.         public string configFilePath = "ViveTrackers.csv";
    28.         [Tooltip("True, to create only the trackers declared in the config file. False, to create all connected trackers available in SteamVR.")]
    29.         public bool createDeclaredTrackersOnly = false;
    30.         [Tooltip("Log tracker detection or not. Useful to discover trackers' serial numbers")]
    31.         public bool logTrackersDetection = true;
    32.         private bool _ovrInit = false;
    33.         private CVRSystem _cvrSystem = null;
    34.         // Trackers declared in config file [TrackedDevice_SerialNumber, Name]
    35.         private Dictionary<string, string> _declaredTrackers = new Dictionary<string, string>();
    36.         // Poses for all tracked devices in OpenVR (HMDs, controllers, trackers, etc...).
    37.         private TrackedDevicePose_t[] _ovrTrackedDevicePoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
    38.         private SteamVR_Action_Boolean triggerAction; // The action for the trigger button
    39.         private void Awake()
    40.         {
    41.             if (createDeclaredTrackersOnly)
    42.             {
    43.                 if (File.Exists(configFilePath))
    44.                 {
    45.                     // Read config file
    46.                     using (StreamReader reader = File.OpenText(configFilePath))
    47.                     {
    48.                         // Read Header
    49.                         string line = reader.ReadLine();
    50.                         char separator = line.Contains(";") ? ';' : ',';
    51.                         // Read Data
    52.                         while ((line = reader.ReadLine()) != null)
    53.                         {
    54.                             // # is used to comment line
    55.                             if (!line.StartsWith("#", System.StringComparison.InvariantCulture))
    56.                             {
    57.                                 string[] items = line.Split(separator);
    58.                                 _declaredTrackers.Add(items[0], items[1]);
    59.                             }
    60.                         }
    61.                     }
    62.                     Debug.Log("[ViveTrackersManager] " + _declaredTrackers.Count + " trackers declared in config file : " + configFilePath);
    63.                 }
    64.                 else
    65.                 {
    66.                     Debug.LogWarning("[ViveTrackersManager] config file not found : " + configFilePath + " !");
    67.                 }
    68.             }
    69.         }
    70.         /// <summary>
    71.         /// Update ViveTracker transforms using the corresponding Vive Tracker devices.
    72.         /// </summary>
    73.         public override void UpdateTrackers(float pDeltaTime)
    74.         {
    75.             if (!_ovrInit)
    76.             {
    77.                 return;
    78.             }
    79.             // Fetch last Vive Tracker devices poses.
    80.             _cvrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, _ovrTrackedDevicePoses);
    81.             // Apply poses to ViveTracker objects.
    82.             foreach (var tracker in _trackers)
    83.             {
    84.                 TrackedDevicePose_t pose = _ovrTrackedDevicePoses[tracker.ID.trackedDevice_Index];
    85.                 SteamVR_Utils.RigidTransform rigidTransform = new SteamVR_Utils.RigidTransform(pose.mDeviceToAbsoluteTracking);
    86.                 tracker.UpdateState(pose.bDeviceIsConnected, pose.bPoseIsValid, (pose.eTrackingResult == ETrackingResult.Running_OK),
    87.                     rigidTransform.pos, rigidTransform.rot, pDeltaTime);
    88.             }
    89.         }
    90.         /// <summary>
    91.         /// Scan for available Vive Tracker devices and creates ViveTracker objects accordingly.
    92.         /// Init OpenVR if not already done.
    93.         /// </summary>
    94.         public override void RefreshTrackers()
    95.         {
    96.             // Delete existing ViveTrackers
    97.             foreach (ViveTracker tracker in _trackers)
    98.             {
    99.                 Destroy(tracker.gameObject);
    100.             }
    101.             _trackers.Clear();
    102.             // OVR check
    103.             if (!_ovrInit)
    104.             {
    105.                 _ovrInit = _InitOpenVR();
    106.                 if (!_ovrInit)
    107.                 {
    108.                     return;
    109.                 }
    110.             }
    111.             Debug.Log("[ViveTrackersManager] Scanning for Tracker devices...");
    112.             for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; ++i)
    113.             {
    114.                 ETrackedDeviceClass deviceClass = _cvrSystem.GetTrackedDeviceClass(i);
    115.                 if (deviceClass == ETrackedDeviceClass.GenericTracker)
    116.                 {
    117.                     string sn = _GetTrackerSerialNumber(i);
    118.                     if (logTrackersDetection)
    119.                     {
    120.                         Debug.Log("[ViveTrackersManager] Tracker detected : " + sn);
    121.                     }
    122.                     if (sn != "")
    123.                     {
    124.                         string trackerName = "";
    125.                         bool declared = _declaredTrackers.TryGetValue(sn, out trackerName);
    126.                         // Creates only trackers declared in config file or all (if !createDeclaredTrackersOnly).
    127.                         if (declared || !createDeclaredTrackersOnly)
    128.                         {
    129.                             ViveTracker vt = GameObject.Instantiate<ViveTracker>(prefab, origin.transform.position, origin.transform.rotation, origin.transform);
    130.                             vt.Init(new ViveTrackerID(i, sn), declared ? trackerName : sn);
    131.                             _trackers.Add(vt);
    132.                         }
    133.                     }
    134.                 }
    135.             }
    136.             // Check
    137.             if (_trackers.Count == 0)
    138.             {
    139.                 Debug.LogWarning("[ViveTrackersManager] No trackers available !");
    140.                 return;
    141.             }
    142.             // Sort Trackers by name.
    143.             _trackers.Sort((ViveTracker x, ViveTracker y) => { return string.Compare(x.name, y.name); });
    144.             Debug.Log(string.Format("[ViveTrackersManager] {0} trackers declared and {1} trackers available:", _declaredTrackers.Count, _trackers.Count));
    145.             foreach (ViveTracker tracker in _trackers)
    146.             {
    147.                 Debug.Log(string.Format("[ViveTrackersManager] -> Tracker : Name = {0} ; SN = {1} ; Index = {2}", tracker.name, tracker.ID.trackedDevice_SerialNumber, tracker.ID.trackedDevice_Index));
    148.             }
    149.             // Fire Action.
    150.             if (TrackersFound != null)
    151.             {
    152.                 TrackersFound(_trackers);
    153.             }
    154.         }
    155.         private bool _InitOpenVR()
    156.         {
    157.             // OpenVR Init
    158.             EVRInitError error = EVRInitError.None;
    159.             _cvrSystem = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);
    160.             if (error != EVRInitError.None)
    161.             {
    162.                 Debug.LogError("[ViveTrackersManager] OpenVR Error : " + error);
    163.                 return false;
    164.             }
    165.             Debug.Log("[ViveTrackersManager] OpenVR initialized.");
    166.             return true;
    167.         }
    168.         private string _GetTrackerSerialNumber(uint pTrackerIndex)
    169.         {
    170.             string sn = "";
    171.             ETrackedPropertyError error = new ETrackedPropertyError();
    172.             StringBuilder sb = new StringBuilder();
    173.             _cvrSystem.GetStringTrackedDeviceProperty(pTrackerIndex, ETrackedDeviceProperty.Prop_SerialNumber_String, sb, OpenVR.k_unMaxPropertyStringSize, ref error);
    174.             if (error == ETrackedPropertyError.TrackedProp_Success)
    175.             {
    176.                 sn = sb.ToString();
    177.             }
    178.             return sn;
    179.         }
    180.     }
    181. }
    182.  
    The relevant method is:
    Code (CSharp):
    1.         public override void UpdateTrackers(float pDeltaTime)
    2.         {
    3.             if (!_ovrInit)
    4.             {
    5.                 return;
    6.             }
    7.             // Fetch last Vive Tracker devices poses.
    8.             _cvrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, _ovrTrackedDevicePoses);
    9.             // Apply poses to ViveTracker objects.
    10.             foreach (var tracker in _trackers)
    11.             {
    12.                 TrackedDevicePose_t pose = _ovrTrackedDevicePoses[tracker.ID.trackedDevice_Index];
    13.                 SteamVR_Utils.RigidTransform rigidTransform = new SteamVR_Utils.RigidTransform(pose.mDeviceToAbsoluteTracking);
    14.                 tracker.UpdateState(pose.bDeviceIsConnected, pose.bPoseIsValid, (pose.eTrackingResult == ETrackingResult.Running_OK),
    15.                     rigidTransform.pos, rigidTransform.rot, pDeltaTime);
    16.             }
    17.         }

    In the ViveManager.cs I would also want to pass on the button states of the trackers. :
    - I don't know how to get the button state in this context
    - I don't know how to pass that information on to the ViveTracker.cs script

    In the ViveTracker.cs the Position and Rotation are updated with this method:
    Code (CSharp):
    1.         public void UpdateState(bool pIsConnected, bool pIsPoseValid, bool pIsOpticallyTracked, Vector3 pLocalPosition, Quaternion pLocalRotation, float pDeltaTime)
    2.         {
    3.             bool isPosValid, isRotValid;
    4.             _trackingStateWatcher.Update(out isPosValid, out isRotValid, pIsConnected, pIsPoseValid, pIsOpticallyTracked, pDeltaTime, imuOnlyReliablePositionDuration);
    5.             //Debug.Log(string.Format("{0} | Connected : {1} | PoseValid : {2} | OpticalTracking : {3} | PosOK : {4} | RotOK : {5}",
    6.             //    name, pIsConnected, pIsPoseValid, pIsOpticallyTracked, isPosValid, isRotValid));
    7.  
    8.             // Warn for states changed.
    9.             Connected = pIsConnected;
    10.             PositionValid = isPosValid;
    11.             RotationValid = isRotValid;
    12.  
    13.             // Update only if the tracker is reliably tracked.
    14.             // This way, the tracker keeps its last transform when the tracking is lost (better than using unreliable values).
    15.             // POSITION
    16.             if (isPosValid)
    17.             {
    18.                 _transform.localPosition = pLocalPosition;
    19.             }
    20.             // ROTATION
    21.             if (isRotValid)
    22.             {
    23.                 if (_calibrate)
    24.                 {
    25.                     _trackerRotationOffset = Quaternion.Inverse(pLocalRotation);
    26.                     _calibrate = false;
    27.  
    28.                     if (Calibrated != null)
    29.                     {
    30.                         Calibrated(this);
    31.                     }
    32.                 }
    33.                 _transform.localRotation = pLocalRotation * _trackerRotationOffset;
    34.             }
    35.         }
    Help would be appreciated!
     
    Last edited: Apr 11, 2023
  2. studioplay

    studioplay

    Joined:
    Aug 28, 2019
    Posts:
    2