BMFontEditor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Xml;
  9. using UnityEditor;
  10. using UnityEngine;
  11. using Debug = UnityEngine.Debug;
  12. public class BMFontTools : EditorWindow
  13. {
  14. private string configDirPath;
  15. private string configFlag = "# imported icon images";
  16. //字体文件的生成路径
  17. private string _fontDirPath;
  18. private Vector2 _scrollPos;
  19. private bool _showBMConfig;
  20. private bool _showBMInfo;
  21. private string _currentSelect = string.Empty;
  22. private struct FontInfo
  23. {
  24. //图片路径
  25. public string ImgPath;
  26. //字符
  27. public char charInfo;
  28. }
  29. private List<FontInfo> _fontInfoList = new List<FontInfo>();
  30. private List<string> _filesList;
  31. private List<string> _filesNameList;
  32. private void Awake()
  33. {
  34. configDirPath = Path.Combine(Application.dataPath, "../BMFont");
  35. _fontDirPath = Path.Combine(Application.dataPath, "Content/Fonts");
  36. _initConfigInfo();
  37. }
  38. private void _initConfigInfo()
  39. {
  40. _filesList = new List<string>(Directory.GetFiles(configDirPath, "*.bmfc"));
  41. _filesNameList = new List<string>();
  42. for (int i = 0; i < _filesList.Count; i++)
  43. {
  44. _filesNameList.Add(Path.GetFileNameWithoutExtension(_filesList[i]));
  45. }
  46. }
  47. [MenuItem("RO_Tool/BMFontTools", false, 13)]
  48. private static void MyBMFontTools()
  49. {
  50. BMFontTools bmFont = new BMFontTools();
  51. bmFont.Show();
  52. }
  53. private void _setBMFontConfigs()
  54. {
  55. _showBMConfig = EditorGUILayout.Foldout(_showBMConfig, "BMFont Configs");
  56. if (_showBMConfig)
  57. {
  58. for (int i = 0; i < _filesList.Count; i++)
  59. {
  60. GUILayout.BeginHorizontal();
  61. GUI.enabled = false;
  62. EditorGUILayout.TextField(_filesList[i], GUILayout.MaxWidth(400));
  63. GUI.enabled = true;
  64. EditorGUILayout.LabelField("FontName:", GUILayout.MaxWidth(80));
  65. _filesNameList[i] = EditorGUILayout.TextField(_filesNameList[i], GUILayout.MaxWidth(100));
  66. if (GUILayout.Button("Reset Name"))
  67. {
  68. Regex regex = new Regex(@"/|\\|<|>|\*|\?");
  69. if (!string.IsNullOrEmpty(_filesNameList[i]) && !regex.IsMatch(_filesNameList[i]))
  70. {
  71. string fileNameTemp = _filesList[i].Replace(Path.GetFileNameWithoutExtension(_filesList[i]), _filesNameList[i]);
  72. if (File.Exists(fileNameTemp))
  73. {
  74. Debug.LogError("文件冲突,命名失败");
  75. }
  76. else
  77. {
  78. File.Move(_filesList[i], fileNameTemp);
  79. }
  80. _initConfigInfo();
  81. }
  82. else
  83. {
  84. Debug.LogError("文件名非法或为空,命名失败");
  85. }
  86. }
  87. if (GUILayout.Button("Select"))
  88. {
  89. _currentSelect = _filesList[i];
  90. _fontInfoList = _analysisConfig(_currentSelect);
  91. }
  92. GUILayout.EndHorizontal();
  93. }
  94. }
  95. GUI.color = Color.green;
  96. EditorGUILayout.LabelField("CurrentSelect:", _currentSelect);
  97. GUI.color = Color.white;
  98. if (GUILayout.Button("New Font Config"))
  99. {
  100. File.WriteAllText(Path.Combine(configDirPath, string.Format("{0}.bmfc",
  101. DateTime.Now.ToString("yyyyMMddhhmmss"))), configFlag, Encoding.UTF8);
  102. _initConfigInfo();
  103. }
  104. }
  105. private void _setConfigInfo()
  106. {
  107. _showBMInfo = EditorGUILayout.Foldout(_showBMInfo, "BMFont Info");
  108. if (_showBMInfo && !string.IsNullOrEmpty(_currentSelect))
  109. {
  110. for (int i = 0; i < _fontInfoList.Count; i++)
  111. {
  112. EditorGUILayout.BeginHorizontal();
  113. if (GUILayout.Button("Select Img", GUILayout.MaxWidth(100)))
  114. {
  115. string pathTemp = EditorUtility.OpenFilePanelWithFilters("选择图片",
  116. string.Format("{0}\\GameMin\\UI\\UISprites", Application.dataPath.Replace('/', '\\')),
  117. new string[] { "Image", "png" });
  118. if (!string.IsNullOrEmpty(pathTemp))
  119. {
  120. FontInfo fontInfo = new FontInfo();
  121. fontInfo.charInfo = _fontInfoList[i].charInfo;
  122. fontInfo.ImgPath = _formatPath(pathTemp);
  123. _fontInfoList[i] = fontInfo;
  124. }
  125. }
  126. EditorGUILayout.LabelField("Char:", GUILayout.MaxWidth(55));
  127. FontInfo info = new FontInfo();
  128. if (!string.IsNullOrEmpty(_fontInfoList[i].charInfo.ToString()))
  129. {
  130. string temp = EditorGUILayout.TextField(_fontInfoList[i].charInfo.ToString(), GUILayout.MaxWidth(30));
  131. if (temp.Length == 1 && Regex.IsMatch(temp, "[\x20-\x7e]"))
  132. {
  133. info.charInfo = temp[0];
  134. info.ImgPath = _fontInfoList[i].ImgPath;
  135. _fontInfoList[i] = info;
  136. }
  137. }
  138. EditorGUILayout.LabelField("ImgPath:", GUILayout.MaxWidth(55));
  139. GUI.enabled = false;
  140. EditorGUILayout.TextField(_fontInfoList[i].ImgPath);
  141. GUI.enabled = true;
  142. EditorGUILayout.EndHorizontal();
  143. }
  144. if (GUILayout.Button("Add"))
  145. {
  146. _fontInfoList.Add(new FontInfo());
  147. }
  148. if (GUILayout.Button("Save And Export Font"))
  149. {
  150. _saveFontAndExport();
  151. }
  152. }
  153. }
  154. private void _saveFontAndExport()
  155. {
  156. //保存配置文件
  157. string baseFontInfo = File.ReadAllText(configDirPath + "/BaseConfig.bmf");
  158. baseFontInfo += "\n";
  159. for (int i = 0; i < _fontInfoList.Count; i++)
  160. {
  161. if (string.IsNullOrEmpty(_fontInfoList[i].ImgPath) ||
  162. string.IsNullOrEmpty(_fontInfoList[i].charInfo.ToString()))
  163. {
  164. continue;
  165. }
  166. string info = string.Format("icon=\"{0}\",{1},0,0,0\n", _fontInfoList[i].ImgPath,
  167. (int)_fontInfoList[i].charInfo);
  168. baseFontInfo += info;
  169. }
  170. File.WriteAllText(_currentSelect, baseFontInfo);
  171. _exportFontInfo();
  172. AssetDatabase.Refresh();
  173. }
  174. private void _exportFontInfo()
  175. {
  176. string fileName = Path.GetFileNameWithoutExtension(_currentSelect);
  177. string targetDir = Path.Combine(_fontDirPath, fileName);
  178. if (!Directory.Exists(targetDir))
  179. {
  180. Directory.CreateDirectory(targetDir);
  181. }
  182. Process process = new Process();
  183. string batPath = Path.Combine(configDirPath, "BMFontGenerate.bat");
  184. process.StartInfo.FileName = batPath;
  185. process.StartInfo.WorkingDirectory = configDirPath;
  186. process.StartInfo.Arguments =
  187. string.Format("{0} {1}", _currentSelect, Path.Combine(_fontDirPath, targetDir + "/" + fileName));
  188. process.Start();
  189. process.WaitForExit();
  190. AssetDatabase.Refresh();
  191. _genFontInfo(targetDir, fileName);
  192. }
  193. private string _getAssetPath(string path)
  194. {
  195. string pathTemp = path.Replace("\\", "/");
  196. pathTemp = pathTemp.Replace(Application.dataPath, "Assets");
  197. return pathTemp;
  198. }
  199. private void _genFontInfo(string fontDirPath, string fileName)
  200. {
  201. string matPath = Path.Combine(fontDirPath, fileName + "_0.mat");
  202. Material mat = AssetDatabase.LoadAssetAtPath<Material>(_getAssetPath(matPath));
  203. if (mat == null)
  204. {
  205. mat = new Material(Shader.Find("UI/Default Font"));
  206. AssetDatabase.CreateAsset(mat, _getAssetPath(matPath));
  207. }
  208. string texturePath = Path.Combine(fontDirPath, fileName + "_0.png");
  209. Texture _fontTexture = AssetDatabase.LoadAssetAtPath<Texture>(_getAssetPath(texturePath));
  210. mat = AssetDatabase.LoadAssetAtPath<Material>(_getAssetPath(matPath));
  211. mat.SetTexture("_MainTex", _fontTexture);
  212. string fontPath = Path.Combine(fontDirPath, fileName + ".fontsettings");
  213. Font font = AssetDatabase.LoadAssetAtPath<Font>(_getAssetPath(fontPath));
  214. if (font == null)
  215. {
  216. font = new Font();
  217. AssetDatabase.CreateAsset(font, _getAssetPath(fontPath));
  218. }
  219. string fontConfigPath = Path.Combine(fontDirPath, fileName + ".fnt");
  220. List<CharacterInfo> chars = _getFontInfo(fontConfigPath, _fontTexture);
  221. font.material = mat;
  222. _serializeFont(font, chars, 1);
  223. File.Delete(fontConfigPath);
  224. AssetDatabase.SaveAssets();
  225. AssetDatabase.Refresh();
  226. }
  227. private List<CharacterInfo> _getFontInfo(string fontConfig, Texture texture)
  228. {
  229. XmlDocument xml = new XmlDocument();
  230. xml.Load(fontConfig);
  231. List<CharacterInfo> chtInfoList = new List<CharacterInfo>();
  232. XmlNode node = xml.SelectSingleNode("font/chars");
  233. foreach (XmlNode nd in node.ChildNodes)
  234. {
  235. XmlElement xe = (XmlElement)nd;
  236. int x = int.Parse(xe.GetAttribute("x"));
  237. int y = int.Parse(xe.GetAttribute("y"));
  238. int width = int.Parse(xe.GetAttribute("width"));
  239. int height = int.Parse(xe.GetAttribute("height"));
  240. int advance = int.Parse(xe.GetAttribute("xadvance"));
  241. CharacterInfo info = new CharacterInfo();
  242. info.glyphHeight = texture.height;
  243. info.glyphWidth = texture.width;
  244. info.index = int.Parse(xe.GetAttribute("id"));
  245. //这里注意下UV坐标系和从BMFont里得到的信息的坐标系是不一样的哦,前者左下角为(0,0),
  246. //右上角为(1,1)。而后者则是左上角上角为(0,0),右下角为(图宽,图高)
  247. info.uvTopLeft = new Vector2((float)x / texture.width, 1 - (float)y / texture.height);
  248. info.uvTopRight = new Vector2((float)(x + width) / texture.width, 1 - (float)y / texture.height);
  249. info.uvBottomLeft = new Vector2((float)x / texture.width, 1 - (float)(y + height) / texture.height);
  250. info.uvBottomRight = new Vector2((float)(x + width) / texture.width, 1 - (float)(y + height) / texture.height);
  251. info.minX = 0;
  252. info.minY = -height;
  253. info.maxX = width;
  254. info.maxY = 0;
  255. info.advance = advance;
  256. chtInfoList.Add(info);
  257. }
  258. return chtInfoList;
  259. }
  260. private static void _setLineHeight(SerializedObject font, float height)
  261. {
  262. font.FindProperty("m_LineSpacing").floatValue = height;
  263. }
  264. private static SerializedObject _serializeFont(Font font, List<CharacterInfo> chars, float lineHeight)
  265. {
  266. SerializedObject serializedFont = new SerializedObject(font);
  267. _setLineHeight(serializedFont, lineHeight);
  268. _serializeFontCharInfos(serializedFont, chars);
  269. serializedFont.ApplyModifiedProperties();
  270. return serializedFont;
  271. }
  272. private static void _serializeFontCharInfos(SerializedObject font, List<CharacterInfo> chars)
  273. {
  274. SerializedProperty charRects = font.FindProperty("m_CharacterRects");
  275. charRects.arraySize = chars.Count;
  276. for (int i = 0; i < chars.Count; ++i)
  277. {
  278. CharacterInfo info = chars[i];
  279. SerializedProperty prop = charRects.GetArrayElementAtIndex(i);
  280. SerializeCharInfo(prop, info);
  281. }
  282. }
  283. public static void SerializeCharInfo(SerializedProperty prop, CharacterInfo charInfo)
  284. {
  285. prop.FindPropertyRelative("index").intValue = charInfo.index;
  286. prop.FindPropertyRelative("uv").rectValue = charInfo.uv;
  287. prop.FindPropertyRelative("vert").rectValue = charInfo.vert;
  288. prop.FindPropertyRelative("advance").floatValue = charInfo.advance;
  289. prop.FindPropertyRelative("flipped").boolValue = false;
  290. }
  291. private void OnGUI()
  292. {
  293. _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos);
  294. EditorGUILayout.BeginVertical();
  295. EditorGUILayout.BeginHorizontal();
  296. GUILayout.Label("Font Save Path:", GUILayout.MaxWidth(100));
  297. GUILayout.TextField(_fontDirPath);
  298. EditorGUILayout.EndHorizontal();
  299. _setBMFontConfigs();
  300. _setConfigInfo();
  301. EditorGUILayout.EndVertical();
  302. EditorGUILayout.EndScrollView();
  303. }
  304. private List<FontInfo> _analysisConfig(string configPath)
  305. {
  306. List<FontInfo> infoList = new List<FontInfo>();
  307. string[] fileInfo = File.ReadAllLines(configPath);
  308. bool isGetInfoFlag = false;
  309. for (int i = 0; i < fileInfo.Length; i++)
  310. {
  311. if (fileInfo[i].Contains(configFlag) || isGetInfoFlag)
  312. {
  313. if (!isGetInfoFlag)
  314. {
  315. i++;
  316. isGetInfoFlag = true;
  317. }
  318. if (i < fileInfo.Length && !string.IsNullOrEmpty(fileInfo[i]))
  319. {
  320. infoList.Add(_getFontInfoByStr(fileInfo[i]));
  321. }
  322. }
  323. }
  324. return infoList;
  325. }
  326. private FontInfo _getFontInfoByStr(string str)
  327. {
  328. string[] strTemp = str.Split(',');
  329. FontInfo fontInfo = new FontInfo();
  330. string strPathTemp = string.Empty;
  331. for (int i = 0; i < strTemp.Length; i++)
  332. {
  333. if (_isOddDoubleQuota(strTemp[i]))
  334. {
  335. strPathTemp += strTemp[i] + ",";
  336. if (!_isOddDoubleQuota(strPathTemp))
  337. {
  338. strPathTemp = strPathTemp.Substring(0, strPathTemp.Length - 1);
  339. break;
  340. }
  341. }
  342. else
  343. {
  344. strPathTemp = strTemp[i];
  345. break;
  346. }
  347. }
  348. fontInfo.ImgPath = strPathTemp.Replace("icon=\"", string.Empty).Replace("\"", string.Empty);
  349. fontInfo.charInfo = (char)int.Parse(strTemp[strTemp.Length - 4]);
  350. return fontInfo;
  351. }
  352. private bool _isOddDoubleQuota(string str)
  353. {
  354. return _getDoubleQuotaCount(str) % 2 == 1;
  355. }
  356. private int _getDoubleQuotaCount(string str)
  357. {
  358. string[] strArray = str.Split('"');
  359. int doubleQuotaCount = strArray.Length - 1;
  360. doubleQuotaCount = doubleQuotaCount < 0 ? 0 : doubleQuotaCount;
  361. return doubleQuotaCount;
  362. }
  363. private string _formatPath(string path)
  364. {
  365. path = path.Replace("\\", "/");
  366. return path;
  367. }
  368. }