Meido.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Linq;
  5. using System.Xml.Linq;
  6. using UnityEngine;
  7. using static TBody;
  8. using System.Collections.Generic;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. public class Meido : ISerializable
  12. {
  13. private bool initialized;
  14. private float[] BlendSetValueBackup;
  15. public DragPointGravity HairGravityControl { get; private set; }
  16. public DragPointGravity SkirtGravityControl { get; private set; }
  17. public bool HairGravityActive
  18. {
  19. get => HairGravityControl.Valid && HairGravityControl.Active;
  20. set
  21. {
  22. if (HairGravityControl.Valid && value != HairGravityControl.Active)
  23. {
  24. HairGravityControl.gameObject.SetActive(value);
  25. }
  26. }
  27. }
  28. public bool SkirtGravityActive
  29. {
  30. get => SkirtGravityControl.Valid && SkirtGravityControl.Active;
  31. set
  32. {
  33. if (SkirtGravityControl.Valid && value != SkirtGravityControl.Active)
  34. {
  35. SkirtGravityControl.gameObject.SetActive(value);
  36. }
  37. }
  38. }
  39. public const int meidoDataVersion = 1000;
  40. public static readonly PoseInfo DefaultPose =
  41. new PoseInfo(Constants.PoseGroupList[0], Constants.PoseDict[Constants.PoseGroupList[0]][0]);
  42. public static readonly string defaultFaceBlendSet = "通常";
  43. public static readonly string[] faceKeys = new string[24]
  44. {
  45. "eyeclose", "eyeclose2", "eyeclose3", "eyebig", "eyeclose6", "eyeclose5", "hitomih",
  46. "hitomis", "mayuha", "mayuw", "mayuup", "mayuv", "mayuvhalf", "moutha", "mouths",
  47. "mouthc", "mouthi", "mouthup", "mouthdw", "mouthhe", "mouthuphalf", "tangout",
  48. "tangup", "tangopen"
  49. };
  50. public static readonly string[] faceToggleKeys = new string[12]
  51. {
  52. // blush, shade, nose up, tears, drool, teeth
  53. "hoho2", "shock", "nosefook", "namida", "yodare", "toothoff",
  54. // cry 1, cry 2, cry 3, blush 1, blush 2, blush 3
  55. "tear1", "tear2", "tear3", "hohos", "hoho", "hohol"
  56. };
  57. public enum Curl
  58. {
  59. front, back, shift
  60. }
  61. public event EventHandler<MeidoUpdateEventArgs> UpdateMeido;
  62. public int StockNo { get; }
  63. public Maid Maid { get; }
  64. public TBody Body => Maid.body0;
  65. public MeidoDragPointManager IKManager { get; }
  66. public Texture2D Portrait => Maid.GetThumIcon();
  67. public bool IsEditMaid { get; set; }
  68. public PoseInfo CachedPose { get; private set; } = DefaultPose;
  69. public string CurrentFaceBlendSet { get; private set; } = defaultFaceBlendSet;
  70. public int Slot { get; private set; }
  71. public bool Loading { get; private set; }
  72. public string FirstName => Maid.status.firstName;
  73. public string LastName => Maid.status.lastName;
  74. public bool Busy => Maid.IsBusy || Loading;
  75. public bool CurlingFront => Maid.IsItemChange("skirt", "めくれスカート")
  76. || Maid.IsItemChange("onepiece", "めくれスカート");
  77. public bool CurlingBack => Maid.IsItemChange("skirt", "めくれスカート後ろ")
  78. || Maid.IsItemChange("onepiece", "めくれスカート後ろ");
  79. public bool PantsuShift => Maid.IsItemChange("panz", "パンツずらし")
  80. || Maid.IsItemChange("mizugi", "パンツずらし");
  81. private bool freeLook;
  82. public bool FreeLook
  83. {
  84. get => freeLook;
  85. set
  86. {
  87. if (freeLook == value) return;
  88. freeLook = value;
  89. Body.trsLookTarget = freeLook ? null : GameMain.Instance.MainCamera.transform;
  90. OnUpdateMeido();
  91. }
  92. }
  93. public bool HeadToCam
  94. {
  95. get => Body.isLoadedBody && Body.boHeadToCam;
  96. set
  97. {
  98. if (!Body.isLoadedBody || HeadToCam == value) return;
  99. Body.HeadToCamPer = 0f;
  100. Body.boHeadToCam = value;
  101. if (!HeadToCam && !EyeToCam) FreeLook = false;
  102. OnUpdateMeido();
  103. }
  104. }
  105. public bool EyeToCam
  106. {
  107. get => Body.isLoadedBody && Body.boEyeToCam;
  108. set
  109. {
  110. if (!Body.isLoadedBody || EyeToCam == value) return;
  111. Body.boEyeToCam = value;
  112. if (!HeadToCam && !EyeToCam) FreeLook = false;
  113. OnUpdateMeido();
  114. }
  115. }
  116. public bool Stop
  117. {
  118. get => !Body.isLoadedBody || !Maid.GetAnimation().isPlaying;
  119. set
  120. {
  121. if (!Body.isLoadedBody || value == Stop) return;
  122. if (value) Maid.GetAnimation().Stop();
  123. else
  124. {
  125. Body.boEyeToCam = true;
  126. Body.boHeadToCam = true;
  127. SetPose(CachedPose.Pose);
  128. }
  129. OnUpdateMeido();
  130. }
  131. }
  132. public bool IK
  133. {
  134. get => IKManager.Active;
  135. set
  136. {
  137. if (value == IKManager.Active) return;
  138. IKManager.Active = value;
  139. }
  140. }
  141. public bool Bone
  142. {
  143. get => IKManager.IsBone;
  144. set
  145. {
  146. if (value == Bone) return;
  147. IKManager.IsBone = value;
  148. OnUpdateMeido();
  149. }
  150. }
  151. public event EventHandler<GravityEventArgs> GravityMove;
  152. public Quaternion DefaultEyeRotL { get; private set; }
  153. public Quaternion DefaultEyeRotR { get; private set; }
  154. public Meido(int stockMaidIndex)
  155. {
  156. StockNo = stockMaidIndex;
  157. Maid = GameMain.Instance.CharacterMgr.GetStockMaid(stockMaidIndex);
  158. IKManager = new MeidoDragPointManager(this);
  159. IKManager.SelectMaid += (s, args) => OnUpdateMeido(args);
  160. }
  161. public void Load(int slot)
  162. {
  163. if (Busy) return;
  164. Slot = slot;
  165. FreeLook = false;
  166. Maid.Visible = true;
  167. Body.boHeadToCam = true;
  168. Body.boEyeToCam = true;
  169. Body.SetBoneHitHeightY(-1000f);
  170. if (!Body.isLoadedBody)
  171. {
  172. Maid.DutPropAll();
  173. Maid.AllProcPropSeqStart();
  174. }
  175. StartLoad(OnBodyLoad);
  176. }
  177. private void StartLoad(Action callback)
  178. {
  179. if (Loading) return;
  180. GameMain.Instance.StartCoroutine(Load(callback));
  181. }
  182. private IEnumerator Load(Action callback)
  183. {
  184. Loading = true;
  185. while (Maid.IsBusy) yield return null;
  186. yield return new WaitForEndOfFrame();
  187. callback();
  188. Loading = false;
  189. }
  190. private void OnBodyLoad()
  191. {
  192. if (!initialized)
  193. {
  194. DefaultEyeRotL = Body.quaDefEyeL;
  195. DefaultEyeRotR = Body.quaDefEyeR;
  196. initialized = true;
  197. }
  198. if (BlendSetValueBackup == null) BackupBlendSetValues();
  199. if (!HairGravityControl) InitializeGravityControls();
  200. HairGravityControl.Move += OnGravityEvent;
  201. SkirtGravityControl.Move += OnGravityEvent;
  202. if (MeidoPhotoStudio.EditMode) AllProcPropSeqStartPatcher.SequenceStart += ReinitializeBody;
  203. IKManager.Initialize();
  204. IK = true;
  205. Stop = false;
  206. Bone = false;
  207. }
  208. private void ReinitializeBody(object sender, ProcStartEventArgs args)
  209. {
  210. if (Loading || !Body.isLoadedBody) return;
  211. if (args.maid.status.guid == Maid.status.guid)
  212. {
  213. MPN[] gravityControlProps = new[] {
  214. MPN.skirt, MPN.onepiece, MPN.mizugi, MPN.panz, MPN.set_maidwear, MPN.set_mywear, MPN.set_underwear,
  215. MPN.hairf, MPN.hairr, MPN.hairs, MPN.hairt
  216. };
  217. // Change body
  218. if (Maid.GetProp(MPN.body).boDut)
  219. {
  220. IKManager.Destroy();
  221. StartLoad(reinitializeBody);
  222. }
  223. // Change face
  224. else if (Maid.GetProp(MPN.head).boDut)
  225. {
  226. SetFaceBlendSet(defaultFaceBlendSet);
  227. StartLoad(reinitializeFace);
  228. }
  229. // Gravity control clothing/hair change
  230. else if (gravityControlProps.Any(prop => Maid.GetProp(prop).boDut))
  231. {
  232. if (HairGravityControl) GameObject.Destroy(HairGravityControl.gameObject);
  233. if (SkirtGravityControl) GameObject.Destroy(SkirtGravityControl.gameObject);
  234. StartLoad(reinitializeGravity);
  235. }
  236. // Clothing/accessory changes
  237. // Includes null_mpn too but any button click results in null_mpn bodut I think
  238. else StartLoad(() => OnUpdateMeido());
  239. void reinitializeBody()
  240. {
  241. IKManager.Initialize();
  242. Stop = false;
  243. // Maid animation needs to be set again for custom parts edit
  244. GameObject uiRoot = GameObject.Find("UI Root");
  245. var customPartsWindow = UTY.GetChildObject(uiRoot, "Window/CustomPartsWindow")
  246. .GetComponent<SceneEditWindow.CustomPartsWindow>();
  247. Utility.SetFieldValue(customPartsWindow, "animation", Maid.GetAnimation());
  248. }
  249. void reinitializeFace()
  250. {
  251. DefaultEyeRotL = Body.quaDefEyeL;
  252. DefaultEyeRotR = Body.quaDefEyeR;
  253. BackupBlendSetValues();
  254. }
  255. void reinitializeGravity()
  256. {
  257. InitializeGravityControls();
  258. OnUpdateMeido();
  259. }
  260. }
  261. }
  262. public void Unload()
  263. {
  264. if (Body.isLoadedBody && Maid.Visible)
  265. {
  266. DetachAllMpnAttach();
  267. Body.jbMuneL.enabled = true;
  268. Body.jbMuneR.enabled = true;
  269. Body.quaDefEyeL = DefaultEyeRotL;
  270. Body.quaDefEyeR = DefaultEyeRotR;
  271. if (HairGravityControl)
  272. {
  273. HairGravityControl.Move -= OnGravityEvent;
  274. HairGravityActive = false;
  275. }
  276. if (SkirtGravityControl)
  277. {
  278. SkirtGravityControl.Move -= OnGravityEvent;
  279. SkirtGravityActive = false;
  280. }
  281. ApplyGravity(Vector3.zero, skirt: false);
  282. ApplyGravity(Vector3.zero, skirt: true);
  283. SetFaceBlendSet(defaultFaceBlendSet);
  284. }
  285. AllProcPropSeqStartPatcher.SequenceStart -= ReinitializeBody;
  286. Body.MuneYureL(1f);
  287. Body.MuneYureR(1f);
  288. Body.SetMaskMode(MaskMode.None);
  289. Body.SetBoneHitHeightY(0f);
  290. Maid.Visible = false;
  291. IKManager.Destroy();
  292. }
  293. public void Deactivate()
  294. {
  295. Unload();
  296. if (HairGravityControl) GameObject.Destroy(HairGravityControl.gameObject);
  297. if (SkirtGravityControl) GameObject.Destroy(SkirtGravityControl.gameObject);
  298. Maid.SetPos(Vector3.zero);
  299. Maid.SetRot(Vector3.zero);
  300. Maid.SetPosOffset(Vector3.zero);
  301. Body.transform.localScale = Vector3.one;
  302. Maid.ResetAll();
  303. Maid.MabatakiUpdateStop = false;
  304. Maid.ActiveSlotNo = -1;
  305. }
  306. public void SetPose(PoseInfo poseInfo)
  307. {
  308. CachedPose = poseInfo;
  309. SetPose(poseInfo.Pose);
  310. }
  311. public void SetPose(string pose)
  312. {
  313. if (!Body.isLoadedBody) return;
  314. if (pose.StartsWith(Constants.customPosePath))
  315. {
  316. string poseFilename = Path.GetFileNameWithoutExtension(pose);
  317. try
  318. {
  319. byte[] poseBuffer = File.ReadAllBytes(pose);
  320. string hash = Path.GetFileName(pose).GetHashCode().ToString();
  321. Body.CrossFade(hash, poseBuffer, loop: true, fade: 0f);
  322. }
  323. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  324. {
  325. Utility.LogWarning($"{poseFilename}: Could not open because {e.Message}");
  326. Constants.InitializeCustomPoses();
  327. return;
  328. }
  329. catch (Exception e)
  330. {
  331. Utility.LogWarning($"{poseFilename}: Could not apply pose because {e.Message}");
  332. return;
  333. }
  334. SetMune(true, left: true);
  335. SetMune(true, left: false);
  336. }
  337. else
  338. {
  339. string[] poseComponents = pose.Split(',');
  340. pose = poseComponents[0] + ".anm";
  341. Maid.CrossFade(pose, loop: true, val: 0f);
  342. Maid.GetAnimation().Play();
  343. if (poseComponents.Length > 1)
  344. {
  345. Maid.GetAnimation()[pose].time = float.Parse(poseComponents[1]);
  346. Maid.GetAnimation()[pose].speed = 0f;
  347. }
  348. SetPoseMune();
  349. }
  350. Maid.SetAutoTwistAll(true);
  351. }
  352. public void CopyPose(Meido fromMeido)
  353. {
  354. Stop = true;
  355. GetCacheBoneData().SetFrameBinary(fromMeido.SerializePose(frameBinary: true));
  356. SetMune(fromMeido.Body.GetMuneYureL() != 0f, left: true);
  357. SetMune(fromMeido.Body.GetMuneYureR() != 0f, left: false);
  358. }
  359. public void SetMune(bool enabled, bool left = false)
  360. {
  361. float value = enabled ? 1f : 0f;
  362. if (left)
  363. {
  364. Body.MuneYureL(value);
  365. Body.jbMuneL.enabled = enabled;
  366. }
  367. else
  368. {
  369. Body.MuneYureR(value);
  370. Body.jbMuneR.enabled = enabled;
  371. }
  372. }
  373. private void SetPoseMune()
  374. {
  375. bool momiOrPaizuri = CachedPose.Pose.Contains("_momi") || CachedPose.Pose.Contains("paizuri_");
  376. SetMune(!momiOrPaizuri, left: true);
  377. SetMune(!momiOrPaizuri, left: false);
  378. }
  379. public void SetHandPreset(string filename, bool right)
  380. {
  381. string faceFilename = Path.GetFileNameWithoutExtension(filename);
  382. try
  383. {
  384. XDocument handDocument = XDocument.Load(filename);
  385. XElement handElement = handDocument.Element("FingerData");
  386. if (handElement?.Elements().Any(element => element?.IsEmpty ?? true) ?? true)
  387. {
  388. Utility.LogWarning($"{faceFilename}: Could not apply hand preset because it is invalid.");
  389. return;
  390. }
  391. Stop = true;
  392. bool rightData = bool.Parse(handElement.Element("RightData").Value);
  393. string base64Data = handElement.Element("BinaryData").Value;
  394. byte[] handData = Convert.FromBase64String(base64Data);
  395. IKManager.DeserializeHand(handData, right, rightData != right);
  396. }
  397. catch (System.Xml.XmlException e)
  398. {
  399. Utility.LogWarning($"{faceFilename}: Hand preset data is malformed because {e.Message}");
  400. }
  401. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  402. {
  403. Utility.LogWarning($"{faceFilename}: Could not open hand preset because {e.Message}");
  404. Constants.InitializeHandPresets();
  405. }
  406. catch (Exception e)
  407. {
  408. Utility.LogWarning($"{faceFilename}: Could not parse hand preset because {e.Message}");
  409. }
  410. }
  411. public byte[] SerializePose(bool frameBinary = false)
  412. {
  413. CacheBoneDataArray cache = GetCacheBoneData();
  414. bool muneL = Body.GetMuneYureL() == 0f;
  415. bool muneR = Body.GetMuneYureR() == 0f;
  416. return frameBinary ? cache.GetFrameBinary(muneL, muneR) : cache.GetAnmBinary(true, true);
  417. }
  418. public Dictionary<string, float> SerializeFace()
  419. {
  420. Dictionary<string, float> faceData = new Dictionary<string, float>();
  421. foreach (string hash in faceKeys.Concat(faceToggleKeys))
  422. {
  423. try
  424. {
  425. float value = GetFaceBlendValue(hash);
  426. faceData.Add(hash, value);
  427. }
  428. catch { }
  429. }
  430. return faceData;
  431. }
  432. public void SetFaceBlendSet(string blendSet)
  433. {
  434. if (blendSet.StartsWith(Constants.customFacePath))
  435. {
  436. string blendSetFileName = Path.GetFileNameWithoutExtension(blendSet);
  437. try
  438. {
  439. XDocument faceDocument = XDocument.Load(blendSet, LoadOptions.SetLineInfo);
  440. XElement faceDataElement = faceDocument.Element("FaceData");
  441. if (faceDataElement?.IsEmpty ?? true)
  442. {
  443. Utility.LogWarning($"{blendSetFileName}: Could not apply face preset because it is invalid.");
  444. return;
  445. }
  446. HashSet<string> hashKeys = new HashSet<string>(faceKeys.Concat(faceToggleKeys));
  447. foreach (XElement element in faceDataElement.Elements())
  448. {
  449. System.Xml.IXmlLineInfo info = element;
  450. int line = info.HasLineInfo() ? info.LineNumber : -1;
  451. string key;
  452. if ((key = (string)element.Attribute("name")) == null)
  453. {
  454. Utility.LogWarning($"{blendSetFileName}: Could not read face blend key at line {line}.");
  455. continue;
  456. }
  457. if (!hashKeys.Contains(key))
  458. {
  459. Utility.LogWarning($"{blendSetFileName}: Invalid face blend key '{key}' at line {line}.");
  460. continue;
  461. }
  462. if (float.TryParse(element.Value, out float value))
  463. {
  464. try { SetFaceBlendValue(key, value); }
  465. catch { }
  466. }
  467. else Utility.LogWarning(
  468. $"{blendSetFileName}: Could not parse value '{element.Value}' of '{key}' at line {line}"
  469. );
  470. }
  471. }
  472. catch (System.Xml.XmlException e)
  473. {
  474. Utility.LogWarning($"{blendSetFileName}: Face preset data is malformed because {e.Message}");
  475. return;
  476. }
  477. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  478. {
  479. Utility.LogWarning($"{blendSetFileName}: Could not open face preset because {e.Message}");
  480. Constants.InitializeCustomFaceBlends();
  481. return;
  482. }
  483. catch (Exception e)
  484. {
  485. Utility.LogWarning($"{blendSetFileName}: Could not parse face preset because {e.Message}");
  486. return;
  487. }
  488. }
  489. else
  490. {
  491. ApplyBackupBlendSet();
  492. CurrentFaceBlendSet = blendSet;
  493. BackupBlendSetValues();
  494. Maid.FaceAnime(blendSet, 0f);
  495. }
  496. StopBlink();
  497. OnUpdateMeido();
  498. }
  499. public void SetFaceBlendValue(string hash, float value)
  500. {
  501. TMorph morph = Body.Face.morph;
  502. hash = Utility.GP01FbFaceHash(morph, hash);
  503. if (morph.Contains(hash))
  504. {
  505. if (hash == "nosefook") Maid.boNoseFook = morph.boNoseFook = value > 0f;
  506. else morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]] = value;
  507. }
  508. }
  509. public float GetFaceBlendValue(string hash)
  510. {
  511. TMorph morph = Body.Face.morph;
  512. if (hash == "nosefook") return (Maid.boNoseFook || morph.boNoseFook) ? 1f : 0f;
  513. hash = Utility.GP01FbFaceHash(morph, hash);
  514. return morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]];
  515. }
  516. public void StopBlink()
  517. {
  518. Maid.MabatakiUpdateStop = true;
  519. Body.Face.morph.EyeMabataki = 0f;
  520. Utility.SetFieldValue(Maid, "MabatakiVal", 0f);
  521. }
  522. public void SetMaskMode(MaskMode maskMode)
  523. {
  524. bool invisibleBody = !Body.GetMask(SlotID.body);
  525. Body.SetMaskMode(maskMode);
  526. if (invisibleBody) SetBodyMask(false);
  527. }
  528. public void SetBodyMask(bool enabled)
  529. {
  530. Hashtable table = Utility.GetFieldValue<TBody, Hashtable>(Body, "m_hFoceHide");
  531. foreach (SlotID bodySlot in MaidDressingPane.bodySlots)
  532. {
  533. table[bodySlot] = enabled;
  534. }
  535. if (Body.goSlot[19].m_strModelFileName.Contains("melala_body"))
  536. {
  537. table[SlotID.accHana] = enabled;
  538. }
  539. Body.FixMaskFlag();
  540. Body.FixVisibleFlag(false);
  541. }
  542. public void SetCurling(Curl curling, bool enabled)
  543. {
  544. string[] name = curling == Curl.shift
  545. ? new[] { "panz", "mizugi" }
  546. : new[] { "skirt", "onepiece" };
  547. if (enabled)
  548. {
  549. string action = curling == Curl.shift
  550. ? "パンツずらし" : curling == Curl.front
  551. ? "めくれスカート" : "めくれスカート後ろ";
  552. Maid.ItemChangeTemp(name[0], action);
  553. Maid.ItemChangeTemp(name[1], action);
  554. }
  555. else
  556. {
  557. Maid.ResetProp(name[0]);
  558. Maid.ResetProp(name[1]);
  559. }
  560. Maid.AllProcProp();
  561. HairGravityControl.Control.OnChangeMekure();
  562. SkirtGravityControl.Control.OnChangeMekure();
  563. }
  564. public void SetMpnProp(MpnAttachProp prop, bool detach)
  565. {
  566. if (detach) Maid.ResetProp(prop.Tag, false);
  567. else Maid.SetProp(prop.Tag, prop.MenuFile, 0, true);
  568. Maid.AllProcProp();
  569. }
  570. public void DetachAllMpnAttach()
  571. {
  572. Maid.ResetProp(MPN.kousoku_lower, false);
  573. Maid.ResetProp(MPN.kousoku_upper, false);
  574. Maid.AllProcProp();
  575. }
  576. public void ApplyGravity(Vector3 position, bool skirt = false)
  577. {
  578. DragPointGravity dragPoint = skirt ? SkirtGravityControl : HairGravityControl;
  579. if (dragPoint.Valid) dragPoint.Control.transform.localPosition = position;
  580. }
  581. private void BackupBlendSetValues()
  582. {
  583. float[] values = Body.Face.morph.dicBlendSet[CurrentFaceBlendSet];
  584. BlendSetValueBackup = new float[values.Length];
  585. values.CopyTo(BlendSetValueBackup, 0);
  586. }
  587. private void ApplyBackupBlendSet()
  588. {
  589. BlendSetValueBackup.CopyTo(Body.Face.morph.dicBlendSet[CurrentFaceBlendSet], 0);
  590. Maid.boNoseFook = false;
  591. }
  592. private CacheBoneDataArray GetCacheBoneData()
  593. {
  594. CacheBoneDataArray cache = Maid.gameObject.GetComponent<CacheBoneDataArray>();
  595. void CreateCache() => cache.CreateCache(Body.GetBone("Bip01"));
  596. if (cache == null)
  597. {
  598. cache = Maid.gameObject.AddComponent<CacheBoneDataArray>();
  599. CreateCache();
  600. }
  601. if (cache.bone_data?.transform == null)
  602. {
  603. Utility.LogDebug("Cache bone_data is null");
  604. CreateCache();
  605. }
  606. return cache;
  607. }
  608. private void InitializeGravityControls()
  609. {
  610. HairGravityControl = MakeGravityControl(skirt: false);
  611. SkirtGravityControl = MakeGravityControl(skirt: true);
  612. }
  613. private DragPointGravity MakeGravityControl(bool skirt = false)
  614. {
  615. DragPointGravity gravityDragpoint = DragPoint.Make<DragPointGravity>(
  616. PrimitiveType.Cube, Vector3.one * 0.12f
  617. );
  618. GravityTransformControl control = DragPointGravity.MakeGravityControl(Maid, skirt);
  619. gravityDragpoint.Initialize(() => control.transform.position, () => Vector3.zero);
  620. gravityDragpoint.Set(control.transform);
  621. gravityDragpoint.gameObject.SetActive(false);
  622. return gravityDragpoint;
  623. }
  624. private void OnUpdateMeido(MeidoUpdateEventArgs args = null)
  625. {
  626. UpdateMeido?.Invoke(this, args ?? MeidoUpdateEventArgs.Empty);
  627. }
  628. private void OnGravityEvent(object sender, EventArgs args) => OnGravityChange((DragPointGravity)sender);
  629. private void OnGravityChange(DragPointGravity dragPoint)
  630. {
  631. GravityEventArgs args = new GravityEventArgs(
  632. dragPoint == SkirtGravityControl, dragPoint.MyObject.transform.localPosition
  633. );
  634. GravityMove?.Invoke(this, args);
  635. }
  636. public void Serialize(BinaryWriter binaryWriter)
  637. {
  638. using (MemoryStream memoryStream = new MemoryStream())
  639. using (BinaryWriter tempWriter = new BinaryWriter(memoryStream))
  640. {
  641. // transform
  642. tempWriter.WriteVector3(Maid.transform.position);
  643. tempWriter.WriteQuaternion(Maid.transform.rotation);
  644. tempWriter.WriteVector3(Maid.transform.localScale);
  645. // pose
  646. byte[] poseBuffer = SerializePose(true);
  647. tempWriter.Write(poseBuffer.Length);
  648. tempWriter.Write(poseBuffer);
  649. CachedPose.Serialize(tempWriter);
  650. // eye direction
  651. tempWriter.WriteQuaternion(Body.quaDefEyeL * Quaternion.Inverse(DefaultEyeRotL));
  652. tempWriter.WriteQuaternion(Body.quaDefEyeR * Quaternion.Inverse(DefaultEyeRotR));
  653. // free look
  654. tempWriter.Write(FreeLook);
  655. if (FreeLook)
  656. {
  657. tempWriter.WriteVector3(Body.offsetLookTarget);
  658. tempWriter.WriteVector3(Utility.GetFieldValue<TBody, Vector3>(Body, "HeadEulerAngle"));
  659. }
  660. // Head/eye to camera
  661. tempWriter.Write(HeadToCam);
  662. tempWriter.Write(EyeToCam);
  663. // face
  664. SerializeFace(tempWriter);
  665. // body visible
  666. tempWriter.Write(Body.GetMask(SlotID.body));
  667. // clothing
  668. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  669. {
  670. bool value = true;
  671. if (clothingSlot == SlotID.wear)
  672. {
  673. if (MaidDressingPane.wearSlots.Any(slot => Body.GetSlotLoaded(slot)))
  674. {
  675. value = MaidDressingPane.wearSlots.Any(slot => Body.GetMask(slot));
  676. }
  677. }
  678. else if (clothingSlot == SlotID.megane)
  679. {
  680. SlotID[] slots = new[] { SlotID.megane, SlotID.accHead };
  681. if (slots.Any(slot => Body.GetSlotLoaded(slot)))
  682. {
  683. value = slots.Any(slot => Body.GetMask(slot));
  684. }
  685. }
  686. else if (Body.GetSlotLoaded(clothingSlot))
  687. {
  688. value = Body.GetMask(clothingSlot);
  689. }
  690. tempWriter.Write(value);
  691. }
  692. // hair/skirt gravity
  693. tempWriter.Write(HairGravityActive);
  694. if (HairGravityActive) tempWriter.WriteVector3(HairGravityControl.Control.transform.localPosition);
  695. tempWriter.Write(SkirtGravityActive);
  696. if (SkirtGravityActive) tempWriter.WriteVector3(SkirtGravityControl.Control.transform.localPosition);
  697. // zurashi and mekure
  698. tempWriter.Write(CurlingFront);
  699. tempWriter.Write(CurlingBack);
  700. tempWriter.Write(PantsuShift);
  701. bool hasKousokuUpper = Body.GetSlotLoaded(SlotID.kousoku_upper);
  702. tempWriter.Write(hasKousokuUpper);
  703. if (hasKousokuUpper) tempWriter.Write(Maid.GetProp(MPN.kousoku_upper).strTempFileName);
  704. bool hasKousokuLower = Body.GetSlotLoaded(SlotID.kousoku_lower);
  705. tempWriter.Write(hasKousokuLower);
  706. if (hasKousokuLower) tempWriter.Write(Maid.GetProp(MPN.kousoku_lower).strTempFileName);
  707. binaryWriter.Write(memoryStream.Length);
  708. binaryWriter.Write(memoryStream.ToArray());
  709. }
  710. }
  711. private void SerializeFace(BinaryWriter binaryWriter)
  712. {
  713. binaryWriter.Write("MPS_FACE");
  714. foreach (string hash in faceKeys.Concat(faceToggleKeys))
  715. {
  716. try
  717. {
  718. float value = GetFaceBlendValue(hash);
  719. binaryWriter.Write(hash);
  720. binaryWriter.Write(value);
  721. }
  722. catch { }
  723. }
  724. binaryWriter.Write("END_FACE");
  725. }
  726. public void Deserialize(BinaryReader binaryReader) => Deserialize(binaryReader, meidoDataVersion, false);
  727. public void Deserialize(BinaryReader binaryReader, int dataVersion, bool mmScene)
  728. {
  729. Maid.GetAnimation().Stop();
  730. DetachAllMpnAttach();
  731. binaryReader.ReadInt64(); // meido buffer length
  732. // transform
  733. Maid.transform.position = binaryReader.ReadVector3();
  734. Maid.transform.rotation = binaryReader.ReadQuaternion();
  735. Maid.transform.localScale = binaryReader.ReadVector3();
  736. IKManager.SetDragPointScale(Maid.transform.localScale.x);
  737. // pose
  738. KeyValuePair<bool, bool> muneSetting = new KeyValuePair<bool, bool>(true, true);
  739. if (mmScene) IKManager.Deserialize(binaryReader);
  740. else
  741. {
  742. int poseBufferLength = binaryReader.ReadInt32();
  743. byte[] poseBuffer = binaryReader.ReadBytes(poseBufferLength);
  744. muneSetting = GetCacheBoneData().SetFrameBinary(poseBuffer);
  745. }
  746. SetMune(!muneSetting.Key, left: true);
  747. SetMune(!muneSetting.Value, left: false);
  748. CachedPose = PoseInfo.Deserialize(binaryReader);
  749. // eye direction
  750. Body.quaDefEyeL = binaryReader.ReadQuaternion() * DefaultEyeRotL;
  751. Body.quaDefEyeR = binaryReader.ReadQuaternion() * DefaultEyeRotR;
  752. // free look
  753. FreeLook = binaryReader.ReadBoolean();
  754. if (FreeLook)
  755. {
  756. Body.offsetLookTarget = binaryReader.ReadVector3();
  757. // Head angle cannot be resolved with just the offsetLookTarget
  758. if (!mmScene)
  759. {
  760. Utility.SetFieldValue(Body, "HeadEulerAngleG", Vector3.zero);
  761. Utility.SetFieldValue(Body, "HeadEulerAngle", binaryReader.ReadVector3());
  762. }
  763. }
  764. // Head/eye to camera
  765. HeadToCam = binaryReader.ReadBoolean();
  766. EyeToCam = binaryReader.ReadBoolean();
  767. // face
  768. DeserializeFace(binaryReader);
  769. // body visible
  770. SetBodyMask(binaryReader.ReadBoolean());
  771. // clothing
  772. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  773. {
  774. bool value = binaryReader.ReadBoolean();
  775. if (mmScene) continue;
  776. if (clothingSlot == SlotID.wear)
  777. {
  778. Body.SetMask(SlotID.wear, value);
  779. Body.SetMask(SlotID.mizugi, value);
  780. Body.SetMask(SlotID.onepiece, value);
  781. }
  782. else if (clothingSlot == SlotID.megane)
  783. {
  784. Body.SetMask(SlotID.megane, value);
  785. Body.SetMask(SlotID.accHead, value);
  786. }
  787. else if (Body.GetSlotLoaded(clothingSlot))
  788. {
  789. Body.SetMask(clothingSlot, value);
  790. }
  791. }
  792. // hair/skirt gravity
  793. bool hairGravityActive = binaryReader.ReadBoolean();
  794. if (hairGravityActive)
  795. {
  796. HairGravityActive = true;
  797. ApplyGravity(binaryReader.ReadVector3(), skirt: false);
  798. }
  799. bool skirtGravityActive = binaryReader.ReadBoolean();
  800. if (skirtGravityActive)
  801. {
  802. SkirtGravityActive = true;
  803. ApplyGravity(binaryReader.ReadVector3(), skirt: true);
  804. }
  805. // zurashi and mekure
  806. bool curlingFront = binaryReader.ReadBoolean();
  807. bool curlingBack = binaryReader.ReadBoolean();
  808. bool curlingPantsu = binaryReader.ReadBoolean();
  809. if (!mmScene)
  810. {
  811. if (CurlingFront != curlingFront) SetCurling(Curl.front, curlingFront);
  812. if (CurlingBack != curlingBack) SetCurling(Curl.back, curlingBack);
  813. SetCurling(Curl.shift, curlingPantsu);
  814. }
  815. bool hasKousokuUpper = binaryReader.ReadBoolean();
  816. if (hasKousokuUpper)
  817. {
  818. try
  819. {
  820. SetMpnProp(new MpnAttachProp(MPN.kousoku_upper, binaryReader.ReadString()), false);
  821. }
  822. catch { }
  823. }
  824. bool hasKousokuLower = binaryReader.ReadBoolean();
  825. if (hasKousokuLower)
  826. {
  827. try
  828. {
  829. SetMpnProp(new MpnAttachProp(MPN.kousoku_lower, binaryReader.ReadString()), false);
  830. }
  831. catch { }
  832. }
  833. // OnUpdateMeido();
  834. }
  835. private void DeserializeFace(BinaryReader binaryReader)
  836. {
  837. StopBlink();
  838. binaryReader.ReadString(); // read face header
  839. string header;
  840. while ((header = binaryReader.ReadString()) != "END_FACE")
  841. {
  842. SetFaceBlendValue(header, binaryReader.ReadSingle());
  843. }
  844. }
  845. }
  846. public class GravityEventArgs : EventArgs
  847. {
  848. public Vector3 LocalPosition { get; }
  849. public bool IsSkirt { get; }
  850. public GravityEventArgs(bool isSkirt, Vector3 localPosition)
  851. {
  852. LocalPosition = localPosition;
  853. IsSkirt = isSkirt;
  854. }
  855. }
  856. public struct PoseInfo
  857. {
  858. public string PoseGroup { get; }
  859. public string Pose { get; }
  860. public bool CustomPose { get; }
  861. public PoseInfo(string poseGroup, string pose, bool customPose = false)
  862. {
  863. PoseGroup = poseGroup;
  864. Pose = pose;
  865. CustomPose = customPose;
  866. }
  867. public void Serialize(BinaryWriter binaryWriter)
  868. {
  869. binaryWriter.Write(PoseGroup);
  870. binaryWriter.Write(Pose);
  871. binaryWriter.Write(CustomPose);
  872. }
  873. public static PoseInfo Deserialize(BinaryReader binaryReader)
  874. {
  875. return new PoseInfo
  876. (
  877. binaryReader.ReadString(),
  878. binaryReader.ReadString(),
  879. binaryReader.ReadBoolean()
  880. );
  881. }
  882. }
  883. }