Example #1
0
 private void Update()
 {
     Debug.Log(OpenVR.IsHmdPresent());
     if (OpenVR.IsHmdPresent() && (SteamVR.instance != null))
     {
         PCUI.SetActive(false);
         PCCam.SetActive(false);
         VRUI.SetActive(true);
         VRCam.SetActive(true);
     }
     else
     {
         VRUI.SetActive(false);
         VRCam.SetActive(false);
         PCUI.SetActive(true);
         PCCam.SetActive(true);
     }
 }
Example #2
0
    // Use this for initialization
    void Start()
    {
        if (OpenVR.IsHmdPresent())
        {
            CVRChaperone chap = OpenVR.Chaperone;
            float        w    = 0.0f;
            float        l    = 0.0f;
            chap.GetPlayAreaSize(ref w, ref l);
            this.transform.localScale = new Vector3(w * 0.1f, 1.0f, l * 0.1f);

            Material mat = this.gameObject.GetComponent <Renderer>().material;


            mat.mainTextureScale = new Vector2(Mathf.Round(w * 5.0f), Mathf.Round(l * 5.0f));
        }
        else
        {
            Debug.Log("Can't initialize checkered floor pattern. Starting without it.");
        }
    }
Example #3
0
 void Update()
 {
     if (Input.GetKeyDown(KeyCode.O))
     {
         Debug.Log("Switching to OpenVR...");
         try {
             if (OpenVR.IsHmdPresent())
             {
                 StartCoroutine(SwitchToOpenVR());
             }
         } catch (Exception e) {
             Debug.Log("VR NOT POSSIBLE: " + e);
         }
     }
     if (Input.GetKeyDown(KeyCode.N))
     {
         Debug.Log("Switching to None...");
         StartCoroutine(SwitchToNone());
     }
 }
Example #4
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on successful initialization, false otherwise.</returns>
        private static void InitializeOpenVR()
        {
            // return if HMD has already been initialized
            if (hmdState == HmdState.Initialized)
            {
                return;
            }

            // set the location of the OpenVR DLL
            SetDllDirectory(Globals.OpenVRDllPath);

            // check if HMD is connected on the system
            if (!OpenVR.IsHmdPresent())
            {
                throw new InvalidOperationException("HMD not found on this system");
            }

            // check if SteamVR runtime is installed
            if (!OpenVR.IsRuntimeInstalled())
            {
                throw new InvalidOperationException("SteamVR runtime not found on this system");
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);
            if (hmdInitErrorCode != EVRInitError.None)
            {
                throw new Exception("OpenVR error: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
            }

            // reset "seated position" and capture initial position. this means you should hold the HMD in
            // the position you would like to consider "seated", before running this code.
            ResetInitialHmdPosition();

            // get HMD render target size
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            OpenVR.System.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);

            // at the moment, only Direct3D12 is working with Kerbal Space Program
            ETextureType textureType = ETextureType.DirectX;

            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                textureType = ETextureType.OpenGL;
                throw new InvalidOperationException(SystemInfo.graphicsDeviceType.ToString() + " does not support VR. You must use -force-d3d12");

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
                throw new InvalidOperationException(SystemInfo.graphicsDeviceType.ToString() + " does not support VR. You must use -force-d3d12");

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                textureType = ETextureType.DirectX;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D12:
                textureType = ETextureType.DirectX;
                break;

            default:
                throw new InvalidOperationException(SystemInfo.graphicsDeviceType.ToString() + " not supported");
            }

            // initialize render textures (for displaying on HMD)
            for (int i = 0; i < 2; i++)
            {
                hmdEyeRenderTexture[i] = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
                hmdEyeRenderTexture[i].Create();
                hmdEyeTexture[i].handle      = hmdEyeRenderTexture[i].GetNativeTexturePtr();
                hmdEyeTexture[i].eColorSpace = EColorSpace.Auto;
                hmdEyeTexture[i].eType       = textureType;
            }

            // set rendering bounds on texture to render
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 1.0f; // flip the vertical coordinate for some reason
            hmdTextureBounds.vMax = 0.0f;
        }
Example #5
0
 /// <summary>
 /// Returns whether VR is available at all (not necessarily loaded).
 /// </summary>
 /// <returns>VR readiness.</returns>
 public static bool Available()
 {
     return(OpenVR.IsHmdPresent());
 }
Example #6
0
 public static bool hmdAttached()
 {
     return(OpenVR.IsHmdPresent());
 }
Example #7
0
 public bool IsHmdPresent()
 {
     return(OpenVR.IsHmdPresent());
 }
Example #8
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        bool InitHMD()
        {
            bool retVal = false;

            // return if HMD has already been initialized
            if (hmdIsInitialized)
            {
                return(true);
            }

            bool   is64bit = (IntPtr.Size == 8);
            string mypath  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            log("OpenVR path set to " + Path.Combine(mypath, is64bit ? "win64" : "win32"));
            SetDllDirectory(Path.Combine(mypath, is64bit ? "win64" : "win32"));

            // check if HMD is connected on the system
            retVal = OpenVR.IsHmdPresent();
            if (!retVal)
            {
                err("HMD not found on this system.");
                return(retVal);
            }

            // check if SteamVR runtime is installed.
            // For this plugin, MAKE SURE IT IS ALREADY RUNNING.
            retVal = OpenVR.IsRuntimeInstalled();
            if (!retVal)
            {
                err("SteamVR runtime not found on this system.");
                return(retVal);
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            vrSystem = OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);

            // return if failure
            retVal = (hmdInitErrorCode == EVRInitError.None);
            if (!retVal)
            {
                err("Failed to initialize HMD. Init returned: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
                return(retVal);
            }
            else
            {
                log("OpenVR.Init passed.");
            }

            // reset "seated position" and capture initial position. this means you should hold the HMD in
            // the position you would like to consider "seated", before running this code.

            ResetInitialHmdPosition();

            // initialize Compositor
            vrCompositor = OpenVR.Compositor;

            // initialize render textures (for displaying on HMD)
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            vrSystem.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);
            //renderTextureWidth /= 2;
            //renderTextureHeight /= 2;

            log("Render Texture size: " + renderTextureWidth + " x " + renderTextureHeight);

            hmdLeftEyeRenderTexture = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
            hmdLeftEyeRenderTexture.Create();

            hmdRightEyeRenderTexture = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
            hmdRightEyeRenderTexture.Create();

            hmdLeftEyeTexture.handle      = hmdLeftEyeRenderTexture.GetNativeTexturePtr();
            hmdLeftEyeTexture.eColorSpace = EColorSpace.Auto;

            hmdRightEyeTexture.handle      = hmdRightEyeRenderTexture.GetNativeTexturePtr();
            hmdRightEyeTexture.eColorSpace = EColorSpace.Auto;


            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGL2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                hmdLeftEyeTexture.eType  = EGraphicsAPIConvention.API_OpenGL;
                hmdRightEyeTexture.eType = EGraphicsAPIConvention.API_OpenGL;
                break;     //doesnt work in unity 5.4 with current SteamVR (12/2016)

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
                throw (new Exception("DirectX9 not supported"));

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                hmdLeftEyeTexture.eType  = EGraphicsAPIConvention.API_DirectX;
                hmdRightEyeTexture.eType = EGraphicsAPIConvention.API_DirectX;
                break;

            default:
                throw (new Exception(SystemInfo.graphicsDeviceType.ToString() + " not supported"));
            }

            // Set rendering bounds on texture to render?
            // I assume min=0.0 and max=1.0 renders to the full extent of the texture
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 0.0f;
            hmdTextureBounds.vMax = 1.0f;

            // TODO: Need to understand better how to create render targets and incorporate hidden area mask mesh

            foreach (Camera camera in Camera.allCameras)
            {
                log("KSP Camera: " + camera.name);
            }

            // search for camera objects to render
            foreach (string cameraName in cameraNamesToRender)
            {
                foreach (Camera camera in Camera.allCameras)
                {
                    if (cameraName.Equals(camera.name))
                    {
                        float nearClipPlane = (camera.name.Equals(cameraNames[3])) ? 0.05f : camera.nearClipPlane;

                        HmdMatrix44_t projLeft  = vrSystem.GetProjectionMatrix(EVREye.Eye_Left, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_OpenGL);
                        HmdMatrix44_t projRight = vrSystem.GetProjectionMatrix(EVREye.Eye_Right, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_OpenGL);
                        //HmdMatrix44_t projLeft = vrSystem.GetProjectionMatrix(EVREye.Eye_Left, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_DirectX); // this doesn't seem to work
                        //HmdMatrix44_t projRight = vrSystem.GetProjectionMatrix(EVREye.Eye_Right, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_DirectX); // this doesn't seem to work
                        camerasToRender.Add(new CameraProperties(camera, camera.projectionMatrix, MathUtils.Matrix4x4_OpenVr2UnityFormat(ref projLeft), MathUtils.Matrix4x4_OpenVr2UnityFormat(ref projRight)));
                        break;
                    }
                }
            }

            // detect controllers
            for (uint idx = 0; idx < OpenVR.k_unMaxTrackedDeviceCount; idx++)
            {
                if ((ctrlIndexLeft == 0) && (vrSystem.GetTrackedDeviceClass(idx) == ETrackedDeviceClass.Controller))
                {
                    ctrlIndexLeft = idx;
                }
                else if ((ctrlIndexRight == 0) && (vrSystem.GetTrackedDeviceClass(idx) == ETrackedDeviceClass.Controller))
                {
                    ctrlIndexRight = idx;
                }
            }
            bool ctrlFocusCaptured = vrSystem.CaptureInputFocus();

            if (!ctrlFocusCaptured)
            {
                warn("Controller input focus was not captured");
            }

            initTmr.Start();

            return(retVal);
        }
Example #9
0
    //--------------------------------------------------------------------------

    //初期化処理
    private void Start()
    {
#pragma warning disable 0219
        string Tag = "[" + this.GetType().Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(); //クラス名とメソッド名を自動取得
#pragma warning restore 0219
        Debug.Log(Tag + "Begin");

        var openVRError  = EVRInitError.None;
        var overlayError = EVROverlayError.None;
        error = false;

        if (!OpenVR.IsHmdPresent())
        {
            this.enabled = false;
        }

        //フレームレートを90fpsにする。(しないと無限に早くなることがある)
        Application.targetFrameRate = 90;
        Debug.Log(Tag + "Set Frame Rate 90");

        //OpenVRの初期化
        openvr = OpenVR.Init(ref openVRError, EVRApplicationType.VRApplication_Overlay);
        if (openVRError != EVRInitError.None)
        {
            Debug.LogError(Tag + "OpenVRの初期化に失敗." + openVRError.ToString());
            ProcessError();
            return;
        }

        //オーバーレイ機能の初期化
        overlay      = OpenVR.Overlay;
        overlayError = overlay.CreateOverlay(OverlayKeyName, OverlayFriendlyName, ref overlayHandle);
        if (overlayError != EVROverlayError.None)
        {
            Debug.LogError(Tag + "Overlayの初期化に失敗. " + overlayError.ToString());
            ProcessError();
            return;
        }

        //オーバーレイに渡すテクスチャ種類の設定
        var OverlayTextureBounds = new VRTextureBounds_t();
        var isOpenGL             = SystemInfo.graphicsDeviceVersion.Contains("OpenGL");
        if (isOpenGL)
        {
            //pGLuintTexture
            overlayTexture.eType = ETextureType.OpenGL;
            //上下反転しない
            OverlayTextureBounds.uMin = 1;
            OverlayTextureBounds.vMin = 0;
            OverlayTextureBounds.uMax = 1;
            OverlayTextureBounds.vMax = 0;
            overlay.SetOverlayTextureBounds(overlayHandle, ref OverlayTextureBounds);
        }
        else
        {
            //pTexture
            overlayTexture.eType = ETextureType.DirectX;
            //上下反転する
            OverlayTextureBounds.uMin = 0;
            OverlayTextureBounds.vMin = 1;
            OverlayTextureBounds.uMax = 1;
            OverlayTextureBounds.vMax = 0;
            overlay.SetOverlayTextureBounds(overlayHandle, ref OverlayTextureBounds);
        }

        //--------
        showDevices();

        Debug.Log(Tag + "初期化完了しました");
    }
Example #10
0
    void Update()
    {
        if (Input.GetButtonDown("Toggle VR"))
        {
            forceNoVR = !forceNoVR;
        }

        if (Input.GetButtonDown("Toggle Paper"))
        {
            // RechalkCamEffect paper = Camera.main.GetComponent<RechalkCamEffect>();
            // paper.enabled = !paper.enabled;
        }

        vr = OpenVR.IsHmdPresent() && !forceNoVR;
        InGameControls.SetActive(vr && seated);
        if (mouseLook == null)
        {
            mouseLook = Camera.main.GetComponent <SimpleSmoothMouseLook>();
        }
        if (mouseLook != null)
        {
            mouseLook.enabled = !vr;
        }

        if (Input.GetButtonDown("Trigger"))
        {
            Reticle.Triggered = true;
        }
        if (!Frozen && Input.GetButtonDown("Home"))
        {
            SelectLevel(null);
        }
        if (vr && seated)
        {
            // TODO timer-based reticle... in Reticle.cs
        }

        // Google Cardboard Earth demo - styled movement

        /*
         * if (Reticle.Triggered && Reticle.Focused == null) {
         *              Moving = !Moving;
         *              if (!Frozen) {
         *                      for (int i = 0; i < inGameButtons.Length; i++) {
         *                              FloatingButton button = inGameButtons[i];
         *                              if (button == null) {
         *                                      continue;
         *                              }
         *                              button.ScaleFadeSpeed = Moving ? -0.1f : 0.1f;
         *                      }
         *              }
         *      }
         *
         * if (Moving && !Frozen) {
         *              transform.position += Camera.main.transform.forward * Speed * HoloFEZHelper.SpeedF;
         *      }
         */

        // Seated gamepad movement
        if (seated && !Frozen)
        {
            Vector3 dir = Vector3.zero;

            dir += Camera.main.transform.forward * Input.GetAxis("Vertical");

            float angleY = Camera.main.transform.rotation.eulerAngles.y;
            angleY = (angleY + 90f) / 180f * Mathf.PI;
            dir   += new Vector3(Mathf.Sin(angleY), 0f, Mathf.Cos(angleY)) * Input.GetAxis("Horizontal");

            if (dir != Vector3.zero)
            {
                dir.Normalize();
                transform.position += dir * Speed * HoloFEZHelper.SpeedF;
            }

            transform.position += Vector3.up * Input.GetAxis("Y Movement") * Speed * HoloFEZHelper.SpeedF;
        }

        // Seated recalibration
        if (seated && Input.GetButtonDown("Recalibrate"))
        {
            transform.rotation            = Quaternion.Euler(0f, lastRecalibratedYRot = (Camera.main.transform.rotation.eulerAngles.y - lastRecalibratedYRot) - 90f, 0f);
            VRControls.transform.rotation = nullRotation;
        }

        FixedUpdate();
    }
Example #11
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        private bool InitHMD()
        {
            bool retVal = false;

            // return if HMD has already been initialized
            if (hmdIsInitialized)
            {
                return(true);
            }

            // set the location of the OpenVR DLL
            SetDllDirectory(Globals.OpenVRDllPath);

            // check if HMD is connected on the system
            retVal = OpenVR.IsHmdPresent();
            if (!retVal)
            {
                Utils.LogError("HMD not found on this system.");
                return(retVal);
            }

            // check if SteamVR runtime is installed
            retVal = OpenVR.IsRuntimeInstalled();
            if (!retVal)
            {
                Utils.LogError("SteamVR runtime not found on this system.");
                return(retVal);
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);
            retVal = (hmdInitErrorCode == EVRInitError.None);
            if (!retVal)
            {
                Utils.LogError("Failed to initialize HMD. Init returned: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
                return(retVal);
            }

            // reset "seated position" and capture initial position. this means you should hold the HMD in
            // the position you would like to consider "seated", before running this code.
            ResetInitialHmdPosition();

            // get HMD render target size
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            OpenVR.System.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);

            // at the moment, only Direct3D12 is working with Kerbal Space Program
            ETextureType textureType = ETextureType.DirectX;

            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                textureType = ETextureType.OpenGL;
                break;     // doesn't work

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                textureType = ETextureType.DirectX;
                break;     // doesn't work

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D12:
                textureType = ETextureType.DirectX;     // do not use DirectX12
                break;

            default:
                throw (new Exception(SystemInfo.graphicsDeviceType.ToString() + " not supported"));
            }

            openvrTexture             = new Texture_t();
            openvrTexture.eType       = textureType;
            openvrTexture.eColorSpace = EColorSpace.Auto;

            Debug.Log("Graphics Type: " + SystemInfo.graphicsDeviceType);

            // initialize render textures (for displaying on HMD)

            rightEyeRenderTextures[0] = new Texture2D((int)(renderTextureWidth * 1.5), (int)(renderTextureHeight * 1.5), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[0]  = new Texture2D((int)(renderTextureWidth * 1.5), (int)(renderTextureHeight * 1.5), TextureFormat.ARGB32, false);
            renderTextures[0]         = new RenderTexture((int)(renderTextureWidth * 1.5), (int)(renderTextureHeight * 1.5), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[1] = new Texture2D((int)(renderTextureWidth), (int)(renderTextureHeight), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[1]  = new Texture2D((int)(renderTextureWidth), (int)(renderTextureHeight), TextureFormat.ARGB32, false);
            renderTextures[1]         = new RenderTexture((int)(renderTextureWidth), (int)(renderTextureHeight), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[2] = new Texture2D((int)(renderTextureWidth * .75), (int)(renderTextureHeight * .75), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[2]  = new Texture2D((int)(renderTextureWidth * .75), (int)(renderTextureHeight * .75), TextureFormat.ARGB32, false);
            renderTextures[2]         = new RenderTexture((int)(renderTextureWidth * .75), (int)(renderTextureHeight * .75), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[3] = new Texture2D((int)(renderTextureWidth * .5), (int)(renderTextureHeight * .5), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[3]  = new Texture2D((int)(renderTextureWidth * .5), (int)(renderTextureHeight * .5), TextureFormat.ARGB32, false);
            renderTextures[3]         = new RenderTexture((int)(renderTextureWidth * .5), (int)(renderTextureHeight * .5), 24, RenderTextureFormat.ARGB32);

            rightEyeRenderTextures[4] = new Texture2D((int)(renderTextureWidth * .25), (int)(renderTextureHeight * .25), TextureFormat.ARGB32, false);
            leftEyeRenderTextures[4]  = new Texture2D((int)(renderTextureWidth * .25), (int)(renderTextureHeight * .25), TextureFormat.ARGB32, false);
            renderTextures[4]         = new RenderTexture((int)(renderTextureWidth * .25), (int)(renderTextureHeight * .25), 24, RenderTextureFormat.ARGB32);

            // set rendering bounds on texture to render
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 1.0f; // flip the vertical coordinate for some reason
            hmdTextureBounds.vMax = 0.0f;


            hmdIsInitialized = true;

            return(retVal);
        }
Example #12
0
        /// <summary>
        /// Initialize HMD using OpenVR API calls.
        /// </summary>
        /// <returns>True on success, false otherwise. Errors logged.</returns>
        bool InitHMD()
        {
            bool retVal = false;

            // return if HMD has already been initialized
            if (hmdIsInitialized)
            {
                return(true);
            }

            // check if HMD is connected on the system
            retVal = OpenVR.IsHmdPresent();
            if (!retVal)
            {
                Debug.Log("[KerbalVR] HMD not found on this system.");
                return(retVal);
            }

            // check if SteamVR runtime is installed.
            // For this plugin, MAKE SURE IT IS ALREADY RUNNING.
            retVal = OpenVR.IsRuntimeInstalled();
            if (!retVal)
            {
                Debug.Log("[KerbalVR] SteamVR runtime not found on this system.");
                return(retVal);
            }

            // initialize HMD
            EVRInitError hmdInitErrorCode = EVRInitError.None;

            vrSystem = OpenVR.Init(ref hmdInitErrorCode, EVRApplicationType.VRApplication_Scene);

            // return if failure
            retVal = (hmdInitErrorCode == EVRInitError.None);
            if (!retVal)
            {
                Debug.Log("[KerbalVR] Failed to initialize HMD. Init returned: " + OpenVR.GetStringForHmdError(hmdInitErrorCode));
                return(retVal);
            }
            else
            {
                Debug.Log("[KerbalVR] OpenVR.Init passed.");
            }

            // reset "seated position" and capture initial position. this means you should hold the HMD in
            // the position you would like to consider "seated", before running this code.
            hmdIsInitialized = true;
            ResetInitialHmdPosition();

            // initialize Compositor
            vrCompositor = OpenVR.Compositor;

            // initialize render textures (for displaying on HMD)
            uint renderTextureWidth  = 0;
            uint renderTextureHeight = 0;

            vrSystem.GetRecommendedRenderTargetSize(ref renderTextureWidth, ref renderTextureHeight);
            //renderTextureWidth /= 2;
            //renderTextureHeight /= 2;

            Debug.Log("[KerbalVR] Render Texture size: " + renderTextureWidth + " x " + renderTextureHeight);

            hmdLeftEyeRenderTexture = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
            hmdLeftEyeRenderTexture.antiAliasing = 1;
            hmdLeftEyeRenderTexture.Create();

            hmdRightEyeRenderTexture = new RenderTexture((int)renderTextureWidth, (int)renderTextureHeight, 24, RenderTextureFormat.ARGB32);
            hmdRightEyeRenderTexture.Create();

            hmdLeftEyeTexture.handle = hmdLeftEyeRenderTexture.GetNativeTexturePtr();
            hmdLeftEyeTexture.eType  = EGraphicsAPIConvention.API_OpenGL;
            //hmdLeftEyeTexture.eType = EGraphicsAPIConvention.API_DirectX; // this doesn't seem to work
            hmdLeftEyeTexture.eColorSpace = EColorSpace.Auto;

            hmdRightEyeTexture.handle = hmdRightEyeRenderTexture.GetNativeTexturePtr();
            hmdRightEyeTexture.eType  = EGraphicsAPIConvention.API_OpenGL;
            //hmdRightEyeTexture.eType = EGraphicsAPIConvention.API_DirectX; // this doesn't seem to work
            hmdRightEyeTexture.eColorSpace = EColorSpace.Auto;

            // Set rendering bounds on texture to render?
            // I assume min=0.0 and max=1.0 renders to the full extent of the texture
            hmdTextureBounds.uMin = 0.0f;
            hmdTextureBounds.uMax = 1.0f;
            hmdTextureBounds.vMin = 0.0f;
            hmdTextureBounds.vMax = 1.0f;

            // create the hidden area mask meshes
            HiddenAreaMesh_t vrHiddenAreaMesh = vrSystem.GetHiddenAreaMesh(EVREye.Eye_Left);

            hmdHiddenAreaMeshLeft  = SteamVR_Utils.CreateHiddenAreaMesh(vrHiddenAreaMesh, hmdTextureBounds);
            vrHiddenAreaMesh       = vrSystem.GetHiddenAreaMesh(EVREye.Eye_Right);
            hmdHiddenAreaMeshRight = SteamVR_Utils.CreateHiddenAreaMesh(vrHiddenAreaMesh, hmdTextureBounds);

            // TODO: Need to understand better how to create render targets and incorporate hidden area mask mesh

            // search for camera objects to render
            foreach (string cameraName in cameraNamesToRender)
            {
                foreach (Camera camera in Camera.allCameras)
                {
                    if (cameraName.Equals(camera.name))
                    {
                        float nearClipPlane = (camera.name.Equals(cameraNames[3])) ? 0.05f : camera.nearClipPlane;

                        HmdMatrix44_t projLeft  = vrSystem.GetProjectionMatrix(EVREye.Eye_Left, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_OpenGL);
                        HmdMatrix44_t projRight = vrSystem.GetProjectionMatrix(EVREye.Eye_Right, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_OpenGL);
                        //HmdMatrix44_t projLeft = vrSystem.GetProjectionMatrix(EVREye.Eye_Left, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_DirectX); // this doesn't seem to work
                        //HmdMatrix44_t projRight = vrSystem.GetProjectionMatrix(EVREye.Eye_Right, nearClipPlane, camera.farClipPlane, EGraphicsAPIConvention.API_DirectX); // this doesn't seem to work
                        camerasToRender.Add(new CameraProperties(camera, camera.projectionMatrix, MathUtils.Matrix4x4_OpenVr2UnityFormat(ref projLeft), MathUtils.Matrix4x4_OpenVr2UnityFormat(ref projRight)));
                        break;
                    }
                }
            }

            foreach (Camera camera in Camera.allCameras)
            {
                if (cameraNames[5].Equals(camera.name))
                {
                    uiCamera = camera;
                }
            }

            // detect controllers
            for (uint idx = 0; idx < OpenVR.k_unMaxTrackedDeviceCount; idx++)
            {
                if ((ctrlIndexLeft == 0) && (vrSystem.GetTrackedDeviceClass(idx) == ETrackedDeviceClass.Controller))
                {
                    ctrlIndexLeft = idx;
                }
                else if ((ctrlIndexRight == 0) && (vrSystem.GetTrackedDeviceClass(idx) == ETrackedDeviceClass.Controller))
                {
                    ctrlIndexRight = idx;
                }
            }
            bool ctrlFocusCaptured = vrSystem.CaptureInputFocus();

            if (!ctrlFocusCaptured)
            {
                Debug.LogWarning("[KerbalVR] Controller input focus was not captured");
            }

            return(retVal);
        }
    // Start is called before the first frame update
    void Start()
    {
        // Check for available HMD
        trackingSystem = OpenVR.IVRSystem_Version;

        if (!OpenVR.IsHmdPresent())
        {
            Debug.LogWarning("No HMD present, render properties init - desktop mode");
            EnvConstants.DesktopMode = true;
            XRSettings.enabled       = false;
            return;
        }

        // Initially, determine rendering parameters, save them and display on startup once in debugLog
        uint w = 0, h = 0;

        OpenVR.System.GetRecommendedRenderTargetSize(ref w, ref h);
        var sceneWidth  = (float)w;
        var sceneHeight = (float)h;

        hmdResolution = new Vector2(w, h);

        float l_left = 0.0f, l_right = 0.0f, l_top = 0.0f, l_bottom = 0.0f;

        OpenVR.System.GetProjectionRaw(EVREye.Eye_Left, ref l_left, ref l_right, ref l_top, ref l_bottom);


        float r_left = 0.0f, r_right = 0.0f, r_top = 0.0f, r_bottom = 0.0f;

        OpenVR.System.GetProjectionRaw(EVREye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

        var tanHalfFov = new Vector2(
            Mathf.Max(-l_left, l_right, -r_left, r_right),
            Mathf.Max(-l_top, l_bottom, -r_top, r_bottom));

        // Get raw texture bounds
        textureBounds = new VRTextureBounds_t[2];

        textureBounds[0].uMin = 0.5f + 0.5f * l_left / tanHalfFov.x;
        textureBounds[0].uMax = 0.5f + 0.5f * l_right / tanHalfFov.x;
        textureBounds[0].vMin = 0.5f - 0.5f * l_bottom / tanHalfFov.y;
        textureBounds[0].vMax = 0.5f - 0.5f * l_top / tanHalfFov.y;

        textureBounds[1].uMin = 0.5f + 0.5f * r_left / tanHalfFov.x;
        textureBounds[1].uMax = 0.5f + 0.5f * r_right / tanHalfFov.x;
        textureBounds[1].vMin = 0.5f - 0.5f * r_bottom / tanHalfFov.y;
        textureBounds[1].vMax = 0.5f - 0.5f * r_top / tanHalfFov.y;

        // Grow the recommended size to account for the overlapping fov
        sceneWidth  = sceneWidth / Mathf.Max(textureBounds[0].uMax - textureBounds[0].uMin, textureBounds[1].uMax - textureBounds[1].uMin);
        sceneHeight = sceneHeight / Mathf.Max(textureBounds[0].vMax - textureBounds[0].vMin, textureBounds[1].vMax - textureBounds[1].vMin);

        // Calculate initial base resolution
        renderBaseResolution = new Vector2(sceneWidth, sceneHeight);

        // Calculate aspect / fov
        recommendedAspect = tanHalfFov.x / tanHalfFov.y;
        recommendedFOV    = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        // Per-Eye Texture Settings
        initialPositionBoth = new Vector2(renderBaseResolution.x / 2, renderBaseResolution.y / 2);

        // Calculate actual position for left eye w/ bounds
        adaptedPositionLeft = new Vector2(-(initialPositionBoth.x) + ((1.0f - textureBounds[0].uMax) * sceneWidth),
                                          -(initialPositionBoth.y) - (textureBounds[0].vMin * sceneHeight));
        //Debug.LogWarning(textureBounds[0].uMin + " ---- " + textureBounds[0].uMax);

        // Calculate actual position for right eye w/ bounds
        adaptedPositionRight = new Vector2(-(initialPositionBoth.x) - (textureBounds[1].uMin * sceneWidth),
                                           -(initialPositionBoth.y) - (textureBounds[1].vMin * sceneHeight));
        //Debug.LogWarning(textureBounds[1].uMin + " ---- " + textureBounds[1].uMax);

        // Set material props
        if (setMaterialPropsOnStart)
        {
            //Left
            LeftEyeGO.GetComponent <Renderer>().material.SetFloat("_X", adaptedPositionLeft.x);
            LeftEyeGO.GetComponent <Renderer>().material.SetFloat("_Y", adaptedPositionLeft.y);
            LeftEyeGO.GetComponent <Renderer>().material.SetFloat("_Width", renderBaseResolution.x);
            LeftEyeGO.GetComponent <Renderer>().material.SetFloat("_Height", renderBaseResolution.y);
            //LeftEyeRT.width = (int) renderBaseResolution.x;
            //LeftEyeRT.height = (int) renderBaseResolution.y;

            //Right
            RightEyeGO.GetComponent <Renderer>().material.SetFloat("_X", adaptedPositionRight.x);
            RightEyeGO.GetComponent <Renderer>().material.SetFloat("_Y", adaptedPositionRight.y);
            RightEyeGO.GetComponent <Renderer>().material.SetFloat("_Width", renderBaseResolution.x);
            RightEyeGO.GetComponent <Renderer>().material.SetFloat("_Height", renderBaseResolution.y);
            //RightEyeRT.width = (int) renderBaseResolution.x;
            //RightEyeRT.height = (int) renderBaseResolution.y;
        }
    }
Example #14
0
 public static bool isVRPresent()
 {
     return(OpenVR.IsHmdPresent());
 }