Meido.cs 36 KB

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