BoundingBox2D.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 axis-aligned bounding box in 2D space, defined by minimum and maximum corner points.
  12. /// </summary>
  13. [DataContract]
  14. [DebuggerDisplay("{DebugDisplayString,nq}")]
  15. public struct BoundingBox2D : IEquatable<BoundingBox2D>
  16. {
  17. /// <summary>
  18. /// The number of corners in this bounding box.
  19. /// </summary>
  20. public const int CornerCount = 4;
  21. #region Public Fields
  22. /// <summary>
  23. /// The minimum corner position with the smallest X and Y coordinates.
  24. /// </summary>
  25. [DataMember]
  26. public Vector2 Min;
  27. /// <summary>
  28. /// The maximum corner position with the largest X and Y coordinates.
  29. /// </summary>
  30. [DataMember]
  31. public Vector2 Max;
  32. #endregion
  33. #region Public Properties
  34. /// <summary>
  35. /// Gets the center position of this bounding box in 2D space.
  36. /// </summary>
  37. public readonly Vector2 Center => (Min + Max) * 0.5f;
  38. /// <summary>
  39. /// Gets the size of this bounding box as width and height.
  40. /// </summary>
  41. public readonly Vector2 Size => Max - Min;
  42. /// <summary>
  43. /// Gets the half extents of this bounding box, representing the distance from the center to each edge.
  44. /// </summary>
  45. public readonly Vector2 HalfExtents => (Max - Min) * 0.5f;
  46. /// <summary>
  47. /// Gets the width of this bounding box.
  48. /// </summary>
  49. public readonly float Width => Max.X - Min.X;
  50. /// <summary>
  51. /// Gets the height of this bounding box.
  52. /// </summary>
  53. public readonly float Height => Max.Y - Min.Y;
  54. /// <summary>
  55. /// Gets the area enclosed by this bounding box.
  56. /// </summary>
  57. public readonly float Area => Width * Height;
  58. #endregion
  59. #region Internal Properties
  60. internal string DebugDisplayString
  61. {
  62. get
  63. {
  64. return string.Concat(
  65. "Min( ", Min.ToString(), " ) \r\n",
  66. "Max( ", Max.ToString(), " )"
  67. );
  68. }
  69. }
  70. #endregion
  71. #region Public Constructors
  72. /// <summary>
  73. /// Creates a new <see cref="BoundingBox2D"/> with the specified minimum and maximum corners.
  74. /// </summary>
  75. /// <param name="min">The minimum corner, containing the smallest X and Y coordinate values.</param>
  76. /// <param name="max">The maximum corner, containing the largest X and Y coordinate values.</param>
  77. public BoundingBox2D(Vector2 min, Vector2 max)
  78. {
  79. Min = min;
  80. Max = max;
  81. }
  82. #endregion
  83. #region Public Methods
  84. /// <summary>
  85. /// Creates a new <see cref="BoundingBox2D"/> from the specified minimum and maximum corners.
  86. /// </summary>
  87. /// <param name="min">The minimum corner, containing the smallest X and Y coordinate values.</param>
  88. /// <param name="max">The maximum corner, containing the largest X and Y coordinate values.</param>
  89. /// <returns>
  90. /// A new <see cref="BoundingBox2D"/> with the specified corners.
  91. /// </returns>
  92. public static BoundingBox2D CreateFromMinMax(Vector2 min, Vector2 max)
  93. {
  94. return new BoundingBox2D(min, max);
  95. }
  96. /// <summary>
  97. /// Creates a new <see cref="BoundingBox2D"/> from a center position and half extents.
  98. /// </summary>
  99. /// <param name="center">The center position of the bounding box in 2D space.</param>
  100. /// <param name="halfExtents">
  101. /// The half extents representing the distance from the center to each edge (half-width and half-height).
  102. /// </param>
  103. /// <returns>
  104. /// A new <see cref="BoundingBox2D"/> centered at the specified position with the given extents.
  105. /// </returns>
  106. public static BoundingBox2D CreateFromCenterAndExtents(Vector2 center, Vector2 halfExtents)
  107. {
  108. return new BoundingBox2D(center - halfExtents, center + halfExtents);
  109. }
  110. /// <summary>
  111. /// Creates a new <see cref="BoundingBox2D"/> from a minimum corner position and size.
  112. /// </summary>
  113. /// <param name="position">The minimum corner position in 2D space.</param>
  114. /// <param name="size">The size as width and height.</param>
  115. /// <returns>
  116. /// A new <see cref="BoundingBox2D"/> with the specified position and size.
  117. /// </returns>
  118. public static BoundingBox2D CreateFromPositionAndSize(Vector2 position, Vector2 size)
  119. {
  120. return new BoundingBox2D(position, position + size);
  121. }
  122. /// <summary>
  123. /// Creates a new <see cref="BoundingBox2D"/> that encloses all specified points.
  124. /// </summary>
  125. /// <param name="points">The array of points to enclose within the bounding box.</param>
  126. /// <returns>
  127. /// A new <see cref="BoundingBox2D"/> with minimum and maximum corners positioned to contain all the specified points.
  128. /// </returns>
  129. /// <exception cref="ArgumentNullException">
  130. /// Thrown when <paramref name="points"/> is <see langword="null"/>.
  131. /// </exception>
  132. /// <exception cref="ArgumentException">
  133. /// Thrown when <paramref name="points"/> is empty.
  134. /// </exception>
  135. public static BoundingBox2D CreateFromPoints(Vector2[] points)
  136. {
  137. if (points == null)
  138. {
  139. throw new ArgumentNullException(nameof(points));
  140. }
  141. if (points.Length == 0)
  142. {
  143. throw new ArgumentException("Cannot create bounding box from empty point array.", nameof(points));
  144. }
  145. Vector2 min = new Vector2(float.MaxValue, float.MaxValue);
  146. Vector2 max = new Vector2(float.MinValue, float.MinValue);
  147. for (int i = 0; i < points.Length; i++)
  148. {
  149. if (points[i].X < min.X) min.X = points[i].X;
  150. if (points[i].Y < min.Y) min.Y = points[i].Y;
  151. if (points[i].X > max.X) max.X = points[i].X;
  152. if (points[i].Y > max.Y) max.Y = points[i].Y;
  153. }
  154. return new BoundingBox2D(min, max);
  155. }
  156. /// <summary>
  157. /// Creates a new <see cref="BoundingBox2D"/> that encloses two bounding boxes.
  158. /// </summary>
  159. /// <param name="original">The first bounding box to enclose.</param>
  160. /// <param name="additional">The second bounding box to enclose.</param>
  161. /// <returns>
  162. /// A new <see cref="BoundingBox2D"/> that completely contains both input bounding boxes.
  163. /// </returns>
  164. public static BoundingBox2D CreateMerged(BoundingBox2D original, BoundingBox2D additional)
  165. {
  166. BoundingBox2D result;
  167. result.Min.X = MathF.Min(original.Min.X, additional.Min.X);
  168. result.Min.Y = MathF.Min(original.Min.Y, additional.Min.Y);
  169. result.Max.X = MathF.Max(original.Max.X, additional.Max.X);
  170. result.Max.Y = MathF.Max(original.Max.Y, additional.Max.Y);
  171. return result;
  172. }
  173. /// <summary>
  174. /// Gets an array containing the four corner positions of this bounding box.
  175. /// </summary>
  176. /// <returns>
  177. /// An array of 4 corner positions in counter-clockwise order starting from the minimum corner:
  178. /// bottom-left, bottom-right, top-right, top-left.
  179. /// </returns>
  180. public readonly Vector2[] GetCorners()
  181. {
  182. return new Vector2[CornerCount]
  183. {
  184. new Vector2(Min.X, Min.Y),
  185. new Vector2(Max.X, Min.Y),
  186. new Vector2(Max.X, Max.Y),
  187. new Vector2(Min.X, Max.Y)
  188. };
  189. }
  190. /// <summary>
  191. /// Writes the four corner positions of this bounding box into an existing array.
  192. /// </summary>
  193. /// <param name="corners">
  194. /// The array to write corner positions into. Must have at least 4 elements.
  195. /// Corners are written in counter-clockwise order starting from the minimum corner.
  196. /// </param>
  197. /// <exception cref="ArgumentNullException">
  198. /// Thrown when <paramref name="corners"/> is <see langword="null"/>.
  199. /// </exception>
  200. /// <exception cref="ArgumentException">
  201. /// Thrown when <paramref name="corners"/> has fewer than 4 elements.
  202. /// </exception>
  203. public readonly void GetCorners(Vector2[] corners)
  204. {
  205. if (corners == null)
  206. throw new ArgumentNullException(nameof(corners));
  207. if (corners.Length < CornerCount)
  208. throw new ArgumentException($"Array must have at least {CornerCount} elements", nameof(corners));
  209. corners[0] = new Vector2(Min.X, Min.Y);
  210. corners[1] = new Vector2(Max.X, Min.Y);
  211. corners[2] = new Vector2(Max.X, Max.Y);
  212. corners[3] = new Vector2(Min.X, Max.Y);
  213. }
  214. /// <summary>
  215. /// Applies a matrix transformation to this bounding box and creates a new axis-aligned bounding box that encloses the result.
  216. /// </summary>
  217. /// <param name="matrix">The transformation matrix to apply.</param>
  218. /// <returns>
  219. /// A new axis-aligned <see cref="BoundingBox2D"/> that completely contains all corners of this bounding box after transformation.
  220. /// </returns>
  221. /// <remarks>
  222. /// When a transformation includes rotation or skew, the transformed corners of the original box may no longer
  223. /// be axis-aligned. This method computes a new axis-aligned bounding box that encloses all transformed corners,
  224. /// which may be larger than the original if rotation is applied.
  225. /// </remarks>
  226. public readonly BoundingBox2D Transform(Matrix matrix)
  227. {
  228. Vector2 transformedCenter = Vector2.Transform(Center, matrix);
  229. // For each axis, sum the absolute values of the transformed half-extents.
  230. // This gives us the new box that bounds the rotated original
  231. Vector2 newHalfExtents;
  232. newHalfExtents.X = MathF.Abs(matrix.M11) * HalfExtents.X
  233. + MathF.Abs(matrix.M12) * HalfExtents.Y;
  234. newHalfExtents.Y = MathF.Abs(matrix.M21) * HalfExtents.X
  235. + MathF.Abs(matrix.M22) * HalfExtents.Y;
  236. return CreateFromCenterAndExtents(transformedCenter, newHalfExtents);
  237. }
  238. /// <summary>
  239. /// Creates a new <see cref="BoundingBox2D"/> by translating this bounding box by the specified offset.
  240. /// </summary>
  241. /// <param name="translation">The offset to translate the bounding box by in 2D space.</param>
  242. /// <returns>
  243. /// A new <see cref="BoundingBox2D"/> at the translated position with the same size.
  244. /// </returns>
  245. public readonly BoundingBox2D Translate(Vector2 translation)
  246. {
  247. return new BoundingBox2D(Min + translation, Max + translation);
  248. }
  249. /// <summary>
  250. /// Tests whether a point lies inside this bounding box or on its boundary.
  251. /// </summary>
  252. /// <param name="point">The point to test in 2D space.</param>
  253. /// <returns>
  254. /// <see cref="ContainmentType.Contains"/> if the point is inside or on the boundary;
  255. /// otherwise, <see cref="ContainmentType.Disjoint"/> if the point is outside.
  256. /// </returns>
  257. public readonly ContainmentType Contains(Vector2 point)
  258. {
  259. return Collision2D.ContainsAabbPoint(point, Min, Max);
  260. }
  261. /// <summary>
  262. /// Tests whether this bounding box contains, intersects, or is separate from another bounding box.
  263. /// </summary>
  264. /// <param name="other">The other bounding box to test against.</param>
  265. /// <returns>
  266. /// <see cref="ContainmentType.Contains"/> if the other bounding box is completely inside this one;
  267. /// <see cref="ContainmentType.Intersects"/> if they partially overlap;
  268. /// or <see cref="ContainmentType.Disjoint"/> if they do not touch.
  269. /// </returns>
  270. public readonly ContainmentType Contains(BoundingBox2D other)
  271. {
  272. return Collision2D.ContainsAabbAabb(Min, Max, other.Min, other.Max);
  273. }
  274. /// <summary>
  275. /// Tests whether this bounding box contains, intersects, or is separate from a circle.
  276. /// </summary>
  277. /// <param name="circle">The circle to test against.</param>
  278. /// <returns>
  279. /// <see cref="ContainmentType.Contains"/> if the circle is completely inside this bounding box;
  280. /// <see cref="ContainmentType.Intersects"/> if they partially overlap;
  281. /// or <see cref="ContainmentType.Disjoint"/> if they do not touch.
  282. /// </returns>
  283. public readonly ContainmentType Contains(BoundingCircle2D circle)
  284. {
  285. return Collision2D.ContainsAabbCircle(Min, Max, circle.Center, circle.Radius);
  286. }
  287. /// <summary>
  288. /// Tests whether this bounding box contains, intersects, or is separate from an oriented bounding box.
  289. /// </summary>
  290. /// <param name="obb">The oriented bounding box to test against.</param>
  291. /// <returns>
  292. /// <see cref="ContainmentType.Contains"/> if the oriented bounding box is completely inside this bounding box;
  293. /// <see cref="ContainmentType.Intersects"/> if they partially overlap;
  294. /// or <see cref="ContainmentType.Disjoint"/> if they do not touch.
  295. /// </returns>
  296. public readonly ContainmentType Contains(OrientedBoundingBox2D obb)
  297. {
  298. return Collision2D.ContainsAabbObb(Min, Max, obb.Center, obb.AxisX, obb.AxisY, obb.HalfExtents);
  299. }
  300. /// <summary>
  301. /// Tests whether this bounding box contains, intersects, or is separate from a capsule.
  302. /// </summary>
  303. /// <param name="capsule">The capsule to test against.</param>
  304. /// <returns>
  305. /// <see cref="ContainmentType.Contains"/> if the capsule is completely inside this bounding box;
  306. /// <see cref="ContainmentType.Intersects"/> if they partially overlap;
  307. /// or <see cref="ContainmentType.Disjoint"/> if they do not touch.
  308. /// </returns>
  309. public readonly ContainmentType Contains(BoundingCapsule2D capsule)
  310. {
  311. return Collision2D.ContainsAabbCapsule(Min, Max, capsule.PointA, capsule.PointB, capsule.Radius);
  312. }
  313. /// <summary>
  314. /// Tests whether this bounding box contains, intersects, or is separate from a polygon.
  315. /// </summary>
  316. /// <param name="polygon">The polygon to test against.</param>
  317. /// <returns>
  318. /// <see cref="ContainmentType.Contains"/> if the polygon is completely inside this bounding box;
  319. /// <see cref="ContainmentType.Intersects"/> if they partially overlap;
  320. /// or <see cref="ContainmentType.Disjoint"/> if they do not touch.
  321. /// </returns>
  322. public readonly ContainmentType Contains(BoundingPolygon2D polygon)
  323. {
  324. return Collision2D.ContainsAabbConvexPolygon(Min, Max, polygon.Vertices, polygon.Normals);
  325. }
  326. /// <summary>
  327. /// Tests whether this bounding box intersects with another bounding box.
  328. /// </summary>
  329. /// <param name="other">The other bounding box to test against.</param>
  330. /// <returns>
  331. /// <see langword="true"/> if the bounding boxes overlap or touch; otherwise, <see langword="false"/>.
  332. /// </returns>
  333. public readonly bool Intersects(BoundingBox2D other)
  334. {
  335. return Collision2D.IntersectsAabbAabb(Min, Max, other.Min, other.Max);
  336. }
  337. /// <summary>
  338. /// Tests whether this bounding box intersects with a circle.
  339. /// </summary>
  340. /// <param name="circle">The circle to test against.</param>
  341. /// <returns>
  342. /// <see langword="true"/> if the bounding box and circle overlap or touch; otherwise, <see langword="false"/>.
  343. /// </returns>
  344. public readonly bool Intersects(BoundingCircle2D circle)
  345. {
  346. return Collision2D.IntersectsCircleAabb(circle.Center, circle.Radius, Min, Max);
  347. }
  348. /// <summary>
  349. /// Tests whether this bounding box intersects with a capsule.
  350. /// </summary>
  351. /// <param name="capsule">The capsule to test against.</param>
  352. /// <returns>
  353. /// <see langword="true"/> if the bounding box and capsule overlap or touch; otherwise, <see langword="false"/>.
  354. /// </returns>
  355. public readonly bool Intersects(BoundingCapsule2D capsule)
  356. {
  357. return Collision2D.IntersectsAabbCapsule(Min, Max, capsule.PointA, capsule.PointB, capsule.Radius);
  358. }
  359. /// <summary>
  360. /// Tests whether this bounding box intersects with an oriented bounding box.
  361. /// </summary>
  362. /// <param name="obb">The oriented bounding box to test against.</param>
  363. /// <returns>
  364. /// <see langword="true"/> if the boxes overlap or touch; otherwise, <see langword="false"/>.
  365. /// </returns>
  366. public readonly bool Intersects(OrientedBoundingBox2D obb)
  367. {
  368. return Collision2D.IntersectsAabbObb(Center, HalfExtents, obb.Center, obb.AxisX, obb.AxisY, obb.HalfExtents);
  369. }
  370. /// <summary>
  371. /// Tests whether this bounding box intersects with a polygon.
  372. /// </summary>
  373. /// <param name="polygon">The polygon to test against.</param>
  374. /// <returns>
  375. /// <see langword="true"/> if the box and polygon overlap or touch; otherwise, <see langword="false"/>.
  376. /// </returns>
  377. public readonly bool Intersects(BoundingPolygon2D polygon)
  378. {
  379. return Collision2D.IntersectsAabbConvexPolygon(Center, HalfExtents, polygon.Vertices, polygon.Normals);
  380. }
  381. /// <summary>
  382. /// Deconstructs this bounding box into its component values.
  383. /// </summary>
  384. /// <param name="min">
  385. /// When this method returns, contains the minimum corner, containing the smallest X and Y coordinate values.
  386. /// </param>
  387. /// <param name="max">
  388. /// When this method returns, contains the maximum corner, containing the largest X and Y coordinate values.
  389. /// </param>
  390. public readonly void Deconstruct(out Vector2 min, out Vector2 max)
  391. {
  392. min = Min;
  393. max = Max;
  394. }
  395. /// <inheritdoc/>
  396. public readonly bool Equals(BoundingBox2D other)
  397. {
  398. return Min.Equals(other.Min) && Max.Equals(other.Max);
  399. }
  400. /// <inheritdoc/>
  401. public override readonly bool Equals(object obj)
  402. {
  403. return obj is BoundingBox2D other && Equals(other);
  404. }
  405. /// <inheritdoc/>
  406. public override readonly int GetHashCode()
  407. {
  408. return Min.GetHashCode() ^ Max.GetHashCode();
  409. }
  410. /// <inheritdoc/>
  411. public override readonly string ToString()
  412. {
  413. return $"{{Min:{Min} Max:{Max}}}";
  414. }
  415. /// <summary/>
  416. public static bool operator ==(BoundingBox2D left, BoundingBox2D right)
  417. {
  418. return left.Equals(right);
  419. }
  420. /// <summary/>
  421. public static bool operator !=(BoundingBox2D left, BoundingBox2D right)
  422. {
  423. return !left.Equals(right);
  424. }
  425. #endregion
  426. }
  427. }