SceneManager.cs 10 KB

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