NRDevice.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using AOT;
  12. using System;
  13. using System.Collections.Generic;
  14. #if UNITY_ANDROID && !UNITY_EDITOR
  15. using System.Runtime.InteropServices;
  16. using System.Threading;
  17. using UnityEngine;
  18. #endif
  19. /// <summary> Manage the HMD device. </summary>
  20. public class NRDevice : SingleTon<NRDevice>
  21. {
  22. /// <summary> Event queue for all listeners interested in OnGlassesStateChanged events. </summary>
  23. public static event GlassesEvent OnGlassesStateChanged;
  24. /// <summary> Event queue for all listeners interested in OnGlassesDisconnect events. </summary>
  25. public static event GlassesDisconnectEvent OnGlassesDisconnect;
  26. /// <summary> Values that represent glasses event types. </summary>
  27. public enum GlassesEventType
  28. {
  29. /// <summary> An enum constant representing the put on option. </summary>
  30. PutOn,
  31. /// <summary> An enum constant representing the put off option. </summary>
  32. PutOff
  33. }
  34. private const float SDK_RELEASE_TIMEOUT = 2f;
  35. private bool m_IsInitialized = false;
  36. private Exception m_InitException = null;
  37. private static NRDeviceSubsystem m_Subsystem;
  38. public static NRDeviceSubsystem Subsystem
  39. {
  40. get
  41. {
  42. if (m_Subsystem == null)
  43. {
  44. string str_match = NRDeviceSubsystemDescriptor.Name;
  45. List<NRDeviceSubsystemDescriptor> descriptors = new List<NRDeviceSubsystemDescriptor>();
  46. NRSubsystemManager.GetSubsystemDescriptors(descriptors);
  47. foreach (var des in descriptors)
  48. {
  49. if (des.id.Equals(str_match))
  50. {
  51. m_Subsystem = des.Create();
  52. }
  53. }
  54. }
  55. return m_Subsystem;
  56. }
  57. }
  58. #if UNITY_ANDROID && !UNITY_EDITOR
  59. private static AndroidJavaObject m_UnityActivity;
  60. #endif
  61. /// <summary> Init HMD device. </summary>
  62. public void Init()
  63. {
  64. // Keep the exception state.
  65. if (m_InitException != null)
  66. {
  67. throw m_InitException;
  68. }
  69. if (m_IsInitialized)
  70. {
  71. return;
  72. }
  73. NRTools.Init();
  74. MainThreadDispather.Initialize();
  75. #if UNITY_ANDROID && !UNITY_EDITOR
  76. // Init before all actions.
  77. AndroidJavaClass cls_UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  78. m_UnityActivity = cls_UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  79. NativeApi.NRSDKInitSetAndroidActivity(m_UnityActivity.GetRawObject());
  80. #endif
  81. try
  82. {
  83. Subsystem.Start();
  84. Subsystem.RegestEvents(OnGlassesWear, OnGlassesDisconnectEvent);
  85. }
  86. catch (Exception e)
  87. {
  88. m_InitException = e;
  89. throw e;
  90. }
  91. m_IsInitialized = true;
  92. }
  93. public void Pause()
  94. {
  95. Subsystem.Pause();
  96. }
  97. public void Resume()
  98. {
  99. Subsystem.Resume();
  100. }
  101. public void Destroy()
  102. {
  103. Subsystem.Stop();
  104. }
  105. private void OnGlassesWear(NRDevice.GlassesEventType eventtype)
  106. {
  107. NRDebugger.Info("[NRDevice] " + (eventtype == GlassesEventType.PutOn ? "Glasses put on" : "Glasses put off"));
  108. OnGlassesStateChanged?.Invoke(eventtype);
  109. NRSessionManager.OnGlassesStateChanged?.Invoke(eventtype);
  110. }
  111. private void OnGlassesDisconnectEvent(GlassesDisconnectReason reason)
  112. {
  113. NRDebugger.Info("[NRDevice] OnGlassesDisconnectEvent:" + reason.ToString());
  114. // If NRSDK release time out in 2 seconds, FoceKill the process.
  115. AsyncTaskExecuter.Instance.RunAction(() =>
  116. {
  117. try
  118. {
  119. OnGlassesDisconnect?.Invoke(reason);
  120. NRSessionManager.OnGlassesDisconnect?.Invoke(reason);
  121. }
  122. catch (Exception e)
  123. {
  124. NRDebugger.Info("[NRDevice] Operate OnGlassesDisconnect event error:" + e.ToString());
  125. throw e;
  126. }
  127. finally
  128. {
  129. bool forceKill = true;
  130. // Some app contains 2D content and 3D content. It may wish to keep process alive after glasses switch mode.
  131. if (reason == GlassesDisconnectReason.NOTIFY_TO_QUIT_APP && !NRSessionManager.Instance.NRSessionBehaviour.SessionConfig.ForceKillWhileGlassSwitchMode)
  132. forceKill = false;
  133. NRDebugger.Info("[NRDevice] OnGlassesDisconnectEvent: forceKill={0}, ForceKillWhileGlassSwitchMode={1}", forceKill, NRSessionManager.Instance.NRSessionBehaviour.SessionConfig.ForceKillWhileGlassSwitchMode);
  134. if (forceKill)
  135. ForceKill(true);
  136. else
  137. Subsystem.ResetStateOnNextResume();
  138. }
  139. }, () =>
  140. {
  141. NRDebugger.Error("[NRDevice] Release sdk timeout, force kill the process!!!");
  142. ForceKill(false);
  143. }, SDK_RELEASE_TIMEOUT);
  144. }
  145. #region Quit
  146. /// <summary> Quit the app. </summary>
  147. public static void QuitApp()
  148. {
  149. NRDebugger.Info("[NRDevice] Start To Quit Application.");
  150. #if UNITY_EDITOR
  151. UnityEditor.EditorApplication.isPlaying = false;
  152. #else
  153. ForceKill();
  154. #endif
  155. }
  156. /// <summary> Force kill the app. Avoid timeout to pause UnityEngine. </summary>
  157. /// <exception cref="Exception"> Thrown when an exception error condition occurs.</exception>
  158. public static void ForceKill(bool needrelease = true)
  159. {
  160. NRDebugger.Info("[NRDevice] ForceKill: release={0}", needrelease);
  161. try
  162. {
  163. ReleaseSDK();
  164. }
  165. catch (Exception e)
  166. {
  167. throw e;
  168. }
  169. finally
  170. {
  171. #if UNITY_ANDROID && !UNITY_EDITOR
  172. AndroidJNI.AttachCurrentThread();
  173. m_UnityActivity?.Call("finish");
  174. AndroidJavaClass processClass = new AndroidJavaClass("android.os.Process");
  175. int myPid = processClass.CallStatic<int>("myPid");
  176. processClass.CallStatic("killProcess", myPid);
  177. #endif
  178. }
  179. }
  180. public static void ReleaseSDK()
  181. {
  182. NRDebugger.Info("[NRDevice] Start to release sdk");
  183. System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
  184. stopwatch.Start();
  185. NRSessionManager.Instance.DestroySession();
  186. NRDebugger.Info("[NRDevice] Release sdk end, cost:{0} ms", stopwatch.ElapsedMilliseconds);
  187. }
  188. #endregion
  189. #if UNITY_ANDROID && !UNITY_EDITOR
  190. private struct NativeApi
  191. {
  192. [DllImport(NativeConstants.NRNativeLibrary)]
  193. public static extern NativeResult NRSDKInitSetAndroidActivity(IntPtr android_activity);
  194. }
  195. #endif
  196. }
  197. }