PlayerController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. using Assets.Scripts.Models;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading;
  7. using UnityEngine;
  8. using UnityEngine.SceneManagement;
  9. using UnityEngine.UI;
  10. public class PlayerController : MonoBehaviour
  11. {
  12. public static Dictionary<uint, List<Structure>> Workers = new Dictionary<uint, List<Structure>>();
  13. public static List<Structure> TestStructures = new List<Structure>();
  14. public static List<Beacon> Beacons = new List<Beacon>();
  15. public GameObject WorkersList; // scroll content
  16. public Dropdown DropdownCompany;
  17. public Dropdown DropdownLocation;
  18. public Dropdown DropdownData;
  19. public GameObject inputField_date;
  20. //public InputField inputField_location;
  21. public GameObject TimeStart;
  22. public GameObject TimeEnd;
  23. public GameObject StartHour;
  24. public GameObject StartMin;
  25. public GameObject StartSec;
  26. public GameObject EndHour;
  27. public GameObject EndMin;
  28. public GameObject EndSec;
  29. public GameObject StartStopButton;
  30. public GameObject ErrorDialog;
  31. // public GameObject ButtonPlay;
  32. public Dropdown DropdownMode;
  33. public Toggle ToggleLine;
  34. public Toggle ToggleDisappearance;
  35. public GameObject DatePicker;
  36. Camera camera;
  37. public Toggle projection;
  38. public GameObject Locations;
  39. public enum Mode { RealTime = 0, History = 1, Stop = 2 };
  40. public static Mode active_mode = Mode.Stop;
  41. int mode = 0;
  42. //public GameObject Time;
  43. Client client;
  44. static EditorController editor;
  45. DateTimePicker Date;
  46. //public List<GameObject> maps;
  47. static bool starting = false; // флаг остановки
  48. public static Dictionary<uint, bool> end_send = new Dictionary<uint, bool>(); // флаги завершения загрузки
  49. Dictionary<uint, MarkerMoving> moving = new Dictionary<uint, MarkerMoving>(); // флаги начала движения
  50. float interpolationPeriod = 0.1f;
  51. //float time_realtime = 0;
  52. float time_draw = 0;
  53. public static List<User> users = new List<User>();
  54. public static bool users_load = false;
  55. public static bool beacons_load = false;
  56. public static List<Location> locations;
  57. public static List<Marker> markers;
  58. //List<bool> StartStop = new List<bool>();
  59. // Start is called before the first frame update
  60. void Start()
  61. {
  62. DebugHelper.ActivateConsole();
  63. client = Client.instance;
  64. editor = GameObject.Find("Canvas").transform.GetChild(3).GetComponent<EditorController>();
  65. camera = Camera.main;
  66. markers = new List<Marker>();
  67. locations = new List<Location>();
  68. Date = DatePicker.GetComponent<DateTimePicker>();
  69. locations.Add(new Location { id = 1, name = "1 Братск" });
  70. locations.Add(new Location { id = 22, name = "22 Офис Ижевск" });
  71. locations.Add(new Location { id = 25, name = "25" });
  72. foreach(var l in locations)
  73. DropdownLocation.options.Add(new Dropdown.OptionData(l.name));
  74. //for (int i = 0; i < Locations.transform.childCount; i++)
  75. // maps.Add(Locations.transform.GetChild(i).gameObject);
  76. DropdownCompany.options.Add(new Dropdown.OptionData("Тайшет"));
  77. DropdownCompany.options.Add(new Dropdown.OptionData("Тестовая"));
  78. DropdownCompany.options.Add(new Dropdown.OptionData("Братское"));
  79. }
  80. public static int active_location = 0;
  81. public static int active_company = 0;
  82. // Update is called once per frame
  83. void Update()
  84. {
  85. if (DropdownMode.value != mode)
  86. {
  87. StopProgress();
  88. active_mode = Mode.Stop;
  89. mode = DropdownMode.value;
  90. switch (DropdownMode.value)
  91. {
  92. case 0:
  93. DatePicker.SetActive(false);
  94. TimeStart.SetActive(false);
  95. TimeEnd.SetActive(false);
  96. break;
  97. case 1:
  98. DatePicker.SetActive(true);
  99. TimeStart.SetActive(true);
  100. TimeEnd.SetActive(true);
  101. break;
  102. }
  103. }
  104. if(active_company != DropdownCompany.value)
  105. {
  106. active_company = DropdownCompany.value;
  107. foreach(var m in markers)
  108. {
  109. Destroy(m.marker.gameObject);
  110. Destroy(m.marker_line.gameObject);
  111. Destroy(m.toggle.gameObject);
  112. }
  113. markers = new List<Marker>();
  114. client.SendGetUsers((uint) active_company + 1);
  115. }
  116. time_draw += Time.deltaTime;
  117. if (time_draw >= interpolationPeriod)
  118. {
  119. foreach (var m in markers.Select((value, i) => (value, i)))
  120. {
  121. m.value.marker.SetActive(m.value.toggle.isOn);
  122. if (m.value.toggle.isOn && Workers.ContainsKey(m.value.acc_id) && starting && end_send[m.value.acc_id])
  123. {
  124. //end_send[m.value.acc_id] = false;
  125. // moving.Add(true);
  126. //if (markers.Count - 1 == m.i)
  127. StartingAccPositiong(m.value);
  128. var temp = Workers.Values.Max(v => v.Count);
  129. if (active_mode == Mode.History && m.i == temp - 1 && moving[moving.Keys.Last()].step >= 1f)
  130. {
  131. StopProgress();
  132. }
  133. if (active_mode == Mode.RealTime && moving[moving.Keys.Last()].index == 1)
  134. {
  135. starting = false;
  136. }
  137. }
  138. }
  139. time_draw -= interpolationPeriod;
  140. }
  141. //time_realtime += Time.deltaTime;
  142. if (active_mode == Mode.RealTime /*&& !inputField_location.text.Equals("")*/ /*&& time_realtime >= interpolationPeriod*/ && !starting)
  143. {
  144. //time_realtime -= interpolationPeriod;
  145. //var location_id = uint.Parse(inputField_location.text);
  146. foreach (var m in markers)
  147. {
  148. if (m.toggle.isOn)
  149. {
  150. client.CoordinatesRequest(0, 0, 1, (uint)locations[active_location].id, m.acc_id);
  151. end_send[m.acc_id] = false;
  152. }
  153. }
  154. starting = true;
  155. }
  156. if (ToggleLine.isOn)
  157. {
  158. foreach (var m in markers)
  159. m.marker_line.gameObject.SetActive(true);
  160. ToggleDisappearance.interactable = true;
  161. }
  162. else
  163. {
  164. foreach (var m in markers)
  165. {
  166. m.marker_line.gameObject.SetActive(false);
  167. m.marker_line.positionCount = 0;
  168. }
  169. ToggleDisappearance.interactable = false;
  170. }
  171. if (projection.isOn)
  172. {
  173. camera.orthographic = true;
  174. }
  175. else
  176. {
  177. camera.orthographic = false;
  178. }
  179. if (users_load)
  180. {
  181. users_load = false;
  182. foreach (var u in users.OrderBy(u => u.id))
  183. WorkerMarker(u, Color.green);
  184. }
  185. LoadMaps(client, DropdownLocation, Locations);
  186. }
  187. /// <summary>
  188. /// Создание маркера для сотрудника
  189. /// </summary>
  190. /// <param name="acc_id"></param>
  191. void WorkerMarker(User user, Color color)
  192. {
  193. var toggle = Instantiate(Resources.Load("GameObjects/Toggle", typeof(Toggle))) as Toggle;
  194. toggle.name = $"{user.id}";
  195. toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{user.id} {user.name}";
  196. toggle.transform.SetParent(WorkersList.transform);
  197. toggle.isOn = false;
  198. var marker = Instantiate(Resources.Load("GameObjects/Capsule", typeof(GameObject))) as GameObject;
  199. marker.name = $"marker_{user.id}";
  200. marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{user.id}";
  201. marker.transform.SetParent(GameObject.Find("Markers").transform);
  202. marker.GetComponent<Renderer>().material.color = color; // UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
  203. var marker_line = Instantiate(Resources.Load("GameObjects/Line", typeof(LineRenderer))) as LineRenderer;
  204. marker_line.name = $"marker_line_{user.id}";
  205. marker_line.startColor = color;
  206. marker_line.endColor = Color.white;
  207. marker_line.material.color = color;
  208. marker_line.transform.SetParent(GameObject.Find("Markers").transform);
  209. markers.Add(new Marker { acc_id = user.id, marker = marker, toggle = toggle, marker_line = marker_line });
  210. }
  211. /// <summary>
  212. /// Смена положения маркера
  213. /// </summary>
  214. /// <param name="step">Шаг до нового положения</param>
  215. /// <param name="start_pos">Начальное положение</param>
  216. /// <param name="end_pos">Финальное положение</param>
  217. /// <param name="marker">Маркер сотрудника</param>
  218. /// <param name="w">Данные из БД</param>
  219. /// <param name="progress">Номер записи из БД</param>
  220. /// <returns></returns>
  221. void Position(float step, Vector3 start_pos, Vector3 end_pos, Marker marker, Structure w, string progress)
  222. {
  223. if (marker.marker.activeSelf == true)
  224. {
  225. var x_position = Mathf.Lerp(start_pos.x, end_pos.x, step);
  226. var y_position = Mathf.Lerp(start_pos.z, end_pos.z, step);
  227. //Debug.Log($"marker name={worker_marker.name} time={pause} step={step} sec x={x_position} y={y_position} x0={start_pos.x} y0={start_pos.z} x1={end_pos.x} y1={end_pos.z}");
  228. var new_position = new Vector3(x_position, 0.5f, y_position);
  229. if (marker.marker.transform.position != new_position)
  230. {
  231. marker.marker.transform.position = new Vector3(x_position, 0.5f, y_position);
  232. marker.marker_line.SetPosition(marker.marker_line.positionCount++, new Vector3(x_position, 0, y_position));
  233. if(ToggleDisappearance.isOn)marker.marker_line = LineDisappearance(marker.marker_line);
  234. }
  235. marker.marker.transform.GetChild(0).transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = $"{w.acc_id} x={end_pos.x} y={end_pos.z}";
  236. marker.toggle.transform.GetChild(1).gameObject.GetComponent<Text>().text = $"{w.acc_id} {w.ts:hh:mm:ss}{progress}";
  237. }
  238. }
  239. /// <summary>
  240. /// Запуск отрисовки
  241. /// </summary>
  242. public void ButtonStart()
  243. {
  244. if (active_mode == Mode.Stop)
  245. foreach (var m in markers)
  246. m.marker_line.positionCount = 0;
  247. var button_text = StartStopButton.transform.GetChild(0);
  248. switch (DropdownMode.value)
  249. {
  250. case 0:
  251. //real_time = !real_time;
  252. if (active_mode == Mode.Stop/*real_time*/)
  253. {
  254. active_mode = Mode.RealTime;
  255. button_text.GetComponent<Text>().text = "Остановить";
  256. }
  257. else
  258. {
  259. active_mode = Mode.Stop;
  260. button_text.GetComponent<Text>().text = "Отобразить";
  261. }
  262. break;
  263. case 1:
  264. if (int.Parse(StartHour.GetComponent<InputField>().text) == 99) SceneManager.LoadScene("Editor3D");
  265. else
  266. {
  267. if (active_mode == Mode.Stop/*real_time*/) active_mode = Mode.History;
  268. else active_mode = Mode.Stop;
  269. }//history_start = !history_start;
  270. if (active_mode == Mode.History/*history_start*/)
  271. {
  272. starting=true;
  273. var date = Date.Date;
  274. var time_start = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
  275. time_start = time_start.AddHours(int.Parse(StartHour.GetComponent<InputField>().text));
  276. time_start = time_start.AddMinutes(int.Parse(StartMin.GetComponent<InputField>().text));
  277. time_start = time_start.AddSeconds(int.Parse(StartSec.GetComponent<InputField>().text));
  278. Debug.Log(time_start);
  279. var time_end = date; //new DateTime(dates.ElementAt(DropdownData.value).Ticks);
  280. time_end = time_end.AddHours(int.Parse(EndHour.GetComponent<InputField>().text));
  281. time_end = time_end.AddMinutes(int.Parse(EndMin.GetComponent<InputField>().text));
  282. time_end = time_end.AddSeconds(int.Parse(EndSec.GetComponent<InputField>().text));
  283. foreach (var m in markers)
  284. {
  285. if (m.toggle.isOn)
  286. {
  287. client.CoordinatesRequest(time_start.Ticks, time_end.Ticks, 1, (uint)locations[active_location].id, m.acc_id);
  288. end_send[m.acc_id] = false;
  289. }
  290. }
  291. button_text.GetComponent<Text>().text = "Остановить";
  292. }
  293. else
  294. {
  295. StopProgress();
  296. }
  297. break;
  298. }
  299. }
  300. public void ErrorDialogClose()
  301. {
  302. ErrorDialog.SetActive(false);
  303. }
  304. public void StopProgress()
  305. {
  306. starting = false;
  307. StartStopButton.transform.GetChild(0).GetComponent<Text>().text = "Отобразить";
  308. active_mode = Mode.Stop;
  309. foreach (var m in markers)
  310. {
  311. end_send[m.acc_id] = false;
  312. moving.Remove(m.acc_id);
  313. }
  314. }
  315. /// <summary>
  316. /// Затухание траектории
  317. /// </summary>
  318. /// <param name="lineRenderer">Траектория</param>
  319. /// <returns></returns>
  320. LineRenderer LineDisappearance(LineRenderer lineRenderer)
  321. {
  322. //LineRenderer lineRenderer = GetComponent<LineRenderer>();
  323. int newPositionCount = lineRenderer.positionCount - 1;
  324. Vector3[] newPositions = new Vector3[newPositionCount];
  325. for (int i = 0; i < newPositionCount; i++)
  326. {
  327. newPositions[i] = lineRenderer.GetPosition(i + 1);
  328. }
  329. lineRenderer.SetPositions(newPositions);
  330. return lineRenderer;
  331. }
  332. /// <summary>
  333. /// Смена положения по интервалу
  334. /// Шаги для плавного перемещения
  335. /// </summary>
  336. /// <param name="m">Данные о маркере</param>
  337. void StartingAccPositiong(Marker m)
  338. {
  339. int i = 0;
  340. float step = 0.1f;
  341. if (moving.ContainsKey(m.acc_id))
  342. {
  343. if (moving[m.acc_id].index < Workers[m.acc_id].Count) i = moving[m.acc_id].index;
  344. if (moving[m.acc_id].step < 1.1f) step = moving[m.acc_id].step;
  345. }
  346. else moving[m.acc_id] = new MarkerMoving();
  347. var worker = Workers[m.acc_id].OrderBy(wr => wr.ts).ToList();
  348. if (worker.Any())
  349. {
  350. var w = worker.ElementAt(i);
  351. var start_pos = m.marker.transform.position;
  352. if (i != 0) start_pos = new Vector3(worker.ElementAt(i - 1).coord_x / 100f, 0.5f, worker.ElementAt(i - 1).coord_y / 100f);
  353. if (active_mode == Mode.History && i == 0) start_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
  354. var end_pos = new Vector3(w.coord_x / 100f, 0.5f, w.coord_y / 100f);
  355. var progress = "";
  356. if (active_mode == Mode.History) progress = $"\n{i + 1} из {Workers[m.acc_id].Count}";
  357. if (starting) Position(step, start_pos, end_pos, m, w, progress);
  358. // StartingAccPositiong(m.value, time_step);
  359. }
  360. if (step >= 1) i++;
  361. step += interpolationPeriod; // 0.1f;
  362. moving[m.acc_id].index = i;
  363. moving[m.acc_id].step = step;
  364. }
  365. /// <summary>
  366. /// Отображение маяков
  367. /// </summary>
  368. /// <param name="b"></param>
  369. public static void AddBeacon(Beacon b)
  370. {
  371. var beacon = Instantiate(Resources.Load("GameObjects/Beacon", typeof(GameObject))) as GameObject;
  372. beacon.transform.position = new Vector3(b.x/100, 0.5f, b.y/100);
  373. beacon.name = $"BeaconButton_{b.id}";
  374. beacon.GetComponent<BeaconController>().info = false;
  375. beacon.transform.SetParent(GameObject.Find("Beacons").transform);
  376. beacon.transform.GetChild(0).GetChild(0).GetChild(0).GetComponent<Text>().text = $"{b.id}\nuuid={b.uuid}\nmajor={b.major}\nminor={b.minor}";
  377. b.beacon = beacon;
  378. }
  379. public void OpenEditor()
  380. {
  381. SceneManager.LoadScene("Scenes/Editor2D");
  382. }
  383. void OnGUI()
  384. {
  385. //if (Input.GetKeyDown(KeyCode.BackQuote))
  386. DebugHelper.DrawConsole();
  387. }
  388. public static void LoadMaps(Client client, Dropdown DropdownLocation, GameObject Locations)
  389. {
  390. if (active_location != DropdownLocation.value)
  391. {
  392. Locations.transform.GetChild(active_location).gameObject.SetActive(false);
  393. Locations.transform.GetChild(DropdownLocation.value).gameObject.SetActive(true);
  394. active_location = DropdownLocation.value;
  395. foreach (var b in Beacons)
  396. {
  397. Destroy(b.beacon);
  398. Destroy(b.panel_button);
  399. }
  400. Beacons = new List<Beacon>();
  401. if (ModeController.editor == true && DropdownLocation.value != DropdownLocation.options.Count - 1) client.BeaconsRequest((uint)locations[DropdownLocation.value].id);
  402. if(ModeController.editor == false) client.BeaconsRequest((uint)locations[DropdownLocation.value].id);
  403. }
  404. if (beacons_load)
  405. {
  406. beacons_load = false;
  407. foreach (var b in Beacons)
  408. {
  409. //if (ModeController.editor == false) AddBeacon(b);
  410. //if (ModeController.editor == true)
  411. editor.AddBeacon(b);
  412. }
  413. }
  414. }
  415. }