PlayerController.cs 19 KB

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