MVP_Model.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. namespace SketchAssistantWPF
  13. {
  14. public class MVP_Model
  15. {
  16. /// <summary>
  17. /// The Presenter of the MVP-Model.
  18. /// </summary>
  19. MVP_Presenter programPresenter;
  20. /// <summary>
  21. /// History of Actions
  22. /// </summary>
  23. ActionHistory historyOfActions;
  24. /// <summary>
  25. /// The assistant responsible for the redraw mode
  26. /// </summary>
  27. //RedrawAssistant redrawAss;
  28. OptiTrackConnector connector;
  29. /***********************/
  30. /*** CLASS VARIABLES ***/
  31. /***********************/
  32. /// <summary>
  33. /// If the program is in drawing mode.
  34. /// </summary>
  35. bool inDrawingMode;
  36. /// <summary>
  37. /// if the program is using OptiTrack
  38. /// </summary>
  39. public bool optiTrackInUse{ get; private set; }
  40. /// <summary>
  41. /// Size of deletion area
  42. /// </summary>
  43. int deletionRadius = 5;
  44. /// <summary>
  45. /// Size of areas marking endpoints of lines in the redraw mode.
  46. /// </summary>
  47. int markerRadius = 10;
  48. /// <summary>
  49. /// The Position of the Cursor in the right picture box
  50. /// </summary>
  51. Point currentCursorPosition;
  52. /// <summary>
  53. /// The Previous Cursor Position in the right picture box
  54. /// </summary>
  55. Point previousCursorPosition;
  56. /// <summary>
  57. /// Queue for the cursorPositions
  58. /// </summary>
  59. Queue<Point> cursorPositions = new Queue<Point>();
  60. /// <summary>
  61. /// Lookup Matrix for checking postions of lines in the image
  62. /// </summary>
  63. bool[,] isFilledMatrix;
  64. /// <summary>
  65. /// Lookup Matrix for getting line ids at a certain postions of the image
  66. /// </summary>
  67. HashSet<int>[,] linesMatrix;
  68. /// <summary>
  69. /// List of items which will be overlayed over the right canvas.
  70. /// </summary>
  71. List<Tuple<bool, HashSet<Point>>> overlayItems;
  72. /// <summary>
  73. /// Width of the LeftImageBox.
  74. /// </summary>
  75. public int leftImageBoxWidth;
  76. /// <summary>
  77. /// Height of the LeftImageBox.
  78. /// </summary>
  79. public int leftImageBoxHeight;
  80. /// <summary>
  81. /// Width of the RightImageBox.
  82. /// </summary>
  83. public int rightImageBoxWidth;
  84. /// <summary>
  85. /// Height of the RightImageBox.
  86. /// </summary>
  87. public int rightImageBoxHeight;
  88. public ImageDimension leftImageSize { get; private set; }
  89. public ImageDimension rightImageSize { get; private set; }
  90. /// <summary>
  91. /// Indicates whether or not the canvas on the right side is active.
  92. /// </summary>
  93. public bool canvasActive {get; set;}
  94. /// <summary>
  95. /// Indicates if there is a graphic loaded in the left canvas.
  96. /// </summary>
  97. public bool graphicLoaded { get; set; }
  98. //TODO: calibrate
  99. double OPTITRACK_X_OFFSET = 0.7878 ;
  100. double OPTITRACK_Y_OFFSET = 0.7977 ;
  101. double OPTITRACK_CANVAS_HEIGHT = 1.29;
  102. double OPTITRACK_X_SCALE = -0.254 * (((1.816 / 0.0254) * 96) / (1.816));
  103. double OPTITRACK_Y_SCALE = 0.254 * (((1.360 / 0.0254) * 96) / (1.360));
  104. Image rightImageWithoutOverlay;
  105. List<InternalLine> leftLineList;
  106. List<Tuple<bool, InternalLine>> rightLineList;
  107. List<Point> currentLine = new List<Point>();
  108. public MVP_Model(MVP_Presenter presenter)
  109. {
  110. programPresenter = presenter;
  111. historyOfActions = new ActionHistory();
  112. //redrawAss = new RedrawAssistant();
  113. //overlayItems = new List<Tuple<bool, HashSet<Point>>>();
  114. rightLineList = new List<Tuple<bool, InternalLine>>();
  115. canvasActive = false;
  116. UpdateUI();
  117. rightImageSize = new ImageDimension(0, 0);
  118. leftImageSize = new ImageDimension(0, 0);
  119. connector = new OptiTrackConnector();
  120. armband = new Armband();
  121. if (connector.Init(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  122. {
  123. connector.StartTracking(getOptiTrackPosition);
  124. }
  125. }
  126. [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
  127. private static extern bool SetCursorPos(int X, int Y);
  128. //[DllImport("user32.dll")]
  129. //public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
  130. public enum MouseEventType : int
  131. {
  132. LeftDown = 0x02,
  133. LeftUp = 0x04,
  134. RightDown = 0x08,
  135. RightUp = 0x10
  136. }
  137. /**************************/
  138. /*** INTERNAL FUNCTIONS ***/
  139. /**************************/
  140. /// <summary>
  141. /// Change the status of whether or not the lines are shown.
  142. /// </summary>
  143. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  144. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  145. private void ChangeLines(HashSet<int> lines, bool shown)
  146. {
  147. foreach (int lineId in lines)
  148. {
  149. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  150. {
  151. rightLineList[lineId] = new Tuple<bool, InternalLine>(shown, rightLineList[lineId].Item2);
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// A function that populates the matrixes needed for deletion detection with line data.
  157. /// </summary>
  158. private void RepopulateDeletionMatrixes()
  159. {
  160. if (canvasActive)
  161. {
  162. isFilledMatrix = new bool[rightImageSize.Width, rightImageSize.Height];
  163. linesMatrix = new HashSet<int>[rightImageSize.Width, rightImageSize.Height];
  164. foreach (Tuple<bool, InternalLine> lineTuple in rightLineList)
  165. {
  166. if (lineTuple.Item1)
  167. {
  168. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  169. }
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Tells the Presenter to Update the UI
  175. /// </summary>
  176. private void UpdateUI()
  177. {
  178. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), canvasActive, graphicLoaded, optiTrackInUse);
  179. }
  180. /// <summary>
  181. /// A function that checks the deletion matrixes at a certain point
  182. /// and returns all Line ids at that point and in a square around it in a certain range.
  183. /// </summary>
  184. /// <param name="p">The point around which to check.</param>
  185. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  186. /// <returns>A List of all lines.</returns>
  187. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  188. {
  189. HashSet<int> returnSet = new HashSet<int>();
  190. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  191. {
  192. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageSize.Width && pnt.Y < rightImageSize.Height)
  193. {
  194. if (isFilledMatrix[(int)pnt.X, (int)pnt.Y])
  195. {
  196. returnSet.UnionWith(linesMatrix[(int)pnt.X, (int)pnt.Y]);
  197. }
  198. }
  199. }
  200. return returnSet;
  201. }
  202. /********************************************/
  203. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  204. /********************************************/
  205. /// <summary>
  206. /// A function to update the dimensions of the left and right canvas when the window is resized.
  207. /// </summary>
  208. /// <param name="LeftCanvas">The size of the left canvas.</param>
  209. /// <param name="RightCanvas">The size of the right canvas.</param>
  210. public void ResizeEvent(ImageDimension LeftCanvas, ImageDimension RightCanvas)
  211. {
  212. if(LeftCanvas.Height >= 0 && LeftCanvas.Width>= 0) { leftImageSize = LeftCanvas; }
  213. if(RightCanvas.Height >= 0 && RightCanvas.Width >= 0) { rightImageSize = RightCanvas; }
  214. RepopulateDeletionMatrixes();
  215. }
  216. /// <summary>
  217. /// A function to reset the right image.
  218. /// </summary>
  219. public void ResetRightImage()
  220. {
  221. rightLineList.Clear();
  222. programPresenter.PassLastActionTaken(historyOfActions.Reset());
  223. programPresenter.ClearRightLines();
  224. }
  225. /// <summary>
  226. /// The function to set the left image.
  227. /// </summary>
  228. /// <param name="width">The width of the left image.</param>
  229. /// <param name="height">The height of the left image.</param>
  230. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  231. public void SetLeftLineList(int width, int height, List<InternalLine> listOfLines)
  232. {
  233. leftImageSize = new ImageDimension(width, height);
  234. rightImageSize = new ImageDimension(width, height);
  235. leftLineList = listOfLines;
  236. graphicLoaded = true;
  237. programPresenter.UpdateLeftLines(leftLineList);
  238. CanvasActivated();
  239. /*
  240. var workingCanvas = GetEmptyCanvas(width, height);
  241. var workingGraph = Graphics.FromImage(workingCanvas);
  242. leftLineList = listOfLines;
  243. //redrawAss = new RedrawAssistant(leftLineList);
  244. //overlayItems = redrawAss.Initialize(markerRadius);
  245. //Lines
  246. foreach (InternalLine line in leftLineList)
  247. {
  248. line.DrawLine(workingGraph);
  249. }
  250. leftImage = workingCanvas;
  251. programPresenter.UpdateLeftImage(leftImage);
  252. //Set right image to same size as left image and delete linelist
  253. DrawEmptyCanvasRight();
  254. rightLineList = new List<Tuple<bool, InternalLine>>();
  255. */
  256. }
  257. /// <summary>
  258. /// A function to tell the model a new canvas was activated.
  259. /// </summary>
  260. public void CanvasActivated()
  261. {
  262. canvasActive = true;
  263. RepopulateDeletionMatrixes();
  264. UpdateUI();
  265. }
  266. /// <summary>
  267. /// Will undo the last action taken, if the action history allows it.
  268. /// </summary>
  269. public void Undo()
  270. {
  271. if (historyOfActions.CanUndo())
  272. {
  273. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  274. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  275. switch (undoAction)
  276. {
  277. case SketchAction.ActionType.Delete:
  278. //Deleted Lines need to be shown
  279. ChangeLines(affectedLines, true);
  280. break;
  281. case SketchAction.ActionType.Draw:
  282. //Drawn lines need to be hidden
  283. ChangeLines(affectedLines, false);
  284. break;
  285. default:
  286. break;
  287. }
  288. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  289. programPresenter.UpdateRightLines(rightLineList);
  290. }
  291. RepopulateDeletionMatrixes();
  292. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  293. UpdateUI();
  294. }
  295. /// <summary>
  296. /// Will redo the last action undone, if the action history allows it.
  297. /// </summary>
  298. public void Redo()
  299. {
  300. if (historyOfActions.CanRedo())
  301. {
  302. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  303. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  304. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  305. switch (redoAction)
  306. {
  307. case SketchAction.ActionType.Delete:
  308. //Deleted Lines need to be redeleted
  309. ChangeLines(affectedLines, false);
  310. break;
  311. case SketchAction.ActionType.Draw:
  312. //Drawn lines need to be redrawn
  313. ChangeLines(affectedLines, true);
  314. break;
  315. default:
  316. break;
  317. }
  318. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  319. programPresenter.UpdateRightLines(rightLineList);
  320. RepopulateDeletionMatrixes();
  321. }
  322. UpdateUI();
  323. }
  324. /// <summary>
  325. /// The function called by the Presenter to change the drawing state of the program.
  326. /// </summary>
  327. /// <param name="nowDrawing">The new drawingstate of the program</param>
  328. public void ChangeState(bool nowDrawing)
  329. {
  330. inDrawingMode = nowDrawing;
  331. UpdateUI();
  332. }
  333. public void ChangeOptiTrack(bool usingOptiTrack)
  334. {
  335. optiTrackInUse = usingOptiTrack;
  336. }
  337. /// <summary>
  338. /// Updates the current cursor position of the model.
  339. /// </summary>
  340. /// <param name="p">The new cursor position</param>
  341. public void SetCurrentCursorPosition(Point p)
  342. {
  343. if (!optiTrackInUse) currentCursorPosition = p;
  344. }
  345. /// <summary>
  346. /// Updates the current cursor position of the model.
  347. /// </summary>
  348. /// <param name="p">The new cursor position</param>
  349. public void SetCurrentFingerPosition(Point p)
  350. {
  351. Console.WriteLine("raw coordinates: " + p.X + ";" + p.Y);
  352. Point correctedPoint = ConvertTo96thsOfInch(p);
  353. Console.WriteLine(correctedPoint.X + "," + correctedPoint.Y);
  354. currentCursorPosition = correctedPoint;
  355. }
  356. private Point ConvertTo96thsOfInch(Point p)
  357. {
  358. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * OPTITRACK_X_SCALE;
  359. double yCoordinate = (OPTITRACK_CANVAS_HEIGHT - (p.Y - OPTITRACK_Y_OFFSET)) * OPTITRACK_Y_SCALE;
  360. return new Point(xCoordinate, yCoordinate);
  361. }
  362. private Point ConvertToPixel(Point p)
  363. {
  364. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * -1 * (/*Anzahl Pixel X-Richtung*/0 / (1.816)) + 0/*1/2 * x-richtung pixel*/); //TODO
  365. double yCoordinate = (((OPTITRACK_CANVAS_HEIGHT + 0/*meter von oberer Rand Leinwand zu oberer Rand Bildschirm*/) - (p.Y - OPTITRACK_Y_OFFSET))) * (/*Anzahl Pixel Y-Richtung*/0 / (1.360));
  366. return new Point(xCoordinate, yCoordinate);
  367. }
  368. /// <summary>
  369. /// Start a new Line, when the Mouse is pressed down.
  370. /// </summary>
  371. public void StartNewLine()
  372. {
  373. if (inDrawingMode)
  374. {
  375. currentLine.Clear();
  376. currentLine.Add(currentCursorPosition);
  377. }
  378. }
  379. /// <summary>
  380. /// Finish the current Line, when the pressed Mouse is released.
  381. /// </summary>
  382. public void FinishCurrentLine()
  383. {
  384. foreach (Point p in currentLine)
  385. {
  386. Console.WriteLine(p.X + ";" + p.Y);
  387. }
  388. if (inDrawingMode && currentLine.Count > 0)
  389. {
  390. InternalLine newLine = new InternalLine(currentLine, rightLineList.Count);
  391. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  392. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  393. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  394. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  395. programPresenter.UpdateRightLines(rightLineList);
  396. currentLine.Clear();
  397. programPresenter.UpdateCurrentLine(currentLine);
  398. }
  399. UpdateUI();
  400. }
  401. public float optiTrackX;
  402. public float optiTrackY;
  403. public float optiTrackZ;
  404. private bool optiTrackInsideDrawingZone = false;
  405. private double WARNING_ZONE_BOUNDARY= 0.10; //5cm
  406. private Armband armband;
  407. void getOptiTrackPosition(OptiTrack.Frame frame)
  408. {
  409. optiTrackX = frame.Trackables[0].X;
  410. optiTrackY = frame.Trackables[0].Y;
  411. optiTrackZ = frame.Trackables[0].Z;
  412. }
  413. /// <summary>
  414. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  415. /// </summary>
  416. public void Tick()
  417. {
  418. if (optiTrackInUse)
  419. {
  420. if (CheckInsideDrawingZone(optiTrackZ))
  421. {
  422. SetCurrentFingerPosition(new Point(optiTrackX, optiTrackY));
  423. if (!optiTrackInsideDrawingZone)
  424. {
  425. optiTrackInsideDrawingZone = true;
  426. StartNewLine();
  427. Console.WriteLine("new line begun");
  428. }
  429. if(optiTrackZ > WARNING_ZONE_BOUNDARY)
  430. {
  431. armband.pushForward();
  432. }
  433. else if(optiTrackZ < -1 * WARNING_ZONE_BOUNDARY)
  434. {
  435. armband.pushBackward();
  436. }
  437. }
  438. else
  439. {
  440. if (optiTrackInsideDrawingZone)
  441. {
  442. optiTrackInsideDrawingZone = false;
  443. FinishCurrentLine();
  444. Console.WriteLine("line finished");
  445. }
  446. }
  447. projectPointOntoScreen(optiTrackX, optiTrackY);
  448. }
  449. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  450. else { previousCursorPosition = currentCursorPosition; }
  451. cursorPositions.Enqueue(currentCursorPosition);
  452. //Drawing
  453. if (optiTrackInUse)
  454. {
  455. if (CheckInsideDrawingZone(optiTrackZ))
  456. {
  457. Console.WriteLine("point added");
  458. currentLine.Add(currentCursorPosition);
  459. programPresenter.UpdateCurrentLine(currentLine);
  460. }
  461. }
  462. else if (inDrawingMode && programPresenter.IsMousePressed())
  463. {
  464. currentLine.Add(currentCursorPosition);
  465. programPresenter.UpdateCurrentLine(currentLine);
  466. }
  467. //Deleting
  468. if (!inDrawingMode && programPresenter.IsMousePressed())
  469. {
  470. List<Point> uncheckedPoints= GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  471. foreach (Point currPoint in uncheckedPoints)
  472. {
  473. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  474. if (linesToDelete.Count > 0)
  475. {
  476. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  477. foreach (int lineID in linesToDelete)
  478. {
  479. rightLineList[lineID] = new Tuple<bool, InternalLine>(false, rightLineList[lineID].Item2);
  480. }
  481. RepopulateDeletionMatrixes();
  482. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  483. programPresenter.UpdateRightLines(rightLineList);
  484. }
  485. }
  486. }
  487. }
  488. private void projectPointOntoScreen(float optiTrackX, float optiTrackY)
  489. {
  490. Point auxiliaryPoint = ConvertToPixel(new Point(optiTrackX, optiTrackY));
  491. SetCursorPos((int)auxiliaryPoint.X, (int)auxiliaryPoint.Y);
  492. }
  493. private bool CheckInsideDrawingZone(float optiTrackZ)
  494. {
  495. if (Math.Abs(optiTrackZ) > WARNING_ZONE_BOUNDARY * 2) return false;
  496. return true;
  497. }
  498. /// <summary>
  499. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  500. /// </summary>
  501. /// <param name="CanvasSize">The size of the canvas</param>
  502. public void UpdateSizes(ImageDimension CanvasSize)
  503. {
  504. if (rightImageWithoutOverlay != null)
  505. {
  506. int widthImage = rightImageSize.Width;
  507. int heightImage = rightImageSize.Height;
  508. int widthBox = CanvasSize.Width;
  509. int heightBox = CanvasSize.Height;
  510. float imageRatio = (float)widthImage / (float)heightImage;
  511. float containerRatio = (float)widthBox / (float)heightBox;
  512. float zoomFactor = 0;
  513. if (imageRatio >= containerRatio)
  514. {
  515. //Image is wider than it is high
  516. zoomFactor = (float)widthImage / (float)widthBox;
  517. }
  518. else
  519. {
  520. //Image is higher than it is wide
  521. zoomFactor = (float)heightImage / (float)heightBox;
  522. }
  523. markerRadius = (int)(10 * zoomFactor);
  524. deletionRadius = (int)(5 * zoomFactor);
  525. }
  526. }
  527. /// <summary>
  528. /// If there is unsaved progress.
  529. /// </summary>
  530. /// <returns>True if there is progress that has not been saved.</returns>
  531. public bool HasUnsavedProgress()
  532. {
  533. return !historyOfActions.IsEmpty();
  534. }
  535. }
  536. }