LineSegment.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. using System;
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Runtime.Serialization;
  5. using Microsoft.Xna.Framework;
  6. namespace MonoGame.Extended;
  7. /// <summary>
  8. /// Represents a line segment defined by two endpoints.
  9. /// </summary>
  10. [DataContract]
  11. [DebuggerDisplay("{DebugDisplayString,nq}")]
  12. public struct LineSegment : IEquatable<LineSegment>
  13. {
  14. #region Fields
  15. private static readonly LineSegment s_empty = new LineSegment(Vector2.Zero, Vector2.Zero);
  16. /// <summary>
  17. /// The starting point of the line segment.
  18. /// </summary>
  19. [DataMember]
  20. public Vector2 Start;
  21. /// <summary>
  22. /// The ending point of the line segment.
  23. /// </summary>
  24. [DataMember]
  25. public Vector2 End;
  26. #endregion
  27. #region Properties
  28. /// <summary>
  29. /// Gets an empty line segment representing a degenerate case with both endpoints at the same position.
  30. /// </summary>
  31. public static LineSegment Empty => s_empty;
  32. /// <summary>
  33. /// Gets a value indicating whether this line segment represents a degenerate case with no length,
  34. /// having both endpoints at the same position.
  35. /// </summary>
  36. public readonly bool IsEmpty => Start == End;
  37. /// <summary>
  38. /// Gets the direction vector from start to end point with magnitude equal to segment length.
  39. /// </summary>
  40. public readonly Vector2 Direction => End - Start;
  41. /// <summary>
  42. /// Gets the direction vector from start to end point normalized to unit length.
  43. /// </summary>
  44. public readonly Vector2 DirectionNormalized => Vector2.Normalize(Direction);
  45. /// <summary>
  46. /// Gets the length of the line segment.
  47. /// </summary>
  48. public readonly float Length => Vector2.Distance(Start, End);
  49. /// <summary>
  50. /// Gets the squared length of the line segment, avoiding square root calculation.
  51. /// </summary>
  52. /// <remarks>
  53. /// This property avoids the expensive square root operation, making it more efficient
  54. /// for length comparisons when the actual distance value is not needed.
  55. /// </remarks>
  56. public readonly float LengthSquared => Vector2.DistanceSquared(Start, End);
  57. /// <summary>
  58. /// Gets the midpoint of the line segment.
  59. /// </summary>
  60. public readonly Vector2 Center => (Start + End) * 0.5f;
  61. #endregion
  62. #region Constructors
  63. /// <summary>
  64. /// Initializes a new line segment with the specified endpoints.
  65. /// </summary>
  66. /// <param name="start">The starting point of the segment.</param>
  67. /// <param name="end">The ending point of the segment.</param>
  68. public LineSegment(Vector2 start, Vector2 end)
  69. {
  70. Start = start;
  71. End = end;
  72. }
  73. #endregion
  74. #region Create From Methods
  75. /// <summary>
  76. /// Creates a line segment from a starting point, direction, and length.
  77. /// </summary>
  78. /// <param name="start">The starting point of the segment.</param>
  79. /// <param name="direction">The direction vector (will be normalized if non-zero).</param>
  80. /// <param name="length">The length of the segment.</param>
  81. /// <returns>A new line segment with the specified properties.</returns>
  82. public static LineSegment FromDirection(Vector2 start, Vector2 direction, float length)
  83. {
  84. Vector2 normalizedDir = direction;
  85. if (direction != Vector2.Zero)
  86. {
  87. normalizedDir.Normalize();
  88. }
  89. return new LineSegment(start, start + normalizedDir * length);
  90. }
  91. #endregion
  92. #region Intersection Methods
  93. /// <summary>
  94. /// Determines whether this line segment intersects with another line segment.
  95. /// </summary>
  96. /// <param name="other">The other line segment to test for intersection.</param>
  97. /// <returns>
  98. /// <see langword="true"/> if this line segment intersects the other; otherwise, <see langword="false"/>.
  99. /// </returns>
  100. public readonly bool Intersects(LineSegment other) => IntersectionTests.LineSegmentLineSegment(in this, in other);
  101. /// <summary>
  102. /// Determines whether this line segment intersects with a circle
  103. /// </summary>
  104. /// <param name="circle">The circle to test for intersection.</param>
  105. /// <returns>
  106. /// <see langword="true"/> if this line segment intersects the circle; otherwise, <see langword="false"/>.
  107. /// </returns>
  108. public readonly bool Intersects(Circle circle) => IntersectionTests.CirceLineSegment(in circle, in this);
  109. /// <summary>
  110. /// Determines whether this line segment intersects with an ellipse
  111. /// </summary>
  112. /// <param name="ellipse">The ellipse to test for intersection.</param>
  113. /// <returns>
  114. /// <see langword="true"/> if this line segment intersects the ellipse; otherwise, <see langword="false"/>.
  115. /// </returns>
  116. public readonly bool Intersects(Ellipse ellipse) => IntersectionTests.EllipseLineSegment(in ellipse, in this);
  117. /// <summary>
  118. /// Determines whether this line segment intersects with a rectangle
  119. /// </summary>
  120. /// <param name="rectangle">The rectangle to test for intersection.</param>
  121. /// <returns>
  122. /// <see langword="true"/> if this line segment intersects the rectangle; otherwise, <see langword="false"/>.
  123. /// </returns>
  124. public readonly bool Intersects(RectangleF rectangle) => IntersectionTests.RectangleFLineSegment(in rectangle, in this);
  125. /// <summary>
  126. /// Determines whether this line segment intersects with a ray
  127. /// </summary>
  128. /// <param name="ray">The ray to test for intersection.</param>
  129. /// <returns>
  130. /// <see langword="true"/> if this line segment intersects the ray; otherwise, <see langword="false"/>.
  131. /// </returns>
  132. public readonly bool Intersects(Ray ray) => IntersectionTests.RayLineSegment(in ray, in this);
  133. #endregion
  134. #region Closest Point To Methods
  135. /// <summary>
  136. /// Computes the closest point on the line segment to the specified point.
  137. /// </summary>
  138. /// <param name="point">The query point for closest-point computation.</param>
  139. /// <returns>The point on the segment closest to the query point.</returns>
  140. /// <remarks>
  141. /// This method projects the point onto the line defined by the segment, then clamps
  142. /// the result to the segment endpoints if necessary.
  143. /// </remarks>
  144. public readonly Vector2 ClosestPointTo(Vector2 point)
  145. {
  146. Vector2 ab = End - Start;
  147. float t = Vector2.Dot(point - Start, ab);
  148. if (t <= 0.0f)
  149. {
  150. // Point projects outside segment on the start side
  151. return Start;
  152. }
  153. float denom = Vector2.Dot(ab, ab);
  154. if (t >= denom)
  155. {
  156. // Point project outside segment on the end side
  157. return End;
  158. }
  159. // Point project inside segment
  160. return Start + ab * (t / denom);
  161. }
  162. /// <summary>
  163. /// Computes the closest point on the line segment to the specified point with parametric position.
  164. /// </summary>
  165. /// <param name="point">The query point for closest-point computation.</param>
  166. /// <param name="t">
  167. /// When this method returns, contains the parametric position (0 to 1) of the closest point along the segment,
  168. /// where 0 corresponds to the start point and 1 corresponds to the end point.
  169. /// </param>
  170. /// <returns>The point on the segment closest to the query point.</returns>
  171. public readonly Vector2 ClosestPointTo(Vector2 point, out float t)
  172. {
  173. Vector2 ab = End - Start;
  174. t = Vector2.Dot(point - Start, ab);
  175. if (t <= 0.0f)
  176. {
  177. // Point projects outside segment on the start side
  178. t = 0.0f;
  179. return Start;
  180. }
  181. float denom = Vector2.Dot(ab, ab);
  182. if (t >= denom)
  183. {
  184. // Point projects outside segment on the End side
  185. t = 1.0f;
  186. return End;
  187. }
  188. // Point projects inside segment
  189. t = t / denom;
  190. return Start + t * ab;
  191. }
  192. /// <summary>
  193. /// Computes the closest points between this segment and another segment.
  194. /// </summary>
  195. /// <param name="other">The other line segment to test against.</param>
  196. /// <param name="pointOnThis">When this method returns, contains the closest point on this segment.</param>
  197. /// <param name="pointOnOther">When this method returns, contains the closest point on the other segment.</param>
  198. /// <returns>The distance between the two closest points.</returns>
  199. public readonly float ClosestPoints(LineSegment other, out Vector2 pointOnThis, out Vector2 pointOnOther)
  200. {
  201. return ClosestPointsSegmentSegment(Start, End, other.Start, other.End, out _, out _, out pointOnThis, out pointOnOther);
  202. }
  203. /// <summary>
  204. /// Computes the closest points between two line segments.
  205. /// </summary>
  206. /// <param name="p1">The start point of the first segment.</param>
  207. /// <param name="q1">The end point of the first segment.</param>
  208. /// <param name="p2">The start point of the second segment.</param>
  209. /// <param name="q2">The end point of the second segment.</param>
  210. /// <param name="s">When this method returns, contains the parametric position on the first segment.</param>
  211. /// <param name="t">When this method returns, contains the parametric position on the second segment.</param>
  212. /// <param name="c1">When this method returns, contains the closest point on the first segment.</param>
  213. /// <param name="c2">When this method returns, contains the closest point on the second segment.</param>
  214. /// <returns>The distance between the closest points.</returns>
  215. private static float ClosestPointsSegmentSegment(Vector2 p1, Vector2 q1, Vector2 p2, Vector2 q2, out float s, out float t, out Vector2 c1, out Vector2 c2)
  216. {
  217. // Direction vector of segment S1
  218. Vector2 d1 = q1 - p1;
  219. // Direction vector of segment S2
  220. Vector2 d2 = q2 - p2;
  221. Vector2 r = p1 - p2;
  222. // Squared length of segment S1
  223. float a = Vector2.Dot(d1, d1);
  224. // Squared length of segment S2
  225. float e = Vector2.Dot(d2, d2);
  226. float f = Vector2.Dot(d2, r);
  227. // Check if either or both segments degenerate into points
  228. if (a <= 0.001f && e <= 0.001f)
  229. {
  230. // Both segments degenerate into points
  231. s = t = 0.0f;
  232. c1 = p1;
  233. c2 = p2;
  234. return Vector2.Distance(c1, c2);
  235. }
  236. if (a <= 0.001f)
  237. {
  238. // First segment degenerates into a point
  239. s = 0.0f;
  240. t = f / e;
  241. t = Math.Clamp(t, 0.0f, 1.0f);
  242. }
  243. else
  244. {
  245. float c = Vector2.Dot(d1, r);
  246. if (e <= 0.001f)
  247. {
  248. // second segment degenerates into a point
  249. t = 0.0f;
  250. s = Math.Clamp(-c / a, 0.0f, 1.0f);
  251. }
  252. else
  253. {
  254. // The general non-degenerate case starts here
  255. float b = Vector2.Dot(d1, d2);
  256. float denom = a * e - b * b;
  257. // If segments not parallel, compute closest point on L1 to L2
  258. if (denom != 0.0f)
  259. {
  260. s = Math.Clamp((b * f - c * e) / denom, 0.0f, 1.0f);
  261. }
  262. else
  263. {
  264. // Parallel segments - pick arbitrary s
  265. s = 0.0f;
  266. }
  267. // Compute point on L2 closest to S1(s)
  268. t = (b * s + f) / e;
  269. // If t in [0,1] done. Else clamp t, recompute s
  270. if (t < 0.0f)
  271. {
  272. t = 0.0f;
  273. s = Math.Clamp(-c / a, 0.0f, 1.0f);
  274. }
  275. else if (t > 1.0f)
  276. {
  277. t = 1.0f;
  278. s = Math.Clamp((b - c) / a, 0.0f, 1.0f);
  279. }
  280. }
  281. }
  282. c1 = p1 + d1 * s;
  283. c2 = p2 + d2 * t;
  284. return Vector2.Distance(c1, c2);
  285. }
  286. /// <summary>
  287. /// Computes the point on the segment at the specified parametric position.
  288. /// </summary>
  289. /// <param name="t">
  290. /// The parametric position along the segment, where 0 returns <see cref="Start"/>
  291. /// and 1 returns <see cref="End"/>. Values outside [0,1] extrapolate beyond the segment.
  292. /// </param>
  293. /// <returns>The point at position t along the segment.</returns>
  294. public readonly Vector2 GetPointAt(float t)
  295. {
  296. return Start + t * (End - Start);
  297. }
  298. #endregion
  299. #region Distance Methods
  300. /// <summary>
  301. /// Computes the shortest distance from the line segment to the specified point.
  302. /// </summary>
  303. /// <param name="point">The point to measure distance to.</param>
  304. /// <returns>The shortest distance from the segment to the point.</returns>
  305. public readonly float DistanceTo(Vector2 point)
  306. {
  307. return MathF.Sqrt(DistanceSquaredTo(point));
  308. }
  309. /// <summary>
  310. /// Computes the squared shortest distance from the line segment to the specified point.
  311. /// </summary>
  312. /// <param name="point">The point to measure distance to.</param>
  313. /// <returns>The squared shortest distance from the segment to the point.</returns>
  314. /// <remarks>
  315. /// This method is more efficient than <see cref="DistanceTo(Vector2)"/> as it avoids the expensive square root
  316. /// operation.
  317. /// </remarks>
  318. public readonly float DistanceSquaredTo(Vector2 point)
  319. {
  320. Vector2 ab = End - Start;
  321. Vector2 ac = point - Start;
  322. Vector2 bc = point - End;
  323. float e = Vector2.Dot(ac, ab);
  324. // Point projects outside the segment on the start side
  325. if (e <= 0.0f)
  326. {
  327. return Vector2.Dot(ac, ac);
  328. }
  329. float f = Vector2.Dot(ab, ab);
  330. // Point projects outside the segment on the end side
  331. if (e >= f)
  332. {
  333. return Vector2.Dot(bc, bc);
  334. }
  335. // Point projects inside the segment
  336. return Vector2.Dot(ac, ac) - e * e / f;
  337. }
  338. #endregion
  339. #region Offset Methods
  340. /// <summary>
  341. /// Translates the line segment by moving both endpoints, preserving direction and length.
  342. /// </summary>
  343. /// <param name="offset">The translation vector to apply to both endpoints.</param>
  344. public void Offset(Vector2 offset)
  345. {
  346. Start += offset;
  347. End += offset;
  348. }
  349. /// <summary>
  350. /// Creates a new line segment translated by the specified offset vector.
  351. /// </summary>
  352. /// <param name="lineSegment">The line segment to translate.</param>
  353. /// <param name="offset">The translation vector to apply.</param>
  354. /// <returns>A new line segment with both endpoints translated.</returns>
  355. public static LineSegment Offset(LineSegment lineSegment, Vector2 offset)
  356. {
  357. return lineSegment with { Start = lineSegment.Start + offset, End = lineSegment.End + offset };
  358. }
  359. #endregion
  360. #region Transform Methods
  361. /// <summary>
  362. /// Applies a 2D transformation matrix to the line segment, transforming both endpoints.
  363. /// </summary>
  364. /// <param name="matrix">The transformation matrix to apply.</param>
  365. public void Transform(Matrix3x2 matrix)
  366. {
  367. Transform(ref matrix);
  368. }
  369. /// <summary>
  370. /// Applies a 2D transformation matrix to the line segment, transforming both endpoints.
  371. /// </summary>
  372. /// <param name="matrix">The transformation matrix to apply.</param>
  373. public void Transform(ref Matrix3x2 matrix)
  374. {
  375. Start = Vector2.Transform(Start, matrix);
  376. End = Vector2.Transform(End, matrix);
  377. }
  378. /// <summary>
  379. /// Creates a new line segment by applying a 2D transformation matrix.
  380. /// </summary>
  381. /// <param name="lineSegment">The line segment to transform.</param>
  382. /// <param name="matrix">The transformation matrix to apply.</param>
  383. /// <returns>A new transformed line segment.</returns>
  384. public static LineSegment Transform(LineSegment lineSegment, Matrix3x2 matrix)
  385. {
  386. return Transform(lineSegment, ref matrix);
  387. }
  388. /// <summary>
  389. /// Computes a transformed line segment using reference parameters for performance.
  390. /// </summary>
  391. /// <param name="lineSegment">The line segment to transform.</param>
  392. /// <param name="matrix">The transformation matrix to apply.</param>
  393. public static LineSegment Transform(LineSegment lineSegment, ref Matrix3x2 matrix)
  394. {
  395. return lineSegment with { Start = Vector2.Transform(lineSegment.Start, matrix), End = Vector2.Transform(lineSegment.End, matrix) };
  396. }
  397. #endregion
  398. #region Equality Methods
  399. /// <summary>
  400. /// Determines whether this line segment is equal to the specified object.
  401. /// </summary>
  402. /// <param name="obj">The object to compare.</param>
  403. /// <returns>
  404. /// <c>true</c> if the object is a <see cref="LineSegment"/> with the same start and end; otherwise, <c>false</c>.
  405. /// </returns>
  406. public override readonly bool Equals([NotNullWhen(true)] object obj)
  407. {
  408. return obj is LineSegment other && Equals(other);
  409. }
  410. /// <summary>
  411. /// Determines whether this line segment is equal to another line segment.
  412. /// </summary>
  413. /// <param name="other">The line segment to compare with this line segment.</param>
  414. /// <returns>
  415. /// <c>true</c> if the line segments have the same start and end; otherwise, <c>false</c>.
  416. /// </returns>
  417. public readonly bool Equals(LineSegment other)
  418. {
  419. return Equals(other);
  420. }
  421. #endregion
  422. /// <summary>
  423. /// Computes the hash code for this line segment.
  424. /// </summary>
  425. /// <returns>A hash code derived from the start and end points.</returns>
  426. public override readonly int GetHashCode()
  427. {
  428. return HashCode.Combine(Start, End);
  429. }
  430. /// <summary>
  431. /// Creates a string representation of this line segment.
  432. /// </summary>
  433. /// <returns>A formatted string containing the start and end points.</returns>
  434. public override readonly string ToString()
  435. {
  436. return $"LineSegment({Start} - {End})";
  437. }
  438. internal readonly string DebugDisplayString => ToString();
  439. #region Operators
  440. /// <summary>
  441. /// Tests whether two line segments are equal.
  442. /// </summary>
  443. /// <param name="left">The first line segment.</param>
  444. /// <param name="right">The second line segment.</param>
  445. /// <returns><c>true</c> if both line segments have the same start and end; otherwise, <c>false</c>.</returns>
  446. public static bool operator ==(LineSegment left, LineSegment right)
  447. {
  448. return left.Equals(right);
  449. }
  450. /// <summary>
  451. /// Tests whether two line segments are not equal.
  452. /// </summary>
  453. /// <param name="left">The first line segment.</param>
  454. /// <param name="right">The second line segment.</param>
  455. /// <returns><c>true</c> if the line segments have different start or end points; otherwise, <c>false</c>.</returns>
  456. public static bool operator !=(LineSegment left, LineSegment right)
  457. {
  458. return !left.Equals(right);
  459. }
  460. #endregion
  461. }