Meido.cs 33 KB

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