ScreenManager.cs 16 KB

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