Region.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #nullable enable
  2. using System.Buffers;
  3. /// <summary>
  4. /// Represents a region composed of one or more rectangles, providing methods for union, intersection, exclusion, and
  5. /// complement operations.
  6. /// </summary>
  7. public class Region : IDisposable
  8. {
  9. private List<Rectangle> _rectangles;
  10. /// <summary>
  11. /// Initializes a new instance of the <see cref="Region"/> class.
  12. /// </summary>
  13. public Region () { _rectangles = new (); }
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="Region"/> class with the specified rectangle.
  16. /// </summary>
  17. /// <param name="rectangle">The initial rectangle for the region.</param>
  18. public Region (Rectangle rectangle) { _rectangles = new () { rectangle }; }
  19. /// <summary>
  20. /// Adds the specified rectangle to the region.
  21. /// </summary>
  22. /// <param name="rectangle">The rectangle to add to the region.</param>
  23. public void Union (Rectangle rectangle)
  24. {
  25. _rectangles.Add (rectangle);
  26. _rectangles = MergeRectangles (_rectangles);
  27. }
  28. /// <summary>
  29. /// Adds the specified region to this region.
  30. /// </summary>
  31. /// <param name="region">The region to add to this region.</param>
  32. public void Union (Region region)
  33. {
  34. _rectangles.AddRange (region._rectangles);
  35. _rectangles = MergeRectangles (_rectangles);
  36. }
  37. /// <summary>
  38. /// Updates the region to be the intersection of itself with the specified rectangle.
  39. /// </summary>
  40. /// <param name="rectangle">The rectangle to intersect with the region.</param>
  41. public void Intersect (Rectangle rectangle)
  42. {
  43. if (_rectangles.Count == 0)
  44. {
  45. return;
  46. }
  47. // TODO: In-place swap within the original list. Does order of intersections matter?
  48. // Rectangle = 4 * i32 = 16 B
  49. // ~128 B stack allocation
  50. const int maxStackallocLength = 8;
  51. Rectangle []? rentedArray = null;
  52. try
  53. {
  54. Span<Rectangle> rectBuffer = _rectangles.Count <= maxStackallocLength
  55. ? stackalloc Rectangle[maxStackallocLength]
  56. : (rentedArray = ArrayPool<Rectangle>.Shared.Rent (_rectangles.Count));
  57. _rectangles.CopyTo (rectBuffer);
  58. ReadOnlySpan<Rectangle> rectangles = rectBuffer[.._rectangles.Count];
  59. _rectangles.Clear ();
  60. foreach (var rect in rectangles)
  61. {
  62. Rectangle intersection = Rectangle.Intersect (rect, rectangle);
  63. if (!intersection.IsEmpty)
  64. {
  65. _rectangles.Add (intersection);
  66. }
  67. }
  68. }
  69. finally
  70. {
  71. if (rentedArray != null)
  72. {
  73. ArrayPool<Rectangle>.Shared.Return (rentedArray);
  74. }
  75. }
  76. }
  77. /// <summary>
  78. /// Updates the region to be the intersection of itself with the specified region.
  79. /// </summary>
  80. /// <param name="region">The region to intersect with this region.</param>
  81. public void Intersect (Region region)
  82. {
  83. List<Rectangle> intersections = new List<Rectangle> ();
  84. foreach (Rectangle rect1 in _rectangles)
  85. {
  86. foreach (Rectangle rect2 in region._rectangles)
  87. {
  88. Rectangle intersected = Rectangle.Intersect (rect1, rect2);
  89. if (!intersected.IsEmpty)
  90. {
  91. intersections.Add (intersected);
  92. }
  93. }
  94. }
  95. _rectangles = intersections;
  96. }
  97. /// <summary>
  98. /// Removes the specified rectangle from the region.
  99. /// </summary>
  100. /// <param name="rectangle">The rectangle to exclude from the region.</param>
  101. public void Exclude (Rectangle rectangle) { _rectangles = _rectangles.SelectMany (r => SubtractRectangle (r, rectangle)).ToList (); }
  102. /// <summary>
  103. /// Removes the portion of the specified region from this region.
  104. /// </summary>
  105. /// <param name="region">The region to exclude from this region.</param>
  106. public void Exclude (Region region)
  107. {
  108. foreach (Rectangle rect in region._rectangles)
  109. {
  110. _rectangles = _rectangles.SelectMany (r => SubtractRectangle (r, rect)).ToList ();
  111. }
  112. }
  113. /// <summary>
  114. /// Updates the region to be the complement of itself within the specified bounds.
  115. /// </summary>
  116. /// <param name="bounds">The bounding rectangle to use for complementing the region.</param>
  117. public void Complement (Rectangle bounds)
  118. {
  119. if (bounds.IsEmpty || _rectangles.Count == 0)
  120. {
  121. _rectangles.Clear ();
  122. return;
  123. }
  124. List<Rectangle> complementRectangles = new List<Rectangle> { bounds };
  125. foreach (Rectangle rect in _rectangles)
  126. {
  127. complementRectangles = complementRectangles.SelectMany (r => SubtractRectangle (r, rect)).ToList ();
  128. }
  129. _rectangles = complementRectangles;
  130. }
  131. /// <summary>
  132. /// Creates an exact copy of the region.
  133. /// </summary>
  134. /// <returns>A new <see cref="Region"/> that is a copy of this instance.</returns>
  135. public Region Clone ()
  136. {
  137. var clone = new Region ();
  138. clone._rectangles = new (_rectangles);
  139. return clone;
  140. }
  141. /// <summary>
  142. /// Gets a bounding rectangle for the entire region.
  143. /// </summary>
  144. /// <returns>A <see cref="Rectangle"/> that bounds the region.</returns>
  145. public Rectangle GetBounds ()
  146. {
  147. if (_rectangles.Count == 0)
  148. {
  149. return Rectangle.Empty;
  150. }
  151. int left = _rectangles.Min (r => r.Left);
  152. int top = _rectangles.Min (r => r.Top);
  153. int right = _rectangles.Max (r => r.Right);
  154. int bottom = _rectangles.Max (r => r.Bottom);
  155. return new (left, top, right - left, bottom - top);
  156. }
  157. /// <summary>
  158. /// Determines whether the region is empty.
  159. /// </summary>
  160. /// <returns><c>true</c> if the region is empty; otherwise, <c>false</c>.</returns>
  161. public bool IsEmpty () { return !_rectangles.Any (); }
  162. /// <summary>
  163. /// Determines whether the specified point is contained within the region.
  164. /// </summary>
  165. /// <param name="x">The x-coordinate of the point.</param>
  166. /// <param name="y">The y-coordinate of the point.</param>
  167. /// <returns><c>true</c> if the point is contained within the region; otherwise, <c>false</c>.</returns>
  168. public bool Contains (int x, int y)
  169. {
  170. foreach (var rect in _rectangles)
  171. {
  172. if (rect.Contains (x, y))
  173. {
  174. return true;
  175. }
  176. }
  177. return false;
  178. }
  179. /// <summary>
  180. /// Determines whether the specified rectangle is contained within the region.
  181. /// </summary>
  182. /// <param name="rectangle">The rectangle to check for containment.</param>
  183. /// <returns><c>true</c> if the rectangle is contained within the region; otherwise, <c>false</c>.</returns>
  184. public bool Contains (Rectangle rectangle)
  185. {
  186. foreach (var rect in _rectangles)
  187. {
  188. if (rect.Contains (rectangle))
  189. {
  190. return true;
  191. }
  192. }
  193. return false;
  194. }
  195. /// <summary>
  196. /// Returns an array of rectangles that represent the region.
  197. /// </summary>
  198. /// <returns>An array of <see cref="Rectangle"/> objects that make up the region.</returns>
  199. public Rectangle [] GetRegionScans () { return _rectangles.ToArray (); }
  200. /// <summary>
  201. /// Offsets all rectangles in the region by the specified amounts.
  202. /// </summary>
  203. /// <param name="offsetX">The amount to offset along the x-axis.</param>
  204. /// <param name="offsetY">The amount to offset along the y-axis.</param>
  205. public void Offset (int offsetX, int offsetY)
  206. {
  207. for (int i = 0; i < _rectangles.Count; i++)
  208. {
  209. var rect = _rectangles [i];
  210. _rectangles [i] = new Rectangle (rect.Left + offsetX, rect.Top + offsetY, rect.Width, rect.Height);
  211. }
  212. }
  213. /// <summary>
  214. /// Merges overlapping rectangles into a minimal set of non-overlapping rectangles.
  215. /// </summary>
  216. /// <param name="rectangles">The list of rectangles to merge.</param>
  217. /// <returns>A list of merged rectangles.</returns>
  218. private List<Rectangle> MergeRectangles (List<Rectangle> rectangles)
  219. {
  220. // Simplified merging logic: this does not handle all edge cases for merging overlapping rectangles.
  221. // For a full implementation, a plane sweep algorithm or similar would be needed.
  222. List<Rectangle> merged = new List<Rectangle> (rectangles);
  223. bool mergedAny;
  224. do
  225. {
  226. mergedAny = false;
  227. for (var i = 0; i < merged.Count; i++)
  228. {
  229. for (int j = i + 1; j < merged.Count; j++)
  230. {
  231. if (merged [i].IntersectsWith (merged [j]))
  232. {
  233. merged [i] = Rectangle.Union (merged [i], merged [j]);
  234. merged.RemoveAt (j);
  235. mergedAny = true;
  236. break;
  237. }
  238. }
  239. if (mergedAny)
  240. {
  241. break;
  242. }
  243. }
  244. }
  245. while (mergedAny);
  246. return merged;
  247. }
  248. /// <summary>
  249. /// Subtracts the specified rectangle from the original rectangle, returning the resulting rectangles.
  250. /// </summary>
  251. /// <param name="original">The original rectangle.</param>
  252. /// <param name="subtract">The rectangle to subtract from the original.</param>
  253. /// <returns>An enumerable collection of resulting rectangles after subtraction.</returns>
  254. private IEnumerable<Rectangle> SubtractRectangle (Rectangle original, Rectangle subtract)
  255. {
  256. if (!original.IntersectsWith (subtract))
  257. {
  258. yield return original;
  259. yield break;
  260. }
  261. // Top segment
  262. if (original.Top < subtract.Top)
  263. {
  264. yield return new (original.Left, original.Top, original.Width, subtract.Top - original.Top);
  265. }
  266. // Bottom segment
  267. if (original.Bottom > subtract.Bottom)
  268. {
  269. yield return new (original.Left, subtract.Bottom, original.Width, original.Bottom - subtract.Bottom);
  270. }
  271. // Left segment
  272. if (original.Left < subtract.Left)
  273. {
  274. int top = Math.Max (original.Top, subtract.Top);
  275. int bottom = Math.Min (original.Bottom, subtract.Bottom);
  276. if (bottom > top)
  277. {
  278. yield return new (original.Left, top, subtract.Left - original.Left, bottom - top);
  279. }
  280. }
  281. // Right segment
  282. if (original.Right > subtract.Right)
  283. {
  284. int top = Math.Max (original.Top, subtract.Top);
  285. int bottom = Math.Min (original.Bottom, subtract.Bottom);
  286. if (bottom > top)
  287. {
  288. yield return new (subtract.Right, top, original.Right - subtract.Right, bottom - top);
  289. }
  290. }
  291. }
  292. /// <summary>
  293. /// Releases all resources used by the <see cref="Region"/>.
  294. /// </summary>
  295. public void Dispose () { _rectangles.Clear (); }
  296. }