ARLocalizer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*===============================================================================
  2. Copyright (C) 2022 Immersal - Part of Hexagon. All Rights Reserved.
  3. This file is part of the Immersal SDK.
  4. The Immersal SDK cannot be copied, distributed, or made available to
  5. third-parties for commercial purposes without written permission of Immersal Ltd.
  6. Contact sdk@immersal.com for licensing requests.
  7. ===============================================================================*/
  8. using UnityEngine;
  9. using System;
  10. using System.Collections.Generic;
  11. using UnityEngine.XR.ARFoundation;
  12. using UnityEngine.XR.ARSubsystems;
  13. using System.Threading.Tasks;
  14. using Immersal.REST;
  15. namespace Immersal.AR
  16. {
  17. public class ARLocalizer : LocalizerBase
  18. {
  19. private static ARLocalizer instance = null;
  20. private bool m_localizationDebugLoggingEnabled = false;
  21. public bool LocalizationDebugLoggingEnabled
  22. {
  23. set => m_localizationDebugLoggingEnabled = value;
  24. get => m_localizationDebugLoggingEnabled;
  25. }
  26. private void LocalizerDebugLog(string message)
  27. {
  28. if (m_localizationDebugLoggingEnabled)
  29. {
  30. Debug.Log("[ARLocalizer]: "+message);
  31. }
  32. }
  33. private void ARSessionStateChanged(ARSessionStateChangedEventArgs args)
  34. {
  35. CheckTrackingState(args.state);
  36. }
  37. private void CheckTrackingState(ARSessionState newState)
  38. {
  39. isTracking = newState == ARSessionState.SessionTracking;
  40. if (!isTracking)
  41. {
  42. foreach (KeyValuePair<Transform, SpaceContainer> item in ARSpace.transformToSpace)
  43. item.Value.filter.InvalidateHistory();
  44. }
  45. }
  46. public static ARLocalizer Instance
  47. {
  48. get
  49. {
  50. #if UNITY_EDITOR
  51. if (instance == null && !Application.isPlaying)
  52. {
  53. instance = UnityEngine.Object.FindObjectOfType<ARLocalizer>();
  54. }
  55. #endif
  56. if (instance == null)
  57. {
  58. Debug.LogError("No ARLocalizer instance found. Ensure one exists in the scene.");
  59. }
  60. return instance;
  61. }
  62. }
  63. void Awake()
  64. {
  65. if (instance == null)
  66. {
  67. instance = this;
  68. }
  69. if (instance != this)
  70. {
  71. Debug.LogError("There must be only one ARLocalizer object in a scene.");
  72. UnityEngine.Object.DestroyImmediate(this);
  73. return;
  74. }
  75. }
  76. public override void Start()
  77. {
  78. base.Start();
  79. m_Sdk.RegisterLocalizer(instance);
  80. }
  81. public override void OnEnable()
  82. {
  83. base.OnEnable();
  84. #if !UNITY_EDITOR
  85. CheckTrackingState(ARSession.state);
  86. ARSession.stateChanged += ARSessionStateChanged;
  87. #endif
  88. }
  89. public override void OnDisable()
  90. {
  91. #if !UNITY_EDITOR
  92. ARSession.stateChanged -= ARSessionStateChanged;
  93. #endif
  94. base.OnDisable();
  95. }
  96. public override async void LocalizeServer(SDKMapId[] mapIds)
  97. {
  98. #if PLATFORM_LUMIN && UNITY_2020_1
  99. XRCameraImage image;
  100. #else
  101. XRCpuImage image;
  102. #endif
  103. ARCameraManager cameraManager = m_Sdk.cameraManager;
  104. var cameraSubsystem = cameraManager.subsystem;
  105. #if PLATFORM_LUMIN && UNITY_2020_1
  106. if (cameraSubsystem.TryGetLatestImage(out image))
  107. #else
  108. if (cameraSubsystem.TryAcquireLatestCpuImage(out image))
  109. #endif
  110. {
  111. stats.localizationAttemptCount++;
  112. JobLocalizeServerAsync j = new JobLocalizeServerAsync();
  113. byte[] pixels;
  114. Vector3 camPos = m_Cam.transform.position;
  115. Quaternion camRot = m_Cam.transform.rotation;
  116. Vector4 intrinsics;
  117. int channels = 1;
  118. int width = image.width;
  119. int height = image.height;
  120. ARHelper.GetIntrinsics(out intrinsics);
  121. ARHelper.GetPlaneData(out pixels, image);
  122. float startTime = Time.realtimeSinceStartup;
  123. Task<(byte[], icvCaptureInfo)> t = Task.Run(() =>
  124. {
  125. byte[] capture = new byte[channels * width * height + 8192];
  126. icvCaptureInfo info = Immersal.Core.CaptureImage(capture, capture.Length, pixels, width, height, channels);
  127. Array.Resize(ref capture, info.captureSize);
  128. return (capture, info);
  129. });
  130. await t;
  131. j.image = t.Result.Item1;
  132. j.intrinsics = intrinsics;
  133. j.mapIds = mapIds;
  134. j.OnResult += (SDKLocalizeResult result) =>
  135. {
  136. float elapsedTime = Time.realtimeSinceStartup - startTime;
  137. if (result.success)
  138. {
  139. LocalizerDebugLog(string.Format("Relocalized in {0} seconds", elapsedTime));
  140. int mapId = result.map;
  141. if (mapId > 0 && ARSpace.mapIdToMap.ContainsKey(mapId))
  142. {
  143. ARMap map = ARSpace.mapIdToMap[mapId];
  144. if (mapId != lastLocalizedMapId)
  145. {
  146. if (resetOnMapChange)
  147. {
  148. Reset();
  149. }
  150. lastLocalizedMapId = mapId;
  151. OnMapChanged?.Invoke(mapId);
  152. }
  153. MapOffset mo = ARSpace.mapIdToOffset[mapId];
  154. stats.localizationSuccessCount++;
  155. Matrix4x4 responseMatrix = Matrix4x4.identity;
  156. responseMatrix.m00 = result.r00; responseMatrix.m01 = result.r01; responseMatrix.m02 = result.r02; responseMatrix.m03 = result.px;
  157. responseMatrix.m10 = result.r10; responseMatrix.m11 = result.r11; responseMatrix.m12 = result.r12; responseMatrix.m13 = result.py;
  158. responseMatrix.m20 = result.r20; responseMatrix.m21 = result.r21; responseMatrix.m22 = result.r22; responseMatrix.m23 = result.pz;
  159. Vector3 pos = responseMatrix.GetColumn(3);
  160. Quaternion rot = responseMatrix.rotation;
  161. ARHelper.GetRotation(ref rot);
  162. pos = ARHelper.SwitchHandedness(pos);
  163. rot = ARHelper.SwitchHandedness(rot);
  164. Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
  165. Vector3 scaledPos = Vector3.Scale(pos, mo.scale);
  166. Matrix4x4 cloudSpace = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
  167. Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
  168. Matrix4x4 m = trackerSpace * (cloudSpace.inverse);
  169. if (useFiltering)
  170. mo.space.filter.RefinePose(m);
  171. else
  172. ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
  173. double[] ecef = map.MapToEcefGet();
  174. LocalizerBase.GetLocalizerPose(out lastLocalizedPose, mapId, pos, rot, m.inverse, ecef);
  175. map.NotifySuccessfulLocalization(mapId);
  176. OnPoseFound?.Invoke(lastLocalizedPose);
  177. }
  178. }
  179. else
  180. {
  181. LocalizerDebugLog(string.Format("Localization attempt failed after {0} seconds", elapsedTime));
  182. }
  183. };
  184. await j.RunJobAsync();
  185. image.Dispose();
  186. }
  187. base.LocalizeServer(mapIds);
  188. }
  189. public override async void LocalizeGeoPose(SDKMapId[] mapIds)
  190. {
  191. ARCameraManager cameraManager = m_Sdk.cameraManager;
  192. var cameraSubsystem = cameraManager.subsystem;
  193. #if PLATFORM_LUMIN && UNITY_2020_1
  194. XRCameraImage image;
  195. if (cameraSubsystem.TryGetLatestImage(out image))
  196. #else
  197. XRCpuImage image;
  198. if (cameraSubsystem.TryAcquireLatestCpuImage(out image))
  199. #endif
  200. {
  201. stats.localizationAttemptCount++;
  202. JobGeoPoseAsync j = new JobGeoPoseAsync();
  203. byte[] pixels;
  204. Vector3 camPos = m_Cam.transform.position;
  205. Quaternion camRot = m_Cam.transform.rotation;
  206. int channels = 1;
  207. int width = image.width;
  208. int height = image.height;
  209. j.mapIds = mapIds;
  210. ARHelper.GetIntrinsics(out j.intrinsics);
  211. ARHelper.GetPlaneData(out pixels, image);
  212. float startTime = Time.realtimeSinceStartup;
  213. Task<(byte[], icvCaptureInfo)> t = Task.Run(() =>
  214. {
  215. byte[] capture = new byte[channels * width * height + 8192];
  216. icvCaptureInfo info = Immersal.Core.CaptureImage(capture, capture.Length, pixels, width, height, channels);
  217. Array.Resize(ref capture, info.captureSize);
  218. return (capture, info);
  219. });
  220. await t;
  221. j.image = t.Result.Item1;
  222. j.OnResult += (SDKGeoPoseResult result) =>
  223. {
  224. float elapsedTime = Time.realtimeSinceStartup - startTime;
  225. if (result.success)
  226. {
  227. LocalizerDebugLog(string.Format("Relocalized in {0} seconds", elapsedTime));
  228. int mapId = result.map;
  229. double latitude = result.latitude;
  230. double longitude = result.longitude;
  231. double ellipsoidHeight = result.ellipsoidHeight;
  232. Quaternion rot = new Quaternion(result.quaternion[1], result.quaternion[2], result.quaternion[3], result.quaternion[0]);
  233. LocalizerDebugLog(string.Format("GeoPose returned latitude: {0}, longitude: {1}, ellipsoidHeight: {2}, quaternion: {3}", latitude, longitude, ellipsoidHeight, rot));
  234. double[] ecef = new double[3];
  235. double[] wgs84 = new double[3] { latitude, longitude, ellipsoidHeight };
  236. Core.PosWgs84ToEcef(ecef, wgs84);
  237. if (ARSpace.mapIdToMap.ContainsKey(mapId))
  238. {
  239. ARMap map = ARSpace.mapIdToMap[mapId];
  240. if (mapId != lastLocalizedMapId)
  241. {
  242. if (resetOnMapChange)
  243. {
  244. Reset();
  245. }
  246. lastLocalizedMapId = mapId;
  247. OnMapChanged?.Invoke(mapId);
  248. }
  249. MapOffset mo = ARSpace.mapIdToOffset[mapId];
  250. stats.localizationSuccessCount++;
  251. double[] mapToEcef = map.MapToEcefGet();
  252. Vector3 mapPos;
  253. Quaternion mapRot;
  254. Core.PosEcefToMap(out mapPos, ecef, mapToEcef);
  255. Core.RotEcefToMap(out mapRot, rot, mapToEcef);
  256. Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
  257. Vector3 scaledPos = Vector3.Scale(mapPos, mo.scale);
  258. Matrix4x4 cloudSpace = offsetNoScale * Matrix4x4.TRS(scaledPos, mapRot, Vector3.one);
  259. Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
  260. Matrix4x4 m = trackerSpace*(cloudSpace.inverse);
  261. if (useFiltering)
  262. mo.space.filter.RefinePose(m);
  263. else
  264. ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
  265. LocalizerBase.GetLocalizerPose(out lastLocalizedPose, mapId, cloudSpace.GetColumn(3), cloudSpace.rotation, m.inverse, mapToEcef);
  266. map.NotifySuccessfulLocalization(mapId);
  267. OnPoseFound?.Invoke(lastLocalizedPose);
  268. }
  269. }
  270. else
  271. {
  272. LocalizerDebugLog(string.Format("GeoPose localization attempt failed after {0} seconds", elapsedTime));
  273. }
  274. };
  275. await j.RunJobAsync();
  276. image.Dispose();
  277. }
  278. base.LocalizeGeoPose(mapIds);
  279. }
  280. public override async void Localize()
  281. {
  282. Debug.Log("Localize===>start");
  283. #if PLATFORM_LUMIN && UNITY_2020_1
  284. XRCameraImage image;
  285. #else
  286. XRCpuImage image;
  287. #endif
  288. ARCameraManager cameraManager = m_Sdk.cameraManager;
  289. var cameraSubsystem = cameraManager.subsystem;
  290. Debug.Log("Localize===>cameraSubsystem");
  291. #if PLATFORM_LUMIN && UNITY_2020_1
  292. if (cameraSubsystem != null && cameraSubsystem.TryGetLatestImage(out image))
  293. #else
  294. if (cameraSubsystem != null && cameraSubsystem.TryAcquireLatestCpuImage(out image))
  295. #endif
  296. {
  297. Debug.Log("Localize===>cameraSubsystem TryAcquireLatestCpuImage");
  298. stats.localizationAttemptCount++;
  299. Vector4 intrinsics;
  300. Vector3 camPos = m_Cam.transform.position;
  301. Quaternion camRot = m_Cam.transform.rotation;
  302. ARHelper.GetIntrinsics(out intrinsics);
  303. ARHelper.GetPlaneDataFast(ref m_PixelBuffer, image);
  304. if (m_PixelBuffer != IntPtr.Zero)
  305. {
  306. Vector3 pos = Vector3.zero;
  307. Quaternion rot = Quaternion.identity;
  308. float startTime = Time.realtimeSinceStartup;
  309. Task<int> t = Task.Run(() =>
  310. {
  311. return Immersal.Core.LocalizeImage(out pos, out rot, image.width, image.height, ref intrinsics, m_PixelBuffer);
  312. });
  313. await t;
  314. int mapHandle = t.Result;
  315. int mapId = ARMap.MapHandleToId(mapHandle);
  316. float elapsedTime = Time.realtimeSinceStartup - startTime;
  317. if (mapId > 0 && ARSpace.mapIdToOffset.ContainsKey(mapId))
  318. {
  319. ARHelper.GetRotation(ref rot);
  320. pos = ARHelper.SwitchHandedness(pos);
  321. rot = ARHelper.SwitchHandedness(rot);
  322. LocalizerDebugLog(string.Format("Relocalized in {0} seconds", elapsedTime));
  323. stats.localizationSuccessCount++;
  324. if (mapId != lastLocalizedMapId)
  325. {
  326. if (resetOnMapChange)
  327. {
  328. Reset();
  329. }
  330. lastLocalizedMapId = mapId;
  331. OnMapChanged?.Invoke(mapId);
  332. }
  333. MapOffset mo = ARSpace.mapIdToOffset[mapId];
  334. Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
  335. Vector3 scaledPos = Vector3.Scale(pos, mo.scale);
  336. Matrix4x4 cloudSpace = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
  337. Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
  338. Matrix4x4 m = trackerSpace * (cloudSpace.inverse);
  339. if (useFiltering)
  340. mo.space.filter.RefinePose(m);
  341. else
  342. ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
  343. GetLocalizerPose(out lastLocalizedPose, mapId, pos, rot, m.inverse);
  344. OnPoseFound?.Invoke(lastLocalizedPose);
  345. ARMap map = ARSpace.mapIdToMap[mapId];
  346. map.NotifySuccessfulLocalization(mapId);
  347. }
  348. else
  349. {
  350. LocalizerDebugLog(string.Format("Localization attempt failed after {0} seconds", elapsedTime));
  351. }
  352. }
  353. image.Dispose();
  354. }
  355. base.Localize();
  356. }
  357. }
  358. }