Texture2DAtlas.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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.Collections;
  6. using System.Collections.Generic;
  7. using System.Runtime.InteropServices;
  8. using Microsoft.Xna.Framework;
  9. using Microsoft.Xna.Framework.Graphics;
  10. using MonoGame.Extended.Animations;
  11. namespace MonoGame.Extended.Graphics;
  12. /// <summary>
  13. /// Represents a 2D texture atlas that contains a collection of texture regions.
  14. /// </summary>
  15. /// <remarks>
  16. /// <para>
  17. /// A texture atlas, also known as a tile map, tile engine, or sprite sheet, is a large image that contains a
  18. /// collection of sub-images, or "textures", each representing a texture map for a specific part of a 2D or 3D model.
  19. /// </para>
  20. /// <para>
  21. /// These sub-textures can be rendered by adjusting the texture coordinates (UV map) to reference the appropriate
  22. /// part of the atlas. This technique allows efficient rendering in applications where many small textures are
  23. /// frequently used.
  24. /// </para>
  25. /// <para>
  26. /// By storing textures in a single atlas, the graphics hardware treats them as a single unit, which can save memory
  27. /// and improve performance by reducing the number of rendering state changes. Binding one large texture once is
  28. /// typically faster than binding multiple smaller textures individually.
  29. /// </para>
  30. /// <para>
  31. /// However, careful alignment is necessary to avoid texture bleeding when using mipmapping, and to prevent artifacts
  32. /// between tiles when using texture compression.
  33. /// </para>
  34. /// </remarks>
  35. public class Texture2DAtlas : IEnumerable<Texture2DRegion>
  36. {
  37. private readonly List<Texture2DRegion> _regionsByIndex = new List<Texture2DRegion>();
  38. private readonly Dictionary<string, Texture2DRegion> _regionsByName = new Dictionary<string, Texture2DRegion>();
  39. /// <summary>
  40. /// Gets the name of the texture atlas.
  41. /// </summary>
  42. public string Name { get; }
  43. /// <summary>
  44. /// Gets the underlying 2D texture.
  45. /// </summary>
  46. public Texture2D Texture { get; }
  47. /// <summary>
  48. /// Gets the number of regions in the atlas.
  49. /// </summary>
  50. public int RegionCount => _regionsByIndex.Count;
  51. /// <summary>
  52. /// Gets the <see cref="Texture2DRegion"/> at the specified index.
  53. /// </summary>
  54. /// <param name="index">The index of the texture region.</param>
  55. /// <returns>The texture region at the specified index.</returns>
  56. /// <exception cref="ArgumentOutOfRangeException">
  57. /// Thrown if the value of the <paramref name="index"/> parameter is less than zero or greater than or equal to
  58. /// the total number of regions in this atlas.
  59. /// </exception>
  60. public Texture2DRegion this[int index] => GetRegion(index);
  61. /// <summary>
  62. /// Gets the <see cref="Texture2DRegion"/> with the specified name.
  63. /// </summary>
  64. /// <param name="name">The name of the texture region.</param>
  65. /// <returns>The texture region with the specified name.</returns>
  66. /// <exception cref="KeyNotFoundException">
  67. /// Thrown if this atlas does not contain a region with a name that matches the <paramref name="name"/> parameter.
  68. /// </exception>
  69. public Texture2DRegion this[string name] => GetRegion(name);
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="Texture2DAtlas"/> class with the specified texture.
  72. /// </summary>
  73. /// <param name="texture">The texture to create the atlas from.</param>
  74. /// <exception cref="ArgumentNullException">Thrown if <paramref name="texture"/> is null.</exception>
  75. /// <exception cref="ObjectDisposedException">Thrown if <paramref name="texture"/> is disposed.</exception>
  76. public Texture2DAtlas(Texture2D texture) : this(null, texture) { }
  77. /// <summary>
  78. /// Initializes a new instance of the <see cref="Texture2DAtlas"/> class with the specified name and texture.
  79. /// </summary>
  80. /// <param name="name">The name of the texture atlas.</param>
  81. /// <param name="texture">The texture to create the atlas from.</param>
  82. /// <exception cref="ArgumentNullException">Thrown if <paramref name="texture"/> is null.</exception>
  83. /// <exception cref="ObjectDisposedException">Thrown if <paramref name="texture"/> is disposed.</exception>
  84. public Texture2DAtlas(string name, Texture2D texture)
  85. {
  86. ArgumentNullException.ThrowIfNull(texture);
  87. if (texture.IsDisposed)
  88. {
  89. throw new ObjectDisposedException(nameof(texture), $"{nameof(texture)} was disposed prior");
  90. }
  91. if (string.IsNullOrEmpty(name))
  92. {
  93. name = $"{texture.Name}Atlas";
  94. }
  95. Name = name;
  96. Texture = texture;
  97. }
  98. /// <summary>
  99. /// Creates a new texture region and adds it to this atlas.
  100. /// </summary>
  101. /// <param name="x">The x-coordinate of the region.</param>
  102. /// <param name="y">The y-coordinate of the region.</param>
  103. /// <param name="width">The width, in pixels, of the region.</param>
  104. /// <param name="height">The height, in pixels, of the region.</param>
  105. /// <returns>The created texture region.</returns>
  106. public Texture2DRegion CreateRegion(int x, int y, int width, int height) => CreateRegion(new Rectangle(x, y, width, height), null);
  107. /// <summary>
  108. /// Creates a new texture region with the specified name and adds it to this atlas.
  109. /// </summary>
  110. /// <param name="x">The x-coordinate of the region.</param>
  111. /// <param name="y">The y-coordinate of the region.</param>
  112. /// <param name="width">The width, in pixels, of the region.</param>
  113. /// <param name="height">The height, in pixels, of the region.</param>
  114. /// <param name="name">The name of the texture region.</param>
  115. /// <returns>The created texture region.</returns>
  116. /// <exception cref="InvalidOperationException">
  117. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  118. /// </exception>
  119. public Texture2DRegion CreateRegion(int x, int y, int width, int height, string name) => CreateRegion(new Rectangle(x, y, width, height), name);
  120. /// <summary>
  121. /// Creates a new texture region and adds it to this atlas.
  122. /// </summary>
  123. /// <param name="location">The location of the region.</param>
  124. /// <param name="size">The size, in pixels, of the region.</param>
  125. /// <returns>The created texture region.</returns>
  126. public Texture2DRegion CreateRegion(Point location, Size size) => CreateRegion(new Rectangle(location.X, location.Y, size.Width, size.Height), null);
  127. /// <summary>
  128. /// Creates a new texture region with the specified name and adds it to this atlas.
  129. /// </summary>
  130. /// <param name="location">The location of the region.</param>
  131. /// <param name="size">The size, in pixels, of the region.</param>
  132. /// <param name="name">The name of the texture region.</param>
  133. /// <returns>The created texture region.</returns>
  134. /// <exception cref="InvalidOperationException">
  135. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  136. /// </exception>
  137. public Texture2DRegion CreateRegion(string name, Point location, Size size) => CreateRegion(new Rectangle(location.X, location.Y, size.Width, size.Height), name);
  138. /// <summary>
  139. /// Creates a new texture region and adds it to this atlas.
  140. /// </summary>
  141. /// <param name="bounds">The bounds of the region.</param>
  142. /// <returns>The created texture region.</returns>
  143. public Texture2DRegion CreateRegion(Rectangle bounds) => CreateRegion(bounds, null);
  144. /// <summary>
  145. /// Creates a new texture region with the specified name and adds it to this atlas.
  146. /// </summary>
  147. /// <param name="bounds">The bounds of the region.</param>
  148. /// <param name="name">The name of the texture region.</param>
  149. /// <returns>The created texture region.</returns>
  150. /// <exception cref="InvalidOperationException">
  151. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  152. /// </exception>
  153. public Texture2DRegion CreateRegion(Rectangle bounds, string name)
  154. {
  155. Texture2DRegion region = new Texture2DRegion(Texture, bounds, name);
  156. AddRegion(region);
  157. return region;
  158. }
  159. /// <summary>
  160. /// Creates a new texture region with the specified name and adds it to this atlas.
  161. /// </summary>
  162. /// <param name="bounds">The bounds of the region.</param>
  163. /// <param name="name">The name of the texture region.</param>
  164. /// <param name="isRotated">A value indicating whether this texture region is rotated 90 degrees clockwise in the atlas.</param>
  165. /// <returns>The created texture region.</returns>
  166. /// <exception cref="InvalidOperationException">
  167. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  168. /// </exception>
  169. public Texture2DRegion CreateRegion(Rectangle bounds, bool isRotated, Size originalSize, Vector2 trimOffset, Vector2? originNormalized, string name)
  170. {
  171. Texture2DRegion region = new Texture2DRegion(Texture, bounds.X, bounds.Y, bounds.Width, bounds.Height, isRotated, originalSize, trimOffset, originNormalized, name);
  172. AddRegion(region);
  173. return region;
  174. }
  175. /// <summary>
  176. /// Determines whether the atlas contains a region with the specified name.
  177. /// </summary>
  178. /// <param name="name">The name of the region.</param>
  179. /// <returns>
  180. /// <see langword="true"/> if the atlas contains a region with the specified name; otherwise,
  181. /// <see langword="false"/>.
  182. /// </returns>
  183. public bool ContainsRegion(string name) => _regionsByName.ContainsKey(name);
  184. /// <summary>
  185. /// Gets the index of the region with the specified name.
  186. /// </summary>
  187. /// <param name="name">The name of the region.</param>
  188. /// <returns>The index of the region if found; otherwise, <c>-1</c>.</returns>
  189. public int GetIndexOfRegion(string name)
  190. {
  191. for (int i = 0; i < _regionsByIndex.Count; i++)
  192. {
  193. if (_regionsByIndex[i].Name == name)
  194. {
  195. return i;
  196. }
  197. }
  198. return -1;
  199. }
  200. /// <summary>
  201. /// Gets the region at the specified index.
  202. /// </summary>
  203. /// <param name="index">The index of the region.</param>
  204. /// <returns>The region at the specified index.</returns>
  205. /// <exception cref="ArgumentOutOfRangeException">
  206. /// Throw if the value of the <paramref name="index"/> is less than zero or is greater than or equal to the total
  207. /// number of regions in this atlas.
  208. /// </exception>
  209. public Texture2DRegion GetRegion(int index) => _regionsByIndex[index];
  210. /// <summary>
  211. /// Gets the region with the specified name.
  212. /// </summary>
  213. /// <param name="name">The name of the region.</param>
  214. /// <returns>The region with the specified name.</returns>
  215. /// <exception cref="KeyNotFoundException">
  216. /// Thrown if this atlas does not contain a region with a name that matches the <paramref name="name"/> parameter.
  217. /// </exception>
  218. public Texture2DRegion GetRegion(string name) => _regionsByName[name];
  219. /// <summary>
  220. /// Tries to get the region at the specified index.
  221. /// </summary>
  222. /// <param name="index">The index of the region.</param>
  223. /// <param name="region">
  224. /// When this method returns, contains the region at the specified index, if the index is found; otherwise,
  225. /// <see langword="null"/>.
  226. /// </param>
  227. /// <returns>
  228. /// <see langword="true"/> if the region is found at the specified index; otherwise, <see langword="false"/>.
  229. /// </returns>
  230. public bool TryGetRegion(int index, out Texture2DRegion region)
  231. {
  232. region = default;
  233. if (index < 0 || index >= _regionsByIndex.Count)
  234. {
  235. return false;
  236. }
  237. region = _regionsByIndex[index];
  238. return true;
  239. }
  240. /// <summary>
  241. /// Tries to get the region with the specified name.
  242. /// </summary>
  243. /// <param name="name">The name of the region.</param>
  244. /// <param name="region">
  245. /// When this method returns, contains the region with the specified name, if the name is found; otherwise,
  246. /// <see langword="null"/>.
  247. /// </param>
  248. /// <returns>
  249. /// <see langword="true"/> if the region is found with the specified name; otherwise, <see langword="false"/>.
  250. /// </returns>
  251. public bool TryGetRegion(string name, out Texture2DRegion region) => _regionsByName.TryGetValue(name, out region);
  252. /// <summary>
  253. /// Gets the regions at the specified indexes.
  254. /// </summary>
  255. /// <param name="indexes">The indexes of the regions to get.</param>
  256. /// <returns>An array of the regions at the specified indexes.</returns>
  257. /// <exception cref="ArgumentOutOfRangeException">
  258. /// Thrown if the value of any index in the <paramref name="indexes"/> parameter is less than zero or is greater
  259. /// than or equal to the total number of regions in this atlas.
  260. /// </exception>
  261. public Texture2DRegion[] GetRegions(params int[] indexes)
  262. {
  263. Texture2DRegion[] regions = new Texture2DRegion[indexes.Length];
  264. for (int i = 0; i < indexes.Length; i++)
  265. {
  266. regions[i] = GetRegion(indexes[i]);
  267. }
  268. return regions;
  269. }
  270. internal Texture2DRegion[] GetRegions(ReadOnlySpan<IAnimationFrame> frames)
  271. {
  272. Texture2DRegion[] regions = new Texture2DRegion[frames.Length];
  273. for (int i = 0; i < frames.Length; i++)
  274. {
  275. regions[i] = GetRegion(frames[i].FrameIndex);
  276. }
  277. return regions;
  278. }
  279. /// <summary>
  280. /// Gets the regions with the specified names.
  281. /// </summary>
  282. /// <param name="names">The names of the regions to get.</param>
  283. /// <returns>An array of the regions with the specified names.</returns>
  284. /// <exception cref="KeyNotFoundException">
  285. /// Thrown if a region is not found in this atlas with a name that matches any of the names in the
  286. /// <paramref name="names"/> parameter.
  287. /// </exception>
  288. public Texture2DRegion[] GetRegions(params string[] names)
  289. {
  290. Texture2DRegion[] regions = new Texture2DRegion[names.Length];
  291. for (int i = 0; i < names.Length; i++)
  292. {
  293. regions[i] = GetRegion(names[i]);
  294. }
  295. return regions;
  296. }
  297. /// <summary>
  298. /// Removes the region at the specified index.
  299. /// </summary>
  300. /// <param name="index">The index of the region to remove.</param>
  301. /// <returns>
  302. /// <see langword="true"/> if the region is successfully removed; otherwise, <see langword="false"/>.
  303. /// </returns>
  304. /// <exception cref="ArgumentOutOfRangeException">
  305. /// Throw if the value of the <paramref name="index"/> is less than zero or is greater than or equal to the total
  306. /// number of regions in this atlas.
  307. /// </exception>
  308. public bool RemoveRegion(int index)
  309. {
  310. if (TryGetRegion(index, out Texture2DRegion region))
  311. {
  312. return RemoveRegion(region);
  313. }
  314. return false;
  315. }
  316. /// <summary>
  317. /// Removes the region with the specified name.
  318. /// </summary>
  319. /// <param name="name">The name of the region to remove.</param>
  320. /// <returns>
  321. /// <see langword="true"/> if the region is successfully removed; otherwise, <see langword="false"/>.
  322. /// </returns>
  323. public bool RemoveRegion(string name)
  324. {
  325. if (TryGetRegion(name, out Texture2DRegion region))
  326. {
  327. return RemoveRegion(region);
  328. }
  329. return false;
  330. }
  331. /// <summary>
  332. /// Removes all regions from the atlas.
  333. /// </summary>
  334. public void ClearRegions()
  335. {
  336. _regionsByIndex.Clear();
  337. _regionsByName.Clear();
  338. }
  339. private void AddRegion(Texture2DRegion region)
  340. {
  341. if (_regionsByName.ContainsKey(region.Name))
  342. {
  343. throw new InvalidOperationException($"This {nameof(Texture2DAtlas)} already contains a {nameof(Texture2DRegion)} with the name '{region.Name}'");
  344. }
  345. _regionsByIndex.Add(region);
  346. _regionsByName.Add(region.Name, region);
  347. }
  348. /// <summary>
  349. /// Creates a new <see cref="Sprite"/> using the region from this atlas at the specified index.
  350. /// </summary>
  351. /// <param name="regionIndex">The index of the region to use.</param>
  352. /// <returns>The <see cref="Sprite"/> created using the region at the specified index.</returns>
  353. /// <exception cref="ArgumentOutOfRangeException">
  354. /// Throw if the value of the <paramref name="regionIndex"/> is less than zero or is greater than or equal to the total
  355. /// number of regions in this atlas.
  356. /// </exception>
  357. public Sprite CreateSprite(int regionIndex)
  358. {
  359. Texture2DRegion region = GetRegion(regionIndex);
  360. return new Sprite(region);
  361. }
  362. /// <summary>
  363. /// Creates a new <see cref="Sprite"/> using the region from this atlas with the specified name.
  364. /// </summary>
  365. /// <param name="regionName">The name of the region to use.</param>
  366. /// <returns>The <see cref="Sprite"/> created using the region with the specified name.</returns>
  367. /// <exception cref="KeyNotFoundException">
  368. /// Thrown if this atlas does not contain a region with a name that matches the <paramref name="regionName"/> parameter.
  369. /// </exception>
  370. public Sprite CreateSprite(string regionName)
  371. {
  372. Texture2DRegion region = GetRegion(regionName);
  373. return new Sprite(region);
  374. }
  375. private bool RemoveRegion(Texture2DRegion region) => _regionsByIndex.Remove(region) && _regionsByName.Remove(region.Name);
  376. /// <summary>
  377. /// Returns an enumerator that iterates through the collection of texture regions.
  378. /// </summary>
  379. /// <returns>An enumerator that can be used to iterate through the collection.</returns>
  380. public IEnumerator<Texture2DRegion> GetEnumerator() => _regionsByIndex.GetEnumerator();
  381. /// <summary>
  382. /// Returns an enumerator that iterates through the collection of texture regions.
  383. /// </summary>
  384. /// <returns>An enumerator that can be used to iterate through the collection.</returns>
  385. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  386. /// <summary>
  387. /// Creates a new <see cref="Texture2DAtlas"/> from the specified texture by dividing it into regions.
  388. /// </summary>
  389. /// <param name="name">The name of the texture atlas.</param>
  390. /// <param name="texture">The source texture to create the atlas from.</param>
  391. /// <param name="regionWidth">The width, in pixels, of each region.</param>
  392. /// <param name="regionHeight">The height, in pixels, of each region.</param>
  393. /// <param name="maxRegionCount">
  394. /// The maximum number of regions to create. Defaults to <see cref="int.MaxValue"/>.
  395. /// </param>
  396. /// <param name="margin">
  397. /// The margin, in pixels, to leave around the edges of the texture. Defaults to <c>0</c>.
  398. /// </param>
  399. /// <param name="spacing">The spacing, in pixels, between regions. Defaults to <c>0</c>.</param>
  400. /// <returns>A <see cref="Texture2DAtlas"/> containing the created regions.</returns>
  401. /// <remarks>
  402. /// Region names are automatically generated using the pattern <c>{name}_{index}</c>, where <paramref name="name"/>
  403. /// is the atlas name and <c>index</c> is the sequential region number starting from 0. For example, if the atlas
  404. /// is named "spritesheet", the regions will be named "spritesheet_0", "spritesheet_1", "spritesheet_2", etc.
  405. /// Regions are created in row-major order (left-to-right, top-to-bottom).
  406. /// </remarks>
  407. /// <exception cref="ArgumentNullException">Thrown if <paramref name="texture"/> is null.</exception>
  408. /// <exception cref="ObjectDisposedException">Thrown if <paramref name="texture"/> is disposed.</exception>
  409. public static Texture2DAtlas Create(string name, Texture2D texture, int regionWidth, int regionHeight,
  410. int maxRegionCount = int.MaxValue, int margin = 0, int spacing = 0)
  411. {
  412. ReadOnlySpan<CalculatedRegion> regions = CalculateRegions(name, texture.Width, texture.Height, regionWidth, regionHeight, maxRegionCount, margin, spacing);
  413. Texture2DAtlas textureAtlas = new(name, texture);
  414. for (int i = 0; i < regions.Length; i++)
  415. {
  416. CalculatedRegion region = regions[i];
  417. textureAtlas.CreateRegion(region.bounds, region.Name);
  418. }
  419. return textureAtlas;
  420. }
  421. internal readonly record struct CalculatedRegion(Rectangle bounds, string Name);
  422. internal static ReadOnlySpan<CalculatedRegion> CalculateRegions(string atlasName, int textureWidth, int textureHeight, int regionWidth, int regionHeight, int maxRegionCount, int margin, int spacing)
  423. {
  424. int width = textureWidth - margin;
  425. int height = textureHeight - margin;
  426. int xIncrement = regionWidth + spacing;
  427. int yIncrement = regionHeight + spacing;
  428. int columns = (width - margin + spacing) / xIncrement;
  429. int rows = (height - margin + spacing) / yIncrement;
  430. int totalRegions = columns * rows;
  431. // We know what the final size of the collection will be so calculate it
  432. // and use it to prevent reallocations as items are added to the list
  433. int capacity = Math.Min(totalRegions, maxRegionCount);
  434. List<CalculatedRegion> regions = new List<CalculatedRegion>(capacity);
  435. for (int i = 0; i < totalRegions; i++)
  436. {
  437. int x = margin + (i % columns) * xIncrement;
  438. int y = margin + (i / columns) * yIncrement;
  439. if (x >= width || y >= height)
  440. {
  441. break;
  442. }
  443. Rectangle bounds = new Rectangle(x, y, regionWidth, regionHeight);
  444. string name = $"{atlasName}_{i}";
  445. CalculatedRegion region = new(bounds, name);
  446. regions.Add(region);
  447. if (regions.Count >= maxRegionCount)
  448. {
  449. break;
  450. }
  451. }
  452. return CollectionsMarshal.AsSpan(regions);
  453. }
  454. }