MeidoPhotoStudio.cs 19 KB

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