CsvToLua.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.IO;
  5. using UnityEditor;
  6. using System.Text;
  7. using System;
  8. using Game.Config;
  9. using RO.Editor;
  10. using LuaInterface;
  11. using System.Linq;
  12. using System.Text.RegularExpressions;
  13. public class CfgLanguageCfg : GameData<CfgLanguageCfg>
  14. {
  15. public string CfgName;
  16. public string Field;
  17. public string CfgID;
  18. public int CfgType;
  19. public CfgLanguageCfg()
  20. {
  21. CfgName = "";
  22. Field = "";
  23. CfgID = "";
  24. CfgType = 0;
  25. }
  26. public static void OnCsvLoad(CsvReader csvReader)
  27. {
  28. CfgLanguageCfg.Onload(csvReader);
  29. }
  30. public static string FileName_S()
  31. {
  32. return "";
  33. }
  34. }
  35. public class LanguageCfg : GameData<LanguageCfg>
  36. {
  37. public string key;
  38. public string Language;
  39. public LanguageCfg()
  40. {
  41. key = "";
  42. Language = "";
  43. }
  44. public static void OnCsvLoad(CsvReader csvReader)
  45. {
  46. LanguageCfg.Onload(csvReader);
  47. }
  48. public static string FileName_S()
  49. {
  50. return "";
  51. }
  52. }
  53. public class CsvToLua : EditorWindow
  54. {
  55. public static string CSV_PATH = "csv path";
  56. public static string LUA_PATH = "lua path";
  57. public static string START_LINE = "start line";
  58. public string tableDirectoryName;
  59. public string luaDirectoryName;
  60. public int startDataLine = 1;
  61. public static bool IsObj;
  62. [MenuItem("Tools/CsvToLua")]
  63. static void Init()
  64. {
  65. CsvToLua window = (CsvToLua)GetWindow(typeof(CsvToLua));
  66. window.Show();
  67. }
  68. void OnEnable()
  69. {
  70. tableDirectoryName = EditorPrefs.GetString(CSV_PATH);
  71. luaDirectoryName = EditorPrefs.GetString(LUA_PATH);
  72. startDataLine = EditorPrefs.GetInt(START_LINE);
  73. }
  74. void OnDisable()
  75. {
  76. EditorPrefs.SetString(CSV_PATH, tableDirectoryName);
  77. EditorPrefs.SetString(LUA_PATH, luaDirectoryName);
  78. EditorPrefs.SetInt(START_LINE, startDataLine);
  79. }
  80. private void OnGUI()
  81. {
  82. GUILayout.Label("Base Settings", EditorStyles.boldLabel);
  83. EditorGUILayout.BeginHorizontal();
  84. tableDirectoryName = EditorGUILayout.TextField("TableDirectory Name", tableDirectoryName);
  85. if (GUILayout.Button("选择csv路径", GUILayout.Width(200)))
  86. {
  87. tableDirectoryName = GetFilePath();
  88. }
  89. EditorGUILayout.EndHorizontal();
  90. EditorGUILayout.BeginHorizontal();
  91. luaDirectoryName = EditorGUILayout.TextField("LuaDirectory Name", luaDirectoryName);
  92. if (GUILayout.Button("选择到处table路径", GUILayout.Width(200)))
  93. {
  94. luaDirectoryName = GetFilePath();
  95. }
  96. EditorGUILayout.EndHorizontal();
  97. startDataLine = EditorGUILayout.IntField("StartDataLine", startDataLine);
  98. if (GUILayout.Button("CsvToLua"))
  99. Change();
  100. if (GUILayout.Button("测试"))
  101. {
  102. string lua = @"local aaa =
  103. {
  104. [1] =
  105. {
  106. ['a'] = 1,
  107. ['b'] = '2',
  108. ['c'] = 'asd' ,
  109. ['d'] = {1,2,3,{{1,2},{3,4},{1.2,0},{0}}},
  110. ['aId'] = 1,
  111. } ,
  112. }
  113. return aaa";
  114. using (LuaState runTime = new LuaState())
  115. {
  116. runTime.Start();
  117. //LuaState runTime = LuaClient.Instance.luaState;
  118. runTime.DoFile("Assets\\Editor\\CsvToLua\\table-save.lua");
  119. LuaTable luaTable = runTime.DoString<LuaTable>(lua);
  120. RolePreviewWindow.SaveToLua(runTime, "aaa.lua", luaTable, "AAA","");
  121. }
  122. }
  123. if (GUILayout.Button("检查"))
  124. {
  125. CheckCgf();
  126. }
  127. IsObj = GUILayout.Toggle(IsObj,"运行时启动");
  128. }
  129. public static string GetFilePath()
  130. {
  131. OpenDialogDir ofn2 = new OpenDialogDir();
  132. ofn2.pszDisplayName = new string(new char[2000]); ; // 存放目录路径缓冲区
  133. ofn2.lpszTitle = "Open Project";// 标题
  134. //ofn2.ulFlags = BIF_NEWDIALOGSTYLE | BIF_EDITBOX; // 新的样式,带编辑框
  135. IntPtr pidlPtr = DllOpenFileDialog.SHBrowseForFolder(ofn2);
  136. char[] charArray = new char[2000];
  137. for (int i = 0; i < 2000; i++)
  138. charArray[i] = '\0';
  139. DllOpenFileDialog.SHGetPathFromIDList(pidlPtr, charArray);
  140. string fullDirPath = new String(charArray);
  141. fullDirPath = fullDirPath.Substring(0, fullDirPath.IndexOf('\0'));
  142. return fullDirPath;
  143. }
  144. public void Change()
  145. {
  146. Debug.Log(tableDirectoryName);
  147. foreach (var item in Directory.GetFiles(tableDirectoryName))
  148. {
  149. if (item.Contains(".meta"))
  150. continue;
  151. CreatLuaTable(item);
  152. }
  153. }
  154. void CreatLuaTable(string filePath)
  155. {
  156. CreatDirectory();
  157. Save(GetSavePath(filePath), GetSaveContext(filePath));
  158. }
  159. void CreatDirectory()
  160. {
  161. string path = luaDirectoryName;
  162. if (!Directory.Exists(path))
  163. {
  164. Directory.CreateDirectory(path);
  165. AssetDatabase.Refresh();
  166. }
  167. }
  168. string GetSavePath(string filePath)
  169. {
  170. string fileName = GetFileName(filePath);
  171. return luaDirectoryName + "/" + fileName + ".lua";
  172. }
  173. string GetFileName(string filePath)
  174. {
  175. string targetPath = filePath.Replace(@"\", "/");
  176. string[] strs = targetPath.Split('/');
  177. targetPath = strs[strs.Length - 1];
  178. strs = targetPath.Split('.');
  179. string fileName = strs[0];
  180. return fileName;
  181. }
  182. string GetSaveContext(string filePath)
  183. {
  184. string fileName = GetFileName(filePath);
  185. List<string> context = GetContext(filePath);
  186. string[] propertyName = GetPropertyName(context[1]);
  187. string[] typeName = GetPropertyName(context[2]);
  188. StringBuilder sb = new StringBuilder();
  189. sb.Append("local " + fileName + " = {" + "\n");
  190. for (int i = startDataLine; i < context.Count; i++)
  191. {
  192. context[i] = context[i].Replace(" ", "");
  193. string[] details = context[i].Split(',');
  194. sb.Append("[" + details[0] + "]={" + "\n");
  195. for (int j = 0; j < propertyName.Length; j++)
  196. {
  197. sb.Append("['" + propertyName[j] + "']=");
  198. if (typeName[j].Equals("string"))
  199. sb.Append("'" + details[j] + "'," + "\n");
  200. else if (typeName[j].Equals("bool"))
  201. {
  202. sb.Append(details[j].ToLower() + "," + "\n");
  203. }
  204. else if (typeName[j].Equals("list"))
  205. {
  206. if (details[j].IndexOf(';') > 0)
  207. {
  208. ParseTable(sb, details[j], ';');
  209. }
  210. else if (details[j].IndexOf(':') > 0 && details[j].IndexOf(';') < 0)
  211. {
  212. sb.Append("{");
  213. ParseTable(sb, details[j], ':');
  214. sb.Append("}");
  215. }
  216. else
  217. {
  218. sb.Append("{");
  219. try
  220. {
  221. if (details[j].IndexOf('.') > 0)
  222. {
  223. Convert.ToDouble(details[j]);
  224. }
  225. else
  226. {
  227. Convert.ToInt32(details[j]);
  228. }
  229. sb.Append(details[j]);
  230. }
  231. catch
  232. {
  233. if (!string.IsNullOrEmpty(details[j]))
  234. sb.Append("'" + details[j] + "'");
  235. }
  236. sb.Append("}");
  237. }
  238. sb.Append(",\n");
  239. }
  240. else if (typeName[j].Equals("enum"))
  241. {
  242. sb.Append("Enum." + propertyName[j] + "." + details[j] + "," + "\n");
  243. }
  244. else
  245. {
  246. string num = "0";
  247. if (details[j] != "")
  248. {
  249. num = details[j];
  250. }
  251. sb.Append(num + "," + "\n");
  252. }
  253. }
  254. sb.Append("}," + "\n");
  255. }
  256. sb.Append("}" + "\n");
  257. sb.Append("return " + fileName);
  258. return sb.ToString();
  259. }
  260. void ParseTable(StringBuilder sb, string content, char split)
  261. {
  262. string[] strs = content.Split(split);
  263. sb.Append("{");
  264. for (int m = 0; m < strs.Length; ++m)
  265. {
  266. try
  267. {
  268. if (strs[m].IndexOf(':') > 0)
  269. {
  270. ParseTable(sb, strs[m], ':');
  271. }
  272. else
  273. {
  274. if (strs[m].IndexOf('.') > 0)
  275. {
  276. Convert.ToDouble(strs[m]);
  277. }
  278. else
  279. {
  280. Convert.ToInt32(strs[m]);
  281. }
  282. sb.Append(strs[m]);
  283. }
  284. }
  285. catch
  286. {
  287. if (!string.IsNullOrEmpty(strs[m]))
  288. sb.Append("'" + strs[m] + "'");
  289. }
  290. if (m < strs.Length - 1)
  291. {
  292. sb.Append(",");
  293. }
  294. }
  295. sb.Append("}");
  296. }
  297. List<string> GetContext(string filePath)
  298. {
  299. StreamReader sr = new StreamReader(filePath);
  300. List<string> contexts = new List<string>();
  301. string line;
  302. while ((line = sr.ReadLine()) != null)
  303. contexts.Add(line);
  304. return contexts;
  305. }
  306. string[] GetPropertyName(string line)
  307. {
  308. string[] names = line.Split(',');
  309. return names;
  310. }
  311. void Save(string path, string information)
  312. {
  313. if (File.Exists(path))
  314. File.Delete(path);
  315. FileStream aFile = new FileStream(@"" + path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  316. StreamWriter sw = new StreamWriter(aFile);
  317. sw.Write(information);
  318. sw.Close();
  319. sw.Dispose();
  320. aFile.Close();
  321. aFile.Dispose();
  322. sw = null;
  323. aFile = null;
  324. AssetDatabase.Refresh();
  325. }
  326. public static Dictionary<string, List<CfgLanguageCfg>> GetCfgLanguageCfg(string path)
  327. {
  328. Dictionary<string, List<CfgLanguageCfg>> ret = new Dictionary<string, List<CfgLanguageCfg>>();
  329. TextAsset ta = AssetDatabase.LoadAssetAtPath<TextAsset>(path);
  330. CsvReader csvReader = new CsvReader(CfgLanguageCfg.FileName_S(), ta.bytes);
  331. CfgLanguageCfg.OnCsvLoad(csvReader);
  332. CfgLanguageCfg.Foreach(it =>
  333. {
  334. if (ret.ContainsKey(it.CfgName))
  335. {
  336. ret[it.CfgName].Add(it);
  337. }
  338. else
  339. {
  340. List<CfgLanguageCfg> cfgs = new List<CfgLanguageCfg>();
  341. cfgs.Add(it);
  342. ret.Add(it.CfgName,cfgs);
  343. }
  344. //Debug.Log(it.BaseName);
  345. });
  346. CfgLanguageCfg.Clear();
  347. return ret;
  348. }
  349. public static Dictionary<string, LanguageCfg> GetLanguageCfg(string path)
  350. {
  351. Dictionary<string, LanguageCfg> ret = new Dictionary<string, LanguageCfg>();
  352. TextAsset ta = AssetDatabase.LoadAssetAtPath<TextAsset>(path);
  353. CsvReader csvReader = new CsvReader(LanguageCfg.FileName_S(), ta.bytes,1,2,3);
  354. LanguageCfg.OnCsvLoad(csvReader);
  355. LanguageCfg.Foreach(it =>
  356. {
  357. if (!ret.ContainsKey(it.key))
  358. {
  359. ret.Add(it.key, it);
  360. }
  361. else
  362. {
  363. ret.Add(it.key+ret.Count,it);
  364. Debug.Log("重复项:" + it.key);
  365. }
  366. //Debug.Log(it.BaseName);
  367. });
  368. LanguageCfg.Clear(false);
  369. return ret;
  370. }
  371. public static void CheckCgf()
  372. {
  373. string luaPath = "Assets/Lua/Config/";
  374. string csvPath = "Assets/Content/Config/";
  375. string OutPutPath = "Build/NewCfg/";
  376. Dictionary<string, List<CfgLanguageCfg>> cfgs = GetCfgLanguageCfg("Assets/Editor/CsvToLua/CfgLanguageCfg.csv");
  377. Dictionary<string, LanguageCfg> language = GetLanguageCfg("Assets/Content/Config/LanguagePackage_cn.csv");
  378. float ckcount = 0;
  379. foreach (var item in cfgs)
  380. {
  381. ckcount+=1;
  382. List<CfgLanguageCfg> value = item.Value;
  383. EditorUtility.DisplayProgressBar("检测配置中", $"检测:{item.Key}...", ckcount/cfgs.Count);
  384. string cfgPath = "";
  385. if (value[0].CfgType == 1)
  386. {
  387. cfgPath = luaPath + item.Key + ".lua";
  388. CheckLauCfg_CS(value,cfgPath,language, $"{OutPutPath}lua/{value[0].CfgName}.lua");
  389. }
  390. else
  391. {
  392. cfgPath = csvPath + item.Key + ".csv";
  393. CheckCsvCfg(value, cfgPath, language, $"{OutPutPath}csv/{value[0].CfgName}.csv");
  394. }
  395. }
  396. EditorUtility.ClearProgressBar();
  397. CsvWriter<LanguageCfg> csvWriter = new CsvWriter<LanguageCfg>(OutPutPath+ "Language.csv", "Language.csv",language.Values.ToList(), LanguageCfg.GetFormatInfo());
  398. csvWriter.Write();
  399. }
  400. private static void CheckLauCfg(List<CfgLanguageCfg> cfg,string path, Dictionary<string, LanguageCfg> language,string outputPath)
  401. {
  402. using (LuaState runTime = new LuaState())
  403. {
  404. runTime.Start();
  405. RolePreviewWindow.LuaForEach<int, LuaTable>(runTime, path, (id,luatable) =>
  406. {
  407. for (int i = 0; i < cfg.Count; i++)
  408. {
  409. string value = luatable.RawGet<string, string>(cfg[i].Field);
  410. if (string.IsNullOrEmpty(value))
  411. {
  412. continue;
  413. }
  414. KeyValuePair<string,LanguageCfg> valuePair = language.FirstOrDefault(it =>
  415. {
  416. return string.Equals(it.Value.Language, value);
  417. });
  418. if (!string.IsNullOrEmpty(valuePair.Key))
  419. {
  420. luatable.RawSet<string, string>(cfg[i].Field, valuePair.Key);
  421. }
  422. else
  423. {
  424. string key = cfg[i].CfgID + id;
  425. luatable.RawSet<string, string>(cfg[i].Field, key);
  426. if (value.Contains("\n"))
  427. {
  428. Debug.Log(value);
  429. value = value.Replace("\n","\\n");
  430. Debug.Log(value);
  431. }
  432. language.Add(key,new LanguageCfg() { key = key,Language = value});
  433. }
  434. }
  435. },(ltab)=>
  436. {
  437. bool useObj = IsObj;
  438. if (useObj)
  439. {
  440. LuaState luaState = LuaClient.Instance.luaState;
  441. luaState.DoFile("Assets\\Editor\\CsvToLua\\table-save.lua");
  442. RolePreviewWindow.SaveToLua(luaState, outputPath, ltab, cfg[0].CfgName, "1");
  443. }
  444. else
  445. {
  446. LuaState luaState = runTime;
  447. luaState.DoFile("Assets\\Editor\\CsvToLua\\table-save.lua");
  448. RolePreviewWindow.SaveToLua(luaState, outputPath, ltab, cfg[0].CfgName, "");
  449. }
  450. });
  451. }
  452. }
  453. private static void SetLuaLine(string[] rowDatas,int id,string key,string data)
  454. {
  455. string idkey = $"[{id}]";
  456. string keykey = $"'{key}'";
  457. string wdata = $"'{data}',";
  458. bool isFind = false;
  459. for (int line = 0; line < rowDatas.Length; line++)
  460. {
  461. if (rowDatas[line].Trim().IndexOf("--") == 0)
  462. {
  463. Debug.Log("注释跳过");
  464. }
  465. if (rowDatas[line].Contains(idkey))
  466. {
  467. isFind = true;
  468. }
  469. if (isFind && rowDatas[line].Contains(keykey))
  470. {
  471. int s = rowDatas[line].IndexOf('[');
  472. string p = "";
  473. if (s > 0)
  474. {
  475. for (int i = 0; i < s; i++)
  476. {
  477. p += " ";
  478. }
  479. }
  480. string newstr = $"{p}[{keykey}]={wdata}" ;
  481. rowDatas[line] = newstr;
  482. break;
  483. }
  484. }
  485. }
  486. private static void CheckLauCfg_CS(List<CfgLanguageCfg> cfg, string path, Dictionary<string, LanguageCfg> language, string outputPath)
  487. {
  488. string[] rowDatas = File.ReadAllLines(path);
  489. using (LuaState runTime = new LuaState())
  490. {
  491. runTime.Start();
  492. RolePreviewWindow.LuaForEach<int, LuaTable>(runTime, path, (id, luatable) =>
  493. {
  494. for (int i = 0; i < cfg.Count; i++)
  495. {
  496. string value = luatable.RawGet<string, string>(cfg[i].Field);
  497. if (string.IsNullOrEmpty(value))
  498. {
  499. continue;
  500. }
  501. KeyValuePair<string, LanguageCfg> valuePair = language.FirstOrDefault(it =>
  502. {
  503. return string.Equals(it.Value.Language, value);
  504. });
  505. if (!string.IsNullOrEmpty(valuePair.Key))
  506. {
  507. luatable.RawSet<string, string>(cfg[i].Field, valuePair.Key);
  508. SetLuaLine(rowDatas,id, cfg[i].Field, valuePair.Key);
  509. }
  510. else
  511. {
  512. string key = cfg[i].CfgID + id;
  513. luatable.RawSet<string, string>(cfg[i].Field, key);
  514. SetLuaLine(rowDatas, id, cfg[i].Field, key);
  515. if (value.Contains("\n"))
  516. {
  517. Debug.Log(value);
  518. value = value.Replace("\n", "\\n");
  519. Debug.Log(value);
  520. }
  521. language.Add(key, new LanguageCfg() { key = key, Language = value });
  522. }
  523. }
  524. });
  525. }
  526. File.WriteAllLines(outputPath,rowDatas);
  527. }
  528. private static void CheckCsvCfg(List<CfgLanguageCfg> cfg, string path, Dictionary<string, LanguageCfg> language, string outputPath)
  529. {
  530. CsvReader csvReader = new CsvReader(path,1,2,3);
  531. string[][] datas = csvReader.RowDatas;
  532. for (int i = csvReader.StartLine; i < datas.Length; i++)
  533. {
  534. string[] curLine = datas[i];
  535. for (int j = 0; j < cfg.Count; j++)
  536. {
  537. string value = csvReader.GetDataByFieldName(cfg[j].Field,i);
  538. if (string.IsNullOrEmpty(value))
  539. {
  540. continue;
  541. }
  542. KeyValuePair<string, LanguageCfg> valuePair = language.FirstOrDefault(it =>
  543. {
  544. return string.Equals(it.Value.Language, value);
  545. });
  546. if (!string.IsNullOrEmpty(valuePair.Key))
  547. {
  548. csvReader.SetDataByFieldName(cfg[j].Field, valuePair.Key, i);
  549. }
  550. else
  551. {
  552. string key = cfg[j].CfgID + i;
  553. csvReader.SetDataByFieldName(cfg[j].Field, key,i);
  554. language.Add(key, new LanguageCfg() { key = key, Language = value });
  555. }
  556. }
  557. }
  558. FileHelper.WirteStringToFile(outputPath,csvReader.GetString());
  559. }
  560. }