ScreenManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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 the appropriate fonts based on the saved language setting
  145. // This handles the case where the game was closed with a CJK language selected
  146. string currentLanguage = Blackjack.GameSettings.Instance.Language;
  147. bool useCJKFont = currentLanguage == "日本語" || currentLanguage == "中文";
  148. string menuFontPath = useCJKFont ? "Fonts/MenuFont_CJK" : "Fonts/MenuFont";
  149. string regularFontPath = useCJKFont ? "Fonts/Regular_CJK" : "Fonts/Regular";
  150. string boldFontPath = useCJKFont ? "Fonts/Bold_CJK" : "Fonts/Bold";
  151. font = content.Load<SpriteFont>(menuFontPath);
  152. regularFont = content.Load<SpriteFont>(regularFontPath);
  153. boldFont = content.Load<SpriteFont>(boldFontPath);
  154. blankTexture = content.Load<Texture2D>("Images/blank");
  155. buttonBackground = content.Load<Texture2D>("Images/ButtonRegular");
  156. buttonPressed = content.Load<Texture2D>("Images/ButtonPressed");
  157. // Tell each of the screens to load their content.
  158. foreach (GameScreen screen in screens)
  159. {
  160. screen.LoadContent();
  161. }
  162. }
  163. /// <summary>
  164. /// Reloads the font based on the current language setting.
  165. /// Uses CJK fonts for Japanese and Chinese, regular fonts for other languages.
  166. /// NOTE: This only loads fonts. Call RefreshScreensAfterLanguageChange() after
  167. /// the language has been set to rebuild screen content.
  168. /// </summary>
  169. public void ReloadFontForLanguage(string language)
  170. {
  171. ContentManager content = Game.Content;
  172. // Determine if we need CJK font support
  173. bool useCJKFont = language == "日本語" || language == "中文";
  174. // Load all appropriate fonts
  175. string menuFontPath = useCJKFont ? "Fonts/MenuFont_CJK" : "Fonts/MenuFont";
  176. string regularFontPath = useCJKFont ? "Fonts/Regular_CJK" : "Fonts/Regular";
  177. string boldFontPath = useCJKFont ? "Fonts/Bold_CJK" : "Fonts/Bold";
  178. font = content.Load<SpriteFont>(menuFontPath);
  179. regularFont = content.Load<SpriteFont>(regularFontPath);
  180. boldFont = content.Load<SpriteFont>(boldFontPath);
  181. }
  182. /// <summary>
  183. /// Refreshes all screens after language change. Call this AFTER setting the language
  184. /// to ensure screens rebuild with matching language and fonts.
  185. /// </summary>
  186. public void RefreshScreensAfterLanguageChange()
  187. {
  188. foreach (GameScreen screen in screens)
  189. {
  190. if (screen is Blackjack.SettingsScreen settingsScreen)
  191. {
  192. // SettingsScreen rebuilds itself in the cycle methods
  193. }
  194. else if (screen is Blackjack.GameplayScreen gameplayScreen)
  195. {
  196. // Update gameplay button text (Deal, Clear, Hit, Stand, etc.)
  197. gameplayScreen.UpdateButtonText();
  198. }
  199. else if (screen is GameStateManagement.MenuScreen menuScreen)
  200. {
  201. // Force menu screens to rebuild their entries with the new language
  202. menuScreen.LoadContent();
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// Unload your graphics content.
  208. /// </summary>
  209. protected override void UnloadContent()
  210. {
  211. // Tell each of the screens to unload their content.
  212. foreach (GameScreen screen in screens)
  213. {
  214. screen.UnloadContent();
  215. }
  216. }
  217. /// <summary>
  218. /// Allows each screen to run logic.
  219. /// </summary>
  220. public override void Update(GameTime gameTime)
  221. {
  222. // Read the keyboard and gamepad.
  223. inputState.Update(gameTime);
  224. // Make a copy of the master screen list, to avoid confusion if
  225. // the process of updating one screen adds or removes others.
  226. screensToUpdate.Clear();
  227. foreach (GameScreen screen in screens)
  228. screensToUpdate.Add(screen);
  229. bool otherScreenHasFocus = !Game.IsActive;
  230. bool coveredByOtherScreen = false;
  231. // Loop as long as there are screens waiting to be updated.
  232. while (screensToUpdate.Count > 0)
  233. {
  234. // Pop the topmost screen off the waiting list.
  235. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
  236. screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
  237. // Update the screen.
  238. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  239. if (screen.ScreenState == ScreenState.TransitionOn ||
  240. screen.ScreenState == ScreenState.Active)
  241. {
  242. // If this is the first active screen we came across,
  243. // give it a chance to handle input.
  244. if (!otherScreenHasFocus)
  245. {
  246. screen.HandleInput(inputState);
  247. otherScreenHasFocus = true;
  248. }
  249. // If this is an active non-popup, inform any subsequent
  250. // screens that they are covered by it.
  251. if (!screen.IsPopup)
  252. coveredByOtherScreen = true;
  253. }
  254. }
  255. // Print debug trace?
  256. if (traceEnabled)
  257. TraceScreens();
  258. }
  259. /// <summary>
  260. /// Prints a list of all the screens, for debugging.
  261. /// </summary>
  262. void TraceScreens()
  263. {
  264. List<string> screenNames = new List<string>();
  265. foreach (GameScreen screen in screens)
  266. screenNames.Add(screen.GetType().Name);
  267. Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
  268. }
  269. /// <summary>
  270. /// Tells each screen to draw itself.
  271. /// </summary>
  272. public override void Draw(GameTime gameTime)
  273. {
  274. foreach (GameScreen screen in screens)
  275. {
  276. if (screen.ScreenState == ScreenState.Hidden)
  277. continue;
  278. screen.Draw(gameTime);
  279. }
  280. }
  281. /// <summary>
  282. /// Adds a new screen to the screen manager.
  283. /// </summary>
  284. public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
  285. {
  286. screen.ControllingPlayer = controllingPlayer;
  287. screen.ScreenManager = this;
  288. screen.IsExiting = false;
  289. // If we have a graphics device, tell the screen to load content.
  290. if (isInitialized)
  291. {
  292. screen.LoadContent();
  293. }
  294. screens.Add(screen);
  295. // update the TouchPanel to respond to gestures this screen is interested in
  296. TouchPanel.EnabledGestures = screen.EnabledGestures;
  297. }
  298. /// <summary>
  299. /// Removes a screen from the screen manager. You should normally
  300. /// use GameScreen.ExitScreen instead of calling this directly, so
  301. /// the screen can gradually transition off rather than just being
  302. /// instantly removed.
  303. /// </summary>
  304. public void RemoveScreen(GameScreen screen)
  305. {
  306. // If we have a graphics device, tell the screen to unload content.
  307. if (isInitialized)
  308. {
  309. screen.UnloadContent();
  310. }
  311. screens.Remove(screen);
  312. screensToUpdate.Remove(screen);
  313. // if there is a screen still in the manager, update TouchPanel
  314. // to respond to gestures that screen is interested in.
  315. if (screens.Count > 0)
  316. {
  317. TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
  318. }
  319. }
  320. /// <summary>
  321. /// Expose an array holding all the screens. We return a copy rather
  322. /// than the real master list, because screens should only ever be added
  323. /// or removed using the AddScreen and RemoveScreen methods.
  324. /// </summary>
  325. public GameScreen[] GetScreens()
  326. {
  327. return screens.ToArray();
  328. }
  329. /// <summary>
  330. /// Helper draws a translucent black fullscreen sprite, used for fading
  331. /// screens in and out, and for darkening the background behind popups.
  332. /// </summary>
  333. public void FadeBackBufferToBlack(float alpha)
  334. {
  335. spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, GlobalTransformation);
  336. spriteBatch.Draw(blankTexture,
  337. new Rectangle(0, 0, BASE_BUFFER_WIDTH, BASE_BUFFER_HEIGHT),
  338. Color.Black * alpha);
  339. spriteBatch.End();
  340. }
  341. /// <summary>
  342. /// Scales the game presentation area to match the screen's aspect ratio.
  343. /// </summary>
  344. public void ScalePresentationArea()
  345. {
  346. // Validate parameters before calculation
  347. if (GraphicsDevice == null || baseScreenSize.X <= 0 || baseScreenSize.Y <= 0)
  348. {
  349. throw new InvalidOperationException("Invalid graphics configuration");
  350. }
  351. // Fetch screen dimensions
  352. backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
  353. backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
  354. // Prevent division by zero
  355. if (backbufferHeight == 0 || baseScreenSize.Y == 0)
  356. {
  357. return;
  358. }
  359. // Calculate aspect ratios
  360. float baseAspectRatio = baseScreenSize.X / baseScreenSize.Y;
  361. float screenAspectRatio = backbufferWidth / (float)backbufferHeight;
  362. // Determine uniform scaling factor
  363. float scalingFactor;
  364. float horizontalOffset = 0;
  365. float verticalOffset = 0;
  366. if (screenAspectRatio > baseAspectRatio)
  367. {
  368. // Wider screen: scale by height
  369. scalingFactor = backbufferHeight / baseScreenSize.Y;
  370. // Centre things horizontally.
  371. horizontalOffset = (backbufferWidth - baseScreenSize.X * scalingFactor) / 2;
  372. }
  373. else
  374. {
  375. // Taller screen: scale by width
  376. scalingFactor = backbufferWidth / baseScreenSize.X;
  377. // Centre things vertically.
  378. verticalOffset = (backbufferHeight - baseScreenSize.Y * scalingFactor) / 2;
  379. }
  380. // Update the transformation matrix
  381. globalTransformation = Matrix.CreateScale(scalingFactor) *
  382. Matrix.CreateTranslation(horizontalOffset, verticalOffset, 0);
  383. // Update the inputTransformation with the Inverted globalTransformation
  384. inputState.UpdateInputTransformation(Matrix.Invert(globalTransformation));
  385. // Debug info
  386. Debug.WriteLine($"Screen Size - Width[{backbufferWidth}] Height[{backbufferHeight}] ScalingFactor[{scalingFactor}]");
  387. }
  388. /// <summary>
  389. /// Informs the screen manager to serialize its state to disk.
  390. /// </summary>
  391. public void SerializeState()
  392. {
  393. // open up isolated storage
  394. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  395. {
  396. // if our screen manager directory already exists, delete the contents
  397. if (storage.DirectoryExists("ScreenManager"))
  398. {
  399. DeleteState(storage);
  400. }
  401. // otherwise just create the directory
  402. else
  403. {
  404. storage.CreateDirectory("ScreenManager");
  405. }
  406. // create a file we'll use to store the list of screens in the stack
  407. using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
  408. {
  409. using (BinaryWriter writer = new BinaryWriter(stream))
  410. {
  411. // write out the full name of all the types in our stack so we can
  412. // recreate them if needed.
  413. foreach (GameScreen screen in screens)
  414. {
  415. if (screen.IsSerializable)
  416. {
  417. writer.Write(screen.GetType().AssemblyQualifiedName);
  418. }
  419. }
  420. }
  421. }
  422. // now we create a new file stream for each screen so it can save its state
  423. // if it needs to. we name each file "ScreenX.dat" where X is the index of
  424. // the screen in the stack, to ensure the files are uniquely named
  425. int screenIndex = 0;
  426. foreach (GameScreen screen in screens)
  427. {
  428. if (screen.IsSerializable)
  429. {
  430. string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);
  431. // open up the stream and let the screen serialize whatever state it wants
  432. using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
  433. {
  434. screen.Serialize(stream);
  435. }
  436. screenIndex++;
  437. }
  438. }
  439. }
  440. }
  441. public bool DeserializeState()
  442. {
  443. // open up isolated storage
  444. using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
  445. {
  446. // see if our saved state directory exists
  447. if (storage.DirectoryExists("ScreenManager"))
  448. {
  449. try
  450. {
  451. // see if we have a screen list
  452. if (storage.FileExists("ScreenManager\\ScreenList.dat"))
  453. {
  454. // load the list of screen types
  455. using (IsolatedStorageFileStream stream =
  456. storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open,
  457. FileAccess.Read))
  458. {
  459. using (BinaryReader reader = new BinaryReader(stream))
  460. {
  461. while (reader.BaseStream.Position < reader.BaseStream.Length)
  462. {
  463. // read a line from our file
  464. string line = reader.ReadString();
  465. // if it isn't blank, we can create a screen from it
  466. if (!string.IsNullOrEmpty(line))
  467. {
  468. Type screenType = Type.GetType(line);
  469. GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
  470. AddScreen(screen, PlayerIndex.One);
  471. }
  472. }
  473. }
  474. }
  475. }
  476. // next we give each screen a chance to deserialize from the disk
  477. for (int i = 0; i < screens.Count; i++)
  478. {
  479. string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
  480. using (IsolatedStorageFileStream stream = storage.OpenFile(filename,
  481. FileMode.Open, FileAccess.Read))
  482. {
  483. screens[i].Deserialize(stream);
  484. }
  485. }
  486. return true;
  487. }
  488. catch (Exception)
  489. {
  490. // if an exception was thrown while reading, odds are we cannot recover
  491. // from the saved state, so we will delete it so the game can correctly
  492. // launch.
  493. DeleteState(storage);
  494. }
  495. }
  496. }
  497. return false;
  498. }
  499. /// <summary>
  500. /// Deletes the saved state files from isolated storage.
  501. /// </summary>
  502. private void DeleteState(IsolatedStorageFile storage)
  503. {
  504. // get all of the files in the directory and delete them
  505. string[] files = storage.GetFileNames("ScreenManager\\*");
  506. foreach (string file in files)
  507. {
  508. storage.DeleteFile(Path.Combine("ScreenManager", file));
  509. }
  510. }
  511. }
  512. }