ZED3DObjectVisualizer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Assets.Logging;
  6. using Assets.ZED.SDK.Helpers.Scripts;
  7. using UnityEngine;
  8. using UnityEngine.UIElements;
  9. /// <summary>
  10. /// For the ZED 3D Object Detection sample.
  11. /// Listens for new object detections (via the ZEDManager.OnObjectDetection event) and moves + resizes cube prefabs
  12. /// to represent them.
  13. /// <para>Works by instantiating a pool of prefabs, and each frame going through the DetectedFrame received from the event
  14. /// to make sure each detected object has a representative GameObject. Also disables GameObjects whose objects are no
  15. /// longer visible and returns them to the pool.</para>
  16. /// </summary>
  17. public class ZED3DObjectVisualizer : MonoBehaviour
  18. {
  19. /// <summary>
  20. /// The scene's ZEDManager.
  21. /// If you want to visualize detections from multiple ZEDs at once you will need multiple ZED3DObjectVisualizer commponents in the scene.
  22. /// </summary>
  23. [Tooltip("The scene's ZEDManager.\r\n" +
  24. "If you want to visualize detections from multiple ZEDs at once you will need multiple ZED3DObjectVisualizer commponents in the scene. ")]
  25. IZEDManager ZedManager => zedManagerLazy.Value;
  26. Lazy<IZEDManager> zedManagerLazy;
  27. /// <summary>
  28. /// If true, the ZED Object Detection manual will be started as soon as the ZED is initiated.
  29. /// This avoids having to press the Start Object Detection button in ZEDManager's Inspector.
  30. /// </summary>
  31. [Tooltip("If true, the ZED Object Detection manual will be started as soon as the ZED is initiated. " +
  32. "This avoids having to press the Start Object Detection button in ZEDManager's Inspector.")]
  33. public bool startObjectDetectionAutomatically = true;
  34. /// <summary>
  35. /// Prefab object that's instantiated to represent detected objects.
  36. /// This class expects the object to have the default Unity cube as a mesh - otherwise, it may be scaled incorrectly.
  37. /// It also expects a BBox3DHandler component in the root object, but you won't have errors if it lacks one.
  38. /// </summary>
  39. [Space(5)]
  40. [Header("Box Appearance")]
  41. [Tooltip("Prefab object that's instantiated to represent detected objects. " +
  42. "This class expects the object to have the default Unity cube as a mesh - otherwise, it may be scaled incorrectly.\r\n" +
  43. "It also expects a BBox3DHandler component in the root object, but you won't have errors if it lacks one. ")]
  44. public GameObject boundingBoxPrefab;
  45. /// <summary>
  46. /// The colors that will be cycled through when assigning colors to new bounding boxes.
  47. /// </summary>
  48. [Tooltip("The colors that will be cycled through when assigning colors to new bounding boxes. ")]
  49. //[ColorUsage(true, true)] //Uncomment to enable HDR colors in versions of Unity that support it.
  50. public List<Color> boxColors = new List<Color>()
  51. {
  52. new Color(.231f, .909f, .69f, 1),
  53. new Color(.098f, .686f, .816f, 1),
  54. new Color(.412f, .4f, .804f, 1),
  55. new Color(1, .725f, 0f, 1),
  56. new Color(.989f, .388f, .419f, 1)
  57. };
  58. /// <summary>
  59. /// If true, bounding boxes are rotated to face the camera that detected them. This has more parity with the SDK and will generally result in more accurate boxes.
  60. /// If false, the boxes are calculated from known bounds to face Z = 1.
  61. /// </summary>
  62. [Space(5)]
  63. [Header("Box Transform")]
  64. [Tooltip("If true, bounding boxes are rotated to face the camera that detected them. If false, the boxes are calculated from known bounds to face Z = 1. " +
  65. "'False' has more parity with the SDK and will generally result in more accurate boxes.")]
  66. public bool boxesFaceCamera = false;
  67. /// <summary>
  68. /// If true, transforms the localScale of the root bounding box transform to match the detected 3D bounding box.
  69. /// </summary>
  70. [Tooltip("If true, transforms the localScale of the root bounding box transform to match the detected 3D bounding box. ")]
  71. public bool transformBoxScale = true;
  72. /// <summary>
  73. /// If true, and transformBoxScale is also true, modifies the center and Y bounds of each detected bounding box so that its
  74. /// bottom is at floor level (Y = 0) while keeping the other corners at the same place.
  75. /// </summary>
  76. [Tooltip("If true, and transformBoxScale is also true, modifies the center and Y bounds of each detected bounding box so that its " +
  77. "bottom is at floor level (Y = 0) while keeping the other corners at the same place. WARNING: Estimate Initial position must be set to true.")]
  78. public bool transformBoxToTouchFloor = true;
  79. /// <summary>
  80. /// If true, sets the Y value of the center of the bounding box to 0. Use for bounding box prefabs meant to be centered at the user's feet.
  81. /// </summary>
  82. [Tooltip("If true, sets the Y value of the center of the bounding box to 0. Use for bounding box prefabs meant to be centered at the user's feet. ")]
  83. [LabelOverride("Box Center Always On Floor")]
  84. public bool floorBBoxPosition = false;
  85. /// <summary>
  86. /// Display bounding boxes of objects that are actively being tracked by object tracking, where valid positions are known.
  87. /// </summary>
  88. [Space(5)]
  89. [Header("Filters")]
  90. [Tooltip("Display bounding boxes of objects that are actively being tracked by object tracking, where valid positions are known. ")]
  91. public bool showONTracked = true;
  92. /// <summary>
  93. /// Display bounding boxes of objects that were actively being tracked by object tracking, but that were lost very recently.
  94. /// </summary>
  95. [Tooltip("Display bounding boxes of objects that were actively being tracked by object tracking, but that were lost very recently.")]
  96. public bool showSEARCHINGTracked = false;
  97. /// <summary>
  98. /// Display bounding boxes of objects that are visible but not actively being tracked by object tracking (usually because object tracking is disabled in ZEDManager).
  99. /// </summary>
  100. [Tooltip("Display bounding boxes of objects that are visible but not actively being tracked by object tracking (usually because object tracking is disabled in ZEDManager).")]
  101. public bool showOFFTracked = false;
  102. /// <summary>
  103. /// How wide a bounding box has to be in order to be displayed. Use this to remove tiny bounding boxes from partially-occluded objects.
  104. /// (If you have this issue, it can also be helpful to set showSEARCHINGTracked to OFF.)
  105. /// </summary>
  106. [Tooltip("How wide a bounding box has to be in order to be displayed. Use this to remove tiny bounding boxes from partially-occluded objects.\r\n" +
  107. "(If you have this issue, it can also be helpful to set showSEARCHINGTracked to OFF.)")]
  108. public float minimumWidthToDisplay = 0.3f;
  109. /// <summary>
  110. /// When a detected object is first given a box and assigned a color, we store it so that if the object
  111. /// disappears and appears again later, it's assigned the same color.
  112. /// This is also solvable by making the color a function of the ID number itself, but then you can get
  113. /// repeat colors under certain conditions.
  114. /// </summary>
  115. private Dictionary<int, Color> idColorDict = new Dictionary<int, Color>();
  116. /// <summary>
  117. /// Pre-instantiated bbox prefabs currently not in use.
  118. /// </summary>
  119. private Stack<GameObject> bboxPool = new Stack<GameObject>();
  120. /// <summary>
  121. /// All active GameObjects that were instantiated to the prefab and that currently represent a detected object.
  122. /// Key is the object's objectID.
  123. /// </summary>
  124. private Dictionary<int, GameObject> liveBBoxes = new Dictionary<int, GameObject>();
  125. /// <summary>
  126. /// Used to know which of the available colors will be assigned to the next bounding box to be used.
  127. /// </summary>
  128. private int nextColorIndex = 0;
  129. private void Awake()
  130. {
  131. zedManagerLazy = new(new LoggingZEDManager(FindObjectOfType<ZEDManager>(), new DetectionFrameLogger()));
  132. }
  133. void Start()
  134. {
  135. ZedManager.OnObjectDetection += ZedManager_OnObjectDetection;
  136. ZedManager.OnZEDReady += OnZEDReady;
  137. if (ZedManager.EstimateInitialPosition == false && transformBoxToTouchFloor == true)
  138. {
  139. Debug.Log("Estimate initial position is set to false. Then, transformBoxToTouchFloor is disable.");
  140. transformBoxToTouchFloor = false;
  141. }
  142. }
  143. private void ZedManager_OnObjectDetection(DetectionFrame objFrame)
  144. {
  145. Visualize3DBoundingBoxes(objFrame);
  146. }
  147. private void OnZEDReady()
  148. {
  149. if (startObjectDetectionAutomatically && !ZedManager.IsObjectDetectionRunning)
  150. {
  151. ZedManager.StartObjectDetection();
  152. }
  153. }
  154. /// <summary>
  155. /// Given a frame of object detections, positions a GameObject to represent every visible object
  156. /// in that object's actual 3D location within the world.
  157. /// <para>Called from ZEDManager.OnObjectDetection each time there's a new detection frame available.</para>
  158. /// </summary>
  159. private void Visualize3DBoundingBoxes(DetectionFrame dframe)
  160. {
  161. //Get a list of all active IDs from last frame, and we'll remove each box that's visible this frame.
  162. //At the end, we'll clear the remaining boxes, as those are objects no longer visible to the ZED.
  163. List<int> activeids = liveBBoxes.Keys.ToList();
  164. List<DetectedObject> newobjects = dframe.GetFilteredObjectList(showONTracked, showSEARCHINGTracked, showOFFTracked);
  165. foreach (DetectedObject dobj in newobjects)
  166. {
  167. Bounds objbounds = dobj.Get3DWorldBounds();
  168. //Make sure the object is big enough to count. We filter out very small boxes.
  169. if (objbounds.size.x < minimumWidthToDisplay || objbounds.size == Vector3.zero) continue;
  170. //Remove the ID from the list we'll use to clear no-longer-visible boxes.
  171. if (activeids.Contains(dobj.id)) activeids.Remove(dobj.id);
  172. //Get the box and update its distance value.
  173. GameObject bbox = GetBBoxForObject(dobj);
  174. //Move the box into position.
  175. Vector3 obj_position = dobj.Get3DWorldPosition();
  176. if (!ZEDSupportFunctions.IsVector3NaN(obj_position))
  177. {
  178. bbox.transform.position = obj_position;
  179. if (floorBBoxPosition)
  180. {
  181. bbox.transform.position = new Vector3(bbox.transform.position.x, 0, bbox.transform.position.z);
  182. }
  183. bbox.transform.rotation = dobj.Get3DWorldRotation(boxesFaceCamera); //Rotate them.
  184. }
  185. //Transform the box if desired.
  186. if (transformBoxScale)
  187. {
  188. //We'll scale the object assuming that it's mesh is the default Unity cube, or something sized equally.
  189. if (transformBoxToTouchFloor)
  190. {
  191. Vector3 startscale = objbounds.size;
  192. float distfromfloor = bbox.transform.position.y - (objbounds.size.y / 2f);
  193. bbox.transform.localScale = new Vector3(objbounds.size.x, objbounds.size.y + distfromfloor, objbounds.size.z);
  194. Vector3 newpos = bbox.transform.position;
  195. newpos.y -= (distfromfloor / 2f);
  196. bbox.transform.position = newpos;
  197. }
  198. else
  199. {
  200. bbox.transform.localScale = objbounds.size;
  201. }
  202. }
  203. //Now that we've adjusted position, tell the handler on the prefab to adjust distance display..
  204. BBox3DHandler boxhandler = bbox.GetComponent<BBox3DHandler>();
  205. if (boxhandler)
  206. {
  207. var position = dobj.Get3DWorldPosition();
  208. float disttobox = Vector3.Distance(dobj.detectingZEDManager.GetLeftCameraTransform().position, dobj.Get3DWorldPosition());
  209. boxhandler.SetDistance(disttobox);
  210. boxhandler.SetX(position.x);
  211. boxhandler.SetY(position.y);
  212. boxhandler.SetZ(position.z);
  213. boxhandler.UpdateBoxUVScales();
  214. boxhandler.UpdateLabelScaleAndPosition();
  215. Debug.Log($"Frame {dframe.frameCountAtDetection}, X: {position.x}, Y: {position.y}, Z: {position.z}");
  216. }
  217. //DrawDebugBox(dobj);
  218. }
  219. //Remove boxes for objects that the ZED can no longer see.
  220. foreach (int id in activeids)
  221. {
  222. ReturnBoxToPool(id, liveBBoxes[id]);
  223. }
  224. }
  225. /// <summary>
  226. /// Returs the GameObject (instantiated from boundingBoxPrefab) that represents the provided DetectedObject.
  227. /// If none exists, it retrieves one from the pool (or instantiates a new one if none is available) and
  228. /// sets it up with the proper ID and colors.
  229. /// </summary>
  230. private GameObject GetBBoxForObject(DetectedObject dobj)
  231. {
  232. if (!liveBBoxes.ContainsKey(dobj.id))
  233. {
  234. GameObject newbox = GetAvailableBBox();
  235. newbox.name = "Object #" + dobj.id;
  236. BBox3DHandler boxhandler = newbox.GetComponent<BBox3DHandler>();
  237. Color col;
  238. if (idColorDict.ContainsKey(dobj.id))
  239. {
  240. col = idColorDict[dobj.id];
  241. }
  242. else
  243. {
  244. col = GetNextColor();
  245. idColorDict.Add(dobj.id, col);
  246. }
  247. if (boxhandler)
  248. {
  249. boxhandler.SetColor(col);
  250. if (ZedManager.ObjectDetectionModel == sl.DETECTION_MODEL.CUSTOM_BOX_OBJECTS)
  251. {
  252. //boxhandler.SetID(dobj.rawObjectData.rawLabel.ToString());
  253. boxhandler.SetID(dobj.id.ToString());
  254. }
  255. else
  256. {
  257. boxhandler.SetID(dobj.id.ToString());
  258. }
  259. }
  260. liveBBoxes[dobj.id] = newbox;
  261. return newbox;
  262. }
  263. else return liveBBoxes[dobj.id];
  264. }
  265. /// <summary>
  266. /// Gets an available GameObject (instantiated from boundingBoxPrefab) from the pool,
  267. /// or instantiates a new one if none are available.
  268. /// </summary>
  269. /// <returns></returns>
  270. private GameObject GetAvailableBBox()
  271. {
  272. if (bboxPool.Count == 0)
  273. {
  274. GameObject newbbox = Instantiate(boundingBoxPrefab);
  275. newbbox.transform.SetParent(transform, false);
  276. bboxPool.Push(newbbox);
  277. }
  278. GameObject bbox = bboxPool.Pop();
  279. bbox.SetActive(true);
  280. return bbox;
  281. }
  282. /// <summary>
  283. /// Disables a GameObject that was being used to represent an object (of the given id) and puts it back
  284. /// into the pool for later use.
  285. /// </summary>
  286. private void ReturnBoxToPool(int id, GameObject bbox)
  287. {
  288. bbox.SetActive(false);
  289. bbox.name = "Unused";
  290. bboxPool.Push(bbox);
  291. if (liveBBoxes.ContainsKey(id))
  292. {
  293. liveBBoxes.Remove(id);
  294. }
  295. else
  296. {
  297. Debug.LogError("Tried to remove object ID " + id + " from active bboxes, but it wasn't in the dictionary.");
  298. }
  299. }
  300. /// <summary>
  301. /// Returns a color from the boxColors list.
  302. /// Colors are returned sequentially in order of their appearance in that list.
  303. /// </summary>
  304. /// <returns></returns>
  305. private Color GetNextColor()
  306. {
  307. if (boxColors.Count == 0)
  308. {
  309. return new Color(.043f, .808f, .435f, 1);
  310. }
  311. if (nextColorIndex >= boxColors.Count)
  312. {
  313. nextColorIndex = 0;
  314. }
  315. Color returncol = boxColors[nextColorIndex];
  316. nextColorIndex++;
  317. return returncol;
  318. }
  319. private void OnDestroy()
  320. {
  321. if (ZedManager != null)
  322. {
  323. ZedManager.OnObjectDetection -= ZedManager_OnObjectDetection;
  324. ZedManager.OnZEDReady -= OnZEDReady;
  325. }
  326. }
  327. /// <summary>
  328. /// Draws a bounding box in the Scene window. Useful for debugging a 3D bbox's position relative to it.
  329. /// </summary>
  330. private void DrawDebugBox(DetectedObject dobj)
  331. {
  332. //Test bbox orientation.
  333. Transform camtrans = dobj.detectingZEDManager.GetLeftCameraTransform();
  334. Vector3[] corners = dobj.rawObjectData.worldBoundingBox;
  335. Vector3[] rotcorners = new Vector3[8];
  336. //Vector3[] corners3d = new Vector3[8];
  337. Vector3[] corners3d = dobj.Get3DWorldCorners();
  338. for (int i = 0; i < 8; i++)
  339. {
  340. Vector3 fixrot = camtrans.InverseTransformPoint(corners[i]);
  341. rotcorners[i] = fixrot;
  342. }
  343. Debug.DrawLine(corners3d[0], corners3d[1], Color.red);
  344. Debug.DrawLine(corners3d[1], corners3d[2], Color.red);
  345. Debug.DrawLine(corners3d[2], corners3d[3], Color.red);
  346. Debug.DrawLine(corners3d[3], corners3d[0], Color.red);
  347. Debug.DrawLine(corners3d[4], corners3d[5], Color.red);
  348. Debug.DrawLine(corners3d[5], corners3d[6], Color.red);
  349. Debug.DrawLine(corners3d[6], corners3d[7], Color.red);
  350. Debug.DrawLine(corners3d[7], corners3d[4], Color.red);
  351. Debug.DrawLine(corners3d[0], corners3d[4], Color.red);
  352. Debug.DrawLine(corners3d[1], corners3d[5], Color.red);
  353. Debug.DrawLine(corners3d[2], corners3d[6], Color.red);
  354. Debug.DrawLine(corners3d[3], corners3d[7], Color.red);
  355. }
  356. }