ScreenManager.cs 15 KB

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