SceneManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 System.Text;
  8. namespace COM3D2.MeidoPhotoStudio.Plugin
  9. {
  10. using Input = InputManager;
  11. public class SceneManager : IManager
  12. {
  13. public static bool Busy { get; private set; }
  14. public static readonly Vector2 sceneDimensions = new Vector2(480, 270);
  15. private static readonly ConfigEntry<bool> sortDescending;
  16. private static readonly ConfigEntry<SortMode> currentSortMode;
  17. private readonly MeidoPhotoStudio meidoPhotoStudio;
  18. private int SortDirection => SortDescending ? -1 : 1;
  19. public bool Initialized { get; private set; }
  20. public bool KankyoMode { get; set; }
  21. public bool SortDescending
  22. {
  23. get => sortDescending.Value;
  24. set => sortDescending.Value = value;
  25. }
  26. public List<Scene> SceneList { get; } = new List<Scene>();
  27. public int CurrentDirectoryIndex { get; private set; } = -1;
  28. public string CurrentDirectoryName => CurrentDirectoryList[CurrentDirectoryIndex];
  29. public List<string> CurrentDirectoryList
  30. => KankyoMode ? Constants.KankyoDirectoryList : Constants.SceneDirectoryList;
  31. public string CurrentBasePath => KankyoMode ? Constants.kankyoPath : Constants.scenesPath;
  32. public string CurrentScenesDirectory
  33. => CurrentDirectoryIndex == 0 ? CurrentBasePath : Path.Combine(CurrentBasePath, CurrentDirectoryName);
  34. public SortMode CurrentSortMode
  35. {
  36. get => currentSortMode.Value;
  37. private set => currentSortMode.Value = value;
  38. }
  39. public int CurrentSceneIndex { get; private set; } = -1;
  40. public Scene CurrentScene => SceneList.Count == 0 ? null : SceneList[CurrentSceneIndex];
  41. public enum SortMode
  42. {
  43. Name, DateCreated, DateModified
  44. }
  45. static SceneManager()
  46. {
  47. sortDescending = Configuration.Config.Bind(
  48. "SceneManager", "SortDescending",
  49. false,
  50. "Sort scenes descending (Z-A)"
  51. );
  52. currentSortMode = Configuration.Config.Bind(
  53. "SceneManager", "SortMode",
  54. SortMode.Name,
  55. "Scene sorting mode"
  56. );
  57. Input.Register(MpsKey.OpenSceneManager, KeyCode.F8, "Hide/show scene manager");
  58. Input.Register(MpsKey.SaveScene, KeyCode.S, "Quick save scene");
  59. Input.Register(MpsKey.LoadScene, KeyCode.A, "Load quick saved scene");
  60. }
  61. public SceneManager(MeidoPhotoStudio meidoPhotoStudio)
  62. {
  63. this.meidoPhotoStudio = meidoPhotoStudio;
  64. Activate();
  65. }
  66. public void Activate() { }
  67. public void Initialize()
  68. {
  69. if (!Initialized)
  70. {
  71. Initialized = true;
  72. SelectDirectory(0);
  73. }
  74. }
  75. public void Deactivate() => ClearSceneList();
  76. public void Update()
  77. {
  78. if (Input.Control)
  79. {
  80. if (Input.GetKeyDown(MpsKey.SaveScene)) QuickSaveScene();
  81. else if (Input.GetKeyDown(MpsKey.LoadScene)) QuickLoadScene();
  82. }
  83. }
  84. public void DeleteDirectory()
  85. {
  86. if (Directory.Exists(CurrentScenesDirectory)) Directory.Delete(CurrentScenesDirectory, true);
  87. CurrentDirectoryList.RemoveAt(CurrentDirectoryIndex);
  88. CurrentDirectoryIndex = Mathf.Clamp(CurrentDirectoryIndex, 0, CurrentDirectoryList.Count - 1);
  89. UpdateSceneList();
  90. }
  91. public void OverwriteScene() => SaveScene(overwrite: true);
  92. public void ToggleKankyoMode()
  93. {
  94. KankyoMode = !KankyoMode;
  95. CurrentDirectoryIndex = 0;
  96. UpdateSceneList();
  97. }
  98. public void SaveScene(bool overwrite = false)
  99. {
  100. if (Busy) return;
  101. Busy = true;
  102. if (!Directory.Exists(CurrentScenesDirectory)) Directory.CreateDirectory(CurrentScenesDirectory);
  103. MeidoPhotoStudio.NotifyRawScreenshot += SaveScene;
  104. MeidoPhotoStudio.TakeScreenshot(new ScreenshotEventArgs() { InMemory = true });
  105. void SaveScene(object sender, ScreenshotEventArgs args)
  106. {
  107. MeidoPhotoStudio.NotifyRawScreenshot -= SaveScene;
  108. SaveSceneToFile(args.Screenshot, overwrite);
  109. }
  110. }
  111. public void SelectDirectory(int directoryIndex)
  112. {
  113. directoryIndex = Mathf.Clamp(directoryIndex, 0, CurrentDirectoryList.Count - 1);
  114. if (directoryIndex == CurrentDirectoryIndex) return;
  115. CurrentDirectoryIndex = directoryIndex;
  116. UpdateSceneList();
  117. }
  118. public void SelectScene(int sceneIndex)
  119. {
  120. CurrentSceneIndex = Mathf.Clamp(sceneIndex, 0, SceneList.Count - 1);
  121. CurrentScene.GetNumberOfMaids();
  122. }
  123. public void AddDirectory(string directoryName)
  124. {
  125. directoryName = Utility.SanitizePathPortion(directoryName);
  126. if (!CurrentDirectoryList.Contains(directoryName, StringComparer.InvariantCultureIgnoreCase))
  127. {
  128. string finalPath = Path.Combine(CurrentBasePath, directoryName);
  129. string fullPath = Path.GetFullPath(finalPath);
  130. if (!fullPath.StartsWith(CurrentBasePath))
  131. {
  132. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  133. Utility.LogError($"Could not add directory to {baseDirectoryName}. Path is invalid: '{fullPath}'");
  134. return;
  135. }
  136. CurrentDirectoryList.Add(directoryName);
  137. Directory.CreateDirectory(finalPath);
  138. UpdateDirectoryList();
  139. CurrentDirectoryIndex = CurrentDirectoryList.IndexOf(directoryName);
  140. UpdateSceneList();
  141. }
  142. }
  143. public void Refresh()
  144. {
  145. if (!Directory.Exists(CurrentScenesDirectory)) CurrentDirectoryIndex = 0;
  146. if (KankyoMode) Constants.InitializeKankyoDirectories();
  147. else Constants.InitializeSceneDirectories();
  148. UpdateSceneList();
  149. }
  150. public void SortScenes(SortMode sortMode)
  151. {
  152. CurrentSortMode = sortMode;
  153. Comparison<Scene> comparator = CurrentSortMode switch
  154. {
  155. SortMode.DateModified => SortByDateModified,
  156. SortMode.DateCreated => SortByDateCreated,
  157. _ => SortByName,
  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 BinaryReader binaryReader = new BinaryReader(new MemoryStream(sceneData), Encoding.UTF8);
  272. try
  273. {
  274. if (binaryReader.ReadString() != "MPS_SCENE")
  275. {
  276. Utility.LogWarning($"'{filePath}' is not a {MeidoPhotoStudio.pluginName} scene");
  277. return;
  278. }
  279. if (binaryReader.ReadInt32() > MeidoPhotoStudio.sceneVersion)
  280. {
  281. Utility.LogWarning(
  282. $"'{filePath}' is made in a newer version of {MeidoPhotoStudio.pluginName}"
  283. );
  284. return;
  285. }
  286. NumberOfMaids = binaryReader.ReadInt32();
  287. }
  288. catch (Exception e)
  289. {
  290. Utility.LogWarning($"Failed to deserialize scene '{filePath}' because {e.Message}");
  291. }
  292. }
  293. public void Destroy()
  294. {
  295. if (Thumbnail != null) UnityEngine.Object.DestroyImmediate(Thumbnail);
  296. }
  297. }
  298. }
  299. }