Нема описа
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BufferedRTHandleSystem.cs 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Assertions;
  4. using UnityEngine.Rendering;
  5. namespace UnityEngine.Rendering
  6. {
  7. /// <summary>
  8. /// Implement a multiple buffering for RenderTextures.
  9. /// </summary>
  10. /// <example>
  11. /// <code>
  12. /// enum BufferType
  13. /// {
  14. /// Color,
  15. /// Depth
  16. /// }
  17. ///
  18. /// void Render()
  19. /// {
  20. /// var camera = GetCamera();
  21. /// var buffers = GetFrameHistoryBuffersFor(camera);
  22. ///
  23. /// // Set reference size in case the rendering size changed this frame
  24. /// buffers.SetReferenceSize(
  25. /// GetCameraWidth(camera), GetCameraHeight(camera),
  26. /// GetCameraUseMSAA(camera), GetCameraMSAASamples(camera)
  27. /// );
  28. /// buffers.Swap();
  29. ///
  30. /// var currentColor = buffer.GetFrameRT((int)BufferType.Color, 0);
  31. /// if (currentColor == null) // Buffer was not allocated
  32. /// {
  33. /// buffer.AllocBuffer(
  34. /// (int)BufferType.Color, // Color buffer id
  35. /// ColorBufferAllocator, // Custom functor to implement allocation
  36. /// 2 // Use 2 RT for this buffer for double buffering
  37. /// );
  38. /// currentColor = buffer.GetFrameRT((int)BufferType.Color, 0);
  39. /// }
  40. ///
  41. /// var previousColor = buffers.GetFrameRT((int)BufferType.Color, 1);
  42. ///
  43. /// // Use previousColor and write into currentColor
  44. /// }
  45. /// </code>
  46. /// </example>
  47. public class BufferedRTHandleSystem : IDisposable
  48. {
  49. Dictionary<int, RTHandle[]> m_RTHandles = new Dictionary<int, RTHandle[]>();
  50. RTHandleSystem m_RTHandleSystem = new RTHandleSystem();
  51. bool m_DisposedValue = false;
  52. /// <summary>
  53. /// Maximum allocated width of the Buffered RTHandle System
  54. /// </summary>
  55. public int maxWidth { get { return m_RTHandleSystem.GetMaxWidth(); } }
  56. /// <summary>
  57. /// Maximum allocated height of the Buffered RTHandle System
  58. /// </summary>
  59. public int maxHeight { get { return m_RTHandleSystem.GetMaxHeight(); } }
  60. /// <summary>
  61. /// Current properties of the Buffered RTHandle System
  62. /// </summary>
  63. public RTHandleProperties rtHandleProperties { get { return m_RTHandleSystem.rtHandleProperties; } }
  64. /// <summary>
  65. /// Return the frame RT or null.
  66. /// </summary>
  67. /// <param name="bufferId">Defines the buffer to use.</param>
  68. /// <param name="frameIndex">Defines which frame to access within the buffer.</param>
  69. /// <returns>The frame RT or null when the <paramref name="bufferId"/> was not previously allocated (<see cref="BufferedRTHandleSystem.AllocBuffer(int, Func{RTHandleSystem, int, RTHandle}, int)" />).</returns>
  70. public RTHandle GetFrameRT(int bufferId, int frameIndex)
  71. {
  72. if (!m_RTHandles.ContainsKey(bufferId))
  73. return null;
  74. Assert.IsTrue(frameIndex >= 0 && frameIndex < m_RTHandles[bufferId].Length);
  75. return m_RTHandles[bufferId][frameIndex];
  76. }
  77. /// <summary>
  78. /// Clears all the previously created history buffers
  79. /// </summary>
  80. /// <param name="cmd">Defines the command buffer used for clearing.</param>
  81. public void ClearBuffers(CommandBuffer cmd)
  82. {
  83. foreach (var rtHandle in m_RTHandles)
  84. {
  85. for (int i = 0; i < rtHandle.Value.Length; ++i)
  86. {
  87. CoreUtils.SetRenderTarget(cmd, rtHandle.Value[i], clearFlag: ClearFlag.Color, clearColor: Color.black);
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// Allocate RT handles for a buffer.
  93. /// </summary>
  94. /// <param name="bufferId">The buffer to allocate.</param>
  95. /// <param name="allocator">The functor to use for allocation.</param>
  96. /// <param name="bufferCount">The number of RT handles for this buffer.</param>
  97. public void AllocBuffer(
  98. int bufferId,
  99. Func<RTHandleSystem, int, RTHandle> allocator,
  100. int bufferCount
  101. )
  102. {
  103. // This function should only be used when there is a non-zero number of buffers to allocate.
  104. // If the caller provides a value of zero, they're likely doing something unintentional in the calling code.
  105. Debug.Assert(bufferCount > 0);
  106. var buffer = new RTHandle[bufferCount];
  107. m_RTHandles.Add(bufferId, buffer);
  108. // First is autoresized
  109. buffer[0] = allocator(m_RTHandleSystem, 0);
  110. // Other are resized on demand
  111. for (int i = 1, c = buffer.Length; i < c; ++i)
  112. {
  113. buffer[i] = allocator(m_RTHandleSystem, i);
  114. m_RTHandleSystem.SwitchResizeMode(buffer[i], RTHandleSystem.ResizeMode.OnDemand);
  115. }
  116. }
  117. /// <summary>
  118. /// Allocate RT handles for a buffer using a RenderTextureDescriptor.
  119. /// </summary>
  120. /// <param name="bufferId">The buffer to allocate.</param>
  121. /// <param name="bufferCount">The number of RT handles for this buffer.</param>
  122. /// <param name="descriptor">RenderTexture descriptor of the RTHandles.</param>
  123. /// <param name="filterMode">Filtering mode of the RTHandles.</param>
  124. /// <param name="wrapMode">Addressing mode of the RTHandles.</param>
  125. /// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
  126. /// <param name="anisoLevel">Anisotropic filtering level.</param>
  127. /// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
  128. /// <param name="name">Name of the RTHandle.</param>
  129. // NOTE: API is similar to RTHandles.Alloc.
  130. public void AllocBuffer(int bufferId, int bufferCount,
  131. ref RenderTextureDescriptor descriptor,
  132. FilterMode filterMode = FilterMode.Point,
  133. TextureWrapMode wrapMode = TextureWrapMode.Repeat,
  134. bool isShadowMap = false,
  135. int anisoLevel = 1,
  136. float mipMapBias = 0,
  137. string name = "")
  138. {
  139. // This function should only be used when there is a non-zero number of buffers to allocate.
  140. // If the caller provides a value of zero, they're likely doing something unintentional in the calling code.
  141. Debug.Assert(bufferCount > 0);
  142. var buffer = new RTHandle[bufferCount];
  143. m_RTHandles.Add(bufferId, buffer);
  144. RTHandle Alloc(ref RenderTextureDescriptor d, FilterMode fMode, TextureWrapMode wMode, bool isShadow, int aniso, float mipBias, string n)
  145. {
  146. return m_RTHandleSystem.Alloc(
  147. d.width,
  148. d.height,
  149. d.volumeDepth,
  150. (DepthBits)d.depthBufferBits,
  151. d.graphicsFormat,
  152. fMode,
  153. wMode,
  154. d.dimension,
  155. d.enableRandomWrite,
  156. d.useMipMap,
  157. d.autoGenerateMips,
  158. isShadow,
  159. aniso,
  160. mipBias,
  161. (MSAASamples)d.msaaSamples,
  162. d.bindMS,
  163. d.useDynamicScale,
  164. d.useDynamicScaleExplicit,
  165. d.memoryless,
  166. d.vrUsage,
  167. n);
  168. }
  169. // First is autoresized
  170. buffer[0] = Alloc(ref descriptor, filterMode, wrapMode, isShadowMap, anisoLevel, mipMapBias, name);
  171. // Other are resized on demand
  172. for (int i = 1, c = buffer.Length; i < c; ++i)
  173. {
  174. buffer[i] = Alloc(ref descriptor, filterMode, wrapMode, isShadowMap, anisoLevel, mipMapBias, name);
  175. m_RTHandleSystem.SwitchResizeMode(buffer[i], RTHandleSystem.ResizeMode.OnDemand);
  176. }
  177. }
  178. /// <summary>
  179. /// Release a buffer
  180. /// </summary>
  181. /// <param name="bufferId">Id of the buffer that needs to be released.</param>
  182. public void ReleaseBuffer(int bufferId)
  183. {
  184. if (m_RTHandles.TryGetValue(bufferId, out var buffers))
  185. {
  186. foreach (var rt in buffers)
  187. m_RTHandleSystem.Release(rt);
  188. }
  189. m_RTHandles.Remove(bufferId);
  190. }
  191. /// <summary>
  192. /// Swap buffers Set the reference size for this RT Handle System (<see cref="RTHandleSystem.SetReferenceSize(int, int, bool)"/>)
  193. /// </summary>
  194. /// <param name="width">The width of the RTs of this buffer.</param>
  195. /// <param name="height">The height of the RTs of this buffer.</param>
  196. public void SwapAndSetReferenceSize(int width, int height)
  197. {
  198. Swap();
  199. m_RTHandleSystem.SetReferenceSize(width, height);
  200. }
  201. /// <summary>
  202. /// Reset the reference size of the system and reallocate all textures.
  203. /// </summary>
  204. /// <param name="width">New width.</param>
  205. /// <param name="height">New height.</param>
  206. public void ResetReferenceSize(int width, int height)
  207. {
  208. m_RTHandleSystem.ResetReferenceSize(width, height);
  209. }
  210. /// <summary>
  211. /// Queries the number of RT handle buffers allocated for a buffer ID.
  212. /// </summary>
  213. /// <param name="bufferId">The buffer ID to query.</param>
  214. /// <returns>The num of frames allocated</returns>
  215. public int GetNumFramesAllocated(int bufferId)
  216. {
  217. if (!m_RTHandles.ContainsKey(bufferId))
  218. return 0;
  219. return m_RTHandles[bufferId].Length;
  220. }
  221. /// <summary>
  222. /// Returns the ratio against the current target's max resolution
  223. /// </summary>
  224. /// <param name="width">width to utilize</param>
  225. /// <param name="height">height to utilize</param>
  226. /// <returns> retruns the width,height / maxTargetSize.xy ratio. </returns>
  227. public Vector2 CalculateRatioAgainstMaxSize(int width, int height)
  228. {
  229. return m_RTHandleSystem.CalculateRatioAgainstMaxSize(new Vector2Int(width, height));
  230. }
  231. void Swap()
  232. {
  233. foreach (var item in m_RTHandles)
  234. {
  235. // Do not index out of bounds...
  236. if (item.Value.Length > 1)
  237. {
  238. var nextFirst = item.Value[item.Value.Length - 1];
  239. for (int i = 0, c = item.Value.Length - 1; i < c; ++i)
  240. item.Value[i + 1] = item.Value[i];
  241. item.Value[0] = nextFirst;
  242. // First is autoresize, other are on demand
  243. m_RTHandleSystem.SwitchResizeMode(item.Value[0], RTHandleSystem.ResizeMode.Auto);
  244. m_RTHandleSystem.SwitchResizeMode(item.Value[1], RTHandleSystem.ResizeMode.OnDemand);
  245. }
  246. else
  247. {
  248. m_RTHandleSystem.SwitchResizeMode(item.Value[0], RTHandleSystem.ResizeMode.Auto);
  249. }
  250. }
  251. }
  252. void Dispose(bool disposing)
  253. {
  254. if (!m_DisposedValue)
  255. {
  256. if (disposing)
  257. {
  258. ReleaseAll();
  259. m_RTHandleSystem.Dispose();
  260. m_RTHandleSystem = null;
  261. }
  262. m_DisposedValue = true;
  263. }
  264. }
  265. /// <summary>
  266. /// Dispose implementation
  267. /// </summary>
  268. public void Dispose()
  269. {
  270. Dispose(true);
  271. }
  272. /// <summary>
  273. /// Deallocate and clear all buffers.
  274. /// </summary>
  275. public void ReleaseAll()
  276. {
  277. foreach (var item in m_RTHandles)
  278. {
  279. for (int i = 0, c = item.Value.Length; i < c; ++i)
  280. {
  281. m_RTHandleSystem.Release(item.Value[i]);
  282. }
  283. }
  284. m_RTHandles.Clear();
  285. }
  286. }
  287. }