2
0

ScreenManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. using System.IO;
  15. using System.IO.IsolatedStorage;
  16. namespace GameStateManagement
  17. {
  18. /// <summary>
  19. /// The screen manager is a component which manages one or more GameScreen
  20. /// instances. It maintains a stack of screens, calls their Update and Draw
  21. /// methods at the appropriate times, and automatically routes input to the
  22. /// topmost active screen.
  23. /// </summary>
  24. public class ScreenManager : DrawableGameComponent
  25. {
  26. List<GameScreen> screens = new List<GameScreen>();
  27. List<GameScreen> screensToUpdate = new List<GameScreen>();
  28. public InputState input = new InputState();
  29. SpriteBatch spriteBatch;
  30. SpriteFont font;
  31. Texture2D blankTexture;
  32. Texture2D buttonBackground;
  33. bool isInitialized;
  34. bool traceEnabled;
  35. internal const int BACK_BUFFER_WIDTH = 800;
  36. internal const int BACK_BUFFER_HEIGHT = 480;
  37. private int backbufferWidth;
  38. /// <summary>Gets or sets the current backbuffer width.</summary>
  39. public int BackbufferWidth { get => backbufferWidth; set => backbufferWidth = value; }
  40. private int backbufferHeight;
  41. /// <summary>Gets or sets the current backbuffer height.</summary>
  42. public int BackbufferHeight { get => backbufferHeight; set => backbufferHeight = value; }
  43. private Vector2 baseScreenSize = new Vector2(BACK_BUFFER_WIDTH, BACK_BUFFER_HEIGHT);
  44. /// <summary>Gets or sets the base screen size used for scaling calculations.</summary>
  45. public Vector2 BaseScreenSize { get => baseScreenSize; set => baseScreenSize = value; }
  46. private Matrix globalTransformation;
  47. /// <summary>Gets or sets the global transformation matrix for scaling and positioning.</summary>
  48. public Matrix GlobalTransformation { get => globalTransformation; set => globalTransformation = value; }
  49. /// <summary>
  50. /// A default SpriteBatch shared by all the screens. This saves
  51. /// each screen having to bother creating their own local instance.
  52. /// </summary>
  53. public SpriteBatch SpriteBatch
  54. {
  55. get { return spriteBatch; }
  56. }
  57. public Texture2D ButtonBackground
  58. {
  59. get { return buttonBackground; }
  60. }
  61. public Texture2D BlankTexture
  62. {
  63. get { return blankTexture; }
  64. }
  65. /// <summary>
  66. /// A default font shared by all the screens. This saves
  67. /// each screen having to bother loading their own local copy.
  68. /// </summary>
  69. public SpriteFont Font
  70. {
  71. get { return font; }
  72. }
  73. /// <summary>
  74. /// If true, the manager prints out a list of all the screens
  75. /// each time it is updated. This can be useful for making sure
  76. /// everything is being added and removed at the right times.
  77. /// </summary>
  78. public bool TraceEnabled
  79. {
  80. get { return traceEnabled; }
  81. set { traceEnabled = value; }
  82. }
  83. Rectangle safeArea = new Rectangle(0, 0, BACK_BUFFER_WIDTH, BACK_BUFFER_HEIGHT);
  84. /// <summary>
  85. /// Returns the portion of the screen where drawing is safely allowed.
  86. /// </summary>
  87. public Rectangle SafeArea
  88. {
  89. get
  90. {
  91. return safeArea;
  92. }
  93. }
  94. /// <summary>
  95. /// Constructs a new screen manager component.
  96. /// </summary>
  97. public ScreenManager(Game game)
  98. : base(game)
  99. {
  100. // we must set EnabledGestures before we can query for them, but
  101. // we don't assume the game wants to read them.
  102. TouchPanel.EnabledGestures = GestureType.None;
  103. }
  104. /// <summary>
  105. /// Initializes the screen manager component.
  106. /// </summary>
  107. public override void Initialize()
  108. {
  109. base.Initialize();
  110. isInitialized = true;
  111. }
  112. /// <summary>
  113. /// Load your graphics content.
  114. /// </summary>
  115. protected override void LoadContent()
  116. {
  117. // Load content belonging to the screen manager.
  118. ContentManager content = Game.Content;
  119. spriteBatch = new SpriteBatch(GraphicsDevice);
  120. font = content.Load<SpriteFont>("Fonts/MenuFont");
  121. blankTexture = content.Load<Texture2D>("Images/blank");
  122. buttonBackground = content.Load<Texture2D>("Images/ButtonRegular");
  123. // Tell each of the screens to load their content.
  124. foreach (GameScreen screen in screens)
  125. {
  126. screen.LoadContent();
  127. }
  128. }
  129. /// <summary>
  130. /// Unload your graphics content.
  131. /// </summary>
  132. protected override void UnloadContent()
  133. {
  134. // Tell each of the screens to unload their content.
  135. foreach (GameScreen screen in screens)
  136. {
  137. screen.UnloadContent();
  138. }
  139. }
  140. /// <summary>
  141. /// Allows each screen to run logic.
  142. /// </summary>
  143. public override void Update(GameTime gameTime)
  144. {
  145. // Read the keyboard and gamepad.
  146. input.Update();
  147. // Make a copy of the master screen list, to avoid confusion if
  148. // the process of updating one screen adds or removes others.
  149. screensToUpdate.Clear();
  150. foreach (GameScreen screen in screens)
  151. screensToUpdate.Add(screen);
  152. bool otherScreenHasFocus = !Game.IsActive;
  153. bool coveredByOtherScreen = false;
  154. // Loop as long as there are screens waiting to be updated.
  155. while (screensToUpdate.Count > 0)
  156. {
  157. // Pop the topmost screen off the waiting list.
  158. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  159. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  160. // Update the screen.
  161. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  162. if (screen.ScreenState == ScreenState.TransitionOn ||
  163. screen.ScreenState == ScreenState.Active)
  164. {
  165. // If this is the first active screen we came across,
  166. // give it a chance to handle input.
  167. if (!otherScreenHasFocus)
  168. {
  169. screen.HandleInput(input);
  170. otherScreenHasFocus = true;
  171. }
  172. // If this is an active non-popup, inform any subsequent
  173. // screens that they are covered by it.
  174. if (!screen.IsPopup)
  175. coveredByOtherScreen = true;
  176. }
  177. }
  178. // Print debug trace?
  179. if (traceEnabled)
  180. TraceScreens();
  181. }
  182. /// <summary>
  183. /// Prints a list of all the screens, for debugging.
  184. /// </summary>
  185. void TraceScreens()
  186. {
  187. List<string> screenNames = new List<string>();
  188. foreach (GameScreen screen in screens)
  189. screenNames.Add(screen.GetType().Name);
  190. Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
  191. }
  192. /// <summary>
  193. /// Tells each screen to draw itself.
  194. /// </summary>
  195. public override void Draw(GameTime gameTime)
  196. {
  197. foreach (GameScreen screen in screens)
  198. {
  199. if (screen.ScreenState == ScreenState.Hidden)
  200. continue;
  201. screen.Draw(gameTime);
  202. }
  203. }
  204. /// <summary>
  205. /// Adds a new screen to the screen manager.
  206. /// </summary>
  207. public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
  208. {
  209. screen.ControllingPlayer = controllingPlayer;
  210. screen.ScreenManager = this;
  211. screen.IsExiting = false;
  212. // If we have a graphics device, tell the screen to load content.
  213. if (isInitialized)
  214. {
  215. screen.LoadContent();
  216. }
  217. screens.Add(screen);
  218. // update the TouchPanel to respond to gestures this screen is interested in
  219. TouchPanel.EnabledGestures = screen.EnabledGestures;
  220. }
  221. /// <summary>
  222. /// Removes a screen from the screen manager. You should normally
  223. /// use GameScreen.ExitScreen instead of calling this directly, so
  224. /// the screen can gradually transition off rather than just being
  225. /// instantly removed.
  226. /// </summary>
  227. public void RemoveScreen(GameScreen screen)
  228. {
  229. // If we have a graphics device, tell the screen to unload content.
  230. if (isInitialized)
  231. {
  232. screen.UnloadContent();
  233. }
  234. screens.Remove(screen);
  235. screensToUpdate.Remove(screen);
  236. // if there is a screen still in the manager, update TouchPanel
  237. // to respond to gestures that screen is interested in.
  238. if (screens.Count > 0)
  239. {
  240. TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
  241. }
  242. }
  243. /// <summary>
  244. /// Expose an array holding all the screens. We return a copy rather
  245. /// than the real master list, because screens should only ever be added
  246. /// or removed using the AddScreen and RemoveScreen methods.
  247. /// </summary>
  248. public GameScreen[] GetScreens()
  249. {
  250. return screens.ToArray();
  251. }
  252. /// <summary>
  253. /// Helper draws a translucent black fullscreen sprite, used for fading
  254. /// screens in and out, and for darkening the background behind popups.
  255. /// </summary>
  256. public void FadeBackBufferToBlack(float alpha)
  257. {
  258. spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, GlobalTransformation);
  259. spriteBatch.Draw(blankTexture,
  260. new Rectangle(0, 0, BACK_BUFFER_WIDTH, BACK_BUFFER_HEIGHT),
  261. Color.Black * alpha);
  262. spriteBatch.End();
  263. }
  264. /// <summary>
  265. /// Scales the game presentation area to match the screen's aspect ratio.
  266. /// </summary>
  267. public void ScalePresentationArea()
  268. {
  269. // Validate parameters before calculation
  270. if (GraphicsDevice == null || baseScreenSize.X <= 0 || baseScreenSize.Y <= 0)
  271. {
  272. throw new InvalidOperationException("Invalid graphics configuration");
  273. }
  274. // Fetch screen dimensions
  275. backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
  276. backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
  277. // Prevent division by zero
  278. if (backbufferHeight == 0 || baseScreenSize.Y == 0)
  279. {
  280. return;
  281. }
  282. // Calculate aspect ratios
  283. float baseAspectRatio = baseScreenSize.X / baseScreenSize.Y;
  284. float screenAspectRatio = backbufferWidth / (float)backbufferHeight;
  285. // Determine uniform scaling factor
  286. float scalingFactor;
  287. float horizontalOffset = 0;
  288. float verticalOffset = 0;
  289. if (screenAspectRatio > baseAspectRatio)
  290. {
  291. // Wider screen: scale by height
  292. scalingFactor = backbufferHeight / baseScreenSize.Y;
  293. // Centre things horizontally.
  294. horizontalOffset = (backbufferWidth - baseScreenSize.X * scalingFactor) / 2;
  295. }
  296. else
  297. {
  298. // Taller screen: scale by width
  299. scalingFactor = backbufferWidth / baseScreenSize.X;
  300. // Centre things vertically.
  301. verticalOffset = (backbufferHeight - baseScreenSize.Y * scalingFactor) / 2;
  302. }
  303. // Update the transformation matrix
  304. globalTransformation = Matrix.CreateScale(scalingFactor) *
  305. Matrix.CreateTranslation(horizontalOffset, verticalOffset, 0);
  306. // Update the inputTransformation with the Inverted globalTransformation
  307. // TODO inputState.UpdateInputTransformation(Matrix.Invert(globalTransformation));
  308. // Debug info
  309. Debug.WriteLine($"Screen Size - Width[{backbufferWidth}] Height[{backbufferHeight}] ScalingFactor[{scalingFactor}]");
  310. }
  311. /// <summary>
  312. /// Informs the screen manager to serialize its state to disk.
  313. /// </summary>
  314. public void SerializeState()
  315. {
  316. // open up isolated storage
  317. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  318. {
  319. // if our screen manager directory already exists, delete the contents
  320. if (storage.DirectoryExists("ScreenManager"))
  321. {
  322. DeleteState(storage);
  323. }
  324. // otherwise just create the directory
  325. else
  326. {
  327. storage.CreateDirectory("ScreenManager");
  328. }
  329. // create a file we'll use to store the list of screens in the stack
  330. using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
  331. {
  332. using (BinaryWriter writer = new BinaryWriter(stream))
  333. {
  334. // write out the full name of all the types in our stack so we can
  335. // recreate them if needed.
  336. foreach (GameScreen screen in screens)
  337. {
  338. if (screen.IsSerializable)
  339. {
  340. writer.Write(screen.GetType().AssemblyQualifiedName);
  341. }
  342. }
  343. }
  344. }
  345. // now we create a new file stream for each screen so it can save its state
  346. // if it needs to. we name each file "ScreenX.dat" where X is the index of
  347. // the screen in the stack, to ensure the files are uniquely named
  348. int screenIndex = 0;
  349. foreach (GameScreen screen in screens)
  350. {
  351. if (screen.IsSerializable)
  352. {
  353. string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);
  354. // open up the stream and let the screen serialize whatever state it wants
  355. using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
  356. {
  357. screen.Serialize(stream);
  358. }
  359. screenIndex++;
  360. }
  361. }
  362. }
  363. }
  364. public bool DeserializeState()
  365. {
  366. // open up isolated storage
  367. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  368. {
  369. // see if our saved state directory exists
  370. if (storage.DirectoryExists("ScreenManager"))
  371. {
  372. try
  373. {
  374. // see if we have a screen list
  375. if (storage.FileExists("ScreenManager\\ScreenList.dat"))
  376. {
  377. // load the list of screen types
  378. using (IsolatedStorageFileStream stream =
  379. storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open,
  380. FileAccess.Read))
  381. {
  382. using (BinaryReader reader = new BinaryReader(stream))
  383. {
  384. while (reader.BaseStream.Position < reader.BaseStream.Length)
  385. {
  386. // read a line from our file
  387. string line = reader.ReadString();
  388. // if it isn't blank, we can create a screen from it
  389. if (!string.IsNullOrEmpty(line))
  390. {
  391. Type screenType = Type.GetType(line);
  392. GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
  393. AddScreen(screen, PlayerIndex.One);
  394. }
  395. }
  396. }
  397. }
  398. }
  399. // next we give each screen a chance to deserialize from the disk
  400. for (int i = 0; i < screens.Count; i++)
  401. {
  402. string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
  403. using (IsolatedStorageFileStream stream = storage.OpenFile(filename,
  404. FileMode.Open, FileAccess.Read))
  405. {
  406. screens[i].Deserialize(stream);
  407. }
  408. }
  409. return true;
  410. }
  411. catch (Exception)
  412. {
  413. // if an exception was thrown while reading, odds are we cannot recover
  414. // from the saved state, so we will delete it so the game can correctly
  415. // launch.
  416. DeleteState(storage);
  417. }
  418. }
  419. }
  420. return false;
  421. }
  422. /// <summary>
  423. /// Deletes the saved state files from isolated storage.
  424. /// </summary>
  425. private void DeleteState(IsolatedStorageFile storage)
  426. {
  427. // get all of the files in the directory and delete them
  428. string[] files = storage.GetFileNames("ScreenManager\\*");
  429. foreach (string file in files)
  430. {
  431. storage.DeleteFile(Path.Combine("ScreenManager", file));
  432. }
  433. }
  434. }
  435. }