Proto2CS.cs 14 KB

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