BloomComponent.cs 12 KB

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