SceneManager.cs 13 KB

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