ScreenManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. //-----------------------------------------------------------------------------
  2. // ScreenManager.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Diagnostics;
  9. using System.Collections.Generic;
  10. using Microsoft.Xna.Framework;
  11. using Microsoft.Xna.Framework.Content;
  12. using Microsoft.Xna.Framework.Graphics;
  13. using Microsoft.Xna.Framework.Input.Touch;
  14. namespace NetworkStateManagement
  15. {
  16. /// <summary>
  17. /// The screen manager is a component which manages one or more GameScreen
  18. /// instances. It maintains a stack of screens, calls their Update and Draw
  19. /// methods at the appropriate times, and automatically routes input to the
  20. /// topmost active screen.
  21. /// </summary>
  22. public class ScreenManager : DrawableGameComponent
  23. {
  24. List<GameScreen> screens = new List<GameScreen>();
  25. List<GameScreen> screensToUpdate = new List<GameScreen>();
  26. InputState inputState = new InputState(BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT);
  27. public InputState InputState => inputState;
  28. SpriteBatch spriteBatch;
  29. SpriteFont font;
  30. Texture2D blankTexture;
  31. bool isInitialized;
  32. bool traceEnabled;
  33. internal const int BASE_BUFFER_WIDTH = 800;
  34. internal const int BASE_BUFFER_HEIGHT = 480;
  35. private int backbufferWidth;
  36. /// <summary>Gets or sets the current backbuffer width.</summary>
  37. public int BackbufferWidth { get => backbufferWidth; set => backbufferWidth = value; }
  38. private int backbufferHeight;
  39. /// <summary>Gets or sets the current backbuffer height.</summary>
  40. public int BackbufferHeight { get => backbufferHeight; set => backbufferHeight = value; }
  41. private Vector2 baseScreenSize = new Vector2(BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT);
  42. /// <summary>Gets or sets the base screen size used for scaling calculations.</summary>
  43. public Vector2 BaseScreenSize { get => baseScreenSize; set => baseScreenSize = value; }
  44. private Matrix globalTransformation;
  45. /// <summary>Gets or sets the global transformation matrix for scaling and positioning.</summary>
  46. public Matrix GlobalTransformation { get => globalTransformation; set => globalTransformation = value; }
  47. /// <summary>
  48. /// A default SpriteBatch shared by all the screens. This saves
  49. /// each screen having to bother creating their own local instance.
  50. /// </summary>
  51. public SpriteBatch SpriteBatch
  52. {
  53. get { return spriteBatch; }
  54. }
  55. /// <summary>
  56. /// A default font shared by all the screens. This saves
  57. /// each screen having to bother loading their own local copy.
  58. /// </summary>
  59. public SpriteFont Font
  60. {
  61. get { return font; }
  62. }
  63. /// <summary>
  64. /// If true, the manager prints out a list of all the screens
  65. /// each time it is updated. This can be useful for making sure
  66. /// everything is being added and removed at the right times.
  67. /// </summary>
  68. public bool TraceEnabled
  69. {
  70. get { return traceEnabled; }
  71. set { traceEnabled = value; }
  72. }
  73. /// <summary>
  74. /// Constructs a new screen manager component.
  75. /// </summary>
  76. public ScreenManager(Game game)
  77. : base(game)
  78. {
  79. // we must set EnabledGestures before we can query for them, but
  80. // we don't assume the game wants to read them.
  81. TouchPanel.EnabledGestures = GestureType.None;
  82. }
  83. /// <summary>
  84. /// Initializes the screen manager component.
  85. /// </summary>
  86. public override void Initialize()
  87. {
  88. base.Initialize();
  89. isInitialized = true;
  90. }
  91. /// <summary>
  92. /// Load your graphics content.
  93. /// </summary>
  94. protected override void LoadContent()
  95. {
  96. // Load content belonging to the screen manager.
  97. ContentManager content = Game.Content;
  98. spriteBatch = new SpriteBatch(GraphicsDevice);
  99. font = content.Load<SpriteFont>("menufont");
  100. blankTexture = content.Load<Texture2D>("blank");
  101. // Tell each of the screens to load their content.
  102. foreach (GameScreen screen in screens)
  103. {
  104. screen.LoadContent();
  105. }
  106. }
  107. /// <summary>
  108. /// Unload your graphics content.
  109. /// </summary>
  110. protected override void UnloadContent()
  111. {
  112. // Tell each of the screens to unload their content.
  113. foreach (GameScreen screen in screens)
  114. {
  115. screen.UnloadContent();
  116. }
  117. }
  118. /// <summary>
  119. /// Allows each screen to run logic.
  120. /// </summary>
  121. public override void Update(GameTime gameTime)
  122. {
  123. // Read the keyboard and gamepad.
  124. inputState.Update();
  125. // Make a copy of the master screen list, to avoid confusion if
  126. // the process of updating one screen adds or removes others.
  127. screensToUpdate.Clear();
  128. foreach (GameScreen screen in screens)
  129. screensToUpdate.Add(screen);
  130. bool otherScreenHasFocus = !Game.IsActive;
  131. bool coveredByOtherScreen = false;
  132. // Loop as long as there are screens waiting to be updated.
  133. while (screensToUpdate.Count > 0)
  134. {
  135. // Pop the topmost screen off the waiting list.
  136. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  137. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  138. // Update the screen.
  139. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  140. if (screen.ScreenState == ScreenState.TransitionOn ||
  141. screen.ScreenState == ScreenState.Active)
  142. {
  143. // If this is the first active screen we came across,
  144. // give it a chance to handle input.
  145. if (!otherScreenHasFocus)
  146. {
  147. screen.HandleInput(inputState);
  148. otherScreenHasFocus = true;
  149. }
  150. // If this is an active non-popup, inform any subsequent
  151. // screens that they are covered by it.
  152. if (!screen.IsPopup)
  153. coveredByOtherScreen = true;
  154. }
  155. }
  156. // Print debug trace?
  157. if (traceEnabled)
  158. TraceScreens();
  159. }
  160. /// <summary>
  161. /// Prints a list of all the screens, for debugging.
  162. /// </summary>
  163. void TraceScreens()
  164. {
  165. List<string> screenNames = new List<string>();
  166. foreach (GameScreen screen in screens)
  167. screenNames.Add(screen.GetType().Name);
  168. Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
  169. }
  170. /// <summary>
  171. /// Tells each screen to draw itself.
  172. /// </summary>
  173. public override void Draw(GameTime gameTime)
  174. {
  175. foreach (GameScreen screen in screens)
  176. {
  177. if (screen.ScreenState == ScreenState.Hidden)
  178. continue;
  179. screen.Draw(gameTime);
  180. }
  181. }
  182. /// <summary>
  183. /// Adds a new screen to the screen manager.
  184. /// </summary>
  185. public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
  186. {
  187. screen.ControllingPlayer = controllingPlayer;
  188. screen.ScreenManager = this;
  189. screen.IsExiting = false;
  190. // If we have a graphics device, tell the screen to load content.
  191. if (isInitialized)
  192. {
  193. screen.LoadContent();
  194. }
  195. screens.Add(screen);
  196. // update the TouchPanel to respond to gestures this screen is interested in
  197. TouchPanel.EnabledGestures = screen.EnabledGestures;
  198. }
  199. /// <summary>
  200. /// Removes a screen from the screen manager. You should normally
  201. /// use GameScreen.ExitScreen instead of calling this directly, so
  202. /// the screen can gradually transition off rather than just being
  203. /// instantly removed.
  204. /// </summary>
  205. public void RemoveScreen(GameScreen screen)
  206. {
  207. // If we have a graphics device, tell the screen to unload content.
  208. if (isInitialized)
  209. {
  210. screen.UnloadContent();
  211. }
  212. screens.Remove(screen);
  213. screensToUpdate.Remove(screen);
  214. // if there is a screen still in the manager, update TouchPanel
  215. // to respond to gestures that screen is interested in.
  216. if (screens.Count > 0)
  217. {
  218. TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
  219. }
  220. }
  221. /// <summary>
  222. /// Expose an array holding all the screens. We return a copy rather
  223. /// than the real master list, because screens should only ever be added
  224. /// or removed using the AddScreen and RemoveScreen methods.
  225. /// </summary>
  226. public GameScreen[] GetScreens()
  227. {
  228. return screens.ToArray();
  229. }
  230. /// <summary>
  231. /// Helper draws a translucent black fullscreen sprite, used for fading
  232. /// screens in and out, and for darkening the background behind popups.
  233. /// </summary>
  234. public void FadeBackBufferToBlack(float alpha)
  235. {
  236. spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, GlobalTransformation);
  237. spriteBatch.Draw(blankTexture,
  238. new Rectangle(0, 0, BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT),
  239. Color.Black * alpha);
  240. spriteBatch.End();
  241. }
  242. /// <summary>
  243. /// Scales the game presentation area to match the screen's aspect ratio.
  244. /// </summary>
  245. public void ScalePresentationArea()
  246. {
  247. // Validate parameters before calculation
  248. if (GraphicsDevice == null || baseScreenSize.X <= 0 || baseScreenSize.Y <= 0)
  249. {
  250. throw new InvalidOperationException("Invalid graphics configuration");
  251. }
  252. // Fetch screen dimensions
  253. backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
  254. backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
  255. // Prevent division by zero
  256. if (backbufferHeight == 0 || baseScreenSize.Y == 0)
  257. {
  258. return;
  259. }
  260. // Calculate aspect ratios
  261. float baseAspectRatio = baseScreenSize.X / baseScreenSize.Y;
  262. float screenAspectRatio = backbufferWidth / (float)backbufferHeight;
  263. // Determine uniform scaling factor
  264. float scalingFactor;
  265. float horizontalOffset = 0;
  266. float verticalOffset = 0;
  267. if (screenAspectRatio > baseAspectRatio)
  268. {
  269. // Wider screen: scale by height
  270. scalingFactor = backbufferHeight / baseScreenSize.Y;
  271. // Centre things horizontally.
  272. horizontalOffset = (backbufferWidth - baseScreenSize.X * scalingFactor) / 2;
  273. }
  274. else
  275. {
  276. // Taller screen: scale by width
  277. scalingFactor = backbufferWidth / baseScreenSize.X;
  278. // Centre things vertically.
  279. verticalOffset = (backbufferHeight - baseScreenSize.Y * scalingFactor) / 2;
  280. }
  281. // Update the transformation matrix
  282. globalTransformation = Matrix.CreateScale(scalingFactor) *
  283. Matrix.CreateTranslation(horizontalOffset, verticalOffset, 0);
  284. // Update the inputTransformation with the Inverted globalTransformation
  285. inputState.UpdateInputTransformation(Matrix.Invert(globalTransformation));
  286. // Debug info
  287. Debug.WriteLine($"Screen Size - Width[{backbufferWidth}] Height[{backbufferHeight}] ScalingFactor[{scalingFactor}]");
  288. }
  289. }
  290. }