Meido.cs 35 KB

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