private void ApplyPose(SteamVR_Utils.RigidTransform relPose, SteamVR_Utils.RigidTransform pose)
 {
     var newPos = pose.pos - relPose.pos;
     transform.position = AttachTo.position + newPos;
     transform.rotation = Quaternion.Euler(pose.rot.eulerAngles);
     transform.RotateAround(RotationAnchor.transform.position, RotationAxis, RotateBy);
 }
Exemplo n.º 2
0
    // Builds a tessellated grid of quads across the provided bounds with three sets of UVs used to account for
    // lens distortion and chromatic aberration.
    public static Mesh CreateDistortMesh(SteamVR.IHmd hmd, SteamVR.Hmd_Eye eye, int resU, int resV, Rect bounds)
    {
        int numVerts = resU * resV;
        var vertices = new Vector3[numVerts];
        var redUVs   = new Vector3[numVerts];
        var greenUVs = new Vector2[numVerts];
        var blueUVs  = new Vector2[numVerts];

        int iTri      = 0;
        int resUm1    = resU - 1;
        int resVm1    = resV - 1;
        var triangles = new int[2 * 3 * resUm1 * resVm1];

        for (int iV = 0; iV < resV; iV++)
        {
            float v = (float)iV / resVm1;
            float y = SteamVR_Utils.Lerp(bounds.yMax, bounds.yMin, v);             // ComputeDistortion expects 0,0 in upper left
            for (int iU = 0; iU < resU; iU++)
            {
                float u      = (float)iU / resUm1;
                float x      = SteamVR_Utils.Lerp(bounds.xMin, bounds.xMax, u);
                var   coords = hmd.ComputeDistortion(eye, u, v);

                int idx = iV * resU + iU;
                vertices[idx] = new Vector3(x, y, 0.1f);

                redUVs[idx]   = new Vector3(coords.rfRed[0], 1.0f - coords.rfRed[1], 0);
                greenUVs[idx] = new Vector2(coords.rfGreen[0], 1.0f - coords.rfGreen[1]);
                blueUVs[idx]  = new Vector2(coords.rfBlue[0], 1.0f - coords.rfBlue[1]);

                if (iV > 0 && iU > 0)
                {
                    int a = (iV - 1) * resU + (iU - 1);
                    int b = (iV - 1) * resU + iU;
                    int c = iV * resU + (iU - 1);
                    int d = iV * resU + iU;

                    triangles[iTri++] = a;
                    triangles[iTri++] = b;
                    triangles[iTri++] = d;

                    triangles[iTri++] = a;
                    triangles[iTri++] = d;
                    triangles[iTri++] = c;
                }
            }
        }

        var mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.normals   = redUVs;       // stuff data in normals since only two uv sets exposed
        mesh.uv        = greenUVs;
        mesh.uv2       = blueUVs;
        mesh.triangles = triangles;
        return(mesh);
    }
Exemplo n.º 3
0
    void Update()
    {
        if (cameras.Length == 0)
        {
            enabled = false;
            return;
        }

        // If our FixedUpdate rate doesn't match our render framerate, then catch the handoff here.
        SteamVR_Utils.QueueEventOnRenderThread(Unity.k_nRenderEventID_PostPresentHandoff);

        // Force controller update in case no one else called this frame to ensure prevState gets updated.
        SteamVR_Controller.Update();

        // Dispatch any OpenVR events.
        var vr      = SteamVR.instance;
        var vrEvent = new VREvent_t();

        for (int i = 0; i < 64; i++)
        {
            if (!vr.hmd.PollNextEvent(ref vrEvent))
            {
                break;
            }

            switch ((EVREventType)vrEvent.eventType)
            {
            case EVREventType.VREvent_InputFocusCaptured:                     // another app has taken focus (likely dashboard)
                SteamVR_Utils.Event.Send("input_focus", false);
                break;

            case EVREventType.VREvent_InputFocusReleased:                     // that app has released input focus
                SteamVR_Utils.Event.Send("input_focus", true);
                break;

            default:
                var name = System.Enum.GetName(typeof(EVREventType), vrEvent.eventType);
                if (name != null)
                {
                    SteamVR_Utils.Event.Send(name.Substring(8) /*strip VREvent_*/, vrEvent);
                }
                break;
            }
        }

        // Ensure various settings to minimize latency.
        Application.targetFrameRate     = -1;
        Application.runInBackground     = true; // don't require companion window focus
        QualitySettings.maxQueuedFrames = -1;
        QualitySettings.vSyncCount      = 0;    // this applies to the companion window

        if (lockPhysicsUpdateRateToRenderFrequency)
        {
            Time.fixedDeltaTime = 1.0f / vr.hmd_DisplayFrequency;
        }
    }
Exemplo n.º 4
0
    protected override void UpdateHovering()
    {
        if ((noSteamVRFallbackCamera == null) && (isActive == false))
        {
            return;
        }

        if (hoverLocked)
        {
            return;
        }

        if (applicationLostFocusObject.activeSelf)
        {
            return;
        }

        float        closestDistance     = float.MaxValue;
        Interactable closestInteractable = null;

        if (useHoverSphere)
        {
            float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
            CheckHoveringForTransform(hoverSphereTransform.position, scaledHoverRadius, ref closestDistance, ref closestInteractable, Color.green);
        }

        if (useControllerHoverComponent && mainRenderModel != null && mainRenderModel.IsControllerVisibile())
        {
            float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));

            // substitute drumstick object in place of SteamVR's HoverPoint
            if (drumstick != null)
            {
                // get position and radius of drumstick
                Vector3 drumstickPosition = drumstick.transform.position;
                float   drumstickRadius   = drumstick.transform.lossyScale.x / 2f;

                // use SteamVR's method to detect if interactable component overlaps with drumstick size and position
                CheckHoveringForTransform(drumstickPosition, drumstickRadius, ref closestDistance, ref closestInteractable, Color.blue);
            }
            else
            {
                Debug.LogError("Drumsticks not detected. Defaulting to SteamVR hover component.");
                CheckHoveringForTransform(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.blue);
            }
        }

        if (useFingerJointHover && mainRenderModel != null && mainRenderModel.IsHandVisibile())
        {
            float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
            CheckHoveringForTransform(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.yellow);
        }

        // Hover on this one
        hoveringInteractable = closestInteractable;
    }
Exemplo n.º 5
0
    public void Set(SteamVR vr, Valve.VR.EVREye eye)
    {
        int i = (int)eye;

        if (hiddenAreaMeshes[i] == null)
        {
            hiddenAreaMeshes[i] = SteamVR_Utils.CreateHiddenAreaMesh(vr.hmd.GetHiddenAreaMesh(eye, Valve.VR.EHiddenAreaMeshType.k_eHiddenAreaMesh_Standard), vr.textureBounds[i]);
        }
        meshFilter.mesh = hiddenAreaMeshes[i];
    }
        private void ApplyPose(SteamVR_Utils.RigidTransform pose)
        {
            if (TrackPosition)
            {
                transform.position = pose.pos;
            }

            if (TrackRotation)
            {
                transform.rotation = CalibrationParams.RotationOffset * pose.rot;
            }
        }
Exemplo n.º 7
0
        //-------------------------------------------------
        private void ComputeTextEndTransforms()
        {
            //This is done as a separate step after all the ButtonHintInfos have been initialized
            //to make the text hints fan out appropriately based on the button's position on the controller.

            centerPosition /= actionHintInfos.Count;
            float maxDistanceFromCenter = 0.0f;

            foreach (var hintInfo in actionHintInfos)
            {
                hintInfo.Value.distanceFromCenter =
                    Vector3.Distance(hintInfo.Value.textStartAnchor.position, centerPosition);

                if (hintInfo.Value.distanceFromCenter > maxDistanceFromCenter)
                {
                    maxDistanceFromCenter = hintInfo.Value.distanceFromCenter;
                }
            }

            foreach (var hintInfo in actionHintInfos)
            {
                Vector3 centerToButton = hintInfo.Value.textStartAnchor.position - centerPosition;
                centerToButton.Normalize();

                centerToButton = Vector3.Project(centerToButton, renderModel.transform.forward);

                //Spread out the text end positions based on the distance from the center
                float t     = hintInfo.Value.distanceFromCenter / maxDistanceFromCenter;
                float scale = hintInfo.Value.distanceFromCenter * Mathf.Pow(2, 10 * (t - 1.0f)) * 20.0f;

                //Flip the direction of the end pos based on which hand this is
                float endPosOffset = 0.1f;

                Vector3 hintEndPos = hintInfo.Value.textStartAnchor.position +
                                     (hintInfo.Value.textEndOffsetDir * endPosOffset) + (centerToButton * scale * 0.1f);

                if (SteamVR_Utils.IsValid(hintEndPos))
                {
                    hintInfo.Value.textEndAnchor.position = hintEndPos;

                    hintInfo.Value.canvasOffset.position = hintEndPos;
                }
                else
                {
                    Debug.LogWarning(
                        "<b>[SteamVR Interaction]</b> Invalid end position for: " + hintInfo.Value.textStartAnchor.name,
                        hintInfo.Value.textStartAnchor.gameObject);
                }

                hintInfo.Value.canvasOffset.localRotation = Quaternion.identity;
            }
        }
Exemplo n.º 8
0
    public static Quaternion GetRotation(this Matrix4x4 matrix)
    {
        Quaternion quaternion = default(Quaternion);

        quaternion.w = Mathf.Sqrt(Mathf.Max(0f, 1f + matrix.m00 + matrix.m11 + matrix.m22)) / 2f;
        quaternion.x = Mathf.Sqrt(Mathf.Max(0f, 1f + matrix.m00 - matrix.m11 - matrix.m22)) / 2f;
        quaternion.y = Mathf.Sqrt(Mathf.Max(0f, 1f - matrix.m00 + matrix.m11 - matrix.m22)) / 2f;
        quaternion.z = Mathf.Sqrt(Mathf.Max(0f, 1f - matrix.m00 - matrix.m11 + matrix.m22)) / 2f;
        quaternion.x = SteamVR_Utils._copysign(quaternion.x, matrix.m21 - matrix.m12);
        quaternion.y = SteamVR_Utils._copysign(quaternion.y, matrix.m02 - matrix.m20);
        quaternion.z = SteamVR_Utils._copysign(quaternion.z, matrix.m10 - matrix.m01);
        return(quaternion);
    }
Exemplo n.º 9
0
    private IEnumerator RenderLoop()
    {
        while (true)
        {
            yield return(new WaitForEndOfFrame());

            if (pauseRendering)
            {
                continue;
            }

            var vr = SteamVR.instance;

            if (!vr.compositor.CanRenderScene())
            {
                continue;
            }

            vr.compositor.SetTrackingSpace(trackingSpace);
            SteamVR_Utils.QueueEventOnRenderThread(Unity.k_nRenderEventID_WaitGetPoses);

            // Hack to flush render event that was queued in Update (this ensures WaitGetPoses has returned before we grab the new values).
            Unity.EventWriteString("[UnityMain] GetNativeTexturePtr - Begin");
            SteamVR_Camera.GetSceneTexture(cameras[0].GetComponent <Camera>().hdr).GetNativeTexturePtr();
            Unity.EventWriteString("[UnityMain] GetNativeTexturePtr - End");

            vr.compositor.GetLastPoses(poses, gamePoses);
            SteamVR_Utils.Event.Send("new_poses", poses);

            var overlay = SteamVR_Overlay.instance;
            if (overlay != null)
            {
                overlay.UpdateOverlay(vr);
            }

            RenderEye(vr, EVREye.Eye_Left);
            RenderEye(vr, EVREye.Eye_Right);

            // Move cameras back to head position so they can be tracked reliably
            foreach (var c in cameras)
            {
                c.transform.localPosition = Vector3.zero;
                c.transform.localRotation = Quaternion.identity;
            }

            if (cameraMask != null)
            {
                cameraMask.Clear();
            }
        }
    }
Exemplo n.º 10
0
 public void Set(SteamVR vr, Valve.VR.EVREye eye)
 {
     try
     {
         int i = (int)eye;
         if (hiddenAreaMeshes[i] == null)
         {
             hiddenAreaMeshes[i] = SteamVR_Utils.CreateHiddenAreaMesh(vr.hmd.GetHiddenAreaMesh(eye), vr.textureBounds[i]);
         }
         meshFilter.mesh = hiddenAreaMeshes[i];
     } catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Exemplo n.º 11
0
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        try
        {
            if (SteamVR_Render.Top() == this)
            {
                int eventID;
                if (SteamVR_Render.eye == EVREye.Eye_Left)
                {
                    // Get gpu started on work early to avoid bubbles at the top of the frame.
                    SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_Flush);

                    eventID = SteamVR.Unity.k_nRenderEventID_SubmitL;
                }
                else
                {
                    eventID = SteamVR.Unity.k_nRenderEventID_SubmitR;
                }
                // Queue up a call on the render thread to Submit our render target to the compositor.
                SteamVR_Utils.QueueEventOnRenderThread(eventID);
                //Texture_t t = new Texture_t() { eColorSpace = EColorSpace.Auto, eType = EGraphicsAPIConvention.API_DirectX, handle = _sceneTexture.GetNativeTexturePtr() };
                //VRTextureBounds_t b = SteamVR_Render.eye == EVREye.Eye_Left ? SteamVR.instance.textureBounds[0] : SteamVR.instance.textureBounds[1];
                //var res = OpenVR.Compositor.Submit(SteamVR_Render.eye, ref t, ref b, EVRSubmitFlags.Submit_Default);
                //Console.WriteLine(res);
            }
            Graphics.SetRenderTarget(dest);

            SteamVR_Camera.blitMaterial.mainTexture = src;

            GL.PushMatrix();
            GL.LoadOrtho();
            SteamVR_Camera.blitMaterial.SetPass(0);
            GL.Begin(GL.QUADS);
            GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1, 1, 0);
            GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(1, 1, 0);
            GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(1, -1, 0);
            GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1, -1, 0);
            GL.End();
            GL.PopMatrix();

            Graphics.SetRenderTarget(null);
        } catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
Exemplo n.º 12
0
        protected virtual void UpdateHovering()
        {
            if (isActive == false)
            {
                return;
            }

            if (hoverLocked)
            {
                return;
            }

            if (applicationLostFocusObject.activeSelf)
            {
                Debug.Log("lost focus" + name);
                return;
            }

            float        closestDistance     = float.MaxValue;
            Interactable closestInteractable = null;

            if (useHoverSphere)
            {
                float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
                CheckHoveringForTransform(hoverSphereTransform.position, scaledHoverRadius, ref closestDistance, ref closestInteractable, Color.green);
            }

            if (mainRenderModel != null)
            {
                if (mainRenderModel.IsControllerVisibile())
                {
                    float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
                    CheckHoveringForTransform(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.blue);
                }

                if (useFingerJointHover && mainRenderModel.IsHandVisibile())
                {
                    float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
                    CheckHoveringForTransform(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.yellow);
                }
            }


            // Hover on this one
            hoveringInteractable = closestInteractable;
        }
Exemplo n.º 13
0
        protected void UpdateAttachedVelocity(AttachedObject attachedObjectInfo)
        {
            Transform attach_trans = transform;

            float scale = SteamVR_Utils.GetLossyScale(attach_trans);

            float maxVelocityChange        = MaxVelocityChange * scale;
            float velocityMagic            = VelocityMagic;
            float angularVelocityMagic     = AngularVelocityMagic;
            float maxAngularVelocityChange = MaxAngularVelocityChange * scale;

            Vector3 targetItemPosition = attach_trans.TransformPoint(hand_attachment_offset_helper.localPosition);

            Vector3 positionDelta  = (targetItemPosition - attachedObjectInfo.attachedRigidbody.position);
            Vector3 velocityTarget = (positionDelta * velocityMagic * Time.deltaTime);

            if (float.IsNaN(velocityTarget.x) == false && float.IsInfinity(velocityTarget.x) == false)
            {
                attachedObjectInfo.attachedRigidbody.velocity = Vector3.MoveTowards(attachedObjectInfo.attachedRigidbody.velocity, velocityTarget, maxVelocityChange);
            }


            Quaternion targetItemRotation = attach_trans.rotation * hand_attachment_offset_helper.localRotation;

            Quaternion rotationDelta = targetItemRotation * Quaternion.Inverse(attachedObjectInfo.attachedObject.transform.rotation);


            float   angle;
            Vector3 axis;

            rotationDelta.ToAngleAxis(out angle, out axis);

            if (angle > 180)
            {
                angle -= 360;
            }

            if (angle != 0 && float.IsNaN(axis.x) == false && float.IsInfinity(axis.x) == false)
            {
                Vector3 angularTarget = angle * axis * angularVelocityMagic * Time.deltaTime;

                attachedObjectInfo.attachedRigidbody.angularVelocity = Vector3.MoveTowards(attachedObjectInfo.attachedRigidbody.angularVelocity, angularTarget, maxAngularVelocityChange);
            }
        }
Exemplo n.º 14
0
    // Sends the figurine down to the destination position over time.  Once down, actually spawns the entity
    // and destroys the figurine.
    // Assumes the figurine is no longer grabbed.
    private IEnumerator dropFigurineToSpawn(Vector3 startPos, Vector3 destination, Hand hand)
    {
        _elapsedSpawnSeconds = 0f;
        float totalMeters   = Vector3.Distance(startPos, destination);
        float _totalSeconds = totalMeters / _spawnMetersPerSecond;

        while (_elapsedSpawnSeconds < _totalSeconds)
        {
            hand.controller.TriggerHapticPulse(HapticSpawnDrop);

            var currentPos = SteamVR_Utils.Lerp(startPos, destination, _elapsedSpawnSeconds / _totalSeconds);
            transform.position = currentPos;

            _elapsedSpawnSeconds += Time.deltaTime;
            yield return(new WaitForEndOfFrame());
        }

        FigurinePlacedEvent.Invoke(destination);
    }
Exemplo n.º 15
0
        //-------------------------------------------------
        protected virtual void OnHandHoverBegin(Hand hand)
        {
            bool showHint = false;

            // "Catch" the throwable by holding down the interaction button instead of pressing it.
            // Only do this if the throwable is moving faster than the prescribed threshold speed,
            // and if it isn't attached to another hand
            if (!attached && catchingSpeedThreshold != -1)
            {
                float catchingThreshold = catchingSpeedThreshold * SteamVR_Utils.GetLossyScale(Player.instance.trackingOriginTransform);

                GrabTypes bestGrabType = hand.GetBestGrabbingType();

                if (bestGrabType != GrabTypes.None)
                {
                    if (rigidbody.velocity.magnitude >= catchingThreshold)
                    {
                        hand.AttachObject(gameObject, bestGrabType, attachmentFlags);
                        showHint = false;
                    }
                }
            }
            // automatically grab any object if you were holding down the trigger before hovering the object.
            else if (!attached && autoGrabObject)
            {
                GrabTypes bestGrabType = hand.GetBestGrabbingType();
                if (bestGrabType != GrabTypes.None)
                {
                    hand.AttachObject(gameObject, bestGrabType, attachmentFlags);
                    showHint = false;
                }
            }

            if (showHint)
            {
                hand.ShowGrabHint();
            }
        }
Exemplo n.º 16
0
        protected virtual void OnDrawGizmos()
        {
            if (useHoverSphere)
            {
                Gizmos.color = Color.green;
                float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
                Gizmos.DrawWireSphere(hoverSphereTransform.position, scaledHoverRadius / 2);
            }

            if (mainRenderModel != null && mainRenderModel.IsControllerVisibile())
            {
                Gizmos.color = Color.blue;
                float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
                Gizmos.DrawWireSphere(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2 + .01f);
            }

            if (useFingerJointHover && mainRenderModel != null && mainRenderModel.IsHandVisibile())
            {
                Gizmos.color = Color.yellow;
                float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
                Gizmos.DrawWireSphere(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2 + .02f);
            }
        }
        private void OnRequestScreenshot(VREvent_t vrEvent)
        {
            uint handle            = vrEvent.data.screenshot.handle;
            EVRScreenshotType type = (EVRScreenshotType)vrEvent.data.screenshot.type;

            if (type == EVRScreenshotType.StereoPanorama)
            {
                string previewFilename = GetScreenshotFilename(handle, EVRScreenshotPropertyFilenames.Preview);
                string VRFilename      = GetScreenshotFilename(handle, EVRScreenshotPropertyFilenames.VR);
                if (previewFilename != null && VRFilename != null)
                {
                    GameObject gameObject = new GameObject("screenshotPosition");



                    gameObject.transform.position   = Top().transform.position;
                    gameObject.transform.rotation   = Top().transform.rotation;
                    gameObject.transform.localScale = Top().transform.lossyScale;
                    SteamVR_Utils.TakeStereoScreenshot(handle, gameObject, 32, 0.064f, ref previewFilename, ref VRFilename);
                    OpenVR.Screenshots.SubmitScreenshot(handle, type, previewFilename, VRFilename);
                }
            }
        }
Exemplo n.º 18
0
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (SteamVR_Render.Top() == this)
        {
            int eventID;
            if (SteamVR_Render.eye == EVREye.Eye_Left)
            {
                // Get gpu started on work early to avoid bubbles at the top of the frame.
                SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_Flush);

                eventID = SteamVR.Unity.k_nRenderEventID_SubmitL;
            }
            else
            {
                eventID = SteamVR.Unity.k_nRenderEventID_SubmitR;
            }

            // Queue up a call on the render thread to Submit our render target to the compositor.
            SteamVR_Utils.QueueEventOnRenderThread(eventID);
        }

        Graphics.SetRenderTarget(dest);
        SteamVR_Camera.blitMaterial.mainTexture = src;

        GL.PushMatrix();
        GL.LoadOrtho();
        SteamVR_Camera.blitMaterial.SetPass(0);
        GL.Begin(GL.QUADS);
        GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1, 1, 0);
        GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(1, 1, 0);
        GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(1, -1, 0);
        GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1, -1, 0);
        GL.End();
        GL.PopMatrix();

        Graphics.SetRenderTarget(null);
    }
Exemplo n.º 19
0
 public static string GetBadMD5Hash(string usedString)
 {
     return(SteamVR_Utils.GetBadMD5Hash(Encoding.UTF8.GetBytes(usedString + "foobar")));
 }
 private void StashPose(SteamVR_Utils.RigidTransform pose)
 {
     _trackedPoses.Enqueue(new DelayedPose(pose));
 }
Exemplo n.º 21
0
 public static Vector2 Abs(Vector2 A)
 {
     return(new Vector2(SteamVR_Utils.Abs(A.x), SteamVR_Utils.Abs(A.y)));
 }
Exemplo n.º 22
0
    public void Init(SteamVR_Camera tracker, SteamVR.Hmd_Eye eye, float depth)
    {
        this.tracker = tracker;
        this.eye     = eye;

        var hmd = SteamVR.IHmd.instance;
        var i   = (int)eye;

        uint x = 0, y = 0, w = 0, h = 0;

        hmd.GetEyeOutputViewport(eye, ref x, ref y, ref w, ref h);

        overlaySettings.kernel = new Vector3[] {         // AA sub-pixel sampling (2x2 RGSS)
            new Vector3(0.125f / w, -0.375f / h, 0),
            new Vector3(0.375f / w, 0.125f / h, 0),
            new Vector3(-0.125f / w, 0.375f / h, 0),
            new Vector3(-0.375f / w, -0.125f / h, 0)
        };

        float left = 0.0f, right = 0.0f, top = 0.0f, bottom = 0.0f;

        hmd.GetProjectionRaw(eye, ref left, ref right, ref top, ref bottom);

        var   camera = GetComponent <Camera>();
        float zFar   = camera.farClipPlane;
        float zNear  = camera.nearClipPlane;

        var m = Matrix4x4.identity;

        float idx = 1.0f / (right - left);
        float idy = 1.0f / (bottom - top);
        float idz = 1.0f / (zFar - zNear);
        float sx  = right + left;
        float sy  = bottom + top;

        m[0, 0] = 2 * idx; m[0, 1] = 0;     m[0, 2] = sx * idx;    m[0, 3] = 0;
        m[1, 0] = 0;     m[1, 1] = 2 * idy; m[1, 2] = sy * idy;    m[1, 3] = 0;
        m[2, 0] = 0;     m[2, 1] = 0;     m[2, 2] = -zFar * idz; m[2, 3] = -zFar * zNear * idz;
        m[3, 0] = 0;     m[3, 1] = 0;     m[3, 2] = -1.0f;     m[3, 3] = 0;

        camera.projectionMatrix = m;
        camera.depth            = depth;                                // enforce rendering order
        camera.eventMask        = 0;                                    // disable mouse events
        camera.orthographic     = false;                                // force perspective
        camera.aspect           = (float)w / h;

        // Use fov of projection matrix (which is grown to account for non-linear undistort)
        camera.fieldOfView = (Mathf.Atan(bottom) - Mathf.Atan(top)) * Mathf.Rad2Deg;

        // Copy and clear clearFlags to avoid duplicate work.
        if ((int)clearFlags == 0)
        {
            clearFlags        = camera.clearFlags;
            camera.clearFlags = CameraClearFlags.Nothing;
        }

        camera.targetTexture = SteamVR_Camera.sceneTexture;

        overlaySettings.invProj = m.inverse;

        transform.parent     = tracker.offset;
        transform.localScale = Vector3.one;

        var t = new SteamVR_Utils.RigidTransform(hmd.GetHeadFromEyePose(eye));

        transform.localPosition = t.pos;
        transform.localRotation = t.rot;

        if (distortMesh[i] == null)
        {
            var viewportWidth  = SteamVR_Camera.viewportTexture.width;
            var viewportHeight = SteamVR_Camera.viewportTexture.height;

            var eyeViewport = new Rect(
                2.0f * x / viewportWidth - 1.0f,
                2.0f * y / viewportHeight - 1.0f,
                2.0f * w / viewportWidth,
                2.0f * h / viewportHeight);

            distortMesh[i] = SteamVR_Utils.CreateDistortMesh(hmd, eye, 32, 32, eyeViewport);
        }
    }
        private bool CalculateIntersection(DPOverlayBase dpBase, out IntersectionResults results)
        {
            results = new IntersectionResults();

            return(SteamVR_Utils.ComputeIntersection(dpBase.overlay.handle, pointer.position, pointer.forward, SteamVRManager.trackingSpace, ref results));
        }
Exemplo n.º 24
0
 public void Interpolate(RigidTransform to, float t)
 {
     pos = SteamVR_Utils.Lerp(pos, to.pos, t);
     rot = SteamVR_Utils.Slerp(rot, to.rot, t);
 }
Exemplo n.º 25
0
        public static Mesh CreateHiddenAreaMesh(HiddenAreaMesh_t src, VRTextureBounds_t bounds)
        {
            if (src.unTriangleCount == 0u)
            {
                return(null);
            }
            float[] array = new float[src.unTriangleCount * 3u * 2u];
            Marshal.Copy(src.pVertexData, array, 0, array.Length);
            Vector3[] array2 = new Vector3[src.unTriangleCount * 3u + 12u];
            int[]     array3 = new int[src.unTriangleCount * 3u + 24u];
            float     num    = 2f * bounds.uMin - 1f;
            float     num2   = 2f * bounds.uMax - 1f;
            float     num3   = 2f * bounds.vMin - 1f;
            float     num4   = 2f * bounds.vMax - 1f;
            int       num5   = 0;
            int       num6   = 0;

            while ((long)num5 < (long)((ulong)(src.unTriangleCount * 3u)))
            {
                float x = SteamVR_Utils.Lerp(num, num2, array[num6++]);
                float y = SteamVR_Utils.Lerp(num3, num4, array[num6++]);
                array2[num5] = new Vector3(x, y, 0f);
                array3[num5] = num5;
                num5++;
            }
            int num7 = (int)(src.unTriangleCount * 3u);
            int num8 = num7;

            array2[num8++] = new Vector3(-1f, -1f, 0f);
            array2[num8++] = new Vector3(num, -1f, 0f);
            array2[num8++] = new Vector3(-1f, 1f, 0f);
            array2[num8++] = new Vector3(num, 1f, 0f);
            array2[num8++] = new Vector3(num2, -1f, 0f);
            array2[num8++] = new Vector3(1f, -1f, 0f);
            array2[num8++] = new Vector3(num2, 1f, 0f);
            array2[num8++] = new Vector3(1f, 1f, 0f);
            array2[num8++] = new Vector3(num, num3, 0f);
            array2[num8++] = new Vector3(num2, num3, 0f);
            array2[num8++] = new Vector3(num, num4, 0f);
            array2[num8++] = new Vector3(num2, num4, 0f);
            int num9 = num7;

            array3[num9++] = num7;
            array3[num9++] = num7 + 1;
            array3[num9++] = num7 + 2;
            array3[num9++] = num7 + 2;
            array3[num9++] = num7 + 1;
            array3[num9++] = num7 + 3;
            array3[num9++] = num7 + 4;
            array3[num9++] = num7 + 5;
            array3[num9++] = num7 + 6;
            array3[num9++] = num7 + 6;
            array3[num9++] = num7 + 5;
            array3[num9++] = num7 + 7;
            array3[num9++] = num7 + 1;
            array3[num9++] = num7 + 4;
            array3[num9++] = num7 + 8;
            array3[num9++] = num7 + 8;
            array3[num9++] = num7 + 4;
            array3[num9++] = num7 + 9;
            array3[num9++] = num7 + 10;
            array3[num9++] = num7 + 11;
            array3[num9++] = num7 + 3;
            array3[num9++] = num7 + 3;
            array3[num9++] = num7 + 11;
            array3[num9++] = num7 + 6;
            return(new Mesh
            {
                vertices = array2,
                triangles = array3,
                bounds = new Bounds(Vector3.zero, new Vector3(float.MaxValue, float.MaxValue, float.MaxValue))
            });
        }
Exemplo n.º 26
0
 public static Vector3 Lerp(Vector3 A, Vector3 B, float t)
 {
     return(new Vector3(SteamVR_Utils.Lerp(A.x, B.x, t), SteamVR_Utils.Lerp(A.y, B.y, t), SteamVR_Utils.Lerp(A.z, B.z, t)));
 }
    private IEnumerator RenderLoop()
    {
        while (Application.isPlaying)
        {
            yield return(waitForEndOfFrame);

            if (pauseRendering)
            {
                continue;
            }

            var compositor = OpenVR.Compositor;
            if (compositor != null)
            {
                if (!compositor.CanRenderScene())
                {
                    continue;
                }

                compositor.SetTrackingSpace(trackingSpace);

#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
                SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_WaitGetPoses);

                // Hack to flush render event that was queued in Update (this ensures WaitGetPoses has returned before we grab the new values).
                SteamVR.Unity.EventWriteString("[UnityMain] GetNativeTexturePtr - Begin");
                SteamVR_Camera.GetSceneTexture(cameras[0].GetComponent <Camera>().hdr).GetNativeTexturePtr();
                SteamVR.Unity.EventWriteString("[UnityMain] GetNativeTexturePtr - End");

                compositor.GetLastPoses(poses, gamePoses);
                SteamVR_Events.NewPoses.Send(poses);
                SteamVR_Events.NewPosesApplied.Send();
#endif
            }

            var overlay = SteamVR_Overlay.instance;
            if (overlay != null)
            {
                overlay.UpdateOverlay();
            }

            RenderExternalCamera();

#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
            var vr = SteamVR.instance;
            RenderEye(vr, EVREye.Eye_Left);
            RenderEye(vr, EVREye.Eye_Right);

            // Move cameras back to head position so they can be tracked reliably
            foreach (var c in cameras)
            {
                c.transform.localPosition = Vector3.zero;
                c.transform.localRotation = Quaternion.identity;
            }

            if (cameraMask != null)
            {
                cameraMask.Clear();
            }
#endif
        }
    }
Exemplo n.º 28
0
 void FixedUpdate()
 {
     // We want to call this as soon after Present as possible.
     SteamVR_Utils.QueueEventOnRenderThread(Unity.k_nRenderEventID_PostPresentHandoff);
 }
Exemplo n.º 29
0
 public void Interpolate(SteamVR_Utils.RigidTransform to, float t)
 {
     this.pos = SteamVR_Utils.Lerp(this.pos, to.pos, t);
     this.rot = SteamVR_Utils.Slerp(this.rot, to.rot, t);
 }
Exemplo n.º 30
0
        private bool TestComputeIntersection(ulong handle, Transform point)
        {
            IntersectionResults results = new IntersectionResults();

            return(SteamVR_Utils.ComputeIntersection(handle, point.position, point.forward, SteamVRManager.trackingSpace, ref results));
        }
Exemplo n.º 31
0
 public static Vector2 Saturate(Vector2 A)
 {
     return(new Vector2(SteamVR_Utils.Saturate(A.x), SteamVR_Utils.Saturate(A.y)));
 }
Exemplo n.º 32
0
        protected IEnumerator DoRangeOfMotionBlend(EVRSkeletalMotionRange oldRangeOfMotion, EVRSkeletalMotionRange newRangeOfMotion, float overTime)
        {
            float startTime = Time.time;
            float endTime   = startTime + overTime;

            Vector3[]    oldBonePositions;
            Quaternion[] oldBoneRotations;

            Vector3[]    newBonePositions;
            Quaternion[] newBoneRotations;

            while (Time.time < endTime)
            {
                yield return(null);

                float lerp = (Time.time - startTime) / overTime;

                if (skeletonBlend > 0)
                {
                    skeletonAction.SetRangeOfMotion(oldRangeOfMotion);
                    skeletonAction.UpdateValueWithoutEvents();
                    oldBonePositions = (Vector3[])GetBonePositions().Clone();
                    oldBoneRotations = (Quaternion[])GetBoneRotations().Clone();

                    skeletonAction.SetRangeOfMotion(newRangeOfMotion);
                    skeletonAction.UpdateValueWithoutEvents();
                    newBonePositions = GetBonePositions();
                    newBoneRotations = GetBoneRotations();

                    for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++)
                    {
                        if (bones[boneIndex] == null)
                        {
                            continue;
                        }

                        if (SteamVR_Utils.IsValid(newBoneRotations[boneIndex]) == false || SteamVR_Utils.IsValid(oldBoneRotations[boneIndex]) == false)
                        {
                            continue;
                        }

                        Vector3    blendedRangeOfMotionPosition = Vector3.Lerp(oldBonePositions[boneIndex], newBonePositions[boneIndex], lerp);
                        Quaternion blendedRangeOfMotionRotation = Quaternion.Lerp(oldBoneRotations[boneIndex], newBoneRotations[boneIndex], lerp);

                        if (skeletonBlend < 1)
                        {
                            if (blendPoser != null)
                            {
                                SetBonePosition(boneIndex, Vector3.Lerp(blendSnapshot.bonePositions[boneIndex], blendedRangeOfMotionPosition, skeletonBlend));
                                SetBoneRotation(boneIndex, Quaternion.Lerp(GetBlendPoseForBone(boneIndex, blendedRangeOfMotionRotation), blendedRangeOfMotionRotation, skeletonBlend));
                            }
                            else
                            {
                                SetBonePosition(boneIndex, Vector3.Lerp(bones[boneIndex].localPosition, blendedRangeOfMotionPosition, skeletonBlend));
                                SetBoneRotation(boneIndex, Quaternion.Lerp(bones[boneIndex].localRotation, blendedRangeOfMotionRotation, skeletonBlend));
                            }
                        }
                        else
                        {
                            SetBonePosition(boneIndex, blendedRangeOfMotionPosition);
                            SetBoneRotation(boneIndex, blendedRangeOfMotionRotation);
                        }
                    }
                }

                if (onBoneTransformsUpdated != null)
                {
                    onBoneTransformsUpdated.Invoke(this, inputSource);
                }
                if (onBoneTransformsUpdatedEvent != null)
                {
                    onBoneTransformsUpdatedEvent.Invoke(this, inputSource);
                }
            }

            rangeOfMotionBlendRoutine = null;
        }
Exemplo n.º 33
0
    protected override void OnUpdate()
    {
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4_5)
        if (poseUpdater == null)
        {
            var go = new GameObject("poseUpdater");
            go.transform.parent = transform;
            poseUpdater         = go.AddComponent <SteamVR_UpdatePoses>();
        }
#else
        if (cameras.Length == 0)
        {
            enabled = false;
            return;
        }

        // If our FixedUpdate rate doesn't match our render framerate, then catch the handoff here.
        SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_PostPresentHandoff);
#endif
        // Force controller update in case no one else called this frame to ensure prevState gets updated.
        SteamVR_Controller.Update();

        // Dispatch any OpenVR events.
        var system = OpenVR.System;
        if (system != null)
        {
            var vrEvent = new VREvent_t();
            var size    = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VREvent_t));
            for (int i = 0; i < 64; i++)
            {
                if (!system.PollNextEvent(ref vrEvent, size))
                {
                    break;
                }

                switch ((EVREventType)vrEvent.eventType)
                {
                case EVREventType.VREvent_InputFocusCaptured:                         // another app has taken focus (likely dashboard)
                    SteamVR_Utils.Event.Send("input_focus", false);
                    break;

                case EVREventType.VREvent_InputFocusReleased:                         // that app has released input focus
                    SteamVR_Utils.Event.Send("input_focus", true);
                    break;

                case EVREventType.VREvent_ShowRenderModels:
                    SteamVR_Utils.Event.Send("hide_render_models", false);
                    break;

                case EVREventType.VREvent_HideRenderModels:
                    SteamVR_Utils.Event.Send("hide_render_models", true);
                    break;

                default:
                    var name = System.Enum.GetName(typeof(EVREventType), vrEvent.eventType);
                    if (name != null)
                    {
                        SteamVR_Utils.Event.Send(name.Substring(8) /*strip VREvent_*/, vrEvent);
                    }
                    break;
                }
            }
        }

        // Ensure various settings to minimize latency.
        Application.targetFrameRate     = -1;
        Application.runInBackground     = true; // don't require companion window focus
        QualitySettings.maxQueuedFrames = -1;
        QualitySettings.vSyncCount      = 0;    // this applies to the companion window

        if (lockPhysicsUpdateRateToRenderFrequency)
        {
            var vr = SteamVR.instance;
            if (vr != null)
            {
                var timing = new Compositor_FrameTiming();
                timing.m_nSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Compositor_FrameTiming));
                vr.compositor.GetFrameTiming(ref timing, 0);

                Time.fixedDeltaTime = Time.timeScale * timing.m_nNumFramePresents / SteamVR.instance.hmd_DisplayFrequency;
            }
        }
    }
 public DelayedPose(SteamVR_Utils.RigidTransform pose)
     : this()
 {
     Pose = pose;
 }