CalibrationRecorderBehavior.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using Assets.StreetLight.Scripts;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using UnityEngine;
  9. namespace Assets
  10. {
  11. public class CalibrationRecorderBehavior : MonoBehaviour
  12. {
  13. PersonManager PersonManager => personManagerLazy.Value;
  14. Lazy<PersonManager> personManagerLazy;
  15. string calibrationFileName;
  16. private void Awake()
  17. {
  18. personManagerLazy = new Lazy<PersonManager>(FindObjectOfType<PersonManager>);
  19. }
  20. BlockingCollection<Action> taskQueue;
  21. GameObject marker;
  22. void Start()
  23. {
  24. taskQueue = new BlockingCollection<Action>();
  25. calibrationFileName = Path.Combine(@".\CalibrationRecordings", $"CalibrationRecording{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.csv");
  26. InitializeCalibrationFile();
  27. enabled = false;
  28. PersonManager.DetectionReady += PersonManager_DetectionReady;
  29. marker = GameObject.Find("CalibrationMarker");
  30. var markerBehavior = FindObjectOfType<CalibrationMarkerBehavior>();
  31. markerBehavior.PathFinished += MarkerBehavior_PathFinished;
  32. }
  33. private void InitializeCalibrationFile()
  34. {
  35. var directoryPath = Path.GetDirectoryName(calibrationFileName);
  36. if (!Directory.Exists(directoryPath))
  37. {
  38. Directory.CreateDirectory(directoryPath);
  39. }
  40. if (!File.Exists(calibrationFileName))
  41. {
  42. File.WriteAllText(calibrationFileName, string.Empty);
  43. }
  44. }
  45. private void AppendNewCalibrationPoint(float worldX, float worldY, float unityX, float unityY)
  46. {
  47. var valuesToWrite = new float[] { worldX, worldY, unityX, unityY }.Select(f => f.ToString("0." + new string('#', 50), CultureInfo.InvariantCulture));
  48. var line = string.Join(" ", valuesToWrite);
  49. taskQueue.Add(() => File.AppendAllLines(calibrationFileName, new string[] { line }));
  50. Task.Run(() => taskQueue.Take().Invoke());
  51. }
  52. private void MarkerBehavior_PathFinished(object sender, EventArgs e)
  53. {
  54. enabled = false;
  55. taskQueue.Add(() => Application.Quit());
  56. Task.Run(() => taskQueue.Take().Invoke());
  57. }
  58. private void PersonManager_DetectionReady(object sender, EventArgs e)
  59. {
  60. enabled = true;
  61. }
  62. void Update()
  63. {
  64. if (PersonManager.Persons.Count == 1)
  65. {
  66. var person = PersonManager.Persons.Single();
  67. var personPosition = person.WorldPosition;
  68. var markerPosition = marker.transform.position;
  69. AppendNewCalibrationPoint(personPosition.x, personPosition.z, markerPosition.x, markerPosition.z);
  70. }
  71. }
  72. }
  73. }