MeidoPhotoStudio.cs 19 KB

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