暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

PowerOfTwoTextureAtlas.cs 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. using System.Collections.Generic;
  2. using UnityEngine.Experimental.Rendering;
  3. namespace UnityEngine.Rendering
  4. {
  5. /// <summary>
  6. /// Texture atlas with rectangular power of two size.
  7. /// </summary>
  8. public class PowerOfTwoTextureAtlas : Texture2DAtlas
  9. {
  10. readonly int m_MipPadding;
  11. const float k_MipmapFactorApprox = 1.33f;
  12. private Dictionary<int, Vector2Int> m_RequestedTextures = new Dictionary<int, Vector2Int>();
  13. /// <summary>
  14. /// Create a new texture atlas, must have power of two size.
  15. /// </summary>
  16. /// <param name="size">The size of the atlas in pixels. Must be power of two.</param>
  17. /// <param name="mipPadding">Amount of mip padding in power of two.</param>
  18. /// <param name="format">Atlas texture format</param>
  19. /// <param name="filterMode">Atlas texture filter mode.</param>
  20. /// <param name="name">Name of the atlas</param>
  21. /// <param name="useMipMap">Use mip maps</param>
  22. public PowerOfTwoTextureAtlas(int size, int mipPadding, GraphicsFormat format, FilterMode filterMode = FilterMode.Point, string name = "", bool useMipMap = true)
  23. : base(size, size, format, filterMode, true, name, useMipMap)
  24. {
  25. this.m_MipPadding = mipPadding;
  26. // Check if size is a power of two
  27. if ((size & (size - 1)) != 0)
  28. Debug.Assert(false, "Power of two atlas was constructed with non power of two size: " + size);
  29. }
  30. /// <summary>
  31. /// Used mipmap padding size in power of two.
  32. /// </summary>
  33. public int mipPadding => m_MipPadding;
  34. int GetTexturePadding() => (int)Mathf.Pow(2, m_MipPadding) * 2;
  35. /// <summary>
  36. /// Get location of the actual texture data without padding in the atlas.
  37. /// </summary>
  38. /// <param name="texture">The source texture cached in the atlas.</param>
  39. /// <param name="scaleOffset">Cached atlas location (scale and offset) for the source texture.</param>
  40. /// <returns>Scale and offset for the source texture without padding.</returns>
  41. public Vector4 GetPayloadScaleOffset(Texture texture, in Vector4 scaleOffset)
  42. {
  43. int pixelPadding = GetTexturePadding();
  44. Vector2 paddingSize = Vector2.one * pixelPadding;
  45. Vector2 textureSize = GetPowerOfTwoTextureSize(texture);
  46. return GetPayloadScaleOffset(textureSize, paddingSize, scaleOffset);
  47. }
  48. /// <summary>
  49. /// Get location of the actual texture data without padding in the atlas.
  50. /// </summary>
  51. /// <param name="textureSize">Size of the source texture</param>
  52. /// <param name="paddingSize">Padding size used for the source texture. </param>
  53. /// <param name="scaleOffset">Cached atlas location (scale and offset) for the source texture.</param>
  54. /// <returns>Scale and offset for the source texture without padding.</returns>
  55. static public Vector4 GetPayloadScaleOffset(in Vector2 textureSize, in Vector2 paddingSize, in Vector4 scaleOffset)
  56. {
  57. // Scale, Offset is a padded atlas sub-texture rectangle.
  58. // Actual texture data (payload) is inset, i.e. padded inwards.
  59. Vector2 subTexScale = new Vector2(scaleOffset.x, scaleOffset.y);
  60. Vector2 subTexOffset = new Vector2(scaleOffset.z, scaleOffset.w);
  61. // NOTE: Should match Blit() padding calculations.
  62. Vector2 scalePadding = ((textureSize + paddingSize) / textureSize); // Size of padding (sampling) rectangle relative to the payload texture.
  63. Vector2 offsetPadding = (paddingSize / 2.0f) / (textureSize + paddingSize); // Padding offset in the padding rectangle
  64. Vector2 insetScale = subTexScale / scalePadding; // Size of payload rectangle in sub-tex
  65. Vector2 insetOffset = subTexOffset + subTexScale * offsetPadding; // Offset of payload rectangle in sub-tex
  66. return new Vector4(insetScale.x, insetScale.y, insetOffset.x, insetOffset.y);
  67. }
  68. private enum BlitType
  69. {
  70. Padding,
  71. PaddingMultiply,
  72. OctahedralPadding,
  73. OctahedralPaddingMultiply,
  74. }
  75. private void Blit2DTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, BlitType blitType)
  76. {
  77. int mipCount = GetTextureMipmapCount(texture.width, texture.height);
  78. int pixelPadding = GetTexturePadding();
  79. Vector2 textureSize = GetPowerOfTwoTextureSize(texture);
  80. bool bilinear = texture.filterMode != FilterMode.Point;
  81. if (!blitMips)
  82. mipCount = 1;
  83. using (new ProfilingScope(cmd, ProfilingSampler.Get(CoreProfileId.BlitTextureInPotAtlas)))
  84. {
  85. for (int mipLevel = 0; mipLevel < mipCount; mipLevel++)
  86. {
  87. cmd.SetRenderTarget(m_AtlasTexture, mipLevel);
  88. switch (blitType)
  89. {
  90. case BlitType.Padding: Blitter.BlitQuadWithPadding(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
  91. case BlitType.PaddingMultiply: Blitter.BlitQuadWithPaddingMultiply(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
  92. case BlitType.OctahedralPadding: Blitter.BlitOctahedralWithPadding(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
  93. case BlitType.OctahedralPaddingMultiply: Blitter.BlitOctahedralWithPaddingMultiply(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
  94. }
  95. }
  96. }
  97. }
  98. /// <summary>
  99. /// Blit texture into the atlas with padding.
  100. /// </summary>
  101. /// <param name="cmd">Target command buffer for graphics commands.</param>
  102. /// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
  103. /// <param name="texture">Source Texture</param>
  104. /// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
  105. /// <param name="blitMips">Blit mip maps.</param>
  106. /// <param name="overrideInstanceID">Override texture instance ID.</param>
  107. public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1)
  108. {
  109. // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
  110. if (Is2D(texture))
  111. {
  112. Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.Padding);
  113. MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetInstanceID(), blitMips);
  114. }
  115. }
  116. /// <summary>
  117. /// Blit texture into the atlas with padding and blending.
  118. /// </summary>
  119. /// <param name="cmd">Target command buffer for graphics commands.</param>
  120. /// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
  121. /// <param name="texture">Source Texture</param>
  122. /// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
  123. /// <param name="blitMips">Blit mip maps.</param>
  124. /// <param name="overrideInstanceID">Override texture instance ID.</param>
  125. public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1)
  126. {
  127. // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
  128. if (Is2D(texture))
  129. {
  130. Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.PaddingMultiply);
  131. MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetInstanceID(), blitMips);
  132. }
  133. }
  134. /// <summary>
  135. /// Blit octahedral texture into the atlas with padding.
  136. /// </summary>
  137. /// <param name="cmd">Target command buffer for graphics commands.</param>
  138. /// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
  139. /// <param name="texture">Source Texture</param>
  140. /// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
  141. /// <param name="blitMips">Blit mip maps.</param>
  142. /// <param name="overrideInstanceID">Override texture instance ID.</param>
  143. public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1)
  144. {
  145. // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
  146. if (Is2D(texture))
  147. {
  148. Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.OctahedralPadding);
  149. MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetInstanceID(), blitMips);
  150. }
  151. }
  152. /// <summary>
  153. /// Blit octahedral texture into the atlas with padding.
  154. /// </summary>
  155. /// <param name="cmd">Target command buffer for graphics commands.</param>
  156. /// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
  157. /// <param name="texture">Source Texture</param>
  158. /// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
  159. /// <param name="blitMips">Blit mip maps.</param>
  160. /// <param name="overrideInstanceID">Override texture instance ID.</param>
  161. public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1)
  162. {
  163. // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
  164. if (Is2D(texture))
  165. {
  166. Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.OctahedralPaddingMultiply);
  167. MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetInstanceID(), blitMips);
  168. }
  169. }
  170. void TextureSizeToPowerOfTwo(Texture texture, ref int width, ref int height)
  171. {
  172. // Change the width and height of the texture to be power of two
  173. width = Mathf.NextPowerOfTwo(width);
  174. height = Mathf.NextPowerOfTwo(height);
  175. }
  176. Vector2 GetPowerOfTwoTextureSize(Texture texture)
  177. {
  178. int width = texture.width, height = texture.height;
  179. TextureSizeToPowerOfTwo(texture, ref width, ref height);
  180. return new Vector2(width, height);
  181. }
  182. // Override the behavior when we add a texture so all non-pot textures are blitted to a pot target zone
  183. /// <summary>
  184. /// Allocate space from the atlas for a texture and copy texture contents into the atlas.
  185. /// </summary>
  186. /// <param name="cmd">Target command buffer for graphics commands.</param>
  187. /// <param name="scaleOffset">Allocated scale (.xy) and offset (.zw)</param>
  188. /// <param name="texture">Source Texture</param>
  189. /// <param name="width">Request width in pixels.</param>
  190. /// <param name="height">Request height in pixels.</param>
  191. /// <param name="overrideInstanceID">Override texture instance ID.</param>
  192. /// <returns>True on success, false otherwise.</returns>
  193. public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, int overrideInstanceID = -1)
  194. {
  195. // This atlas only supports square textures
  196. if (height != width)
  197. {
  198. Debug.LogError("Can't place " + texture + " in the atlas " + m_AtlasTexture.name + ": Only squared texture are allowed in this atlas.");
  199. return false;
  200. }
  201. TextureSizeToPowerOfTwo(texture, ref height, ref width);
  202. return base.AllocateTexture(cmd, ref scaleOffset, texture, width, height);
  203. }
  204. /// <summary>
  205. /// Clear tracked requested textures.
  206. /// </summary>
  207. public void ResetRequestedTexture() => m_RequestedTextures.Clear();
  208. /// <summary>
  209. /// Reserves the space on the texture atlas
  210. /// </summary>
  211. /// <param name="texture">The source texture</param>
  212. /// <returns>True if the space is reserved</returns>
  213. public bool ReserveSpace(Texture texture) => ReserveSpace(texture, texture.width, texture.height);
  214. /// <summary>
  215. /// Reserves the space on the texture atlas
  216. /// </summary>
  217. /// <param name="texture">The source texture</param>
  218. /// <param name="width">The width</param>
  219. /// <param name="height">The height</param>
  220. /// <returns>True if the space is reserved</returns>
  221. public bool ReserveSpace(Texture texture, int width, int height)
  222. => ReserveSpace(GetTextureID(texture), width, height);
  223. /// <summary>
  224. /// Reserves the space on the texture atlas
  225. /// </summary>
  226. /// <param name="textureA">The source texture A</param>
  227. /// <param name="textureB">The source texture B</param>
  228. /// <param name="width">The width</param>
  229. /// <param name="height">The height</param>
  230. /// <returns>True if the space is reserved</returns>
  231. public bool ReserveSpace(Texture textureA, Texture textureB, int width, int height)
  232. => ReserveSpace(GetTextureID(textureA, textureB), width, height);
  233. /// <summary>
  234. /// Reserves the space on the texture atlas
  235. /// </summary>
  236. /// <param name="id">The id</param>
  237. /// <param name="width">The width</param>
  238. /// <param name="height">The height</param>
  239. /// <returns>True if the space is reserved</returns>
  240. public bool ReserveSpace(int id, int width, int height)
  241. {
  242. m_RequestedTextures[id] = new Vector2Int(width, height);
  243. // Cookie texture resolution changing between frame is a special case, so we handle it here.
  244. // The texture will be re-allocated and may cause holes in the atlas texture, which is fine
  245. // because when it doesn't have any more space, it will re-layout the texture correctly.
  246. var cachedSize = GetCachedTextureSize(id);
  247. if (!IsCached(out _, id) || cachedSize.x != width || cachedSize.y != height)
  248. {
  249. Vector4 scaleBias = Vector4.zero;
  250. if (!AllocateTextureWithoutBlit(id, width, height, ref scaleBias))
  251. return false;
  252. }
  253. return true;
  254. }
  255. /// <summary>
  256. /// sort all the requested allocation from biggest to smallest and re-insert them.
  257. /// This function does not moves the textures in the atlas, it only changes their coordinates
  258. /// </summary>
  259. /// <returns>True if all textures have successfully been re-inserted in the atlas</returns>
  260. public bool RelayoutEntries()
  261. {
  262. var entries = new List<(int instanceId, Vector2Int size)>();
  263. foreach (var entry in m_RequestedTextures)
  264. entries.Add((entry.Key, entry.Value));
  265. ResetAllocator();
  266. // Sort entries from biggest to smallest
  267. entries.Sort((c1, c2) =>
  268. {
  269. return c2.size.magnitude.CompareTo(c1.size.magnitude);
  270. });
  271. bool success = true;
  272. Vector4 newScaleOffset = Vector4.zero;
  273. foreach (var e in entries)
  274. success &= AllocateTextureWithoutBlit(e.instanceId, e.size.x, e.size.y, ref newScaleOffset);
  275. return success;
  276. }
  277. /// <summary>
  278. /// Get cache size in bytes.
  279. /// </summary>
  280. /// <param name="nbElement">The number of elements stored in the cache.</param>
  281. /// <param name="resolution">Atlas resolution (square).</param>
  282. /// <param name="hasMipmap">Atlas uses mip maps.</param>
  283. /// <param name="format">Atlas format.</param>
  284. /// <returns>The approximate size of the cache in bytes.</returns>
  285. public static long GetApproxCacheSizeInByte(int nbElement, int resolution, bool hasMipmap, GraphicsFormat format)
  286. => (long)(nbElement * resolution * resolution * (double)((hasMipmap ? k_MipmapFactorApprox : 1.0f) * GraphicsFormatUtility.GetBlockSize(format)));
  287. /// <summary>
  288. /// Compute the max size of a power of two atlas for a given size in byte (weight).
  289. /// </summary>
  290. /// <param name="weight">Atlas size in bytes.</param>
  291. /// <param name="hasMipmap">Atlas uses mip maps.</param>
  292. /// <param name="format">Atlas format.</param>
  293. /// <returns>The largest possible resolution for a square atlas, constrained by weight, as a power of two value.</returns>
  294. public static int GetMaxCacheSizeForWeightInByte(int weight, bool hasMipmap, GraphicsFormat format)
  295. {
  296. float bytePerPixel = (float)GraphicsFormatUtility.GetBlockSize(format) * (hasMipmap ? k_MipmapFactorApprox : 1.0f);
  297. var maxAtlasSquareSize = Mathf.Sqrt((float)weight / bytePerPixel);
  298. return CoreUtils.PreviousPowerOfTwo((int)maxAtlasSquareSize);
  299. }
  300. }
  301. }