PropManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. using UnityEngine.Rendering;
  7. using BepInEx.Configuration;
  8. namespace COM3D2.MeidoPhotoStudio.Plugin
  9. {
  10. using static MenuFileUtility;
  11. internal class PropManager : IManager, ISerializable
  12. {
  13. public const string header = "PROP";
  14. private static readonly ConfigEntry<bool> modItemsOnly;
  15. public static bool ModItemsOnly => modItemsOnly.Value;
  16. private MeidoManager meidoManager;
  17. private static bool cubeActive = true;
  18. public static bool CubeActive
  19. {
  20. get => cubeActive;
  21. set
  22. {
  23. if (value != cubeActive)
  24. {
  25. cubeActive = value;
  26. CubeActiveChange?.Invoke(null, EventArgs.Empty);
  27. }
  28. }
  29. }
  30. private static bool cubeSmall;
  31. public static bool CubeSmall
  32. {
  33. get => cubeSmall;
  34. set
  35. {
  36. if (value != cubeSmall)
  37. {
  38. cubeSmall = value;
  39. CubeSmallChange?.Invoke(null, EventArgs.Empty);
  40. }
  41. }
  42. }
  43. private static event EventHandler CubeActiveChange;
  44. private static event EventHandler CubeSmallChange;
  45. private List<DragPointDogu> doguList = new List<DragPointDogu>();
  46. public int DoguCount => doguList.Count;
  47. public event EventHandler DoguListChange;
  48. public event EventHandler DoguSelectChange;
  49. public string[] PropNameList
  50. {
  51. get
  52. {
  53. return doguList.Count == 0
  54. ? new[] { Translation.Get("systemMessage", "noProps") }
  55. : doguList.Select(dogu => dogu.Name).ToArray();
  56. }
  57. }
  58. public int CurrentDoguIndex { get; private set; } = 0;
  59. public DragPointDogu CurrentDogu => DoguCount == 0 ? null : doguList[CurrentDoguIndex];
  60. static PropManager()
  61. {
  62. modItemsOnly = Configuration.Config.Bind<bool>(
  63. "Prop", "ModItemsOnly",
  64. false,
  65. "Disable waiting for and loading base game clothing"
  66. );
  67. }
  68. public PropManager(MeidoManager meidoManager)
  69. {
  70. this.meidoManager = meidoManager;
  71. this.meidoManager.BeginCallMeidos += DetachProps;
  72. this.meidoManager.EndCallMeidos += OnEndCall;
  73. }
  74. public void Serialize(BinaryWriter binaryWriter)
  75. {
  76. binaryWriter.Write(header);
  77. binaryWriter.Write(doguList.Count);
  78. foreach (DragPointDogu dogu in doguList)
  79. {
  80. binaryWriter.Write(dogu.assetName);
  81. AttachPointInfo info = dogu.attachPointInfo;
  82. info.Serialize(binaryWriter);
  83. binaryWriter.WriteVector3(dogu.MyObject.position);
  84. binaryWriter.WriteQuaternion(dogu.MyObject.rotation);
  85. binaryWriter.WriteVector3(dogu.MyObject.localScale);
  86. }
  87. }
  88. public void Deserialize(BinaryReader binaryReader)
  89. {
  90. Dictionary<string, string> modToModPath = null;
  91. ClearDogu();
  92. int numberOfProps = binaryReader.ReadInt32();
  93. for (int i = 0; i < numberOfProps; i++)
  94. {
  95. string assetName = binaryReader.ReadString();
  96. bool result = false;
  97. if (assetName.EndsWith(".menu") && assetName.Contains('#') && modToModPath == null)
  98. {
  99. modToModPath = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
  100. foreach (string mod in Menu.GetModFiles()) modToModPath.Add(Path.GetFileName(mod), mod);
  101. }
  102. result = SpawnFromAssetString(assetName, modToModPath);
  103. AttachPointInfo info = AttachPointInfo.Deserialize(binaryReader);
  104. Vector3 position = binaryReader.ReadVector3();
  105. Quaternion rotation = binaryReader.ReadQuaternion();
  106. Vector3 scale = binaryReader.ReadVector3();
  107. if (result)
  108. {
  109. DragPointDogu dogu = doguList[i];
  110. Transform obj = dogu.MyObject;
  111. obj.position = position;
  112. obj.rotation = rotation;
  113. obj.localScale = scale;
  114. dogu.attachPointInfo = info;
  115. }
  116. }
  117. CurrentDoguIndex = 0;
  118. GameMain.Instance.StartCoroutine(DeserializeAttach());
  119. }
  120. private System.Collections.IEnumerator DeserializeAttach()
  121. {
  122. yield return new WaitForEndOfFrame();
  123. foreach (DragPointDogu dogu in doguList)
  124. {
  125. AttachPointInfo info = dogu.attachPointInfo;
  126. if (info.AttachPoint != AttachPoint.None)
  127. {
  128. Meido parent = meidoManager.GetMeido(info.MaidIndex);
  129. if (parent != null)
  130. {
  131. Transform obj = dogu.MyObject;
  132. Vector3 position = obj.position;
  133. Vector3 scale = obj.localScale;
  134. Quaternion rotation = obj.rotation;
  135. Transform point = parent.IKManager.GetAttachPointTransform(info.AttachPoint);
  136. dogu.MyObject.SetParent(point, true);
  137. info = new AttachPointInfo(
  138. info.AttachPoint,
  139. parent.Maid.status.guid,
  140. parent.Slot
  141. );
  142. obj.position = position;
  143. obj.localScale = scale;
  144. obj.rotation = rotation;
  145. }
  146. }
  147. }
  148. }
  149. public void Activate()
  150. {
  151. CubeSmallChange += OnCubeSmall;
  152. }
  153. public void Deactivate()
  154. {
  155. ClearDogu();
  156. CubeSmallChange -= OnCubeSmall;
  157. }
  158. public void Update() { }
  159. private GameObject GetDeploymentObject()
  160. {
  161. return GameObject.Find("Deployment Object Parent")
  162. ?? new GameObject("Deployment Object Parent");
  163. }
  164. public bool SpawnModItemProp(ModItem modItem)
  165. {
  166. GameObject dogu = MenuFileUtility.LoadModel(modItem);
  167. string name = modItem.MenuFile;
  168. if (modItem.IsOfficialMod) name = Path.GetFileNameWithoutExtension(name);
  169. if (dogu != null) AttachDragPoint(dogu, modItem.ToString(), name, new Vector3(0f, 0f, 0.5f));
  170. return dogu != null;
  171. }
  172. public bool SpawnMyRoomProp(MyRoomItem item)
  173. {
  174. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(item.ID);
  175. GameObject dogu = GameObject.Instantiate(data.GetPrefab());
  176. string name = Translation.Get("myRoomPropNames", item.PrefabName);
  177. if (dogu != null) AttachDragPoint(dogu, item.ToString(), name, new Vector3(0f, 0f, 0.5f));
  178. else Utility.LogInfo($"Could not load MyRoomCreative prop '{item.PrefabName}'");
  179. return dogu != null;
  180. }
  181. public bool SpawnBG(string assetName)
  182. {
  183. if (assetName.StartsWith("BG_")) assetName = assetName.Substring(3);
  184. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  185. ?? Resources.Load<GameObject>("BG/" + assetName)
  186. ?? Resources.Load<GameObject>("BG/2_0/" + assetName);
  187. if (obj != null)
  188. {
  189. GameObject dogu = GameObject.Instantiate(obj);
  190. string name = Translation.Get("bgNames", assetName);
  191. dogu.transform.localScale = Vector3.one * 0.1f;
  192. AttachDragPoint(dogu, $"BG_{assetName}", name, Vector3.zero);
  193. }
  194. return obj != null;
  195. }
  196. public bool SpawnObject(string assetName)
  197. {
  198. // TODO: Add a couple more things to ignore list
  199. GameObject dogu = null;
  200. string doguName = Translation.Get("propNames", assetName, false);
  201. Vector3 doguPosition = new Vector3(0f, 0f, 0.5f);
  202. if (assetName.EndsWith(".menu"))
  203. {
  204. dogu = MenuFileUtility.LoadModel(assetName);
  205. string handItem = Utility.HandItemToOdogu(assetName);
  206. if (Translation.Has("propNames", handItem)) doguName = Translation.Get("propNames", handItem);
  207. }
  208. else if (assetName.StartsWith("mirror"))
  209. {
  210. Material mirrorMaterial = new Material(Shader.Find("Mirror"));
  211. dogu = GameObject.CreatePrimitive(PrimitiveType.Plane);
  212. Renderer mirrorRenderer = dogu.GetComponent<Renderer>();
  213. mirrorRenderer.material = mirrorMaterial;
  214. mirrorRenderer.enabled = true;
  215. MirrorReflection2 mirrorReflection = dogu.AddComponent<MirrorReflection2>();
  216. mirrorReflection.m_TextureSize = 2048;
  217. Vector3 localPosition = new Vector3(0f, 0.96f, 0f);
  218. dogu.transform.Rotate(dogu.transform.right, 90f);
  219. switch (assetName)
  220. {
  221. case "mirror1":
  222. dogu.transform.localScale = new Vector3(0.2f, 0.4f, 0.2f);
  223. break;
  224. case "mirror2":
  225. dogu.transform.localScale = new Vector3(0.1f, 0.4f, 0.2f);
  226. break;
  227. case "mirror3":
  228. localPosition.y = 0.85f;
  229. dogu.transform.localScale = new Vector3(0.03f, 0.18f, 0.124f);
  230. break;
  231. }
  232. dogu.transform.localPosition = localPosition;
  233. }
  234. else if (assetName.IndexOf(':') >= 0)
  235. {
  236. string[] assetParts = assetName.Split(':');
  237. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetParts[0])
  238. ?? Resources.Load<GameObject>("BG/" + assetParts[0]);
  239. try
  240. {
  241. GameObject bg = GameObject.Instantiate(obj);
  242. int num = int.Parse(assetParts[1]);
  243. dogu = bg.transform.GetChild(num).gameObject;
  244. dogu.transform.SetParent(null);
  245. GameObject.Destroy(bg);
  246. }
  247. catch { }
  248. }
  249. else
  250. {
  251. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  252. ?? Resources.Load<GameObject>("Prefab/" + assetName);
  253. try
  254. {
  255. dogu = GameObject.Instantiate<GameObject>(obj);
  256. dogu.transform.localPosition = Vector3.zero;
  257. MeshRenderer[] meshRenderers = dogu.GetComponentsInChildren<MeshRenderer>();
  258. for (int i = 0; i < meshRenderers.Length; i++)
  259. {
  260. if (meshRenderers[i] != null
  261. && meshRenderers[i].gameObject.name.ToLower().IndexOf("castshadow") < 0
  262. ) meshRenderers[i].shadowCastingMode = ShadowCastingMode.Off;
  263. }
  264. Collider collider = dogu.transform.GetComponent<Collider>();
  265. if (collider != null) collider.enabled = false;
  266. foreach (Transform transform in dogu.transform)
  267. {
  268. collider = transform.GetComponent<Collider>();
  269. if (collider != null)
  270. {
  271. collider.enabled = false;
  272. }
  273. }
  274. }
  275. catch { }
  276. #region particle system experiment
  277. // if (asset.StartsWith("Particle/"))
  278. // {
  279. // ParticleSystem particleSystem = go.GetComponent<ParticleSystem>();
  280. // if (particleSystem != null)
  281. // {
  282. // ParticleSystem.MainModule main;
  283. // main = particleSystem.main;
  284. // main.loop = true;
  285. // main.duration = Mathf.Infinity;
  286. // ParticleSystem[] particleSystems = particleSystem.GetComponents<ParticleSystem>();
  287. // foreach (ParticleSystem part in particleSystems)
  288. // {
  289. // ParticleSystem.EmissionModule emissionModule = part.emission;
  290. // ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[emissionModule.burstCount];
  291. // emissionModule.GetBursts(bursts);
  292. // for (int i = 0; i < bursts.Length; i++)
  293. // {
  294. // bursts[i].cycleCount = Int32.MaxValue;
  295. // }
  296. // emissionModule.SetBursts(bursts);
  297. // main = part.main;
  298. // main.loop = true;
  299. // main.duration = Mathf.Infinity;
  300. // }
  301. // }
  302. // }
  303. #endregion
  304. }
  305. if (dogu != null)
  306. {
  307. AttachDragPoint(dogu, assetName, doguName, doguPosition);
  308. return true;
  309. }
  310. else
  311. {
  312. Utility.LogInfo($"Could not spawn object '{assetName}'");
  313. }
  314. return false;
  315. }
  316. private bool SpawnFromAssetString(string assetName, Dictionary<string, string> modDict = null)
  317. {
  318. bool result = false;
  319. if (assetName.EndsWith(".menu"))
  320. {
  321. if (assetName.Contains('#'))
  322. {
  323. string[] assetParts = assetName.Split('#');
  324. string menuFile = modDict == null ? Menu.GetModPathFileName(assetParts[0]) : modDict[assetParts[0]];
  325. ModItem item = ModItem.OfficialMod(menuFile);
  326. item.BaseMenuFile = assetParts[1];
  327. result = SpawnModItemProp(item);
  328. }
  329. else if (assetName.StartsWith("handitem")) result = SpawnObject(assetName);
  330. else result = SpawnModItemProp(ModItem.Mod(assetName));
  331. }
  332. else if (assetName.StartsWith("MYR_"))
  333. {
  334. string[] assetParts = assetName.Split('#');
  335. int id = int.Parse(assetParts[0].Substring(4));
  336. string prefabName;
  337. if (assetParts.Length == 2 && !string.IsNullOrEmpty(assetParts[1])) prefabName = assetParts[1];
  338. else
  339. {
  340. // deserialize modifiedMM and maybe MM 23.0+.
  341. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(id);
  342. prefabName = !string.IsNullOrEmpty(data.resourceName) ? data.resourceName : data.assetName;
  343. }
  344. result = SpawnMyRoomProp(new MyRoomItem() { ID = id, PrefabName = prefabName });
  345. }
  346. else if (assetName.StartsWith("BG_")) result = SpawnBG(assetName);
  347. else result = SpawnObject(assetName);
  348. return result;
  349. }
  350. private void AttachDragPoint(GameObject dogu, string assetName, string name, Vector3 position)
  351. {
  352. // TODO: Figure out why some props aren't centred properly
  353. // Doesn't happen in MM but even after copy pasting the code, it doesn't work :/
  354. GameObject deploymentObject = GetDeploymentObject();
  355. GameObject finalDogu = new GameObject(name);
  356. dogu.transform.SetParent(finalDogu.transform, true);
  357. finalDogu.transform.SetParent(deploymentObject.transform, false);
  358. finalDogu.transform.position = position;
  359. DragPointDogu dragDogu = DragPoint.Make<DragPointDogu>(
  360. PrimitiveType.Cube, Vector3.one * 0.12f, DragPoint.LightBlue
  361. );
  362. dragDogu.Initialize(() => finalDogu.transform.position, () => Vector3.zero);
  363. dragDogu.Set(finalDogu.transform);
  364. dragDogu.AddGizmo(scale: 0.45f, mode: CustomGizmo.GizmoMode.World);
  365. dragDogu.ConstantScale = true;
  366. dragDogu.Delete += DeleteDogu;
  367. dragDogu.Select += SelectDogu;
  368. dragDogu.DragPointScale = CubeSmall ? DragPointGeneral.smallCube : 1f;
  369. dragDogu.assetName = assetName;
  370. doguList.Add(dragDogu);
  371. OnDoguListChange();
  372. }
  373. public void SetCurrentDogu(int doguIndex)
  374. {
  375. if (doguIndex >= 0 && doguIndex < DoguCount)
  376. {
  377. this.CurrentDoguIndex = doguIndex;
  378. this.DoguSelectChange?.Invoke(this, EventArgs.Empty);
  379. }
  380. }
  381. public void RemoveDogu(int doguIndex)
  382. {
  383. if (doguIndex >= 0 && doguIndex < DoguCount)
  384. {
  385. DestroyDogu(doguList[doguIndex]);
  386. doguList.RemoveAt(doguIndex);
  387. CurrentDoguIndex = Utility.Bound(CurrentDoguIndex, 0, DoguCount - 1);
  388. OnDoguListChange();
  389. }
  390. }
  391. public void CopyDogu(int doguIndex)
  392. {
  393. if (doguIndex >= 0 && doguIndex < DoguCount)
  394. {
  395. SpawnFromAssetString(doguList[doguIndex].assetName);
  396. }
  397. }
  398. public void AttachProp(
  399. int doguIndex, AttachPoint attachPoint, Meido meido, bool worldPositionStays = true
  400. )
  401. {
  402. if (doguList.Count == 0 || doguIndex >= doguList.Count || doguIndex < 0) return;
  403. AttachProp(doguList[doguIndex], attachPoint, meido, worldPositionStays);
  404. }
  405. private void AttachProp(
  406. DragPointDogu dragDogu, AttachPoint attachPoint, Meido meido, bool worldPositionStays = true
  407. )
  408. {
  409. GameObject dogu = dragDogu.MyGameObject;
  410. Transform attachPointTransform = meido?.IKManager.GetAttachPointTransform(attachPoint)
  411. ?? GetDeploymentObject().transform;
  412. dragDogu.attachPointInfo = new AttachPointInfo(
  413. attachPoint: meido == null ? AttachPoint.None : attachPoint,
  414. maidGuid: meido == null ? String.Empty : meido.Maid.status.guid,
  415. maidIndex: meido == null ? -1 : meido.Slot
  416. );
  417. Vector3 position = dogu.transform.position;
  418. Quaternion rotation = dogu.transform.rotation;
  419. Vector3 scale = dogu.transform.localScale;
  420. dogu.transform.SetParent(attachPointTransform, worldPositionStays);
  421. if (worldPositionStays)
  422. {
  423. dogu.transform.position = position;
  424. dogu.transform.rotation = rotation;
  425. }
  426. else
  427. {
  428. dogu.transform.localPosition = Vector3.zero;
  429. dogu.transform.rotation = Quaternion.identity;
  430. }
  431. dogu.transform.localScale = scale;
  432. if (meido == null) Utility.FixGameObjectScale(dogu);
  433. }
  434. private void DetachProps(object sender, EventArgs args)
  435. {
  436. foreach (DragPointDogu dogu in doguList)
  437. {
  438. if (dogu.attachPointInfo.AttachPoint != AttachPoint.None)
  439. {
  440. dogu.MyObject.SetParent(GetDeploymentObject().transform, true);
  441. }
  442. }
  443. }
  444. private void ClearDogu()
  445. {
  446. for (int i = DoguCount - 1; i >= 0; i--)
  447. {
  448. DestroyDogu(doguList[i]);
  449. }
  450. doguList.Clear();
  451. CurrentDoguIndex = 0;
  452. }
  453. private void OnEndCall(object sender, EventArgs args) => ReattachProps(useGuid: true);
  454. private void ReattachProps(bool useGuid, bool forceStay = false)
  455. {
  456. foreach (DragPointDogu dragDogu in doguList)
  457. {
  458. AttachPointInfo info = dragDogu.attachPointInfo;
  459. Meido meido = useGuid
  460. ? this.meidoManager.GetMeido(info.MaidGuid)
  461. : this.meidoManager.GetMeido(info.MaidIndex);
  462. bool worldPositionStays = forceStay || meido == null;
  463. AttachProp(dragDogu, dragDogu.attachPointInfo.AttachPoint, meido, worldPositionStays);
  464. }
  465. }
  466. private void DeleteDogu(object sender, EventArgs args)
  467. {
  468. DragPointDogu dogu = (DragPointDogu)sender;
  469. RemoveDogu(doguList.FindIndex(dragDogu => dragDogu == dogu));
  470. }
  471. private void DestroyDogu(DragPointDogu dogu)
  472. {
  473. if (dogu == null) return;
  474. dogu.Delete -= DeleteDogu;
  475. dogu.Select -= SelectDogu;
  476. GameObject.Destroy(dogu.gameObject);
  477. }
  478. private void SelectDogu(object sender, EventArgs args)
  479. {
  480. DragPointDogu dogu = (DragPointDogu)sender;
  481. SetCurrentDogu(doguList.IndexOf(dogu));
  482. }
  483. private void OnCubeSmall(object sender, EventArgs args)
  484. {
  485. foreach (DragPointDogu dogu in doguList)
  486. {
  487. dogu.DragPointScale = CubeSmall ? DragPointGeneral.smallCube : 1f;
  488. }
  489. }
  490. private void OnDoguListChange()
  491. {
  492. this.DoguListChange?.Invoke(this, EventArgs.Empty);
  493. }
  494. public void SaveConfiguration()
  495. {
  496. }
  497. }
  498. }