SceneManager.cs 13 KB

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