MVP_Model.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. namespace SketchAssistantWPF
  11. {
  12. public class MVP_Model
  13. {
  14. /// <summary>
  15. /// The Presenter of the MVP-Model.
  16. /// </summary>
  17. MVP_Presenter programPresenter;
  18. /// <summary>
  19. /// History of Actions
  20. /// </summary>
  21. ActionHistory historyOfActions;
  22. /// <summary>
  23. /// The assistant responsible for the redraw mode
  24. /// </summary>
  25. //RedrawAssistant redrawAss;
  26. /// <summary>
  27. /// intensity of the tectile feedback occuring once every passed centimeter (ranging from 0.0 to 1.0)
  28. /// </summary>
  29. static readonly double TACTILE_SURFACE_FEEDBACK_INTENSITY = 1.0;
  30. /// <summary>
  31. /// duration of the tectile feedback occuring once every passed centimeter (in milliseconds)
  32. /// </summary>
  33. static readonly int TACTILE_SURFACE_FEEDBACK_DURATION = 50;
  34. /***********************/
  35. /*** CLASS VARIABLES ***/
  36. /***********************/
  37. /// <summary>
  38. /// If the program is in drawing mode.
  39. /// </summary>
  40. bool inDrawingMode;
  41. /// <summary>
  42. /// Size of deletion area
  43. /// </summary>
  44. int deletionRadius = 5;
  45. /// <summary>
  46. /// Size of areas marking endpoints of lines in the redraw mode.
  47. /// </summary>
  48. int markerRadius = 10;
  49. /// <summary>
  50. /// The Position of the Cursor in the right picture box
  51. /// </summary>
  52. Point currentCursorPosition;
  53. /// <summary>
  54. /// The Previous Cursor Position in the right picture box
  55. /// </summary>
  56. Point previousCursorPosition;
  57. /// <summary>
  58. /// Queue for the cursorPositions
  59. /// </summary>
  60. Queue<Point> cursorPositions = new Queue<Point>();
  61. /// <summary>
  62. /// Lookup Matrix for checking postions of lines in the image
  63. /// </summary>
  64. bool[,] isFilledMatrix;
  65. /// <summary>
  66. /// Lookup Matrix for getting line ids at a certain postions of the image
  67. /// </summary>
  68. HashSet<int>[,] linesMatrix;
  69. /// <summary>
  70. /// List of items which will be overlayed over the right canvas.
  71. /// </summary>
  72. List<Tuple<bool, HashSet<Point>>> overlayItems;
  73. /// <summary>
  74. /// Width of the LeftImageBox.
  75. /// </summary>
  76. public int leftImageBoxWidth;
  77. /// <summary>
  78. /// Height of the LeftImageBox.
  79. /// </summary>
  80. public int leftImageBoxHeight;
  81. /// <summary>
  82. /// Width of the RightImageBox.
  83. /// </summary>
  84. public int rightImageBoxWidth;
  85. /// <summary>
  86. /// Height of the RightImageBox.
  87. /// </summary>
  88. public int rightImageBoxHeight;
  89. public ImageDimension leftImageSize { get; private set; }
  90. public ImageDimension rightImageSize { get; private set; }
  91. /// <summary>
  92. /// Indicates whether or not the canvas on the right side is active.
  93. /// </summary>
  94. public bool canvasActive {get; set;}
  95. /// <summary>
  96. /// Indicates if there is a graphic loaded in the left canvas.
  97. /// </summary>
  98. public bool graphicLoaded { get; set; }
  99. /// <summary>
  100. /// Whether or not the mouse is pressed.
  101. /// </summary>
  102. private bool mouseDown;
  103. Image rightImageWithoutOverlay;
  104. List<InternalLine> leftLineList;
  105. List<Tuple<bool, InternalLine>> rightLineList;
  106. List<Point> currentLine = new List<Point>();
  107. public MVP_Model(MVP_Presenter presenter)
  108. {
  109. //TODO remove
  110. Console.WriteLine("trying to initialize Armband...");
  111. int tmp= LocalArmbandInterface.SetupArmband();
  112. Console.WriteLine("Armband initialization terminated, exit code: " + tmp);
  113. programPresenter = presenter;
  114. historyOfActions = new ActionHistory();
  115. //redrawAss = new RedrawAssistant();
  116. //overlayItems = new List<Tuple<bool, HashSet<Point>>>();
  117. rightLineList = new List<Tuple<bool, InternalLine>>();
  118. canvasActive = false;
  119. UpdateUI();
  120. rightImageSize = new ImageDimension(0, 0);
  121. leftImageSize = new ImageDimension(0, 0);
  122. }
  123. /**************************/
  124. /*** INTERNAL FUNCTIONS ***/
  125. /**************************/
  126. /// <summary>
  127. /// Change the status of whether or not the lines are shown.
  128. /// </summary>
  129. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  130. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  131. private void ChangeLines(HashSet<int> lines, bool shown)
  132. {
  133. foreach (int lineId in lines)
  134. {
  135. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  136. {
  137. rightLineList[lineId] = new Tuple<bool, InternalLine>(shown, rightLineList[lineId].Item2);
  138. }
  139. }
  140. }
  141. /// <summary>
  142. /// A function that populates the matrixes needed for deletion detection with line data.
  143. /// </summary>
  144. private void RepopulateDeletionMatrixes()
  145. {
  146. if (canvasActive)
  147. {
  148. isFilledMatrix = new bool[rightImageSize.Width, rightImageSize.Height];
  149. linesMatrix = new HashSet<int>[rightImageSize.Width, rightImageSize.Height];
  150. foreach (Tuple<bool, InternalLine> lineTuple in rightLineList)
  151. {
  152. if (lineTuple.Item1)
  153. {
  154. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  155. }
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Tells the Presenter to Update the UI
  161. /// </summary>
  162. private void UpdateUI()
  163. {
  164. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), canvasActive, graphicLoaded);
  165. }
  166. /// <summary>
  167. /// A function that checks the deletion matrixes at a certain point
  168. /// and returns all Line ids at that point and in a square around it in a certain range.
  169. /// </summary>
  170. /// <param name="p">The point around which to check.</param>
  171. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  172. /// <returns>A List of all lines.</returns>
  173. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  174. {
  175. HashSet<int> returnSet = new HashSet<int>();
  176. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  177. {
  178. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageSize.Width && pnt.Y < rightImageSize.Height)
  179. {
  180. if (isFilledMatrix[(int)pnt.X, (int)pnt.Y])
  181. {
  182. returnSet.UnionWith(linesMatrix[(int)pnt.X, (int)pnt.Y]);
  183. }
  184. }
  185. }
  186. return returnSet;
  187. }
  188. /********************************************/
  189. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  190. /********************************************/
  191. /// <summary>
  192. /// A function to update the dimensions of the left and right canvas when the window is resized.
  193. /// </summary>
  194. /// <param name="LeftCanvas">The size of the left canvas.</param>
  195. /// <param name="RightCanvas">The size of the right canvas.</param>
  196. public void ResizeEvent(ImageDimension LeftCanvas, ImageDimension RightCanvas)
  197. {
  198. if(LeftCanvas.Height >= 0 && LeftCanvas.Width>= 0) { leftImageSize = LeftCanvas; }
  199. if(RightCanvas.Height >= 0 && RightCanvas.Width >= 0) { rightImageSize = RightCanvas; }
  200. RepopulateDeletionMatrixes();
  201. }
  202. /// <summary>
  203. /// A function to reset the right image.
  204. /// </summary>
  205. public void ResetRightImage()
  206. {
  207. rightLineList.Clear();
  208. programPresenter.PassLastActionTaken(historyOfActions.Reset());
  209. programPresenter.ClearRightLines();
  210. }
  211. /// <summary>
  212. /// The function to set the left image.
  213. /// </summary>
  214. /// <param name="width">The width of the left image.</param>
  215. /// <param name="height">The height of the left image.</param>
  216. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  217. public void SetLeftLineList(int width, int height, List<InternalLine> listOfLines)
  218. {
  219. leftImageSize = new ImageDimension(width, height);
  220. rightImageSize = new ImageDimension(width, height);
  221. leftLineList = listOfLines;
  222. graphicLoaded = true;
  223. programPresenter.UpdateLeftLines(leftLineList);
  224. //programPresenter.ClearRightLines(); //TODO check if right position for this method call
  225. CanvasActivated();
  226. /*
  227. var workingCanvas = GetEmptyCanvas(width, height);
  228. var workingGraph = Graphics.FromImage(workingCanvas);
  229. leftLineList = listOfLines;
  230. //redrawAss = new RedrawAssistant(leftLineList);
  231. //overlayItems = redrawAss.Initialize(markerRadius);
  232. //Lines
  233. foreach (InternalLine line in leftLineList)
  234. {
  235. line.DrawLine(workingGraph);
  236. }
  237. leftImage = workingCanvas;
  238. programPresenter.UpdateLeftImage(leftImage);
  239. //Set right image to same size as left image and delete linelist
  240. DrawEmptyCanvasRight();
  241. rightLineList = new List<Tuple<bool, InternalLine>>();
  242. */
  243. }
  244. /// <summary>
  245. /// A function to tell the model a new canvas was activated.
  246. /// </summary>
  247. public void CanvasActivated()
  248. {
  249. canvasActive = true;
  250. RepopulateDeletionMatrixes();
  251. UpdateUI();
  252. }
  253. /// <summary>
  254. /// Will undo the last action taken, if the action history allows it.
  255. /// </summary>
  256. public void Undo()
  257. {
  258. if (historyOfActions.CanUndo())
  259. {
  260. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  261. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  262. switch (undoAction)
  263. {
  264. case SketchAction.ActionType.Delete:
  265. //Deleted Lines need to be shown
  266. ChangeLines(affectedLines, true);
  267. break;
  268. case SketchAction.ActionType.Draw:
  269. //Drawn lines need to be hidden
  270. ChangeLines(affectedLines, false);
  271. break;
  272. default:
  273. break;
  274. }
  275. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  276. programPresenter.UpdateRightLines(rightLineList);
  277. }
  278. RepopulateDeletionMatrixes();
  279. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  280. UpdateUI();
  281. }
  282. /// <summary>
  283. /// Will redo the last action undone, if the action history allows it.
  284. /// </summary>
  285. public void Redo()
  286. {
  287. if (historyOfActions.CanRedo())
  288. {
  289. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  290. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  291. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  292. switch (redoAction)
  293. {
  294. case SketchAction.ActionType.Delete:
  295. //Deleted Lines need to be redeleted
  296. ChangeLines(affectedLines, false);
  297. break;
  298. case SketchAction.ActionType.Draw:
  299. //Drawn lines need to be redrawn
  300. ChangeLines(affectedLines, true);
  301. break;
  302. default:
  303. break;
  304. }
  305. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  306. programPresenter.UpdateRightLines(rightLineList);
  307. RepopulateDeletionMatrixes();
  308. }
  309. UpdateUI();
  310. }
  311. /// <summary>
  312. /// The function called by the Presenter to change the drawing state of the program.
  313. /// </summary>
  314. /// <param name="nowDrawing">The new drawingstate of the program</param>
  315. public void ChangeState(bool nowDrawing)
  316. {
  317. inDrawingMode = nowDrawing;
  318. UpdateUI();
  319. }
  320. /// <summary>
  321. /// Updates the current cursor position of the model.
  322. /// </summary>
  323. /// <param name="p">The new cursor position</param>
  324. public void SetCurrentCursorPosition(Point p)
  325. {
  326. currentCursorPosition = p;
  327. mouseDown = programPresenter.IsMousePressed();
  328. }
  329. /// <summary>
  330. /// Start a new Line, when the Mouse is pressed down.
  331. /// </summary>
  332. public void MouseDown()
  333. {
  334. mouseDown = true;
  335. if (inDrawingMode && mouseDown)
  336. {
  337. currentLine.Clear();
  338. currentLine.Add(currentCursorPosition);
  339. }
  340. //TODO remove
  341. //LocalArmbandInterface.startVibrate(0, 1);
  342. LocalArmbandInterface.Actuate(0, 1.0, 20);
  343. Console.WriteLine("Vibrate motor 0 for 20ms");
  344. }
  345. /// <summary>
  346. /// Finish the current Line, when the pressed Mouse is released.
  347. /// </summary>
  348. /// <param name="valid">Whether the up event is valid or not</param>
  349. public void MouseUp(bool valid)
  350. {
  351. mouseDown = false;
  352. if (valid)
  353. {
  354. if (inDrawingMode && currentLine.Count > 0)
  355. {
  356. InternalLine newLine = new InternalLine(currentLine, rightLineList.Count);
  357. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  358. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  359. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  360. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  361. programPresenter.UpdateRightLines(rightLineList);
  362. currentLine.Clear();
  363. //programPresenter.UpdateCurrentLine(currentLine);
  364. }
  365. }
  366. else
  367. {
  368. currentLine.Clear();
  369. }
  370. UpdateUI();
  371. }
  372. /// <summary>
  373. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  374. /// </summary>
  375. public void Tick()
  376. {
  377. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  378. else { previousCursorPosition = currentCursorPosition; }
  379. cursorPositions.Enqueue(currentCursorPosition);
  380. //Drawing
  381. if (inDrawingMode && programPresenter.IsMousePressed())
  382. {
  383. currentLine.Add(currentCursorPosition);
  384. //programPresenter.UpdateCurrentLine(currentLine);
  385. }
  386. //Deleting
  387. if (!inDrawingMode && programPresenter.IsMousePressed())
  388. {
  389. List<Point> uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  390. foreach (Point currPoint in uncheckedPoints)
  391. {
  392. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  393. if (linesToDelete.Count > 0)
  394. {
  395. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  396. foreach (int lineID in linesToDelete)
  397. {
  398. rightLineList[lineID] = new Tuple<bool, InternalLine>(false, rightLineList[lineID].Item2);
  399. }
  400. RepopulateDeletionMatrixes();
  401. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  402. programPresenter.UpdateRightLines(rightLineList);
  403. }
  404. }
  405. }
  406. if (programPresenter.IsMousePressed()) //TODO only use if optitrack is in use (currently only available on different branch)
  407. {
  408. if(CentimeterGridPassed(previousCursorPosition, currentCursorPosition)) //TODO replace with optitrack coordinates (and introduce a buffer for previous real-world coordinates)
  409. {
  410. LocalArmbandInterface.Actuate(0, TACTILE_SURFACE_FEEDBACK_INTENSITY, TACTILE_SURFACE_FEEDBACK_DURATION);
  411. }
  412. }
  413. }
  414. /// <summary>
  415. /// checks if the centimeter grid has been passed since the last tick and a vibrotactile feedback has to be sent to the user
  416. /// a high enough tick rate must be ensured to provide a useful feedback and avoid skipping necessary feedback
  417. /// </summary>
  418. /// <param name="previousCursorPosition">the curser position in real world coordinates (obtained from Optitrack) at the last tick</param>
  419. /// <param name="currentCursorPosition">the curser position in real world coordinates (obtained from Optitrack) at the current tick</param>
  420. /// <returns>true iff the grid has been passed</returns>
  421. private bool CentimeterGridPassed(Point previousCursorPositionRealWorldCoordinates, Point currentCursorPositionRealWorldCoordinates)
  422. {
  423. //truncate coordiates to int after converting to centimeters (from meters),
  424. if ((int)(previousCursorPositionRealWorldCoordinates.X * 100) != (int)(currentCursorPositionRealWorldCoordinates.X * 100)) return true;
  425. if ((int)(previousCursorPositionRealWorldCoordinates.Y * 100) != (int)(currentCursorPositionRealWorldCoordinates.Y * 100)) return true;
  426. return false;
  427. }
  428. /*
  429. /// <summary>
  430. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  431. /// </summary>
  432. /// <param name="CanvasSize">The size of the canvas</param>
  433. public void UpdateSizes(ImageDimension CanvasSize)
  434. {
  435. if (rightImageWithoutOverlay != null)
  436. {
  437. int widthImage = rightImageSize.Width;
  438. int heightImage = rightImageSize.Height;
  439. int widthBox = CanvasSize.Width;
  440. int heightBox = CanvasSize.Height;
  441. float imageRatio = (float)widthImage / (float)heightImage;
  442. float containerRatio = (float)widthBox / (float)heightBox;
  443. float zoomFactor = 0;
  444. if (imageRatio >= containerRatio)
  445. {
  446. //Image is wider than it is high
  447. zoomFactor = (float)widthImage / (float)widthBox;
  448. }
  449. else
  450. {
  451. //Image is higher than it is wide
  452. zoomFactor = (float)heightImage / (float)heightBox;
  453. }
  454. markerRadius = (int)(10 * zoomFactor);
  455. deletionRadius = (int)(5 * zoomFactor);
  456. }
  457. }
  458. */
  459. /// <summary>
  460. /// If there is unsaved progress.
  461. /// </summary>
  462. /// <returns>True if there is progress that has not been saved.</returns>
  463. public bool HasUnsavedProgress()
  464. {
  465. return !historyOfActions.IsEmpty();
  466. }
  467. }
  468. }