SpriteEffects.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // SpriteEffects.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. using Microsoft.Xna.Framework.Input;
  15. #endregion
  16. namespace SpriteEffects
  17. {
  18. /// <summary>
  19. /// Sample demonstrating how shaders can be used to
  20. /// apply special effects to sprite rendering.
  21. /// </summary>
  22. public class SpriteEffectsGame : Microsoft.Xna.Framework.Game
  23. {
  24. #region Fields
  25. GraphicsDeviceManager graphics;
  26. KeyboardState lastKeyboardState = new KeyboardState ();
  27. GamePadState lastGamePadState = new GamePadState ();
  28. KeyboardState currentKeyboardState = new KeyboardState ();
  29. GamePadState currentGamePadState = new GamePadState ();
  30. // Enum describes all the rendering techniques used in this demo.
  31. enum DemoEffect
  32. {
  33. Desaturate,
  34. Disappear,
  35. RefractCat,
  36. RefractGlacier,
  37. Normalmap,
  38. }
  39. DemoEffect currentEffect = DemoEffect.RefractGlacier;
  40. // Effects used by this sample.
  41. Effect desaturateEffect;
  42. Effect disappearEffect;
  43. Effect normalmapEffect;
  44. Effect refractionEffect;
  45. // Textures used by this sample.
  46. Texture2D catTexture;
  47. Texture2D catNormalmapTexture;
  48. Texture2D glacierTexture;
  49. Texture2D waterfallTexture;
  50. // SpriteBatch instance used to render all the effects.
  51. SpriteBatch spriteBatch;
  52. #endregion
  53. #region Initialization
  54. public SpriteEffectsGame ()
  55. {
  56. graphics = new GraphicsDeviceManager (this);
  57. Content.RootDirectory = "Content";
  58. }
  59. /// <summary>
  60. /// Loads graphics content.
  61. /// </summary>
  62. protected override void LoadContent ()
  63. {
  64. desaturateEffect = Content.Load<Effect> ("desaturate");
  65. disappearEffect = Content.Load<Effect> ("disappear");
  66. normalmapEffect = Content.Load<Effect> ("normalmap");
  67. refractionEffect = Content.Load<Effect> ("refraction");
  68. catTexture = Content.Load<Texture2D> ("cat");
  69. catNormalmapTexture = Content.Load<Texture2D> ("cat_normalmap");
  70. glacierTexture = Content.Load<Texture2D> ("glacier");
  71. waterfallTexture = Content.Load<Texture2D> ("waterfall");
  72. spriteBatch = new SpriteBatch (graphics.GraphicsDevice);
  73. }
  74. #endregion
  75. #region Update and Draw
  76. /// <summary>
  77. /// Allows the game to run logic.
  78. /// </summary>
  79. protected override void Update (GameTime gameTime)
  80. {
  81. HandleInput ();
  82. if (NextButtonPressed ()) {
  83. currentEffect++;
  84. if (currentEffect > DemoEffect.Normalmap)
  85. currentEffect = 0;
  86. }
  87. base.Update (gameTime);
  88. }
  89. /// <summary>
  90. /// This is called when the game should draw itself.
  91. /// </summary>
  92. protected override void Draw (GameTime gameTime)
  93. {
  94. switch (currentEffect) {
  95. case DemoEffect.Desaturate:
  96. DrawDesaturate (gameTime);
  97. break;
  98. case DemoEffect.Disappear:
  99. DrawDisappear (gameTime);
  100. break;
  101. case DemoEffect.Normalmap:
  102. DrawNormalmap (gameTime);
  103. break;
  104. case DemoEffect.RefractCat:
  105. DrawRefractCat (gameTime);
  106. break;
  107. case DemoEffect.RefractGlacier:
  108. DrawRefractGlacier (gameTime);
  109. break;
  110. }
  111. base.Draw (gameTime);
  112. }
  113. /// <summary>
  114. /// Effect dynamically changes color saturation.
  115. /// </summary>
  116. void DrawDesaturate (GameTime gameTime)
  117. {
  118. GraphicsDevice.Clear(Color.White);
  119. // Begin the sprite batch, using our custom effect.
  120. spriteBatch.Begin (0, null, null, null, null, desaturateEffect);
  121. // Draw four copies of the same sprite with different saturation levels.
  122. // The saturation amount is passed into the effect using the alpha of the
  123. // SpriteBatch.Draw color parameter. This isn't as flexible as using a
  124. // regular effect parameter, but makes it easy to draw many sprites with
  125. // a different saturation amount for each. If we had used an effect
  126. // parameter for this, we would have to end the sprite batch, then begin
  127. // a new one, each time we wanted to change the saturation setting.
  128. byte pulsate = (byte)Pulsate (gameTime, 4, 0, 255);
  129. spriteBatch.Draw (glacierTexture,
  130. QuarterOfScreen (0, 0),
  131. new Color (255, 255, 255, 0));
  132. spriteBatch.Draw (glacierTexture,
  133. QuarterOfScreen (1, 0),
  134. new Color (255, 255, 255, 64));
  135. spriteBatch.Draw (glacierTexture,
  136. QuarterOfScreen (0, 1),
  137. new Color (255, 255, 255, 255));
  138. spriteBatch.Draw (glacierTexture,
  139. QuarterOfScreen (1, 1),
  140. new Color (255, 255, 255, pulsate));
  141. // End the sprite batch.
  142. spriteBatch.End ();
  143. }
  144. /// <summary>
  145. /// Effect uses a scrolling overlay texture to make different parts of
  146. /// an image fade in or out at different speeds.
  147. /// </summary>
  148. void DrawDisappear (GameTime gameTime)
  149. {
  150. //GraphicsDevice.Clear(Color.White);
  151. // Draw the background image.
  152. spriteBatch.Begin ();
  153. spriteBatch.Draw (glacierTexture, GraphicsDevice.Viewport.Bounds, Color.White);
  154. spriteBatch.End ();
  155. // Set an effect parameter to make our overlay
  156. // texture scroll in a giant circle.
  157. //TextureSampler
  158. disappearEffect.Parameters ["OverlayScroll"].SetValue (
  159. MoveInCircle (gameTime, 0.8f) * 0.25f);
  160. // Set the overlay texture (as texture 1,
  161. // because 0 will be the main sprite texture).
  162. graphics.GraphicsDevice.Textures [1] = waterfallTexture;
  163. // Begin the sprite batch.
  164. spriteBatch.Begin (0, null, null, null, null, disappearEffect);
  165. // Draw the sprite, passing the fade amount as the
  166. // alpha of the SpriteBatch.Draw color parameter.
  167. byte fade = (byte)Pulsate (gameTime, 2, 0, 255);
  168. spriteBatch.Draw (catTexture,
  169. MoveInCircle (gameTime, catTexture, 1),
  170. new Color (255, 255, 255, fade));
  171. // End the sprite batch.
  172. spriteBatch.End ();
  173. }
  174. /// <summary>
  175. // Effect uses a scrolling displacement texture to offset the position of
  176. // the main texture.
  177. /// </summary>
  178. void DrawRefractCat (GameTime gameTime)
  179. {
  180. // Draw the background image.
  181. spriteBatch.Begin ();
  182. spriteBatch.Draw (glacierTexture, GraphicsDevice.Viewport.Bounds, Color.White);
  183. spriteBatch.End ();
  184. // Set an effect parameter to make the
  185. // displacement texture scroll in a giant circle.
  186. refractionEffect.Parameters ["DisplacementScroll"].SetValue (
  187. MoveInCircle (gameTime, 0.1f));
  188. // Set the displacement texture.
  189. graphics.GraphicsDevice.Textures [1] = waterfallTexture;
  190. // Begin the sprite batch.
  191. spriteBatch.Begin (0, null, null, null, null, refractionEffect);
  192. // Draw the sprite.
  193. spriteBatch.Draw (catTexture,
  194. MoveInCircle (gameTime, catTexture, 1),
  195. Color.White);
  196. // End the sprite batch.
  197. spriteBatch.End ();
  198. }
  199. /// <summary>
  200. // Effect uses a scrolling displacement texture to offset the position of
  201. // the main texture.
  202. /// </summary>
  203. void DrawRefractGlacier (GameTime gameTime)
  204. {
  205. // Set an effect parameter to make the
  206. // displacement texture scroll in a giant circle.
  207. refractionEffect.Parameters ["DisplacementScroll"].SetValue (
  208. MoveInCircle (gameTime, 0.2f));
  209. // Set the displacement texture.
  210. graphics.GraphicsDevice.Textures [1] = glacierTexture;
  211. // Begin the sprite batch.
  212. spriteBatch.Begin (0, null, null, null, null, refractionEffect);
  213. //spriteBatch.Begin();
  214. // Because the effect will displace the texture coordinates before
  215. // sampling the main texture, the coordinates could sometimes go right
  216. // off the edges of the texture, which looks ugly. To prevent this, we
  217. // adjust our sprite source region to leave a little border around the
  218. // edge of the texture. The displacement effect will then just move the
  219. // texture coordinates into this border region, without ever hitting
  220. // the edge of the texture.
  221. Rectangle croppedGlacier = new Rectangle (32, 32,
  222. glacierTexture.Width - 64,
  223. glacierTexture.Height - 64);
  224. spriteBatch.Draw (glacierTexture,
  225. GraphicsDevice.Viewport.Bounds,
  226. //croppedGlacier,
  227. Color.White);
  228. // End the sprite batch.
  229. spriteBatch.End ();
  230. }
  231. /// <summary>
  232. /// Effect uses a normalmap texture to apply realtime lighting while
  233. /// drawing a 2D sprite.
  234. /// </summary>
  235. void DrawNormalmap (GameTime gameTime)
  236. {
  237. // Draw the background image.
  238. spriteBatch.Begin ();
  239. spriteBatch.Draw (glacierTexture, GraphicsDevice.Viewport.Bounds, Color.White);
  240. spriteBatch.End ();
  241. // Animate the light direction.
  242. Vector2 spinningLight = MoveInCircle (gameTime, 1.5f);
  243. double time = gameTime.TotalGameTime.TotalSeconds;
  244. float tiltUpAndDown = 0.5f + (float)Math.Cos (time * 0.75) * 0.1f;
  245. Vector3 lightDirection = new Vector3 (spinningLight * tiltUpAndDown,
  246. 1 - tiltUpAndDown);
  247. lightDirection.Normalize ();
  248. normalmapEffect.Parameters ["LightDirection"].SetValue (lightDirection);
  249. // Set the normalmap texture.
  250. graphics.GraphicsDevice.Textures [1] = catNormalmapTexture;
  251. // Begin the sprite batch.
  252. spriteBatch.Begin (0, null, null, null, null, normalmapEffect);
  253. // Draw the sprite.
  254. spriteBatch.Draw (catTexture, CenterOnScreen (catTexture), Color.Azure);
  255. // End the sprite batch.
  256. spriteBatch.End ();
  257. // End the sprite batch.
  258. spriteBatch.End ();
  259. }
  260. /// <summary>
  261. /// Helper calculates the destination rectangle needed
  262. /// to draw a sprite to one quarter of the screen.
  263. /// </summary>
  264. Rectangle QuarterOfScreen (int x, int y)
  265. {
  266. Viewport viewport = graphics.GraphicsDevice.Viewport;
  267. int w = viewport.Width / 2;
  268. int h = viewport.Height / 2;
  269. return new Rectangle (w * x, h * y, w, h);
  270. }
  271. /// <summary>
  272. /// Helper calculates the destination position needed
  273. /// to center a sprite in the middle of the screen.
  274. /// </summary>
  275. Vector2 CenterOnScreen (Texture2D texture)
  276. {
  277. Viewport viewport = graphics.GraphicsDevice.Viewport;
  278. int x = (viewport.Width - texture.Width) / 2;
  279. int y = (viewport.Height - texture.Height) / 2;
  280. return new Vector2 (x, y);
  281. }
  282. /// <summary>
  283. /// Helper computes a value that oscillates over time.
  284. /// </summary>
  285. static float Pulsate (GameTime gameTime, float speed, float min, float max)
  286. {
  287. double time = gameTime.TotalGameTime.TotalSeconds * speed;
  288. return min + ((float)Math.Sin (time) + 1) / 2 * (max - min);
  289. }
  290. /// <summary>
  291. /// Helper for moving a value around in a circle.
  292. /// </summary>
  293. static Vector2 MoveInCircle (GameTime gameTime, float speed)
  294. {
  295. double time = gameTime.TotalGameTime.TotalSeconds * speed;
  296. float x = (float)Math.Cos (time);
  297. float y = (float)Math.Sin (time);
  298. return new Vector2 (x, y);
  299. }
  300. /// <summary>
  301. /// Helper for moving a sprite around in a circle.
  302. /// </summary>
  303. Vector2 MoveInCircle (GameTime gameTime, Texture2D texture, float speed)
  304. {
  305. Viewport viewport = graphics.GraphicsDevice.Viewport;
  306. float x = (viewport.Width - texture.Width) / 2;
  307. float y = (viewport.Height - texture.Height) / 2;
  308. return MoveInCircle (gameTime, speed) * 128 + new Vector2 (x, y);
  309. }
  310. #endregion
  311. #region Handle Input
  312. /// <summary>
  313. /// Handles input for quitting the game.
  314. /// </summary>
  315. private void HandleInput ()
  316. {
  317. lastKeyboardState = currentKeyboardState;
  318. lastGamePadState = currentGamePadState;
  319. currentKeyboardState = Keyboard.GetState ();
  320. currentGamePadState = GamePad.GetState (PlayerIndex.One);
  321. // Check for exit.
  322. if (currentKeyboardState.IsKeyDown (Keys.Escape) ||
  323. currentGamePadState.Buttons.Back == ButtonState.Pressed) {
  324. Exit ();
  325. }
  326. }
  327. /// <summary>
  328. /// Checks whether the user wants to advance to the next rendering effect.
  329. /// </summary>
  330. bool NextButtonPressed ()
  331. {
  332. // Have they pressed the space bar?
  333. if (currentKeyboardState.IsKeyDown (Keys.Space) &&
  334. !lastKeyboardState.IsKeyDown (Keys.Space))
  335. return true;
  336. // Have they pressed the gamepad A button?
  337. if (currentGamePadState.Buttons.A == ButtonState.Pressed &&
  338. lastGamePadState.Buttons.A == ButtonState.Released)
  339. return true;
  340. return false;
  341. }
  342. #endregion
  343. }
  344. }