BloomComponent.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // BloomComponent.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.Content;
  13. using Microsoft.Xna.Framework.Graphics;
  14. #endregion
  15. namespace BloomPostprocess
  16. {
  17. public class BloomComponent : DrawableGameComponent
  18. {
  19. #region Fields
  20. SpriteBatch spriteBatch;
  21. Effect bloomExtractEffect;
  22. Effect bloomCombineEffect;
  23. Effect gaussianBlurEffect;
  24. RenderTarget2D sceneRenderTarget;
  25. RenderTarget2D renderTarget1;
  26. RenderTarget2D renderTarget2;
  27. // Choose what display settings the bloom should use.
  28. public BloomSettings Settings
  29. {
  30. get { return settings; }
  31. set { settings = value; }
  32. }
  33. BloomSettings settings = BloomSettings.PresetSettings[0];
  34. // Optionally displays one of the intermediate buffers used
  35. // by the bloom postprocess, so you can see exactly what is
  36. // being drawn into each rendertarget.
  37. public enum IntermediateBuffer
  38. {
  39. PreBloom,
  40. BlurredHorizontally,
  41. BlurredBothWays,
  42. FinalResult,
  43. }
  44. public IntermediateBuffer ShowBuffer
  45. {
  46. get { return showBuffer; }
  47. set { showBuffer = value; }
  48. }
  49. IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult;
  50. #endregion
  51. #region Initialization
  52. public BloomComponent(Game game)
  53. : base(game)
  54. {
  55. if (game == null)
  56. throw new ArgumentNullException("game");
  57. }
  58. /// <summary>
  59. /// Load your graphics content.
  60. /// </summary>
  61. protected override void LoadContent()
  62. {
  63. spriteBatch = new SpriteBatch(GraphicsDevice);
  64. bloomExtractEffect = Game.Content.Load<Effect>("BloomExtract");
  65. bloomCombineEffect = Game.Content.Load<Effect>("BloomCombine");
  66. gaussianBlurEffect = Game.Content.Load<Effect>("GaussianBlur");
  67. // Look up the resolution and format of our main backbuffer.
  68. PresentationParameters pp = GraphicsDevice.PresentationParameters;
  69. int width = pp.BackBufferWidth;
  70. int height = pp.BackBufferHeight;
  71. SurfaceFormat format = pp.BackBufferFormat;
  72. // Create a texture for rendering the main scene, prior to applying bloom.
  73. sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
  74. format, pp.DepthStencilFormat, pp.MultiSampleCount,
  75. RenderTargetUsage.DiscardContents);
  76. // Create two rendertargets for the bloom processing. These are half the
  77. // size of the backbuffer, in order to minimize fillrate costs. Reducing
  78. // the resolution in this way doesn't hurt quality, because we are going
  79. // to be blurring the bloom images in any case.
  80. width /= 2;
  81. height /= 2;
  82. renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
  83. renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
  84. }
  85. /// <summary>
  86. /// Unload your graphics content.
  87. /// </summary>
  88. protected override void UnloadContent()
  89. {
  90. sceneRenderTarget.Dispose();
  91. renderTarget1.Dispose();
  92. renderTarget2.Dispose();
  93. }
  94. #endregion
  95. #region Draw
  96. /// <summary>
  97. /// This should be called at the very start of the scene rendering. The bloom
  98. /// component uses it to redirect drawing into its custom rendertarget, so it
  99. /// can capture the scene image in preparation for applying the bloom filter.
  100. /// </summary>
  101. public void BeginDraw()
  102. {
  103. if (Visible)
  104. {
  105. GraphicsDevice.SetRenderTarget(sceneRenderTarget);
  106. }
  107. }
  108. /// <summary>
  109. /// This is where it all happens. Grabs a scene that has already been rendered,
  110. /// and uses postprocess magic to add a glowing bloom effect over the top of it.
  111. /// </summary>
  112. public override void Draw(GameTime gameTime)
  113. {
  114. GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
  115. // Pass 1: draw the scene into rendertarget 1, using a
  116. // shader that extracts only the brightest parts of the image.
  117. bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
  118. Settings.BloomThreshold);
  119. DrawFullscreenQuad(sceneRenderTarget, renderTarget1,
  120. bloomExtractEffect,
  121. IntermediateBuffer.PreBloom);
  122. // Pass 2: draw from rendertarget 1 into rendertarget 2,
  123. // using a shader to apply a horizontal gaussian blur filter.
  124. SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);
  125. DrawFullscreenQuad(renderTarget1, renderTarget2,
  126. gaussianBlurEffect,
  127. IntermediateBuffer.BlurredHorizontally);
  128. // Pass 3: draw from rendertarget 2 back into rendertarget 1,
  129. // using a shader to apply a vertical gaussian blur filter.
  130. SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);
  131. DrawFullscreenQuad(renderTarget2, renderTarget1,
  132. gaussianBlurEffect,
  133. IntermediateBuffer.BlurredBothWays);
  134. // Pass 4: draw both rendertarget 1 and the original scene
  135. // image back into the main backbuffer, using a shader that
  136. // combines them to produce the final bloomed result.
  137. GraphicsDevice.SetRenderTarget(null);
  138. EffectParameterCollection parameters = bloomCombineEffect.Parameters;
  139. parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
  140. parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
  141. parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
  142. parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);
  143. GraphicsDevice.Textures[1] = sceneRenderTarget;
  144. Viewport viewport = GraphicsDevice.Viewport;
  145. DrawFullscreenQuad(renderTarget1,
  146. viewport.Width, viewport.Height,
  147. bloomCombineEffect,
  148. IntermediateBuffer.FinalResult);
  149. }
  150. /// <summary>
  151. /// Helper for drawing a texture into a rendertarget, using
  152. /// a custom shader to apply postprocessing effects.
  153. /// </summary>
  154. void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget,
  155. Effect effect, IntermediateBuffer currentBuffer)
  156. {
  157. GraphicsDevice.SetRenderTarget(renderTarget);
  158. DrawFullscreenQuad(texture,
  159. renderTarget.Width, renderTarget.Height,
  160. effect, currentBuffer);
  161. }
  162. /// <summary>
  163. /// Helper for drawing a texture into the current rendertarget,
  164. /// using a custom shader to apply postprocessing effects.
  165. /// </summary>
  166. void DrawFullscreenQuad(Texture2D texture, int width, int height,
  167. Effect effect, IntermediateBuffer currentBuffer)
  168. {
  169. // If the user has selected one of the show intermediate buffer options,
  170. // we still draw the quad to make sure the image will end up on the screen,
  171. // but might need to skip applying the custom pixel shader.
  172. if (showBuffer < currentBuffer)
  173. {
  174. effect = null;
  175. }
  176. spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
  177. spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
  178. spriteBatch.End();
  179. }
  180. /// <summary>
  181. /// Computes sample weightings and texture coordinate offsets
  182. /// for one pass of a separable gaussian blur filter.
  183. /// </summary>
  184. void SetBlurEffectParameters(float dx, float dy)
  185. {
  186. // Look up the sample weight and offset effect parameters.
  187. EffectParameter weightsParameter, offsetsParameter;
  188. weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"];
  189. offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"];
  190. // Look up how many samples our gaussian blur effect supports.
  191. int sampleCount = weightsParameter.Elements.Count;
  192. // Create temporary arrays for computing our filter settings.
  193. float[] sampleWeights = new float[sampleCount];
  194. Vector2[] sampleOffsets = new Vector2[sampleCount];
  195. // The first sample always has a zero offset.
  196. sampleWeights[0] = ComputeGaussian(0);
  197. sampleOffsets[0] = new Vector2(0);
  198. // Maintain a sum of all the weighting values.
  199. float totalWeights = sampleWeights[0];
  200. // Add pairs of additional sample taps, positioned
  201. // along a line in both directions from the center.
  202. for (int i = 0; i < sampleCount / 2; i++)
  203. {
  204. // Store weights for the positive and negative taps.
  205. float weight = ComputeGaussian(i + 1);
  206. sampleWeights[i * 2 + 1] = weight;
  207. sampleWeights[i * 2 + 2] = weight;
  208. totalWeights += weight * 2;
  209. // To get the maximum amount of blurring from a limited number of
  210. // pixel shader samples, we take advantage of the bilinear filtering
  211. // hardware inside the texture fetch unit. If we position our texture
  212. // coordinates exactly halfway between two texels, the filtering unit
  213. // will average them for us, giving two samples for the price of one.
  214. // This allows us to step in units of two texels per sample, rather
  215. // than just one at a time. The 1.5 offset kicks things off by
  216. // positioning us nicely in between two texels.
  217. float sampleOffset = i * 2 + 1.5f;
  218. Vector2 delta = new Vector2(dx, dy) * sampleOffset;
  219. // Store texture coordinate offsets for the positive and negative taps.
  220. sampleOffsets[i * 2 + 1] = delta;
  221. sampleOffsets[i * 2 + 2] = -delta;
  222. }
  223. // Normalize the list of sample weightings, so they will always sum to one.
  224. for (int i = 0; i < sampleWeights.Length; i++)
  225. {
  226. sampleWeights[i] /= totalWeights;
  227. }
  228. // Tell the effect about our new filter settings.
  229. weightsParameter.SetValue(sampleWeights);
  230. offsetsParameter.SetValue(sampleOffsets);
  231. }
  232. /// <summary>
  233. /// Evaluates a single point on the gaussian falloff curve.
  234. /// Used for setting up the blur filter weightings.
  235. /// </summary>
  236. float ComputeGaussian(float n)
  237. {
  238. float theta = Settings.BlurAmount;
  239. return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
  240. Math.Exp(-(n * n) / (2 * theta * theta)));
  241. }
  242. #endregion
  243. }
  244. }