Proto2CS.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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/Codes/Model/Generate/Client/Message/";
  25. private const string serverMessagePath = "../Unity/Assets/Scripts/Codes/Model/Generate/Server/Message/";
  26. private static readonly char[] splitChars = { ' ', '\t' };
  27. private static readonly List<OpcodeInfo> msgOpcode = new List<OpcodeInfo>();
  28. public static void Proto2CS()
  29. {
  30. msgOpcode.Clear();
  31. if (Directory.Exists(clientMessagePath))
  32. {
  33. Directory.Delete(clientMessagePath, true);
  34. }
  35. if (Directory.Exists(serverMessagePath))
  36. {
  37. Directory.Delete(serverMessagePath, true);
  38. }
  39. List<string> list = FileHelper.GetAllFiles(protoDir, "*proto");
  40. foreach (string s in list)
  41. {
  42. if (!s.EndsWith(".proto"))
  43. {
  44. continue;
  45. }
  46. string fileName = Path.GetFileNameWithoutExtension(s);
  47. string[] ss2 = fileName.Split('_');
  48. string protoName = ss2[0];
  49. string cs = ss2[1];
  50. int startOpcode = int.Parse(ss2[2]);
  51. ProtoFile2CS(fileName, protoName, cs, startOpcode);
  52. }
  53. }
  54. public static void ProtoFile2CS(string fileName, string protoName, string cs, int startOpcode)
  55. {
  56. string ns = "ET";
  57. msgOpcode.Clear();
  58. string proto = Path.Combine(protoDir, $"{fileName}.proto");
  59. string s = File.ReadAllText(proto);
  60. StringBuilder sb = new StringBuilder();
  61. sb.Append("using ET;\n");
  62. sb.Append("using ProtoBuf;\n");
  63. sb.Append("using System.Collections.Generic;\n");
  64. sb.Append($"namespace {ns}\n");
  65. sb.Append("{\n");
  66. bool isMsgStart = false;
  67. foreach (string line in s.Split('\n'))
  68. {
  69. string newline = line.Trim();
  70. if (newline == "")
  71. {
  72. continue;
  73. }
  74. if (newline.StartsWith("//ResponseType"))
  75. {
  76. string responseType = line.Split(" ")[1].TrimEnd('\r', '\n');
  77. sb.AppendLine($"\t[ResponseType(nameof({responseType}))]");
  78. continue;
  79. }
  80. if (newline.StartsWith("//"))
  81. {
  82. sb.Append($"{newline}\n");
  83. continue;
  84. }
  85. if (newline.StartsWith("message"))
  86. {
  87. string parentClass = "";
  88. isMsgStart = true;
  89. string msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
  90. string[] ss = newline.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
  91. if (ss.Length == 2)
  92. {
  93. parentClass = ss[1].Trim();
  94. }
  95. msgOpcode.Add(new OpcodeInfo() { Name = msgName, Opcode = ++startOpcode });
  96. sb.Append($"\t[Message({protoName}.{msgName})]\n");
  97. sb.Append($"\t[ProtoContract]\n");
  98. sb.Append($"\tpublic partial class {msgName}: Object");
  99. if (parentClass == "IActorMessage" || parentClass == "IActorRequest" || parentClass == "IActorResponse")
  100. {
  101. sb.Append($", {parentClass}\n");
  102. }
  103. else if (parentClass != "")
  104. {
  105. sb.Append($", {parentClass}\n");
  106. }
  107. else
  108. {
  109. sb.Append("\n");
  110. }
  111. continue;
  112. }
  113. if (isMsgStart)
  114. {
  115. if (newline == "{")
  116. {
  117. sb.Append("\t{\n");
  118. continue;
  119. }
  120. if (newline == "}")
  121. {
  122. isMsgStart = false;
  123. sb.Append("\t}\n\n");
  124. continue;
  125. }
  126. if (newline.Trim().StartsWith("//"))
  127. {
  128. sb.AppendLine(newline);
  129. continue;
  130. }
  131. if (newline.Trim() != "" && newline != "}")
  132. {
  133. if (newline.StartsWith("repeated"))
  134. {
  135. Repeated(sb, ns, newline);
  136. }
  137. else
  138. {
  139. Members(sb, newline, true);
  140. }
  141. }
  142. }
  143. }
  144. sb.Append("\tpublic static class " + protoName + "\n\t{\n");
  145. foreach (OpcodeInfo info in msgOpcode)
  146. {
  147. sb.AppendLine($"\t\t public const ushort {info.Name} = {info.Opcode};");
  148. }
  149. sb.AppendLine("\t}");
  150. sb.Append("}\n");
  151. if (cs.Contains("C"))
  152. {
  153. GenerateCS(sb, clientMessagePath, proto);
  154. GenerateCS(sb, serverMessagePath, proto);
  155. }
  156. if (cs.Contains("S"))
  157. {
  158. GenerateCS(sb, serverMessagePath, proto);
  159. }
  160. }
  161. private static void GenerateCS(StringBuilder sb, string path, string proto)
  162. {
  163. if (!Directory.Exists(path))
  164. {
  165. Directory.CreateDirectory(path);
  166. }
  167. string csPath = Path.Combine(path, Path.GetFileNameWithoutExtension(proto) + ".cs");
  168. using FileStream txt = new FileStream(csPath, FileMode.Create, FileAccess.ReadWrite);
  169. using StreamWriter sw = new StreamWriter(txt);
  170. sw.Write(sb.ToString());
  171. }
  172. private static void Repeated(StringBuilder sb, string ns, string newline)
  173. {
  174. try
  175. {
  176. int index = newline.IndexOf(";");
  177. newline = newline.Remove(index);
  178. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  179. string type = ss[1];
  180. type = ConvertType(type);
  181. string name = ss[2];
  182. int n = int.Parse(ss[4]);
  183. sb.Append($"\t\t[ProtoMember({n})]\n");
  184. sb.Append($"\t\tpublic List<{type}> {name} = new List<{type}>();\n\n");
  185. }
  186. catch (Exception e)
  187. {
  188. Console.WriteLine($"{newline}\n {e}");
  189. }
  190. }
  191. private static string ConvertType(string type)
  192. {
  193. string typeCs = "";
  194. switch (type)
  195. {
  196. case "int16":
  197. typeCs = "short";
  198. break;
  199. case "int32":
  200. typeCs = "int";
  201. break;
  202. case "bytes":
  203. typeCs = "byte[]";
  204. break;
  205. case "uint32":
  206. typeCs = "uint";
  207. break;
  208. case "long":
  209. typeCs = "long";
  210. break;
  211. case "int64":
  212. typeCs = "long";
  213. break;
  214. case "uint64":
  215. typeCs = "ulong";
  216. break;
  217. case "uint16":
  218. typeCs = "ushort";
  219. break;
  220. default:
  221. typeCs = type;
  222. break;
  223. }
  224. return typeCs;
  225. }
  226. private static void Members(StringBuilder sb, string newline, bool isRequired)
  227. {
  228. try
  229. {
  230. int index = newline.IndexOf(";");
  231. newline = newline.Remove(index);
  232. string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
  233. string type = ss[0];
  234. string name = ss[1];
  235. int n = int.Parse(ss[3]);
  236. string typeCs = ConvertType(type);
  237. sb.Append($"\t\t[ProtoMember({n})]\n");
  238. sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
  239. }
  240. catch (Exception e)
  241. {
  242. Console.WriteLine($"{newline}\n {e}");
  243. }
  244. }
  245. }
  246. }