SceneManager.cs 12 KB

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