Triangle.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace MonoGame.Extended.Triangulation
  5. {
  6. /// <summary>
  7. /// A basic triangle structure that holds the three vertices that make up a given triangle.
  8. /// MIT Licensed: https://github.com/nickgravelyn/Triangulator
  9. /// </summary>
  10. struct Triangle
  11. {
  12. public readonly Vertex A;
  13. public readonly Vertex B;
  14. public readonly Vertex C;
  15. public Triangle(Vertex a, Vertex b, Vertex c)
  16. {
  17. A = a;
  18. B = b;
  19. C = c;
  20. }
  21. public bool ContainsPoint(Vertex point)
  22. {
  23. //return true if the point to test is one of the vertices
  24. if (point.Equals(A) || point.Equals(B) || point.Equals(C))
  25. return true;
  26. bool oddNodes = false;
  27. if (checkPointToSegment(C, A, point))
  28. oddNodes = !oddNodes;
  29. if (checkPointToSegment(A, B, point))
  30. oddNodes = !oddNodes;
  31. if (checkPointToSegment(B, C, point))
  32. oddNodes = !oddNodes;
  33. return oddNodes;
  34. }
  35. public static bool ContainsPoint(Vertex a, Vertex b, Vertex c, Vertex point)
  36. {
  37. return new Triangle(a, b, c).ContainsPoint(point);
  38. }
  39. static bool checkPointToSegment(Vertex sA, Vertex sB, Vertex point)
  40. {
  41. if ((sA.Position.Y < point.Position.Y && sB.Position.Y >= point.Position.Y) ||
  42. (sB.Position.Y < point.Position.Y && sA.Position.Y >= point.Position.Y))
  43. {
  44. float x =
  45. sA.Position.X +
  46. (point.Position.Y - sA.Position.Y) /
  47. (sB.Position.Y - sA.Position.Y) *
  48. (sB.Position.X - sA.Position.X);
  49. if (x < point.Position.X)
  50. return true;
  51. }
  52. return false;
  53. }
  54. public override bool Equals(object obj)
  55. {
  56. if (obj.GetType() != typeof(Triangle))
  57. return false;
  58. return Equals((Triangle)obj);
  59. }
  60. public bool Equals(Triangle obj)
  61. {
  62. return obj.A.Equals(A) && obj.B.Equals(B) && obj.C.Equals(C);
  63. }
  64. public override int GetHashCode()
  65. {
  66. unchecked
  67. {
  68. int result = A.GetHashCode();
  69. result = (result * 397) ^ B.GetHashCode();
  70. result = (result * 397) ^ C.GetHashCode();
  71. return result;
  72. }
  73. }
  74. }
  75. }