ARRemoteDevice.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5. using UnityEngine;
  6. using UnityEngine.Events;
  7. using UnityEngine.Networking.PlayerConnection;
  8. using Utils;
  9. // Runs on the remote device. Talks to the Editor.
  10. namespace UnityARInterface
  11. {
  12. public class ARRemoteDevice : MonoBehaviour
  13. {
  14. [SerializeField]
  15. protected Camera m_ARCamera;
  16. private bool m_SendVideo;
  17. private ARInterface.Settings m_CachedSettings;
  18. private ARInterface.PointCloud m_PointCloud;
  19. private ARInterface.CameraImage m_CameraImage;
  20. private bool m_HaveSentCameraParams;
  21. private ARInterface m_ARInterface;
  22. private PlayerConnection m_PlayerConnection;
  23. private int m_EditorId;
  24. public bool isConnected { get { return m_PlayerConnection.isConnected; } }
  25. private Dictionary<Guid, UnityAction<SerializableSubMessage>> m_MessageHandler =
  26. new Dictionary<Guid, UnityAction<SerializableSubMessage>>();
  27. private bool m_BackgroundRendering;
  28. public bool BackgroundRendering
  29. {
  30. get
  31. {
  32. return m_BackgroundRendering;
  33. }
  34. set
  35. {
  36. m_BackgroundRendering = value;
  37. if (m_ARInterface != null){
  38. m_ARInterface.BackgroundRendering = m_BackgroundRendering;
  39. }
  40. }
  41. }
  42. public bool IsRunning
  43. {
  44. get
  45. {
  46. if (m_ARInterface == null)
  47. return false;
  48. return m_ARInterface.IsRunning;
  49. }
  50. }
  51. void Register(Guid guid, UnityAction<SerializableSubMessage> handler)
  52. {
  53. m_MessageHandler.Add(guid, handler);
  54. }
  55. void Start()
  56. {
  57. Debug.Log("Connecting to editor...");
  58. m_EditorId = -1;
  59. m_PlayerConnection = PlayerConnection.instance;
  60. m_PlayerConnection.RegisterConnection(EditorConnectedEventHandler);
  61. m_PlayerConnection.RegisterDisconnection(EditorDisconnectedEventHandler);
  62. m_PlayerConnection.Register(ARMessageIds.fromEditor, FromEditorMessageHandler);
  63. // The PlayerConnection object can only register a single callback
  64. // (this is a bug). To listen to more than one type of message,
  65. // we register a generic one in the PlayerConnection and then
  66. // decode its meaning with these "SubMessageIds".
  67. Register(ARMessageIds.SubMessageIds.startService, StartServiceMessageHandler);
  68. Register(ARMessageIds.SubMessageIds.stopService, StopServiceMessageHandler);
  69. Register(ARMessageIds.SubMessageIds.enableVideo, EnableVideoMessageHandler);
  70. Register(ARMessageIds.SubMessageIds.backgroundRendering, BackgroundRenderingMessageHandler);
  71. }
  72. private void OnDisable()
  73. {
  74. if (m_PlayerConnection != null)
  75. m_PlayerConnection.DisconnectAll();
  76. }
  77. void OnGUI()
  78. {
  79. string message = "";
  80. if (isConnected && !IsRunning)
  81. {
  82. message = "Connected. Waiting for Editor.";
  83. }
  84. else if (!isConnected)
  85. {
  86. message = "Waiting for editor connection...";
  87. }
  88. else
  89. {
  90. return;
  91. }
  92. var rect = new Rect((Screen.width / 2) - 200, (Screen.height / 2), 400, 50);
  93. GUI.Box(rect, message);
  94. }
  95. void StopServiceMessageHandler(SerializableSubMessage message)
  96. {
  97. if (m_ARInterface != null)
  98. StopService();
  99. }
  100. void StopService()
  101. {
  102. StopAllCoroutines();
  103. m_ARInterface.StopService();
  104. ARInterface.planeAdded -= PlaneAddedHandler;
  105. ARInterface.planeUpdated -= PlaneUpdatedHandler;
  106. ARInterface.planeRemoved -= PlaneRemovedHandler;
  107. m_ARInterface = null;
  108. m_HaveSentCameraParams = false;
  109. }
  110. void EnableVideoMessageHandler(SerializableSubMessage message)
  111. {
  112. var requestedVideoState = message.GetDataAs<SerializableEnableVideo>();
  113. m_SendVideo = requestedVideoState.enableVideo;
  114. m_HaveSentCameraParams = false;
  115. }
  116. void BackgroundRenderingMessageHandler(SerializableSubMessage message)
  117. {
  118. var requestedBackgroundRenderingState = message.GetDataAs<SerializableBackgroundRendering>();
  119. BackgroundRendering = requestedBackgroundRenderingState.backgroundRendering;
  120. }
  121. void StartServiceMessageHandler(SerializableSubMessage message)
  122. {
  123. var settings = message.GetDataAs<SerializableARSettings>();
  124. if (settings == null)
  125. return;
  126. if (IsRunning)
  127. {
  128. Debug.LogWarning("Received message to start service while service is already running. Restarting.");
  129. m_ARInterface.StopService();
  130. }
  131. StartService(settings);
  132. }
  133. void FromEditorMessageHandler(MessageEventArgs args)
  134. {
  135. var subMessage = args.data.Deserialize<SerializableSubMessage>();
  136. if (subMessage != null)
  137. {
  138. UnityAction<SerializableSubMessage> handler = null;
  139. if (m_MessageHandler.TryGetValue(subMessage.subMessageId, out handler))
  140. {
  141. handler.Invoke(subMessage);
  142. }
  143. }
  144. }
  145. void StartService(SerializableARSettings serializedSettings)
  146. {
  147. m_CachedSettings = serializedSettings;
  148. StopAllCoroutines();
  149. StartCoroutine(StartServiceRoutine());
  150. }
  151. IEnumerator StartServiceRoutine()
  152. {
  153. var arInterface = ARInterface.GetInterface();
  154. yield return arInterface.StartService(m_CachedSettings);
  155. if (!arInterface.IsRunning)
  156. yield break;
  157. m_ARInterface = arInterface;
  158. m_ARInterface.SetupCamera(m_ARCamera);
  159. m_ARInterface.BackgroundRendering = BackgroundRendering;
  160. ARInterface.planeAdded += PlaneAddedHandler;
  161. ARInterface.planeUpdated += PlaneUpdatedHandler;
  162. ARInterface.planeRemoved += PlaneRemovedHandler;
  163. }
  164. public void PlaneAddedHandler(BoundedPlane plane)
  165. {
  166. SerializableBoundedPlane serializedPlane = plane;
  167. SendToEditor(ARMessageIds.addPlane, serializedPlane);
  168. }
  169. public void PlaneUpdatedHandler(BoundedPlane plane)
  170. {
  171. SerializableBoundedPlane serializedPlane = plane;
  172. SendToEditor(ARMessageIds.updatePlane, serializedPlane);
  173. }
  174. public void PlaneRemovedHandler(BoundedPlane plane)
  175. {
  176. SerializableBoundedPlane serializedPlane = plane;
  177. SendToEditor(ARMessageIds.removePlane, serializedPlane);
  178. }
  179. void EditorConnectedEventHandler(int playerId)
  180. {
  181. m_EditorId = playerId;
  182. }
  183. void EditorDisconnectedEventHandler(int playerId)
  184. {
  185. if (m_EditorId == playerId)
  186. m_EditorId = -1;
  187. DisconnectFromEditor();
  188. if (m_ARInterface != null)
  189. StopService();
  190. }
  191. public void DisconnectFromEditor()
  192. {
  193. #if UNITY_2017_1_OR_NEWER
  194. m_PlayerConnection.DisconnectAll();
  195. #endif
  196. }
  197. public void SendToEditor(System.Guid msgId, byte[] data)
  198. {
  199. if (m_PlayerConnection.isConnected)
  200. m_PlayerConnection.Send(msgId, data);
  201. }
  202. public void SendToEditor(System.Guid msgId, object serializableObject)
  203. {
  204. byte[] arrayToSend = serializableObject.SerializeToByteArray();
  205. SendToEditor(msgId, arrayToSend);
  206. }
  207. void OnEnable()
  208. {
  209. Application.targetFrameRate = 60;
  210. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  211. // See if we are on a camera
  212. if (m_ARCamera == null)
  213. m_ARCamera = GetComponent<Camera>();
  214. // Fallback to main camera
  215. if (m_ARCamera == null)
  216. m_ARCamera = Camera.main;
  217. }
  218. private void Update()
  219. {
  220. if (m_ARInterface == null)
  221. return;
  222. m_ARInterface.Update();
  223. m_ARInterface.UpdateCamera(m_ARCamera);
  224. Pose pose = new Pose();
  225. if (m_ARInterface.TryGetPose(ref pose))
  226. {
  227. m_ARCamera.transform.position = pose.position;
  228. m_ARCamera.transform.rotation = pose.rotation;
  229. }
  230. if (isConnected && IsRunning)
  231. {
  232. var serializedFrame = new SerializableFrame(
  233. m_ARCamera.projectionMatrix,
  234. m_ARCamera.transform.position,
  235. m_ARCamera.transform.rotation,
  236. m_ARInterface.GetDisplayTransform());
  237. SendToEditor(ARMessageIds.frame, serializedFrame);
  238. if (m_CachedSettings.enablePointCloud)
  239. {
  240. if (m_ARInterface.TryGetPointCloud(ref m_PointCloud))
  241. {
  242. var serializedPointCloud = new SerializablePointCloud(m_PointCloud);
  243. SendToEditor(ARMessageIds.pointCloud, serializedPointCloud);
  244. }
  245. }
  246. if (m_CachedSettings.enableLightEstimation)
  247. {
  248. var serializedLightEstimate = (SerializableLightEstimate)m_ARInterface.GetLightEstimate();
  249. SendToEditor(ARMessageIds.lightEstimate, serializedLightEstimate);
  250. }
  251. if (m_SendVideo && m_ARInterface.BackgroundRendering)
  252. {
  253. if (m_ARInterface.TryGetCameraImage(ref m_CameraImage))
  254. {
  255. if (!m_HaveSentCameraParams)
  256. {
  257. var screenCaptureParams = new SerializableScreenCaptureParams(
  258. m_CameraImage.width,
  259. m_CameraImage.height,
  260. (int)TextureFormat.YUY2);
  261. SendToEditor(ARMessageIds.screenCaptureParams, screenCaptureParams);
  262. m_HaveSentCameraParams = true;
  263. }
  264. SendToEditor(ARMessageIds.screenCaptureY, m_CameraImage.y);
  265. SendToEditor(ARMessageIds.screenCaptureUV, m_CameraImage.uv);
  266. }
  267. }
  268. }
  269. }
  270. }
  271. }