SceneManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. internal class SceneManager : IManager
  11. {
  12. public static bool Busy { get; private set; }
  13. public bool Initialized { get; private set; }
  14. public static readonly Vector2 sceneDimensions = new Vector2(480, 270);
  15. private readonly MeidoPhotoStudio meidoPhotoStudio;
  16. private int SortDirection => SortDescending ? -1 : 1;
  17. public bool KankyoMode { get; set; }
  18. private static readonly ConfigEntry<bool> sortDescending;
  19. public bool SortDescending
  20. {
  21. get => sortDescending.Value;
  22. set => sortDescending.Value = value;
  23. }
  24. public List<Scene> SceneList { get; } = new List<Scene>();
  25. public int CurrentDirectoryIndex { get; private set; } = -1;
  26. public string CurrentDirectoryName => CurrentDirectoryList[CurrentDirectoryIndex];
  27. public List<string> CurrentDirectoryList
  28. => KankyoMode ? Constants.KankyoDirectoryList : Constants.SceneDirectoryList;
  29. public string CurrentBasePath => KankyoMode ? Constants.kankyoPath : Constants.scenesPath;
  30. public string CurrentScenesDirectory
  31. => CurrentDirectoryIndex == 0 ? CurrentBasePath : Path.Combine(CurrentBasePath, CurrentDirectoryName);
  32. private static readonly ConfigEntry<SortMode> currentSortMode;
  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. if (!Directory.Exists(CurrentScenesDirectory)) Directory.CreateDirectory(CurrentScenesDirectory);
  101. meidoPhotoStudio.StartCoroutine(SaveSceneToFile(overwrite));
  102. }
  103. public void SelectDirectory(int directoryIndex)
  104. {
  105. directoryIndex = Mathf.Clamp(directoryIndex, 0, CurrentDirectoryList.Count - 1);
  106. if (directoryIndex == CurrentDirectoryIndex) return;
  107. CurrentDirectoryIndex = directoryIndex;
  108. UpdateSceneList();
  109. }
  110. public void SelectScene(int sceneIndex)
  111. {
  112. CurrentSceneIndex = Mathf.Clamp(sceneIndex, 0, SceneList.Count - 1);
  113. CurrentScene.GetNumberOfMaids();
  114. }
  115. public void AddDirectory(string directoryName)
  116. {
  117. directoryName = Utility.SanitizePathPortion(directoryName);
  118. if (!CurrentDirectoryList.Contains(directoryName, StringComparer.InvariantCultureIgnoreCase))
  119. {
  120. string finalPath = Path.Combine(CurrentBasePath, directoryName);
  121. string fullPath = Path.GetFullPath(finalPath);
  122. if (!fullPath.StartsWith(CurrentBasePath))
  123. {
  124. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  125. Utility.LogError($"Could not add directory to {baseDirectoryName}. Path is invalid: '{fullPath}'");
  126. return;
  127. }
  128. CurrentDirectoryList.Add(directoryName);
  129. Directory.CreateDirectory(finalPath);
  130. UpdateDirectoryList();
  131. CurrentDirectoryIndex = CurrentDirectoryList.IndexOf(directoryName);
  132. UpdateSceneList();
  133. }
  134. }
  135. public void Refresh()
  136. {
  137. if (!Directory.Exists(CurrentScenesDirectory)) CurrentDirectoryIndex = 0;
  138. Constants.InitializeScenes();
  139. UpdateSceneList();
  140. }
  141. public void SortScenes(SortMode sortMode)
  142. {
  143. CurrentSortMode = sortMode;
  144. Comparison<Scene> comparator;
  145. switch (CurrentSortMode)
  146. {
  147. case SortMode.DateModified: comparator = SortByDateModified; break;
  148. case SortMode.DateCreated: comparator = SortByDateCreated; break;
  149. default: comparator = SortByName; break;
  150. }
  151. SceneList.Sort(comparator);
  152. }
  153. public void DeleteScene()
  154. {
  155. if (CurrentScene.FileInfo.Exists)
  156. {
  157. CurrentScene.FileInfo.Delete();
  158. }
  159. SceneList.RemoveAt(CurrentSceneIndex);
  160. CurrentSceneIndex = Mathf.Clamp(CurrentSceneIndex, 0, SceneList.Count - 1);
  161. }
  162. public void LoadScene()
  163. {
  164. meidoPhotoStudio.ApplyScene(CurrentScene.FileInfo.FullName);
  165. }
  166. private int SortByName(Scene a, Scene b)
  167. {
  168. return SortDirection * LexicographicStringComparer.Comparison(a.FileInfo.Name, b.FileInfo.Name);
  169. }
  170. private int SortByDateCreated(Scene a, Scene b)
  171. {
  172. return SortDirection * DateTime.Compare(a.FileInfo.CreationTime, b.FileInfo.CreationTime);
  173. }
  174. private int SortByDateModified(Scene a, Scene b)
  175. {
  176. return SortDirection * DateTime.Compare(a.FileInfo.LastWriteTime, b.FileInfo.LastWriteTime);
  177. }
  178. private void UpdateSceneList()
  179. {
  180. ClearSceneList();
  181. if (!Directory.Exists(CurrentScenesDirectory))
  182. {
  183. Directory.CreateDirectory(CurrentScenesDirectory);
  184. }
  185. foreach (string filename in Directory.GetFiles(CurrentScenesDirectory))
  186. {
  187. if (Path.GetExtension(filename) == ".png") SceneList.Add(new Scene(filename));
  188. }
  189. SortScenes(CurrentSortMode);
  190. CurrentSceneIndex = Mathf.Clamp(CurrentSceneIndex, 0, SceneList.Count - 1);
  191. }
  192. private void UpdateDirectoryList()
  193. {
  194. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  195. CurrentDirectoryList.Sort((a, b)
  196. => a.Equals(baseDirectoryName, StringComparison.InvariantCultureIgnoreCase) ? -1 : a.CompareTo(b));
  197. }
  198. private void ClearSceneList()
  199. {
  200. foreach (Scene scene in SceneList) scene.Destroy();
  201. SceneList.Clear();
  202. }
  203. private void QuickSaveScene()
  204. {
  205. if (Busy) return;
  206. byte[] data = meidoPhotoStudio.SerializeScene(kankyo: false);
  207. if (data == null) return;
  208. File.WriteAllBytes(Path.Combine(Constants.configPath, "mpstempscene"), data);
  209. }
  210. private void QuickLoadScene()
  211. {
  212. if (Busy) return;
  213. meidoPhotoStudio.ApplyScene(Path.Combine(Constants.configPath, "mpstempscene"));
  214. }
  215. private System.Collections.IEnumerator SaveSceneToFile(bool overwrite = false)
  216. {
  217. Busy = true;
  218. byte[] sceneData = meidoPhotoStudio.SerializeScene(KankyoMode);
  219. if (sceneData != null)
  220. {
  221. string screenshotPath = Utility.TempScreenshotFilename();
  222. MeidoPhotoStudio.TakeScreenshot(screenshotPath, 1, KankyoMode);
  223. do yield return new WaitForSecondsRealtime(0.2f);
  224. while (!File.Exists(screenshotPath));
  225. string scenePrefix = KankyoMode ? "mpskankyo" : "mpsscene";
  226. string fileName = $"{scenePrefix}{Utility.Timestamp}.png";
  227. string savePath = Path.Combine(CurrentScenesDirectory, fileName);
  228. if (overwrite && CurrentScene != null)
  229. {
  230. savePath = CurrentScene.FileInfo.FullName;
  231. }
  232. else overwrite = false;
  233. Texture2D screenshot = new Texture2D(1, 1, TextureFormat.ARGB32, false);
  234. screenshot.LoadImage(File.ReadAllBytes(screenshotPath));
  235. int sceneWidth = (int)sceneDimensions.x;
  236. int sceneHeight = (int)sceneDimensions.y;
  237. Utility.ResizeToFit(screenshot, sceneWidth, sceneHeight);
  238. using (FileStream fileStream = File.Create(savePath))
  239. {
  240. byte[] encodedPng = screenshot.EncodeToPNG();
  241. fileStream.Write(encodedPng, 0, encodedPng.Length);
  242. fileStream.Write(sceneData, 0, sceneData.Length);
  243. }
  244. UnityEngine.Object.DestroyImmediate(screenshot);
  245. if (overwrite)
  246. {
  247. File.SetCreationTime(savePath, CurrentScene.FileInfo.CreationTime);
  248. CurrentScene.Destroy();
  249. SceneList.RemoveAt(CurrentSceneIndex);
  250. }
  251. SceneList.Add(new Scene(savePath));
  252. SortScenes(CurrentSortMode);
  253. }
  254. Busy = false;
  255. }
  256. public class Scene
  257. {
  258. public const int initialNumberOfMaids = -2;
  259. public Texture2D Thumbnail { get; }
  260. public FileInfo FileInfo { get; set; }
  261. public int NumberOfMaids { get; private set; } = initialNumberOfMaids;
  262. public Scene(string filePath)
  263. {
  264. FileInfo = new FileInfo(filePath);
  265. Thumbnail = new Texture2D(1, 1, TextureFormat.ARGB32, false);
  266. Thumbnail.LoadImage(File.ReadAllBytes(FileInfo.FullName));
  267. }
  268. public void GetNumberOfMaids()
  269. {
  270. if (NumberOfMaids != initialNumberOfMaids) return;
  271. string filePath = FileInfo.FullName;
  272. byte[] sceneData = MeidoPhotoStudio.DecompressScene(filePath);
  273. if (sceneData == null) return;
  274. using (MemoryStream memoryStream = new MemoryStream(sceneData))
  275. using (BinaryReader binaryReader = new BinaryReader(memoryStream, System.Text.Encoding.UTF8))
  276. {
  277. try
  278. {
  279. if (binaryReader.ReadString() != "MPS_SCENE")
  280. {
  281. Utility.LogWarning($"'{filePath}' is not a {MeidoPhotoStudio.pluginName} scene");
  282. return;
  283. }
  284. if (binaryReader.ReadInt32() > MeidoPhotoStudio.sceneVersion)
  285. {
  286. Utility.LogWarning(
  287. $"'{filePath}' is made in a newer version of {MeidoPhotoStudio.pluginName}"
  288. );
  289. return;
  290. }
  291. NumberOfMaids = binaryReader.ReadInt32();
  292. }
  293. catch (Exception e)
  294. {
  295. Utility.LogWarning($"Failed to deserialize scene '{filePath}' because {e.Message}");
  296. return;
  297. }
  298. }
  299. }
  300. public void Destroy()
  301. {
  302. if (Thumbnail != null) UnityEngine.Object.DestroyImmediate(Thumbnail);
  303. }
  304. }
  305. }
  306. }