DemoInputManager.cs 18 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
//-----------------------------------------------------------------------
// <copyright file="DemoInputManager.cs" company="Google Inc.">
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

#if UNITY_ANDROID && !UNITY_EDITOR
#define RUNNING_ON_ANDROID_DEVICE
#endif  // UNITY_ANDROID && !UNITY_EDITOR

namespace GoogleVR.Demos
{
    using System;
    using UnityEngine;
    using UnityEngine.UI;

#if UNITY_2017_2_OR_NEWER
    using UnityEngine.XR;
#else // UNITY_2017_2_OR_NEWER
    using XRSettings = UnityEngine.VR.VRSettings;
#endif  // UNITY_2017_2_OR_NEWER

    /// <summary>
    /// Manages input controllers in Daydream or triggers in Cardboard in Demo scenes.
    /// </summary>
    public class DemoInputManager : MonoBehaviour
    {
        /// <summary>The name of the **controller main** property.</summary>
        public const string CONTROLLER_MAIN_PROP_NAME = "controllerMain";

        /// <summary>The name of the **controller pointer** property.</summary>
        public const string CONTROLLER_POINTER_PROP_NAME = "controllerPointers";

        /// <summary>The name of the **reticle pointer** property.</summary>
        public const string RETICLE_POINTER_PROP_NAME = "reticlePointer";

        /// <summary>The controller main.</summary>
        [Tooltip("Reference to GvrControllerMain")]
        public GameObject controllerMain;

        /// <summary>The controller pointers.</summary>
        [Tooltip("Reference to GvrControllerPointers")]
        public GameObject[] controllerPointers;

        /// <summary>The reticle pointer.</summary>
        [Tooltip("Reference to GvrReticlePointer")]
        public GameObject reticlePointer;

        /// <summary>The message canvas.</summary>
        public GameObject messageCanvas;

        /// <summary>The message text.</summary>
        public Text messageText;

#if !RUNNING_ON_ANDROID_DEVICE
        /// <summary>The Gvr Platforms.</summary>
        public enum EmulatedPlatformType
        {
            Daydream,
            Cardboard
        }

        /// <summary>The type of the GVR emulated platform.</summary>
        [Tooltip("Emulated GVR Platform")]
        public EmulatedPlatformType gvrEmulatedPlatformType = EmulatedPlatformType.Daydream;

        /// <summary>The name of the **emulated platform** property.</summary>
        public static string EMULATED_PLATFORM_PROP_NAME = "gvrEmulatedPlatformType";
#endif // !RUNNING_ON_ANDROID_DEVICE

        private const string MESSAGE_CANVAS_NAME = "MessageCanvas";
        private const string MESSAGE_TEXT_NAME = "MessageText";
        private const string LASER_GAMEOBJECT_NAME = "Laser";
        private const string CONTROLLER_CONNECTING_MESSAGE = "Daydream controller connecting...";
        private const string CONTROLLER_DISCONNECTED_MESSAGE = "Daydream controller not connected";
        private const string CONTROLLER_SCANNING_MESSAGE = "Scanning for Daydream controller...";
        private const string NON_GVR_PLATFORM =
            "Please select a supported Google VR platform via "
            + "'Build Settings > Android | iOS > Switch Platform'\n";

        private const string VR_SUPPORT_NOT_CHECKED =
        "Please make sure 'Player Settings > Virtual Reality Supported' is checked\n";

        private const string EMPTY_VR_SDK_WARNING_MESSAGE =
        "Please add 'Daydream' or 'Cardboard' under 'Player Settings > Virtual Reality SDKs'\n";

        // Java class, method, and field constants.
        private const int ANDROID_MIN_DAYDREAM_API = 24;
        private const string FIELD_SDK_INT = "SDK_INT";
        private const string PACKAGE_BUILD_VERSION = "android.os.Build$VERSION";
        private const string PACKAGE_DAYDREAM_API_CLASS = "com.google.vr.ndk.base.DaydreamApi";
        private const string METHOD_IS_DAYDREAM_READY = "isDaydreamReadyPlatform";

        // Buttons that can trigger pointer switching.
        private const GvrControllerButton POINTER_BUTTON_MASK =
                GvrControllerButton.App |
                GvrControllerButton.TouchPadButton |
                GvrControllerButton.Trigger |
                GvrControllerButton.Grip;

        private static readonly GvrControllerHand[] ALL_HANDS =
        {
            GvrControllerHand.Right,
            GvrControllerHand.Left,
        };

#if RUNNING_ON_ANDROID_DEVICE
        // Running on an Android device.
        private GvrSettings.ViewerPlatformType viewerPlatform;
#endif // RUNNING_ON_ANDROID_DEVICE

        private bool isDaydream = false;
        private int activeControllerPointer = 0;

        /// <summary>Whether Daydream is enabled in this Unity project's Player Settings.</summary>
        /// <returns>
        /// Returns `true` if Daydream is enabled in Unity Player Settings.  Otherwise, returns
        /// `false`.
        /// </returns>
        public static bool playerSettingsHasDaydream()
        {
            string[] playerSettingsVrSdks = XRSettings.supportedDevices;
            return Array.Exists<string>(playerSettingsVrSdks,
                element => element.Equals(GvrSettings.VR_SDK_DAYDREAM));
        }

        /// <summary>Whether Cardboard is enabled in this Unity project's Player Settings.</summary>
        /// <returns>
        /// Returns `true` if Cardboard is enabled in Unity Player Settings.  Otherwise, returns
        /// `false`.
        /// </returns>
        public static bool playerSettingsHasCardboard()
        {
            string[] playerSettingsVrSdks = XRSettings.supportedDevices;
            return Array.Exists<string>(playerSettingsVrSdks,
                element => element.Equals(GvrSettings.VR_SDK_CARDBOARD));
        }

        /// <summary>Determines whether the Platform is currently Daydream.</summary>
        /// <returns>
        /// Returns `true` if this Platform is currently daydream.  Otherwise, returns `false`.
        /// </returns>
        public bool IsCurrentlyDaydream()
        {
            return isDaydream;
        }

#if RUNNING_ON_ANDROID_DEVICE
        // Running on an Android device.
        private static bool IsDeviceDaydreamReady()
        {
            // Check API level.
            using (var version = new AndroidJavaClass(PACKAGE_BUILD_VERSION))
            {
                if (version.GetStatic<int>(FIELD_SDK_INT) < ANDROID_MIN_DAYDREAM_API)
                {
                    return false;
                }
            }

            // API level > 24, check whether the device is Daydream-ready.
            AndroidJavaObject androidActivity = null;
            try
            {
                androidActivity = GvrActivityHelper.GetActivity();
            }
            catch (AndroidJavaException e)
            {
                Debug.LogError("Exception while getting the Android Activity: " + e);
                return false;
            }

            AndroidJavaClass daydreamApiClass = new AndroidJavaClass(PACKAGE_DAYDREAM_API_CLASS);
            if (daydreamApiClass == null || androidActivity == null)
            {
                return false;
            }

            return daydreamApiClass.CallStatic<bool>(METHOD_IS_DAYDREAM_READY, androidActivity);
        }
#endif  // RUNNING_ON_ANDROID_DEVICE

        private void Start()
        {
            if (messageCanvas == null)
            {
                messageCanvas = transform.Find(MESSAGE_CANVAS_NAME).gameObject;
                if (messageCanvas != null)
                {
                    messageText =
                        messageCanvas.transform.Find(MESSAGE_TEXT_NAME).GetComponent<Text>();
                }
            }

            // Message canvas will be enabled later when there's a message to display.
            messageCanvas.SetActive(false);
#if !RUNNING_ON_ANDROID_DEVICE
            if (playerSettingsHasDaydream() || playerSettingsHasCardboard())
            {
                // The list is populated with valid VR SDK(s), pick the first one.
                gvrEmulatedPlatformType =
                    (XRSettings.supportedDevices[0] == GvrSettings.VR_SDK_DAYDREAM) ?
                        EmulatedPlatformType.Daydream :
                        EmulatedPlatformType.Cardboard;
            }
            isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream);
#else

            // Running on an Android device.
            viewerPlatform = GvrSettings.ViewerPlatform;

            // First loaded device in Player Settings.
            string vrDeviceName = XRSettings.loadedDeviceName;
            if (vrDeviceName != GvrSettings.VR_SDK_CARDBOARD &&
                vrDeviceName != GvrSettings.VR_SDK_DAYDREAM)
            {
                Debug.LogErrorFormat("Loaded device was '{0}', must be one of '{1}' or '{2}'",
                    vrDeviceName, GvrSettings.VR_SDK_DAYDREAM, GvrSettings.VR_SDK_CARDBOARD);
                return;
            }

            // On a non-Daydream ready phone, fall back to Cardboard if it's present in the list of
            // enabled VR SDKs.
            // On a Daydream-ready phone, go into Cardboard mode if it's the currently-paired
            // viewer.
            if ((!IsDeviceDaydreamReady() && playerSettingsHasCardboard()) ||
                (IsDeviceDaydreamReady() && playerSettingsHasCardboard() &&
                    GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Cardboard))
            {
                vrDeviceName = GvrSettings.VR_SDK_CARDBOARD;
            }

            isDaydream = vrDeviceName == GvrSettings.VR_SDK_DAYDREAM;
#endif  // !RUNNING_ON_ANDROID_DEVICE
            SetVRInputMechanism();
        }

        // Runtime switching enabled only in-editor.
        private void Update()
        {
            UpdateStatusMessage();

            // Scan all devices' buttons for button down, and switch the singleton pointer
            // to the controller the user last clicked.
            int newPointer = activeControllerPointer;

            if (controllerPointers.Length > 1 && controllerPointers[1] != null)
            {
                GvrTrackedController trackedController1 =
                    controllerPointers[1].GetComponent<GvrTrackedController>();
                foreach (var hand in ALL_HANDS)
                {
                    GvrControllerInputDevice device = GvrControllerInput.GetDevice(hand);
                    if (device.GetButtonDown(POINTER_BUTTON_MASK))
                    {
                        // Match the button to our own controllerPointers list.
                        if (device == trackedController1.ControllerInputDevice)
                        {
                            newPointer = 1;
                        }
                        else
                        {
                            newPointer = 0;
                        }

                        break;
                    }
                }
            }

            if (newPointer != activeControllerPointer)
            {
                activeControllerPointer = newPointer;
                SetVRInputMechanism();
            }

#if !RUNNING_ON_ANDROID_DEVICE
            UpdateEmulatedPlatformIfPlayerSettingsChanged();
            if ((isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Daydream) ||
                (!isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard))
            {
                return;
            }

            isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream);
            SetVRInputMechanism();
#else
            // Running on an Android device.
            // Viewer type switched at runtime.
            if (!IsDeviceDaydreamReady() || viewerPlatform == GvrSettings.ViewerPlatform)
            {
                return;
            }

            isDaydream = GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Daydream;
            viewerPlatform = GvrSettings.ViewerPlatform;
            SetVRInputMechanism();
#endif  // !RUNNING_ON_ANDROID_DEVICE
        }

#if !RUNNING_ON_ANDROID_DEVICE
        private void UpdateEmulatedPlatformIfPlayerSettingsChanged()
        {
            if (!playerSettingsHasDaydream() && !playerSettingsHasCardboard())
            {
                return;
            }

            // Player Settings > VR SDK list may have changed at runtime. The emulated platform
            // may not have been manually updated if that's the case.
            if (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream &&
                !playerSettingsHasDaydream())
            {
                gvrEmulatedPlatformType = EmulatedPlatformType.Cardboard;
            }
            else if (gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard &&
                     !playerSettingsHasCardboard())
            {
                gvrEmulatedPlatformType = EmulatedPlatformType.Daydream;
            }
        }
#endif  // !RUNNING_ON_ANDROID_DEVICE

        private void UpdateStatusMessage()
        {
            if (messageText == null || messageCanvas == null)
            {
                return;
            }

#if !UNITY_ANDROID && !UNITY_IOS
            messageText.text = NON_GVR_PLATFORM;
            messageCanvas.SetActive(true);
            return;
#else
#if UNITY_EDITOR
            if (!UnityEditor.PlayerSettings.virtualRealitySupported)
            {
                messageText.text = VR_SUPPORT_NOT_CHECKED;
                messageCanvas.SetActive(true);
                return;
            }
#endif  // UNITY_EDITOR

            bool isVrSdkListEmpty = !playerSettingsHasCardboard() && !playerSettingsHasDaydream();
            if (!isDaydream)
            {
                if (messageCanvas.activeSelf)
                {
                    messageText.text = EMPTY_VR_SDK_WARNING_MESSAGE;
                    messageCanvas.SetActive(isVrSdkListEmpty);
                }

                return;
            }

            string vrSdkWarningMessage =
                isVrSdkListEmpty ? EMPTY_VR_SDK_WARNING_MESSAGE : "";
            string controllerMessage = "";
            GvrPointerGraphicRaycaster graphicRaycaster =
                messageCanvas.GetComponent<GvrPointerGraphicRaycaster>();
            GvrControllerInputDevice dominantDevice =
                GvrControllerInput.GetDevice(GvrControllerHand.Dominant);
            GvrConnectionState connectionState = dominantDevice.State;

            // This is an example of how to process the controller's state to display a status
            // message.
            switch (connectionState)
            {
                case GvrConnectionState.Connected:
                    break;
                case GvrConnectionState.Disconnected:
                    controllerMessage = CONTROLLER_DISCONNECTED_MESSAGE;
                    messageText.color = Color.white;
                    break;
                case GvrConnectionState.Scanning:
                    controllerMessage = CONTROLLER_SCANNING_MESSAGE;
                    messageText.color = Color.cyan;
                    break;
                case GvrConnectionState.Connecting:
                    controllerMessage = CONTROLLER_CONNECTING_MESSAGE;
                    messageText.color = Color.yellow;
                    break;
                case GvrConnectionState.Error:
                    controllerMessage = "ERROR: " + dominantDevice.ErrorDetails;
                    messageText.color = Color.red;
                    break;
                default:
                    // Shouldn't happen.
                    Debug.LogError("Invalid controller state: " + connectionState);
                    break;
            }

            messageText.text = string.Format("{0}\n{1}", vrSdkWarningMessage, controllerMessage);
            if (graphicRaycaster != null)
            {
                graphicRaycaster.enabled =
                    !isVrSdkListEmpty || connectionState != GvrConnectionState.Connected;
            }

            messageCanvas.SetActive(isVrSdkListEmpty ||
                                    (connectionState != GvrConnectionState.Connected));
#endif  // !UNITY_ANDROID && !UNITY_IOS
    }

        private void SetVRInputMechanism()
        {
            SetGazeInputActive(!isDaydream);
            SetControllerInputActive(isDaydream);
        }

        private void SetGazeInputActive(bool active)
        {
            if (reticlePointer == null)
            {
                return;
            }

            reticlePointer.SetActive(active);

            // Update the pointer type only if this is currently activated.
            if (!active)
            {
                return;
            }

            GvrReticlePointer pointer =
                reticlePointer.GetComponent<GvrReticlePointer>();
            if (pointer != null)
            {
                GvrPointerInputModule.Pointer = pointer;
            }
        }

        private void SetControllerInputActive(bool active)
        {
            if (controllerMain != null)
            {
                controllerMain.SetActive(active);
            }

            if (controllerPointers == null || controllerPointers.Length <= activeControllerPointer)
            {
                return;
            }

            controllerPointers[activeControllerPointer].SetActive(active);

            // Update the pointer type only if this is currently activated.
            if (!active)
            {
                return;
            }

            GvrLaserPointer pointer =
                controllerPointers[activeControllerPointer].GetComponentInChildren<GvrLaserPointer>(
                    true);
            if (pointer != null)
            {
                GvrPointerInputModule.Pointer = pointer;
            }
        }
    }
}