NRLocalizer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using Immersal.REST;
  2. using NRKernal;
  3. using System;
  4. using System.Threading.Tasks;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using UnityEngine;
  7. using XRTool.Util;
  8. /*===============================================================================
  9. Copyright (C) 2022 Immersal - Part of Hexagon. All Rights Reserved.
  10. This file is part of the Immersal SDK.
  11. The Immersal SDK cannot be copied, distributed, or made available to
  12. third-parties for commercial purposes without written permission of Immersal Ltd.
  13. Contact sdk@immersal.com for licensing requests.
  14. ===============================================================================*/
  15. namespace Immersal.AR.Nreal
  16. {
  17. public class NRLocalizer : LocalizerBase
  18. {
  19. [Tooltip("Disable if you want to use RGB video capture while localizing. Also disable Multithreaded Rendering.")]
  20. [SerializeField]
  21. private bool m_UseYUV;
  22. private static NRLocalizer instance = null;
  23. private CameraModelView CamTexture { get; set; }
  24. public static NRLocalizer Instance
  25. {
  26. get
  27. {
  28. #if UNITY_EDITOR
  29. if (instance == null && !Application.isPlaying)
  30. {
  31. instance = UnityEngine.Object.FindObjectOfType<NRLocalizer>();
  32. }
  33. #endif
  34. if (instance == null)
  35. {
  36. Debug.LogError("No NRLocalizer instance found. Ensure one exists in the scene.");
  37. }
  38. return instance;
  39. }
  40. }
  41. void Awake()
  42. {
  43. if (instance == null)
  44. {
  45. instance = this;
  46. }
  47. if (instance != this)
  48. {
  49. Debug.LogError("There must be only one NRLocalizer object in a scene.");
  50. UnityEngine.Object.DestroyImmediate(this);
  51. return;
  52. }
  53. }
  54. public override void Start()
  55. {
  56. base.Start();
  57. m_Sdk.RegisterLocalizer(instance);
  58. if (m_UseYUV)
  59. {
  60. CamTexture = new NRRGBCamTextureYUV();
  61. (CamTexture as NRRGBCamTextureYUV).OnUpdate += OnYUVCaptureUpdate;
  62. }
  63. else
  64. {
  65. CamTexture = new NRRGBCamTexture();
  66. (CamTexture as NRRGBCamTexture).OnUpdate += OnRGBCaptureUpdate;
  67. }
  68. if (autoStart)
  69. {
  70. CamTexture.Play();
  71. }
  72. }
  73. public override void StartLocalizing()
  74. {
  75. CamTexture.Play();
  76. base.StartLocalizing();
  77. }
  78. public override void StopLocalizing()
  79. {
  80. base.StopLocalizing();
  81. CamTexture.Stop();
  82. }
  83. public override void Pause()
  84. {
  85. base.Pause();
  86. CamTexture.Pause();
  87. }
  88. protected override void Update()
  89. {
  90. isTracking = NRFrame.SessionStatus == SessionState.Running;
  91. base.Update();
  92. }
  93. public override void OnDestroy()
  94. {
  95. CamTexture.Stop();
  96. if (m_UseYUV)
  97. {
  98. (CamTexture as NRRGBCamTextureYUV).OnUpdate -= OnYUVCaptureUpdate;
  99. }
  100. else
  101. {
  102. (CamTexture as NRRGBCamTexture).OnUpdate -= OnRGBCaptureUpdate;
  103. }
  104. base.OnDestroy();
  105. }
  106. public override async void Localize()
  107. {
  108. while (!CamTexture.DidUpdateThisFrame)
  109. {
  110. await Task.Yield();
  111. }
  112. if (m_PixelBuffer != IntPtr.Zero)
  113. {
  114. stats.localizationAttemptCount++;
  115. Vector4 intrinsics;
  116. Pose headPose = NRFrame.HeadPose;
  117. Pose rgbCameraFromEyePose = NRFrame.EyePoseFromHead.RGBEyePose;
  118. Vector3 camPos = headPose.position + rgbCameraFromEyePose.position;
  119. Quaternion camRot = headPose.rotation * rgbCameraFromEyePose.rotation;
  120. int width = CamTexture.Width;
  121. int height = CamTexture.Height;
  122. Vector3 pos = Vector3.zero;
  123. Quaternion rot = Quaternion.identity;
  124. GetIntrinsics(out intrinsics);
  125. float startTime = Time.realtimeSinceStartup;
  126. Task<int> t = Task.Run(() =>
  127. {
  128. return Immersal.Core.LocalizeImage(out pos, out rot, width, height, ref intrinsics, m_PixelBuffer);
  129. });
  130. await t;
  131. int mapHandle = t.Result;
  132. int mapId = ARMap.MapHandleToId(mapHandle);
  133. float elapsedTime = Time.realtimeSinceStartup - startTime;
  134. if (mapId > 0 && ARSpace.mapIdToMap.ContainsKey(mapId))
  135. {
  136. Debug.Log(string.Format("Relocalized in {0} seconds", elapsedTime));
  137. stats.localizationSuccessCount++;
  138. ARMap map = ARSpace.mapIdToMap[mapId];
  139. if (mapId != lastLocalizedMapId)
  140. {
  141. if (resetOnMapChange)
  142. {
  143. Reset();
  144. }
  145. lastLocalizedMapId = mapId;
  146. OnMapChanged?.Invoke(mapId);
  147. }
  148. rot *= Quaternion.Euler(0f, 0f, 180.0f);
  149. pos = ARHelper.SwitchHandedness(pos);
  150. rot = ARHelper.SwitchHandedness(rot);
  151. MapOffset mo = ARSpace.mapIdToOffset[mapId];
  152. Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
  153. Vector3 scaledPos = Vector3.Scale(pos, mo.scale);
  154. Matrix4x4 cloudSpace = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
  155. Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
  156. Matrix4x4 m = trackerSpace * (cloudSpace.inverse);
  157. if (useFiltering)
  158. mo.space.filter.RefinePose(m);
  159. else
  160. ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
  161. Vector3 p = m.GetColumn(3);
  162. Vector3 euler = m.rotation.eulerAngles;
  163. GetLocalizerPose(out lastLocalizedPose, mapId, pos, rot, m.inverse);
  164. map.NotifySuccessfulLocalization(mapId);
  165. OnPoseFound?.Invoke(lastLocalizedPose);
  166. }
  167. else
  168. {
  169. Debug.Log(string.Format("Localization attempt failed after {0} seconds", elapsedTime));
  170. }
  171. }
  172. else
  173. {
  174. Debug.LogError("No camera pixel buffer");
  175. }
  176. base.Localize();
  177. }
  178. public override async void LocalizeServer(SDKMapId[] mapIds)
  179. {
  180. while (!CamTexture.DidUpdateThisFrame)
  181. {
  182. await Task.Yield();
  183. }
  184. if (m_PixelBuffer != IntPtr.Zero)
  185. {
  186. stats.localizationAttemptCount++;
  187. JobLocalizeServerAsync j = new JobLocalizeServerAsync();
  188. Vector4 intrinsics;
  189. Pose headPose = NRFrame.HeadPose;
  190. Pose rgbCameraFromEyePose = NRFrame.EyePoseFromHead.RGBEyePose;
  191. Vector3 camPos = headPose.position + rgbCameraFromEyePose.position;
  192. Quaternion camRot = headPose.rotation * rgbCameraFromEyePose.rotation;
  193. int channels = 1;
  194. int width = CamTexture.Width;
  195. int height = CamTexture.Height;
  196. byte[] pixels = m_UseYUV ? (CamTexture as NRRGBCamTextureYUV).GetTexture().YBuf : GetYBufFromTexture((CamTexture as NRRGBCamTexture).GetTexture());
  197. GetIntrinsics(out intrinsics);
  198. float startTime = Time.realtimeSinceStartup;
  199. Task<(byte[], icvCaptureInfo)> t = Task.Run(() =>
  200. {
  201. byte[] capture = new byte[channels * width * height + 8192];
  202. icvCaptureInfo info = Immersal.Core.CaptureImage(capture, capture.Length, pixels, width, height, channels);
  203. Array.Resize(ref capture, info.captureSize);
  204. return (capture, info);
  205. });
  206. await t;
  207. j.image = t.Result.Item1;
  208. j.intrinsics = intrinsics;
  209. j.mapIds = mapIds;
  210. j.OnResult += (SDKLocalizeResult result) =>
  211. {
  212. float elapsedTime = Time.realtimeSinceStartup - startTime;
  213. if (result.success)
  214. {
  215. Debug.Log("*************************** On-Server Localization Succeeded ***************************");
  216. Debug.Log(string.Format("Relocalized in {0} seconds", elapsedTime));
  217. int mapId = result.map;
  218. if (mapId > 0 && ARSpace.mapIdToMap.ContainsKey(mapId))
  219. {
  220. ARMap map = ARSpace.mapIdToMap[mapId];
  221. if (mapId != lastLocalizedMapId)
  222. {
  223. if (resetOnMapChange)
  224. {
  225. Reset();
  226. }
  227. lastLocalizedMapId = mapId;
  228. OnMapChanged?.Invoke(mapId);
  229. }
  230. MapOffset mo = ARSpace.mapIdToOffset[mapId];
  231. stats.localizationSuccessCount++;
  232. Matrix4x4 responseMatrix = Matrix4x4.identity;
  233. responseMatrix.m00 = result.r00; responseMatrix.m01 = result.r01; responseMatrix.m02 = result.r02; responseMatrix.m03 = result.px;
  234. responseMatrix.m10 = result.r10; responseMatrix.m11 = result.r11; responseMatrix.m12 = result.r12; responseMatrix.m13 = result.py;
  235. responseMatrix.m20 = result.r20; responseMatrix.m21 = result.r21; responseMatrix.m22 = result.r22; responseMatrix.m23 = result.pz;
  236. Vector3 pos = responseMatrix.GetColumn(3);
  237. Quaternion rot = responseMatrix.rotation;
  238. rot *= Quaternion.Euler(0f, 0f, 180.0f);
  239. pos = ARHelper.SwitchHandedness(pos);
  240. rot = ARHelper.SwitchHandedness(rot);
  241. Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
  242. Vector3 scaledPos = Vector3.Scale(pos, mo.scale);
  243. Matrix4x4 cloudSpace = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
  244. Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
  245. Matrix4x4 m = trackerSpace * (cloudSpace.inverse);
  246. if (useFiltering)
  247. mo.space.filter.RefinePose(m);
  248. else
  249. ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
  250. double[] ecef = map.MapToEcefGet();
  251. LocalizerBase.GetLocalizerPose(out lastLocalizedPose, mapId, pos, rot, m.inverse, ecef);
  252. map.NotifySuccessfulLocalization(mapId);
  253. OnPoseFound?.Invoke(lastLocalizedPose);
  254. }
  255. }
  256. else
  257. {
  258. Debug.Log("*************************** On-Server Localization Failed ***************************");
  259. Debug.Log(string.Format("Localization attempt failed after {0} seconds", elapsedTime));
  260. }
  261. };
  262. await j.RunJobAsync();
  263. }
  264. else
  265. {
  266. Debug.LogError("No camera pixel buffer");
  267. }
  268. base.LocalizeServer(mapIds);
  269. }
  270. public override async void LocalizeGeoPose(SDKMapId[] mapIds)
  271. {
  272. while (!CamTexture.DidUpdateThisFrame)
  273. {
  274. await Task.Yield();
  275. }
  276. if (m_PixelBuffer != IntPtr.Zero)
  277. {
  278. stats.localizationAttemptCount++;
  279. JobGeoPoseAsync j = new JobGeoPoseAsync();
  280. Vector4 intrinsics;
  281. Pose headPose = NRFrame.HeadPose;
  282. Pose rgbCameraFromEyePose = NRFrame.EyePoseFromHead.RGBEyePose;
  283. Vector3 camPos = headPose.position + rgbCameraFromEyePose.position;
  284. Quaternion camRot = headPose.rotation * rgbCameraFromEyePose.rotation;
  285. int channels = 1;
  286. int width = CamTexture.Width;
  287. int height = CamTexture.Height;
  288. byte[] pixels = m_UseYUV ? (CamTexture as NRRGBCamTextureYUV).GetTexture().YBuf : GetYBufFromTexture((CamTexture as NRRGBCamTexture).GetTexture());
  289. GetIntrinsics(out intrinsics);
  290. float startTime = Time.realtimeSinceStartup;
  291. Task<(byte[], icvCaptureInfo)> t = Task.Run(() =>
  292. {
  293. byte[] capture = new byte[channels * width * height + 8192];
  294. icvCaptureInfo info = Immersal.Core.CaptureImage(capture, capture.Length, pixels, width, height, channels);
  295. Array.Resize(ref capture, info.captureSize);
  296. return (capture, info);
  297. });
  298. await t;
  299. j.image = t.Result.Item1;
  300. j.intrinsics = intrinsics;
  301. j.mapIds = mapIds;
  302. j.OnResult += (SDKGeoPoseResult result) =>
  303. {
  304. float elapsedTime = Time.realtimeSinceStartup - startTime;
  305. if (result.success)
  306. {
  307. Debug.Log("*************************** GeoPose Localization Succeeded ***************************");
  308. Debug.Log(string.Format("Relocalized in {0} seconds", elapsedTime));
  309. int mapId = result.map;
  310. double latitude = result.latitude;
  311. double longitude = result.longitude;
  312. double ellipsoidHeight = result.ellipsoidHeight;
  313. Quaternion rot = new Quaternion(result.quaternion[1], result.quaternion[2], result.quaternion[3], result.quaternion[0]);
  314. Debug.Log(string.Format("GeoPose returned latitude: {0}, longitude: {1}, ellipsoidHeight: {2}, quaternion: {3}", latitude, longitude, ellipsoidHeight, rot));
  315. double[] ecef = new double[3];
  316. double[] wgs84 = new double[3] { latitude, longitude, ellipsoidHeight };
  317. Core.PosWgs84ToEcef(ecef, wgs84);
  318. if (ARSpace.mapIdToMap.ContainsKey(mapId))
  319. {
  320. ARMap map = ARSpace.mapIdToMap[mapId];
  321. if (mapId != lastLocalizedMapId)
  322. {
  323. if (resetOnMapChange)
  324. {
  325. Reset();
  326. }
  327. lastLocalizedMapId = mapId;
  328. OnMapChanged?.Invoke(mapId);
  329. }
  330. MapOffset mo = ARSpace.mapIdToOffset[mapId];
  331. stats.localizationSuccessCount++;
  332. double[] mapToEcef = map.MapToEcefGet();
  333. Vector3 mapPos;
  334. Quaternion mapRot;
  335. Core.PosEcefToMap(out mapPos, ecef, mapToEcef);
  336. Core.RotEcefToMap(out mapRot, rot, mapToEcef);
  337. Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
  338. Vector3 scaledPos = Vector3.Scale(mapPos, mo.scale);
  339. Matrix4x4 cloudSpace = offsetNoScale * Matrix4x4.TRS(scaledPos, mapRot, Vector3.one);
  340. Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
  341. Matrix4x4 m = trackerSpace * (cloudSpace.inverse);
  342. if (useFiltering)
  343. mo.space.filter.RefinePose(m);
  344. else
  345. ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
  346. LocalizerBase.GetLocalizerPose(out lastLocalizedPose, mapId, cloudSpace.GetColumn(3), cloudSpace.rotation, m.inverse, mapToEcef);
  347. map.NotifySuccessfulLocalization(mapId);
  348. OnPoseFound?.Invoke(lastLocalizedPose);
  349. }
  350. }
  351. else
  352. {
  353. Debug.Log("*************************** GeoPose Localization Failed ***************************");
  354. Debug.Log(string.Format("GeoPose localization attempt failed after {0} seconds", elapsedTime));
  355. }
  356. };
  357. await j.RunJobAsync();
  358. }
  359. else
  360. {
  361. Debug.LogError("No camera pixel buffer");
  362. }
  363. base.LocalizeGeoPose(mapIds);
  364. }
  365. private void OnRGBCaptureUpdate(CameraTextureFrame frame)
  366. {
  367. byte[] pixels = GetYBufFromTexture((Texture2D)frame.texture);
  368. unsafe
  369. {
  370. ulong handle;
  371. byte* ptr = (byte*)UnsafeUtility.PinGCArrayAndGetDataAddress(pixels, out handle);
  372. m_PixelBuffer = (IntPtr)ptr;
  373. UnsafeUtility.ReleaseGCObject(handle);
  374. }
  375. }
  376. private void OnYUVCaptureUpdate(NRRGBCamTextureYUV.YUVTextureFrame frame)
  377. {
  378. if (m_PixelBuffer == IntPtr.Zero)
  379. {
  380. unsafe
  381. {
  382. ulong handle;
  383. byte* ptr = (byte*)UnsafeUtility.PinGCArrayAndGetDataAddress(frame.YBuf, out handle);
  384. m_PixelBuffer = (IntPtr)ptr;
  385. UnsafeUtility.ReleaseGCObject(handle);
  386. }
  387. }
  388. }
  389. private byte[] GetYBufFromTexture(Texture2D tex)
  390. {
  391. Color32[] rgbArray = tex.GetPixels32();
  392. byte[] pixels = new byte[rgbArray.Length];
  393. for (int i = 0; i < rgbArray.Length; i++)
  394. {
  395. pixels[i] = rgbArray[i].g;
  396. }
  397. return pixels;
  398. }
  399. private void GetIntrinsics(out Vector4 intrinsics)
  400. {
  401. intrinsics = Vector4.zero;
  402. NativeMat3f m = NRFrame.GetRGBCameraIntrinsicMatrix();
  403. intrinsics.x = m.column0.X;
  404. intrinsics.y = m.column1.Y;
  405. intrinsics.z = m.column2.X;
  406. intrinsics.w = m.column2.Y;
  407. }
  408. }
  409. }