Line2D.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. // Copyright (c) Craftwork Games. All rights reserved.
  2. // Licensed under the MIT license.
  3. // See LICENSE file in the project root for full license information.
  4. using System;
  5. using System.Diagnostics;
  6. using System.Runtime.Serialization;
  7. using Microsoft.Xna.Framework;
  8. namespace MonoGame.Extended
  9. {
  10. /// <summary>
  11. /// Represents an infinite line in 2D space that extends in both directions without bounds.
  12. /// </summary>
  13. [DataContract]
  14. [DebuggerDisplay("{DebugDisplayString,nq}")]
  15. public struct Line2D : IEquatable<Line2D>
  16. {
  17. #region Public Fields
  18. /// <summary>
  19. /// The signed perpendicular distance from the origin to this line along its normal direction.
  20. /// Positive values indicate the origin is on the opposite side of the line from the normal.
  21. /// </summary>
  22. [DataMember]
  23. public float Distance;
  24. /// <summary>
  25. /// The unit normal vector perpendicular to this line, used with <see cref="Distance"/>
  26. /// to define the line's position and orientation.
  27. /// </summary>
  28. [DataMember]
  29. public Vector2 Normal;
  30. #endregion
  31. #region Internal Properties
  32. internal readonly string DebugDisplayString
  33. {
  34. get
  35. {
  36. return string.Concat(
  37. "Normal( ", Normal.ToString(), " ) \r\n",
  38. "Distance( ", Distance.ToString(), " )"
  39. );
  40. }
  41. }
  42. #endregion
  43. #region Public Constructors
  44. /// <summary>
  45. /// Creates a new <see cref="Line2D"/> with the specified normal and distance from the origin.
  46. /// </summary>
  47. /// <param name="normal">The unit normal vector perpendicular to the line.</param>
  48. /// <param name="distance">The perpendicular distance from the origin to the line along its normal direction.</param>
  49. public Line2D(Vector2 normal, float distance)
  50. {
  51. Normal = normal;
  52. Distance = distance;
  53. }
  54. #endregion
  55. #region Public Methods
  56. /// <summary>
  57. /// Creates a <see cref="Line2D"/> that passes through a specified point with a given normal direction.
  58. /// </summary>
  59. /// <param name="point">A point in 2D space that the line passes through.</param>
  60. /// <param name="normal">
  61. /// The normal vector perpendicular to the line. This vector will be normalized automatically.
  62. /// </param>
  63. /// <returns>
  64. /// A new <see cref="Line2D"/> with a unit normal passing through the specified point.
  65. /// </returns>
  66. public static Line2D CreateFromPointAndNormal(Vector2 point, Vector2 normal)
  67. {
  68. Vector2 n = Vector2.Normalize(normal);
  69. float d = Vector2.Dot(n, point);
  70. return new Line2D(n, d);
  71. }
  72. /// <summary>
  73. /// Creates a <see cref="Line2D"/> that passes through two specified points.
  74. /// </summary>
  75. /// <param name="p1">The first point in 2D space.</param>
  76. /// <param name="p2">The second point in 2D space, must be distinct from the first.</param>
  77. /// <returns>
  78. /// A new <see cref="Line2D"/> passing through both points. The line's normal is oriented
  79. /// 90 degrees counter-clockwise from the direction vector p1 to p2.
  80. /// </returns>
  81. /// <exception cref="ArgumentException">
  82. /// Thrown when the two points are too close to define a unique line.
  83. /// </exception>
  84. public static Line2D CreateFromTwoPoints(Vector2 p1, Vector2 p2)
  85. {
  86. Vector2 direction = p2 - p1;
  87. float lengthSquared = direction.LengthSquared();
  88. if (lengthSquared < Collision2D.Epsilon * Collision2D.Epsilon)
  89. {
  90. throw new ArgumentException("Points must be distinct to define a line.");
  91. }
  92. // Normal is perpendicular to direction (rotate 90deg CCW)
  93. Vector2 normal = new Vector2(-direction.Y, direction.X);
  94. return CreateFromPointAndNormal(p1, normal);
  95. }
  96. /// <summary>
  97. /// Creates a <see cref="Line2D"/> that passes through a specified point and extends in a given direction.
  98. /// </summary>
  99. /// <param name="point">A point in 2D space that the line passes through.</param>
  100. /// <param name="direction">
  101. /// The direction vector the line extends along. This vector will be normalized automatically.
  102. /// </param>
  103. /// <returns>
  104. /// A new <see cref="Line2D"/> with a unit normal perpendicular to the direction, passing through the specified point.
  105. /// </returns>
  106. public static Line2D CreateFromPointAndDirection(Vector2 point, Vector2 direction)
  107. {
  108. // Normal is perpendicular to direction (rotate 90deg CCW)
  109. Vector2 normal = Vector2.Normalize(new Vector2(-direction.Y, direction.X));
  110. float distance = Vector2.Dot(normal, point);
  111. return new Line2D(normal, distance);
  112. }
  113. /// <summary>
  114. /// Computes the signed perpendicular distance from a point to this line.
  115. /// </summary>
  116. /// <param name="point">The point in 2D space to measure from.</param>
  117. /// <returns>
  118. /// The signed distance from the point to the line. Positive values indicate the point is on
  119. /// the same side as the normal vector, negative values indicate the opposite side, and zero
  120. /// indicates the point lies on the line.
  121. /// </returns>
  122. public readonly float DistanceToPoint(Vector2 point)
  123. {
  124. // C. Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005
  125. // Section 5.1.1 "Closest Point on Plane To Point"
  126. // Adapted from 3D plane to 2D line using implicit line equation
  127. return Vector2.Dot(Normal, point) - Distance;
  128. }
  129. /// <summary>
  130. /// Computes the closest point on this line to a specified point.
  131. /// </summary>
  132. /// <param name="point">The point in 2D space to project onto the line.</param>
  133. /// <param name="distanceAlongLine">
  134. /// When this method returns, contains the parametric distance along the line's direction vector
  135. /// to the closest point, where <c>distanceAlongLine = 0</c> corresponds to the point on the line
  136. /// closest to the origin.
  137. /// </param>
  138. /// <returns>
  139. /// The point on the line closest to the specified point, computed as the perpendicular projection
  140. /// of the point onto the line.
  141. /// </returns>
  142. public readonly Vector2 ClosestPoint(Vector2 point, out float distanceAlongLine)
  143. {
  144. // C. Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005
  145. // Section 5.1.2 "Closest Point on Line Segment to Point"
  146. // Applied to an infinite line (no clamping of t), as described by Ericson.
  147. // This line is represented in implicit form:
  148. // Dot(Normal, X) = Distance
  149. // We need to calculate X, as any point X that satisfies this
  150. // equation lies on the line.
  151. Vector2 n = Normal;
  152. float nn = Vector2.Dot(n, n);
  153. if (nn <= Collision2D.Epsilon)
  154. {
  155. // Degenerate line, normal has no meaningful direction
  156. // Treat line as a single point
  157. distanceAlongLine = 0.0f;
  158. return Vector2.Zero;
  159. }
  160. // Compute a specific point 'a' on the line by scaling the normal.
  161. // Since Dot(n, n * (Distance / Dot(N, n))) = Distance
  162. // this point satisfies the line equation
  163. Vector2 a = n * (Distance / nn);
  164. // Compute a direction vector 'ab' that lies along the line.
  165. // In 2D a direction perpendicular to the normal is given by (-n.Y, n.X)
  166. Vector2 ab = new Vector2(-n.Y, n.X);
  167. float denom = Vector2.Dot(ab, ab);
  168. distanceAlongLine = Vector2.Dot(point - a, ab);
  169. distanceAlongLine /= denom;
  170. return a + distanceAlongLine * ab;
  171. }
  172. /// <summary>
  173. /// Returns a normalized representation of the specified line with a unit normal vector.
  174. /// </summary>
  175. /// <param name="line">The line to normalize.</param>
  176. /// <returns>
  177. /// A new <see cref="Line2D"/> representing the same geometric line with a unit normal vector.
  178. /// </returns>
  179. public static Line2D Normalize(Line2D line)
  180. {
  181. Line2D result;
  182. Normalize(ref line, out result);
  183. return result;
  184. }
  185. /// <summary>
  186. /// Returns a normalized representation of the specified line with a unit normal vector.
  187. /// </summary>
  188. /// <param name="value">The line to normalize.</param>
  189. /// <param name="result">
  190. /// When this method returns, contains a <see cref="Line2D"/> representing the same geometric line
  191. /// with a unit normal vector and proportionally adjusted distance.
  192. /// </param>
  193. public static void Normalize(ref Line2D value, out Line2D result)
  194. {
  195. float length = value.Normal.Length();
  196. if (length < Collision2D.Epsilon)
  197. {
  198. result = value;
  199. return;
  200. }
  201. result = new Line2D(value.Normal / length, value.Distance / length);
  202. }
  203. /// <summary>
  204. /// Normalizes this line's representation by ensuring the normal vector has unit length.
  205. /// </summary>
  206. /// <remarks>
  207. /// After normalization, the <see cref="Normal"/> will be a unit vector and <see cref="Distance"/>
  208. /// will be adjusted proportionally to maintain the same geometric line.
  209. /// </remarks>
  210. public void Normalize()
  211. {
  212. float length = Normal.Length();
  213. if (length > Collision2D.Epsilon)
  214. {
  215. Normal /= length;
  216. Distance /= length;
  217. }
  218. }
  219. /// <summary>
  220. /// Tests if this line intersects with another line.
  221. /// </summary>
  222. /// <param name="other">The other line to test against.</param>
  223. /// <param name="point">
  224. /// When this method returns <see langword="true"/>, contains the point where the lines intersect.
  225. /// When this method returns <see langword="false"/>, contains <see langword="null"/> indicating
  226. /// the lines are parallel or coincident.
  227. /// </param>
  228. /// <returns>
  229. /// <see langword="true"/> if the lines intersect at a single point; otherwise, <see langword="false"/>
  230. /// if the lines are parallel or coincident.
  231. /// </returns>
  232. public readonly bool Intersects(Line2D other, out Vector2? point)
  233. {
  234. // Use implicit line representation and Cramer's rule
  235. // to solve a 2D line-line intersection
  236. // Check if lines are parallel
  237. float cross = Normal.X * other.Normal.Y - Normal.Y * other.Normal.X;
  238. if (MathF.Abs(cross) < Collision2D.Epsilon)
  239. {
  240. // Lines are parallel or coincident
  241. point = null;
  242. return false;
  243. }
  244. float x = (Distance * other.Normal.Y - other.Distance * Normal.Y) / cross;
  245. float y = (other.Distance * Normal.X - Distance * other.Normal.X) / cross;
  246. point = new Vector2(x, y);
  247. return true;
  248. }
  249. /// <summary>
  250. /// Tests if this line intersects with another line.
  251. /// </summary>
  252. /// <param name="other">The other line to test against.</param>
  253. /// <returns>
  254. /// <see langword="true"/> if the lines intersect at a single point; otherwise, <see langword="false"/>
  255. /// if the lines are parallel or coincident.
  256. /// </returns>
  257. public readonly bool Intersects(Line2D other)
  258. {
  259. return Intersects(other, out _);
  260. }
  261. /// <summary>
  262. /// Tests if this line intersects with a ray.
  263. /// </summary>
  264. /// <param name="ray">The ray to test against.</param>
  265. /// <param name="distanceAlongRay">
  266. /// When this method returns <see langword="true"/>, contains the parametric distance along the ray
  267. /// to the intersection point.
  268. /// When this method returns <see langword="false"/>, contains <see langword="null"/>.
  269. /// </param>
  270. /// <param name="point">
  271. /// When this method returns <see langword="true"/>, contains the point where the line and ray intersect.
  272. /// When this method returns <see langword="false"/>, contains <see langword="null"/>.
  273. /// </param>
  274. /// <returns>
  275. /// <see langword="true"/> if the line and ray intersect in the ray's forward direction;
  276. /// otherwise, <see langword="false"/> if they are parallel or the intersection point is behind the ray's origin.
  277. /// </returns>
  278. public readonly bool Intersects(Ray2D ray, out float? distanceAlongRay, out Vector2? point)
  279. {
  280. if (!Collision2D.SolveParametricIntersectionWithImplicitLine(Normal, Distance, ray.Origin, ray.Direction, out float t))
  281. {
  282. // Parallel or coincident
  283. distanceAlongRay = null;
  284. point = null;
  285. return false;
  286. }
  287. // Ray only intersects in forward direction
  288. if (t < 0.0f)
  289. {
  290. distanceAlongRay = null;
  291. point = null;
  292. return false;
  293. }
  294. distanceAlongRay = t;
  295. point = ray.Origin + t * ray.Direction;
  296. return true;
  297. }
  298. /// <summary>
  299. /// Tests if this line intersects with a ray.
  300. /// </summary>
  301. /// <param name="ray">The ray to test against.</param>
  302. /// <returns>
  303. /// <see langword="true"/> if the line and ray intersect in the ray's forward direction;
  304. /// otherwise, <see langword="false"/> if they are parallel or the intersection point is behind the ray's origin.
  305. /// </returns>
  306. public readonly bool Intersects(Ray2D ray)
  307. {
  308. return Intersects(ray, out _, out _);
  309. }
  310. /// <summary>
  311. /// Tests if this line intersects with a line segment.
  312. /// </summary>
  313. /// <param name="segment">The line segment to test against.</param>
  314. /// <param name="distanceAlongSegment">
  315. /// When this method returns <see langword="true"/>, contains the parametric distance along the segment
  316. /// to the intersection point, in the range [0, 1] where 0 represents the start and 1 represents the end.
  317. /// When this method returns <see langword="false"/>, contains <see langword="null"/>.
  318. /// </param>
  319. /// <param name="point">
  320. /// When this method returns <see langword="true"/>, contains the point where the line and segment intersect.
  321. /// When this method returns <see langword="false"/>, contains <see langword="null"/>.
  322. /// </param>
  323. /// <returns>
  324. /// <see langword="true"/> if the line intersects the segment within its bounds;
  325. /// otherwise, <see langword="false"/> if they are parallel or the intersection point lies outside the segment.
  326. /// </returns>
  327. public readonly bool Intersects(LineSegment2D segment, out float? distanceAlongSegment, out Vector2? point)
  328. {
  329. Vector2 ab = segment.End - segment.Start;
  330. if (!Collision2D.SolveParametricIntersectionWithImplicitLine(Normal, Distance, segment.Start, ab, out float t))
  331. {
  332. distanceAlongSegment = null;
  333. point = null;
  334. return false;
  335. }
  336. // Check if the intersection is within the segment bounds
  337. if (t < 0.0f || t > 1.0f)
  338. {
  339. distanceAlongSegment = null;
  340. point = null;
  341. return false;
  342. }
  343. distanceAlongSegment = t;
  344. point = segment.Start + t * ab;
  345. return true;
  346. }
  347. /// <summary>
  348. /// Tests if this line intersects with a line segment.
  349. /// </summary>
  350. /// <param name="segment">The line segment to test against.</param>
  351. /// <returns>
  352. /// <see langword="true"/> if the line intersects the segment within its bounds;
  353. /// otherwise, <see langword="false"/> if they are parallel or the intersection point lies outside the segment.
  354. /// </returns>
  355. public readonly bool Intersects(LineSegment2D segment)
  356. {
  357. return Intersects(segment, out _, out _);
  358. }
  359. /// <summary>
  360. /// Tests if this line intersects with an axis-aligned bounding box.
  361. /// </summary>
  362. /// <param name="box">The bounding box to test against.</param>
  363. /// <returns>
  364. /// <see langword="true"/> if the line passes through or touches the bounding box;
  365. /// otherwise, <see langword="false"/>.
  366. /// </returns>
  367. public readonly bool Intersects(BoundingBox2D box)
  368. {
  369. Vector2 n = Normal;
  370. float nn = Vector2.Dot(n, n);
  371. // Check for degenerate line
  372. if(nn <= Collision2D.Epsilon * Collision2D.Epsilon)
  373. return false;
  374. // Point on the line: a = n * (d / Dot(n,n))
  375. Vector2 origin = n * (Distance / nn);
  376. // Direction along the line (perpendicular to normal)
  377. Vector2 dir = new Vector2(-n.Y, n.X);
  378. return Collision2D.ClipLineToAabb(origin, dir, box.Min, box.Max, float.MinValue, float.MaxValue, out _, out _);
  379. }
  380. /// <summary>
  381. /// Tests if this line intersects with a circle.
  382. /// </summary>
  383. /// <param name="circle">The circle to test against.</param>
  384. /// <returns>
  385. /// <see langword="true"/> if the line passes through or is tangent to the circle;
  386. /// otherwise, <see langword="false"/>.
  387. /// </returns>
  388. public readonly bool Intersects(BoundingCircle2D circle)
  389. {
  390. // C. Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005
  391. // Distance‑based intersection of implicit line with circle
  392. // Derived from Section 5.2.2 "Testing Sphere Against Plane" (2D reduction)
  393. // Compute signed distance from circle center to line
  394. float signedDist = DistanceToPoint(circle.Center);
  395. // Line intersects circle if perpendicular distance is within radius
  396. return MathF.Abs(signedDist) <= circle.Radius;
  397. }
  398. /// <summary>
  399. /// Tests if this line intersects with a capsule.
  400. /// </summary>
  401. /// <param name="capsule">The capsule to test against.</param>
  402. /// <returns>
  403. /// <see langword="true"/> if the line passes through or is tangent to the capsule;
  404. /// otherwise, <see langword="false"/>.
  405. /// </returns>
  406. public readonly bool Intersects(BoundingCapsule2D capsule)
  407. {
  408. // C. Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005
  409. // Intersection of an implicit line with a 2D capsule (line segment swept by a circle)
  410. // Derived from Section 4.5.1 "Sphere-swept Volume Intersection" and Section 5.2.2 "Testing Sphere Against Plane"
  411. // Compute signed distance to capsule endpoints
  412. float signedDistA = DistanceToPoint(capsule.PointA);
  413. float signedDistB = DistanceToPoint(capsule.PointB);
  414. // Get absolute distances for comparison
  415. float distToA = MathF.Abs(signedDistA);
  416. float distToB = MathF.Abs(signedDistB);
  417. // minimum distance starts as the closer of the two end points
  418. float minDistSq = MathF.Min(distToA * distToA, distToB * distToB);
  419. // Check if capsule's medial segment is not degenerate
  420. Vector2 segmentDir = capsule.PointB - capsule.PointA;
  421. float segmentLenSq = segmentDir.LengthSquared();
  422. if (segmentLenSq > Collision2D.Epsilon * Collision2D.Epsilon)
  423. {
  424. // If endpoints are on opposite sides of the line, the segment crosses it
  425. if (signedDistA * signedDistB <= 0.0f)
  426. {
  427. minDistSq = 0.0f;
  428. }
  429. }
  430. // Line intersects capsule if minimum distance is within radius
  431. return minDistSq <= capsule.Radius * capsule.Radius;
  432. }
  433. /// <summary>
  434. /// Tests if this line intersects with an oriented bounding box.
  435. /// </summary>
  436. /// <param name="obb">The oriented bounding box to test against.</param>
  437. /// <returns>
  438. /// <see langword="true"/> if the line passes through or touches the box;
  439. /// otherwise, <see langword="false"/>.
  440. /// </returns>
  441. public readonly bool Intersects(OrientedBoundingBox2D obb)
  442. {
  443. Vector2 n = Normal;
  444. float nn = Vector2.Dot(n, n);
  445. // Handle degenerate line
  446. if(nn <= Collision2D.Epsilon * Collision2D.Epsilon)
  447. return false;
  448. // Get a world space point and direction for the line
  449. Vector2 a = n * (Distance / nn);
  450. Vector2 dir = new Vector2(-n.Y, n.X);
  451. // Transform line into OBB local space
  452. Vector2 diff = a - obb.Center;
  453. Vector2 localOrigin = new Vector2(Vector2.Dot(diff, obb.AxisX), Vector2.Dot(diff, obb.AxisY));
  454. Vector2 localDirection = new Vector2(Vector2.Dot(dir, obb.AxisX), Vector2.Dot(dir, obb.AxisY));
  455. // Local OBB is just ABB [-halfExtents, +halfExtents]
  456. return Collision2D.ClipLineToAabb(localOrigin, localDirection, -obb.HalfExtents, obb.HalfExtents, float.MinValue, float.MaxValue, out _, out _);
  457. }
  458. /// <summary>
  459. /// Tests if this line intersects with a polygon.
  460. /// </summary>
  461. /// <param name="polygon">The polygon to test against.</param>
  462. /// <returns>
  463. /// <see langword="true"/> if the line passes through or is tangent to the polygon;
  464. /// otherwise, <see langword="false"/>.
  465. /// </returns>
  466. public readonly bool Intersects(BoundingPolygon2D polygon)
  467. {
  468. Vector2 n = Normal;
  469. float nn = Vector2.Dot(n, n);
  470. // Check for degenerate line
  471. if(nn <= Collision2D.Epsilon * Collision2D.Epsilon)
  472. return false;
  473. // A point on the line: a = n * (d / Dot(n,n))
  474. Vector2 a = n * (Distance / nn);
  475. // A direction along the line (perpendicular to n)
  476. Vector2 dir = new Vector2(-n.Y, n.X);
  477. // Clip infinite line against polygon half-spaces
  478. return Collision2D.ClipLineToConvexPolygon(a, dir, polygon.Vertices, polygon.Normals, float.MinValue, float.MaxValue, out _, out _);
  479. }
  480. /// <summary>
  481. /// Deconstructs this line into its component values.
  482. /// </summary>
  483. /// <param name="normal">
  484. /// When this method returns, contains the unit normal vector perpendicular to this line.
  485. /// </param>
  486. /// <param name="distance">
  487. /// When this method returns, contains the signed perpendicular distance from the origin
  488. /// to this line along its normal direction.
  489. /// </param>
  490. public readonly void Deconstruct(out Vector2 normal, out float distance)
  491. {
  492. normal = Normal;
  493. distance = Distance;
  494. }
  495. /// <inheritdoc/>
  496. public readonly bool Equals(Line2D other)
  497. {
  498. return Normal.Equals(other.Normal)
  499. && Math.Abs(Distance - other.Distance) < Collision2D.Epsilon;
  500. }
  501. /// <inheritdoc/>
  502. public override readonly bool Equals(object obj)
  503. {
  504. return obj is Line2D other && Equals(other);
  505. }
  506. /// <inheritdoc/>
  507. public override readonly int GetHashCode()
  508. {
  509. return Normal.GetHashCode() ^ Distance.GetHashCode();
  510. }
  511. /// <inheritdoc/>
  512. public override readonly string ToString()
  513. {
  514. return "{Normal:" + Normal.ToString() + " Distance:" + Distance.ToString() + "}";
  515. }
  516. /// <summary/>
  517. public static bool operator ==(Line2D left, Line2D right)
  518. {
  519. return left.Equals(right);
  520. }
  521. /// <summary/>
  522. public static bool operator !=(Line2D left, Line2D right)
  523. {
  524. return !left.Equals(right);
  525. }
  526. #endregion
  527. }
  528. }