No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TMPro_FontAssetCreatorWindow.cs 84KB

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