Proto2CS.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace ET
  7. {
  8. internal class OpcodeInfo
  9. {
  10. public string Name;
  11. public int Opcode;
  12. }
  13. public static class Proto2CS
  14. {
  15. public static void Export()
  16. {
  17. InnerProto2CS.Proto2CS();
  18. }
  19. }
  20. public static partial class InnerProto2CS
  21. {
  22. private const string clientMessagePath = "../Generate/Client/Proto/";
  23. private const string serverMessagePath = "../Generate/Server/Proto/";
  24. private const string clientServerMessagePath = "../Generate/ClientServer/Proto/";
  25. private static readonly char[] splitChars = [' ', '\t'];
  26. private static readonly List<OpcodeInfo> msgOpcode = [];
  27. public static void Proto2CS()
  28. {
  29. msgOpcode.Clear();
  30. if (!Directory.Exists(clientMessagePath))
  31. {
  32. Directory.CreateDirectory(clientMessagePath);
  33. }
  34. if (!Directory.Exists(serverMessagePath))
  35. {
  36. Directory.CreateDirectory(serverMessagePath);
  37. }
  38. if (!Directory.Exists(clientServerMessagePath))
  39. {
  40. Directory.CreateDirectory(clientServerMessagePath);
  41. }
  42. RemoveAllFilesExceptMeta(clientMessagePath);
  43. RemoveAllFilesExceptMeta(serverMessagePath);
  44. RemoveAllFilesExceptMeta(clientServerMessagePath);
  45. System.Collections.Generic.List<(string, string)> list = new ();
  46. foreach (string directory in Directory.GetDirectories("../Unity/Packages", "com.et.*"))
  47. {
  48. string p = Path.Combine(directory, "Proto");
  49. if (!Directory.Exists(p))
  50. {
  51. continue;
  52. }
  53. string baseName = Path.GetFileName(directory);
  54. string moduleName = baseName.Substring(7);
  55. moduleName = StringHelper.CapitalizeFirstLetter(moduleName);
  56. list.Add((p, moduleName));
  57. }
  58. foreach (string directory in Directory.GetDirectories("../Unity/Library/PackageCache", "com.et.*"))
  59. {
  60. string p = Path.Combine(directory, "Proto");
  61. if (!Directory.Exists(p))
  62. {
  63. continue;
  64. }
  65. string baseName = Path.GetFileName(directory);
  66. string moduleName = baseName.Substring(7);
  67. moduleName = StringHelper.CapitalizeFirstLetter(moduleName);
  68. list.Add((p, moduleName));
  69. }
  70. System.Collections.Generic.List<(string, string)> protoList = new ();
  71. foreach ((string s, string module) in list)
  72. {
  73. foreach (var f in FileHelper.GetAllFiles(s, "*.proto"))
  74. {
  75. protoList.Add((f, module));
  76. }
  77. }
  78. foreach ((string s, string module) in protoList)
  79. {
  80. if (!s.EndsWith(".proto"))
  81. {
  82. continue;
  83. }
  84. string fileName = Path.GetFileNameWithoutExtension(s);
  85. string[] ss2 = fileName.Split('_');
  86. string protoName = ss2[0];
  87. string cs = ss2[1];
  88. int startOpcode = int.Parse(ss2[2]);
  89. ProtoFile2CS(s, module, protoName, cs, startOpcode);
  90. }
  91. RemoveUnusedMetaFiles(clientMessagePath);
  92. RemoveUnusedMetaFiles(serverMessagePath);
  93. RemoveUnusedMetaFiles(clientServerMessagePath);
  94. }
  95. private static void ProtoFile2CS(string path, string module, string protoName, string cs, int startOpcode)
  96. {
  97. msgOpcode.Clear();
  98. string proto = path;
  99. string s = File.ReadAllText(proto);
  100. StringBuilder sb = new();
  101. sb.Append("using MemoryPack;\n");
  102. sb.Append("using System.Collections.Generic;\n\n");
  103. sb.Append($"namespace ET\n");
  104. sb.Append("{\n");
  105. bool isMsgStart = false;
  106. string msgName = "";
  107. string responseType = "";
  108. StringBuilder sbDispose = new();
  109. Regex responseTypeRegex = ResponseTypeRegex();
  110. foreach (string line in s.Split('\n'))
  111. {
  112. string newline = line.Trim();
  113. if (string.IsNullOrEmpty(newline))
  114. {
  115. continue;
  116. }
  117. if (responseTypeRegex.IsMatch(newline))
  118. {
  119. responseType = responseTypeRegex.Replace(newline, string.Empty);
  120. responseType = responseType.Trim().Split(' ')[0].TrimEnd('\r', '\n');
  121. continue;
  122. }
  123. if (!isMsgStart && newline.StartsWith("//"))
  124. {
  125. if (newline.StartsWith("///"))
  126. {
  127. sb.Append("\t/// <summary>\n");
  128. sb.Append($"\t/// {newline.TrimStart('/', ' ')}\n");
  129. sb.Append("\t/// </summary>\n");
  130. }
  131. else
  132. {
  133. sb.Append($"\t// {newline.TrimStart('/', ' ')}\n");
  134. }
  135. continue;
  136. }
  137. if (newline.StartsWith("message"))
  138. {
  139. isMsgStart = true;
  140. string parentClass = "";
  141. msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
  142. string[] ss = newline.Split(["//"], StringSplitOptions.RemoveEmptyEntries);
  143. if (ss.Length == 2)
  144. {
  145. parentClass = ss[1].Trim();
  146. }
  147. msgOpcode.Add(new OpcodeInfo() { Name = msgName, Opcode = ++startOpcode });
  148. sb.Append($"\t[MemoryPackable]\n");
  149. sb.Append($"\t[Message({protoName}.{msgName})]\n");
  150. if (!string.IsNullOrEmpty(responseType))
  151. {
  152. sb.Append($"\t[ResponseType(nameof({responseType}))]\n");
  153. }
  154. sb.Append($"\tpublic partial class {msgName} : MessageObject");
  155. if (parentClass is "IActorMessage" or "IActorRequest" or "IActorResponse")
  156. {
  157. sb.Append($", {parentClass}\n");
  158. }
  159. else if (parentClass != "")
  160. {
  161. sb.Append($", {parentClass}\n");
  162. }
  163. else
  164. {
  165. sb.Append('\n');
  166. }
  167. continue;
  168. }
  169. if (isMsgStart)
  170. {
  171. if (newline.StartsWith('{'))
  172. {
  173. sbDispose.Clear();
  174. sb.Append("\t{\n");
  175. sb.Append($"\t\tpublic static {msgName} Create(bool isFromPool = false)\n\t\t{{\n\t\t\treturn ObjectPool.Fetch<{msgName}>(isFromPool);\n\t\t}}\n\n");
  176. continue;
  177. }
  178. if (newline.StartsWith('}'))
  179. {
  180. isMsgStart = false;
  181. responseType = "";
  182. // 加了no dispose则自己去定义dispose函数,不要自动生成
  183. if (!newline.Contains("// no dispose"))
  184. {
  185. sb.Append($"\t\tpublic override void Dispose()\n\t\t{{\n\t\t\tif (!this.IsFromPool)\n\t\t\t{{\n\t\t\t\treturn;\n\t\t\t}}\n\n\t\t\t{sbDispose.ToString().TrimEnd('\t')}\n\t\t\tObjectPool.Recycle(this);\n\t\t}}\n");
  186. }
  187. sb.Append("\t}\n\n");
  188. continue;
  189. }
  190. if (newline.StartsWith("//"))
  191. {
  192. sb.Append("\t\t/// <summary>\n");
  193. sb.Append($"\t\t/// {newline.TrimStart('/', ' ')}\n");
  194. sb.Append("\t\t/// </summary>\n");
  195. continue;
  196. }
  197. string memberStr;
  198. if (newline.Contains("//"))
  199. {
  200. string[] lineSplit = newline.Split("//");
  201. memberStr = lineSplit[0].Trim();
  202. sb.Append("\t\t/// <summary>\n");
  203. sb.Append($"\t\t/// {lineSplit[1].Trim()}\n");
  204. sb.Append("\t\t/// </summary>\n");
  205. }
  206. else
  207. {
  208. memberStr = newline;
  209. }
  210. if (memberStr.StartsWith("map<"))
  211. {
  212. Map(sb, memberStr, sbDispose);
  213. }
  214. else if (memberStr.StartsWith("repeated"))
  215. {
  216. Repeated(sb, memberStr, sbDispose);
  217. }
  218. else
  219. {
  220. Members(sb, memberStr, sbDispose);
  221. }
  222. }
  223. }
  224. sb.Append("\tpublic static class " + protoName + "\n\t{\n");
  225. foreach (OpcodeInfo info in msgOpcode)
  226. {
  227. sb.Append($"\t\tpublic const ushort {info.Name} = {info.Opcode};\n");
  228. }
  229. sb.Append("\t}\n");
  230. sb.Append('}');
  231. sb.Replace("\t", " ");
  232. string result = sb.ToString().ReplaceLineEndings("\r\n");
  233. if (cs.Contains('C'))
  234. {
  235. GenerateCS(result, clientMessagePath + module, proto);
  236. GenerateCS(result, serverMessagePath + module, proto);
  237. GenerateCS(result, clientServerMessagePath + module, proto);
  238. }
  239. if (cs.Contains('S'))
  240. {
  241. GenerateCS(result, serverMessagePath + module, proto);
  242. GenerateCS(result, clientServerMessagePath + module, proto);
  243. }
  244. }
  245. private static void GenerateCS(string result, string path, string proto)
  246. {
  247. if (!Directory.Exists(path))
  248. {
  249. Directory.CreateDirectory(path);
  250. }
  251. string csPath = Path.Combine(path, Path.GetFileNameWithoutExtension(proto) + ".cs");
  252. using FileStream txt = new(csPath, FileMode.Create, FileAccess.ReadWrite);
  253. using StreamWriter sw = new(txt);
  254. sw.Write(result);
  255. }
  256. private static void Map(StringBuilder sb, string newline, StringBuilder sbDispose)
  257. {
  258. int start = newline.IndexOf('<') + 1;
  259. int end = newline.IndexOf('>');
  260. string types = newline.Substring(start, end - start);
  261. string[] ss = types.Split(',');
  262. string keyType = ConvertType(ss[0].Trim());
  263. string valueType = ConvertType(ss[1].Trim());
  264. string tail = newline[(end + 1)..];
  265. ss = tail.Trim().Replace(";", "").Split(' ');
  266. string v = ss[0];
  267. int n = int.Parse(ss[2]);
  268. sb.Append("\t\t[MongoDB.Bson.Serialization.Attributes.BsonDictionaryOptions(MongoDB.Bson.Serialization.Options.DictionaryRepresentation.ArrayOfArrays)]\n");
  269. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  270. sb.Append($"\t\tpublic Dictionary<{keyType}, {valueType}> {v} {{ get; set; }} = new();\n");
  271. sbDispose.Append($"this.{v}.Clear();\n\t\t\t");
  272. }
  273. private static void Repeated(StringBuilder sb, string newline, StringBuilder sbDispose)
  274. {
  275. try
  276. {
  277. int index = newline.IndexOf(';');
  278. newline = newline.Remove(index);
  279. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  280. string type = ss[1];
  281. type = ConvertType(type);
  282. string name = ss[2];
  283. int n = int.Parse(ss[4]);
  284. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  285. sb.Append($"\t\tpublic List<{type}> {name} {{ get; set; }} = new();\n\n");
  286. sbDispose.Append($"this.{name}.Clear();\n\t\t\t");
  287. }
  288. catch (Exception e)
  289. {
  290. Console.WriteLine($"{newline}\n {e}");
  291. }
  292. }
  293. private static string ConvertType(string type)
  294. {
  295. return type switch
  296. {
  297. "int16" => "short",
  298. "int32" => "int",
  299. "bytes" => "byte[]",
  300. "uint32" => "uint",
  301. "long" => "long",
  302. "int64" => "long",
  303. "uint64" => "ulong",
  304. "uint16" => "ushort",
  305. _ => type
  306. };
  307. }
  308. private static void Members(StringBuilder sb, string newline, StringBuilder sbDispose)
  309. {
  310. try
  311. {
  312. int index = newline.IndexOf(';');
  313. newline = newline.Remove(index);
  314. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  315. string type = ss[0];
  316. string name = ss[1];
  317. int n = int.Parse(ss[3]);
  318. string typeCs = ConvertType(type);
  319. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  320. sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
  321. switch (typeCs)
  322. {
  323. case "bytes":
  324. {
  325. break;
  326. }
  327. default:
  328. sbDispose.Append($"this.{name} = default;\n\t\t\t");
  329. break;
  330. }
  331. }
  332. catch (Exception e)
  333. {
  334. Console.WriteLine($"{newline}\n {e}");
  335. }
  336. }
  337. /// <summary>
  338. /// 删除meta以外的所有文件
  339. /// </summary>
  340. static void RemoveAllFilesExceptMeta(string directory)
  341. {
  342. if (!Directory.Exists(directory))
  343. {
  344. return;
  345. }
  346. DirectoryInfo targetDir = new(directory);
  347. FileInfo[] fileInfos = targetDir.GetFiles("*", SearchOption.AllDirectories);
  348. foreach (FileInfo info in fileInfos)
  349. {
  350. if (!info.Name.EndsWith(".meta"))
  351. {
  352. File.Delete(info.FullName);
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// 删除多余的meta文件
  358. /// </summary>
  359. static void RemoveUnusedMetaFiles(string directory)
  360. {
  361. if (!Directory.Exists(directory))
  362. {
  363. return;
  364. }
  365. DirectoryInfo targetDir = new(directory);
  366. FileInfo[] fileInfos = targetDir.GetFiles("*.meta", SearchOption.AllDirectories);
  367. foreach (FileInfo info in fileInfos)
  368. {
  369. string pathWithoutMeta = info.FullName.Remove(info.FullName.LastIndexOf(".meta", StringComparison.Ordinal));
  370. if (!File.Exists(pathWithoutMeta) && !Directory.Exists(pathWithoutMeta))
  371. {
  372. File.Delete(info.FullName);
  373. }
  374. }
  375. }
  376. [GeneratedRegex(@"//\s*ResponseType")]
  377. private static partial Regex ResponseTypeRegex();
  378. }
  379. }