Example #1
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;
        oldshow = !show;

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

        //JSON読み込み
        Debug.Log(Tag + "Load JSON");
        loadJSON();

        InstanceKeyText.text = "";
        //複数起動用キー
        if (Environment.GetCommandLineArgs().Length >= 3)
        {
            Debug.Log(Environment.GetCommandLineArgs()[1]);
            Debug.Log(Environment.GetCommandLineArgs()[2]);

            //引数に合わせて一時的にKeyを変更する
            if (Environment.GetCommandLineArgs()[1] == "overlaykey")
            {
                config.OverlayKeyName      = Environment.GetCommandLineArgs()[2];
                config.OverlayFriendlyName = Environment.GetCommandLineArgs()[2];

                //サブインスタンス表示
                InstanceKeyText.text = config.OverlayKeyName;
            }
        }

        //表示用
        OverlayKeyName      = config.OverlayKeyName;
        OverlayFriendlyName = config.OverlayFriendlyName;


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

            //エラーを告知し5秒後に終了
            DOVirtual.DelayedCall(5f, () => {
                ApplicationQuit();
            });

            ProcessError();
            return;
        }

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

            //エラーを告知し5秒後に終了
            DOVirtual.DelayedCall(5f, () => {
                ApplicationQuit();
            });

            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 + "初期化完了しました");
    }
 public void Close()
 {
     openVR = null;
     OpenVR.Shutdown();
 }
Example #3
0
 private static void ShutdownSystems()
 {
     OpenVR.Shutdown();
 }
 private void OnDestroy()
 {
     OpenVR.Shutdown();
 }
Example #5
0
    private static void ShutdownSystems()
    {
#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
        OpenVR.Shutdown();
#endif
    }
Example #6
0
 protected override void Terminate()
 {
     base.Terminate();
     OpenVR.Shutdown();
 }
Example #7
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     OpenVR.Shutdown();
 }
Example #8
0
        /// <summary>
        /// Checks if it can connect to OpenVR.
        /// </summary>
        /// <returns></returns>
        private bool AttemptOpenVRConnection(ref CVRSystem system)
        {
            system = null;

            EVRInitError eie = new EVRInitError();

            try
            {
                system = OpenVR.Init(ref eie, EVRApplicationType.VRApplication_Background);
            }
            catch (Exception ex)
            {
                system = null;
                //MessageBox.Show("Err 1: " + ex.Message);
            }

            if (eie == EVRInitError.Init_NoServerForBackgroundApp)
            {
                system = null;
                return(true);
            }
            if (system == null)
            {
                return(false);
            }

            this._useLegacyInput = true;

            EVRApplicationError appError = OpenVR.Applications.AddApplicationManifest(Path.GetFullPath("./manifest/app.vrmanifest"), false);

            if (appError != EVRApplicationError.None)
            {
                return(true); //Will use legacy input
            }

            EVRInputError ioError = OpenVR.Input.SetActionManifestPath(Path.GetFullPath("./manifest/actions.json"));

            if (ioError != EVRInputError.None)
            {
                return(true); //Will use legacy input
            }

            if (!LoadAction("/actions/default/in/reset_viewport", ref this.actionResetViewport))
            {
                return(true); //Will use legacy input
            }
            if (!LoadAction("/actions/default/in/reset_viewport_leftgrip", ref this.actionResetViewportLeftGrip))
            {
                return(true); //Will use legacy input
            }
            if (!LoadAction("/actions/default/in/reset_viewport_rightgrip", ref this.actionResetViewportRightGrip))
            {
                return(true); //Will use legacy input
            }

            if (OpenVR.Input.GetActionSetHandle("/actions/default", ref this.actionHandle) != EVRInputError.None)
            {
                return(true);             //Will use legacy input
            }
            this._useLegacyInput = false; //Actions loaded successfully, we can use the modern input.

            return(true);
        }
Example #9
0
        private async void UninstallButton(object sender, RoutedEventArgs e)
        {
            string driverPath_rel = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\..\vmt";
            string driverPath     = System.IO.Path.GetFullPath(driverPath_rel);

            if (installPath == "")
            {
                //インストールパスが受信できていない場合少し待つ
                await Task.Delay(2000);
            }

            if (installPath != "")
            {
                //場所がわかっている
                var res = MessageBox.Show("Uninstall VMT Driver?\nVMTドライバをアンインストールしますか?\n\n" + installPath, title, MessageBoxButton.OKCancel, MessageBoxImage.Question);
                if (res != MessageBoxResult.OK)
                {
                    return;
                }
                //現在のフォルダパスの代わりに、受信したパスでアンインストールを試す
                driverPath = installPath;
            }
            else
            {
                //場所不明だがとりあえず現在の場所としてアンインストールしようとするか確認する
                var res = MessageBox.Show("Manager couldn't communication to VMT Driver.\nOther VMT Driver version maybe installed.\nIn many cases, this driver located on different path.\nmanager can not uninstallation these.\nIf you want to remove currently installed VMT driver, press cancel and please use manager of drivers itself.\n\nIf you want to try uninstallation anyway, press OK. (it will fail in many cases.)\n\nVMTドライバと通信できませんでした。\n違うバージョンのVMTドライバが入っている可能性があります。\n多くの場合これは別のパスにあります。\n本Managerではアンインストールできません。\nアンインストールしたい場合は、キャンセルを押し、そのVMTドライバに付属のManagerを使用してください\n\nOKを押すと、とにかくアンインストールを試します。(多くの場合失敗します。)", title, MessageBoxButton.OKCancel, MessageBoxImage.Error);
                if (res != MessageBoxResult.OK)
                {
                    return;
                }
            }

            try
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.WorkingDirectory = OpenVR.RuntimePath() + @"\bin\win64";
                process.StartInfo.FileName         = OpenVR.RuntimePath() + @"\bin\win64\vrpathreg.exe";
                process.StartInfo.Arguments        = "removedriver \"" + driverPath + "\"";
                process.StartInfo.UseShellExecute  = false;
                process.Start();
                process.WaitForExit();

                if (File.Exists(driverPath + @"\setting.json"))
                {
                    var res = MessageBox.Show("Do you want to remove setting.json?(Recommended: Yes)\nSetting.jsonを消去しますか?(推奨: はい)\n\n" + installPath + @"\setting.json", title, MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (res != MessageBoxResult.Yes)
                    {
                        MessageBox.Show("OK (ExitCode=" + process.ExitCode + ")\nPlease restart SteamVR.", title);
                        return;
                    }
                    File.Delete(driverPath + @"\setting.json");
                    MessageBox.Show("OK and remove setting.json(ExitCode=" + process.ExitCode + ")\nPlease restart SteamVR.", title);
                    return;
                }
                else
                {
                    MessageBox.Show("OK (ExitCode=" + process.ExitCode + ")\nPlease restart SteamVR.", title);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, title);
                Close();
                return;
            }
        }
Example #10
0
 public static void ShutDownOpenVR()
 {
     OpenVR.Shutdown();
 }
Example #11
0
        private void InstallButton(object sender, RoutedEventArgs e)
        {
            if (DriverVersion.Text != " - ")
            {
                //MessageBox.Show("Please uninstall VMT before install.\nインストールを続ける前に、VMTをアンインストールしてください", title, MessageBoxButton.OK, MessageBoxImage.Error);
                TopWarningMessage("Please uninstall VMT before install.\nインストールを続ける前に、VMTをアンインストールしてください", true);
                return;
            }

            try
            {
                string driverPath_rel = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\..\vmt";
                string driverPath     = System.IO.Path.GetFullPath(driverPath_rel);
                Console.WriteLine(OpenVR.RuntimePath() + @"\bin\win64");
                Console.WriteLine(driverPath);

                if (driverPath.Length > 100)
                {
                    MessageBox.Show("Path length over 100. it couldn't install.\nパスの長さが100を超えています。インストールできません。\n\n" + driverPath, title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (driverPath.Contains("Program Files"))
                {
                    MessageBox.Show("Path contains \"Program Files\". it couldn't install.\nパスに\"Program Files\"が入っています。インストールできません。\n\n" + driverPath, title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (driverPath.Contains(" "))
                {
                    MessageBox.Show("Path contains space. it couldn't install.\nパスにスペースが入っています。インストールできません。\n\n" + driverPath, title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (!File.Exists(driverPath + @"\bin\win64\driver_vmt.dll"))
                {
                    MessageBox.Show("driver_vmt.dll not found. Do not break apart files. it couldn't install.\ndriver_vmt.dllが見つかりませんでした。ファイル構成をバラバラにしないでください。。インストールできません。\n\n" + driverPath, title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                Encoding enc = Encoding.GetEncoding("us-ascii", new EncoderExceptionFallback(), new DecoderExceptionFallback());
                try
                {
                    enc.GetBytes(driverPath);
                }
                catch (EncoderFallbackException) {
                    MessageBox.Show("Path contains non-ascii (Japanese, Chinese, emoji, or other). it couldn't install.\nパスに非ASCII文字(日本語、中国語、絵文字、その他)が入っています。インストールできません。\n\n" + driverPath, title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.WorkingDirectory = OpenVR.RuntimePath() + @"\bin\win64";
                process.StartInfo.FileName         = OpenVR.RuntimePath() + @"\bin\win64\vrpathreg.exe";
                process.StartInfo.Arguments        = "adddriver \"" + driverPath + "\"";
                process.StartInfo.UseShellExecute  = false;
                process.Start();
                process.WaitForExit();

                MessageBox.Show("OK (ExitCode=" + process.ExitCode + ")\nPlease restart SteamVR.", title);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, title);
                Close();
                return;
            }
        }
 private void OnDisable()
 {
     OpenVR.Shutdown();
 }
    public static VRInitException Make(EVRInitError errorCode)
    {
        string message = OpenVR.GetStringForHmdError(errorCode);

        return(new VRInitException(message, errorCode));
    }
Example #14
0
        public override void Init()
        {
            base.Init();

            // make sure OpenVR is init right away
            EVRInitError e = EVRInitError.None;

            system = OpenVR.System;
            if (system == null)
            {
                system = OpenVR.Init(ref e);
            }
            Debug.Log("OpenVR version: " + system.GetRuntimeVersion());

            // init input system
            input = OpenVR.Input;
            string actionsPath;

            if (XRInput.singleton.steamSDK_InUse)
            {
                actionsPath = Path.Combine(Application.dataPath, "StreamingAssets", "SteamVR", "actions.json");
            }
            else
            {
                actionsPath = Path.Combine(Application.dataPath, "StreamingAssets", "OpenVR", "vrstudios_actions.json");
            }
            actionsPath = actionsPath.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
            Debug.Log($"Loading OpenVR Input actions: '{actionsPath}'");
            var error = input.SetActionManifestPath(actionsPath);

            if (error != EVRInputError.None)
            {
                Debug.LogError("Failed: 'SetActionManifestPath': " + error.ToString());
                return;
            }

            // get hands
            GetInputSourceHandle("/user/hand/right", ref viveSource_RightHand);
            GetInputSourceHandle("/user/hand/left", ref viveSource_LeftHand);

            // get action set
            actionSets = new VRActiveActionSet_t[1];
            if (!GetActionSetHandle("/actions/vrstudios", ref viveActionSetHandle))
            {
                return;
            }
            actionSets[0].ulActionSet = viveActionSetHandle;

            // get object actions (touch)
            GetActionHandle("/actions/vrstudios/in/triggertouch", ref viveAction_TriggerTouch);
            GetActionHandle("/actions/vrstudios/in/griptouch", ref viveAction_GripTouch);
            GetActionHandle("/actions/vrstudios/in/menutouch", ref viveAction_MenuTouch);
            GetActionHandle("/actions/vrstudios/in/touch1", ref viveAction_Touch1);
            GetActionHandle("/actions/vrstudios/in/touch2", ref viveAction_Touch2);
            GetActionHandle("/actions/vrstudios/in/joystick1_touch", ref viveAction_Joystick1_Touch);

            // get object actions (buttons)
            GetActionHandle("/actions/vrstudios/in/triggerbutton", ref viveAction_TriggerButton);
            GetActionHandle("/actions/vrstudios/in/gripbutton", ref viveAction_GripButton);
            GetActionHandle("/actions/vrstudios/in/menubutton", ref viveAction_MenuButton);
            GetActionHandle("/actions/vrstudios/in/button1", ref viveAction_Button1);
            GetActionHandle("/actions/vrstudios/in/button2", ref viveAction_Button2);
            GetActionHandle("/actions/vrstudios/in/touchpad1_button", ref viveAction_Touchpad1_Button);
            GetActionHandle("/actions/vrstudios/in/joystick1_button", ref viveAction_Joystick1_Button);

            // get object actions (grips)
            GetActionHandle("/actions/vrstudios/in/grip", ref viveAction_Grip);

            // get object actions (triggers)
            GetActionHandle("/actions/vrstudios/in/trigger", ref viveAction_Trigger);

            // get object actions (touchpads)
            GetActionHandle("/actions/vrstudios/in/touchpad1", ref viveAction_Touchpad1);

            // get object actions (joysticks)
            GetActionHandle("/actions/vrstudios/in/joystick1", ref viveAction_Joystick1);

            // rumble
            GetActionHandle("/actions/vrstudios/out/haptic_right", ref viveAction_Rumble_RightHand);
            GetActionHandle("/actions/vrstudios/out/haptic_left", ref viveAction_Rumble_LeftHand);

            // finish
            isInit = true;
        }
    private SteamVR(System.IntPtr pHmd, System.IntPtr pCompositor, System.IntPtr pOverlay)
    {
        hmd = new CVRSystem(pHmd);
        Debug.Log("Connected to " + hmd_TrackingSystemName + ":" + hmd_SerialNumber);

        compositor = new CVRCompositor(pCompositor);
        overlay    = new CVROverlay(pOverlay);

        var device = new UnityGraphicsDevice();

        GetUnityGraphicsDevice(ref device);
        switch (device.type)
        {
        case GfxDeviceRenderer.kGfxRendererD3D11:
            compositor.SetGraphicsDevice(Compositor_DeviceType.D3D11, device.ptr);
            break;

        case GfxDeviceRenderer.kGfxRendererOpenGL:
            compositor.SetGraphicsDevice(Compositor_DeviceType.OpenGL, device.ptr);
            break;

        default:
            throw new System.Exception("Unsupported device type.");
        }

        var capacity = compositor.GetLastError(null, 0);

        if (capacity > 1)
        {
            var result = new System.Text.StringBuilder((int)capacity);
            compositor.GetLastError(result, capacity);
            Debug.Log("Compositor - " + result);
        }

        // Register for a callback if our graphics device goes away, so we can properly clean up.
        var resetDelegate = new UnityResetDelegate(SteamVR.SafeDispose);

        callbackHandle = GCHandle.Alloc(resetDelegate);
        SetUnityResetCallback(Marshal.GetFunctionPointerForDelegate(resetDelegate));

        // Hook up the render thread present event just in case we wind up needing to use this.
        var error = HmdError.None;

        SetUnityRenderCallback(OpenVR.GetGenericInterface(IVRHmdDistortPresent_Version, ref error));

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

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

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

        hmd.GetProjectionRaw(Hmd_Eye.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;

        hmd.GetProjectionRaw(Hmd_Eye.Eye_Right, ref r_left, ref r_right, ref r_top, ref r_bottom);

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

        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);

        aspect      = tanHalfFov.x / tanHalfFov.y;
        fieldOfView = 2.0f * Mathf.Atan(tanHalfFov.y) * Mathf.Rad2Deg;

        eyes = new SteamVR_Utils.RigidTransform[] {
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Left)),
            new SteamVR_Utils.RigidTransform(hmd.GetEyeToHeadTransform(Hmd_Eye.Eye_Right))
        };

        SteamVR_Utils.Event.Listen("initializing", OnInitializing);
        SteamVR_Utils.Event.Listen("calibrating", OnCalibrating);
        SteamVR_Utils.Event.Listen("out_of_range", OnOutOfRange);
        SteamVR_Utils.Event.Listen("device_connected", OnDeviceConnected);
        SteamVR_Utils.Event.Listen("new_poses", OnNewPoses);
    }