MeidoPhotoStudio.cs 19 KB

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