AtlasUtilities.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if UNITY_2019_3_OR_NEWER
  30. #define CONFIGURABLE_ENTER_PLAY_MODE
  31. #endif
  32. using UnityEngine;
  33. using System.Collections.Generic;
  34. using System;
  35. namespace Spine.Unity.AttachmentTools {
  36. public static class AtlasUtilities {
  37. internal const TextureFormat SpineTextureFormat = TextureFormat.RGBA32;
  38. internal const float DefaultMipmapBias = -0.5f;
  39. internal const bool UseMipMaps = false;
  40. internal const float DefaultScale = 0.01f;
  41. const int NonrenderingRegion = -1;
  42. #if CONFIGURABLE_ENTER_PLAY_MODE
  43. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  44. static void Init () {
  45. // handle disabled domain reload
  46. AtlasUtilities.ClearCache();
  47. }
  48. #endif
  49. public static AtlasRegion ToAtlasRegion (this Texture2D t, Material materialPropertySource, float scale = DefaultScale) {
  50. return t.ToAtlasRegion(materialPropertySource.shader, scale, materialPropertySource);
  51. }
  52. public static AtlasRegion ToAtlasRegion (this Texture2D t, Shader shader, float scale = DefaultScale, Material materialPropertySource = null) {
  53. var material = new Material(shader);
  54. if (materialPropertySource != null) {
  55. material.CopyPropertiesFromMaterial(materialPropertySource);
  56. material.shaderKeywords = materialPropertySource.shaderKeywords;
  57. }
  58. material.mainTexture = t;
  59. var page = material.ToSpineAtlasPage();
  60. float width = t.width;
  61. float height = t.height;
  62. var region = new AtlasRegion();
  63. region.name = t.name;
  64. region.index = -1;
  65. region.rotate = false;
  66. // World space units
  67. Vector2 boundsMin = Vector2.zero, boundsMax = new Vector2(width, height) * scale;
  68. // Texture space/pixel units
  69. region.width = (int)width;
  70. region.originalWidth = (int)width;
  71. region.height = (int)height;
  72. region.originalHeight = (int)height;
  73. region.offsetX = width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0));
  74. region.offsetY = height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0));
  75. // Use the full area of the texture.
  76. region.u = 0;
  77. region.v = 1;
  78. region.u2 = 1;
  79. region.v2 = 0;
  80. region.x = 0;
  81. region.y = 0;
  82. region.page = page;
  83. return region;
  84. }
  85. /// <summary>
  86. /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
  87. public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) {
  88. return t.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource);
  89. }
  90. /// <summary>
  91. /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
  92. public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) {
  93. var material = new Material(shader);
  94. if (materialPropertySource != null) {
  95. material.CopyPropertiesFromMaterial(materialPropertySource);
  96. material.shaderKeywords = materialPropertySource.shaderKeywords;
  97. }
  98. var newTexture = t.GetClone(textureFormat, mipmaps, applyPMA : true);
  99. newTexture.name = t.name + "-pma-";
  100. material.name = t.name + shader.name;
  101. material.mainTexture = newTexture;
  102. var page = material.ToSpineAtlasPage();
  103. var region = newTexture.ToAtlasRegion(shader);
  104. region.page = page;
  105. return region;
  106. }
  107. /// <summary>
  108. /// Creates a new Spine.AtlasPage from a UnityEngine.Material. If the material has a preassigned texture, the page width and height will be set.</summary>
  109. public static AtlasPage ToSpineAtlasPage (this Material m) {
  110. var newPage = new AtlasPage {
  111. rendererObject = m,
  112. name = m.name
  113. };
  114. var t = m.mainTexture;
  115. if (t != null) {
  116. newPage.width = t.width;
  117. newPage.height = t.height;
  118. }
  119. return newPage;
  120. }
  121. /// <summary>
  122. /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite.</summary>
  123. public static AtlasRegion ToAtlasRegion (this Sprite s, AtlasPage page) {
  124. if (page == null) throw new System.ArgumentNullException("page", "page cannot be null. AtlasPage determines which texture region belongs and how it should be rendered. You can use material.ToSpineAtlasPage() to get a shareable AtlasPage from a Material, or use the sprite.ToAtlasRegion(material) overload.");
  125. var region = s.ToAtlasRegion();
  126. region.page = page;
  127. return region;
  128. }
  129. /// <summary>
  130. /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. This creates a new AtlasPage object for every AtlasRegion you create. You can centralize Material control by creating a shared atlas page using Material.ToSpineAtlasPage and using the sprite.ToAtlasRegion(AtlasPage) overload.</summary>
  131. public static AtlasRegion ToAtlasRegion (this Sprite s, Material material) {
  132. var region = s.ToAtlasRegion();
  133. region.page = material.ToSpineAtlasPage();
  134. return region;
  135. }
  136. public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) {
  137. return s.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource);
  138. }
  139. /// <summary>
  140. /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
  141. public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) {
  142. var material = new Material(shader);
  143. if (materialPropertySource != null) {
  144. material.CopyPropertiesFromMaterial(materialPropertySource);
  145. material.shaderKeywords = materialPropertySource.shaderKeywords;
  146. }
  147. var tex = s.ToTexture(textureFormat, mipmaps, applyPMA : true);
  148. tex.name = s.name + "-pma-";
  149. material.name = tex.name + shader.name;
  150. material.mainTexture = tex;
  151. var page = material.ToSpineAtlasPage();
  152. var region = s.ToAtlasRegion(true);
  153. region.page = page;
  154. return region;
  155. }
  156. internal static AtlasRegion ToAtlasRegion (this Sprite s, bool isolatedTexture = false) {
  157. var region = new AtlasRegion();
  158. region.name = s.name;
  159. region.index = -1;
  160. region.rotate = s.packed && s.packingRotation != SpritePackingRotation.None;
  161. // World space units
  162. Bounds bounds = s.bounds;
  163. Vector2 boundsMin = bounds.min, boundsMax = bounds.max;
  164. // Texture space/pixel units
  165. Rect spineRect = s.rect.SpineUnityFlipRect(s.texture.height);
  166. region.width = (int)spineRect.width;
  167. region.originalWidth = (int)spineRect.width;
  168. region.height = (int)spineRect.height;
  169. region.originalHeight = (int)spineRect.height;
  170. region.offsetX = spineRect.width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0));
  171. region.offsetY = spineRect.height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0));
  172. if (isolatedTexture) {
  173. region.u = 0;
  174. region.v = 1;
  175. region.u2 = 1;
  176. region.v2 = 0;
  177. region.x = 0;
  178. region.y = 0;
  179. } else {
  180. Texture2D tex = s.texture;
  181. Rect uvRect = TextureRectToUVRect(s.textureRect, tex.width, tex.height);
  182. region.u = uvRect.xMin;
  183. region.v = uvRect.yMax;
  184. region.u2 = uvRect.xMax;
  185. region.v2 = uvRect.yMin;
  186. region.x = (int)spineRect.x;
  187. region.y = (int)spineRect.y;
  188. }
  189. return region;
  190. }
  191. #region Runtime Repacking
  192. static readonly Dictionary<AtlasRegion, int> existingRegions = new Dictionary<AtlasRegion, int>();
  193. static readonly List<int> regionIndices = new List<int>();
  194. static readonly List<Texture2D> texturesToPack = new List<Texture2D>();
  195. static readonly List<AtlasRegion> originalRegions = new List<AtlasRegion>();
  196. static readonly List<AtlasRegion> repackedRegions = new List<AtlasRegion>();
  197. static readonly List<Attachment> repackedAttachments = new List<Attachment>();
  198. static List<Texture2D>[] texturesToPackAtParam = new List<Texture2D>[1];
  199. /// <summary>
  200. /// Fills the outputAttachments list with new attachment objects based on the attachments in sourceAttachments,
  201. /// but mapped to a new single texture using the same material.</summary>
  202. /// <remarks>Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
  203. /// to free resources.
  204. /// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory
  205. /// footprint when used excessively. Set <paramref name="clearCache"/> to <c>true</c>
  206. /// or call <see cref="AtlasUtilities.ClearCache()"/> to clear this texture cache.
  207. /// You may want to call <c>Resources.UnloadUnusedAssets()</c> after that.
  208. /// </remarks>
  209. /// <param name="sourceAttachments">The list of attachments to be repacked.</param>
  210. /// <param name = "outputAttachments">The List(Attachment) to populate with the newly created Attachment objects.</param>
  211. /// <param name="materialPropertySource">May be null. If no Material property source is provided, no special </param>
  212. /// <param name="clearCache">When set to <c>true</c>, <see cref="AtlasUtilities.ClearCache()"/> is called after
  213. /// repacking to clear the texture cache. See remarks for additional info.</param>
  214. public static void GetRepackedAttachments (List<Attachment> sourceAttachments, List<Attachment> outputAttachments, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, string newAssetName = "Repacked Attachments", bool clearCache = false, bool useOriginalNonrenderables = true) {
  215. if (sourceAttachments == null) throw new System.ArgumentNullException("sourceAttachments");
  216. if (outputAttachments == null) throw new System.ArgumentNullException("outputAttachments");
  217. // Use shared lists to detect and use shared regions.
  218. existingRegions.Clear();
  219. regionIndices.Clear();
  220. texturesToPack.Clear();
  221. originalRegions.Clear();
  222. outputAttachments.Clear();
  223. outputAttachments.AddRange(sourceAttachments);
  224. int newRegionIndex = 0;
  225. for (int i = 0, n = sourceAttachments.Count; i < n; i++) {
  226. var originalAttachment = sourceAttachments[i];
  227. if (IsRenderable(originalAttachment)) {
  228. var newAttachment = originalAttachment.GetCopy(true);
  229. var region = newAttachment.GetRegion();
  230. int existingIndex;
  231. if (existingRegions.TryGetValue(region, out existingIndex)) {
  232. regionIndices.Add(existingIndex); // Store the region index for the eventual new attachment.
  233. } else {
  234. originalRegions.Add(region);
  235. texturesToPack.Add(region.ToTexture(textureFormat, mipmaps)); // Add the texture to the PackTextures argument
  236. existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions
  237. regionIndices.Add(newRegionIndex); // Store the region index for the eventual new attachment.
  238. newRegionIndex++;
  239. }
  240. outputAttachments[i] = newAttachment;
  241. } else {
  242. outputAttachments[i] = useOriginalNonrenderables ? originalAttachment : originalAttachment.GetCopy(true);
  243. regionIndices.Add(NonrenderingRegion); // Output attachments pairs with regionIndexes list 1:1. Pad with a sentinel if the attachment doesn't have a region.
  244. }
  245. }
  246. // Fill a new texture with the collected attachment textures.
  247. var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps);
  248. newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias;
  249. newTexture.name = newAssetName;
  250. // Copy settings
  251. if (texturesToPack.Count > 0) {
  252. var sourceTexture = texturesToPack[0];
  253. newTexture.CopyTextureAttributesFrom(sourceTexture);
  254. }
  255. var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize);
  256. // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments
  257. Shader shader = materialPropertySource == null ? Shader.Find("Spine/Skeleton") : materialPropertySource.shader;
  258. var newMaterial = new Material(shader);
  259. if (materialPropertySource != null) {
  260. newMaterial.CopyPropertiesFromMaterial(materialPropertySource);
  261. newMaterial.shaderKeywords = materialPropertySource.shaderKeywords;
  262. }
  263. newMaterial.name = newAssetName;
  264. newMaterial.mainTexture = newTexture;
  265. var page = newMaterial.ToSpineAtlasPage();
  266. page.name = newAssetName;
  267. repackedRegions.Clear();
  268. for (int i = 0, n = originalRegions.Count; i < n; i++) {
  269. var oldRegion = originalRegions[i];
  270. var newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page);
  271. repackedRegions.Add(newRegion);
  272. }
  273. // Map the cloned attachments to the repacked atlas.
  274. for (int i = 0, n = outputAttachments.Count; i < n; i++) {
  275. var a = outputAttachments[i];
  276. if (IsRenderable(a))
  277. a.SetRegion(repackedRegions[regionIndices[i]]);
  278. }
  279. // Clean up.
  280. if (clearCache)
  281. AtlasUtilities.ClearCache();
  282. outputTexture = newTexture;
  283. outputMaterial = newMaterial;
  284. }
  285. /// <summary>
  286. /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas
  287. /// comprised of all the regions from the original skin.</summary>
  288. /// <remarks>GetRepackedSkin is an expensive operation, preferably call it at level load time.
  289. /// No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.
  290. /// Returned <c>Material</c> and <c>Texture</c> behave like <c>new Texture2D()</c>, thus you need to call <c>Destroy()</c>
  291. /// to free resources.
  292. /// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory
  293. /// footprint when used excessively. Set <paramref name="clearCache"/> to <c>true</c>
  294. /// or call <see cref="AtlasUtilities.ClearCache()"/> to clear this texture cache.
  295. /// You may want to call <c>Resources.UnloadUnusedAssets()</c> after that.
  296. /// </remarks>
  297. /// <param name="clearCache">When set to <c>true</c>, <see cref="AtlasUtilities.ClearCache()"/> is called after
  298. /// repacking to clear the texture cache. See remarks for additional info.</param>
  299. /// <param name="additionalTexturePropertyIDsToCopy">Optional additional textures (such as normal maps) to copy while repacking.
  300. /// To copy e.g. the main texture and normal maps, pass 'new int[] { Shader.PropertyToID("_BumpMap") }' at this parameter.</param>
  301. /// <param name="additionalOutputTextures">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
  302. /// this array will be filled with the resulting repacked texture for every property,
  303. /// just as the main repacked texture is assigned to <c>outputTexture</c>.</param>
  304. /// <param name="additionalTextureFormats">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
  305. /// this array will be used as <c>TextureFormat</c> at the Texture at the respective property.
  306. /// When <c>additionalTextureFormats</c> is <c>null</c> or when its array size is smaller,
  307. /// <c>textureFormat</c> is used where there exists no corresponding array item.</param>
  308. /// <param name="additionalTextureIsLinear">When <c>additionalTexturePropertyIDsToCopy</c> is non-null,
  309. /// this array will be used to determine whether <c>linear</c> or <c>sRGB</c> color space is used at the
  310. /// Texture at the respective property. When <c>additionalTextureIsLinear</c> is <c>null</c>, <c>linear</c> color space
  311. /// is assumed at every additional Texture element.
  312. /// When e.g. packing the main texture and normal maps, pass 'new bool[] { true }' at this parameter, because normal maps use
  313. /// linear color space.</param>
  314. public static Skin GetRepackedSkin (this Skin o, string newName, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture,
  315. int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
  316. bool useOriginalNonrenderables = true, bool clearCache = false,
  317. int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
  318. TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
  319. return GetRepackedSkin(o, newName, materialPropertySource.shader, out outputMaterial, out outputTexture,
  320. maxAtlasSize, padding, textureFormat, mipmaps, materialPropertySource,
  321. clearCache, useOriginalNonrenderables, additionalTexturePropertyIDsToCopy, additionalOutputTextures,
  322. additionalTextureFormats, additionalTextureIsLinear);
  323. }
  324. /// <summary>
  325. /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas
  326. /// comprised of all the regions from the original skin.</summary>
  327. /// See documentation of <see cref="GetRepackedSkin"/> for details.
  328. public static Skin GetRepackedSkin (this Skin o, string newName, Shader shader, out Material outputMaterial, out Texture2D outputTexture,
  329. int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
  330. Material materialPropertySource = null, bool clearCache = false, bool useOriginalNonrenderables = true,
  331. int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null,
  332. TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) {
  333. outputTexture = null;
  334. if (additionalTexturePropertyIDsToCopy != null && additionalTextureIsLinear == null) {
  335. additionalTextureIsLinear = new bool[additionalTexturePropertyIDsToCopy.Length];
  336. for (int i = 0; i < additionalTextureIsLinear.Length; ++i) {
  337. additionalTextureIsLinear[i] = true;
  338. }
  339. }
  340. if (o == null) throw new System.NullReferenceException("Skin was null");
  341. var skinAttachments = o.Attachments;
  342. var newSkin = new Skin(newName);
  343. newSkin.bones.AddRange(o.bones);
  344. newSkin.constraints.AddRange(o.constraints);
  345. // Use these to detect and use shared regions.
  346. existingRegions.Clear();
  347. regionIndices.Clear();
  348. // Collect all textures from the attachments of the original skin.
  349. repackedAttachments.Clear();
  350. int numTextureParamsToRepack = 1 + (additionalTexturePropertyIDsToCopy == null ? 0 : additionalTexturePropertyIDsToCopy.Length);
  351. additionalOutputTextures = (additionalTexturePropertyIDsToCopy == null ? null : new Texture2D[additionalTexturePropertyIDsToCopy.Length]);
  352. if (texturesToPackAtParam.Length < numTextureParamsToRepack)
  353. Array.Resize(ref texturesToPackAtParam, numTextureParamsToRepack);
  354. for (int i = 0; i < numTextureParamsToRepack; ++i) {
  355. if (texturesToPackAtParam[i] != null)
  356. texturesToPackAtParam[i].Clear();
  357. else
  358. texturesToPackAtParam[i] = new List<Texture2D>();
  359. }
  360. originalRegions.Clear();
  361. int newRegionIndex = 0;
  362. foreach (var skinEntry in skinAttachments) {
  363. var originalKey = skinEntry.Key;
  364. var originalAttachment = skinEntry.Value;
  365. Attachment newAttachment;
  366. if (IsRenderable(originalAttachment)) {
  367. newAttachment = originalAttachment.GetCopy(true);
  368. var region = newAttachment.GetRegion();
  369. int existingIndex;
  370. if (existingRegions.TryGetValue(region, out existingIndex)) {
  371. regionIndices.Add(existingIndex); // Store the region index for the eventual new attachment.
  372. } else {
  373. originalRegions.Add(region);
  374. for (int i = 0; i < numTextureParamsToRepack; ++i) {
  375. Texture2D regionTexture = (i == 0 ?
  376. region.ToTexture(textureFormat, mipmaps) :
  377. region.ToTexture((additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ?
  378. additionalTextureFormats[i - 1] : textureFormat,
  379. mipmaps, additionalTexturePropertyIDsToCopy[i - 1], additionalTextureIsLinear[i - 1]));
  380. texturesToPackAtParam[i].Add(regionTexture); // Add the texture to the PackTextures argument
  381. }
  382. existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions
  383. regionIndices.Add(newRegionIndex); // Store the region index for the eventual new attachment.
  384. newRegionIndex++;
  385. }
  386. repackedAttachments.Add(newAttachment);
  387. newSkin.SetAttachment(originalKey.SlotIndex, originalKey.Name, newAttachment);
  388. } else {
  389. newSkin.SetAttachment(originalKey.SlotIndex, originalKey.Name, useOriginalNonrenderables ? originalAttachment : originalAttachment.GetCopy(true));
  390. }
  391. }
  392. // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments
  393. var newMaterial = new Material(shader);
  394. if (materialPropertySource != null) {
  395. newMaterial.CopyPropertiesFromMaterial(materialPropertySource);
  396. newMaterial.shaderKeywords = materialPropertySource.shaderKeywords;
  397. }
  398. newMaterial.name = newName;
  399. Rect[] rects = null;
  400. for (int i = 0; i < numTextureParamsToRepack; ++i) {
  401. // Fill a new texture with the collected attachment textures.
  402. var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize,
  403. (i > 0 && additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ?
  404. additionalTextureFormats[i - 1] : textureFormat,
  405. mipmaps,
  406. (i > 0) ? additionalTextureIsLinear[i - 1] : false);
  407. newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias;
  408. var texturesToPack = texturesToPackAtParam[i];
  409. if (texturesToPack.Count > 0) {
  410. var sourceTexture = texturesToPack[0];
  411. newTexture.CopyTextureAttributesFrom(sourceTexture);
  412. }
  413. newTexture.name = newName;
  414. var rectsForTexParam = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize);
  415. if (i == 0) {
  416. rects = rectsForTexParam;
  417. newMaterial.mainTexture = newTexture;
  418. outputTexture = newTexture;
  419. }
  420. else {
  421. newMaterial.SetTexture(additionalTexturePropertyIDsToCopy[i - 1], newTexture);
  422. additionalOutputTextures[i - 1] = newTexture;
  423. }
  424. }
  425. var page = newMaterial.ToSpineAtlasPage();
  426. page.name = newName;
  427. repackedRegions.Clear();
  428. for (int i = 0, n = originalRegions.Count; i < n; i++) {
  429. var oldRegion = originalRegions[i];
  430. var newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page);
  431. repackedRegions.Add(newRegion);
  432. }
  433. // Map the cloned attachments to the repacked atlas.
  434. for (int i = 0, n = repackedAttachments.Count; i < n; i++) {
  435. var a = repackedAttachments[i];
  436. if (IsRenderable(a))
  437. a.SetRegion(repackedRegions[regionIndices[i]]);
  438. }
  439. // Clean up.
  440. if (clearCache)
  441. AtlasUtilities.ClearCache();
  442. outputMaterial = newMaterial;
  443. return newSkin;
  444. }
  445. public static Sprite ToSprite (this AtlasRegion ar, float pixelsPerUnit = 100) {
  446. return Sprite.Create(ar.GetMainTexture(), ar.GetUnityRect(), new Vector2(0.5f, 0.5f), pixelsPerUnit);
  447. }
  448. struct IntAndAtlasRegionKey {
  449. int i;
  450. AtlasRegion region;
  451. public IntAndAtlasRegionKey(int i, AtlasRegion region) {
  452. this.i = i;
  453. this.region = region;
  454. }
  455. public override int GetHashCode () {
  456. return i.GetHashCode() * 23 ^ region.GetHashCode();
  457. }
  458. }
  459. static Dictionary<IntAndAtlasRegionKey, Texture2D> CachedRegionTextures = new Dictionary<IntAndAtlasRegionKey, Texture2D>();
  460. static List<Texture2D> CachedRegionTexturesList = new List<Texture2D>();
  461. /// <summary>
  462. /// Frees up textures cached by repacking and remapping operations.
  463. ///
  464. /// Calling <see cref="AttachmentCloneExtensions.GetRemappedClone"/> with parameter <c>premultiplyAlpha=true</c>,
  465. /// <see cref="GetRepackedAttachments"/> or <see cref="GetRepackedSkin"/> will cache textures for later re-use,
  466. /// which might steadily increase the texture memory footprint when used excessively.
  467. /// You can clear this Texture cache by calling <see cref="AtlasUtilities.ClearCache()"/>.
  468. /// You may also want to call <c>Resources.UnloadUnusedAssets()</c> after that. Be aware that while this cleanup
  469. /// frees up memory, it is also a costly operation and will likely cause a spike in the framerate.
  470. /// Thus it is recommended to perform costly repacking and cleanup operations after e.g. a character customization
  471. /// screen has been exited, and if required additionally after a certain number of <c>GetRemappedClone()</c> calls.
  472. /// </summary>
  473. public static void ClearCache () {
  474. foreach (var t in CachedRegionTexturesList) {
  475. UnityEngine.Object.Destroy(t);
  476. }
  477. CachedRegionTextures.Clear();
  478. CachedRegionTexturesList.Clear();
  479. }
  480. /// <summary>Creates a new Texture2D object based on an AtlasRegion.
  481. /// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data.</summary>
  482. public static Texture2D ToTexture (this AtlasRegion ar, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps,
  483. int texturePropertyId = 0, bool linear = false, bool applyPMA = false) {
  484. Texture2D output;
  485. IntAndAtlasRegionKey cacheKey = new IntAndAtlasRegionKey(texturePropertyId, ar);
  486. CachedRegionTextures.TryGetValue(cacheKey, out output);
  487. if (output == null) {
  488. Texture2D sourceTexture = texturePropertyId == 0 ? ar.GetMainTexture() : ar.GetTexture(texturePropertyId);
  489. Rect r = ar.GetUnityRect();
  490. // Compensate any image resizing due to Texture 'Max Size' import settings.
  491. // sourceTexture.width returns the resized image dimensions, at least in newer Unity versions.
  492. if (sourceTexture.width < ar.page.width) {
  493. float scaleX = (float)(sourceTexture.width) / (float)(ar.page.width);
  494. float scaleY = (float)(sourceTexture.height) / (float)(ar.page.height);
  495. var scale = new Vector2(scaleX, scaleY);
  496. r = new Rect(Vector2.Scale(r.position, scale), Vector2.Scale(r.size, scale));
  497. }
  498. int width = (int)r.width;
  499. int height = (int)r.height;
  500. output = new Texture2D(width, height, textureFormat, mipmaps, linear) { name = ar.name };
  501. output.CopyTextureAttributesFrom(sourceTexture);
  502. if (applyPMA)
  503. AtlasUtilities.CopyTextureApplyPMA(sourceTexture, r, output);
  504. else
  505. AtlasUtilities.CopyTexture(sourceTexture, r, output);
  506. CachedRegionTextures.Add(cacheKey, output);
  507. CachedRegionTexturesList.Add(output);
  508. }
  509. return output;
  510. }
  511. static Texture2D ToTexture (this Sprite s, TextureFormat textureFormat = SpineTextureFormat,
  512. bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) {
  513. var spriteTexture = s.texture;
  514. Rect r;
  515. if (!s.packed || s.packingMode == SpritePackingMode.Rectangle) {
  516. r = s.textureRect;
  517. }
  518. else {
  519. r = new Rect();
  520. r.xMin = Math.Min(s.uv[0].x, s.uv[1].x) * spriteTexture.width;
  521. r.xMax = Math.Max(s.uv[0].x, s.uv[1].x) * spriteTexture.width;
  522. r.yMin = Math.Min(s.uv[0].y, s.uv[2].y) * spriteTexture.height;
  523. r.yMax = Math.Max(s.uv[0].y, s.uv[2].y) * spriteTexture.height;
  524. #if UNITY_EDITOR
  525. if (s.uv.Length > 4) {
  526. Debug.LogError("When using a tightly packed SpriteAtlas with Spine, you may only access Sprites that are packed as 'FullRect' from it! " +
  527. "You can either disable 'Tight Packing' at the whole SpriteAtlas, or change the single Sprite's TextureImporter Setting 'MeshType' to 'Full Rect'." +
  528. "Sprite Asset: " + s.name, s);
  529. }
  530. #endif
  531. }
  532. var newTexture = new Texture2D((int)r.width, (int)r.height, textureFormat, mipmaps, linear);
  533. newTexture.CopyTextureAttributesFrom(spriteTexture);
  534. if (applyPMA)
  535. AtlasUtilities.CopyTextureApplyPMA(spriteTexture, r, newTexture);
  536. else
  537. AtlasUtilities.CopyTexture(spriteTexture, r, newTexture);
  538. return newTexture;
  539. }
  540. static Texture2D GetClone (this Texture2D t, TextureFormat textureFormat = SpineTextureFormat,
  541. bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) {
  542. var newTexture = new Texture2D((int)t.width, (int)t.height, textureFormat, mipmaps, linear);
  543. newTexture.CopyTextureAttributesFrom(t);
  544. if (applyPMA)
  545. AtlasUtilities.CopyTextureApplyPMA(t, new Rect(0, 0, t.width, t.height), newTexture);
  546. else
  547. AtlasUtilities.CopyTexture(t, new Rect(0, 0, t.width, t.height), newTexture);
  548. return newTexture;
  549. }
  550. static void CopyTexture (Texture2D source, Rect sourceRect, Texture2D destination) {
  551. if (SystemInfo.copyTextureSupport == UnityEngine.Rendering.CopyTextureSupport.None) {
  552. // GetPixels fallback for old devices.
  553. Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height);
  554. destination.SetPixels(pixelBuffer);
  555. destination.Apply();
  556. } else {
  557. Graphics.CopyTexture(source, 0, 0, (int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height, destination, 0, 0, 0, 0);
  558. }
  559. }
  560. static void CopyTextureApplyPMA (Texture2D source, Rect sourceRect, Texture2D destination) {
  561. Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height);
  562. for (int i = 0, n = pixelBuffer.Length; i < n; i++) {
  563. Color p = pixelBuffer[i];
  564. float a = p.a;
  565. p.r = p.r * a;
  566. p.g = p.g * a;
  567. p.b = p.b * a;
  568. pixelBuffer[i] = p;
  569. }
  570. destination.SetPixels(pixelBuffer);
  571. destination.Apply();
  572. }
  573. static bool IsRenderable (Attachment a) {
  574. return a is IHasRendererObject;
  575. }
  576. /// <summary>
  577. /// Get a rect with flipped Y so that a Spine atlas rect gets converted to a Unity Sprite rect and vice versa.</summary>
  578. static Rect SpineUnityFlipRect (this Rect rect, int textureHeight) {
  579. rect.y = textureHeight - rect.y - rect.height;
  580. return rect;
  581. }
  582. /// <summary>
  583. /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).
  584. /// This overload relies on region.page.height being correctly set.</summary>
  585. static Rect GetUnityRect (this AtlasRegion region) {
  586. return region.GetSpineAtlasRect().SpineUnityFlipRect(region.page.height);
  587. }
  588. /// <summary>
  589. /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up).</summary>
  590. static Rect GetUnityRect (this AtlasRegion region, int textureHeight) {
  591. return region.GetSpineAtlasRect().SpineUnityFlipRect(textureHeight);
  592. }
  593. /// <summary>
  594. /// Returns a Rect of the AtlasRegion according to Spine texture coordinates. (x-right, y-down)</summary>
  595. static Rect GetSpineAtlasRect (this AtlasRegion region, bool includeRotate = true) {
  596. if (includeRotate && (region.degrees == 90 || region.degrees == 270))
  597. return new Rect(region.x, region.y, region.height, region.width);
  598. else
  599. return new Rect(region.x, region.y, region.width, region.height);
  600. }
  601. /// <summary>
  602. /// Denormalize a uvRect into a texture-space Rect.</summary>
  603. static Rect UVRectToTextureRect (Rect uvRect, int texWidth, int texHeight) {
  604. uvRect.x *= texWidth;
  605. uvRect.width *= texWidth;
  606. uvRect.y *= texHeight;
  607. uvRect.height *= texHeight;
  608. return uvRect;
  609. }
  610. /// <summary>
  611. /// Normalize a texture Rect into UV coordinates.</summary>
  612. static Rect TextureRectToUVRect (Rect textureRect, int texWidth, int texHeight) {
  613. textureRect.x = Mathf.InverseLerp(0, texWidth, textureRect.x);
  614. textureRect.y = Mathf.InverseLerp(0, texHeight, textureRect.y);
  615. textureRect.width = Mathf.InverseLerp(0, texWidth, textureRect.width);
  616. textureRect.height = Mathf.InverseLerp(0, texHeight, textureRect.height);
  617. return textureRect;
  618. }
  619. /// <summary>
  620. /// Creates a new Spine AtlasRegion according to a Unity UV Rect (x-right, y-up, uv-normalized).</summary>
  621. static AtlasRegion UVRectToAtlasRegion (Rect uvRect, AtlasRegion referenceRegion, AtlasPage page) {
  622. var tr = UVRectToTextureRect(uvRect, page.width, page.height);
  623. var rr = tr.SpineUnityFlipRect(page.height);
  624. int x = (int)rr.x, y = (int)rr.y;
  625. int w, h;
  626. if (referenceRegion.degrees == 90 || referenceRegion.degrees == 270) {
  627. w = (int)rr.height;
  628. h = (int)rr.width;
  629. } else {
  630. w = (int)rr.width;
  631. h = (int)rr.height;
  632. }
  633. int originalW = Mathf.RoundToInt((float)w * ((float)referenceRegion.originalWidth / (float)referenceRegion.width));
  634. int originalH = Mathf.RoundToInt((float)h * ((float)referenceRegion.originalHeight / (float)referenceRegion.height));
  635. int offsetX = Mathf.RoundToInt((float)referenceRegion.offsetX * ((float)w / (float)referenceRegion.width));
  636. int offsetY = Mathf.RoundToInt((float)referenceRegion.offsetY * ((float)h / (float)referenceRegion.height));
  637. if (referenceRegion.degrees == 270) {
  638. w = (int)rr.width;
  639. h = (int)rr.height;
  640. }
  641. float u = uvRect.xMin;
  642. float u2 = uvRect.xMax;
  643. float v = uvRect.yMax;
  644. float v2 = uvRect.yMin;
  645. return new AtlasRegion {
  646. page = page,
  647. name = referenceRegion.name,
  648. u = u,
  649. u2 = u2,
  650. v = v,
  651. v2 = v2,
  652. index = -1,
  653. width = w,
  654. originalWidth = originalW,
  655. height = h,
  656. originalHeight = originalH,
  657. offsetX = offsetX,
  658. offsetY = offsetY,
  659. x = x,
  660. y = y,
  661. rotate = referenceRegion.rotate,
  662. degrees = referenceRegion.degrees
  663. };
  664. }
  665. /// <summary>
  666. /// Convenience method for getting the main texture of the material of the page of the region.</summary>
  667. static Texture2D GetMainTexture (this AtlasRegion region) {
  668. var material = (region.page.rendererObject as Material);
  669. return material.mainTexture as Texture2D;
  670. }
  671. /// <summary>
  672. /// Convenience method for getting any texture of the material of the page of the region by texture property name.</summary>
  673. static Texture2D GetTexture (this AtlasRegion region, string texturePropertyName) {
  674. var material = (region.page.rendererObject as Material);
  675. return material.GetTexture(texturePropertyName) as Texture2D;
  676. }
  677. /// <summary>
  678. /// Convenience method for getting any texture of the material of the page of the region by texture property id.</summary>
  679. static Texture2D GetTexture (this AtlasRegion region, int texturePropertyId) {
  680. var material = (region.page.rendererObject as Material);
  681. return material.GetTexture(texturePropertyId) as Texture2D;
  682. }
  683. static void CopyTextureAttributesFrom(this Texture2D destination, Texture2D source) {
  684. destination.filterMode = source.filterMode;
  685. destination.anisoLevel = source.anisoLevel;
  686. #if UNITY_EDITOR
  687. destination.alphaIsTransparency = source.alphaIsTransparency;
  688. #endif
  689. destination.wrapModeU = source.wrapModeU;
  690. destination.wrapModeV = source.wrapModeV;
  691. destination.wrapModeW = source.wrapModeW;
  692. }
  693. #endregion
  694. static float InverseLerp (float a, float b, float value) {
  695. return (value - a) / (b - a);
  696. }
  697. }
  698. }