SceneManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. using BepInEx.Configuration;
  7. using Object = UnityEngine.Object;
  8. namespace MeidoPhotoStudio.Plugin
  9. {
  10. using Input = InputManager;
  11. public class SceneManager : IManager
  12. {
  13. private static byte[] tempSceneData;
  14. private static string TempScenePath => Path.Combine(Constants.configPath, "mpstempscene");
  15. public static bool Busy { get; private set; }
  16. public static readonly Vector2 sceneDimensions = new Vector2(480, 270);
  17. private static readonly ConfigEntry<bool> sortDescending;
  18. private static readonly ConfigEntry<SortMode> currentSortMode;
  19. private readonly MeidoPhotoStudio meidoPhotoStudio;
  20. private int SortDirection => SortDescending ? -1 : 1;
  21. public bool Initialized { get; private set; }
  22. public bool KankyoMode { get; set; }
  23. public bool SortDescending
  24. {
  25. get => sortDescending.Value;
  26. set => sortDescending.Value = value;
  27. }
  28. public List<MPSScene> SceneList { get; } = new();
  29. public int CurrentDirectoryIndex { get; private set; } = -1;
  30. public string CurrentDirectoryName => CurrentDirectoryList[CurrentDirectoryIndex];
  31. public List<string> CurrentDirectoryList
  32. => KankyoMode ? Constants.KankyoDirectoryList : Constants.SceneDirectoryList;
  33. public string CurrentBasePath => KankyoMode ? Constants.kankyoPath : Constants.scenesPath;
  34. public string CurrentScenesDirectory
  35. => CurrentDirectoryIndex == 0 ? CurrentBasePath : Path.Combine(CurrentBasePath, CurrentDirectoryName);
  36. public SortMode CurrentSortMode
  37. {
  38. get => currentSortMode.Value;
  39. private set => currentSortMode.Value = value;
  40. }
  41. public int CurrentSceneIndex { get; private set; } = -1;
  42. public MPSScene CurrentScene => SceneList.Count == 0 ? null : SceneList[CurrentSceneIndex];
  43. public enum SortMode
  44. {
  45. Name, DateCreated, DateModified
  46. }
  47. static SceneManager()
  48. {
  49. sortDescending = Configuration.Config.Bind(
  50. "SceneManager", "SortDescending",
  51. false,
  52. "Sort scenes descending (Z-A)"
  53. );
  54. currentSortMode = Configuration.Config.Bind(
  55. "SceneManager", "SortMode",
  56. SortMode.Name,
  57. "Scene sorting mode"
  58. );
  59. Input.Register(MpsKey.OpenSceneManager, KeyCode.F8, "Hide/show scene manager");
  60. Input.Register(MpsKey.SaveScene, KeyCode.S, "Quick save scene");
  61. Input.Register(MpsKey.LoadScene, KeyCode.A, "Load quick saved scene");
  62. }
  63. public SceneManager(MeidoPhotoStudio meidoPhotoStudio)
  64. {
  65. this.meidoPhotoStudio = meidoPhotoStudio;
  66. Activate();
  67. }
  68. public void Activate() { }
  69. public void Initialize()
  70. {
  71. if (!Initialized)
  72. {
  73. Initialized = true;
  74. SelectDirectory(0);
  75. }
  76. }
  77. public void Deactivate() => ClearSceneList();
  78. public void Update()
  79. {
  80. if (Input.Control)
  81. {
  82. if (Input.GetKeyDown(MpsKey.SaveScene)) QuickSaveScene();
  83. else if (Input.GetKeyDown(MpsKey.LoadScene)) QuickLoadScene();
  84. }
  85. }
  86. public void DeleteDirectory()
  87. {
  88. if (Directory.Exists(CurrentScenesDirectory)) Directory.Delete(CurrentScenesDirectory, true);
  89. CurrentDirectoryList.RemoveAt(CurrentDirectoryIndex);
  90. CurrentDirectoryIndex = Mathf.Clamp(CurrentDirectoryIndex, 0, CurrentDirectoryList.Count - 1);
  91. UpdateSceneList();
  92. }
  93. public void OverwriteScene() => SaveScene(overwrite: true);
  94. public void ToggleKankyoMode()
  95. {
  96. KankyoMode = !KankyoMode;
  97. CurrentDirectoryIndex = 0;
  98. UpdateSceneList();
  99. }
  100. public void SaveScene(bool overwrite = false)
  101. {
  102. if (Busy) return;
  103. Busy = true;
  104. if (!Directory.Exists(CurrentScenesDirectory)) Directory.CreateDirectory(CurrentScenesDirectory);
  105. MeidoPhotoStudio.NotifyRawScreenshot += SaveScene;
  106. MeidoPhotoStudio.TakeScreenshot(new ScreenshotEventArgs() { InMemory = true });
  107. void SaveScene(object sender, ScreenshotEventArgs args)
  108. {
  109. MeidoPhotoStudio.NotifyRawScreenshot -= SaveScene;
  110. SaveSceneToFile(args.Screenshot, overwrite);
  111. }
  112. }
  113. public void SelectDirectory(int directoryIndex)
  114. {
  115. directoryIndex = Mathf.Clamp(directoryIndex, 0, CurrentDirectoryList.Count - 1);
  116. if (directoryIndex == CurrentDirectoryIndex) return;
  117. CurrentDirectoryIndex = directoryIndex;
  118. UpdateSceneList();
  119. }
  120. public void SelectScene(int sceneIndex)
  121. {
  122. CurrentSceneIndex = Mathf.Clamp(sceneIndex, 0, SceneList.Count - 1);
  123. CurrentScene.Preload();
  124. }
  125. public void AddDirectory(string directoryName)
  126. {
  127. directoryName = Utility.SanitizePathPortion(directoryName);
  128. if (!CurrentDirectoryList.Contains(directoryName, StringComparer.InvariantCultureIgnoreCase))
  129. {
  130. string finalPath = Path.Combine(CurrentBasePath, directoryName);
  131. string fullPath = Path.GetFullPath(finalPath);
  132. if (!fullPath.StartsWith(CurrentBasePath))
  133. {
  134. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  135. Utility.LogError($"Could not add directory to {baseDirectoryName}. Path is invalid: '{fullPath}'");
  136. return;
  137. }
  138. CurrentDirectoryList.Add(directoryName);
  139. Directory.CreateDirectory(finalPath);
  140. UpdateDirectoryList();
  141. CurrentDirectoryIndex = CurrentDirectoryList.IndexOf(directoryName);
  142. UpdateSceneList();
  143. }
  144. }
  145. public void Refresh()
  146. {
  147. if (!Directory.Exists(CurrentScenesDirectory)) CurrentDirectoryIndex = 0;
  148. if (KankyoMode) Constants.InitializeKankyoDirectories();
  149. else Constants.InitializeSceneDirectories();
  150. UpdateSceneList();
  151. }
  152. public void SortScenes(SortMode sortMode)
  153. {
  154. CurrentSortMode = sortMode;
  155. Comparison<MPSScene> comparator = CurrentSortMode switch
  156. {
  157. SortMode.DateModified => SortByDateModified,
  158. SortMode.DateCreated => SortByDateCreated,
  159. _ => SortByName,
  160. };
  161. SceneList.Sort(comparator);
  162. }
  163. public void DeleteScene()
  164. {
  165. if (CurrentScene.FileInfo.Exists)
  166. {
  167. CurrentScene.FileInfo.Delete();
  168. }
  169. SceneList.RemoveAt(CurrentSceneIndex);
  170. CurrentSceneIndex = Mathf.Clamp(CurrentSceneIndex, 0, SceneList.Count - 1);
  171. }
  172. public void LoadScene(MPSScene scene) => meidoPhotoStudio.LoadScene(scene.Data);
  173. private int SortByName(MPSScene a, MPSScene b)
  174. {
  175. return SortDirection * LexicographicStringComparer.Comparison(a.FileInfo.Name, b.FileInfo.Name);
  176. }
  177. private int SortByDateCreated(MPSScene a, MPSScene b)
  178. {
  179. return SortDirection * DateTime.Compare(a.FileInfo.CreationTime, b.FileInfo.CreationTime);
  180. }
  181. private int SortByDateModified(MPSScene a, MPSScene b)
  182. {
  183. return SortDirection * DateTime.Compare(a.FileInfo.LastWriteTime, b.FileInfo.LastWriteTime);
  184. }
  185. private void UpdateSceneList()
  186. {
  187. ClearSceneList();
  188. if (!Directory.Exists(CurrentScenesDirectory))
  189. {
  190. Directory.CreateDirectory(CurrentScenesDirectory);
  191. }
  192. foreach (string filename in Directory.GetFiles(CurrentScenesDirectory))
  193. {
  194. if (Path.GetExtension(filename) == ".png") SceneList.Add(new MPSScene(filename));
  195. }
  196. SortScenes(CurrentSortMode);
  197. CurrentSceneIndex = Mathf.Clamp(CurrentSceneIndex, 0, SceneList.Count - 1);
  198. }
  199. private void UpdateDirectoryList()
  200. {
  201. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  202. CurrentDirectoryList.Sort((a, b)
  203. => a.Equals(baseDirectoryName, StringComparison.InvariantCultureIgnoreCase)
  204. ? -1 : LexicographicStringComparer.Comparison(a, b));
  205. }
  206. private void ClearSceneList()
  207. {
  208. foreach (MPSScene scene in SceneList) scene.Destroy();
  209. SceneList.Clear();
  210. }
  211. private void QuickSaveScene()
  212. {
  213. if (Busy) return;
  214. var data = meidoPhotoStudio.SaveScene();
  215. if (data == null) return;
  216. tempSceneData = data;
  217. File.WriteAllBytes(TempScenePath, data);
  218. }
  219. private void QuickLoadScene()
  220. {
  221. if (Busy) return;
  222. if (tempSceneData == null)
  223. {
  224. if (File.Exists(TempScenePath)) tempSceneData = File.ReadAllBytes(TempScenePath);
  225. else return;
  226. }
  227. meidoPhotoStudio.LoadScene(tempSceneData);
  228. }
  229. private void SaveSceneToFile(Texture2D screenshot, bool overwrite = false)
  230. {
  231. Busy = true;
  232. byte[] sceneData = meidoPhotoStudio.SaveScene(KankyoMode);
  233. if (sceneData != null)
  234. {
  235. string scenePrefix = KankyoMode ? "mpskankyo" : "mpsscene";
  236. string fileName = $"{scenePrefix}{Utility.Timestamp}.png";
  237. string savePath = Path.Combine(CurrentScenesDirectory, fileName);
  238. Utility.ResizeToFit(screenshot, (int) sceneDimensions.x, (int) sceneDimensions.y);
  239. try
  240. {
  241. if (overwrite && CurrentScene?.FileInfo != null) savePath = CurrentScene.FileInfo.FullName;
  242. else overwrite = false;
  243. using (FileStream fileStream = File.Create(savePath))
  244. {
  245. byte[] encodedPng = screenshot.EncodeToPNG();
  246. fileStream.Write(encodedPng, 0, encodedPng.Length);
  247. fileStream.Write(sceneData, 0, sceneData.Length);
  248. }
  249. if (overwrite)
  250. {
  251. File.SetCreationTime(savePath, CurrentScene.FileInfo.CreationTime);
  252. CurrentScene.Destroy();
  253. SceneList.RemoveAt(CurrentSceneIndex);
  254. }
  255. }
  256. catch (Exception e)
  257. {
  258. Utility.LogError($"Failed to save scene to disk because {e.Message}\n{e.StackTrace}");
  259. Object.DestroyImmediate(screenshot);
  260. Busy = false;
  261. return;
  262. }
  263. SceneList.Add(new MPSScene(savePath, screenshot));
  264. SortScenes(CurrentSortMode);
  265. }
  266. else Object.DestroyImmediate(screenshot);
  267. Busy = false;
  268. }
  269. }
  270. }