ScreenManager.cs 15 KB

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