ScreenManager.cs 21 KB

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