GameMain.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // DemoGame.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 System.Collections.Generic;
  12. using System.Linq;
  13. using Microsoft.Xna.Framework;
  14. using Microsoft.Xna.Framework.Audio;
  15. using Microsoft.Xna.Framework.Content;
  16. using Microsoft.Xna.Framework.GamerServices;
  17. using Microsoft.Xna.Framework.Graphics;
  18. using Microsoft.Xna.Framework.Input;
  19. using Microsoft.Xna.Framework.Input.Touch;
  20. using Microsoft.Xna.Framework.Media;
  21. #endregion
  22. namespace Graphics3DSample
  23. {
  24. /// <summary>
  25. /// This is the main type for your game
  26. /// </summary>
  27. public class Graphics3DSampleGame : Microsoft.Xna.Framework.Game
  28. {
  29. #region Fields
  30. #region Constants
  31. const int buttonHeight = 70;
  32. const int buttonWidth = 70;
  33. const int buttonMargin = 15;
  34. #endregion
  35. GraphicsDeviceManager graphics;
  36. Spaceship spaceship;
  37. Checkbox[] lightEnablingButtons;
  38. Checkbox perpixelLightingButton;
  39. Checkbox animationButton;
  40. Checkbox backgroundTextureEnablingButton;
  41. float cameraFOV = 45; // Initial camera FOV (serves as a zoom level)
  42. float rotationXAmount = 0.0f;
  43. float rotationYAmount = 0.0f;
  44. float? prevLength;
  45. Texture2D background;
  46. Animation animation;
  47. Vector2 animationPosition;
  48. #region Public accessors
  49. /// <summary>
  50. /// Provides SporiteBatch to components that draw sprites
  51. /// </summary>
  52. public SpriteBatch SpriteBatch { get; private set; }
  53. #endregion
  54. #endregion
  55. #region Initialization
  56. /// <summary>
  57. /// Initialization that does not depend on GraphicsDevice
  58. /// </summary>
  59. public Graphics3DSampleGame()
  60. {
  61. Content.RootDirectory = "Content";
  62. graphics = new GraphicsDeviceManager(this);
  63. graphics.IsFullScreen = true;
  64. graphics.SupportedOrientations =
  65. DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
  66. graphics.ApplyChanges();
  67. }
  68. /// <summary>
  69. /// Initialization that depends on GraphicsDevice but does not depend on Content
  70. /// </summary>
  71. protected override void Initialize()
  72. {
  73. GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
  74. SpriteBatch = new SpriteBatch(GraphicsDevice);
  75. CreateSpaceship();
  76. CreateLightEnablingButtons();
  77. CreateBackgroundTextureEnablingButton();
  78. CreatePerPixelLightingButton();
  79. CreateAnimationButton();
  80. //Initialize gestures support - Pinch for Zoom and horizontal drag for rotate
  81. TouchPanel.EnabledGestures = GestureType.FreeDrag | GestureType.Pinch | GestureType.PinchComplete;
  82. base.Initialize();
  83. }
  84. /// <summary>
  85. /// Loads content and creates graphics resources.
  86. /// </summary>
  87. protected override void LoadContent()
  88. {
  89. background = Content.Load<Texture2D>("Textures/spaceBG");
  90. animation = CreateAnimation();
  91. spaceship.Load(this.Content);
  92. base.LoadContent();
  93. }
  94. /// <summary>
  95. /// Creates animation
  96. /// </summary>
  97. /// <returns></returns>
  98. private Animation CreateAnimation()
  99. {
  100. // Load multiple animations form XML definition
  101. System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load("Content/AnimationDef.xml");
  102. System.Xml.Linq.XName name = System.Xml.Linq.XName.Get("Definition");
  103. var definitions = doc.Document.Descendants(name);
  104. // Get the first (and only in this case) animation from the XML definition
  105. var definition = definitions.First();
  106. Texture2D texture = Content.Load<Texture2D>(definition.Attribute("SheetName").Value);
  107. Point frameSize = new Point();
  108. frameSize.X = int.Parse(definition.Attribute("FrameWidth").Value);
  109. frameSize.Y = int.Parse(definition.Attribute("FrameHeight").Value);
  110. Point sheetSize = new Point();
  111. sheetSize.X = int.Parse(definition.Attribute("SheetColumns").Value);
  112. sheetSize.Y = int.Parse(definition.Attribute("SheetRows").Value);
  113. TimeSpan frameInterval = TimeSpan.FromSeconds((float)1 / int.Parse(definition.Attribute("Speed").Value));
  114. //Calculate the animation position (in the middle fot he screen)
  115. animationPosition = new Vector2((graphics.PreferredBackBufferWidth / 2 - frameSize.X),
  116. (graphics.PreferredBackBufferHeight / 2 - frameSize.Y));
  117. return new Animation(texture, frameSize, sheetSize, frameInterval);
  118. }
  119. /// <summary>
  120. /// Creates spaceship
  121. /// </summary>
  122. private void CreateSpaceship()
  123. {
  124. spaceship = new Spaceship();
  125. spaceship.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(cameraFOV),
  126. GraphicsDevice.Viewport.AspectRatio, 10, 20000);
  127. }
  128. /// <summary>
  129. /// Creates light enabling buttons
  130. /// </summary>
  131. private void CreateLightEnablingButtons()
  132. {
  133. lightEnablingButtons = new Checkbox[3];
  134. for (int n = 0; n < lightEnablingButtons.Length; n++)
  135. {
  136. lightEnablingButtons[n] = new Checkbox(this, "Buttons/lamp_60x60",
  137. new Rectangle(GraphicsDevice.Viewport.Width - (n + 1) * (buttonWidth + buttonMargin),
  138. buttonMargin, buttonWidth, buttonHeight), true);
  139. this.Components.Add(lightEnablingButtons[n]);
  140. }
  141. }
  142. /// <summary>
  143. /// Creates per-pixel lighting button
  144. /// </summary>
  145. private void CreatePerPixelLightingButton()
  146. {
  147. perpixelLightingButton = new Checkbox(this, "Buttons/perPixelLight_60x60",
  148. new Rectangle(GraphicsDevice.Viewport.Width - (buttonWidth + buttonMargin),
  149. GraphicsDevice.Viewport.Height - (buttonHeight + buttonMargin),
  150. buttonWidth, buttonHeight), false);
  151. this.Components.Add(perpixelLightingButton);
  152. }
  153. /// <summary>
  154. /// Creates animation button
  155. /// </summary>
  156. private void CreateAnimationButton()
  157. {
  158. animationButton = new Checkbox(this, "Buttons/animation_60x60",
  159. new Rectangle(buttonMargin,
  160. GraphicsDevice.Viewport.Height - (buttonHeight + buttonMargin),
  161. buttonWidth, buttonHeight), false);
  162. this.Components.Add(animationButton);
  163. }
  164. /// <summary>
  165. /// Create texture enabling button
  166. /// </summary>
  167. private void CreateBackgroundTextureEnablingButton()
  168. {
  169. backgroundTextureEnablingButton = new Checkbox(this, "Buttons/textureOnOff",
  170. new Rectangle(buttonMargin, buttonMargin, buttonWidth, buttonHeight), false);
  171. this.Components.Add(backgroundTextureEnablingButton);
  172. }
  173. #endregion
  174. #region Update
  175. /// <summary>
  176. /// Updates spaceship rendering properties
  177. /// </summary>
  178. protected override void Update(GameTime gameTime)
  179. {
  180. // Handle touch input first
  181. HandleInput();
  182. // Allows the game to exit
  183. if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
  184. this.Exit();
  185. spaceship.Rotation = GetRotationMatrix();
  186. spaceship.View = GetViewMatrix();
  187. spaceship.Lights = lightEnablingButtons.Select(e => e.IsChecked).ToArray();
  188. spaceship.IsTextureEnabled = true;
  189. spaceship.IsPerPixelLightingEnabled = perpixelLightingButton.IsChecked;
  190. spaceship.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(cameraFOV),
  191. GraphicsDevice.Viewport.AspectRatio, 10, 20000);
  192. if (animationButton.IsChecked)
  193. {
  194. animation.Update(gameTime);
  195. }
  196. base.Update(gameTime);
  197. }
  198. private void HandleInput()
  199. {
  200. while (TouchPanel.IsGestureAvailable)
  201. {
  202. GestureSample gestureSample = TouchPanel.ReadGesture();
  203. switch (gestureSample.GestureType)
  204. {
  205. case GestureType.FreeDrag:
  206. rotationXAmount += gestureSample.Delta.X;
  207. rotationYAmount -= gestureSample.Delta.Y;
  208. break;
  209. case GestureType.Pinch:
  210. float gestureValue = 0;
  211. float minFOV = 60;
  212. float maxFOV = 30;
  213. float gestureLengthToZoomScale = 10;
  214. Vector2 gestureDiff = gestureSample.Position - gestureSample.Position2;
  215. gestureValue = gestureDiff.Length() / gestureLengthToZoomScale;
  216. if (null != prevLength) // Skip the first pinch event
  217. cameraFOV -= gestureValue - prevLength.Value;
  218. cameraFOV = MathHelper.Clamp(cameraFOV, maxFOV, minFOV);
  219. prevLength = gestureValue;
  220. break;
  221. case GestureType.PinchComplete:
  222. prevLength = null;
  223. break;
  224. default:
  225. break;
  226. }
  227. }
  228. }
  229. /// <summary>
  230. /// Gets spaceship rotation matrix
  231. /// </summary>
  232. /// <returns></returns>
  233. private Matrix GetRotationMatrix()
  234. {
  235. Matrix matrix = Matrix.CreateWorld(new Vector3(0, 250, 0), Vector3.Forward, Vector3.Up) *
  236. Matrix.CreateFromYawPitchRoll((float)Math.PI + MathHelper.PiOver2 + rotationXAmount / 100, rotationYAmount / 100, 0);
  237. return matrix;
  238. }
  239. /// <summary>
  240. /// Gets spaceship view matrix
  241. /// </summary>
  242. private Matrix GetViewMatrix()
  243. {
  244. return Matrix.CreateLookAt(
  245. new Vector3(3500, 400, 0) + new Vector3(0, 250, 0),
  246. new Vector3(0, 250, 0),
  247. Vector3.Up);
  248. }
  249. #endregion
  250. #region Draw
  251. /// <summary>
  252. /// Draws the game
  253. /// </summary>
  254. protected override void Draw(GameTime gameTime)
  255. {
  256. GraphicsDevice.Clear(Color.CornflowerBlue);
  257. if (backgroundTextureEnablingButton.IsChecked)
  258. {
  259. SpriteBatch.Begin();
  260. SpriteBatch.Draw(background, Vector2.Zero, Color.White);
  261. SpriteBatch.End();
  262. }
  263. var lights = lightEnablingButtons.Select(e => e.IsChecked).ToArray();
  264. // Set render states.
  265. GraphicsDevice.BlendState = BlendState.Opaque;
  266. GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
  267. GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  268. GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
  269. // This draws game components, including the currently active menu screen.
  270. // Draw the spaceship model
  271. spaceship.Draw();
  272. if (animationButton.IsChecked)
  273. {
  274. DrawAnimation();
  275. }
  276. base.Draw(gameTime);
  277. }
  278. /// <summary>
  279. /// Draws animation
  280. /// </summary>
  281. private void DrawAnimation()
  282. {
  283. float screenHeight = graphics.PreferredBackBufferHeight;
  284. float scale = (float)(graphics.PreferredBackBufferWidth / 480.0);
  285. SpriteBatch.Begin();
  286. animation.Draw(SpriteBatch, animationPosition, 2.0f, SpriteEffects.None);
  287. SpriteBatch.End();
  288. }
  289. #endregion
  290. }
  291. }