Meido.cs 33 KB

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