MeidoPhotoStudio.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.SceneManagement;
  7. using Ionic.Zlib;
  8. using BepInEx;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. [BepInPlugin(pluginGuid, pluginName, pluginVersion)]
  12. public class MeidoPhotoStudio : BaseUnityPlugin
  13. {
  14. private static CameraMain mainCamera = GameMain.Instance.MainCamera;
  15. private static event EventHandler<ScreenshotEventArgs> ScreenshotEvent;
  16. private const string pluginGuid = "com.habeebweeb.com3d2.meidophotostudio";
  17. public const string pluginName = "MeidoPhotoStudio";
  18. public const string pluginVersion = "0.0.0";
  19. public const int sceneVersion = 1100;
  20. public const int kankyoMagic = -765;
  21. public static string pluginString = $"{pluginName} {pluginVersion}";
  22. private WindowManager windowManager;
  23. private SceneManager sceneManager;
  24. private MeidoManager meidoManager;
  25. private EnvironmentManager environmentManager;
  26. private MessageWindowManager messageWindowManager;
  27. private LightManager lightManager;
  28. private PropManager propManager;
  29. private EffectManager effectManager;
  30. private Constants.Scene currentScene;
  31. private bool initialized = false;
  32. private bool active = false;
  33. private bool uiActive = false;
  34. private void Awake()
  35. {
  36. ScreenshotEvent += OnScreenshotEvent;
  37. DontDestroyOnLoad(this);
  38. }
  39. private void Start()
  40. {
  41. Constants.Initialize();
  42. Translation.Initialize(Configuration.CurrentLanguage);
  43. UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
  44. }
  45. public byte[] SerializeScene(bool kankyo = false)
  46. {
  47. if (meidoManager.Busy) return null;
  48. byte[] compressedData;
  49. using (MemoryStream memoryStream = new MemoryStream())
  50. using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
  51. using (BinaryWriter binaryWriter = new BinaryWriter(deflateStream, System.Text.Encoding.UTF8))
  52. {
  53. binaryWriter.Write("MPS_SCENE");
  54. binaryWriter.Write(sceneVersion);
  55. binaryWriter.Write(kankyo ? kankyoMagic : meidoManager.ActiveMeidoList.Count);
  56. effectManager.Serialize(binaryWriter);
  57. environmentManager.Serialize(binaryWriter, kankyo);
  58. lightManager.Serialize(binaryWriter);
  59. if (!kankyo)
  60. {
  61. messageWindowManager.Serialize(binaryWriter);
  62. // meidomanager has to be serialized before propmanager because reattached props will be in the
  63. // wrong place after a maid's pose is deserialized.
  64. meidoManager.Serialize(binaryWriter);
  65. }
  66. propManager.Serialize(binaryWriter);
  67. binaryWriter.Write("END");
  68. deflateStream.Close();
  69. compressedData = memoryStream.ToArray();
  70. }
  71. return compressedData;
  72. }
  73. public static byte[] DecompressScene(string filePath)
  74. {
  75. if (!File.Exists(filePath))
  76. {
  77. Utility.LogWarning($"Scene file '{filePath}' does not exist.");
  78. return null;
  79. }
  80. byte[] compressedData;
  81. using (FileStream fileStream = File.OpenRead(filePath))
  82. {
  83. if (Utility.IsPngFile(fileStream))
  84. {
  85. if (!Utility.SeekPngEnd(fileStream))
  86. {
  87. Utility.LogWarning($"'{filePath}' is not a PNG file");
  88. return null;
  89. }
  90. if (fileStream.Position == fileStream.Length)
  91. {
  92. Utility.LogWarning($"'{filePath}' contains no scene data");
  93. return null;
  94. }
  95. int dataLength = (int)(fileStream.Length - fileStream.Position);
  96. compressedData = new byte[dataLength];
  97. fileStream.Read(compressedData, 0, dataLength);
  98. }
  99. else
  100. {
  101. compressedData = new byte[fileStream.Length];
  102. fileStream.Read(compressedData, 0, compressedData.Length);
  103. }
  104. }
  105. return DeflateStream.UncompressBuffer(compressedData);
  106. }
  107. public void ApplyScene(string filePath)
  108. {
  109. if (meidoManager.Busy) return;
  110. byte[] sceneBinary = DecompressScene(filePath);
  111. if (sceneBinary == null) return;
  112. using (MemoryStream memoryStream = new MemoryStream(sceneBinary))
  113. using (BinaryReader binaryReader = new BinaryReader(memoryStream, System.Text.Encoding.UTF8))
  114. {
  115. try
  116. {
  117. if (binaryReader.ReadString() != "MPS_SCENE")
  118. {
  119. Utility.LogWarning($"'{filePath}' is not a {pluginName} scene");
  120. return;
  121. }
  122. if (binaryReader.ReadInt32() > sceneVersion)
  123. {
  124. Utility.LogWarning($"'{filePath}' is made in a newer version of {pluginName}");
  125. return;
  126. }
  127. binaryReader.ReadInt32(); // Number of Maids
  128. string previousHeader = string.Empty;
  129. string header;
  130. while ((header = binaryReader.ReadString()) != "END")
  131. {
  132. switch (header)
  133. {
  134. case MessageWindowManager.header:
  135. messageWindowManager.Deserialize(binaryReader);
  136. break;
  137. case EnvironmentManager.header:
  138. environmentManager.Deserialize(binaryReader);
  139. break;
  140. case MeidoManager.header:
  141. meidoManager.Deserialize(binaryReader);
  142. break;
  143. case PropManager.header:
  144. propManager.Deserialize(binaryReader);
  145. break;
  146. case LightManager.header:
  147. lightManager.Deserialize(binaryReader);
  148. break;
  149. case EffectManager.header:
  150. effectManager.Deserialize(binaryReader);
  151. break;
  152. default: throw new Exception($"Unknown header '{header}'. Last {previousHeader}");
  153. }
  154. previousHeader = header;
  155. }
  156. }
  157. catch (Exception e)
  158. {
  159. Utility.LogError($"Failed to deserialize scene '{filePath}' because {e.Message}");
  160. return;
  161. }
  162. }
  163. }
  164. public static void TakeScreenshot(ScreenshotEventArgs args) => ScreenshotEvent?.Invoke(null, args);
  165. public static void TakeScreenshot(string path = "", int superSize = -1, bool hideMaids = false)
  166. {
  167. TakeScreenshot(new ScreenshotEventArgs() { Path = path, SuperSize = superSize, HideMaids = hideMaids });
  168. }
  169. private void OnScreenshotEvent(object sender, ScreenshotEventArgs args)
  170. {
  171. StartCoroutine(Screenshot(args));
  172. }
  173. private void Update()
  174. {
  175. if (currentScene == Constants.Scene.Daily)
  176. {
  177. if (Input.GetKeyDown(KeyCode.F6))
  178. {
  179. if (active) Deactivate();
  180. else Activate();
  181. }
  182. if (active)
  183. {
  184. if (!Input.GetKey(KeyCode.Q) && !Utility.GetModKey(Utility.ModKey.Control)
  185. && Input.GetKeyDown(KeyCode.S)
  186. ) TakeScreenshot();
  187. meidoManager.Update();
  188. environmentManager.Update();
  189. windowManager.Update();
  190. effectManager.Update();
  191. sceneManager.Update();
  192. }
  193. }
  194. }
  195. private IEnumerator Screenshot(ScreenshotEventArgs args)
  196. {
  197. // Hide UI and dragpoints
  198. GameObject editUI = GameObject.Find("/UI Root/Camera");
  199. GameObject fpsViewer =
  200. UTY.GetChildObject(GameMain.Instance.gameObject, "SystemUI Root/FpsCounter", false);
  201. GameObject sysDialog =
  202. UTY.GetChildObject(GameMain.Instance.gameObject, "SystemUI Root/SystemDialog", false);
  203. GameObject sysShortcut =
  204. UTY.GetChildObject(GameMain.Instance.gameObject, "SystemUI Root/SystemShortcut", false);
  205. editUI.SetActive(false);
  206. fpsViewer.SetActive(false);
  207. sysDialog.SetActive(false);
  208. sysShortcut.SetActive(false);
  209. uiActive = false;
  210. // TODO: Hide cubes for bg, maid, lights etc.
  211. List<Meido> activeMeidoList = this.meidoManager.ActiveMeidoList;
  212. bool[] isIK = new bool[activeMeidoList.Count];
  213. bool[] isVisible = new bool[activeMeidoList.Count];
  214. for (int i = 0; i < activeMeidoList.Count; i++)
  215. {
  216. Meido meido = activeMeidoList[i];
  217. isIK[i] = meido.IK;
  218. isVisible[i] = meido.Maid.Visible;
  219. if (meido.IK) meido.IK = false;
  220. if (args.HideMaids) meido.Maid.Visible = false;
  221. }
  222. GizmoRender.UIVisible = false;
  223. yield return new WaitForEndOfFrame();
  224. // Take Screenshot
  225. int[] defaultSuperSize = new[] { 1, 2, 4 };
  226. int selectedSuperSize = args.SuperSize < 1
  227. ? defaultSuperSize[(int)GameMain.Instance.CMSystem.ScreenShotSuperSize]
  228. : args.SuperSize;
  229. string path = string.IsNullOrEmpty(args.Path)
  230. ? Utility.ScreenshotFilename()
  231. : args.Path;
  232. Application.CaptureScreenshot(path, selectedSuperSize);
  233. GameMain.Instance.SoundMgr.PlaySe("se022.ogg", false);
  234. yield return new WaitForEndOfFrame();
  235. // Show UI and dragpoints
  236. uiActive = true;
  237. editUI.SetActive(true);
  238. fpsViewer.SetActive(GameMain.Instance.CMSystem.ViewFps);
  239. sysDialog.SetActive(true);
  240. sysShortcut.SetActive(true);
  241. for (int i = 0; i < activeMeidoList.Count; i++)
  242. {
  243. Meido meido = activeMeidoList[i];
  244. if (isIK[i]) meido.IK = true;
  245. if (args.HideMaids && isVisible[i]) meido.Maid.Visible = true;
  246. }
  247. GizmoRender.UIVisible = true;
  248. }
  249. private void OnGUI()
  250. {
  251. if (uiActive)
  252. {
  253. windowManager.DrawWindows();
  254. if (DropdownHelper.Visible) DropdownHelper.HandleDropdown();
  255. if (Modal.Visible) Modal.Draw();
  256. }
  257. }
  258. private void OnSceneLoaded(Scene scene, LoadSceneMode sceneMode)
  259. {
  260. currentScene = (Constants.Scene)scene.buildIndex;
  261. if (active) Deactivate();
  262. ResetCalcNearClip();
  263. }
  264. private void Initialize()
  265. {
  266. if (initialized) return;
  267. initialized = true;
  268. meidoManager = new MeidoManager();
  269. environmentManager = new EnvironmentManager(meidoManager);
  270. messageWindowManager = new MessageWindowManager();
  271. lightManager = new LightManager();
  272. propManager = new PropManager(meidoManager);
  273. effectManager = new EffectManager();
  274. sceneManager = new SceneManager(this);
  275. MaidSwitcherPane maidSwitcherPane = new MaidSwitcherPane(meidoManager);
  276. SceneWindow sceneWindow = new SceneWindow(sceneManager);
  277. windowManager = new WindowManager()
  278. {
  279. [Constants.Window.Main] = new MainWindow(meidoManager)
  280. {
  281. [Constants.Window.Call] = new CallWindowPane(meidoManager),
  282. [Constants.Window.Pose] = new PoseWindowPane(meidoManager, maidSwitcherPane),
  283. [Constants.Window.Face] = new FaceWindowPane(meidoManager, maidSwitcherPane),
  284. [Constants.Window.BG] = new BGWindowPane(
  285. environmentManager, lightManager, effectManager, sceneWindow
  286. ),
  287. [Constants.Window.BG2] = new BG2WindowPane(meidoManager, propManager)
  288. },
  289. [Constants.Window.Message] = new MessageWindow(messageWindowManager),
  290. [Constants.Window.Save] = sceneWindow
  291. };
  292. meidoManager.BeginCallMeidos += (s, a) => uiActive = false;
  293. meidoManager.EndCallMeidos += (s, a) => uiActive = true;
  294. }
  295. private void Activate()
  296. {
  297. if (!initialized) Initialize();
  298. SetNearClipPlane();
  299. uiActive = true;
  300. active = true;
  301. meidoManager.Activate();
  302. environmentManager.Activate();
  303. propManager.Activate();
  304. lightManager.Activate();
  305. effectManager.Activate();
  306. windowManager.Activate();
  307. messageWindowManager.Activate();
  308. GameObject dailyPanel = GameObject.Find("UI Root").transform.Find("DailyPanel").gameObject;
  309. dailyPanel.SetActive(false);
  310. }
  311. private void Deactivate()
  312. {
  313. if (meidoManager.Busy || SceneManager.Busy) return;
  314. ResetCalcNearClip();
  315. uiActive = false;
  316. active = false;
  317. meidoManager.Deactivate();
  318. environmentManager.Deactivate();
  319. propManager.Deactivate();
  320. lightManager.Deactivate();
  321. effectManager.Deactivate();
  322. messageWindowManager.Deactivate();
  323. windowManager.Deactivate();
  324. Modal.Close();
  325. GameObject dailyPanel = GameObject.Find("UI Root")?.transform.Find("DailyPanel")?.gameObject;
  326. dailyPanel?.SetActive(true);
  327. }
  328. private void SetNearClipPlane()
  329. {
  330. mainCamera.StopAllCoroutines();
  331. mainCamera.m_bCalcNearClip = false;
  332. mainCamera.camera.nearClipPlane = 0.01f;
  333. }
  334. private void ResetCalcNearClip()
  335. {
  336. if (mainCamera.m_bCalcNearClip) return;
  337. mainCamera.StopAllCoroutines();
  338. mainCamera.m_bCalcNearClip = true;
  339. mainCamera.Start();
  340. }
  341. }
  342. public class ScreenshotEventArgs : EventArgs
  343. {
  344. public string Path { get; set; } = string.Empty;
  345. public int SuperSize { get; set; } = -1;
  346. public bool HideMaids { get; set; } = false;
  347. }
  348. }