Ejemplo n.º 1
0
    private void CheckLeftOrRightContoller(MessageObject obj)
    {
        ETrackedControllerRole trackerdRole = ETrackedControllerRole.Invalid;
        var system = Valve.VR.OpenVR.System;

        if (system != null && null != trackedController)
        {
            trackerdRole = system.GetControllerRoleForTrackedDeviceIndex(trackedController.controllerIndex);
        }

        #region use by string name as legacy
#if By_Name_String
        controllerType = HandleControllerType.Invalid;
        if (this.name.Contains("left"))
        {
            controllerType = HandleControllerType.LeftHand;
        }
        if (this.name.Contains("right"))
        {
            controllerType = HandleControllerType.RightHand;
        }
#endif
        #endregion
        controllerType = (HandleControllerType)((int)trackerdRole);
    }
Ejemplo n.º 2
0
    // Token: 0x0600570A RID: 22282 RVA: 0x001DFABC File Offset: 0x001DDEBC
    public override void GenerateHapticEvent(VRCTracking.ID id, float duration, float amplitude, float frequency)
    {
        CVRSystem system = OpenVR.System;

        if (system == null)
        {
            return;
        }
        ETrackedControllerRole unDeviceType = ETrackedControllerRole.Invalid;

        if (id != VRCTracking.ID.HandTracker_LeftWrist)
        {
            if (id == VRCTracking.ID.HandTracker_RightWrist)
            {
                unDeviceType = ETrackedControllerRole.RightHand;
            }
        }
        else
        {
            unDeviceType = ETrackedControllerRole.LeftHand;
        }
        VRCTrackingTouch.HapticWave hapticWave = default(VRCTrackingTouch.HapticWave);
        hapticWave.controllerIndex = system.GetTrackedDeviceIndexForControllerRole(unDeviceType);
        hapticWave.duration        = duration;
        hapticWave.strength        = Mathf.Clamp01(amplitude);
        hapticWave.frequency       = frequency;
        if (this.currentHapticLoop[(int)((UIntPtr)hapticWave.controllerIndex)] != null)
        {
            base.StopCoroutine(this.currentHapticLoop[(int)((UIntPtr)hapticWave.controllerIndex)]);
        }
        this.currentHapticLoop[(int)((UIntPtr)hapticWave.controllerIndex)] = base.StartCoroutine("HapticLoop", hapticWave);
    }
Ejemplo n.º 3
0
    private void ReportControllerFound(ETrackedControllerRole role, uint index)
    {
        switch (role)
        {
        case ETrackedControllerRole.LeftHand:
            if (!_alreadyFoundLeft)
            {
                Log("Found Controller ( Device: {0} ): Left", index);
            }
            _alreadyFoundLeft = true;
            break;

        case ETrackedControllerRole.RightHand:
            if (!_alreadyFoundRight)
            {
                Log("Found Controller ( Device: {0} ): Right", index);
            }
            _alreadyFoundRight = true;
            break;

        case ETrackedControllerRole.Invalid:
            Log("Found Controller ( Device: {0} ): Unassigned", index);
            break;
        }
    }
Ejemplo n.º 4
0
 private void CallIndexChanged(ETrackedControllerRole role, uint index)
 {
     if (OnControllerIndexChanged != null)
     {
         OnControllerIndexChanged(role, index);
     }
 }
Ejemplo n.º 5
0
        private uint GetControllerId(Chirality chirality)
        {
            ETrackedControllerRole targetRole = ETrackedControllerRole.Invalid;

            if (chirality == Chirality.Left)
            {
                targetRole = ETrackedControllerRole.LeftHand;
            }
            if (chirality == Chirality.Right)
            {
                targetRole = ETrackedControllerRole.RightHand;
            }

            uint index = 0;

            for (int i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                if (OpenVR.System.GetControllerRoleForTrackedDeviceIndex((uint)i) == targetRole)
                {
                    index = (uint)i;
                    break;
                }
            }

            return(index);
        }
Ejemplo n.º 6
0
 public void SetOverlayTransformTrackedDeviceRelative(ETrackedControllerRole Device, HmdMatrix34_t matrix)
 {
     if (this.Controller != null)
     {
         OpenVR.Overlay.SetOverlayTransformTrackedDeviceRelative(this.Handle, OpenVR.System.GetTrackedDeviceIndexForControllerRole(Device), ref matrix);
     }
 }
    private void ShowInfo(uint deviceIndex)
    {
        ETrackedDeviceClass    deviceClass = OpenVR.System.GetTrackedDeviceClass(deviceIndex);
        ETrackedControllerRole role        = GetDeviceRole(deviceIndex);
        bool hasbattery = HasBattery(deviceIndex);
        bool isCharging = IsCharging(deviceIndex);

        Debug.Log($"{this}:#{deviceIndex} {deviceClass}/{role} battery: {hasbattery} charging: {isCharging}", this);
    }
Ejemplo n.º 8
0
        public void OnLateUpdate()
        {
            dispatchOpenVREvents();

            EVRCompositorError compositorError = OpenVR.Compositor.WaitGetPoses(VRManager.RenderPoses, VRManager.GamePoses);

            if (compositorError != EVRCompositorError.None)
            {
                throw new Exception("OpenVr error: " + compositorError.ToString());
            }

            OpenVR.System.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, Utils.CalculatePredictedSecondsToPhotons(), VRManager.DevicePoses);
            SteamVR_Events.NewPoses.Send(VRManager.DevicePoses);

            for (int i = 0; i < VRManager.DevicePoses.Length; i++)
            {
                TrackedDevicePose_t devicePose = VRManager.DevicePoses[i];
                if (!devicePose.bDeviceIsConnected || !devicePose.bPoseIsValid)
                {
                    continue;
                }

                SteamVR_Utils.RigidTransform rigidTransform = new SteamVR_Utils.RigidTransform(devicePose.mDeviceToAbsoluteTracking);

                ETrackedDeviceClass deviceType = OpenVR.System.GetTrackedDeviceClass((uint)i);

                if (deviceType == ETrackedDeviceClass.HMD)
                {
                    Head.transform.localPosition = rigidTransform.pos;
                    Head.transform.localRotation = rigidTransform.rot;
                    Head.Velocity        = fromHmdVector3_t(devicePose.vVelocity);
                    Head.AngularVelocity = fromHmdVector3_t(devicePose.vAngularVelocity);
                    Head.DeviceIndex     = (uint)i;
                }
                else if (deviceType == ETrackedDeviceClass.Controller)
                {
                    ETrackedControllerRole role = OpenVR.System.GetControllerRoleForTrackedDeviceIndex((uint)i);
                    if (role == ETrackedControllerRole.LeftHand)
                    {
                        LeftController.transform.localPosition = rigidTransform.pos;
                        LeftController.transform.localRotation = rigidTransform.rot;
                        LeftController.Velocity        = fromHmdVector3_t(devicePose.vVelocity);
                        LeftController.AngularVelocity = fromHmdVector3_t(devicePose.vAngularVelocity);
                        LeftController.DeviceIndex     = (uint)i;
                    }
                    else if (role == ETrackedControllerRole.RightHand)
                    {
                        RightController.transform.localPosition = rigidTransform.pos;
                        RightController.transform.localRotation = rigidTransform.rot;
                        RightController.Velocity        = fromHmdVector3_t(devicePose.vVelocity);
                        RightController.AngularVelocity = fromHmdVector3_t(devicePose.vAngularVelocity);
                        RightController.DeviceIndex     = (uint)i;
                    }
                }
            }
        }
Ejemplo n.º 9
0
 public OpenVRDevice(string id, bool isConnected, bool isTracking, ETrackedControllerRole controllerRole, ETrackedDeviceClass deviceClass, string modelName, string role)
 {
     this.id             = id;
     this.isConnected    = isConnected;
     this.isTracking     = isTracking;
     this.controllerRole = controllerRole;
     this.deviceClass    = deviceClass;
     this.modelName      = modelName;
     this.role           = role;
 }
    /// <summary>
    /// Creates a button for a tracked object detected in FindTrackedObjects() and sets it up.
    /// </summary>
    /// <param name="deviceindex">Index of the tracked object.</param>
    /// <param name="scriptref">Required ChooseTrackedObjectButton script that must be on the prefab.</param>
    private GameObject CreateTrackedObjectPrefab(uint deviceindex, out ChooseTrackedObjectButton scriptref)
    {
        string label = "ERROR";

#if ZED_STEAM_VR
        ETrackedDeviceClass    dclass = OpenVR.System.GetTrackedDeviceClass(deviceindex);
        ETrackedControllerRole role   = OpenVR.System.GetControllerRoleForTrackedDeviceIndex(deviceindex);

        if (!(dclass == ETrackedDeviceClass.Controller || dclass == ETrackedDeviceClass.GenericTracker))
        {
            //Debug.LogError("Tried to create button for tracked device of index " + deviceindex + ", but it's role is " + dclass + ".");
            scriptref = null;
            return(null);
        }

        if (role == ETrackedControllerRole.LeftHand)
        {
            label = "Left\r\nController";
        }
        else if (role == ETrackedControllerRole.RightHand)
        {
            label = "Right\r\nController";
        }
        else if (dclass == ETrackedDeviceClass.GenericTracker)
        {
            label = "Tracker";
        }
        else
        {
            //Debug.LogError("Tried to create button for tracked device of index " + deviceindex + " with an invalid role/device class combo: " +
            //    role + " / " + dclass);
            scriptref = null;
            return(null);
        }
#elif ZED_OCULUS
        if (deviceindex == TOUCH_INDEX_LEFT)
        {
            label = "Left\r\nController";
        }
        else if (deviceindex == TOUCH_INDEX_RIGHT)
        {
            label = "Right\r\nController";
        }
#endif

        GameObject buttongo = Instantiate(chooseObjectButtonPrefab, transform, false);
        scriptref = buttongo.GetComponentInChildren <ChooseTrackedObjectButton>();

        scriptref.SetDeviceIndex((int)deviceindex);
        scriptref.SetLabel(label);
        buttongo.name = "Select " + label + " Button";
        scriptref.OnTrackedObjectSelected += OnTrackedObjectSelected;

        return(buttongo);
    }
Ejemplo n.º 11
0
    private void CheckLeftOrRightContoller(MessageObject obj)
    {
        ETrackedControllerRole trackerdRole = ETrackedControllerRole.Invalid;
        var system = Valve.VR.OpenVR.System;

        if (system != null && null != trackedController)
        {
            trackerdRole = system.GetControllerRoleForTrackedDeviceIndex(trackedController.controllerIndex);
        }
        controllerType = (HandleControllerType)((int)trackerdRole);
    }
 // If the controller we are tracking changes index, update
 private void OnControllerIndexChanged(ETrackedControllerRole role, uint index)
 {
     if (Type == EType.LeftController && role == ETrackedControllerRole.LeftHand)
     {
         Reset();
     }
     else if (Type == EType.RightController && role == ETrackedControllerRole.RightHand)
     {
         Reset();
     }
 }
Ejemplo n.º 13
0
 // If the controller we are tracking changes index, update
 private void OnControllerIndexChanged(ETrackedControllerRole role, uint index)
 {
     if (_anchorDevice == MountDevice.LeftController && role == ETrackedControllerRole.LeftHand)
     {
         _anchorDevice = MountDevice.World; // This will trick the system into reattaching the overlay
     }
     else if (_anchorDevice == MountDevice.RightController && role == ETrackedControllerRole.RightHand)
     {
         _anchorDevice = MountDevice.World; // This will trick the system into reattaching the overlay
     }
 }
Ejemplo n.º 14
0
    void Update()
    {
        if (Input.GetKeyDown(mRecalibrateButton))
        {
            // switch the roles around
            myRole = myRole == ETrackedControllerRole.LeftHand ? ETrackedControllerRole.RightHand : ETrackedControllerRole.LeftHand;

            // get the new glove index
            GetGloveIndex();
        }
    }
 private void DoIndexAssignment(ETrackedControllerRole role, ref uint index, uint newIndex)
 {
     if (index == newIndex)
     {
         return;
     }
     index = newIndex;
     if (OnControllerIndexChanged != null)
     {
         OnControllerIndexChanged(role, index);
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates a GameObject that represents the left or right device controllers.
        /// These are the "VR hands".
        /// </summary>
        /// <param name="role">The controller device role (left or right).</param>
        /// <returns>The GameObject for the "VR hand".</returns>
        protected GameObject CreateManipulator(ETrackedControllerRole role)
        {
            // create new GameObject
            GameObject manipulator = new GameObject("KVR_Manipulator");

            DontDestroyOnLoad(manipulator);

            // define the Manipulator component
            Manipulator manipulatorComponent = manipulator.AddComponent <Manipulator>();

            manipulatorComponent.SetRole(role);

            return(manipulator);
        }
        public void TriggerHapticPulse(XRNode node, byte strength)
        {
            if (strength == 0)
            {
                return;
            }

            float     pulseDuration  = Time.smoothDeltaTime * 1000000.0f;
            float     biasedStrength = Plugin.SteamBiasTable[Math.Min(9, (int)strength)];
            float     F      = pulseDuration * biasedStrength;
            CVRSystem system = OpenVR.System;
            ETrackedControllerRole unDeviceType      = (node == XRNode.LeftHand) ? ETrackedControllerRole.LeftHand : ETrackedControllerRole.RightHand;
            uint trackedDeviceIndexForControllerRole = system.GetTrackedDeviceIndexForControllerRole(unDeviceType);

            system.TriggerHapticPulse(trackedDeviceIndexForControllerRole, 0u, (char)F);
        }
Ejemplo n.º 18
0
        public void SetRole(ETrackedControllerRole role)
        {
            if (role != ETrackedControllerRole.LeftHand && role != ETrackedControllerRole.RightHand)
            {
                throw new ArgumentException("Cannot assign controller role \"" + role.ToString() + "\"");
            }

            // assign role
            this.Role = role;

            // ensure glove object is mirrored correctly
            Vector3 gloveObjectScale = gloveGameObject.transform.localScale;

            if (Role == ETrackedControllerRole.RightHand)
            {
                gloveObjectScale.y *= -1f;
                gloveGameObject.transform.localScale = gloveObjectScale;
            }
        }
Ejemplo n.º 19
0
        private GameObject CreateManipulator(ETrackedControllerRole role)
        {
            // create new GameObject
            GameObject manipulator = GameObject.CreatePrimitive(PrimitiveType.Sphere);

            manipulator.name = "VR_Manipulator_" + role.ToString();
            DontDestroyOnLoad(manipulator);

            // define the render model
            manipulator.transform.localScale = Vector3.one *
                                               ((role == ETrackedControllerRole.RightHand) ? 0.02f : 0.08f);
            Color        manipulatorColor    = (role == ETrackedControllerRole.RightHand) ? Color.green : Color.red;
            MeshRenderer manipulatorRenderer = manipulator.GetComponent <MeshRenderer>();

            manipulatorRenderer.material.color = manipulatorColor;

            // define the collider
            Rigidbody manipulatorRigidbody = manipulator.AddComponent <Rigidbody>();

            manipulatorRigidbody.isKinematic = true;
            SphereCollider manipulatorCollider = manipulator.GetComponent <SphereCollider>();

            manipulatorCollider.isTrigger = true;

            // define the Manipulator component
            Manipulator manipulatorComponent = manipulator.AddComponent <Manipulator>();

            manipulatorComponent.role          = role;
            manipulatorComponent.originalColor = manipulatorColor;
            manipulatorComponent.activeColor   = Color.yellow;

#if DEBUG
            manipulatorRenderer.enabled = true;
#else
            manipulatorRenderer.enabled = false;
#endif

            return(manipulator);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates a GameObject that represents the left or right device controllers.
        /// These are the "VR hands".
        /// </summary>
        /// <param name="role">The controller device role (left or right).</param>
        /// <returns>The GameObject for the "VR hand".</returns>
        protected GameObject CreateManipulator(ETrackedControllerRole role)
        {
            // create new GameObject
            GameObject manipulator = new GameObject("KVR_Manipulator_" + role.ToString());

            DontDestroyOnLoad(manipulator);

            // define the Manipulator component
            Manipulator manipulatorComponent = manipulator.AddComponent <Manipulator>();

            manipulatorComponent.role = role;

#if DEBUG
            GameObject manipulatorGizmo = Utils.CreateGizmo();
            manipulatorGizmo.transform.SetParent(manipulator.transform);
            manipulatorGizmo.transform.localPosition = Vector3.zero;
            manipulatorGizmo.transform.localRotation = Quaternion.identity;
            manipulatorGizmo.transform.localScale    = Vector3.one * 0.5f;
#endif

            return(manipulator);
        }
Ejemplo n.º 21
0
	public abstract uint GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType);
Ejemplo n.º 22
0
 public void SetOverlayTransformTrackedDeviceRelative(ETrackedControllerRole Device)
 {
     SetOverlayTransformTrackedDeviceRelative(Device, identity);
 }
Ejemplo n.º 23
0
    private void UpdateInput(HOTK_TrackedDevice device, ref bool clicked, ref float clickTime, ref float doubleClickTime, ref bool touchpadClicked, ref float touchpadTime, ref bool grips, ref float gripsTime, ref bool touchpadTouch, ETrackedControllerRole role)
    {
        if (device == null || !device.IsValid)
        {
            return;
        }
        var svr = SteamVR.instance;

        if (svr == null)
        {
            return;
        }
        var c = new VRControllerState_t();

        svr.hmd.GetControllerState((uint)device.Index, ref c);
        // c.rAxis0 is Trackpad
        // c.rAxis1 is Trigger

        // Trigger check
        if (c.rAxis1.x >= 0.99f)
        {
            if (!clicked)
            {
                clicked   = true;
                clickTime = Time.time;
                if (OnControllerTriggerDown != null)
                {
                    OnControllerTriggerDown(device);
                }
            }
        }
        else
        {
            if (clicked)
            {
                clicked = false;
                if (OnControllerTriggerUp != null)
                {
                    OnControllerTriggerUp(device);
                }

                if ((Time.time - doubleClickTime) < 0.25f)
                {
                    if (OnControllerTriggerDoubleClicked != null)
                    {
                        OnControllerTriggerDoubleClicked(device);
                    }
                    return;
                }
                doubleClickTime = Time.time;

                if (!((Time.time - clickTime) < 0.25f))
                {
                    return;
                }
                if (OnControllerTriggerClicked != null)
                {
                    OnControllerTriggerClicked(device);
                }
            }
        }

        // Touchpad Check
        if (GetPress(c, EVRButtonId.k_EButton_SteamVR_Touchpad))
        {
            if (!touchpadClicked)
            {
                touchpadClicked = true;
                touchpadTime    = Time.time;
                if (OnControllerTouchpadDown != null)
                {
                    OnControllerTouchpadDown(device);
                }
            }
        }
        else
        {
            if (touchpadClicked)
            {
                touchpadClicked = false;
                if (OnControllerTouchpadUp != null)
                {
                    OnControllerTouchpadUp(device);
                }
                if (!((Time.time - touchpadTime) < 0.25f))
                {
                    return;
                }
                if (OnControllerTouchpadClicked != null)
                {
                    OnControllerTouchpadClicked(device);
                }
            }
        }

        // Grips Check
        if (GetPress(c, EVRButtonId.k_EButton_Grip))
        {
            if (!grips)
            {
                grips     = true;
                gripsTime = Time.time;
                if (OnControllerGripsDown != null)
                {
                    OnControllerGripsDown(device);
                }
            }
        }
        else
        {
            if (grips)
            {
                grips = false;
                if (OnControllerGripsUp != null)
                {
                    OnControllerGripsUp(device);
                }
                if (!((Time.time - gripsTime) < 0.25f))
                {
                    return;
                }
                if (OnControllerGripsClicked != null)
                {
                    OnControllerGripsClicked(device);
                }
            }
        }

        if (c.rAxis0.x != 0f && c.rAxis0.y != 0f)
        {
            if (!touchpadTouch)
            {
                touchpadTouch = true;
                if (OnControllerTouchpadTouchStart != null)
                {
                    OnControllerTouchpadTouchStart(device, c.rAxis0.x, c.rAxis0.y);
                }
            }
            else if (OnControllerTouchpadTouchMove != null)
            {
                OnControllerTouchpadTouchMove(device, c.rAxis0.x, c.rAxis0.y);
            }
        }
        else
        {
            if (touchpadTouch)
            {
                touchpadTouch = false;
                if (OnControllerTouchpadTouchEnd != null)
                {
                    OnControllerTouchpadTouchEnd(device);
                }
            }
        }
    }
Ejemplo n.º 24
0
	internal static extern uint VR_IVRSystem_GetTrackedDeviceIndexForControllerRole(IntPtr instancePtr, ETrackedControllerRole unDeviceType);
Ejemplo n.º 25
0
        private static void Worker()
        {
            Thread.CurrentThread.IsBackground = true;
            while (true)
            {
                // Getting events
                var vrEvents = new List <VREvent_t>();
                var vrEvent  = new VREvent_t();
                try
                {
                    while (OpenVR.System.PollNextEvent(ref vrEvent, Utils.SizeOf(vrEvent)))
                    {
                        vrEvents.Add(vrEvent);
                    }
                }
                catch (Exception e)
                {
                    Utils.PrintWarning($"Could not get evemt: {e.Message}");
                }

                // Priting events
                foreach (var e in vrEvents)
                {
                    var pid = e.data.process.pid;
                    if ((EVREventType)vrEvent.eventType != EVREventType.VREvent_None)
                    {
                        var name    = Enum.GetName(typeof(EVREventType), e.eventType);
                        var message = $"[{pid}] {name}";
                        if (pid == 0)
                        {
                            Utils.PrintVerbose(message);
                        }
                        else if (name.ToLower().Contains("fail"))
                        {
                            Utils.PrintWarning(message);
                        }
                        else if (name.ToLower().Contains("error"))
                        {
                            Utils.PrintError(message);
                        }
                        else if (name.ToLower().Contains("success"))
                        {
                            Utils.PrintInfo(message);
                        }
                        else
                        {
                            Utils.Print(message);
                        }
                    }
                }

                // Update action set
                // Seems I need the action set when updating the state of actions.
                var actionSet = new VRActiveActionSet_t();
                actionSet.ulActionSet = mActionSetHandle;
                var actionSetArr = new VRActiveActionSet_t[1] {
                    actionSet
                };

                // But I cannot get the size of an array so I supply the one for the set inside the array.
                // No really sure what I am actually supposed to do here (or above).
                var errorUAS = OpenVR.Input.UpdateActionState(actionSetArr, Utils.SizeOf(actionSet));
                if (errorUAS != EVRInputError.None)
                {
                    Utils.PrintError($"UpdateActionState Error: {Enum.GetName(typeof(EVRInputError), errorUAS)}");
                }

                // Get input actions
                var roles = new ETrackedControllerRole[] { ETrackedControllerRole.LeftHand, ETrackedControllerRole.RightHand };
                foreach (var role in roles)
                {
                    // Get device to restrict to, appears mandatory, makes sense for shared actions.
                    uint index = OpenVR.System.GetTrackedDeviceIndexForControllerRole(role);

                    // Load action data
                    var action = new InputDigitalActionData_t(); // I assume this is used for boolean inputs.
                    var size   = Utils.SizeOf(action);
                    var error  = OpenVR.Input.GetDigitalActionData(mActionHandle, ref action, size, index);

                    // Result
                    if (error != mLastError)
                    {
                        mLastError = error;
                        Utils.PrintError($"DigitalActionDataError: {Enum.GetName(typeof(EVRInputError), error)}");
                    }

                    Debug.WriteLine(action.bActive + " " + action.bChanged);
                    if (action.bChanged)
                    {
                        Utils.PrintInfo($"Action state changed to: {action.bState}");
                    }
                }

                // Restrict rate
                Thread.Sleep(1000 / 30);
            }
        }
Ejemplo n.º 26
0
        private void VRInit()
        {
            // init
            var error = EVRInitError.None;

            system = OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            OpenVR.GetGenericInterface(OpenVR.IVRSystem_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception();
            }

            TrackedDevicePose_t[] m_rTrackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
            TrackedDevicePose_t   TrackedDevicePose    = new TrackedDevicePose_t();
            VRControllerState_t   controllerState      = new VRControllerState_t();

            while (true)
            {
                system.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, m_rTrackedDevicePose);

                for (uint unDevice = 0; unDevice < OpenVR.k_unMaxTrackedDeviceCount; unDevice++)
                {
                    if (!system.IsTrackedDeviceConnected(unDevice))
                    {
                        continue;
                    }

                    HmdVector3_t    position;
                    HmdQuaternion_t quaternion;

                    // Get what type of device it is and work with its data
                    ETrackedDeviceClass    trackedDeviceClass    = system.GetTrackedDeviceClass(unDevice);
                    ETrackedControllerRole trackedControllerRole = system.GetControllerRoleForTrackedDeviceIndex(unDevice);
                    ETrackingResult        eTrackingResult;

                    switch (trackedDeviceClass)
                    {
                    case ETrackedDeviceClass.HMD:

                        // get the position and rotation
                        position   = GetPosition(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);
                        quaternion = GetRotation(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);

                        // for printing some more info to the user about the state of the device/pose
                        eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult;

                        // print the tracking data
                        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                            HmdIndex.Text       = String.Format("{0}", unDevice);
                            HmdVectorX.Text     = String.Format("{0:F4}", position.v0);
                            HmdVectorY.Text     = String.Format("{0:F4}", position.v1);
                            HmdVectorZ.Text     = String.Format("{0:F4}", position.v2);
                            HmdQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                            HmdQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                            HmdQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                            HmdQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                            HmdState.Text       = GetDeviceState(eTrackingResult);
                        }));
                        break;

                    case ETrackedDeviceClass.Controller:

                        // get the position and rotation
                        position   = GetPosition(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);
                        quaternion = GetRotation(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking);

                        // for printing some more info to the user about the state of the device/pose
                        eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult;

                        // get Controllers info
                        system.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, unDevice, ref controllerState, (uint)Marshal.SizeOf(controllerState), ref TrackedDevicePose);

                        switch (trackedControllerRole)
                        {
                        case ETrackedControllerRole.LeftHand:

                            // print the tracking data
                            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                                CLIndex.Text       = String.Format("{0}", unDevice);
                                CLVectorX.Text     = String.Format("{0:F4}", position.v0);
                                CLVectorY.Text     = String.Format("{0:F4}", position.v1);
                                CLVectorZ.Text     = String.Format("{0:F4}", position.v2);
                                CLQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                                CLQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                                CLQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                                CLQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                                CLState.Text       = GetDeviceState(eTrackingResult);
                                CLulPressed.Text   = String.Format("{0}", controllerState.ulButtonPressed);
                                CLulTouched.Text   = String.Format("{0}", controllerState.ulButtonTouched);
                                CLAxis0X.Text      = String.Format("{0:F4}", controllerState.rAxis0.x);
                                CLAxis0Y.Text      = String.Format("{0:F4}", controllerState.rAxis0.y);
                                CLAxis1X.Text      = String.Format("{0:F4}", controllerState.rAxis1.x);
                                CLAxis1Y.Text      = String.Format("{0:F4}", controllerState.rAxis1.y);
                                CLAxis2X.Text      = String.Format("{0:F4}", controllerState.rAxis2.x);
                                CLAxis2Y.Text      = String.Format("{0:F4}", controllerState.rAxis2.y);
                                CLAxis3X.Text      = String.Format("{0:F4}", controllerState.rAxis3.x);
                                CLAxis3Y.Text      = String.Format("{0:F4}", controllerState.rAxis3.y);
                                CLAxis4X.Text      = String.Format("{0:F4}", controllerState.rAxis4.x);
                                CLAxis4Y.Text      = String.Format("{0:F4}", controllerState.rAxis4.y);
                            }));
                            break;

                        case ETrackedControllerRole.RightHand:

                            // print the tracking data
                            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                                CRIndex.Text       = String.Format("{0}", unDevice);
                                CRVectorX.Text     = String.Format("{0:F4}", position.v0);
                                CRVectorY.Text     = String.Format("{0:F4}", position.v1);
                                CRVectorZ.Text     = String.Format("{0:F4}", position.v2);
                                CRQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                                CRQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                                CRQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                                CRQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                                CRState.Text       = GetDeviceState(eTrackingResult);
                                CRulPressed.Text   = String.Format("{0}", controllerState.ulButtonPressed);
                                CRulTouched.Text   = String.Format("{0}", controllerState.ulButtonTouched);
                                CRAxis0X.Text      = String.Format("{0:F4}", controllerState.rAxis0.x);
                                CRAxis0Y.Text      = String.Format("{0:F4}", controllerState.rAxis0.y);
                                CRAxis1X.Text      = String.Format("{0:F4}", controllerState.rAxis1.x);
                                CRAxis1Y.Text      = String.Format("{0:F4}", controllerState.rAxis1.y);
                                CRAxis2X.Text      = String.Format("{0:F4}", controllerState.rAxis2.x);
                                CRAxis2Y.Text      = String.Format("{0:F4}", controllerState.rAxis2.y);
                                CRAxis3X.Text      = String.Format("{0:F4}", controllerState.rAxis3.x);
                                CRAxis3Y.Text      = String.Format("{0:F4}", controllerState.rAxis3.y);
                                CRAxis4X.Text      = String.Format("{0:F4}", controllerState.rAxis4.x);
                                CRAxis4Y.Text      = String.Format("{0:F4}", controllerState.rAxis4.y);
                            }));
                            break;
                        }


                        break;

                    case ETrackedDeviceClass.GenericTracker:

                        system.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, unDevice, ref controllerState, (uint)Marshal.SizeOf(controllerState), ref TrackedDevicePose);
                        // get the position and rotation
                        position   = GetPosition(TrackedDevicePose.mDeviceToAbsoluteTracking);
                        quaternion = GetRotation(TrackedDevicePose.mDeviceToAbsoluteTracking);

                        // for printing some more info to the user about the state of the device/pose
                        eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult;

                        // print the tracking data
                        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                            TrackerIndex.Text       = String.Format("{0}", unDevice);
                            TrackerVectorX.Text     = String.Format("{0:F4}", position.v0);
                            TrackerVectorY.Text     = String.Format("{0:F4}", position.v1);
                            TrackerVectorZ.Text     = String.Format("{0:F4}", position.v2);
                            TrackerQuaternionX.Text = String.Format("{0:F4}", quaternion.x);
                            TrackerQuaternionY.Text = String.Format("{0:F4}", quaternion.y);
                            TrackerQuaternionZ.Text = String.Format("{0:F4}", quaternion.z);
                            TrackerQuaternionW.Text = String.Format("{0:F4}", quaternion.w);
                            TrackerState.Text       = GetDeviceState(eTrackingResult);
                        }));
                        break;
                    }
                    Thread.Sleep(10);
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates a GameObject that represents the left or right device controllers.
        /// These are the "VR hands".
        /// </summary>
        /// <param name="role">The controller device role (left or right).</param>
        /// <returns>The GameObject for the "VR hand".</returns>
        protected GameObject CreateManipulator(ETrackedControllerRole role)
        {
            // create new GameObject
            GameObject manipulator = new GameObject("KVR_Manipulator_" + role.ToString());

            DontDestroyOnLoad(manipulator);

            // define the render model
            GameObject glovePrefab = AssetLoader.Instance.GetGameObject("GlovePrefab");

            if (glovePrefab == null)
            {
                Utils.LogError("GameObject \"GlovePrefab\" was not found!");
                return(manipulator);
            }
            GameObject gloveObject = Instantiate(glovePrefab);

            gloveObject.transform.SetParent(manipulator.transform);
            Vector3 gloveObjectScale = Vector3.one * ManipulatorSize;

            if (role == ETrackedControllerRole.RightHand)
            {
                gloveObjectScale.y *= -1f;
            }
            gloveObject.transform.localPosition = GLOVE_POSITION;
            gloveObject.transform.localRotation = Quaternion.Euler(GLOVE_ROTATION);
            gloveObject.transform.localScale    = gloveObjectScale;
            Utils.SetLayer(gloveObject, 20);

            // define the colliders
            Transform colliderObject = gloveObject.transform.Find("HandDummy/Arm Bone L/Wrist Bone L/Finger Index Bone L1/Finger Index Bone L2/Finger Index Bone L3/Finger Index Bone L4");

            if (colliderObject == null)
            {
                Utils.LogWarning("Manipulator is missing fingertip collider child object");
                return(manipulator);
            }
            SphereCollider fingertipCollider = colliderObject.GetComponent <SphereCollider>();

            colliderObject = gloveObject.transform.Find("HandDummy/Arm Bone L/Wrist Bone L");
            if (colliderObject == null)
            {
                Utils.LogWarning("Manipulator is missing grip collider child object");
                return(manipulator);
            }
            CapsuleCollider gripCollider = colliderObject.GetComponent <CapsuleCollider>();


            // retrieve the animator
            Animator manipulatorAnimator = gloveObject.GetComponent <Animator>();

            // define the Manipulator component
            Manipulator manipulatorComponent = manipulator.AddComponent <Manipulator>();

            manipulatorComponent.role = role;
            manipulatorComponent.fingertipCollider   = fingertipCollider;
            manipulatorComponent.gripCollider        = gripCollider;
            manipulatorComponent.manipulatorAnimator = manipulatorAnimator;

#if DEBUG
            GameObject manipulatorGizmo = Utils.CreateGizmo();
            manipulatorGizmo.transform.SetParent(manipulator.transform);
            manipulatorGizmo.transform.localPosition = Vector3.zero;
            manipulatorGizmo.transform.localRotation = Quaternion.identity;
            manipulatorGizmo.transform.localScale    = Vector3.one * 0.5f;
#endif

            return(manipulator);
        }
Ejemplo n.º 28
0
	public override uint GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType)
	{
		CheckIfUsable();
		uint result = VRNativeEntrypoints.VR_IVRSystem_GetTrackedDeviceIndexForControllerRole(m_pVRSystem,unDeviceType);
		return result;
	}
Ejemplo n.º 29
0
        private bool StartupOVR()
        {
            EVRInitError error = EVRInitError.Driver_Failed;

            vr = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);

            if (error != EVRInitError.None)
            {
                Debug.WriteLine("OpenVR Init Error: " + error.ToString());
                return(false);
            }

            overlay = OpenVR.Overlay;

            EVROverlayError overlayError = overlay.CreateOverlay("Jstf_ovr_cards", "OpenVR Cards System Overlay", ref overlayHandle);

            if (overlayError != EVROverlayError.None)
            {
                OpenVR.Shutdown();
                Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString());
                return(false);
            }

            /*overlayError = overlay.SetOverlayFromFile(overlayHandle, AssetsPath + "overlay.png");
             * if (overlayError != EVROverlayError.None)
             * {
             *      CleanupOVR();
             *      Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString());
             *      return false;
             * }*/

            overlayError = overlay.SetOverlayInputMethod(overlayHandle, VROverlayInputMethod.Mouse);
            if (overlayError != EVROverlayError.None)
            {
                CleanupOVR();
                Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString());
                return(false);
            }

            overlayTexture = new Texture_t
            {
                eType       = ETextureType.OpenGL,
                eColorSpace = EColorSpace.Auto,
                handle      = (IntPtr)textureId
            };

            overlayError = overlay.SetOverlayTexture(overlayHandle, ref overlayTexture);
            if (overlayError != EVROverlayError.None)
            {
                CleanupOVR();
                Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString());
                return(false);
            }

            HmdId = OpenVR.k_unTrackedDeviceIndex_Hmd;

            for (uint i = HmdId + 1; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
            {
                if (vr.IsTrackedDeviceConnected(i))
                {
                    ETrackedDeviceClass cls = vr.GetTrackedDeviceClass(i);
                    if (cls == ETrackedDeviceClass.Controller)
                    {
                        ETrackedControllerRole rl = vr.GetControllerRoleForTrackedDeviceIndex(i);
                        if (rl == ETrackedControllerRole.LeftHand)
                        {
                            LeftControllerId = i;
                            Debug.WriteLine("Found Left Controller");
                        }
                        else if (rl == ETrackedControllerRole.RightHand)
                        {
                            RightControllerId = i;
                            Debug.WriteLine("Found Right Controller");
                        }
                    }
                }
            }

            mat = new HmdMatrix34_t
            {
                m0  = 1,
                m1  = 0,
                m2  = 0,
                m3  = 0f,
                m4  = 0,
                m5  = 1,
                m6  = 0,
                m7  = 0.1f,
                m8  = 0,
                m9  = 0,
                m10 = 1,
                m11 = 0f
            };



            overlayError = overlay.SetOverlayTransformTrackedDeviceRelative(overlayHandle, RightControllerId, ref mat);
            if (overlayError != EVROverlayError.None)
            {
                Debug.WriteLine("Cannot bind overlay to Tracked device.");
                Debug.WriteLine("Error: " + overlayError.ToString());
                CleanupOVR();
                return(false);
            }
            overlayError = overlay.SetOverlayWidthInMeters(overlayHandle, 0.2f);
            if (overlayError != EVROverlayError.None)
            {
                Debug.WriteLine("Cannot set overlay size.");
                Debug.WriteLine("Error: " + overlayError.ToString());
                CleanupOVR();
                return(false);
            }

            overlayError = overlay.SetOverlayAlpha(overlayHandle, 1);
            if (overlayError != EVROverlayError.None)
            {
                Debug.WriteLine("Cannot set overlay alpha.");
                Debug.WriteLine("Error: " + overlayError.ToString());
                CleanupOVR();
                return(false);
            }

            overlayError = overlay.SetOverlayColor(overlayHandle, 1, 1, 1);
            if (overlayError != EVROverlayError.None)
            {
                Debug.WriteLine("Cannot set overlay color.");
                Debug.WriteLine("Error: " + overlayError.ToString());
                CleanupOVR();
                return(false);
            }
#if DEBUG
            Debug.WriteLine("OpenVR Startup Complete");
#endif
            return(true);
        }
Ejemplo n.º 30
0
	public uint GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType)
	{
		uint result = FnTable.GetTrackedDeviceIndexForControllerRole(unDeviceType);
		return result;
	}
        private bool ProcessVREvent(VREvent_t event_T)
        {
            switch (event_T.eventType)
            {
            case (uint)EVREventType.VREvent_Quit:
                Shutdown();
                return(false);

            case (uint)EVREventType.VREvent_QuitAborted_UserPrompt:
                return(false);

            case (uint)EVREventType.VREvent_QuitAcknowledged:
                return(false);

            case (uint)EVREventType.VREvent_ButtonPress:

                int msgIdentifyer = 102;

                switch (event_T.data.controller.button)
                {
                case (uint)EVRButtonId.k_EButton_SteamVR_Touchpad:
                    Console.WriteLine("Touchpad");

                    ETrackedControllerRole result = vr_pointer.GetControllerRoleForTrackedDeviceIndex(event_T.trackedDeviceIndex);
                    if (result == ETrackedControllerRole.LeftHand)
                    {
                        int           handid = 1;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_SteamVR_Touchpad);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    else
                    {
                        int           handid = 2;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_SteamVR_Touchpad);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    return(false);

                case (uint)EVRButtonId.k_EButton_ApplicationMenu:
                    Console.WriteLine("ButttonAplication");

                    ETrackedControllerRole result2 = vr_pointer.GetControllerRoleForTrackedDeviceIndex(event_T.trackedDeviceIndex);
                    if (result2 == ETrackedControllerRole.LeftHand)
                    {
                        int           handid = 1;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_ApplicationMenu);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    else
                    {
                        int           handid = 2;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_ApplicationMenu);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    return(false);

                case (uint)EVRButtonId.k_EButton_System:
                    Console.WriteLine("ButtonSystem");

                    ETrackedControllerRole result3 = vr_pointer.GetControllerRoleForTrackedDeviceIndex(event_T.trackedDeviceIndex);
                    if (result3 == ETrackedControllerRole.LeftHand)
                    {
                        int           handid = 1;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_System);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    else
                    {
                        int           handid = 2;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_System);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    return(false);

                case (uint)EVRButtonId.k_EButton_SteamVR_Trigger:
                    Console.WriteLine("Trigger");

                    ETrackedControllerRole result4 = vr_pointer.GetControllerRoleForTrackedDeviceIndex(event_T.trackedDeviceIndex);
                    if (result4 == ETrackedControllerRole.LeftHand)
                    {
                        int           handid = 1;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_SteamVR_Trigger);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    else
                    {
                        int           handid = 2;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_SteamVR_Trigger);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    return(false);

                case (uint)EVRButtonId.k_EButton_Grip:
                    Console.WriteLine("Grip");
                    ETrackedControllerRole result5 = vr_pointer.GetControllerRoleForTrackedDeviceIndex(event_T.trackedDeviceIndex);
                    if (result5 == ETrackedControllerRole.LeftHand)
                    {
                        int           handid = 1;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_Grip);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    else
                    {
                        int           handid = 2;
                        MessageBuffer mb     = new MessageBuffer();
                        mb.add(msgIdentifyer);
                        mb.add((int)EVRButtonId.k_EButton_Grip);
                        mb.add(userId);
                        mb.add(handid);
                        Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                        lock (tcpSocketManager.send_msg(msg))
                        {
                            tcpSocketManager.send_msg(msg);
                        }
                    }
                    return(false);
                }
                return(false);

            default:
                return(false);
            }
        }
        private async void ParseTrackingFrame()
        {
            try
            {
                for (uint id = 0; id < OpenVR.k_unMaxTrackedDeviceCount; id++)
                {
                    if (vr_pointer != null)
                    {
                        TrackedDevicePose_t[] trackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];

                        if (!vr_pointer.IsTrackedDeviceConnected(id))
                        {
                            continue;
                        }

                        VRControllerState_t controllState = new VRControllerState_t();

                        ETrackedDeviceClass trackedDeviceClass = vr_pointer.GetTrackedDeviceClass(id);

                        switch (trackedDeviceClass)
                        {
                        case ETrackedDeviceClass.Controller:

                            vr_pointer.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, id, ref controllState, OpenVR.k_unMaxTrackedDeviceCount, ref trackedDevicePose[id]);

                            HmdVector3_t position = GetPosition(trackedDevicePose[id].mDeviceToAbsoluteTracking);    // devicePose->mDeviceToAbsoluteTracking);
                            HmdVector3_t rotation = GetRotationEuler(trackedDevicePose[id].mDeviceToAbsoluteTracking);


                            int positionControllerX = (int)position.v0;
                            int positionControllerY = (int)position.v1;
                            int positionControllerZ = (int)position.v2 * (-1);

                            int rotationControllerX = (int)rotation.v0 + 180;
                            int rotationControllerY = (int)rotation.v1;
                            int rotationControllerZ = (int)rotation.v2;

                            if (ControlViewModel.teleporOffset[0] != -1)
                            {
                                ControlViewModel.transOffSetControllerX = ControlViewModel.teleporOffset[0];
                                ControlViewModel.transOffSetControllerY = ControlViewModel.teleporOffset[1];
                                ControlViewModel.transOffSetControllerZ = ControlViewModel.teleporOffset[2];
                                ControlViewModel.rotOffSetControllerZ   = ControlViewModel.teleporOffset[3];
                            }

                            ETrackedControllerRole result = vr_pointer.GetControllerRoleForTrackedDeviceIndex(id);

                            if (result != ETrackedControllerRole.LeftHand && lastController != ETrackedControllerRole.LeftHand)
                            {
                                RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.LeftController);
                            }

                            if (result != ETrackedControllerRole.RightHand && lastController != ETrackedControllerRole.RightHand)
                            {
                                RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.RightController);
                            }

                            switch (result)
                            {
                            case ETrackedControllerRole.Invalid:
                                break;

                            case ETrackedControllerRole.LeftHand:

                                if (communicationProtocolUdp == false)
                                {
                                    MessageBuffer mb2 = new MessageBuffer();
                                    someThingTracked = true;
                                    int type = 101;
                                    mb2.add(type);
                                    mb2.add(userId);
                                    int handid = 1;
                                    mb2.add(handid);
                                    mb2.add(positionControllerX + ControlViewModel.transOffSetControllerX);
                                    mb2.add(positionControllerY + ControlViewModel.transOffSetControllerY);
                                    mb2.add(positionControllerZ + ControlViewModel.transOffSetControllerZ);
                                    mb2.add(rotationControllerX);
                                    mb2.add(rotationControllerY);
                                    mb2.add(rotationControllerZ);
                                    mb2.add(ControlViewModel.rotOffSetControllerZ);
                                    RaiseControllerEvent(new TrackingChangedEventArgs(true), Tracker.LeftController);
                                    Message msg = new Message(mb2, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                                    lock (tcpSocketManager.send_msg(msg))
                                    {
                                        tcpSocketManager.send_msg(msg);
                                    }
                                    Thread.Sleep(20);
                                    break;
                                }
                                break;

                            case ETrackedControllerRole.RightHand:

                                if (communicationProtocolUdp == false)
                                {
                                    MessageBuffer mb2 = new MessageBuffer();
                                    someThingTracked = true;
                                    int type = 101;
                                    mb2.add(type);
                                    mb2.add(userId);
                                    int handid = 2;
                                    mb2.add(handid);
                                    mb2.add(positionControllerX + ControlViewModel.transOffSetControllerX);
                                    mb2.add(positionControllerY + ControlViewModel.transOffSetControllerY);
                                    mb2.add(positionControllerZ + ControlViewModel.transOffSetControllerZ);
                                    mb2.add(rotationControllerX);
                                    mb2.add(rotationControllerY);
                                    mb2.add(rotationControllerZ);
                                    mb2.add(ControlViewModel.rotOffSetControllerZ);
                                    Message msg = new Message(mb2, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE);
                                    RaiseControllerEvent(new TrackingChangedEventArgs(true), Tracker.RightController);
                                    lock (tcpSocketManager.send_msg(msg))
                                    {
                                        tcpSocketManager.send_msg(msg);
                                    }
                                    Thread.Sleep(20);
                                    break;
                                }
                                break;
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                log.Warn("ParseTrackingFrame in Controller Tracking wurde beendet!" + e);
                RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.LeftController);
                RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.RightController);
            }
        }
Ejemplo n.º 33
0
        public bool GetDevices(Dictionary <string, TrackedDevice> devices)
        {
            devices.Clear();
            bool changeDetected = false;

            _openVRFacade.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, _poses);

            for (uint i = 0; i < _poses.Length; i++)
            {
                OpenVRDevice        device = _devices[i];
                TrackedDevicePose_t pose   = _poses[i];

                DeviceUse use = DeviceUse.Unknown;

                string id          = device.id;
                bool   isConnected = device.isConnected;
                string modelName   = device.modelName;

                if (pose.bDeviceIsConnected != isConnected)
                {
                    isConnected = pose.bDeviceIsConnected;

                    if (pose.bDeviceIsConnected)
                    {
                        string serialNumber = _openVRFacade.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_SerialNumber_String);

                        modelName = _openVRFacade.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_ModelNumber_String);
                        id        = string.Concat(modelName ?? "Unknown", " ", (uint)serialNumber?.GetHashCode(), "@", i);

                        _logger.Info($"Device '{id}' connected");
                    }
                    else
                    {
                        _logger.Info($"Device '{id}' disconnected");

                        id        = null;
                        modelName = null;
                    }

                    changeDetected = true;
                }

                if (!isConnected)
                {
                    _devices[i] = default;
                    continue;
                }

                ETrackedDeviceClass    deviceClass    = _openVRFacade.GetTrackedDeviceClass(i);
                ETrackedControllerRole controllerRole = _openVRFacade.GetControllerRoleForTrackedDeviceIndex(i);
                string role = _openVRFacade.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_ControllerType_String);

                if (deviceClass != device.deviceClass)
                {
                    _logger.Trace($"Device '{id}' class changed from '{device.deviceClass}' to '{deviceClass}'");

                    changeDetected = true;
                }

                if (controllerRole != device.controllerRole)
                {
                    _logger.Trace($"Device '{id}' controller role changed from '{device.controllerRole}' to '{controllerRole}'");

                    changeDetected = true;
                }

                if (role != device.role)
                {
                    if (role == null)
                    {
                        _logger.Trace($"Device '{id}' role unset from '{device.role}'");
                    }
                    else if (device.role == null)
                    {
                        _logger.Trace($"Device '{id}' role set to '{role}'");
                    }
                    else
                    {
                        _logger.Trace($"Device '{id}' role changed from '{device.role}' to '{role}'");
                    }

                    changeDetected = true;
                }

                switch (deviceClass)
                {
                case ETrackedDeviceClass.HMD:
                    use = DeviceUse.Head;
                    break;

                case ETrackedDeviceClass.Controller:
                    switch (controllerRole)
                    {
                    case ETrackedControllerRole.LeftHand:
                        use = DeviceUse.LeftHand;
                        break;

                    case ETrackedControllerRole.RightHand:
                        use = DeviceUse.RightHand;
                        break;
                    }

                    break;

                case ETrackedDeviceClass.GenericTracker:
                    switch (role)
                    {
                    case "vive_tracker_waist":
                        use = DeviceUse.Waist;
                        break;

                    case "vive_tracker_left_foot":
                        use = DeviceUse.LeftFoot;
                        break;

                    case "vive_tracker_right_foot":
                        use = DeviceUse.RightFoot;
                        break;
                    }

                    break;
                }

                bool isTracking = pose.bPoseIsValid && kValidTrackingResults.Contains(pose.eTrackingResult);

                if (device.isTracking != isTracking)
                {
                    if (isTracking)
                    {
                        _logger.Info($"Acquired tracking of device '{id}'");
                    }
                    else
                    {
                        _logger.Info($"Lost tracking of device '{id}'");
                    }

                    changeDetected = true;
                }

                Vector3    position = Vector3.zero;
                Quaternion rotation = Quaternion.identity;

                if (isTracking)
                {
                    _openVRFacade.GetPositionAndRotation(pose.mDeviceToAbsoluteTracking, out position, out rotation);

                    // Driver4VR rotation correction
                    if (role.StartsWith("d4vr_tracker_") && (use == DeviceUse.LeftFoot || use == DeviceUse.RightFoot))
                    {
                        rotation *= Quaternion.Euler(-90, 180, 0);
                    }

                    // KinectToVR rotation correction
                    if (role == "kinect_device")
                    {
                        if (use == DeviceUse.Waist)
                        {
                            rotation *= Quaternion.Euler(-90, 180, 0);
                        }

                        if (use == DeviceUse.LeftFoot || use == DeviceUse.RightFoot)
                        {
                            rotation *= Quaternion.Euler(0, 180, 0);
                        }
                    }
                }

                _devices[i] = new OpenVRDevice(id, isConnected, isTracking, controllerRole, deviceClass, modelName, role);
                devices.Add(id, new TrackedDevice(id, use, isTracking, position, rotation));
            }

            return(changeDetected);
        }
Ejemplo n.º 34
0
        }                                                                                                                                                                                                                                   // 0x00000001811DFF00-0x00000001811DFF30

        public uint GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType) => default;                                                                                                                                 // 0x00000001811E0AC0-0x00000001811E0AF0