Proto2CS.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. namespace ET
  6. {
  7. internal class OpcodeInfo
  8. {
  9. public string Name;
  10. public int Opcode;
  11. }
  12. public static class Proto2CS
  13. {
  14. public static void Export()
  15. {
  16. // InnerMessage.proto生成cs代码
  17. InnerProto2CS.Proto2CS();
  18. Log.Console("proto2cs succeed!");
  19. }
  20. }
  21. public static 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 = new List<OpcodeInfo>();
  29. public static void Proto2CS()
  30. {
  31. msgOpcode.Clear();
  32. if (Directory.Exists(clientMessagePath))
  33. {
  34. Directory.Delete(clientMessagePath, true);
  35. }
  36. if (Directory.Exists(serverMessagePath))
  37. {
  38. Directory.Delete(serverMessagePath, true);
  39. }
  40. if (Directory.Exists(clientServerMessagePath))
  41. {
  42. Directory.Delete(clientServerMessagePath, true);
  43. }
  44. List<string> list = FileHelper.GetAllFiles(protoDir, "*proto");
  45. foreach (string s in list)
  46. {
  47. if (!s.EndsWith(".proto"))
  48. {
  49. continue;
  50. }
  51. string fileName = Path.GetFileNameWithoutExtension(s);
  52. string[] ss2 = fileName.Split('_');
  53. string protoName = ss2[0];
  54. string cs = ss2[1];
  55. int startOpcode = int.Parse(ss2[2]);
  56. ProtoFile2CS(fileName, protoName, cs, startOpcode);
  57. }
  58. }
  59. public static void ProtoFile2CS(string fileName, string protoName, string cs, int startOpcode)
  60. {
  61. string ns = "ET";
  62. msgOpcode.Clear();
  63. string proto = Path.Combine(protoDir, $"{fileName}.proto");
  64. string s = File.ReadAllText(proto);
  65. StringBuilder sb = new StringBuilder();
  66. sb.Append("using ET;\n");
  67. sb.Append("using MemoryPack;\n");
  68. sb.Append("using System.Collections.Generic;\n");
  69. sb.Append($"namespace {ns}\n");
  70. sb.Append("{\n");
  71. bool isMsgStart = false;
  72. string msgName = "";
  73. foreach (string line in s.Split('\n'))
  74. {
  75. string newline = line.Trim();
  76. if (newline == "")
  77. {
  78. continue;
  79. }
  80. if (newline.StartsWith("//ResponseType"))
  81. {
  82. string responseType = line.Split(" ")[1].TrimEnd('\r', '\n');
  83. sb.Append($"\t[ResponseType(nameof({responseType}))]\n");
  84. continue;
  85. }
  86. if (newline.StartsWith("//"))
  87. {
  88. sb.Append($"{newline}\n");
  89. continue;
  90. }
  91. if (newline.StartsWith("message"))
  92. {
  93. string parentClass = "";
  94. isMsgStart = true;
  95. msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
  96. string[] ss = newline.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
  97. if (ss.Length == 2)
  98. {
  99. parentClass = ss[1].Trim();
  100. }
  101. msgOpcode.Add(new OpcodeInfo() { Name = msgName, Opcode = ++startOpcode });
  102. sb.Append($"\t[Message({protoName}.{msgName})]\n");
  103. sb.Append($"\t[MemoryPackable]\n");
  104. sb.Append($"\tpublic partial class {msgName}: MessageObject");
  105. if (parentClass == "IActorMessage" || parentClass == "IActorRequest" || parentClass == "IActorResponse")
  106. {
  107. sb.Append($", {parentClass}\n");
  108. }
  109. else if (parentClass != "")
  110. {
  111. sb.Append($", {parentClass}\n");
  112. }
  113. else
  114. {
  115. sb.Append("\n");
  116. }
  117. continue;
  118. }
  119. if (isMsgStart)
  120. {
  121. if (newline == "{")
  122. {
  123. sb.Append("\t{\n");
  124. sb.Append($"\t\tpublic static {msgName} Create(bool isFromPool = false) {{ return !isFromPool? new {msgName}() : NetServices.Instance.FetchMessage(typeof({msgName})) as {msgName}; }}\n\n");
  125. sb.Append($"\t\tpublic override void Dispose() {{ NetServices.Instance.RecycleMessage(this); }}\n\n");
  126. continue;
  127. }
  128. if (newline == "}")
  129. {
  130. isMsgStart = false;
  131. sb.Append("\t}\n\n");
  132. continue;
  133. }
  134. if (newline.Trim().StartsWith("//"))
  135. {
  136. sb.Append($"{newline}\n");
  137. continue;
  138. }
  139. if (newline.Trim() != "" && newline != "}")
  140. {
  141. if (newline.StartsWith("map<"))
  142. {
  143. Map(sb, ns, newline);
  144. }
  145. else if (newline.StartsWith("repeated"))
  146. {
  147. Repeated(sb, ns, newline);
  148. }
  149. else
  150. {
  151. Members(sb, newline, true);
  152. }
  153. }
  154. }
  155. }
  156. sb.Append("\tpublic static class " + protoName + "\n\t{\n");
  157. foreach (OpcodeInfo info in msgOpcode)
  158. {
  159. sb.Append($"\t\t public const ushort {info.Name} = {info.Opcode};\n");
  160. }
  161. sb.Append("\t}\n");
  162. sb.Append("}\n");
  163. if (cs.Contains("C"))
  164. {
  165. GenerateCS(sb, clientMessagePath, proto);
  166. GenerateCS(sb, serverMessagePath, proto);
  167. GenerateCS(sb, clientServerMessagePath, proto);
  168. }
  169. if (cs.Contains("S"))
  170. {
  171. GenerateCS(sb, serverMessagePath, proto);
  172. GenerateCS(sb, clientServerMessagePath, proto);
  173. }
  174. }
  175. private static void GenerateCS(StringBuilder sb, string path, string proto)
  176. {
  177. if (!Directory.Exists(path))
  178. {
  179. Directory.CreateDirectory(path);
  180. }
  181. string csPath = Path.Combine(path, Path.GetFileNameWithoutExtension(proto) + ".cs");
  182. using FileStream txt = new FileStream(csPath, FileMode.Create, FileAccess.ReadWrite);
  183. using StreamWriter sw = new StreamWriter(txt);
  184. sw.Write(sb.ToString());
  185. }
  186. private static void Map(StringBuilder sb, string ns, string newline)
  187. {
  188. int start = newline.IndexOf("<") + 1;
  189. int end = newline.IndexOf(">");
  190. string types = newline.Substring(start, end - start);
  191. string[] ss = types.Split(",");
  192. string keyType = ConvertType(ss[0].Trim());
  193. string valueType = ConvertType(ss[1].Trim());
  194. string tail = newline.Substring(end + 1);
  195. ss = tail.Trim().Replace(";", "").Split(" ");
  196. string v = ss[0];
  197. int n = int.Parse(ss[2]);
  198. sb.Append("\t\t[MongoDB.Bson.Serialization.Attributes.BsonDictionaryOptions(MongoDB.Bson.Serialization.Options.DictionaryRepresentation.ArrayOfArrays)]\n");
  199. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  200. sb.Append($"\t\tpublic Dictionary<{keyType}, {valueType}> {v} {{ get; set; }}\n");
  201. }
  202. private static void Repeated(StringBuilder sb, string ns, string newline)
  203. {
  204. try
  205. {
  206. int index = newline.IndexOf(";");
  207. newline = newline.Remove(index);
  208. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  209. string type = ss[1];
  210. type = ConvertType(type);
  211. string name = ss[2];
  212. int n = int.Parse(ss[4]);
  213. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  214. sb.Append($"\t\tpublic List<{type}> {name} {{ get; set; }}\n\n");
  215. }
  216. catch (Exception e)
  217. {
  218. Console.WriteLine($"{newline}\n {e}");
  219. }
  220. }
  221. private static string ConvertType(string type)
  222. {
  223. string typeCs = "";
  224. switch (type)
  225. {
  226. case "int16":
  227. typeCs = "short";
  228. break;
  229. case "int32":
  230. typeCs = "int";
  231. break;
  232. case "bytes":
  233. typeCs = "byte[]";
  234. break;
  235. case "uint32":
  236. typeCs = "uint";
  237. break;
  238. case "long":
  239. typeCs = "long";
  240. break;
  241. case "int64":
  242. typeCs = "long";
  243. break;
  244. case "uint64":
  245. typeCs = "ulong";
  246. break;
  247. case "uint16":
  248. typeCs = "ushort";
  249. break;
  250. default:
  251. typeCs = type;
  252. break;
  253. }
  254. return typeCs;
  255. }
  256. private static void Members(StringBuilder sb, string newline, bool isRequired)
  257. {
  258. try
  259. {
  260. int index = newline.IndexOf(";");
  261. newline = newline.Remove(index);
  262. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  263. string type = ss[0];
  264. string name = ss[1];
  265. int n = int.Parse(ss[3]);
  266. string typeCs = ConvertType(type);
  267. sb.Append($"\t\t[MemoryPackOrder({n - 1})]\n");
  268. sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
  269. }
  270. catch (Exception e)
  271. {
  272. Console.WriteLine($"{newline}\n {e}");
  273. }
  274. }
  275. }
  276. }