MeidoPhotoStudio.cs 18 KB

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