TMPro_FontAssetCreatorWindow.cs 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. using System;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Threading;
  7. using System.IO;
  8. using System.Text.RegularExpressions;
  9. using UnityEngine.TextCore;
  10. using UnityEngine.TextCore.LowLevel;
  11. using UnityEditor.TextCore.LowLevel;
  12. using Object = UnityEngine.Object;
  13. namespace TMPro.EditorUtilities
  14. {
  15. public class TMPro_FontAssetCreatorWindow : EditorWindow
  16. {
  17. [MenuItem("Window/TextMeshPro/Font Asset Creator", false, 2025)]
  18. public static void ShowFontAtlasCreatorWindow()
  19. {
  20. var window = GetWindow<TMPro_FontAssetCreatorWindow>();
  21. window.titleContent = new GUIContent("Font Asset Creator");
  22. window.Focus();
  23. // Make sure TMP Essential Resources have been imported.
  24. window.CheckEssentialResources();
  25. }
  26. public static void ShowFontAtlasCreatorWindow(Font sourceFontFile)
  27. {
  28. var window = GetWindow<TMPro_FontAssetCreatorWindow>();
  29. window.titleContent = new GUIContent("Font Asset Creator");
  30. window.Focus();
  31. window.ClearGeneratedData();
  32. window.m_LegacyFontAsset = null;
  33. window.m_SelectedFontAsset = null;
  34. // Override selected font asset
  35. window.m_SourceFontFile = sourceFontFile;
  36. // Make sure TMP Essential Resources have been imported.
  37. window.CheckEssentialResources();
  38. }
  39. public static void ShowFontAtlasCreatorWindow(TMP_FontAsset fontAsset)
  40. {
  41. var window = GetWindow<TMPro_FontAssetCreatorWindow>();
  42. window.titleContent = new GUIContent("Font Asset Creator");
  43. window.Focus();
  44. // Clear any previously generated data
  45. window.ClearGeneratedData();
  46. window.m_LegacyFontAsset = null;
  47. // Load font asset creation settings if we have valid settings
  48. if (string.IsNullOrEmpty(fontAsset.creationSettings.sourceFontFileGUID) == false)
  49. {
  50. window.LoadFontCreationSettings(fontAsset.creationSettings);
  51. // Override settings to inject character list from font asset
  52. window.m_CharacterSetSelectionMode = 6;
  53. window.m_CharacterSequence = TMP_EditorUtility.GetUnicodeCharacterSequence(TMP_FontAsset.GetCharactersArray(fontAsset));
  54. window.m_ReferencedFontAsset = fontAsset;
  55. window.m_SavedFontAtlas = fontAsset.atlasTexture;
  56. }
  57. else
  58. {
  59. window.m_WarningMessage = "Font Asset [" + fontAsset.name + "] does not contain any previous \"Font Asset Creation Settings\". This usually means [" + fontAsset.name + "] was created before this new functionality was added.";
  60. window.m_SourceFontFile = null;
  61. window.m_LegacyFontAsset = fontAsset;
  62. }
  63. // Even if we don't have any saved generation settings, we still want to pre-select the source font file.
  64. window.m_SelectedFontAsset = fontAsset;
  65. // Make sure TMP Essential Resources have been imported.
  66. window.CheckEssentialResources();
  67. }
  68. [System.Serializable]
  69. class FontAssetCreationSettingsContainer
  70. {
  71. public List<FontAssetCreationSettings> fontAssetCreationSettings;
  72. }
  73. FontAssetCreationSettingsContainer m_FontAssetCreationSettingsContainer;
  74. //static readonly string[] m_FontCreationPresets = new string[] { "Recent 1", "Recent 2", "Recent 3", "Recent 4" };
  75. int m_FontAssetCreationSettingsCurrentIndex = 0;
  76. const string k_FontAssetCreationSettingsContainerKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.Container";
  77. const string k_FontAssetCreationSettingsCurrentIndexKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.CurrentIndex";
  78. const float k_TwoColumnControlsWidth = 335f;
  79. // Diagnostics
  80. System.Diagnostics.Stopwatch m_StopWatch;
  81. double m_GlyphPackingGenerationTime;
  82. double m_GlyphRenderingGenerationTime;
  83. string[] m_FontSizingOptions = { "Auto Sizing", "Custom Size" };
  84. int m_PointSizeSamplingMode;
  85. string[] m_FontResolutionLabels = { "8", "16","32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" };
  86. int[] m_FontAtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
  87. string[] m_FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Unicode Range (Hex)", "Custom Characters", "Characters from File" };
  88. enum FontPackingModes { Fast = 0, Optimum = 4 };
  89. FontPackingModes m_PackingMode = FontPackingModes.Fast;
  90. int m_CharacterSetSelectionMode;
  91. string m_CharacterSequence = "";
  92. string m_OutputFeedback = "";
  93. string m_WarningMessage;
  94. int m_CharacterCount;
  95. Vector2 m_ScrollPosition;
  96. Vector2 m_OutputScrollPosition;
  97. bool m_IsRepaintNeeded;
  98. float m_AtlasGenerationProgress;
  99. string m_AtlasGenerationProgressLabel = string.Empty;
  100. float m_RenderingProgress;
  101. bool m_IsGlyphPackingDone;
  102. bool m_IsGlyphRenderingDone;
  103. bool m_IsRenderingDone;
  104. bool m_IsProcessing;
  105. bool m_IsGenerationDisabled;
  106. bool m_IsGenerationCancelled;
  107. bool m_IsFontAtlasInvalid;
  108. Object m_SourceFontFile;
  109. TMP_FontAsset m_SelectedFontAsset;
  110. TMP_FontAsset m_LegacyFontAsset;
  111. TMP_FontAsset m_ReferencedFontAsset;
  112. TextAsset m_CharactersFromFile;
  113. int m_PointSize;
  114. int m_Padding = 5;
  115. //FaceStyles m_FontStyle = FaceStyles.Normal;
  116. //float m_FontStyleValue = 2;
  117. GlyphRenderMode m_GlyphRenderMode = GlyphRenderMode.SDFAA;
  118. int m_AtlasWidth = 512;
  119. int m_AtlasHeight = 512;
  120. byte[] m_AtlasTextureBuffer;
  121. Texture2D m_FontAtlasTexture;
  122. Texture2D m_SavedFontAtlas;
  123. //
  124. List<Glyph> m_FontGlyphTable = new List<Glyph>();
  125. List<TMP_Character> m_FontCharacterTable = new List<TMP_Character>();
  126. Dictionary<uint, uint> m_CharacterLookupMap = new Dictionary<uint, uint>();
  127. Dictionary<uint, List<uint>> m_GlyphLookupMap = new Dictionary<uint, List<uint>>();
  128. List<Glyph> m_GlyphsToPack = new List<Glyph>();
  129. List<Glyph> m_GlyphsPacked = new List<Glyph>();
  130. List<GlyphRect> m_FreeGlyphRects = new List<GlyphRect>();
  131. List<GlyphRect> m_UsedGlyphRects = new List<GlyphRect>();
  132. List<Glyph> m_GlyphsToRender = new List<Glyph>();
  133. List<uint> m_AvailableGlyphsToAdd = new List<uint>();
  134. List<uint> m_MissingCharacters = new List<uint>();
  135. List<uint> m_ExcludedCharacters = new List<uint>();
  136. private FaceInfo m_FaceInfo;
  137. bool m_IncludeFontFeatures;
  138. public void OnEnable()
  139. {
  140. // Used for Diagnostics
  141. m_StopWatch = new System.Diagnostics.Stopwatch();
  142. // Set Editor window size.
  143. minSize = new Vector2(315, minSize.y);
  144. // Initialize & Get shader property IDs.
  145. ShaderUtilities.GetShaderPropertyIDs();
  146. // Load last selected preset if we are not already in the process of regenerating an existing font asset (via the Context menu)
  147. if (EditorPrefs.HasKey(k_FontAssetCreationSettingsContainerKey))
  148. {
  149. if (m_FontAssetCreationSettingsContainer == null)
  150. m_FontAssetCreationSettingsContainer = JsonUtility.FromJson<FontAssetCreationSettingsContainer>(EditorPrefs.GetString(k_FontAssetCreationSettingsContainerKey));
  151. if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings != null && m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 0)
  152. {
  153. // Load Font Asset Creation Settings preset.
  154. if (EditorPrefs.HasKey(k_FontAssetCreationSettingsCurrentIndexKey))
  155. m_FontAssetCreationSettingsCurrentIndex = EditorPrefs.GetInt(k_FontAssetCreationSettingsCurrentIndexKey);
  156. LoadFontCreationSettings(m_FontAssetCreationSettingsContainer.fontAssetCreationSettings[m_FontAssetCreationSettingsCurrentIndex]);
  157. }
  158. }
  159. ClearGeneratedData();
  160. }
  161. public void OnDisable()
  162. {
  163. //Debug.Log("TextMeshPro Editor Window has been disabled.");
  164. // Destroy Engine only if it has been initialized already
  165. FontEngine.DestroyFontEngine();
  166. ClearGeneratedData();
  167. // Remove Glyph Report if one was created.
  168. if (File.Exists("Assets/TextMesh Pro/Glyph Report.txt"))
  169. {
  170. File.Delete("Assets/TextMesh Pro/Glyph Report.txt");
  171. File.Delete("Assets/TextMesh Pro/Glyph Report.txt.meta");
  172. AssetDatabase.Refresh();
  173. }
  174. // Save Font Asset Creation Settings Index
  175. SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
  176. EditorPrefs.SetInt(k_FontAssetCreationSettingsCurrentIndexKey, m_FontAssetCreationSettingsCurrentIndex);
  177. // Unregister to event
  178. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  179. Resources.UnloadUnusedAssets();
  180. }
  181. // Event received when TMP resources have been loaded.
  182. void ON_RESOURCES_LOADED()
  183. {
  184. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  185. m_IsGenerationDisabled = false;
  186. }
  187. // Make sure TMP Essential Resources have been imported.
  188. void CheckEssentialResources()
  189. {
  190. if (TMP_Settings.instance == null)
  191. {
  192. if (m_IsGenerationDisabled == false)
  193. TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
  194. m_IsGenerationDisabled = true;
  195. }
  196. }
  197. public void OnGUI()
  198. {
  199. GUILayout.BeginHorizontal();
  200. DrawControls();
  201. if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
  202. {
  203. DrawPreview();
  204. }
  205. GUILayout.EndHorizontal();
  206. }
  207. public void Update()
  208. {
  209. if (m_IsRepaintNeeded)
  210. {
  211. //Debug.Log("Repainting...");
  212. m_IsRepaintNeeded = false;
  213. Repaint();
  214. }
  215. // Update Progress bar is we are Rendering a Font.
  216. if (m_IsProcessing)
  217. {
  218. m_AtlasGenerationProgress = FontEngine.generationProgress;
  219. m_IsRepaintNeeded = true;
  220. }
  221. if (m_IsGlyphPackingDone)
  222. {
  223. Debug.Log("Glyph packing completed in: " + m_GlyphPackingGenerationTime.ToString("0.000 ms."));
  224. m_IsGlyphPackingDone = false;
  225. }
  226. if (m_IsGlyphRenderingDone)
  227. {
  228. Debug.Log("Font Atlas generation completed in: " + m_GlyphRenderingGenerationTime.ToString("0.000 ms."));
  229. m_IsGlyphRenderingDone = false;
  230. }
  231. // Update Feedback Window & Create Font Texture once Rendering is done.
  232. if (m_IsRenderingDone)
  233. {
  234. m_IsProcessing = false;
  235. m_IsRenderingDone = false;
  236. if (m_IsGenerationCancelled == false)
  237. {
  238. m_AtlasGenerationProgressLabel = "Generation completed in: " + (m_GlyphPackingGenerationTime + m_GlyphRenderingGenerationTime).ToString("0.00 ms.");
  239. UpdateRenderFeedbackWindow();
  240. CreateFontAtlasTexture();
  241. // If dynamic make readable ...
  242. m_FontAtlasTexture.Apply(false, false);
  243. }
  244. Repaint();
  245. }
  246. }
  247. /// <summary>
  248. /// Method which returns the character corresponding to a decimal value.
  249. /// </summary>
  250. /// <param name="sequence"></param>
  251. /// <returns></returns>
  252. static uint[] ParseNumberSequence(string sequence)
  253. {
  254. List<uint> unicodeList = new List<uint>();
  255. string[] sequences = sequence.Split(',');
  256. foreach (string seq in sequences)
  257. {
  258. string[] s1 = seq.Split('-');
  259. if (s1.Length == 1)
  260. try
  261. {
  262. unicodeList.Add(uint.Parse(s1[0]));
  263. }
  264. catch
  265. {
  266. Debug.Log("No characters selected or invalid format.");
  267. }
  268. else
  269. {
  270. for (uint j = uint.Parse(s1[0]); j < uint.Parse(s1[1]) + 1; j++)
  271. {
  272. unicodeList.Add(j);
  273. }
  274. }
  275. }
  276. return unicodeList.ToArray();
  277. }
  278. /// <summary>
  279. /// Method which returns the character (decimal value) from a hex sequence.
  280. /// </summary>
  281. /// <param name="sequence"></param>
  282. /// <returns></returns>
  283. static uint[] ParseHexNumberSequence(string sequence)
  284. {
  285. List<uint> unicodeList = new List<uint>();
  286. string[] sequences = sequence.Split(',');
  287. foreach (string seq in sequences)
  288. {
  289. string[] s1 = seq.Split('-');
  290. if (s1.Length == 1)
  291. try
  292. {
  293. unicodeList.Add(uint.Parse(s1[0], NumberStyles.AllowHexSpecifier));
  294. }
  295. catch
  296. {
  297. Debug.Log("No characters selected or invalid format.");
  298. }
  299. else
  300. {
  301. for (uint j = uint.Parse(s1[0], NumberStyles.AllowHexSpecifier); j < uint.Parse(s1[1], NumberStyles.AllowHexSpecifier) + 1; j++)
  302. {
  303. unicodeList.Add(j);
  304. }
  305. }
  306. }
  307. return unicodeList.ToArray();
  308. }
  309. void DrawControls()
  310. {
  311. GUILayout.Space(5f);
  312. if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
  313. {
  314. m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition, GUILayout.Width(315));
  315. }
  316. else
  317. {
  318. m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
  319. }
  320. GUILayout.Space(5f);
  321. GUILayout.Label(m_SelectedFontAsset != null ? string.Format("Font Settings [{0}]", m_SelectedFontAsset.name) : "Font Settings", EditorStyles.boldLabel);
  322. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  323. EditorGUIUtility.labelWidth = 125f;
  324. EditorGUIUtility.fieldWidth = 5f;
  325. // Disable Options if already generating a font atlas texture.
  326. EditorGUI.BeginDisabledGroup(m_IsProcessing);
  327. {
  328. // FONT TTF SELECTION
  329. EditorGUI.BeginChangeCheck();
  330. m_SourceFontFile = EditorGUILayout.ObjectField("Source Font File", m_SourceFontFile, typeof(Font), false) as Font;
  331. if (EditorGUI.EndChangeCheck())
  332. {
  333. m_SelectedFontAsset = null;
  334. m_IsFontAtlasInvalid = true;
  335. }
  336. // FONT SIZING
  337. EditorGUI.BeginChangeCheck();
  338. if (m_PointSizeSamplingMode == 0)
  339. {
  340. m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions);
  341. }
  342. else
  343. {
  344. GUILayout.BeginHorizontal();
  345. m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions, GUILayout.Width(225));
  346. m_PointSize = EditorGUILayout.IntField(m_PointSize);
  347. GUILayout.EndHorizontal();
  348. }
  349. if (EditorGUI.EndChangeCheck())
  350. {
  351. m_IsFontAtlasInvalid = true;
  352. }
  353. // FONT PADDING
  354. EditorGUI.BeginChangeCheck();
  355. m_Padding = EditorGUILayout.IntField("Padding", m_Padding);
  356. m_Padding = (int)Mathf.Clamp(m_Padding, 0f, 64f);
  357. if (EditorGUI.EndChangeCheck())
  358. {
  359. m_IsFontAtlasInvalid = true;
  360. }
  361. // FONT PACKING METHOD SELECTION
  362. EditorGUI.BeginChangeCheck();
  363. m_PackingMode = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_PackingMode);
  364. if (EditorGUI.EndChangeCheck())
  365. {
  366. m_IsFontAtlasInvalid = true;
  367. }
  368. // FONT ATLAS RESOLUTION SELECTION
  369. GUILayout.BeginHorizontal();
  370. GUI.changed = false;
  371. EditorGUI.BeginChangeCheck();
  372. EditorGUILayout.PrefixLabel("Atlas Resolution");
  373. m_AtlasWidth = EditorGUILayout.IntPopup(m_AtlasWidth, m_FontResolutionLabels, m_FontAtlasResolutions);
  374. m_AtlasHeight = EditorGUILayout.IntPopup(m_AtlasHeight, m_FontResolutionLabels, m_FontAtlasResolutions);
  375. if (EditorGUI.EndChangeCheck())
  376. {
  377. m_IsFontAtlasInvalid = true;
  378. }
  379. GUILayout.EndHorizontal();
  380. // FONT CHARACTER SET SELECTION
  381. EditorGUI.BeginChangeCheck();
  382. bool hasSelectionChanged = false;
  383. m_CharacterSetSelectionMode = EditorGUILayout.Popup("Character Set", m_CharacterSetSelectionMode, m_FontCharacterSets);
  384. if (EditorGUI.EndChangeCheck())
  385. {
  386. m_CharacterSequence = "";
  387. hasSelectionChanged = true;
  388. m_IsFontAtlasInvalid = true;
  389. }
  390. switch (m_CharacterSetSelectionMode)
  391. {
  392. case 0: // ASCII
  393. //characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
  394. m_CharacterSequence = "32 - 126, 160, 8203, 8230, 9633";
  395. break;
  396. case 1: // EXTENDED ASCII
  397. m_CharacterSequence = "32 - 126, 160 - 255, 8192 - 8303, 8364, 8482, 9633";
  398. // Could add 9632 for missing glyph
  399. break;
  400. case 2: // Lowercase
  401. m_CharacterSequence = "32 - 64, 91 - 126, 160";
  402. break;
  403. case 3: // Uppercase
  404. m_CharacterSequence = "32 - 96, 123 - 126, 160";
  405. break;
  406. case 4: // Numbers & Symbols
  407. m_CharacterSequence = "32 - 64, 91 - 96, 123 - 126, 160";
  408. break;
  409. case 5: // Custom Range
  410. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  411. GUILayout.Label("Enter a sequence of decimal values to define the characters to be included in the font asset or retrieve one from another font asset.", TMP_UIStyleManager.label);
  412. GUILayout.Space(10f);
  413. EditorGUI.BeginChangeCheck();
  414. m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset;
  415. if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
  416. {
  417. if (m_ReferencedFontAsset != null)
  418. m_CharacterSequence = TMP_EditorUtility.GetDecimalCharacterSequence(TMP_FontAsset.GetCharactersArray(m_ReferencedFontAsset));
  419. m_IsFontAtlasInvalid = true;
  420. }
  421. // Filter out unwanted characters.
  422. char chr = Event.current.character;
  423. if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
  424. {
  425. Event.current.character = '\0';
  426. }
  427. GUILayout.Label("Character Sequence (Decimal)", EditorStyles.boldLabel);
  428. EditorGUI.BeginChangeCheck();
  429. m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
  430. if (EditorGUI.EndChangeCheck())
  431. {
  432. m_IsFontAtlasInvalid = true;
  433. }
  434. EditorGUILayout.EndVertical();
  435. break;
  436. case 6: // Unicode HEX Range
  437. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  438. GUILayout.Label("Enter a sequence of Unicode (hex) values to define the characters to be included in the font asset or retrieve one from another font asset.", TMP_UIStyleManager.label);
  439. GUILayout.Space(10f);
  440. EditorGUI.BeginChangeCheck();
  441. m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset;
  442. if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
  443. {
  444. if (m_ReferencedFontAsset != null)
  445. m_CharacterSequence = TMP_EditorUtility.GetUnicodeCharacterSequence(TMP_FontAsset.GetCharactersArray(m_ReferencedFontAsset));
  446. m_IsFontAtlasInvalid = true;
  447. }
  448. // Filter out unwanted characters.
  449. chr = Event.current.character;
  450. if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-'))
  451. {
  452. Event.current.character = '\0';
  453. }
  454. GUILayout.Label("Character Sequence (Hex)", EditorStyles.boldLabel);
  455. EditorGUI.BeginChangeCheck();
  456. m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
  457. if (EditorGUI.EndChangeCheck())
  458. {
  459. m_IsFontAtlasInvalid = true;
  460. }
  461. EditorGUILayout.EndVertical();
  462. break;
  463. case 7: // Characters from Font Asset
  464. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  465. GUILayout.Label("Type the characters to be included in the font asset or retrieve them from another font asset.", TMP_UIStyleManager.label);
  466. GUILayout.Space(10f);
  467. EditorGUI.BeginChangeCheck();
  468. m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset;
  469. if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
  470. {
  471. if (m_ReferencedFontAsset != null)
  472. m_CharacterSequence = TMP_FontAsset.GetCharacters(m_ReferencedFontAsset);
  473. m_IsFontAtlasInvalid = true;
  474. }
  475. EditorGUI.indentLevel = 0;
  476. GUILayout.Label("Custom Character List", EditorStyles.boldLabel);
  477. EditorGUI.BeginChangeCheck();
  478. m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
  479. if (EditorGUI.EndChangeCheck())
  480. {
  481. m_IsFontAtlasInvalid = true;
  482. }
  483. EditorGUILayout.EndVertical();
  484. break;
  485. case 8: // Character List from File
  486. EditorGUI.BeginChangeCheck();
  487. m_CharactersFromFile = EditorGUILayout.ObjectField("Character File", m_CharactersFromFile, typeof(TextAsset), false) as TextAsset;
  488. if (EditorGUI.EndChangeCheck())
  489. {
  490. m_IsFontAtlasInvalid = true;
  491. }
  492. if (m_CharactersFromFile != null)
  493. {
  494. Regex rx = new Regex(@"(?<!\\)(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})");
  495. m_CharacterSequence = rx.Replace(m_CharactersFromFile.text,
  496. match =>
  497. {
  498. if (match.Value.StartsWith("\\U"))
  499. return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\U", ""), NumberStyles.HexNumber));
  500. return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\u", ""), NumberStyles.HexNumber));
  501. });
  502. }
  503. break;
  504. }
  505. // FONT STYLE SELECTION
  506. //GUILayout.BeginHorizontal();
  507. //EditorGUI.BeginChangeCheck();
  508. ////m_FontStyle = (FaceStyles)EditorGUILayout.EnumPopup("Font Style", m_FontStyle, GUILayout.Width(225));
  509. ////m_FontStyleValue = EditorGUILayout.IntField((int)m_FontStyleValue);
  510. //if (EditorGUI.EndChangeCheck())
  511. //{
  512. // m_IsFontAtlasInvalid = true;
  513. //}
  514. //GUILayout.EndHorizontal();
  515. // Render Mode Selection
  516. CheckForLegacyGlyphRenderMode();
  517. EditorGUI.BeginChangeCheck();
  518. m_GlyphRenderMode = (GlyphRenderMode)EditorGUILayout.EnumPopup("Render Mode", m_GlyphRenderMode);
  519. if (EditorGUI.EndChangeCheck())
  520. {
  521. m_IsFontAtlasInvalid = true;
  522. }
  523. m_IncludeFontFeatures = EditorGUILayout.Toggle("Get Kerning Pairs", m_IncludeFontFeatures);
  524. EditorGUILayout.Space();
  525. }
  526. EditorGUI.EndDisabledGroup();
  527. if (!string.IsNullOrEmpty(m_WarningMessage))
  528. {
  529. EditorGUILayout.HelpBox(m_WarningMessage, MessageType.Warning);
  530. }
  531. GUI.enabled = m_SourceFontFile != null && !m_IsProcessing && !m_IsGenerationDisabled; // Enable Preview if we are not already rendering a font.
  532. if (GUILayout.Button("Generate Font Atlas") && GUI.enabled)
  533. {
  534. if (!m_IsProcessing && m_SourceFontFile != null)
  535. {
  536. DestroyImmediate(m_FontAtlasTexture);
  537. m_FontAtlasTexture = null;
  538. m_SavedFontAtlas = null;
  539. // Initialize font engine
  540. FontEngineError errorCode = FontEngine.InitializeFontEngine();
  541. if (errorCode != FontEngineError.Success)
  542. {
  543. Debug.Log("Font Asset Creator - Error [" + errorCode + "] has occurred while Initializing the FreeType Library.");
  544. }
  545. // Get file path of the source font file.
  546. string fontPath = AssetDatabase.GetAssetPath(m_SourceFontFile);
  547. if (errorCode == FontEngineError.Success)
  548. {
  549. errorCode = FontEngine.LoadFontFace(fontPath);
  550. if (errorCode != FontEngineError.Success)
  551. {
  552. Debug.Log("Font Asset Creator - Error Code [" + errorCode + "] has occurred trying to load the [" + m_SourceFontFile.name + "] font file. This typically results from the use of an incompatible or corrupted font file.", m_SourceFontFile);
  553. }
  554. }
  555. // Define an array containing the characters we will render.
  556. if (errorCode == FontEngineError.Success)
  557. {
  558. uint[] characterSet = null;
  559. // Get list of characters that need to be packed and rendered to the atlas texture.
  560. if (m_CharacterSetSelectionMode == 7 || m_CharacterSetSelectionMode == 8)
  561. {
  562. List<uint> char_List = new List<uint>();
  563. for (int i = 0; i < m_CharacterSequence.Length; i++)
  564. {
  565. uint unicode = m_CharacterSequence[i];
  566. // Handle surrogate pairs
  567. if (i < m_CharacterSequence.Length - 1 && char.IsHighSurrogate((char)unicode) && char.IsLowSurrogate(m_CharacterSequence[i + 1]))
  568. {
  569. unicode = (uint)char.ConvertToUtf32(m_CharacterSequence[i], m_CharacterSequence[i + 1]);
  570. i += 1;
  571. }
  572. // Check to make sure we don't include duplicates
  573. if (char_List.FindIndex(item => item == unicode) == -1)
  574. char_List.Add(unicode);
  575. }
  576. characterSet = char_List.ToArray();
  577. }
  578. else if (m_CharacterSetSelectionMode == 6)
  579. {
  580. characterSet = ParseHexNumberSequence(m_CharacterSequence);
  581. }
  582. else
  583. {
  584. characterSet = ParseNumberSequence(m_CharacterSequence);
  585. }
  586. m_CharacterCount = characterSet.Length;
  587. m_AtlasGenerationProgress = 0;
  588. m_IsProcessing = true;
  589. m_IsGenerationCancelled = false;
  590. GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_HINTED) == GlyphRasterModes.RASTER_MODE_HINTED
  591. ? GlyphLoadFlags.LOAD_RENDER
  592. : GlyphLoadFlags.LOAD_RENDER | GlyphLoadFlags.LOAD_NO_HINTING;
  593. glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_MONO) == GlyphRasterModes.RASTER_MODE_MONO
  594. ? glyphLoadFlags | GlyphLoadFlags.LOAD_MONOCHROME
  595. : glyphLoadFlags;
  596. //
  597. AutoResetEvent autoEvent = new AutoResetEvent(false);
  598. // Worker thread to pack glyphs in the given texture space.
  599. ThreadPool.QueueUserWorkItem(PackGlyphs =>
  600. {
  601. // Start Stop Watch
  602. m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
  603. // Clear the various lists used in the generation process.
  604. m_AvailableGlyphsToAdd.Clear();
  605. m_MissingCharacters.Clear();
  606. m_ExcludedCharacters.Clear();
  607. m_CharacterLookupMap.Clear();
  608. m_GlyphLookupMap.Clear();
  609. m_GlyphsToPack.Clear();
  610. m_GlyphsPacked.Clear();
  611. // Check if requested characters are available in the source font file.
  612. for (int i = 0; i < characterSet.Length; i++)
  613. {
  614. uint unicode = characterSet[i];
  615. uint glyphIndex;
  616. if (FontEngine.TryGetGlyphIndex(unicode, out glyphIndex))
  617. {
  618. // Skip over potential duplicate characters.
  619. if (m_CharacterLookupMap.ContainsKey(unicode))
  620. continue;
  621. // Add character to character lookup map.
  622. m_CharacterLookupMap.Add(unicode, glyphIndex);
  623. // Skip over potential duplicate glyph references.
  624. if (m_GlyphLookupMap.ContainsKey(glyphIndex))
  625. {
  626. // Add additional glyph reference for this character.
  627. m_GlyphLookupMap[glyphIndex].Add(unicode);
  628. continue;
  629. }
  630. // Add glyph reference to glyph lookup map.
  631. m_GlyphLookupMap.Add(glyphIndex, new List<uint>() { unicode });
  632. // Add glyph index to list of glyphs to add to texture.
  633. m_AvailableGlyphsToAdd.Add(glyphIndex);
  634. }
  635. else
  636. {
  637. // Add Unicode to list of missing characters.
  638. m_MissingCharacters.Add(unicode);
  639. }
  640. }
  641. // Pack available glyphs in the provided texture space.
  642. if (m_AvailableGlyphsToAdd.Count > 0)
  643. {
  644. int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  645. if (m_PointSizeSamplingMode == 0) // Auto-Sizing Point Size Mode
  646. {
  647. // Estimate min / max range for auto sizing of point size.
  648. int minPointSize = 0;
  649. int maxPointSize = (int)Mathf.Sqrt((m_AtlasWidth * m_AtlasHeight) / m_AvailableGlyphsToAdd.Count) * 3;
  650. m_PointSize = (maxPointSize + minPointSize) / 2;
  651. bool optimumPointSizeFound = false;
  652. for (int iteration = 0; iteration < 15 && optimumPointSizeFound == false; iteration++)
  653. {
  654. m_AtlasGenerationProgressLabel = "Packing glyphs - Pass (" + iteration + ")";
  655. FontEngine.SetFaceSize(m_PointSize);
  656. m_GlyphsToPack.Clear();
  657. m_GlyphsPacked.Clear();
  658. m_FreeGlyphRects.Clear();
  659. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  660. m_UsedGlyphRects.Clear();
  661. for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
  662. {
  663. uint glyphIndex = m_AvailableGlyphsToAdd[i];
  664. Glyph glyph;
  665. if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
  666. {
  667. if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
  668. {
  669. m_GlyphsToPack.Add(glyph);
  670. }
  671. else
  672. {
  673. m_GlyphsPacked.Add(glyph);
  674. }
  675. }
  676. }
  677. FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  678. if (m_IsGenerationCancelled)
  679. {
  680. DestroyImmediate(m_FontAtlasTexture);
  681. m_FontAtlasTexture = null;
  682. return;
  683. }
  684. //Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
  685. if (m_GlyphsToPack.Count > 0)
  686. {
  687. if (m_PointSize > minPointSize)
  688. {
  689. maxPointSize = m_PointSize;
  690. m_PointSize = (m_PointSize + minPointSize) / 2;
  691. //Debug.Log("Decreasing point size from [" + maxPointSize + "] to [" + m_PointSize + "].");
  692. }
  693. }
  694. else
  695. {
  696. if (maxPointSize - minPointSize > 1 && m_PointSize < maxPointSize)
  697. {
  698. minPointSize = m_PointSize;
  699. m_PointSize = (m_PointSize + maxPointSize) / 2;
  700. //Debug.Log("Increasing point size from [" + minPointSize + "] to [" + m_PointSize + "].");
  701. }
  702. else
  703. {
  704. //Debug.Log("[" + iteration + "] iterations to find the optimum point size of : [" + m_PointSize + "].");
  705. optimumPointSizeFound = true;
  706. }
  707. }
  708. }
  709. }
  710. else // Custom Point Size Mode
  711. {
  712. m_AtlasGenerationProgressLabel = "Packing glyphs...";
  713. // Set point size
  714. FontEngine.SetFaceSize(m_PointSize);
  715. m_GlyphsToPack.Clear();
  716. m_GlyphsPacked.Clear();
  717. m_FreeGlyphRects.Clear();
  718. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  719. m_UsedGlyphRects.Clear();
  720. for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
  721. {
  722. uint glyphIndex = m_AvailableGlyphsToAdd[i];
  723. Glyph glyph;
  724. if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
  725. {
  726. if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
  727. {
  728. m_GlyphsToPack.Add(glyph);
  729. }
  730. else
  731. {
  732. m_GlyphsPacked.Add(glyph);
  733. }
  734. }
  735. }
  736. FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  737. if (m_IsGenerationCancelled)
  738. {
  739. DestroyImmediate(m_FontAtlasTexture);
  740. m_FontAtlasTexture = null;
  741. return;
  742. }
  743. //Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
  744. }
  745. }
  746. else
  747. {
  748. int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  749. FontEngine.SetFaceSize(m_PointSize);
  750. m_GlyphsToPack.Clear();
  751. m_GlyphsPacked.Clear();
  752. m_FreeGlyphRects.Clear();
  753. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  754. m_UsedGlyphRects.Clear();
  755. }
  756. //Stop StopWatch
  757. m_StopWatch.Stop();
  758. m_GlyphPackingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds;
  759. m_IsGlyphPackingDone = true;
  760. m_StopWatch.Reset();
  761. m_FontCharacterTable.Clear();
  762. m_FontGlyphTable.Clear();
  763. m_GlyphsToRender.Clear();
  764. // Add glyphs and characters successfully added to texture to their respective font tables.
  765. foreach (Glyph glyph in m_GlyphsPacked)
  766. {
  767. uint glyphIndex = glyph.index;
  768. m_FontGlyphTable.Add(glyph);
  769. // Add glyphs to list of glyphs that need to be rendered.
  770. if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
  771. m_GlyphsToRender.Add(glyph);
  772. foreach (uint unicode in m_GlyphLookupMap[glyphIndex])
  773. {
  774. // Create new Character
  775. m_FontCharacterTable.Add(new TMP_Character(unicode, glyph));
  776. }
  777. }
  778. //
  779. foreach (Glyph glyph in m_GlyphsToPack)
  780. {
  781. foreach (uint unicode in m_GlyphLookupMap[glyph.index])
  782. {
  783. m_ExcludedCharacters.Add(unicode);
  784. }
  785. }
  786. // Get the face info for the current sampling point size.
  787. m_FaceInfo = FontEngine.GetFaceInfo();
  788. autoEvent.Set();
  789. });
  790. // Worker thread to render glyphs in texture buffer.
  791. ThreadPool.QueueUserWorkItem(RenderGlyphs =>
  792. {
  793. autoEvent.WaitOne();
  794. // Start Stop Watch
  795. m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
  796. m_IsRenderingDone = false;
  797. // Allocate texture data
  798. m_AtlasTextureBuffer = new byte[m_AtlasWidth * m_AtlasHeight];
  799. m_AtlasGenerationProgressLabel = "Rendering glyphs...";
  800. // Render and add glyphs to the given atlas texture.
  801. if (m_GlyphsToRender.Count > 0)
  802. {
  803. FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_Padding, m_GlyphRenderMode, m_AtlasTextureBuffer, m_AtlasWidth, m_AtlasHeight);
  804. }
  805. m_IsRenderingDone = true;
  806. // Stop StopWatch
  807. m_StopWatch.Stop();
  808. m_GlyphRenderingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds;
  809. m_IsGlyphRenderingDone = true;
  810. m_StopWatch.Reset();
  811. });
  812. }
  813. SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
  814. }
  815. }
  816. // FONT RENDERING PROGRESS BAR
  817. GUILayout.Space(1);
  818. Rect progressRect = EditorGUILayout.GetControlRect(false, 20);
  819. GUI.enabled = true;
  820. progressRect.width -= 22;
  821. EditorGUI.ProgressBar(progressRect, Mathf.Max(0.01f, m_AtlasGenerationProgress), m_AtlasGenerationProgressLabel);
  822. progressRect.x = progressRect.x + progressRect.width + 2;
  823. progressRect.y -= 1;
  824. progressRect.width = 20;
  825. progressRect.height = 20;
  826. GUI.enabled = m_IsProcessing;
  827. if (GUI.Button(progressRect, "X"))
  828. {
  829. FontEngine.SendCancellationRequest();
  830. m_AtlasGenerationProgress = 0;
  831. m_IsProcessing = false;
  832. m_IsGenerationCancelled = true;
  833. }
  834. GUILayout.Space(5);
  835. // FONT STATUS & INFORMATION
  836. GUI.enabled = true;
  837. GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(200));
  838. m_OutputScrollPosition = EditorGUILayout.BeginScrollView(m_OutputScrollPosition);
  839. EditorGUILayout.LabelField(m_OutputFeedback, TMP_UIStyleManager.label);
  840. EditorGUILayout.EndScrollView();
  841. GUILayout.EndVertical();
  842. // SAVE TEXTURE & CREATE and SAVE FONT XML FILE
  843. GUI.enabled = m_FontAtlasTexture != null && !m_IsProcessing; // Enable Save Button if font_Atlas is not Null.
  844. EditorGUILayout.BeginHorizontal();
  845. if (GUILayout.Button("Save") && GUI.enabled)
  846. {
  847. if (m_SelectedFontAsset == null)
  848. {
  849. if (m_LegacyFontAsset != null)
  850. SaveNewFontAssetWithSameName(m_LegacyFontAsset);
  851. else
  852. SaveNewFontAsset(m_SourceFontFile);
  853. }
  854. else
  855. {
  856. // Save over exiting Font Asset
  857. string filePath = Path.GetFullPath(AssetDatabase.GetAssetPath(m_SelectedFontAsset)).Replace('\\', '/');
  858. if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  859. Save_Bitmap_FontAsset(filePath);
  860. else
  861. Save_SDF_FontAsset(filePath);
  862. }
  863. }
  864. if (GUILayout.Button("Save as...") && GUI.enabled)
  865. {
  866. if (m_SelectedFontAsset == null)
  867. {
  868. SaveNewFontAsset(m_SourceFontFile);
  869. }
  870. else
  871. {
  872. SaveNewFontAssetWithSameName(m_SelectedFontAsset);
  873. }
  874. }
  875. EditorGUILayout.EndHorizontal();
  876. EditorGUILayout.Space();
  877. EditorGUILayout.EndVertical();
  878. GUI.enabled = true; // Re-enable GUI
  879. if (position.height > position.width || position.width < k_TwoColumnControlsWidth)
  880. {
  881. DrawPreview();
  882. GUILayout.Space(5);
  883. }
  884. EditorGUILayout.EndScrollView();
  885. if (m_IsFontAtlasInvalid)
  886. ClearGeneratedData();
  887. }
  888. /// <summary>
  889. /// Clear the previously generated data.
  890. /// </summary>
  891. void ClearGeneratedData()
  892. {
  893. m_IsFontAtlasInvalid = false;
  894. if (m_FontAtlasTexture != null && !EditorUtility.IsPersistent(m_FontAtlasTexture))
  895. {
  896. DestroyImmediate(m_FontAtlasTexture);
  897. m_FontAtlasTexture = null;
  898. }
  899. m_AtlasGenerationProgressLabel = string.Empty;
  900. m_AtlasGenerationProgress = 0;
  901. m_SavedFontAtlas = null;
  902. m_OutputFeedback = string.Empty;
  903. m_WarningMessage = string.Empty;
  904. }
  905. /// <summary>
  906. /// Function to update the feedback window showing the results of the latest generation.
  907. /// </summary>
  908. void UpdateRenderFeedbackWindow()
  909. {
  910. m_PointSize = m_FaceInfo.pointSize;
  911. string missingGlyphReport = string.Empty;
  912. //string colorTag = m_FontCharacterTable.Count == m_CharacterCount ? "<color=#C0ffff>" : "<color=#ffff00>";
  913. string colorTag2 = "<color=#C0ffff>";
  914. missingGlyphReport = "Font: <b>" + colorTag2 + m_FaceInfo.familyName + "</color></b> Style: <b>" + colorTag2 + m_FaceInfo.styleName + "</color></b>";
  915. missingGlyphReport += "\nPoint Size: <b>" + colorTag2 + m_FaceInfo.pointSize + "</color></b> SP/PD Ratio: <b>" + colorTag2 + ((float)m_Padding / m_FaceInfo.pointSize).ToString("0.0%" + "</color></b>");
  916. missingGlyphReport += "\n\nCharacters included: <color=#ffff00><b>" + m_FontCharacterTable.Count + "/" + m_CharacterCount + "</b></color>";
  917. missingGlyphReport += "\nMissing characters: <color=#ffff00><b>" + m_MissingCharacters.Count + "</b></color>";
  918. missingGlyphReport += "\nExcluded characters: <color=#ffff00><b>" + m_ExcludedCharacters.Count + "</b></color>";
  919. // Report characters missing from font file
  920. missingGlyphReport += "\n\n<b><color=#ffff00>Characters missing from font file:</color></b>";
  921. missingGlyphReport += "\n----------------------------------------";
  922. m_OutputFeedback = missingGlyphReport;
  923. for (int i = 0; i < m_MissingCharacters.Count; i++)
  924. {
  925. missingGlyphReport += "\nID: <color=#C0ffff>" + m_MissingCharacters[i] + "\t</color>Hex: <color=#C0ffff>" + m_MissingCharacters[i].ToString("X") + "\t</color>Char [<color=#C0ffff>" + (char)m_MissingCharacters[i] + "</color>]";
  926. if (missingGlyphReport.Length < 16300)
  927. m_OutputFeedback = missingGlyphReport;
  928. }
  929. // Report characters that did not fit in the atlas texture
  930. missingGlyphReport += "\n\n<b><color=#ffff00>Characters excluded from packing:</color></b>";
  931. missingGlyphReport += "\n----------------------------------------";
  932. for (int i = 0; i < m_ExcludedCharacters.Count; i++)
  933. {
  934. missingGlyphReport += "\nID: <color=#C0ffff>" + m_ExcludedCharacters[i] + "\t</color>Hex: <color=#C0ffff>" + m_ExcludedCharacters[i].ToString("X") + "\t</color>Char [<color=#C0ffff>" + (char)m_ExcludedCharacters[i] + "</color>]";
  935. if (missingGlyphReport.Length < 16300)
  936. m_OutputFeedback = missingGlyphReport;
  937. }
  938. if (missingGlyphReport.Length > 16300)
  939. m_OutputFeedback += "\n\n<color=#ffff00>Report truncated.</color>\n<color=#c0ffff>See</color> \"TextMesh Pro\\Glyph Report.txt\"";
  940. // Save Missing Glyph Report file
  941. if (Directory.Exists("Assets/TextMesh Pro"))
  942. {
  943. missingGlyphReport = System.Text.RegularExpressions.Regex.Replace(missingGlyphReport, @"<[^>]*>", string.Empty);
  944. File.WriteAllText("Assets/TextMesh Pro/Glyph Report.txt", missingGlyphReport);
  945. AssetDatabase.Refresh();
  946. }
  947. }
  948. void CreateFontAtlasTexture()
  949. {
  950. if (m_FontAtlasTexture != null)
  951. DestroyImmediate(m_FontAtlasTexture);
  952. m_FontAtlasTexture = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true);
  953. Color32[] colors = new Color32[m_AtlasWidth * m_AtlasHeight];
  954. for (int i = 0; i < colors.Length; i++)
  955. {
  956. byte c = m_AtlasTextureBuffer[i];
  957. colors[i] = new Color32(c, c, c, c);
  958. }
  959. // Clear allocation of
  960. m_AtlasTextureBuffer = null;
  961. if ((m_GlyphRenderMode & GlyphRenderMode.RASTER) == GlyphRenderMode.RASTER || (m_GlyphRenderMode & GlyphRenderMode.RASTER_HINTED) == GlyphRenderMode.RASTER_HINTED)
  962. m_FontAtlasTexture.filterMode = FilterMode.Point;
  963. m_FontAtlasTexture.SetPixels32(colors, 0);
  964. m_FontAtlasTexture.Apply(false, false);
  965. // Saving File for Debug
  966. //var pngData = m_FontAtlasTexture.EncodeToPNG();
  967. //File.WriteAllBytes("Assets/Textures/Debug Font Texture.png", pngData);
  968. }
  969. /// <summary>
  970. /// Open Save Dialog to provide the option save the font asset using the name of the source font file. This also appends SDF to the name if using any of the SDF Font Asset creation modes.
  971. /// </summary>
  972. /// <param name="sourceObject"></param>
  973. void SaveNewFontAsset(Object sourceObject)
  974. {
  975. string filePath;
  976. // Save new Font Asset and open save file requester at Source Font File location.
  977. string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName;
  978. if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  979. {
  980. filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset");
  981. if (filePath.Length == 0)
  982. return;
  983. Save_Bitmap_FontAsset(filePath);
  984. }
  985. else
  986. {
  987. filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name + " SDF", "asset");
  988. if (filePath.Length == 0)
  989. return;
  990. Save_SDF_FontAsset(filePath);
  991. }
  992. }
  993. /// <summary>
  994. /// Open Save Dialog to provide the option to save the font asset under the same name.
  995. /// </summary>
  996. /// <param name="sourceObject"></param>
  997. void SaveNewFontAssetWithSameName(Object sourceObject)
  998. {
  999. string filePath;
  1000. // Save new Font Asset and open save file requester at Source Font File location.
  1001. string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName;
  1002. filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset");
  1003. if (filePath.Length == 0)
  1004. return;
  1005. if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  1006. {
  1007. Save_Bitmap_FontAsset(filePath);
  1008. }
  1009. else
  1010. {
  1011. Save_SDF_FontAsset(filePath);
  1012. }
  1013. }
  1014. void Save_Bitmap_FontAsset(string filePath)
  1015. {
  1016. filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
  1017. string dataPath = Application.dataPath;
  1018. if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1)
  1019. {
  1020. Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
  1021. return;
  1022. }
  1023. string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
  1024. string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
  1025. string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
  1026. string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
  1027. // Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
  1028. TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TMP_FontAsset)) as TMP_FontAsset;
  1029. if (fontAsset == null)
  1030. {
  1031. //Debug.Log("Creating TextMeshPro font asset!");
  1032. fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>(); // Create new TextMeshPro Font Asset.
  1033. AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset");
  1034. // Set version number of font asset
  1035. fontAsset.version = "1.1.0";
  1036. //Set Font Asset Type
  1037. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1038. // Reference to the source font file GUID.
  1039. fontAsset.m_SourceFontFile_EditorRef = (Font)m_SourceFontFile;
  1040. fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile));
  1041. // Add FaceInfo to Font Asset
  1042. fontAsset.faceInfo = m_FaceInfo;
  1043. // Add GlyphInfo[] to Font Asset
  1044. fontAsset.glyphTable = m_FontGlyphTable;
  1045. // Add CharacterTable[] to font asset.
  1046. fontAsset.characterTable = m_FontCharacterTable;
  1047. // Sort glyph and character tables.
  1048. fontAsset.SortAllTables();
  1049. // Get and Add Kerning Pairs to Font Asset
  1050. if (m_IncludeFontFeatures)
  1051. fontAsset.fontFeatureTable = GetKerningTable();
  1052. // Add Font Atlas as Sub-Asset
  1053. fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
  1054. m_FontAtlasTexture.name = tex_FileName + " Atlas";
  1055. fontAsset.atlasWidth = m_AtlasWidth;
  1056. fontAsset.atlasHeight = m_AtlasHeight;
  1057. fontAsset.atlasPadding = m_Padding;
  1058. AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
  1059. // Create new Material and Add it as Sub-Asset
  1060. Shader default_Shader = Shader.Find("TextMeshPro/Bitmap"); // m_shaderSelection;
  1061. Material tmp_material = new Material(default_Shader);
  1062. tmp_material.name = tex_FileName + " Material";
  1063. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture);
  1064. fontAsset.material = tmp_material;
  1065. AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
  1066. }
  1067. else
  1068. {
  1069. // Find all Materials referencing this font atlas.
  1070. Material[] material_references = TMP_EditorUtility.FindMaterialReferences(fontAsset);
  1071. // Set version number of font asset
  1072. fontAsset.version = "1.1.0";
  1073. // Special handling to remove legacy font asset data
  1074. if (fontAsset.m_glyphInfoList != null && fontAsset.m_glyphInfoList.Count > 0)
  1075. fontAsset.m_glyphInfoList = null;
  1076. //Set Font Asset Type
  1077. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1078. // Add FaceInfo to Font Asset
  1079. fontAsset.faceInfo = m_FaceInfo;
  1080. // Add GlyphInfo[] to Font Asset
  1081. fontAsset.glyphTable = m_FontGlyphTable;
  1082. // Add CharacterTable[] to font asset.
  1083. fontAsset.characterTable = m_FontCharacterTable;
  1084. // Sort glyph and character tables.
  1085. fontAsset.SortAllTables();
  1086. // Get and Add Kerning Pairs to Font Asset
  1087. if (m_IncludeFontFeatures)
  1088. fontAsset.fontFeatureTable = GetKerningTable();
  1089. // Destroy Assets that will be replaced.
  1090. if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0)
  1091. {
  1092. for (int i = 1; i < fontAsset.atlasTextures.Length; i++)
  1093. DestroyImmediate(fontAsset.atlasTextures[i], true);
  1094. }
  1095. fontAsset.m_AtlasTextureIndex = 0;
  1096. fontAsset.atlasWidth = m_AtlasWidth;
  1097. fontAsset.atlasHeight = m_AtlasHeight;
  1098. fontAsset.atlasPadding = m_Padding;
  1099. // Make sure remaining atlas texture is of the correct size
  1100. Texture2D tex = fontAsset.atlasTextures[0];
  1101. tex.name = tex_FileName + " Atlas";
  1102. // Make texture readable to allow resizing
  1103. bool isReadableState = tex.isReadable;
  1104. if (isReadableState == false)
  1105. FontEngineEditorUtilities.SetAtlasTextureIsReadable(tex, true);
  1106. if (tex.width != m_AtlasWidth || tex.height != m_AtlasHeight)
  1107. {
  1108. tex.Resize(m_AtlasWidth, m_AtlasHeight);
  1109. tex.Apply();
  1110. }
  1111. // Copy new texture data to existing texture
  1112. Graphics.CopyTexture(m_FontAtlasTexture, tex);
  1113. // Apply changes to the texture.
  1114. tex.Apply(false, !isReadableState);
  1115. // Special handling due to a bug in earlier versions of Unity.
  1116. m_FontAtlasTexture.hideFlags = HideFlags.None;
  1117. fontAsset.material.hideFlags = HideFlags.None;
  1118. // Update the Texture reference on the Material
  1119. //for (int i = 0; i < material_references.Length; i++)
  1120. //{
  1121. // material_references[i].SetFloat(ShaderUtilities.ID_TextureWidth, tex.width);
  1122. // material_references[i].SetFloat(ShaderUtilities.ID_TextureHeight, tex.height);
  1123. // int spread = m_Padding;
  1124. // material_references[i].SetFloat(ShaderUtilities.ID_GradientScale, spread);
  1125. // material_references[i].SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  1126. // material_references[i].SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  1127. //}
  1128. }
  1129. // Add list of GlyphRects to font asset.
  1130. fontAsset.freeGlyphRects = m_FreeGlyphRects;
  1131. fontAsset.usedGlyphRects = m_UsedGlyphRects;
  1132. // Save Font Asset creation settings
  1133. m_SelectedFontAsset = fontAsset;
  1134. m_LegacyFontAsset = null;
  1135. fontAsset.creationSettings = SaveFontCreationSettings();
  1136. AssetDatabase.SaveAssets();
  1137. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version.
  1138. //EditorUtility.SetDirty(font_asset);
  1139. fontAsset.ReadFontAssetDefinition();
  1140. AssetDatabase.Refresh();
  1141. m_FontAtlasTexture = null;
  1142. // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
  1143. TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
  1144. }
  1145. void Save_SDF_FontAsset(string filePath)
  1146. {
  1147. filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
  1148. string dataPath = Application.dataPath;
  1149. if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1)
  1150. {
  1151. Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
  1152. return;
  1153. }
  1154. string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
  1155. string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
  1156. string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
  1157. string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
  1158. // Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
  1159. TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(tex_Path_NoExt + ".asset");
  1160. if (fontAsset == null)
  1161. {
  1162. //Debug.Log("Creating TextMeshPro font asset!");
  1163. fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>(); // Create new TextMeshPro Font Asset.
  1164. AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset");
  1165. // Set version number of font asset
  1166. fontAsset.version = "1.1.0";
  1167. // Reference to source font file GUID.
  1168. fontAsset.m_SourceFontFile_EditorRef = (Font)m_SourceFontFile;
  1169. fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile));
  1170. //Set Font Asset Type
  1171. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1172. // Add FaceInfo to Font Asset
  1173. fontAsset.faceInfo = m_FaceInfo;
  1174. // Add GlyphInfo[] to Font Asset
  1175. fontAsset.glyphTable = m_FontGlyphTable;
  1176. // Add CharacterTable[] to font asset.
  1177. fontAsset.characterTable = m_FontCharacterTable;
  1178. // Sort glyph and character tables.
  1179. fontAsset.SortAllTables();
  1180. // Get and Add Kerning Pairs to Font Asset
  1181. if (m_IncludeFontFeatures)
  1182. fontAsset.fontFeatureTable = GetKerningTable();
  1183. // Add Font Atlas as Sub-Asset
  1184. fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
  1185. m_FontAtlasTexture.name = tex_FileName + " Atlas";
  1186. fontAsset.atlasWidth = m_AtlasWidth;
  1187. fontAsset.atlasHeight = m_AtlasHeight;
  1188. fontAsset.atlasPadding = m_Padding;
  1189. AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
  1190. // Create new Material and Add it as Sub-Asset
  1191. Shader default_Shader = Shader.Find("TextMeshPro/Distance Field");
  1192. Material tmp_material = new Material(default_Shader);
  1193. tmp_material.name = tex_FileName + " Material";
  1194. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture);
  1195. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, m_FontAtlasTexture.width);
  1196. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, m_FontAtlasTexture.height);
  1197. int spread = m_Padding + 1;
  1198. tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
  1199. tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  1200. tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  1201. fontAsset.material = tmp_material;
  1202. AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
  1203. }
  1204. else
  1205. {
  1206. // Find all Materials referencing this font atlas.
  1207. Material[] material_references = TMP_EditorUtility.FindMaterialReferences(fontAsset);
  1208. // Set version number of font asset
  1209. fontAsset.version = "1.1.0";
  1210. // Special handling to remove legacy font asset data
  1211. if (fontAsset.m_glyphInfoList != null && fontAsset.m_glyphInfoList.Count > 0)
  1212. fontAsset.m_glyphInfoList = null;
  1213. //Set Font Asset Type
  1214. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1215. // Add FaceInfo to Font Asset
  1216. fontAsset.faceInfo = m_FaceInfo;
  1217. // Add GlyphInfo[] to Font Asset
  1218. fontAsset.glyphTable = m_FontGlyphTable;
  1219. // Add CharacterTable[] to font asset.
  1220. fontAsset.characterTable = m_FontCharacterTable;
  1221. // Sort glyph and character tables.
  1222. fontAsset.SortAllTables();
  1223. // Get and Add Kerning Pairs to Font Asset
  1224. // TODO: Check and preserve existing adjustment pairs.
  1225. if (m_IncludeFontFeatures)
  1226. fontAsset.fontFeatureTable = GetKerningTable();
  1227. // Destroy Assets that will be replaced.
  1228. if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0)
  1229. {
  1230. for (int i = 1; i < fontAsset.atlasTextures.Length; i++)
  1231. DestroyImmediate(fontAsset.atlasTextures[i], true);
  1232. }
  1233. fontAsset.m_AtlasTextureIndex = 0;
  1234. fontAsset.atlasWidth = m_AtlasWidth;
  1235. fontAsset.atlasHeight = m_AtlasHeight;
  1236. fontAsset.atlasPadding = m_Padding;
  1237. // Make sure remaining atlas texture is of the correct size
  1238. Texture2D tex = fontAsset.atlasTextures[0];
  1239. tex.name = tex_FileName + " Atlas";
  1240. // Make texture readable to allow resizing
  1241. bool isReadableState = tex.isReadable;
  1242. if (isReadableState == false)
  1243. FontEngineEditorUtilities.SetAtlasTextureIsReadable(tex, true);
  1244. if (tex.width != m_AtlasWidth || tex.height != m_AtlasHeight)
  1245. {
  1246. tex.Resize(m_AtlasWidth, m_AtlasHeight);
  1247. tex.Apply();
  1248. }
  1249. // Copy new texture data to existing texture
  1250. Graphics.CopyTexture(m_FontAtlasTexture, tex);
  1251. // Apply changes to the texture.
  1252. tex.Apply(false, !isReadableState);
  1253. // Special handling due to a bug in earlier versions of Unity.
  1254. m_FontAtlasTexture.hideFlags = HideFlags.None;
  1255. fontAsset.material.hideFlags = HideFlags.None;
  1256. // Update the Texture reference on the Material
  1257. for (int i = 0; i < material_references.Length; i++)
  1258. {
  1259. material_references[i].SetFloat(ShaderUtilities.ID_TextureWidth, tex.width);
  1260. material_references[i].SetFloat(ShaderUtilities.ID_TextureHeight, tex.height);
  1261. int spread = m_Padding + 1;
  1262. material_references[i].SetFloat(ShaderUtilities.ID_GradientScale, spread);
  1263. material_references[i].SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  1264. material_references[i].SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  1265. }
  1266. }
  1267. // Saving File for Debug
  1268. //var pngData = destination_Atlas.EncodeToPNG();
  1269. //File.WriteAllBytes("Assets/Textures/Debug Distance Field.png", pngData);
  1270. // Add list of GlyphRects to font asset.
  1271. fontAsset.freeGlyphRects = m_FreeGlyphRects;
  1272. fontAsset.usedGlyphRects = m_UsedGlyphRects;
  1273. // Save Font Asset creation settings
  1274. m_SelectedFontAsset = fontAsset;
  1275. m_LegacyFontAsset = null;
  1276. fontAsset.creationSettings = SaveFontCreationSettings();
  1277. AssetDatabase.SaveAssets();
  1278. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version.
  1279. fontAsset.ReadFontAssetDefinition();
  1280. AssetDatabase.Refresh();
  1281. m_FontAtlasTexture = null;
  1282. // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
  1283. TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
  1284. }
  1285. /// <summary>
  1286. /// Internal method to save the Font Asset Creation Settings
  1287. /// </summary>
  1288. /// <returns></returns>
  1289. FontAssetCreationSettings SaveFontCreationSettings()
  1290. {
  1291. FontAssetCreationSettings settings = new FontAssetCreationSettings();
  1292. //settings.sourceFontFileName = m_SourceFontFile.name;
  1293. settings.sourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile));
  1294. settings.pointSizeSamplingMode = m_PointSizeSamplingMode;
  1295. settings.pointSize = m_PointSize;
  1296. settings.padding = m_Padding;
  1297. settings.packingMode = (int)m_PackingMode;
  1298. settings.atlasWidth = m_AtlasWidth;
  1299. settings.atlasHeight = m_AtlasHeight;
  1300. settings.characterSetSelectionMode = m_CharacterSetSelectionMode;
  1301. settings.characterSequence = m_CharacterSequence;
  1302. settings.referencedFontAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_ReferencedFontAsset));
  1303. settings.referencedTextAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_CharactersFromFile));
  1304. //settings.fontStyle = (int)m_FontStyle;
  1305. //settings.fontStyleModifier = m_FontStyleValue;
  1306. settings.renderMode = (int)m_GlyphRenderMode;
  1307. settings.includeFontFeatures = m_IncludeFontFeatures;
  1308. return settings;
  1309. }
  1310. /// <summary>
  1311. /// Internal method to load the Font Asset Creation Settings
  1312. /// </summary>
  1313. /// <param name="settings"></param>
  1314. void LoadFontCreationSettings(FontAssetCreationSettings settings)
  1315. {
  1316. m_SourceFontFile = AssetDatabase.LoadAssetAtPath<Font>(AssetDatabase.GUIDToAssetPath(settings.sourceFontFileGUID));
  1317. m_PointSizeSamplingMode = settings.pointSizeSamplingMode;
  1318. m_PointSize = settings.pointSize;
  1319. m_Padding = settings.padding;
  1320. m_PackingMode = (FontPackingModes)settings.packingMode;
  1321. m_AtlasWidth = settings.atlasWidth;
  1322. m_AtlasHeight = settings.atlasHeight;
  1323. m_CharacterSetSelectionMode = settings.characterSetSelectionMode;
  1324. m_CharacterSequence = settings.characterSequence;
  1325. m_ReferencedFontAsset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(AssetDatabase.GUIDToAssetPath(settings.referencedFontAssetGUID));
  1326. m_CharactersFromFile = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(settings.referencedTextAssetGUID));
  1327. //m_FontStyle = (FaceStyles)settings.fontStyle;
  1328. //m_FontStyleValue = settings.fontStyleModifier;
  1329. m_GlyphRenderMode = (GlyphRenderMode)settings.renderMode;
  1330. m_IncludeFontFeatures = settings.includeFontFeatures;
  1331. }
  1332. /// <summary>
  1333. /// Save the latest font asset creation settings to EditorPrefs.
  1334. /// </summary>
  1335. /// <param name="settings"></param>
  1336. void SaveCreationSettingsToEditorPrefs(FontAssetCreationSettings settings)
  1337. {
  1338. // Create new list if one does not already exist
  1339. if (m_FontAssetCreationSettingsContainer == null)
  1340. {
  1341. m_FontAssetCreationSettingsContainer = new FontAssetCreationSettingsContainer();
  1342. m_FontAssetCreationSettingsContainer.fontAssetCreationSettings = new List<FontAssetCreationSettings>();
  1343. }
  1344. // Add new creation settings to the list
  1345. m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Add(settings);
  1346. // Since list should only contain the most 4 recent settings, we remove the first element if list exceeds 4 elements.
  1347. if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 4)
  1348. m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.RemoveAt(0);
  1349. m_FontAssetCreationSettingsCurrentIndex = m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count - 1;
  1350. // Serialize list to JSON
  1351. string serializedSettings = JsonUtility.ToJson(m_FontAssetCreationSettingsContainer, true);
  1352. EditorPrefs.SetString(k_FontAssetCreationSettingsContainerKey, serializedSettings);
  1353. }
  1354. void DrawPreview()
  1355. {
  1356. Rect pixelRect;
  1357. if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
  1358. {
  1359. float minSide = Mathf.Min(position.height - 15f, position.width - k_TwoColumnControlsWidth);
  1360. EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.MaxWidth(minSide));
  1361. pixelRect = GUILayoutUtility.GetRect(minSide, minSide, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
  1362. }
  1363. else
  1364. {
  1365. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  1366. pixelRect = GUILayoutUtility.GetAspectRect(1f);
  1367. }
  1368. if (m_FontAtlasTexture != null)
  1369. {
  1370. EditorGUI.DrawTextureAlpha(pixelRect, m_FontAtlasTexture, ScaleMode.StretchToFill);
  1371. }
  1372. else if (m_SavedFontAtlas != null)
  1373. {
  1374. EditorGUI.DrawTextureAlpha(pixelRect, m_SavedFontAtlas, ScaleMode.StretchToFill);
  1375. }
  1376. EditorGUILayout.EndVertical();
  1377. }
  1378. void CheckForLegacyGlyphRenderMode()
  1379. {
  1380. // Special handling for legacy glyph render mode
  1381. if ((int)m_GlyphRenderMode < 0x100)
  1382. {
  1383. switch ((int)m_GlyphRenderMode)
  1384. {
  1385. case 0:
  1386. m_GlyphRenderMode = GlyphRenderMode.SMOOTH_HINTED;
  1387. break;
  1388. case 1:
  1389. m_GlyphRenderMode = GlyphRenderMode.SMOOTH;
  1390. break;
  1391. case 2:
  1392. m_GlyphRenderMode = GlyphRenderMode.RASTER_HINTED;
  1393. break;
  1394. case 3:
  1395. m_GlyphRenderMode = GlyphRenderMode.RASTER;
  1396. break;
  1397. case 6:
  1398. case 7:
  1399. m_GlyphRenderMode = GlyphRenderMode.SDFAA;
  1400. break;
  1401. }
  1402. }
  1403. }
  1404. // Get Kerning Pairs
  1405. public TMP_FontFeatureTable GetKerningTable()
  1406. {
  1407. GlyphPairAdjustmentRecord[] adjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(m_AvailableGlyphsToAdd.ToArray());
  1408. if (adjustmentRecords == null)
  1409. return null;
  1410. TMP_FontFeatureTable fontFeatureTable = new TMP_FontFeatureTable();
  1411. for (int i = 0; i < adjustmentRecords.Length && adjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  1412. {
  1413. fontFeatureTable.glyphPairAdjustmentRecords.Add(new TMP_GlyphPairAdjustmentRecord(adjustmentRecords[i]));
  1414. }
  1415. fontFeatureTable.SortGlyphPairAdjustmentRecords();
  1416. return fontFeatureTable;
  1417. }
  1418. }
  1419. }