PropManager.cs 22 KB

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