PersonManager.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using Assets.StreetLight.Adapters;
  2. using Assets.StreetLight.Interfaces;
  3. using Assets.StreetLight.Poco;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using UnityEngine;
  11. namespace Assets.StreetLight.Scripts
  12. {
  13. public class PersonManager : MonoBehaviour
  14. {
  15. public ObservableCollection<Person> Persons { get; private set; }
  16. private PositionCalculator PositionCalculator;
  17. private IPersonDetector personDetector;
  18. public event EventHandler DetectionReady;
  19. void Start()
  20. {
  21. try
  22. {
  23. var homographyArray = GetHomographyArrayFromFile();
  24. PositionCalculator = new PositionCalculator(homographyArray);
  25. }
  26. catch (Exception ex)
  27. {
  28. Debug.LogWarning($"Could not load homography: {ex.Message} Calculating the unity position of a person will not be possible. (This is expected during calibration.)");
  29. }
  30. Persons = new ObservableCollection<Person>();
  31. personDetector = new ZedPersonDetector(FindObjectOfType<ZEDManager>());
  32. personDetector.PersonsDetected += InvokeDetectionReady;
  33. personDetector.PersonsDetected += PersonDetector_PersonsDetected;
  34. }
  35. private double[,] GetHomographyArrayFromFile()
  36. {
  37. var homographyString = File.ReadAllLines(Configuration.Instance.HomographyFilePath);
  38. var values = homographyString.Select(l => l.Split(' ').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray()).ToArray();
  39. double[,] array = new double[3, 3];
  40. for (int i = 0; i < 3; i++)
  41. {
  42. for (int j = 0; j < 3; j++)
  43. {
  44. array[i, j] = values[i][j];
  45. }
  46. }
  47. return array;
  48. }
  49. private void InvokeDetectionReady(object sender, IEnumerable<Person> e)
  50. {
  51. DetectionReady?.Invoke(this, EventArgs.Empty);
  52. personDetector.PersonsDetected -= InvokeDetectionReady;
  53. }
  54. private void PersonDetector_PersonsDetected(object sender, IEnumerable<Person> e)
  55. {
  56. var detectedIds = new HashSet<int>();
  57. foreach (var detectedPerson in e)
  58. {
  59. var person = Persons.SingleOrDefault(p => p.Id == detectedPerson.Id);
  60. if (person == null)
  61. {
  62. person = new Person(detectedPerson.Id, PositionCalculator);
  63. Persons.Add(person);
  64. }
  65. person.WorldPosition = detectedPerson.WorldPosition;
  66. detectedIds.Add(detectedPerson.Id);
  67. }
  68. var personsToBeRemoved = Persons.Where(p => !detectedIds.Contains(p.Id)).ToArray();
  69. foreach (var person in personsToBeRemoved)
  70. {
  71. Persons.Remove(person);
  72. }
  73. }
  74. void Update()
  75. {
  76. }
  77. }
  78. }