MenuFileUtility.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Linq;
  8. using UnityEngine;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. public static partial class MenuFileUtility
  12. {
  13. private static byte[] fileBuffer;
  14. public const string noCategory = "noCategory";
  15. public static readonly string[] MenuCategories =
  16. {
  17. noCategory, "acchat", "headset", "wear", "skirt", "onepiece", "mizugi", "bra", "panz", "stkg", "shoes",
  18. "acckami", "megane", "acchead", "acchana", "accmimi", "glove", "acckubi", "acckubiwa", "acckamisub",
  19. "accnip", "accude", "accheso", "accashi", "accsenaka", "accshippo", "accxxx"
  20. };
  21. private static readonly HashSet<string> accMpn = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
  22. private enum IMode
  23. {
  24. None,
  25. ItemChange,
  26. TexChange
  27. }
  28. public static event EventHandler MenuFilesReadyChange;
  29. public static bool MenuFilesReady { get; private set; }
  30. static MenuFileUtility()
  31. {
  32. accMpn.UnionWith(MenuCategories.Skip(1));
  33. GameMain.Instance.StartCoroutine(CheckMenuDataBaseJob());
  34. }
  35. private static IEnumerator CheckMenuDataBaseJob()
  36. {
  37. if (MenuFilesReady) yield break;
  38. while (!GameMain.Instance.MenuDataBase.JobFinished()) yield return null;
  39. MenuFilesReady = true;
  40. MenuFilesReadyChange?.Invoke(null, EventArgs.Empty);
  41. }
  42. private static ref byte[] GetFileBuffer(long size)
  43. {
  44. if (fileBuffer == null) fileBuffer = new byte[Math.Max(500000, size)];
  45. else if (fileBuffer.Length < size) fileBuffer = new byte[size];
  46. return ref fileBuffer;
  47. }
  48. private static byte[] ReadAFileBase(string filename)
  49. {
  50. using AFileBase aFileBase = GameUty.FileOpen(filename);
  51. if (aFileBase.IsValid() && aFileBase.GetSize() != 0)
  52. {
  53. ref byte[] buffer = ref GetFileBuffer(aFileBase.GetSize());
  54. aFileBase.Read(ref buffer, aFileBase.GetSize());
  55. return buffer;
  56. }
  57. Utility.LogError($"AFileBase '{filename}' is invalid");
  58. return null;
  59. }
  60. private static byte[] ReadOfficialMod(string filename)
  61. {
  62. using var fileStream = new FileStream(filename, FileMode.Open);
  63. if (fileStream.Length != 0)
  64. {
  65. ref byte[] buffer = ref GetFileBuffer(fileStream.Length);
  66. fileStream.Read(buffer, 0, (int) fileStream.Length);
  67. return buffer;
  68. }
  69. Utility.LogWarning($"Mod menu file '{filename}' is invalid");
  70. return null;
  71. }
  72. private static IEnumerable<Renderer> GetRenderers(GameObject gameObject)
  73. => gameObject.transform.GetComponentsInChildren<Transform>(true)
  74. .Select(transform => transform.GetComponent<Renderer>())
  75. .Where(renderer => renderer && renderer.material).ToList();
  76. private static bool ProcScriptBin(byte[] menuBuf, out ModelInfo modelInfo)
  77. {
  78. modelInfo = null;
  79. using var binaryReader = new BinaryReader(new MemoryStream(menuBuf), Encoding.UTF8);
  80. if (binaryReader.ReadString() != "CM3D2_MENU") return false;
  81. modelInfo = new ModelInfo();
  82. binaryReader.ReadInt32(); // file version
  83. binaryReader.ReadString(); // txt path
  84. binaryReader.ReadString(); // name
  85. binaryReader.ReadString(); // category
  86. binaryReader.ReadString(); // description
  87. binaryReader.ReadInt32(); // idk (as long)
  88. try
  89. {
  90. while (true)
  91. {
  92. int numberOfProps = binaryReader.ReadByte();
  93. var menuPropString = string.Empty;
  94. if (numberOfProps != 0)
  95. {
  96. for (var i = 0; i < numberOfProps; i++)
  97. {
  98. menuPropString = $"{menuPropString}\"{binaryReader.ReadString()}\"";
  99. }
  100. if (menuPropString != string.Empty)
  101. {
  102. var header = UTY.GetStringCom(menuPropString);
  103. string[] menuProps = UTY.GetStringList(menuPropString);
  104. if (header == "end") break;
  105. switch (header)
  106. {
  107. case "マテリアル変更":
  108. {
  109. var matNo = int.Parse(menuProps[2]);
  110. var materialFile = menuProps[3];
  111. modelInfo.MaterialChanges.Add(new MaterialChange(matNo, materialFile));
  112. break;
  113. }
  114. case "additem":
  115. modelInfo.ModelFile = menuProps[1];
  116. break;
  117. }
  118. }
  119. }
  120. else break;
  121. }
  122. }
  123. catch { return false; }
  124. return true;
  125. }
  126. private static void ProcModScriptBin(byte[] cd, GameObject go)
  127. {
  128. var matDict = new Dictionary<string, byte[]>();
  129. string modData;
  130. using (var binaryReader = new BinaryReader(new MemoryStream(cd), Encoding.UTF8))
  131. {
  132. if (binaryReader.ReadString() != "CM3D2_MOD") return;
  133. binaryReader.ReadInt32();
  134. binaryReader.ReadString();
  135. binaryReader.ReadString();
  136. binaryReader.ReadString();
  137. binaryReader.ReadString();
  138. binaryReader.ReadString();
  139. var mpnValue = binaryReader.ReadString();
  140. var mpn = MPN.null_mpn;
  141. try { mpn = (MPN) Enum.Parse(typeof(MPN), mpnValue, true); }
  142. catch { /* ignored */ }
  143. if (mpn != MPN.null_mpn) binaryReader.ReadString();
  144. modData = binaryReader.ReadString();
  145. var entryCount = binaryReader.ReadInt32();
  146. for (var i = 0; i < entryCount; i++)
  147. {
  148. var key = binaryReader.ReadString();
  149. var count = binaryReader.ReadInt32();
  150. byte[] value = binaryReader.ReadBytes(count);
  151. matDict.Add(key, value);
  152. }
  153. }
  154. var mode = IMode.None;
  155. var materialChange = false;
  156. Material material = null;
  157. var materialIndex = 0;
  158. using var stringReader = new StringReader(modData);
  159. string line;
  160. List<Renderer> renderers = null;
  161. while ((line = stringReader.ReadLine()) != null)
  162. {
  163. string[] data = line.Split(new[] {'\t', ' '}, StringSplitOptions.RemoveEmptyEntries);
  164. switch (data[0])
  165. {
  166. case "アイテム変更":
  167. case "マテリアル変更":
  168. mode = IMode.ItemChange;
  169. break;
  170. case "テクスチャ変更":
  171. mode = IMode.TexChange;
  172. break;
  173. }
  174. switch (mode)
  175. {
  176. case IMode.ItemChange:
  177. {
  178. if (data[0] == "スロット名") materialChange = true;
  179. if (materialChange)
  180. {
  181. if (data[0] == "マテリアル番号")
  182. {
  183. materialIndex = int.Parse(data[1]);
  184. renderers ??= GetRenderers(go).ToList();
  185. foreach (Renderer renderer in renderers)
  186. {
  187. if (materialIndex < renderer.materials.Length)
  188. material = renderer.materials[materialIndex];
  189. }
  190. }
  191. if (!material) continue;
  192. switch (data[0])
  193. {
  194. case "テクスチャ設定":
  195. ChangeTex(materialIndex, data[1], data[2].ToLower());
  196. break;
  197. case "色設定":
  198. material.SetColor(data[1],
  199. new Color(
  200. float.Parse(data[2]) / 255f, float.Parse(data[3]) / 255f,
  201. float.Parse(data[4]) / 255f, float.Parse(data[5]) / 255f
  202. )
  203. );
  204. break;
  205. case "数値設定":
  206. material.SetFloat(data[1], float.Parse(data[2]));
  207. break;
  208. }
  209. }
  210. break;
  211. }
  212. case IMode.TexChange:
  213. {
  214. var matno = int.Parse(data[2]);
  215. ChangeTex(matno, data[3], data[4].ToLower());
  216. break;
  217. }
  218. case IMode.None:
  219. break;
  220. default:
  221. throw new ArgumentOutOfRangeException();
  222. }
  223. }
  224. void ChangeTex(int matno, string prop, string filename)
  225. {
  226. byte[] buf = matDict[filename.ToLowerInvariant()];
  227. var textureResource = new TextureResource(2, 2, TextureFormat.ARGB32, null, buf);
  228. renderers ??= GetRenderers(go).ToList();
  229. foreach (Renderer r in renderers)
  230. {
  231. r.materials[matno].SetTexture(prop, null);
  232. Texture2D texture2D = textureResource.CreateTexture2D();
  233. texture2D.name = filename;
  234. r.materials[matno].SetTexture(prop, texture2D);
  235. }
  236. }
  237. }
  238. public static GameObject LoadModel(string menuFile) => LoadModel(new ModItem(menuFile));
  239. public static GameObject LoadModel(ModItem modItem)
  240. {
  241. var menu = modItem.IsOfficialMod ? modItem.BaseMenuFile : modItem.MenuFile;
  242. byte[] modelBuffer;
  243. try { modelBuffer = ReadAFileBase(menu); }
  244. catch (Exception e)
  245. {
  246. Utility.LogError($"Could not read menu file '{menu}' because {e.Message}\n{e.StackTrace}");
  247. return null;
  248. }
  249. if (ProcScriptBin(modelBuffer, out ModelInfo modelInfo))
  250. {
  251. if (InstantiateModel(modelInfo.ModelFile, out GameObject finalModel))
  252. {
  253. IEnumerable<Renderer> renderers = GetRenderers(finalModel).ToList();
  254. foreach (MaterialChange matChange in modelInfo.MaterialChanges)
  255. {
  256. foreach (Renderer renderer in renderers)
  257. {
  258. if (matChange.MaterialIndex < renderer.materials.Length)
  259. {
  260. renderer.materials[matChange.MaterialIndex] = ImportCM.LoadMaterial(
  261. matChange.MaterialFile, null, renderer.materials[matChange.MaterialIndex]
  262. );
  263. }
  264. }
  265. }
  266. if (!modItem.IsOfficialMod) return finalModel;
  267. try { modelBuffer = ReadOfficialMod(modItem.MenuFile); }
  268. catch (Exception e)
  269. {
  270. Utility.LogError(
  271. $"Could not read mod menu file '{modItem.MenuFile}' because {e.Message}\n{e.StackTrace}"
  272. );
  273. return null;
  274. }
  275. ProcModScriptBin(modelBuffer, finalModel);
  276. return finalModel;
  277. }
  278. }
  279. Utility.LogMessage($"Could not load model '{modItem.MenuFile}'");
  280. return null;
  281. }
  282. public static bool ParseNativeMenuFile(int menuIndex, ModItem modItem)
  283. {
  284. MenuDataBase menuDataBase = GameMain.Instance.MenuDataBase;
  285. menuDataBase.SetIndex(menuIndex);
  286. if (menuDataBase.GetBoDelOnly()) return false;
  287. modItem.Category = menuDataBase.GetCategoryMpnText();
  288. if (!accMpn.Contains(modItem.Category)) return false;
  289. modItem.MenuFile = menuDataBase.GetMenuFileName().ToLower();
  290. if (!ValidBG2MenuFile(modItem.MenuFile)) return false;
  291. modItem.Name = menuDataBase.GetMenuName();
  292. modItem.IconFile = menuDataBase.GetIconS();
  293. modItem.Priority = menuDataBase.GetPriority();
  294. return true;
  295. }
  296. public static void ParseMenuFile(string menuFile, ModItem modItem)
  297. {
  298. if (!ValidBG2MenuFile(menuFile)) return;
  299. byte[] buffer;
  300. try { buffer = ReadAFileBase(menuFile); }
  301. catch (Exception e)
  302. {
  303. Utility.LogError($"Could not read menu file '{menuFile}' because {e.Message}");
  304. return ;
  305. }
  306. try
  307. {
  308. using var binaryReader = new BinaryReader(new MemoryStream(buffer), Encoding.UTF8);
  309. if (binaryReader.ReadString() != "CM3D2_MENU") return;
  310. binaryReader.ReadInt32(); // file version
  311. binaryReader.ReadString(); // txt path
  312. modItem.Name = binaryReader.ReadString(); // name
  313. binaryReader.ReadString(); // category
  314. binaryReader.ReadString(); // description
  315. binaryReader.ReadInt32(); // idk (as long)
  316. while (true)
  317. {
  318. int numberOfProps = binaryReader.ReadByte();
  319. var menuPropString = string.Empty;
  320. if (numberOfProps == 0) break;
  321. for (var i = 0; i < numberOfProps; i++)
  322. {
  323. menuPropString = $"{menuPropString}\"{binaryReader.ReadString()}\"";
  324. }
  325. if (string.IsNullOrEmpty(menuPropString)) continue;
  326. var header = UTY.GetStringCom(menuPropString);
  327. string[] menuProps = UTY.GetStringList(menuPropString);
  328. if (header == "end") break;
  329. if (header == "category")
  330. {
  331. modItem.Category = menuProps[1];
  332. if (!accMpn.Contains(modItem.Category)) return;
  333. }
  334. else if (header == "icons" || header == "icon")
  335. {
  336. modItem.IconFile = menuProps[1];
  337. break;
  338. }
  339. else if (header == "priority") modItem.Priority = float.Parse(menuProps[1]);
  340. }
  341. }
  342. catch (Exception e)
  343. {
  344. Utility.LogWarning($"Could not parse menu file '{menuFile}' because {e.Message}");
  345. }
  346. }
  347. public static bool ParseModMenuFile(string modMenuFile, ModItem modItem)
  348. {
  349. if (!ValidBG2MenuFile(modMenuFile)) return false;
  350. byte[] modBuffer;
  351. try { modBuffer = ReadOfficialMod(modMenuFile); }
  352. catch (Exception e)
  353. {
  354. Utility.LogError($"Could not read mod menu file '{modMenuFile} because {e.Message}'");
  355. return false;
  356. }
  357. try
  358. {
  359. using var binaryReader = new BinaryReader(new MemoryStream(modBuffer), Encoding.UTF8);
  360. if (binaryReader.ReadString() != "CM3D2_MOD") return false;
  361. binaryReader.ReadInt32();
  362. var iconName = binaryReader.ReadString();
  363. var baseItemPath = binaryReader.ReadString().Replace(":", " ");
  364. modItem.BaseMenuFile = Path.GetFileName(baseItemPath);
  365. modItem.Name = binaryReader.ReadString();
  366. modItem.Category = binaryReader.ReadString();
  367. if (!accMpn.Contains(modItem.Category)) return false;
  368. binaryReader.ReadString();
  369. var mpnValue = binaryReader.ReadString();
  370. var mpn = MPN.null_mpn;
  371. try { mpn = (MPN) Enum.Parse(typeof(MPN), mpnValue, true); }
  372. catch { /* ignored */ }
  373. if (mpn != MPN.null_mpn) binaryReader.ReadString();
  374. binaryReader.ReadString();
  375. var entryCount = binaryReader.ReadInt32();
  376. for (var i = 0; i < entryCount; i++)
  377. {
  378. var key = binaryReader.ReadString();
  379. var count = binaryReader.ReadInt32();
  380. byte[] data = binaryReader.ReadBytes(count);
  381. if (!string.Equals(key, iconName, StringComparison.InvariantCultureIgnoreCase)) continue;
  382. var tex = new Texture2D(1, 1, TextureFormat.RGBA32, false);
  383. tex.LoadImage(data);
  384. modItem.Icon = tex;
  385. break;
  386. }
  387. }
  388. catch (Exception e)
  389. {
  390. Utility.LogWarning($"Could not parse mod menu file '{modMenuFile}' because {e}");
  391. return false;
  392. }
  393. return true;
  394. }
  395. public static bool ValidBG2MenuFile(ModItem modItem)
  396. => accMpn.Contains(modItem.Category) && ValidBG2MenuFile(modItem.MenuFile);
  397. public static bool ValidBG2MenuFile(string menu)
  398. {
  399. menu = Path.GetFileNameWithoutExtension(menu).ToLower();
  400. return !(menu.EndsWith("_del") || menu.Contains("zurashi") || menu.Contains("mekure")
  401. || menu.Contains("porori") || menu.Contains("moza") || menu.Contains("folder"));
  402. }
  403. public abstract class MenuItem
  404. {
  405. public string IconFile { get; set; }
  406. public Texture2D Icon { get; set; }
  407. }
  408. public class ModItem : MenuItem
  409. {
  410. public string MenuFile { get; set; }
  411. public string BaseMenuFile { get; set; }
  412. public string Name { get; set; }
  413. public string Category { get; set; }
  414. public float Priority { get; set; }
  415. public bool IsMod { get; private set; }
  416. public bool IsOfficialMod { get; private set; }
  417. public static ModItem OfficialMod(string menuFile) => new ModItem()
  418. {
  419. MenuFile = menuFile,
  420. IsMod = true,
  421. IsOfficialMod = true,
  422. Priority = 1000f
  423. };
  424. public static ModItem Mod(string menuFile) => new ModItem()
  425. {
  426. MenuFile = menuFile,
  427. IsMod = true
  428. };
  429. public ModItem() { }
  430. public ModItem(string menuFile) => MenuFile = menuFile;
  431. public override string ToString()
  432. => IsOfficialMod ? $"{Path.GetFileName(MenuFile)}#{BaseMenuFile}" : MenuFile;
  433. public static ModItem Deserialize(BinaryReader binaryReader)
  434. => new ModItem()
  435. {
  436. MenuFile = binaryReader.ReadNullableString(),
  437. BaseMenuFile = binaryReader.ReadNullableString(),
  438. IconFile = binaryReader.ReadNullableString(),
  439. Name = binaryReader.ReadNullableString(),
  440. Category = binaryReader.ReadNullableString(),
  441. Priority = float.Parse(binaryReader.ReadNullableString()),
  442. IsMod = binaryReader.ReadBoolean(),
  443. IsOfficialMod = binaryReader.ReadBoolean()
  444. };
  445. public void Serialize(BinaryWriter binaryWriter)
  446. {
  447. if (IsOfficialMod) return;
  448. binaryWriter.WriteNullableString(MenuFile);
  449. binaryWriter.WriteNullableString(BaseMenuFile);
  450. binaryWriter.WriteNullableString(IconFile);
  451. binaryWriter.WriteNullableString(Name);
  452. binaryWriter.WriteNullableString(Category);
  453. binaryWriter.WriteNullableString(Priority.ToString(CultureInfo.InvariantCulture));
  454. binaryWriter.Write(IsMod);
  455. binaryWriter.Write(IsOfficialMod);
  456. }
  457. }
  458. public class MyRoomItem : MenuItem
  459. {
  460. public int ID { get; set; }
  461. public string PrefabName { get; set; }
  462. public override string ToString() => $"MYR_{ID}#{PrefabName}";
  463. }
  464. private class ModelInfo
  465. {
  466. public List<MaterialChange> MaterialChanges { get; } = new List<MaterialChange>();
  467. public string ModelFile { get; set; }
  468. }
  469. private readonly struct MaterialChange
  470. {
  471. public int MaterialIndex { get; }
  472. public string MaterialFile { get; }
  473. public MaterialChange(int materialIndex, string materialFile)
  474. {
  475. MaterialIndex = materialIndex;
  476. MaterialFile = materialFile;
  477. }
  478. }
  479. }
  480. }