Circle.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Runtime.Serialization;
  6. using Microsoft.Xna.Framework;
  7. namespace MonoGame.Extended;
  8. /// <summary>
  9. /// Represents a circular bounding volume in 2D space defined by a center point and radius.
  10. /// </summary>
  11. [DataContract]
  12. [DebuggerDisplay("{DebugDisplayString,nq}")]
  13. public struct Circle : IEquatable<Circle>
  14. {
  15. #region Fields
  16. private static Circle s_empty = new Circle(Vector2.Zero, 0.0f);
  17. /// <summary>
  18. /// The center position of the circular bounding volume.
  19. /// </summary>
  20. [DataMember]
  21. public Vector2 Center;
  22. /// <summary>
  23. /// The radius defining the circular boundary, measured as the distance from the center to any point on
  24. /// the perimeter.
  25. /// </summary>
  26. [DataMember]
  27. public float Radius;
  28. #endregion
  29. #region Properties
  30. /// <summary>
  31. /// Gets an empty circle representing a degenerate case with zero radius.
  32. /// </summary>
  33. public static Circle Empty => s_empty;
  34. /// <summary>
  35. /// Gets a value indicating whether this circle represents a degenerate case with no area, having zero
  36. /// or negative radius.
  37. /// </summary>
  38. public readonly bool IsEmpty => Radius <= 0.0f;
  39. /// <summary>
  40. /// Gets the diameter of the circle, representing the width across the center.
  41. /// </summary>
  42. public readonly float Diameter => Radius * 2.0f;
  43. /// <summary>
  44. /// Gets the circumference (perimeter) of the circle, representing the total distance around the circular boundary.
  45. /// </summary>
  46. public readonly float Circumference => MathHelper.TwoPi * Radius;
  47. /// <summary>
  48. /// Gets the area enclosed by the circular boundary, representing the total space within the circle.
  49. /// </summary>
  50. public readonly float Area => MathHelper.Pi * Radius * Radius;
  51. #endregion
  52. #region Constructors
  53. /// <summary>
  54. /// Initializes a new circle with the specified center and radius.
  55. /// </summary>
  56. /// <param name="center">The center position of the circle.</param>
  57. /// <param name="radius">The radius defining the circular boundary.</param>
  58. public Circle(Vector2 center, float radius)
  59. {
  60. Center = center;
  61. Radius = radius;
  62. }
  63. /// <summary>
  64. /// Initializes a new circle with the specified center coordinates and radius.
  65. /// </summary>
  66. /// <param name="x">The X coordinate of the center position.</param>
  67. /// <param name="y">The Y coordinate of the center position.</param>
  68. /// <param name="radius">The radius defining the circular boundary.</param>
  69. public Circle(float x, float y, float radius)
  70. {
  71. Center = new Vector2(x, y);
  72. Radius = radius;
  73. }
  74. #endregion
  75. #region Create From Methods
  76. /// <summary>
  77. /// Creates a circle that circumscribes the rectangular region defined by two corner points.
  78. /// </summary>
  79. /// <param name="minimum">The minimum corner coordinates (typically top-left).</param>
  80. /// <param name="maximum">The maximum corner coordinates (typically bottom-right).</param>
  81. /// <returns>A circle centered at the midpoint with radius equal to half the larger dimension of the bounding rectangle.</returns>
  82. /// <remarks>
  83. /// The circle is guaranteed to contain the entire rectangular region defined by the corner points.
  84. /// </remarks>
  85. public static Circle CreateFrom(Vector2 minimum, Vector2 maximum)
  86. {
  87. Vector2 center = new Vector2(maximum.X + minimum.X, maximum.Y + minimum.Y) * 0.5f;
  88. Vector2 distance = maximum - minimum;
  89. float radius = distance.X > distance.Y
  90. ? distance.X * 0.5f
  91. : distance.Y * 0.5f;
  92. return new Circle(center, radius);
  93. }
  94. /// <summary>
  95. /// Creates the smallest circle that contains all specified points using a centroid-based approximation.
  96. /// </summary>
  97. /// <param name="points">The collection of points to enclose.</param>
  98. /// <returns>A circle centered at the centroid of all points with radius extending to the farthest point, or <see cref="Empty"/> if no points are provided.</returns>
  99. /// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is null.</exception>
  100. /// <remarks>
  101. /// This method uses a simple but effective approximation algorithm that computes the centroid (arithmetic mean)
  102. /// of all points and sets the radius to the distance from the centroid to the farthest point. While this does
  103. /// not guarantee the mathematically smallest enclosing circle, it provides a good approximation with O(n) time complexity.
  104. /// </remarks>
  105. public static Circle CreateFrom(IReadOnlyList<Vector2> points)
  106. {
  107. if (points == null || points.Count == 0)
  108. {
  109. return Empty;
  110. }
  111. RectangleF bounds = RectangleF.CreateFrom(points);
  112. Vector2 center = bounds.Center;
  113. float maxDistSquared = 0.0f;
  114. for (int i = 0; i < points.Count; i++)
  115. {
  116. float distSquared = Vector2.DistanceSquared(center, points[i]);
  117. if (distSquared > maxDistSquared)
  118. {
  119. maxDistSquared = distSquared;
  120. }
  121. }
  122. float radius = MathF.Sqrt(maxDistSquared);
  123. return new Circle(center, radius);
  124. }
  125. #endregion
  126. #region Containment Methods
  127. /// <summary>
  128. /// Determines whether the circular boundary contains the specified point.
  129. /// </summary>
  130. /// <param name="point">The point to test for containment.</param>
  131. /// <returns><c>true</c> if the point lies within or on the circular boundary; otherwise, <c>false</c>.</returns>
  132. /// <remarks>
  133. /// Points exactly on the boundary are considered contained.
  134. /// </remarks>
  135. public readonly bool Contains(Vector2 point)
  136. {
  137. float distanceSquared = Vector2.DistanceSquared(Center, point);
  138. return distanceSquared <= Radius * Radius;
  139. }
  140. /// <summary>
  141. /// Determines whether the circular boundary contains the point at the specified coordinates.
  142. /// </summary>
  143. /// <param name="x">The X coordinate of the point to test.</param>
  144. /// <param name="y">The Y coordinate of the point to test.</param>
  145. /// <returns><c>true</c> if the point lies within or on the circular boundary; otherwise, <c>false</c>.</returns>
  146. /// <remarks>
  147. /// Points exactly on the boundary are considered contained.
  148. /// </remarks>
  149. public readonly bool Contains(float x, float y)
  150. {
  151. return Contains(new Vector2(x, y));
  152. }
  153. #endregion
  154. #region Intersection Methods
  155. /// <summary>
  156. /// Determines whether this circle intersects with another circle.
  157. /// </summary>
  158. /// <param name="other">The other circle to test for intersection.</param>
  159. /// <returns>
  160. /// <see langword="true"/> if this circle intersects the other; otherwise, <see langword="false"/>.
  161. /// </returns>
  162. public readonly bool Intersects(Circle other) => IntersectionTests.CircleCircle(in this, in other);
  163. /// <summary>
  164. /// Determines whether this circle intersects with an ellipse
  165. /// </summary>
  166. /// <param name="ellipse">The ellipse to test for intersection.</param>
  167. /// <returns>
  168. /// <see langword="true"/> if this circle intersects the ellipse; otherwise, <see langword="false"/>.
  169. /// </returns>
  170. public readonly bool Intersects(Ellipse ellipse) => IntersectionTests.CircleEllipse(in this, in ellipse);
  171. /// <summary>
  172. /// Determines whether this circle intersects with a rectangle
  173. /// </summary>
  174. /// <param name="rectangle">The rectangle to test for intersection.</param>
  175. /// <returns>
  176. /// <see langword="true"/> if this circle intersects the rectangle; otherwise, <see langword="false"/>.
  177. /// </returns>
  178. public readonly bool Intersects(RectangleF rectangle) => IntersectionTests.CircleRectangleF(in this, in rectangle);
  179. /// <summary>
  180. /// Determines whether this circle intersects with a ray
  181. /// </summary>
  182. /// <param name="ray">The ray to test for intersection.</param>
  183. /// <returns>
  184. /// <see langword="true"/> if this circle intersects the ray; otherwise, <see langword="false"/>.
  185. /// </returns>
  186. public readonly bool Intersects(Ray ray) => IntersectionTests.CircleRay(in this, in ray);
  187. /// <summary>
  188. /// Determines whether this circle intersects with a line segment
  189. /// </summary>
  190. /// <param name="lineSegment">The line segment to test for intersection.</param>
  191. /// <returns>
  192. /// <see langword="true"/> if this circle intersects the line segment; otherwise, <see langword="false"/>.
  193. /// </returns>
  194. public readonly bool Intersects(LineSegment lineSegment) => IntersectionTests.CirceLineSegment(in this, in lineSegment);
  195. #endregion
  196. #region Closest Point To Methods
  197. /// <summary>
  198. /// Computes the closest point on the circular boundary to the specified point.
  199. /// </summary>
  200. /// <param name="point">The query point for closest-point computation.</param>
  201. /// <returns>The point on the circular perimeter closest to the query point.</returns>
  202. /// <remarks>
  203. /// When the query point is at the circle center, returns a point on the positive X-axis.
  204. /// </remarks>
  205. public readonly Vector2 ClosestPointTo(Vector2 point)
  206. {
  207. Vector2 direction = point - Center;
  208. float length = direction.Length();
  209. if (length < 0.001f)
  210. {
  211. // Point is at the center, return any point on the circle
  212. return Center + new Vector2(Radius, 0);
  213. }
  214. return Center + direction * (Radius / length);
  215. }
  216. #endregion
  217. #region Distance Methods
  218. /// <summary>
  219. /// Computes the squared distance from a point to the circular boundary,
  220. /// optimized to avoid square root calculation in distance queries.
  221. /// </summary>
  222. /// <param name="point">The query point for distance computation.</param>
  223. /// <returns>The squared distance to the boundary, or zero if the point lies within the circle.</returns>
  224. public readonly float SquaredDistanceTo(Vector2 point)
  225. {
  226. float distanceToCenter = Vector2.Distance(Center, point);
  227. float distanceToBoundary = distanceToCenter - Radius;
  228. // If point is inside the circle, distance is 0
  229. if (distanceToBoundary < 0.0f)
  230. {
  231. return 0.0f;
  232. }
  233. return distanceToBoundary * distanceToBoundary;
  234. }
  235. /// <summary>
  236. /// Computes the distance from a point to the circular boundary.
  237. /// </summary>
  238. /// <param name="point">The query point for distance computation.</param>
  239. /// <returns>The distance to the boundary, or zero if the point lies within the circle.</returns>
  240. public readonly float DistanceTo(Vector2 point)
  241. {
  242. float distanceToCenter = Vector2.Distance(Center, point);
  243. float distanceToBoundary = distanceToCenter - Radius;
  244. // if point is inside the circle, distance is 0
  245. if (distanceToBoundary < 0.0f)
  246. {
  247. return 0.0f;
  248. }
  249. return distanceToBoundary;
  250. }
  251. #endregion
  252. #region Offset Methods
  253. /// <summary>
  254. /// Translates the circle by moving its center position, preserving the radius.
  255. /// </summary>
  256. /// <param name="offset">The translation vector to apply to the center position.</param>
  257. public void Offset(Vector2 offset)
  258. {
  259. Center += offset;
  260. }
  261. /// <summary>
  262. /// Creates a new circle translated by the specified offset vector.
  263. /// </summary>
  264. /// <param name="circle">The circle to translate.</param>
  265. /// <param name="offset">The translation vector to apply.</param>
  266. /// <returns>A new circle with the translated center position.</returns>
  267. public static Circle Offset(Circle circle, Vector2 offset)
  268. {
  269. return circle with { Center = circle.Center + offset };
  270. }
  271. #endregion
  272. #region Inflate Methods
  273. /// <summary>
  274. /// Modifies the radius to expand or contract the circular boundary.
  275. /// </summary>
  276. /// <param name="amount">The value to add to the radius. Negative values contract the circle.</param>
  277. public void Inflate(float amount)
  278. {
  279. Radius += amount;
  280. }
  281. /// <summary>
  282. /// Creates a new circle with the radius modified by the specified amount.
  283. /// </summary>
  284. /// <param name="circle">The circle to inflate or deflate.</param>
  285. /// <param name="amount">The value to add to the radius. Negative values contract the circle.</param>
  286. /// <returns>A new circle with the modified radius.</returns>
  287. public static Circle Inflate(Circle circle, float amount)
  288. {
  289. return circle with { Radius = circle.Radius + amount };
  290. }
  291. #endregion
  292. #region Transform Methods
  293. /// <summary>
  294. /// Applies a 2D transformation matrix to the circle, transforming both position and scale.
  295. /// </summary>
  296. /// <param name="matrix">The transformation matrix to apply.</param>
  297. /// <remarks>
  298. /// The radius is scaled using the maximum scale factor from the matrix to preserve
  299. /// the circular shape under non-uniform transformations.
  300. /// </remarks>
  301. public void Transform(Matrix3x2 matrix)
  302. {
  303. Transform(ref matrix);
  304. }
  305. /// <summary>
  306. /// Applies a 2D transformation matrix to the circle using reference parameters.
  307. /// </summary>
  308. /// <param name="matrix">The transformation matrix to apply.</param>
  309. /// <remarks>
  310. /// The radius is scaled using the maximum scale factor from the matrix to preserve
  311. /// the circular shape under non-uniform transformations.
  312. /// </remarks>
  313. public void Transform(ref Matrix3x2 matrix)
  314. {
  315. Center = matrix.Transform(Center);
  316. // Extract scale from matrix using maximum scale for non-uniform scale
  317. float scaleX = MathF.Sqrt(matrix.M11 * matrix.M11 + matrix.M12 * matrix.M12);
  318. float scaleY = MathF.Sqrt(matrix.M21 * matrix.M21 + matrix.M22 * matrix.M22);
  319. float scale = MathF.Max(scaleX, scaleY);
  320. Radius *= scale;
  321. }
  322. /// <summary>
  323. /// Creates a new circle by applying a 2D transformation matrix.
  324. /// </summary>
  325. /// <param name="circle">The circle to transform.</param>
  326. /// <param name="matrix">The transformation matrix to apply.</param>
  327. /// <returns>A new transformed circle.</returns>
  328. /// <remarks>
  329. /// The radius is scaled using the maximum scale factor from the matrix to preserve
  330. /// the circular shape under non-uniform transformations.
  331. /// </remarks>
  332. public static Circle Transform(Circle circle, Matrix3x2 matrix)
  333. {
  334. Transform(ref circle, ref matrix);
  335. return circle;
  336. }
  337. /// <summary>
  338. /// Computes a transformed circle using reference parameters for performance.
  339. /// </summary>
  340. /// <param name="circle">The circle to transform.</param>
  341. /// <param name="matrix">The transformation matrix to apply.</param>
  342. /// <remarks>
  343. /// The radius is scaled using the maximum scale factor from the matrix to preserve
  344. /// the circular shape under non-uniform transformations.
  345. /// </remarks>
  346. public static void Transform(ref Circle circle, ref Matrix3x2 matrix)
  347. {
  348. circle.Center = matrix.Transform(circle.Center);
  349. // Extract scale from matrix using maximum scale for non-uniform scale
  350. float scaleX = MathF.Sqrt(matrix.M11 * matrix.M11 + matrix.M12 * matrix.M12);
  351. float scaleY = MathF.Sqrt(matrix.M21 * matrix.M21 + matrix.M22 * matrix.M22);
  352. float scale = MathF.Max(scaleX, scaleY);
  353. circle.Radius *= scale;
  354. }
  355. #endregion
  356. /// <summary>
  357. /// Fills the provided buffer with points that approximate the circle as a polygon.
  358. /// </summary>
  359. /// <param name="buffer">
  360. /// The buffer to fill with polygon vertices. The number of vertices equals the buffer length.
  361. /// </param>
  362. /// <remarks>
  363. /// Distributes points evenly around the circle perimeter.
  364. /// </remarks>
  365. public readonly void ToPolygon(Span<Vector2> buffer)
  366. {
  367. int count = buffer.Length;
  368. float step = MathHelper.TwoPi / count;
  369. for (int i = 0; i < count; i++)
  370. {
  371. float t = step * i;
  372. buffer[i] = new Vector2(
  373. Center.X + Radius * MathF.Cos(t),
  374. Center.Y + Radius * MathF.Sin(t)
  375. );
  376. }
  377. }
  378. #region Equality Methods
  379. /// <summary>
  380. /// Determines whether this circle is equal to the specified object.
  381. /// </summary>
  382. /// <param name="obj">The object to compare.</param>
  383. /// <returns>
  384. /// <c>true</c> if the object is a <see cref="Circle"/> with the same center and radius; otherwise, <c>false</c>.
  385. /// </returns>
  386. public override readonly bool Equals([NotNullWhen(true)] object obj)
  387. {
  388. return obj is Circle other && Equals(other);
  389. }
  390. /// <summary>
  391. /// Determines whether this circle is equal to another circle.
  392. /// </summary>
  393. /// <param name="other">The circle to compare with this circle.</param>
  394. /// <returns><c>true</c> if the circles have the same center and radius; otherwise, <c>false</c>.</returns>
  395. public readonly bool Equals(Circle other)
  396. {
  397. return Center.Equals(other.Center) && Radius.Equals(other.Radius);
  398. }
  399. #endregion
  400. /// <summary>
  401. /// Computes the hash code for this circle.
  402. /// </summary>
  403. /// <returns>A hash code derived from the center position and radius.</returns>
  404. public override readonly int GetHashCode() => HashCode.Combine(Center, Radius);
  405. /// <summary>
  406. /// Creates a string representation of this circle.
  407. /// </summary>
  408. /// <returns>A formatted string containing the center and radius values.</returns>
  409. public override readonly string ToString()
  410. {
  411. return $"Circle(Center: {Center}, Radius: {Radius})";
  412. }
  413. internal readonly string DebugDisplayString => ToString();
  414. #region Operators
  415. /// <summary>
  416. /// Tests whether two circles are equal.
  417. /// </summary>
  418. /// <param name="left">The first circle.</param>
  419. /// <param name="right">The second circle.</param>
  420. /// <returns><c>true</c> if both circles have the same center and radius; otherwise, <c>false</c>.</returns>
  421. public static bool operator ==(Circle left, Circle right)
  422. {
  423. return left.Equals(right);
  424. }
  425. /// <summary>
  426. /// Tests whether two circles are not equal.
  427. /// </summary>
  428. /// <param name="left">The first circle.</param>
  429. /// <param name="right">The second circle.</param>
  430. /// <returns><c>true</c> if the circles have different centers or radii; otherwise, <c>false</c>.</returns>
  431. public static bool operator !=(Circle left, Circle right)
  432. {
  433. return !left.Equals(right);
  434. }
  435. #endregion
  436. }