CsvToLua.cs 20 KB

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