Proto2CS.cs 13 KB

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