MVP_Model.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Controls;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Imaging;
  10. using OptiTrack;
  11. using System.Runtime.InteropServices;
  12. using System.IO;
  13. namespace SketchAssistantWPF
  14. {
  15. public class MVP_Model
  16. {
  17. /// <summary>
  18. /// The Presenter of the MVP-Model.
  19. /// </summary>
  20. MVP_Presenter programPresenter;
  21. /// <summary>
  22. /// History of Actions
  23. /// </summary>
  24. ActionHistory historyOfActions;
  25. /// <summary>
  26. /// The connector class used to get frames from the Optitrack system.
  27. /// </summary>
  28. OptiTrackConnector connector;
  29. /// <summary>
  30. /// intensity of the tectile feedback occuring once every passed centimeter (ranging from 0.0 to 1.0)
  31. /// </summary>
  32. static readonly double TACTILE_SURFACE_FEEDBACK_INTENSITY = 1.0;
  33. /// <summary>
  34. /// duration of the tectile feedback occuring once every passed centimeter (in milliseconds)
  35. /// </summary>
  36. static readonly int TACTILE_SURFACE_FEEDBACK_DURATION = 50;
  37. /***********************/
  38. /*** CLASS VARIABLES ***/
  39. /***********************/
  40. /// <summary>
  41. /// this is a variable used for detecting whether the tracker is in the warning zone (0 +- variable), no drawing zone (0 +- 2 * variable) or normal drawing zone
  42. /// </summary>
  43. readonly double WARNING_ZONE_BOUNDARY = 0.10; //10cm
  44. /// <summary>
  45. /// If the program is in drawing mode.
  46. /// </summary>
  47. public bool inDrawingMode { get; private set; }
  48. /// <summary>
  49. /// if the program is using OptiTrack
  50. /// </summary>
  51. public bool optiTrackInUse { get; private set; }
  52. /// <summary>
  53. /// Size of deletion area
  54. /// </summary>
  55. int deletionRadius = 5;
  56. /// <summary>
  57. /// The Position of the Cursor in the right picture box
  58. /// </summary>
  59. Point currentCursorPosition;
  60. /// <summary>
  61. /// The Previous Cursor Position in the right picture box
  62. /// </summary>
  63. Point previousCursorPosition;
  64. /// <summary>
  65. /// Queue for the cursorPositions
  66. /// </summary>
  67. Queue<Point> cursorPositions = new Queue<Point>();
  68. /// <summary>
  69. /// The Position of the Cursor of opti track
  70. /// </summary>
  71. Point currentOptiCursorPosition;
  72. /// <summary>
  73. /// The Previous Cursor Position of opti track
  74. /// </summary>
  75. Point previousOptiCursorPosition;
  76. /// <summary>
  77. /// Queue for the cursorPositions of opti track
  78. /// </summary>
  79. Queue<Point> optiCursorPositions = new Queue<Point>();
  80. /// <summary>
  81. /// Lookup Matrix for checking postions of lines in the image
  82. /// </summary>
  83. bool[,] isFilledMatrix;
  84. /// <summary>
  85. /// Lookup Matrix for getting line ids at a certain postions of the image
  86. /// </summary>
  87. HashSet<int>[,] linesMatrix;
  88. /// <summary>
  89. /// Width of the LeftImageBox.
  90. /// </summary>
  91. public int leftImageBoxWidth;
  92. /// <summary>
  93. /// Height of the LeftImageBox.
  94. /// </summary>
  95. public int leftImageBoxHeight;
  96. /// <summary>
  97. /// Width of the RightImageBox.
  98. /// </summary>
  99. public int rightImageBoxWidth;
  100. /// <summary>
  101. /// Height of the RightImageBox.
  102. /// </summary>
  103. public int rightImageBoxHeight;
  104. /// <summary>
  105. /// The size of the right canvas.
  106. /// </summary>
  107. public ImageDimension rightImageSize { get; private set; }
  108. /// <summary>
  109. /// Indicates whether or not the canvas on the right side is active.
  110. /// </summary>
  111. public bool canvasActive { get; set; }
  112. /// <summary>
  113. /// Indicates if there is a graphic loaded in the left canvas.
  114. /// </summary>
  115. public bool graphicLoaded { get; set; }
  116. /// <summary>
  117. /// Whether or not an optitrack system is avaiable.
  118. /// </summary>
  119. public bool optitrackAvailable { get; private set; }
  120. /// <summary>
  121. /// x coordinate in real world. one unit is one meter. If standing in front of video wall facing it, moving left results in incrementation of x.
  122. /// </summary>
  123. public float optiTrackX;
  124. /// <summary>
  125. /// y coordinate in real world. one unit is one meter. If standing in front of video wall, moving up results in incrementation of y.
  126. /// </summary>
  127. public float optiTrackY;
  128. /// <summary>
  129. /// z coordinate in real world. one unit is one meter. If standing in front of video wall, moving back results in incrementation of y.
  130. /// </summary>
  131. public float optiTrackZ;
  132. /// <summary>
  133. /// keeps track of whether last tick the trackable was inside drawing zone or not.
  134. /// </summary>
  135. private bool optiTrackInsideDrawingZone = false;
  136. /// <summary>
  137. /// object of class wristband used for controlling the vibrotactile wristband
  138. /// </summary>
  139. private Wristband wristband;
  140. /// <summary>
  141. /// Is set to true when the trackable has passed to the backside of the drawing surface,
  142. /// invalidating all inputs on its way back.
  143. /// </summary>
  144. bool OptiMovingBack = false;
  145. /// <summary>
  146. /// The Layer in which the optitrack system was. 0 is drawing layer, -1 is in front, 1 is behind
  147. /// </summary>
  148. int OptiLayer = 0;
  149. /// <summary>
  150. /// The path traveled since the last tick
  151. /// </summary>
  152. double PathTraveled = 0;
  153. /// <summary>
  154. /// Whether or not the mouse is pressed.
  155. /// </summary>
  156. private bool mouseDown;
  157. /// <summary>
  158. /// A List of lines in the left canvas.
  159. /// </summary>
  160. List<InternalLine> leftLineList;
  161. /// <summary>
  162. /// A list of lines in the right canvas along with a boolean indicating if they should be drawn.
  163. /// </summary>
  164. List<Tuple<bool, InternalLine>> rightLineList;
  165. /// <summary>
  166. /// The line currently being drawin with optitrack.
  167. /// </summary>
  168. List<Point> currentLine = new List<Point>();
  169. public MVP_Model(MVP_Presenter presenter)
  170. {
  171. //TODO remove
  172. Console.WriteLine("trying to initialize Armband...");
  173. int tmp= LocalArmbandInterface.SetupArmband();
  174. Console.WriteLine("Armband initialization terminated, exit code: " + tmp);
  175. programPresenter = presenter;
  176. historyOfActions = new ActionHistory();
  177. rightLineList = new List<Tuple<bool, InternalLine>>();
  178. canvasActive = false;
  179. UpdateUI();
  180. rightImageSize = new ImageDimension(0, 0);
  181. connector = new OptiTrackConnector();
  182. wristband = new Wristband();
  183. //Set up Optitrack
  184. optitrackAvailable = false;
  185. if (File.Exists(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  186. {
  187. if (connector.Init(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  188. {
  189. optitrackAvailable = true;
  190. connector.StartTracking(GetOptiTrackPosition);
  191. }
  192. }
  193. }
  194. /**************************/
  195. /*** INTERNAL FUNCTIONS ***/
  196. /**************************/
  197. /// <summary>
  198. /// Check if the Optitrack trackable is in the drawing plane.
  199. /// </summary>
  200. /// <param name="optiTrackZ">The real world z coordinates of the trackable.</param>
  201. /// <returns>If the trackable is in front of the drawing plane</returns>
  202. private bool CheckInsideDrawingZone(float optiTrackZ)
  203. {
  204. if (Math.Abs(optiTrackZ) > WARNING_ZONE_BOUNDARY * 2) return false;
  205. return true;
  206. }
  207. /// <summary>
  208. /// Function that is called by the OptitrackController to pass frames to the model.
  209. /// </summary>
  210. /// <param name="frame">An Optitrack Frame</param>
  211. void GetOptiTrackPosition(OptiTrack.Frame frame)
  212. {
  213. if (frame.Trackables.Length >= 1)
  214. {
  215. optiTrackX = frame.Trackables[0].X;
  216. optiTrackY = frame.Trackables[0].Y;
  217. optiTrackZ = frame.Trackables[0].Z;
  218. }
  219. }
  220. /// <summary>
  221. /// Change the status of whether or not the lines are shown.
  222. /// </summary>
  223. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  224. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  225. private void ChangeLines(HashSet<int> lines, bool shown)
  226. {
  227. foreach (int lineId in lines)
  228. {
  229. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  230. {
  231. rightLineList[lineId] = new Tuple<bool, InternalLine>(shown, rightLineList[lineId].Item2);
  232. }
  233. }
  234. }
  235. /// <summary>
  236. /// Check if enough distance has been travelled to warrant a vibration.
  237. /// </summary>
  238. private void CheckPathTraveled()
  239. {
  240. var a = Math.Abs(previousOptiCursorPosition.X - currentOptiCursorPosition.X);
  241. var b = Math.Abs(previousOptiCursorPosition.Y - currentOptiCursorPosition.Y);
  242. PathTraveled += Math.Sqrt(Math.Pow(a,2) + Math.Pow(b,2));
  243. //Set the Interval of vibrations here
  244. if(PathTraveled > 2)
  245. {
  246. PathTraveled = 0;
  247. LocalArmbandInterface.Actuate(0, TACTILE_SURFACE_FEEDBACK_INTENSITY, TACTILE_SURFACE_FEEDBACK_DURATION);
  248. }
  249. }
  250. /// <summary>
  251. /// A function that populates the matrixes needed for deletion detection with line data.
  252. /// </summary>
  253. private void RepopulateDeletionMatrixes()
  254. {
  255. if (canvasActive)
  256. {
  257. isFilledMatrix = new bool[rightImageSize.Width, rightImageSize.Height];
  258. linesMatrix = new HashSet<int>[rightImageSize.Width, rightImageSize.Height];
  259. foreach (Tuple<bool, InternalLine> lineTuple in rightLineList)
  260. {
  261. if (lineTuple.Item1)
  262. {
  263. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  264. }
  265. }
  266. }
  267. }
  268. /// <summary>
  269. /// Tells the Presenter to Update the UI
  270. /// </summary>
  271. private void UpdateUI()
  272. {
  273. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), canvasActive, graphicLoaded, optitrackAvailable, optiTrackInUse);
  274. }
  275. /// <summary>
  276. /// A function that checks the deletion matrixes at a certain point
  277. /// and returns all Line ids at that point and in a square around it in a certain range.
  278. /// </summary>
  279. /// <param name="p">The point around which to check.</param>
  280. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  281. /// <returns>A List of all lines.</returns>
  282. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  283. {
  284. HashSet<int> returnSet = new HashSet<int>();
  285. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  286. {
  287. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageSize.Width && pnt.Y < rightImageSize.Height)
  288. {
  289. if (isFilledMatrix[(int)pnt.X, (int)pnt.Y])
  290. {
  291. returnSet.UnionWith(linesMatrix[(int)pnt.X, (int)pnt.Y]);
  292. }
  293. }
  294. }
  295. return returnSet;
  296. }
  297. /// <summary>
  298. /// Converts given point to device-independent pixel.
  299. /// </summary>
  300. /// <param name="p">real world coordinate</param>
  301. /// <returns>The given Point converted to device-independent pixel </returns>
  302. private Point ConvertTo96thsOfInch(Point p)
  303. {
  304. //The position of the optitrack coordinate system
  305. // and sizes of the optitrack tracking area relative to the canvas.
  306. double OPTITRACK_X_OFFSET = -0.4854;
  307. double OPTITRACK_Y_OFFSET = 0.9;
  308. double OPTITRACK_CANVAS_HEIGHT = 1.2;
  309. double OPTITRACK_X_SCALE = 0.21 * (((1.8316/*size of canvas*/ / 0.0254) * 96) / (1.8316));
  310. double OPTITRACK_Y_SCALE = 0.205 * (((1.2 / 0.0254) * 96) / (1.2));
  311. //The coordinates on the display
  312. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * OPTITRACK_X_SCALE;
  313. double yCoordinate = (OPTITRACK_CANVAS_HEIGHT - (p.Y - OPTITRACK_Y_OFFSET)) * OPTITRACK_Y_SCALE;
  314. return new Point(xCoordinate, yCoordinate);
  315. }
  316. /// <summary>
  317. /// Updates the Optitrack coordiantes, aswell as the marker for optitrack.
  318. /// </summary>
  319. /// <param name="p">The new cursor position</param>
  320. private void SetCurrentFingerPosition(Point p)
  321. {
  322. Point correctedPoint = ConvertTo96thsOfInch(p);
  323. if (optiTrackZ < -2.2 * WARNING_ZONE_BOUNDARY && OptiLayer > -1)
  324. {
  325. OptiLayer = -1; OptiMovingBack = false;
  326. programPresenter.SetOverlayColor("optipoint", Brushes.Yellow);
  327. }
  328. else if (optiTrackZ > 2 * WARNING_ZONE_BOUNDARY && OptiLayer < 1)
  329. {
  330. programPresenter.SetOverlayColor("optipoint", Brushes.Red);
  331. OptiLayer = 1;
  332. }
  333. else if(optiTrackZ <= 2 * WARNING_ZONE_BOUNDARY && optiTrackZ >= -2.2 * WARNING_ZONE_BOUNDARY){
  334. if(OptiLayer > 0)
  335. OptiMovingBack = true;
  336. programPresenter.SetOverlayColor("optipoint", Brushes.Green);
  337. OptiLayer = 0;
  338. }
  339. currentOptiCursorPosition = correctedPoint;
  340. programPresenter.MoveOptiPoint(currentOptiCursorPosition);
  341. if (optiCursorPositions.Count > 0) { previousOptiCursorPosition = optiCursorPositions.Dequeue(); }
  342. else { previousOptiCursorPosition = currentOptiCursorPosition; }
  343. optiCursorPositions.Enqueue(currentOptiCursorPosition);
  344. }
  345. /********************************************/
  346. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  347. /********************************************/
  348. /// <summary>
  349. /// A function to update the dimensions of the left and right canvas when the window is resized.
  350. /// </summary>
  351. /// <param name="RightCanvas">The size of the right canvas.</param>
  352. public void ResizeEvent(ImageDimension RightCanvas)
  353. {
  354. if (RightCanvas.Height >= 0 && RightCanvas.Width >= 0) { rightImageSize = RightCanvas; }
  355. RepopulateDeletionMatrixes();
  356. }
  357. /// <summary>
  358. /// A function to reset the right image.
  359. /// </summary>
  360. public void ResetRightImage()
  361. {
  362. if(currentLine.Count > 0)
  363. FinishCurrentLine(true);
  364. rightLineList.Clear();
  365. programPresenter.PassLastActionTaken(historyOfActions.Reset());
  366. programPresenter.ClearRightLines();
  367. }
  368. /// <summary>
  369. /// The function to set the left image.
  370. /// </summary>
  371. /// <param name="width">The width of the left image.</param>
  372. /// <param name="height">The height of the left image.</param>
  373. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  374. public void SetLeftLineList(int width, int height, List<InternalLine> listOfLines)
  375. {
  376. rightImageSize = new ImageDimension(width, height);
  377. leftLineList = listOfLines;
  378. graphicLoaded = true;
  379. programPresenter.UpdateLeftLines(leftLineList);
  380. CanvasActivated();
  381. }
  382. /// <summary>
  383. /// A function to tell the model a new canvas was activated.
  384. /// </summary>
  385. public void CanvasActivated()
  386. {
  387. canvasActive = true;
  388. RepopulateDeletionMatrixes();
  389. UpdateUI();
  390. }
  391. /// <summary>
  392. /// Will undo the last action taken, if the action history allows it.
  393. /// </summary>
  394. public void Undo()
  395. {
  396. if (historyOfActions.CanUndo())
  397. {
  398. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  399. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  400. switch (undoAction)
  401. {
  402. case SketchAction.ActionType.Delete:
  403. //Deleted Lines need to be shown
  404. ChangeLines(affectedLines, true);
  405. break;
  406. case SketchAction.ActionType.Draw:
  407. //Drawn lines need to be hidden
  408. ChangeLines(affectedLines, false);
  409. break;
  410. default:
  411. break;
  412. }
  413. programPresenter.UpdateRightLines(rightLineList);
  414. }
  415. RepopulateDeletionMatrixes();
  416. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  417. UpdateUI();
  418. }
  419. /// <summary>
  420. /// Will redo the last action undone, if the action history allows it.
  421. /// </summary>
  422. public void Redo()
  423. {
  424. if (historyOfActions.CanRedo())
  425. {
  426. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  427. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  428. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  429. switch (redoAction)
  430. {
  431. case SketchAction.ActionType.Delete:
  432. //Deleted Lines need to be redeleted
  433. ChangeLines(affectedLines, false);
  434. break;
  435. case SketchAction.ActionType.Draw:
  436. //Drawn lines need to be redrawn
  437. ChangeLines(affectedLines, true);
  438. break;
  439. default:
  440. break;
  441. }
  442. programPresenter.UpdateRightLines(rightLineList);
  443. RepopulateDeletionMatrixes();
  444. }
  445. UpdateUI();
  446. }
  447. /// <summary>
  448. /// The function called by the Presenter to change the drawing state of the program.
  449. /// </summary>
  450. /// <param name="nowDrawing">The new drawingstate of the program</param>
  451. public void ChangeState(bool nowDrawing)
  452. {
  453. if(inDrawingMode && !nowDrawing && currentLine.Count > 0 && optiTrackInUse)
  454. FinishCurrentLine(true);
  455. inDrawingMode = nowDrawing;
  456. UpdateUI();
  457. }
  458. /// <summary>
  459. /// The function called by the Presenter to set a variable which describes if OptiTrack is in use
  460. /// </summary>
  461. /// <param name="usingOptiTrack">The status of optitrack button</param>
  462. public void SetOptiTrack(bool usingOptiTrack)
  463. {
  464. optiTrackInUse = usingOptiTrack;
  465. if (usingOptiTrack && optiTrackX == 0 && optiTrackY == 0 && optiTrackZ == 0)
  466. {
  467. programPresenter.PassWarning("Trackable not detected, please check if OptiTrack is activated and Trackable is recognized");
  468. optiTrackInUse = false;
  469. //Disable optipoint
  470. programPresenter.SetOverlayStatus("optipoint", false, currentCursorPosition);
  471. }
  472. else
  473. {
  474. //Enable optipoint
  475. programPresenter.SetOverlayStatus("optipoint", true, currentCursorPosition);
  476. }
  477. }
  478. /// <summary>
  479. /// Updates the current cursor position of the model.
  480. /// </summary>
  481. /// <param name="p">The new cursor position</param>
  482. public void SetCurrentCursorPosition(Point p)
  483. {
  484. currentCursorPosition = p;
  485. mouseDown = programPresenter.IsMousePressed();
  486. }
  487. /// <summary>
  488. /// Start a new Line, when the Mouse is pressed down.
  489. /// </summary>
  490. public void StartNewLine()
  491. {
  492. mouseDown = true;
  493. if (inDrawingMode)
  494. {
  495. if(optiTrackInUse)
  496. {
  497. currentLine.Clear();
  498. currentLine.Add(currentOptiCursorPosition);
  499. }
  500. else if (programPresenter.IsMousePressed())
  501. {
  502. currentLine.Clear();
  503. currentLine.Add(currentCursorPosition);
  504. }
  505. }
  506. }
  507. /// <summary>
  508. /// Finish the current Line, when the pressed Mouse is released.
  509. /// </summary>
  510. /// <param name="valid">Whether the up event is valid or not</param>
  511. public void FinishCurrentLine(bool valid)
  512. {
  513. mouseDown = false;
  514. if (valid)
  515. {
  516. if (inDrawingMode && currentLine.Count > 0)
  517. {
  518. InternalLine newLine = new InternalLine(currentLine, rightLineList.Count);
  519. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  520. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  521. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  522. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  523. programPresenter.UpdateRightLines(rightLineList);
  524. currentLine.Clear();
  525. programPresenter.UpdateCurrentLine(currentLine);
  526. }
  527. }
  528. else
  529. {
  530. currentLine.Clear();
  531. }
  532. UpdateUI();
  533. }
  534. /// <summary>
  535. /// Finish the current Line, when the pressed Mouse is released.
  536. /// Overload that is used to pass a list of points to be used when one is available.
  537. /// </summary>
  538. /// <param name="p">The list of points</param>
  539. public void FinishCurrentLine(List<Point> p)
  540. {
  541. mouseDown = false;
  542. if (inDrawingMode && currentLine.Count > 0)
  543. {
  544. InternalLine newLine = new InternalLine(p, rightLineList.Count);
  545. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  546. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  547. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  548. programPresenter.UpdateRightLines(rightLineList);
  549. currentLine.Clear();
  550. }
  551. UpdateUI();
  552. }
  553. /// <summary>
  554. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  555. /// </summary>
  556. public void Tick()
  557. {
  558. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  559. else { previousCursorPosition = currentCursorPosition; }
  560. if(optitrackAvailable)
  561. SetCurrentFingerPosition(new Point(optiTrackX, optiTrackY));
  562. if (optiTrackInUse && inDrawingMode && !OptiMovingBack) // optitrack is being used
  563. {
  564. //outside of drawing zone
  565. if (!CheckInsideDrawingZone(optiTrackZ))
  566. {
  567. //Check if trackable was in drawing zone last tick & program is in drawing mode-> finish line
  568. if (optiTrackInsideDrawingZone && inDrawingMode)
  569. {
  570. optiTrackInsideDrawingZone = false;
  571. FinishCurrentLine(true);
  572. }
  573. }
  574. else //Draw with optitrack, when in drawing zone
  575. {
  576. //Optitrack wasn't in the drawing zone last tick -> start a new line
  577. if (!optiTrackInsideDrawingZone)
  578. {
  579. optiTrackInsideDrawingZone = true;
  580. StartNewLine();
  581. }
  582. else currentLine.Add(currentOptiCursorPosition);
  583. programPresenter.UpdateCurrentLine(currentLine);
  584. if (optiTrackZ > WARNING_ZONE_BOUNDARY)
  585. {
  586. wristband.PushForward();
  587. }
  588. else if (optiTrackZ < -1 * WARNING_ZONE_BOUNDARY)
  589. {
  590. wristband.PushBackward();
  591. }
  592. CheckPathTraveled();
  593. }
  594. }
  595. else if( !optiTrackInUse && inDrawingMode)
  596. {
  597. //drawing without optitrack
  598. cursorPositions.Enqueue(currentCursorPosition);
  599. if (inDrawingMode && programPresenter.IsMousePressed())
  600. {
  601. currentLine.Add(currentCursorPosition);
  602. //programPresenter.UpdateCurrentLine(currentLine);
  603. }
  604. }
  605. //Deletion mode for optitrack and regular use
  606. if (!inDrawingMode)
  607. {
  608. List<Point> uncheckedPoints = new List<Point>();
  609. if (programPresenter.IsMousePressed() && !optiTrackInUse) //without optitrack
  610. uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  611. if(optiTrackInUse && CheckInsideDrawingZone(optiTrackZ) && !OptiMovingBack) //with optitrack
  612. uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousOptiCursorPosition, currentOptiCursorPosition);
  613. foreach (Point currPoint in uncheckedPoints)
  614. {
  615. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  616. if (linesToDelete.Count > 0)
  617. {
  618. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  619. foreach (int lineID in linesToDelete)
  620. {
  621. rightLineList[lineID] = new Tuple<bool, InternalLine>(false, rightLineList[lineID].Item2);
  622. }
  623. RepopulateDeletionMatrixes();
  624. programPresenter.UpdateRightLines(rightLineList);
  625. }
  626. }
  627. }
  628. /*
  629. if (programPresenter.IsMousePressed()) //TODO only use if optitrack is in use (currently only available on different branch)
  630. {
  631. if(CentimeterGridPassed(previousCursorPosition, currentCursorPosition)) //TODO replace with optitrack coordinates (and introduce a buffer for previous real-world coordinates)
  632. {
  633. LocalArmbandInterface.Actuate(0, TACTILE_SURFACE_FEEDBACK_INTENSITY, TACTILE_SURFACE_FEEDBACK_DURATION);
  634. }
  635. }
  636. */
  637. }
  638. /// <summary>
  639. /// checks if the centimeter grid has been passed since the last tick and a vibrotactile feedback has to be sent to the user
  640. /// a high enough tick rate must be ensured to provide a useful feedback and avoid skipping necessary feedback
  641. /// </summary>
  642. /// <param name="previousCursorPosition">the curser position in real world coordinates (obtained from Optitrack) at the last tick</param>
  643. /// <param name="currentCursorPosition">the curser position in real world coordinates (obtained from Optitrack) at the current tick</param>
  644. /// <returns>true iff the grid has been passed</returns>
  645. private bool CentimeterGridPassed(Point previousCursorPositionRealWorldCoordinates, Point currentCursorPositionRealWorldCoordinates)
  646. {
  647. //truncate coordiates to int after converting to centimeters (from meters),
  648. if ((int)(previousCursorPositionRealWorldCoordinates.X * 100) != (int)(currentCursorPositionRealWorldCoordinates.X * 100)) return true;
  649. if ((int)(previousCursorPositionRealWorldCoordinates.Y * 100) != (int)(currentCursorPositionRealWorldCoordinates.Y * 100)) return true;
  650. return false;
  651. }
  652. /*
  653. /// <summary>
  654. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  655. /// </summary>
  656. /// <param name="CanvasSize">The size of the canvas</param>
  657. public void UpdateSizes(ImageDimension CanvasSize)
  658. {
  659. if (rightImageWithoutOverlay != null)
  660. {
  661. int widthImage = rightImageSize.Width;
  662. int heightImage = rightImageSize.Height;
  663. int widthBox = CanvasSize.Width;
  664. int heightBox = CanvasSize.Height;
  665. float imageRatio = (float)widthImage / (float)heightImage;
  666. float containerRatio = (float)widthBox / (float)heightBox;
  667. float zoomFactor = 0;
  668. if (imageRatio >= containerRatio)
  669. {
  670. //Image is wider than it is high
  671. zoomFactor = (float)widthImage / (float)widthBox;
  672. }
  673. else
  674. {
  675. //Image is higher than it is wide
  676. zoomFactor = (float)heightImage / (float)heightBox;
  677. }
  678. markerRadius = (int)(10 * zoomFactor);
  679. deletionRadius = (int)(5 * zoomFactor);
  680. }
  681. }
  682. */
  683. /// <summary>
  684. /// If there is unsaved progress.
  685. /// </summary>
  686. /// <returns>True if there is progress that has not been saved.</returns>
  687. public bool HasUnsavedProgress()
  688. {
  689. return !historyOfActions.IsEmpty();
  690. }
  691. }
  692. }