ScreenManager.cs 16 KB

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