示例#1
0
        //OpenVRを初期化する
        public bool StartOpenVR(EVRApplicationType type = EVRApplicationType.VRApplication_Overlay)
        {
            //すでに利用可能な場合は初期化しない(衝突する)
            if (Init())
            {
                return(true);
            }

            //初期化する
            var openVRError = EVRInitError.None;

            openvr = OpenVR.Init(ref openVRError, type);
            if (openVRError != EVRInitError.None)
            {
                return(false);
            }

            //本ライブラリも初期化
            return(Init());
        }
示例#2
0
        static void Main()
        {
            var error  = EVRInitError.None;
            var handle = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Background);

            if (error != EVRInitError.None)
            {
                MessageBox.Show($"Could not connect to OpenVR server: {OpenVR.GetStringForHmdError(error)}\n\nPlease make sure an OpenVR server is running (e.g. SteamVR) and try again.", "Fatal Error");
                Application.Exit();
                return;
            }

            OpenVRHandle = handle;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            new BatteryStatus().Start();
            Application.Run();
        }
        public static object CallSystemFn(SystemFn fn, params object[] args)
        {
            var initOpenVR = !Varjo_SteamVR.active;

            if (initOpenVR)
            {
                var error = EVRInitError.None;
                OpenVR.Init(ref error, EVRApplicationType.VRApplication_Background);
            }

            var system = OpenVR.System;
            var result = (system != null) ? fn(system, args) : null;

            if (initOpenVR)
            {
                OpenVR.Shutdown();
            }

            return(result);
        }
示例#4
0
    public static object CallSystemFn(SystemFn fn, params object[] args)
    {
        var initOpenVR = (!SteamVR.active && !SteamVR.usingNativeSupport);

        if (initOpenVR)
        {
            var error = EVRInitError.None;
            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Utility);
        }

        var system = OpenVR.System;
        var result = (system != null) ? fn(system, args) : null;

        if (initOpenVR)
        {
            OpenVR.Shutdown();
        }

        return(result);
    }
示例#5
0
        public override int TryInitialize()
        {
            var error = EVRInitError.None;

            m_System = OpenVR.Init(ref error);

            if (error != EVRInitError.None)
            {
                return(-1);
            }

            var strDriver  = GetTrackedDeviceString(OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_TrackingSystemName_String);
            var strDisplay = GetTrackedDeviceString(OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_SerialNumber_String);

            Debug.LogFormat("Driver: {0} - Display {1}", strDriver, strDisplay);

            PreviewRenderEffect = SpriteEffects.FlipVertically;

            return(0);
        }
示例#6
0
        public void Connect()
        {
            if (vr != null)
            {
                return;
            }
            //Initialize OpenVR
            EVRInitError eError = EVRInitError.None;

            vr = OpenVR.Init(ref eError, EVRApplicationType.VRApplication_Background);
            if (eError != EVRInitError.None)
            {
                ReportError(eError);
                OpenVR.Shutdown();
                vr      = null;
                Success = false;
                return;
            }
            Success = true;
        }
示例#7
0
        public static VRSupport TryInit(Client tclient)
        {
            if (!Available())
            {
                return(null);
            }
            EVRInitError err = EVRInitError.None;
            VRSupport    vrs = new VRSupport()
            {
                TheClient = tclient, VR = OpenVR.Init(ref err)
            };

            if (err != EVRInitError.None)
            {
                SysConsole.Output(OutputType.INFO, "VR error: " + err + ": " + OpenVR.GetStringForHmdError(err));
                return(null);
            }
            vrs.Start();
            return(vrs);
        }
示例#8
0
        // Initializing connection to OpenVR
        private static bool InitVR()
        {
            var error = EVRInitError.None;

            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
            if (error != EVRInitError.None)
            {
                LogUtils.WriteLineToCache($"Error: OpenVR init failed: {Enum.GetName(typeof(EVRInitError), error)}");
                return(false);
            }
            else
            {
                LogUtils.WriteLineToCache("OpenVR init success");

                // Add app manifest and set auto-launch
                var appKey = "boll7708.openvrstartup";
                if (!OpenVR.Applications.IsApplicationInstalled(appKey))
                {
                    var manifestError = OpenVR.Applications.AddApplicationManifest(Path.GetFullPath("./app.vrmanifest"), false);
                    if (manifestError == EVRApplicationError.None)
                    {
                        LogUtils.WriteLineToCache("Successfully installed app manifest");
                    }
                    else
                    {
                        LogUtils.WriteLineToCache($"Error: Failed to add app manifest: {Enum.GetName(typeof(EVRApplicationError), manifestError)}");
                    }

                    var autolaunchError = OpenVR.Applications.SetApplicationAutoLaunch(appKey, true);
                    if (autolaunchError == EVRApplicationError.None)
                    {
                        LogUtils.WriteLineToCache("Successfully set app to auto launch");
                    }
                    else
                    {
                        LogUtils.WriteLineToCache($"Error: Failed to turn on auto launch: {Enum.GetName(typeof(EVRApplicationError), autolaunchError)}");
                    }
                }
                return(true);
            }
        }
        IEnumerator Initialize()
        {
            var error = EVRInitError.None;

            // No need to initialize OpenVR until we have a valid session
            while (!VarjoPlugin.SessionValid)
            {
                yield return(new WaitForSeconds(1.0f));
            }

            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Utility);

            if (error != EVRInitError.None)
            {
                Debug.LogWarning("Failed to initialize OpenVR. Entering into poll mode...");

                do
                {
                    OpenVR.Init(ref error, EVRApplicationType.VRApplication_Utility);
                    yield return(new WaitForSeconds(3.0f));
                } while (error != EVRInitError.None);
            }

            Debug.Log("Varjo_SteamVR_Manager initialized succesfully");

            Varjo_SteamVR_Events.System(EVREventType.VREvent_Quit).Listen(OnQuit);
#if UNITY_2017_1_OR_NEWER
            Application.onBeforeRender += OnBeforeRender;
#else
            Camera.onPreCull += OnCameraPreCull;
#endif
            // We should always use standing tracking with Varjo
            TrackingSpace = ETrackingUniverseOrigin.TrackingUniverseStanding;

            var vr = Varjo_SteamVR.instance;
            if (vr == null)
            {
                enabled = false;
                yield break;
            }
        }
示例#10
0
 private static SteamVR CreateInstance()
 {
     try
     {
         EVRInitError eVRInitError = EVRInitError.None;
         if (!SteamVR.usingNativeSupport)
         {
             OpenVR.Init(ref eVRInitError, EVRApplicationType.VRApplication_Scene);
             if (eVRInitError != EVRInitError.None)
             {
                 SteamVR.ReportError(eVRInitError);
                 SteamVR.ShutdownSystems();
                 SteamVR result = null;
                 return(result);
             }
         }
         OpenVR.GetGenericInterface("IVRCompositor_013", ref eVRInitError);
         if (eVRInitError != EVRInitError.None)
         {
             SteamVR.ReportError(eVRInitError);
             SteamVR.ShutdownSystems();
             SteamVR result = null;
             return(result);
         }
         OpenVR.GetGenericInterface("IVROverlay_010", ref eVRInitError);
         if (eVRInitError != EVRInitError.None)
         {
             SteamVR.ReportError(eVRInitError);
             SteamVR.ShutdownSystems();
             SteamVR result = null;
             return(result);
         }
     }
     catch (Exception message)
     {
         Debug.LogError(message);
         SteamVR result = null;
         return(result);
     }
     return(new SteamVR());
 }
示例#11
0
    void Start()
    {
        var error = EVRInitError.None;

        _vrSystem = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);

        if (error != EVRInitError.None)
        {
            Debug.LogWarning("Init error: " + error);
        }

        else
        {
            Debug.Log("init done");
            foreach (var item in targetObjs)
            {
                item.SetActive(false);
            }
            SetDeviceIds();
        }
    }
示例#12
0
        public static OpenVRScene Create(float nearClip, float farClip)
        {
            EVRInitError error = EVRInitError.None;
            CVRSystem    hmd   = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Scene);

            if (error != EVRInitError.None)
            {
                throw new InvalidOperationException($"Unable to initilize OpenVR: {error}");
            }

            string[] failedProps = OpenVRUtil.GetFailedRequiredComponents().ToArray();
            if (failedProps.Length != 0)
            {
                throw new InvalidOperationException($"Failed to initialize the following static properties: {string.Join(", ", failedProps)}");
            }

            int leftIndex  = hmd.LeftControllerIndex().Validate(errMsg => new InvalidOperationException(errMsg));
            int rightIndex = hmd.RightControllerIndex().Validate(errMsg => new InvalidOperationException(errMsg));

            return(new OpenVRScene(nearClip, farClip, hmd, leftIndex, rightIndex));
        }
示例#13
0
    bool OpenVR_Setup()
    {
        EVRInitError error = EVRInitError.None;

        OpenVR.Init(ref error, appType);

        if (CheckErr(error))
        {
            return(false);
        }

        // OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
        // if(CheckErr(error)) return false;

        // OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
        // if(CheckErr(error)) return false;

        Debug.Log("OpenVR - Startup!");

        return(true);
    }
示例#14
0
        public void Initialize(string name, string key, TextureFormat format)
        {
            var openVRError  = EVRInitError.None;
            var overlayError = EVROverlayError.None;

            //OpenVRの初期化
            openvr = OpenVR.Init(ref openVRError, EVRApplicationType.VRApplication_Overlay);
            if (openVRError != EVRInitError.None)
            {
                Dispose();
                throw new IOException(openVRError.ToString());
            }

            //オーバーレイ機能の初期化
            overlay      = OpenVR.Overlay;
            overlayError = overlay.CreateOverlay(name, key, ref overlayHandle);
            if (overlayError != EVROverlayError.None)
            {
                Dispose();
                throw new IOException(overlayError.ToString());
            }

            //オーバーレイに渡すテクスチャ種類の設定
            if (format == TextureFormat.OpenGL)
            {
                //pGLuintTexture
                overlayTexture.eType = ETextureType.OpenGL;
                //上下反転しない
                SetTextureBounds(0, 0, 1, 1);
            }
            else
            {
                //pTexture
                overlayTexture.eType = ETextureType.DirectX;
                //上下反転する
                SetTextureBounds(0, 1, 1, 0);
            }

            return;
        }
示例#15
0
    static SteamVR CreateInstance()
    {
        try
        {
            var error = EVRInitError.None;

            OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }

            // Verify common interfaces are valid.

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                ShutdownSystems();
                return(null);
            }
        }
        catch (System.Exception e)
        {
            throw new System.Exception(e.Message);
        }

        return(new SteamVR());
    }
示例#16
0
        protected override void Initialize()
        {
            base.Initialize();

            var error = EVRInitError.None;

            bool initialized = true;

            hmd = OpenVR.Init(ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                initialized = false;
            }

            // Verify common interfaces are valid.
            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                initialized = false;
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                initialized = false;
            }

            if (!initialized)
            {
                OpenVR.Shutdown();
                return;
            }

            controllerManager.Initialize();
        }
示例#17
0
        public void Init()
        {
            this.connectionCode = Properties.Settings.Default.ConnectionCode;
            if (this.connectionCode == null || this.connectionCode.Length == 0)
            {
                this.connectionCode = RandomString(16);
                Properties.Settings.Default.ConnectionCode = this.connectionCode;
                Properties.Settings.Default.Save();
            }
            Console.WriteLine("Connection Code: " + this.connectionCode);


            //var controller = HUDCenterController.GetInstance();
            //controller.Init(EVRApplicationType.VRApplication_Overlay);

            EVRInitError error = EVRInitError.None;

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

            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing OpenVR!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Compositor!");
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                throw new Exception("An error occured while initializing Overlay!");
            }

            InitOverlay();
        }
示例#18
0
    void Start()
    {
        var error = EVRInitError.None;

        _vrSystem = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);

        if (error != EVRInitError.None)
        {
            Debug.LogWarning("Init error: " + error);
        }

        else
        {
            Debug.Log("init done");
            foreach (var item in targetObjs)
            {
                //Quaternion fixedRot = Quaternion.Euler(90f, 0f, 0f);
                //item.transform.rotation;
                item.SetActive(false);
            }
            SetDeviceIds();
        }
    }
示例#19
0
    static SteamVR CreateInstance()
    {
        try
        {
            var error = EVRInitError.None;
            if (!SteamVR.usingNativeSupport)
            {
                Debug.Log("OpenVR initialization failed.  Ensure 'Virtual Reality Supported' is checked in Player Settings, and OpenVR is added to the list of Virtual Reality SDKs.");
                return(null);
            }

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

            // Verify common interfaces are valid.

            OpenVR.GetGenericInterface(OpenVR.IVRCompositor_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                return(null);
            }

            OpenVR.GetGenericInterface(OpenVR.IVROverlay_Version, ref error);
            if (error != EVRInitError.None)
            {
                ReportError(error);
                return(null);
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError(e);
            return(null);
        }

        return(new SteamVR());
    }
示例#20
0
        static void RegisterManifest()
        {
            EVRInitError initErr = EVRInitError.None;

            OpenVR.Init(ref initErr, EVRApplicationType.VRApplication_Utility);

            if (initErr != EVRInitError.None)
            {
                Console.WriteLine($"Error initializing OpenVR handle: {initErr}");
                Environment.Exit(1);
            }

            var err = OpenVR.Applications.AddApplicationManifest(Utils.PathToResource("manifest.vrmanifest"), false);

            if (err != EVRApplicationError.None)
            {
                Console.WriteLine($"Error registering manifest with OpenVR runtime: {err}");
                Environment.Exit(1);
            }

            Console.WriteLine("Application manifest registered with OpenVR runtime!");

            OpenVR.Shutdown();
        }
示例#21
0
        static void DeregisterManifest()
        {
            EVRInitError initErr = EVRInitError.None;

            OpenVR.Init(ref initErr, EVRApplicationType.VRApplication_Utility);

            if (initErr != EVRInitError.None)
            {
                Console.WriteLine($"Error initializing OpenVR handle: {initErr}");
                Environment.Exit(1);
            }

            var err = OpenVR.Applications.RemoveApplicationManifest(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "manifest.vrmanifest"));

            if (err != EVRApplicationError.None)
            {
                Console.WriteLine($"Error de-registering manifest with OpenVR runtime: {err}");
                Environment.Exit(1);
            }

            Console.WriteLine("Application manifest de-registered with OpenVR runtime!");

            OpenVR.Shutdown();
        }
示例#22
0
        public bool Init()
        {
            EVRInitError peError = EVRInitError.None;

            m_HMD = OpenVR.Init(ref peError, EVRApplicationType.VRApplication_Overlay);
            if (peError != EVRInitError.None)
            {
                txtLog.AppendText("OpenVR啟動失敗: " + peError + '\n');
                return(false);
            }
            if (OpenVR.Overlay != null)
            {
                EVROverlayError overlayError = OpenVR.Overlay.CreateOverlay("ViveOverlayPaster", "Paster", ref m_ulOverlayHandle);
                if (overlayError == EVROverlayError.None)
                {
                    OpenVR.Overlay.SetOverlayWidthInMeters(m_ulOverlayHandle, 1f);
                    OpenVR.Overlay.SetOverlayTransformTrackedDeviceRelative(m_ulOverlayHandle, OpenVR.k_unTrackedDeviceIndex_Hmd, ref m_PosMatrix);
                    OpenVR.Overlay.SetOverlayAlpha(m_ulOverlayHandle, 0.9f);
                    txtLog.AppendText("OpenVR啟動成功\n");
                    return(true);
                }
            }
            return(false);
        }
        public bool Setup()
        {
            var error = EVRInitError.None;

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

            if (error == EVRInitError.Init_HmdNotFound)
            {
                Close();
                //HMD require fallback
                openVR = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Background);
            }

            if (error != EVRInitError.None)
            { //Error Init OpenVR
                Close();
                System.IO.File.WriteAllText(Application.dataPath + "/../OpenVRInitError.txt", error.ToString());
                return(false);
            }

            OnOVRConnected?.Invoke(this, new OVRConnectedEventArgs(true));

            return(true);
        }
示例#24
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;
        }
示例#25
0
    static RenderModel LoadRenderModel(string renderModelName)
    {
        var error = HmdError.None;

        if (!SteamVR.active)
        {
            OpenVR.Init(ref error);
            if (error != HmdError.None)
            {
                return(null);
            }
        }

        var pRenderModels = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);

        if (pRenderModels == System.IntPtr.Zero || error != HmdError.None)
        {
            if (!SteamVR.active)
            {
                OpenVR.Shutdown();
            }
            return(null);
        }

        var renderModels = new CVRRenderModels(pRenderModels);

        var renderModel = new RenderModel_t();

        if (!renderModels.LoadRenderModel(renderModelName, ref renderModel))
        {
            Debug.LogError("Failed to load render model " + renderModelName);

            if (!SteamVR.active)
            {
                OpenVR.Shutdown();
            }
            return(null);
        }

        var vertices = new Vector3[renderModel.unVertexCount];
        var normals  = new Vector3[renderModel.unVertexCount];
        var uv       = new Vector2[renderModel.unVertexCount];

        var type = typeof(RenderModel_Vertex_t);

        for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
        {
            var ptr  = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
            var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

            vertices[iVert] = new Vector3(vert.vPosition.v[0], vert.vPosition.v[1], -vert.vPosition.v[2]);
            normals[iVert]  = new Vector3(vert.vNormal.v[0], vert.vNormal.v[1], -vert.vNormal.v[2]);
            uv[iVert]       = new Vector2(vert.rfTextureCoord[0], vert.rfTextureCoord[1]);
        }

        int indexCount = (int)renderModel.unTriangleCount * 3;
        var indices    = new short[indexCount];

        Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

        var triangles = new int[indexCount];

        for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
        {
            triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
            triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
            triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
        }

        var mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.normals   = normals;
        mesh.uv        = uv;
        mesh.triangles = triangles;

        mesh.Optimize();
        //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

        var textureMapData = new byte[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight * 4];         // RGBA

        Marshal.Copy(renderModel.diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

        var colors = new Color32[renderModel.diffuseTexture.unWidth * renderModel.diffuseTexture.unHeight];
        int iColor = 0;

        for (int iHeight = 0; iHeight < renderModel.diffuseTexture.unHeight; iHeight++)
        {
            for (int iWidth = 0; iWidth < renderModel.diffuseTexture.unWidth; iWidth++)
            {
                var r = textureMapData[iColor++];
                var g = textureMapData[iColor++];
                var b = textureMapData[iColor++];
                var a = textureMapData[iColor++];
                colors[iHeight * renderModel.diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
            }
        }

        var texture = new Texture2D(renderModel.diffuseTexture.unWidth, renderModel.diffuseTexture.unHeight, TextureFormat.ARGB32, true);

        texture.SetPixels32(colors);
        texture.Apply();

        //texture.hideFlags = HideFlags.DontUnloadUnusedAsset;

        renderModels.FreeRenderModel(ref renderModel);

        if (!SteamVR.active)
        {
            OpenVR.Shutdown();
        }

        return(new RenderModel(mesh, texture));
    }
示例#26
0
        static void Main(string[] args)
        {
            // Initializing connection to OpenVR
            var error = EVRInitError.None;

            OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
            if (error != EVRInitError.None)
            {
                Utils.PrintError($"OpenVR initialization errored: {Enum.GetName(typeof(EVRInitError), error)}");
            }
            else
            {
                Utils.PrintInfo("OpenVR initialized successfully.");

                // Loading manifests
                var appError = OpenVR.Applications.AddApplicationManifest(Path.GetFullPath("./app.vrmanifest"), false);
                if (appError != EVRApplicationError.None)
                {
                    Utils.PrintError($"Failed to load Application Manifest: {Enum.GetName(typeof(EVRApplicationError), appError)}");
                }
                else
                {
                    Utils.PrintInfo("Application Manifest loaded successfully.");
                }

                var ioErr = OpenVR.Input.SetActionManifestPath(Path.GetFullPath("./actions.json"));
                if (ioErr != EVRInputError.None)
                {
                    Utils.PrintError($"Failed to load Action Manifest: {Enum.GetName(typeof(EVRInputError), ioErr)}");
                }
                else
                {
                    Utils.PrintInfo("Action Manifest loaded successfully.");
                }

                // Getting action set handle
                var errorAS = OpenVR.Input.GetActionSetHandle("actions/default", ref mActionSetHandle);
                if (errorAS != EVRInputError.None)
                {
                    Utils.PrintError($"GetActionSetHandle Error: {Enum.GetName(typeof(EVRInputError), errorAS)}");
                }
                Utils.PrintDebug($"Action Set Handle: {mActionSetHandle}");

                // Getting action handle.
                var errorA = OpenVR.Input.GetActionHandle("/actions/default/in/toggle_menu", ref mActionHandle);
                if (errorA != EVRInputError.None)
                {
                    Utils.PrintError($"GetActionHandle Error: {Enum.GetName(typeof(EVRInputError), errorA)}");
                }
                Utils.PrintDebug($"Action Handle: {mActionHandle}");

                // Starting worker
                Utils.PrintDebug("Starting worker thread.");
                var t = new Thread(Worker);
                if (!t.IsAlive)
                {
                    t.Start();
                }
                else
                {
                    Utils.PrintError("Could not start worker thread.");
                }
            }
            Console.ReadLine();
            OpenVR.Shutdown();
        }
示例#27
0
文件: VRCXVR.cs 项目: timduru/VRCX
 // NOTE
 // 메모리 릭 때문에 미리 생성해놓고 계속 사용함
 public static void Init()
 {
     m_Device   = new Device(DriverType.Hardware, DeviceCreationFlags.SingleThreaded | DeviceCreationFlags.BgraSupport);
     m_Texture1 = new Texture2D(m_Device, new Texture2DDescription()
     {
         Width             = 512,
         Height            = 512,
         MipLevels         = 1,
         ArraySize         = 1,
         Format            = Format.B8G8R8A8_UNorm,
         SampleDescription = new SampleDescription(1, 0),
         Usage             = ResourceUsage.Dynamic,
         BindFlags         = BindFlags.ShaderResource,
         CpuAccessFlags    = CpuAccessFlags.Write
     });
     m_Texture2 = new Texture2D(m_Device, new Texture2DDescription()
     {
         Width             = 512,
         Height            = 512,
         MipLevels         = 1,
         ArraySize         = 1,
         Format            = Format.B8G8R8A8_UNorm,
         SampleDescription = new SampleDescription(1, 0),
         Usage             = ResourceUsage.Dynamic,
         BindFlags         = BindFlags.ShaderResource,
         CpuAccessFlags    = CpuAccessFlags.Write
     });
     m_Browser1 = new Browser(m_Texture1, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html/vr.html?1"));
     m_Browser2 = new Browser(m_Texture2, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html/vr.html?2"));
     m_Thread   = new Thread(() =>
     {
         var active           = false;
         var e                = new VREvent_t();
         var nextInit         = DateTime.MinValue;
         var nextDeviceUpdate = DateTime.MinValue;
         var nextOverlay      = DateTime.MinValue;
         var overlayIndex     = OpenVR.k_unTrackedDeviceIndexInvalid;
         var overlayVisible1  = false;
         var overlayVisible2  = false;
         var dashboardHandle  = 0UL;
         var overlayHandle1   = 0UL;
         var overlayHandle2   = 0UL;
         while (m_Thread != null)
         {
             try
             {
                 Thread.Sleep(10);
             }
             catch
             {
                 // ThreadInterruptedException
             }
             if (m_Active)
             {
                 m_Browser1.Render();
                 m_Browser2.Render();
                 var system = OpenVR.System;
                 if (system == null)
                 {
                     if (DateTime.UtcNow.CompareTo(nextInit) <= 0)
                     {
                         continue;
                     }
                     var _err = EVRInitError.None;
                     system   = OpenVR.Init(ref _err, EVRApplicationType.VRApplication_Overlay);
                     nextInit = DateTime.UtcNow.AddSeconds(5);
                     if (system == null)
                     {
                         continue;
                     }
                     active = true;
                 }
                 while (system.PollNextEvent(ref e, (uint)Marshal.SizeOf(e)))
                 {
                     var type = (EVREventType)e.eventType;
                     if (type == EVREventType.VREvent_Quit)
                     {
                         active = false;
                         OpenVR.Shutdown();
                         nextInit = DateTime.UtcNow.AddSeconds(10);
                         system   = null;
                         break;
                     }
                 }
                 if (system != null)
                 {
                     if (DateTime.UtcNow.CompareTo(nextDeviceUpdate) >= 0)
                     {
                         overlayIndex = OpenVR.k_unTrackedDeviceIndexInvalid;
                         UpdateDevices(system, ref overlayIndex);
                         if (overlayIndex != OpenVR.k_unTrackedDeviceIndexInvalid)
                         {
                             nextOverlay = DateTime.UtcNow.AddSeconds(10);
                         }
                         nextDeviceUpdate = DateTime.UtcNow.AddSeconds(0.1);
                     }
                     var overlay = OpenVR.Overlay;
                     if (overlay != null)
                     {
                         var dashboardVisible = overlay.IsDashboardVisible();
                         var err = ProcessDashboard(overlay, ref dashboardHandle, dashboardVisible);
                         if (err != EVROverlayError.None &&
                             dashboardHandle != 0)
                         {
                             overlay.DestroyOverlay(dashboardHandle);
                             dashboardHandle = 0;
                         }
                         err = ProcessOverlay1(overlay, ref overlayHandle1, ref overlayVisible1, dashboardVisible, overlayIndex, nextOverlay);
                         if (err != EVROverlayError.None &&
                             overlayHandle1 != 0)
                         {
                             overlay.DestroyOverlay(overlayHandle1);
                             overlayHandle1 = 0;
                         }
                         err = ProcessOverlay2(overlay, ref overlayHandle2, ref overlayVisible2, dashboardVisible);
                         if (err != EVROverlayError.None &&
                             overlayHandle2 != 0)
                         {
                             overlay.DestroyOverlay(overlayHandle2);
                             overlayHandle2 = 0;
                         }
                     }
                 }
             }
             else if (active)
             {
                 active = false;
                 OpenVR.Shutdown();
                 m_Lock.EnterWriteLock();
                 try
                 {
                     m_Devices.Clear();
                 }
                 finally
                 {
                     m_Lock.ExitWriteLock();
                 }
             }
         }
     })
     {
         IsBackground = true
     };
     m_Thread.Start();
 }
示例#28
0
        public bool init()
        {
            // Set up HMD
            EVRInitError eError = EVRInitError.None;

            mHMD = OpenVR.Init(ref eError, EVRApplicationType.VRApplication_Scene);

            if (eError == EVRInitError.None)
            {
                Rhino.RhinoApp.WriteLine("Booted VR System");
                renderPoseArray = new TrackedDevicePose_t[Valve.VR.OpenVR.k_unMaxTrackedDeviceCount];
                gamePoseArray   = new TrackedDevicePose_t[Valve.VR.OpenVR.k_unMaxTrackedDeviceCount];
            }
            else
            {
                Rhino.RhinoApp.WriteLine("Failed to boot");
                mTitleBase = "SparrowHawk (No VR Detected)";
            }

            // // THIS IS FOR UNCLIPPED
            // Width = 864;
            // Height = 820;

            // THIS IS FOR CLIPPED RECTANGLE
            Width  = 691;
            Height = 692;

            // Window Setup Info
            mStrDriver  = UtilOld.GetTrackedDeviceString(ref mHMD, OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_TrackingSystemName_String);
            mStrDisplay = UtilOld.GetTrackedDeviceString(ref mHMD, OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_SerialNumber_String);
            mTitleBase  = "SparrowHawk - " + mStrDriver + " " + mStrDisplay;
            Title       = mTitleBase;
            MakeCurrent();
            setupScene();


            if (eError == EVRInitError.None)
            {
                mRenderer = new VrRenderer(ref mHMD, ref mScene, mRenderWidth, mRenderHeight);
            }
            else
            {
                mRenderer = new VrRenderer(ref mHMD, ref mScene, mRenderWidth, mRenderHeight);
            }

            //use other 8 points for calibrartion
            robotCallibrationPointsTest.Add(new Vector3(22, 15, -100) / 1000);
            robotCallibrationPointsTest.Add(new Vector3(-10, 40, -153) / 1000);
            robotCallibrationPointsTest.Add(new Vector3(25, -25, -181) / 1000);

            foreach (Vector3 v in robotCallibrationPointsTest)
            {
                Vector4 v4 = new Vector4(v.X, v.Y, v.Z, 1);
                v4 = mScene.vrToRobot.Inverted() * v4;
                UtilOld.MarkPoint(ref mScene.staticGeometry, new Vector3(v4.X, v4.Y, v4.Z), 1, 1, 1);
            }
            robotCallibrationPointsTest.Clear();

            //set default matrix
            if (mRenderer.ovrvision_controller != null)
            {
                mRenderer.ovrvision_controller.setDefaultMatrixHC();
            }

            //detecting whether users in control or left
            Rhino.DocObjects.ObjectAttributes attr = new Rhino.DocObjects.ObjectAttributes();
            attr.Name = "user:out";
            Point3d userP = new Point3d(0, 0, 0);

            uGuid = mScene.rhinoDoc.Objects.AddPoint(userP, attr);

            //testing - rotate rhino object as well

            /*
             * Transform transM = new Transform();
             * for (int row = 0; row < 4; row++)
             * {
             *  for (int col = 0; col < 4; col++)
             *  {
             *      transM[row, col] = mScene.platformRotation[row, col];
             *  }
             * }
             * Rhino.DocObjects.ObjectEnumeratorSettings settings = new Rhino.DocObjects.ObjectEnumeratorSettings();
             * settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.Brep;
             * foreach (Rhino.DocObjects.RhinoObject rhObj in mScene.rhinoDoc.Objects.GetObjectList(settings))
             * {
             *  mDoc.Objects.Transform(rhObj.Id, transM, true);
             * }
             * mScene.rhinoDoc.Views.Redraw();
             */

            //testing visualize printStroke
            printStroke   = new Geometry.RobotPrintStroke(ref mScene);
            printStroke_m = new Material.SingleColorMaterial(1, 1, 0, 1.0f);

            return(eError == EVRInitError.None);
        }
示例#29
0
        void KeepAlive()
        {
            KeepAliveCounter++;

            if (StopRequested)
            {
                Stop();
                return;
            }

            if (VRSys == null)
            {
                if (KeepAliveCounter % InitializationDivider != 0) // do not attempt initialization on every loop.
                {
                    return;
                }

                // ***** INITIALIZATION ******

                //if (!OpenVR.IsHmdPresent()) // Note that this also leaks memory

                // To avoid a memory leak, check that SteamVR is running before trying to Initialize
                if (System.Diagnostics.Process.GetProcessesByName(Config.SteamVRProcessName).Any())
                {
                    if (InitAttemptCount >= InitAttemptLimit)
                    {
                        Stop(true); // no point to keep looping and eating memory forever
                    }

                    InitAttemptCount++;
                    OpenVRConnStatus = OpenVRConnectionStatus.Initializing;
                    // do not carelessly call OpenVR.Init(), it will leak memory
                    VRSys = OpenVR.Init(ref LastOpenVRError, EVRApplicationType.VRApplication_Background);
                    if (LastOpenVRError != EVRInitError.None || VRSys == null)
                    {
                        if (LastOpenVRError == EVRInitError.Init_HmdNotFound || LastOpenVRError == EVRInitError.Init_HmdNotFoundPresenceFailed)
                        {
                            OpenVRConnStatus = OpenVRConnectionStatus.NoHMD;
                            Thread.Sleep(SleepTimeAfterQuit);
                        }
                        return;
                    }

                    bool hmdFound = false;
                    // check devices and find HMD index (but I suppose it's always 0) - Documentation is vague.
                    // For example, what's the purpose of OpenVR.k_unTrackedDeviceIndex_Hmd? What about multiple HMDs...
                    for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
                    {
                        if (VRSys.IsTrackedDeviceConnected(i))
                        {
                            ETrackedDeviceClass c = VRSys.GetTrackedDeviceClass(i);
                            if (c == ETrackedDeviceClass.HMD)
                            {
                                HmdIndex = i;
                                hmdFound = true;
                                break;
                            }
                        }
                    }

                    if (!hmdFound‬)
                    {
                        EndCurrentSession();
                        OpenVRConnStatus = OpenVRConnectionStatus.NoHMD;
                        Thread.Sleep(SleepTimeAfterQuit);

                        return;
                    }

                    PoseArray = new TrackedDevicePose_t[HmdIndex + 1];
                    for (int i = 0; i < PoseArray.Length; i++)
                    {
                        PoseArray[i] = new TrackedDevicePose_t();
                    }

                    if (SteamVRWasOffBefore)
                    {
                        // Wait a bit more before reporting OK and allowing hmd queries when SteamVR is started AFTER CG.
                        // The initial yaw values from the API sometimes threw the counter off by one half-turn.
                        // Maybe there's a small window at the beginning when the headset readings are not stable...
                        // This is very hard to reproduce/test as it happens so rarely. Shooting in the dark here.
                        Thread.Sleep(3000);
                        SteamVRWasOffBefore = false;
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }

                    OpenVRConnStatus = OpenVRConnectionStatus.AllOK;
                }
                else
                {
                    SteamVRWasOffBefore = true;
                    OpenVRConnStatus    = OpenVRConnectionStatus.NoSteamVR;
                }
            }
            else // VRSys != null (connection has been initialized)
            {
                // Check quit request
                VRSys.PollNextEvent(ref NextVREvent, (uint)System.Runtime.InteropServices.Marshal.SizeOf(NextVREvent));
                // this doesn't always work... I suppose the quit event can fly by when the poll rate is relatively low
                // It seems that SteamVR kills the VR processes that don't get Quit event with PollNextEvent().
                if (NextVREvent.eventType == (uint)EVREventType.VREvent_Quit)
                {
                    OpenVRConnStatus = OpenVRConnectionStatus.SteamVRQuit; // to immediately prevent native methods from being called
                    EndCurrentSession();
                    OpenVRConnStatus = OpenVRConnectionStatus.SteamVRQuit; // again to get correct status (changed in EndCurrentSession())
                    // a good sleep before starting to poll steamvr -process again
                    Thread.Sleep(SleepTimeAfterQuit);
                }
                else
                {
                    bool interaction = (VRSys.GetTrackedDeviceActivityLevel(HmdIndex) == EDeviceActivityLevel.k_EDeviceActivityLevel_UserInteraction);
                    if (interaction == HMDUserInteraction_previousReading)
                    {
                        HMDUserInteractionCounter++;
                    }
                    else
                    {
                        HMDUserInteractionCounter = 0;
                    }

                    HMDUserInteraction_previousReading = interaction;

                    // some buffer to filter out false flags (and conveniently some delay for notifications)
                    // ... although false flags are not really possible the way OpenVR currently works
                    if (HMDUserInteractionCounter > HMDUserInteractionDivider)
                    {
                        if (HMDUserInteraction_buffered != interaction)
                        {
                            HMDUserInteraction_buffered = interaction;

                            if (interaction)
                            {
                                Worker.ReportProgress(1, null);
                            }
                            else
                            {
                                Worker.ReportProgress(2, null);
                            }
                        }
                        HMDUserInteractionCounter = 0;
                    }
                }
            }
        }
示例#30
0
        private void setup()
        {
            //init VR System and check for errors
            var error = EVRInitError.None;

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

            if ((int)error != (int)EVRInitError.None)
            {
                log("KerbalVrPlugin started.");
            }
            else
            {
                err(error.ToString());
            }

            //rendervalues #########################################################
            // Setup render values
            uint w = 0, h = 0;

            vrSystem.GetRecommendedRenderTargetSize(ref w, ref h);
            float sceneWidth  = (float)w;
            float sceneHeight = (float)h;

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

            vrSystem.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;

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

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

            //Setup rendertextures
            hmdLeftEyeTexture             = new Texture_t();
            hmdLeftEyeTexture.eColorSpace = EColorSpace.Auto;

            hmdRightEyeTexture             = new Texture_t();
            hmdRightEyeTexture.eColorSpace = EColorSpace.Auto;

            //select Texture Type depending on RenderAPI (Currently only DirectX11 is tested)
            switch (SystemInfo.graphicsDeviceType)
            {
            case UnityEngine.Rendering.GraphicsDeviceType.OpenGL2:
                log("OpenGL2");
                hmdLeftEyeTexture.eType  = ETextureType.OpenGL;
                hmdRightEyeTexture.eType = ETextureType.OpenGL;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore:
                log("OpenCore");
                hmdLeftEyeTexture.eType  = ETextureType.OpenGL;
                hmdRightEyeTexture.eType = ETextureType.OpenGL;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2:
                log("OpenGLES2");
                hmdLeftEyeTexture.eType  = ETextureType.OpenGL;
                hmdRightEyeTexture.eType = ETextureType.OpenGL;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3:
                log("OpenGLES3");
                hmdLeftEyeTexture.eType  = ETextureType.OpenGL;
                hmdRightEyeTexture.eType = ETextureType.OpenGL;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D9:
                log("Direct3D9");
                warn("DirectX 9 mode not Supported! There be Dragons!");
                hmdLeftEyeTexture.eType  = ETextureType.DirectX;
                hmdRightEyeTexture.eType = ETextureType.DirectX;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D11:
                log("Direct3D11");
                hmdLeftEyeTexture.eType  = ETextureType.DirectX;
                hmdRightEyeTexture.eType = ETextureType.DirectX;
                break;

            case UnityEngine.Rendering.GraphicsDeviceType.Direct3D12:
                log("Direct3D12");
                warn("DirectX 12 mode not implemented! There be Dragons!");
                hmdLeftEyeTexture.eType  = ETextureType.DirectX12;
                hmdRightEyeTexture.eType = ETextureType.DirectX12;
                break;

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

            vrCompositor = OpenVR.Compositor;

            if (!vrCompositor.CanRenderScene())
            {
                err("can not render scene");
            }
        }