TMP_FontAsset.cs 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. using UnityEngine.TextCore;
  5. using UnityEngine.TextCore.LowLevel;
  6. using UnityEngine.Profiling;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. namespace TMPro
  11. {
  12. public enum AtlasPopulationMode
  13. {
  14. Static = 0x0,
  15. Dynamic = 0x1,
  16. }
  17. [Serializable]
  18. public class TMP_FontAsset : TMP_Asset
  19. {
  20. /// <summary>
  21. /// The version of the font asset class.
  22. /// Version 1.1.0 adds support for the new TextCore.FontEngine and Dynamic SDF system.
  23. /// </summary>
  24. public string version
  25. {
  26. get { return m_Version; }
  27. internal set { m_Version = value; }
  28. }
  29. [SerializeField]
  30. private string m_Version;
  31. /// <summary>
  32. /// This field is set when the font asset is first created.
  33. /// </summary>
  34. [SerializeField]
  35. internal string m_SourceFontFileGUID;
  36. #if UNITY_EDITOR
  37. /// <summary>
  38. /// Persistent reference to the source font file maintained in the editor.
  39. /// </summary>
  40. [SerializeField]
  41. internal Font m_SourceFontFile_EditorRef;
  42. #endif
  43. /// <summary>
  44. /// Source font file when atlas population mode is set to dynamic. Null when the atlas population mode is set to static.
  45. /// </summary>
  46. public Font sourceFontFile
  47. {
  48. get { return m_SourceFontFile; }
  49. internal set { m_SourceFontFile = value; }
  50. }
  51. [SerializeField]
  52. private Font m_SourceFontFile;
  53. public AtlasPopulationMode atlasPopulationMode
  54. {
  55. get { return m_AtlasPopulationMode; }
  56. set
  57. {
  58. m_AtlasPopulationMode = value;
  59. #if UNITY_EDITOR
  60. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  61. m_SourceFontFile = null;
  62. else if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  63. m_SourceFontFile = m_SourceFontFile_EditorRef;
  64. #endif
  65. }
  66. }
  67. [SerializeField]
  68. private AtlasPopulationMode m_AtlasPopulationMode;
  69. /// <summary>
  70. /// Information about the font face.
  71. /// </summary>
  72. public FaceInfo faceInfo
  73. {
  74. get { return m_FaceInfo; }
  75. internal set { m_FaceInfo = value; }
  76. }
  77. [SerializeField]
  78. private FaceInfo m_FaceInfo;
  79. /// <summary>
  80. /// List of glyphs contained in the font asset.
  81. /// </summary>
  82. public List<Glyph> glyphTable
  83. {
  84. get { return m_GlyphTable; }
  85. internal set { m_GlyphTable = value; }
  86. }
  87. [SerializeField]
  88. private List<Glyph> m_GlyphTable = new List<Glyph>();
  89. /// <summary>
  90. /// Dictionary used to lookup glyphs contained in the font asset by their index.
  91. /// </summary>
  92. public Dictionary<uint, Glyph> glyphLookupTable
  93. {
  94. get
  95. {
  96. if (m_GlyphLookupDictionary == null)
  97. ReadFontAssetDefinition();
  98. return m_GlyphLookupDictionary;
  99. }
  100. }
  101. private Dictionary<uint, Glyph> m_GlyphLookupDictionary;
  102. /// <summary>
  103. /// List containing the characters of the given font asset.
  104. /// </summary>
  105. public List<TMP_Character> characterTable
  106. {
  107. get { return m_CharacterTable; }
  108. internal set { m_CharacterTable = value; }
  109. }
  110. [SerializeField]
  111. private List<TMP_Character> m_CharacterTable = new List<TMP_Character>();
  112. /// <summary>
  113. /// Dictionary used to lookup characters contained in the font asset by their unicode values.
  114. /// </summary>
  115. public Dictionary<uint, TMP_Character> characterLookupTable
  116. {
  117. get
  118. {
  119. if (m_CharacterLookupDictionary == null)
  120. ReadFontAssetDefinition();
  121. return m_CharacterLookupDictionary;
  122. }
  123. }
  124. private Dictionary<uint, TMP_Character> m_CharacterLookupDictionary;
  125. /// <summary>
  126. /// The font atlas used by this font asset.
  127. /// This is always the texture at index [0] of the fontAtlasTextures.
  128. /// </summary>
  129. public Texture2D atlasTexture
  130. {
  131. get
  132. {
  133. if (m_AtlasTexture == null)
  134. {
  135. m_AtlasTexture = atlasTextures[0];
  136. }
  137. return m_AtlasTexture;
  138. }
  139. }
  140. private Texture2D m_AtlasTexture;
  141. /// <summary>
  142. /// Array of atlas textures that contain the glyphs used by this font asset.
  143. /// </summary>
  144. public Texture2D[] atlasTextures
  145. {
  146. get
  147. {
  148. if (m_AtlasTextures == null)
  149. {
  150. //
  151. }
  152. return m_AtlasTextures;
  153. }
  154. set
  155. {
  156. m_AtlasTextures = value;
  157. }
  158. }
  159. [SerializeField]
  160. private Texture2D[] m_AtlasTextures;
  161. /// <summary>
  162. /// Index of the font atlas texture that still has available space to add new glyphs.
  163. /// </summary>
  164. [SerializeField]
  165. internal int m_AtlasTextureIndex;
  166. /// <summary>
  167. /// List of spaces occupied by glyphs in a given texture.
  168. /// </summary>
  169. internal List<GlyphRect> usedGlyphRects
  170. {
  171. get { return m_UsedGlyphRects; }
  172. set { m_UsedGlyphRects = value; }
  173. }
  174. [SerializeField]
  175. private List<GlyphRect> m_UsedGlyphRects;
  176. /// <summary>
  177. /// List of spaces available in a given texture to add new glyphs.
  178. /// </summary>
  179. internal List<GlyphRect> freeGlyphRects
  180. {
  181. get { return m_FreeGlyphRects; }
  182. set { m_FreeGlyphRects = value; }
  183. }
  184. [SerializeField]
  185. private List<GlyphRect> m_FreeGlyphRects;
  186. /// <summary>
  187. /// The general information about the font.
  188. /// This property and FaceInfo_Legacy type are not longer used in version 1.1.0 of the font asset.
  189. /// </summary>
  190. [Obsolete("The fontInfo property and underlying type is now obsolete. Please use the faceInfo property and FaceInfo type instead.")]
  191. public FaceInfo_Legacy fontInfo
  192. {
  193. get { return m_fontInfo; }
  194. }
  195. [SerializeField]
  196. private FaceInfo_Legacy m_fontInfo = null;
  197. /// <summary>
  198. ///
  199. /// </summary>
  200. [SerializeField]
  201. public Texture2D atlas; // Should add a property to make this read-only.
  202. /// <summary>
  203. /// The width of the atlas texture(s) used by this font asset.
  204. /// </summary>
  205. public int atlasWidth
  206. {
  207. get { return m_AtlasWidth; }
  208. internal set { m_AtlasWidth = value; }
  209. }
  210. [SerializeField]
  211. private int m_AtlasWidth;
  212. /// <summary>
  213. /// The height of the atlas texture(s) used by this font asset.
  214. /// </summary>
  215. public int atlasHeight
  216. {
  217. get { return m_AtlasHeight; }
  218. internal set { m_AtlasHeight = value; }
  219. }
  220. [SerializeField]
  221. private int m_AtlasHeight;
  222. /// <summary>
  223. /// The padding used between glyphs contained in the atlas texture(s) used by this font asset.
  224. /// </summary>
  225. public int atlasPadding
  226. {
  227. get { return m_AtlasPadding; }
  228. internal set { m_AtlasPadding = value; }
  229. }
  230. [SerializeField]
  231. private int m_AtlasPadding;
  232. public GlyphRenderMode atlasRenderMode
  233. {
  234. get { return m_AtlasRenderMode; }
  235. internal set { m_AtlasRenderMode = value; }
  236. }
  237. [SerializeField]
  238. private GlyphRenderMode m_AtlasRenderMode;
  239. // Legacy field that will eventually be removed.
  240. [SerializeField]
  241. internal List<TMP_Glyph> m_glyphInfoList;
  242. [SerializeField]
  243. [FormerlySerializedAs("m_kerningInfo")]
  244. internal KerningTable m_KerningTable = new KerningTable();
  245. /// <summary>
  246. /// Table containing the various font features of this font asset.
  247. /// </summary>
  248. public TMP_FontFeatureTable fontFeatureTable
  249. {
  250. get { return m_FontFeatureTable; }
  251. internal set { m_FontFeatureTable = value; }
  252. }
  253. [SerializeField]
  254. private TMP_FontFeatureTable m_FontFeatureTable = new TMP_FontFeatureTable();
  255. // Legacy field that will eventually be removed
  256. [SerializeField]
  257. #pragma warning disable 0649
  258. private List<TMP_FontAsset> fallbackFontAssets;
  259. /// <summary>
  260. /// List containing the Fallback font assets for this font.
  261. /// </summary>
  262. public List<TMP_FontAsset> fallbackFontAssetTable
  263. {
  264. get { return m_FallbackFontAssetTable; }
  265. set { m_FallbackFontAssetTable = value; }
  266. }
  267. [SerializeField]
  268. public List<TMP_FontAsset> m_FallbackFontAssetTable;
  269. /// <summary>
  270. /// The settings used in the Font Asset Creator when this font asset was created or edited.
  271. /// </summary>
  272. public FontAssetCreationSettings creationSettings
  273. {
  274. get { return m_CreationSettings; }
  275. set { m_CreationSettings = value; }
  276. }
  277. [SerializeField]
  278. internal FontAssetCreationSettings m_CreationSettings;
  279. /// <summary>
  280. /// Array containing font assets to be used as alternative typefaces for the various potential font weights of this font asset.
  281. /// </summary>
  282. public TMP_FontWeightPair[] fontWeightTable
  283. {
  284. get { return m_FontWeightTable; }
  285. internal set { m_FontWeightTable = value; }
  286. }
  287. [SerializeField]
  288. private TMP_FontWeightPair[] m_FontWeightTable = new TMP_FontWeightPair[10];
  289. // FONT WEIGHTS
  290. /// <summary>
  291. /// Font weights used by font asset prior to version 1.1.0.
  292. /// This is legacy and will be removed at some point in the future.
  293. /// </summary>
  294. [SerializeField]
  295. private TMP_FontWeightPair[] fontWeights = null;
  296. //private int[] m_characterSet; // Array containing all the characters in this font asset.
  297. /// <summary>
  298. /// Defines the dilation of the text when using regular style.
  299. /// </summary>
  300. public float normalStyle = 0;
  301. /// <summary>
  302. /// The spacing between characters when using regular style.
  303. /// </summary>
  304. public float normalSpacingOffset = 0;
  305. /// <summary>
  306. /// Defines the dilation of the text when using bold style.
  307. /// </summary>
  308. public float boldStyle = 0.75f;
  309. /// <summary>
  310. /// The spacing between characters when using regular style.
  311. /// </summary>
  312. public float boldSpacing = 7f;
  313. /// <summary>
  314. /// Defines the slant of the text when using italic style.
  315. /// </summary>
  316. public byte italicStyle = 35;
  317. public byte tabSize = 10;
  318. private byte m_oldTabSize;
  319. internal bool m_IsFontAssetLookupTablesDirty = false;
  320. /// <summary>
  321. /// Create new instance of a font asset using default settings.
  322. /// </summary>
  323. /// <param name="font"></param>
  324. /// <returns></returns>
  325. public static TMP_FontAsset CreateFontAsset(Font font)
  326. {
  327. return CreateFontAsset(font, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024, AtlasPopulationMode.Dynamic);
  328. }
  329. /// <summary>
  330. /// Create new instance of a font asset.
  331. /// </summary>
  332. /// <param name="font">The source font file.</param>
  333. /// <param name="samplingPointSize">The sampling point size.</param>
  334. /// <param name="atlasPadding">The padding / spread between individual glyphs in the font asset.</param>
  335. /// <param name="renderMode"></param>
  336. /// <param name="atlasWidth">The atlas texture width.</param>
  337. /// <param name="atlasHeight">The atlas texture height.</param>
  338. /// <param name="atlasPopulationMode"></param>
  339. /// <returns></returns>
  340. public static TMP_FontAsset CreateFontAsset(Font font, int samplingPointSize, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight, AtlasPopulationMode atlasPopulationMode = AtlasPopulationMode.Dynamic)
  341. {
  342. TMP_FontAsset fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>();
  343. fontAsset.m_Version = "1.1.0";
  344. // Set face information
  345. FontEngine.InitializeFontEngine();
  346. FontEngine.LoadFontFace(font, samplingPointSize);
  347. fontAsset.faceInfo = FontEngine.GetFaceInfo();
  348. // Set font reference and GUID
  349. if (atlasPopulationMode == AtlasPopulationMode.Dynamic)
  350. fontAsset.sourceFontFile = font;
  351. // Set persistent reference to source font file in the Editor only.
  352. #if UNITY_EDITOR
  353. UnityEditor.AssetDatabase.TryGetGUIDAndLocalFileIdentifier(font, out string guid, out long localID);
  354. fontAsset.m_SourceFontFileGUID = guid;
  355. fontAsset.m_SourceFontFile_EditorRef = font;
  356. #endif
  357. fontAsset.atlasPopulationMode = atlasPopulationMode;
  358. fontAsset.atlasWidth = atlasWidth;
  359. fontAsset.atlasHeight = atlasHeight;
  360. fontAsset.atlasPadding = atlasPadding;
  361. fontAsset.atlasRenderMode = renderMode;
  362. // Initialize array for the font atlas textures.
  363. fontAsset.atlasTextures = new Texture2D[1];
  364. // Create and add font atlas texture.
  365. Texture2D texture = new Texture2D(0, 0, TextureFormat.Alpha8, false);
  366. //texture.name = assetName + " Atlas";
  367. fontAsset.atlasTextures[0] = texture;
  368. // Add free rectangle of the size of the texture.
  369. int packingModifier;
  370. if (((GlyphRasterModes)renderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  371. {
  372. packingModifier = 0;
  373. // Optimize by adding static ref to shader.
  374. Material tmp_material = new Material(ShaderUtilities.ShaderRef_MobileBitmap);
  375. //tmp_material.name = texture.name + " Material";
  376. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
  377. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
  378. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
  379. fontAsset.material = tmp_material;
  380. }
  381. else
  382. {
  383. packingModifier = 1;
  384. // Optimize by adding static ref to shader.
  385. Material tmp_material = new Material(ShaderUtilities.ShaderRef_MobileSDF);
  386. //tmp_material.name = texture.name + " Material";
  387. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
  388. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
  389. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
  390. tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier);
  391. tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  392. tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  393. fontAsset.material = tmp_material;
  394. }
  395. fontAsset.freeGlyphRects = new List<GlyphRect>() { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) };
  396. fontAsset.usedGlyphRects = new List<GlyphRect>();
  397. // TODO: Consider adding support for extracting glyph positioning data
  398. fontAsset.ReadFontAssetDefinition();
  399. return fontAsset;
  400. }
  401. void Awake()
  402. {
  403. //Debug.Log("TMP Font Asset [" + this.name + "] with Version #" + m_Version + " has been enabled!");
  404. // Check version number of font asset to see if it needs to be upgraded.
  405. if (this.material != null && string.IsNullOrEmpty(m_Version))
  406. UpgradeFontAsset();
  407. }
  408. #if UNITY_EDITOR
  409. void OnValidate()
  410. {
  411. //if (m_oldTabSize != tabSize)
  412. //{
  413. // m_oldTabSize = tabSize;
  414. // ReadFontAssetDefinition();
  415. //}
  416. // Handle changes to atlas population mode
  417. //if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  418. // m_SourceFontFile = null;
  419. //else
  420. //{
  421. // string path = UnityEditor.AssetDatabase.GUIDToAssetPath(m_SourceFontFileGUID);
  422. // if (path != string.Empty)
  423. // m_SourceFontFile = UnityEditor.AssetDatabase.LoadAssetAtPath<Font>(path);
  424. //}
  425. }
  426. #endif
  427. /// <summary>
  428. /// Read the various data tables of the font asset to populate its different dictionaries to allow for faster lookup of related font asset data.
  429. /// </summary>
  430. internal void InitializeDictionaryLookupTables()
  431. {
  432. // Create new instance of the glyph lookup dictionary or clear the existing one.
  433. if (m_GlyphLookupDictionary == null)
  434. m_GlyphLookupDictionary = new Dictionary<uint, Glyph>();
  435. else
  436. m_GlyphLookupDictionary.Clear();
  437. int glyphCount = m_GlyphTable.Count;
  438. // Initialize glyph index array or clear the existing one.
  439. if (m_GlyphIndexList == null)
  440. m_GlyphIndexList = new List<uint>();
  441. else
  442. m_GlyphIndexList.Clear();
  443. // Add the characters contained in the character table into the dictionary for faster lookup.
  444. for (int i = 0; i < glyphCount; i++)
  445. {
  446. Glyph glyph = m_GlyphTable[i];
  447. uint index = glyph.index;
  448. // TODO: Not sure it is necessary to check here.
  449. if (m_GlyphLookupDictionary.ContainsKey(index) == false)
  450. {
  451. m_GlyphLookupDictionary.Add(index, glyph);
  452. m_GlyphIndexList.Add(index);
  453. }
  454. }
  455. // Create new instance of the character lookup dictionary or clear the existing one.
  456. if (m_CharacterLookupDictionary == null)
  457. m_CharacterLookupDictionary = new Dictionary<uint, TMP_Character>();
  458. else
  459. m_CharacterLookupDictionary.Clear();
  460. // Add the characters contained in the character table into the dictionary for faster lookup.
  461. for (int i = 0; i < m_CharacterTable.Count; i++)
  462. {
  463. TMP_Character character = m_CharacterTable[i];
  464. uint unicode = character.unicode;
  465. uint glyphIndex = character.glyphIndex;
  466. if (m_CharacterLookupDictionary.ContainsKey(unicode) == false)
  467. m_CharacterLookupDictionary.Add(unicode, character);
  468. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  469. {
  470. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  471. }
  472. }
  473. // Upgrade Glyph Adjustment Table to the new Font Feature table and Glyph Pair Adjustment Records
  474. if (m_KerningTable != null && m_KerningTable.kerningPairs != null && m_KerningTable.kerningPairs.Count > 0)
  475. UpgradeGlyphAdjustmentTableToFontFeatureTable();
  476. // Read Font Features which will include kerning data.
  477. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary == null)
  478. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary = new Dictionary<long, TMP_GlyphPairAdjustmentRecord>();
  479. else
  480. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Clear();
  481. List<TMP_GlyphPairAdjustmentRecord> glyphPairAdjustmentRecords = m_FontFeatureTable.m_GlyphPairAdjustmentRecords;
  482. if (glyphPairAdjustmentRecords != null)
  483. {
  484. for (int i = 0; i < glyphPairAdjustmentRecords.Count; i++)
  485. {
  486. TMP_GlyphPairAdjustmentRecord record = glyphPairAdjustmentRecords[i];
  487. long key = new GlyphPairKey(record).key;
  488. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(key, record);
  489. }
  490. }
  491. }
  492. /// <summary>
  493. ///
  494. /// </summary>
  495. public void ReadFontAssetDefinition()
  496. {
  497. //Debug.Log("Reading Font Definition for " + this.name + ".");
  498. // Check version number of font asset to see if it needs to be upgraded.
  499. if (this.material != null && string.IsNullOrEmpty(m_Version))
  500. UpgradeFontAsset();
  501. // Initialize lookup tables for characters and glyphs.
  502. InitializeDictionaryLookupTables();
  503. // Add Tab char(9) to Dictionary.
  504. if (m_CharacterLookupDictionary.ContainsKey(9) == false)
  505. {
  506. Glyph glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, m_FaceInfo.tabWidth * tabSize), GlyphRect.zero, 1.0f, 0);
  507. m_CharacterLookupDictionary.Add(9, new TMP_Character(9, glyph));
  508. }
  509. // Add Linefeed LF char(10) and Carriage Return CR char(13)
  510. if (m_CharacterLookupDictionary.ContainsKey(10) == false)
  511. {
  512. Glyph glyph = new Glyph(0, new GlyphMetrics(10, 0, 0, 0, 0), GlyphRect.zero, 1.0f, 0);
  513. m_CharacterLookupDictionary.Add(10, new TMP_Character(10, glyph));
  514. if (!m_CharacterLookupDictionary.ContainsKey(13))
  515. m_CharacterLookupDictionary.Add(13, new TMP_Character(13, glyph));
  516. }
  517. // Add Zero Width Space 8203 (0x200B)
  518. if (m_CharacterLookupDictionary.ContainsKey(8203) == false)
  519. {
  520. Glyph glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, 0), GlyphRect.zero, 1.0f, 0);
  521. m_CharacterLookupDictionary.Add(8203, new TMP_Character(8203, glyph));
  522. }
  523. // Add Zero Width Non-Breaking Space 8288 (0x2060)
  524. if (m_CharacterLookupDictionary.ContainsKey(8288) == false)
  525. {
  526. Glyph glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, 0), GlyphRect.zero, 1.0f, 0);
  527. m_CharacterLookupDictionary.Add(8288, new TMP_Character(8288, glyph));
  528. }
  529. // Add Non-Breaking Hyphen 8209 (0x2011)
  530. if (m_CharacterLookupDictionary.ContainsKey(8209) == false)
  531. {
  532. if (m_CharacterLookupDictionary.TryGetValue(45, out TMP_Character character))
  533. m_CharacterLookupDictionary.Add(8209, new TMP_Character(8209, character.glyph));
  534. }
  535. // Set Cap Height
  536. if (m_FaceInfo.capLine == 0 && m_CharacterLookupDictionary.ContainsKey(72))
  537. {
  538. uint glyphIndex = m_CharacterLookupDictionary[72].glyphIndex;
  539. m_FaceInfo.capLine = m_GlyphLookupDictionary[glyphIndex].metrics.horizontalBearingY;
  540. }
  541. // Adjust Font Scale for compatibility reasons
  542. if (m_FaceInfo.scale == 0)
  543. m_FaceInfo.scale = 1.0f;
  544. // Set Strikethrough Offset (if needed)
  545. if (m_FaceInfo.strikethroughOffset == 0)
  546. m_FaceInfo.strikethroughOffset = m_FaceInfo.capLine / 2.5f;
  547. // Set Padding value for legacy font assets.
  548. if (m_AtlasPadding == 0)
  549. {
  550. if (material.HasProperty(ShaderUtilities.ID_GradientScale))
  551. m_AtlasPadding = (int)material.GetFloat(ShaderUtilities.ID_GradientScale) - 1;
  552. }
  553. // Compute Hashcode for the font asset name
  554. hashCode = TMP_TextUtilities.GetSimpleHashCode(this.name);
  555. // Compute Hashcode for the material name
  556. materialHashCode = TMP_TextUtilities.GetSimpleHashCode(material.name);
  557. m_IsFontAssetLookupTablesDirty = false;
  558. }
  559. /// <summary>
  560. /// Sort the Character table by Unicode values.
  561. /// </summary>
  562. internal void SortCharacterTable()
  563. {
  564. if (m_CharacterTable != null && m_CharacterTable.Count > 0)
  565. m_CharacterTable = m_CharacterTable.OrderBy(c => c.unicode).ToList();
  566. }
  567. /// <summary>
  568. /// Sort the Glyph table by index values.
  569. /// </summary>
  570. internal void SortGlyphTable()
  571. {
  572. if (m_GlyphTable != null && m_GlyphTable.Count > 0)
  573. m_GlyphTable = m_GlyphTable.OrderBy(c => c.index).ToList();
  574. }
  575. /// <summary>
  576. /// Sort both glyph and character tables.
  577. /// </summary>
  578. internal void SortGlyphAndCharacterTables()
  579. {
  580. SortGlyphTable();
  581. SortCharacterTable();
  582. }
  583. /// <summary>
  584. /// Function to check if a certain character exists in the font asset.
  585. /// </summary>
  586. /// <param name="character"></param>
  587. /// <returns></returns>
  588. public bool HasCharacter(int character)
  589. {
  590. if (m_CharacterLookupDictionary == null)
  591. return false;
  592. if (m_CharacterLookupDictionary.ContainsKey((uint)character))
  593. return true;
  594. return false;
  595. }
  596. /// <summary>
  597. /// Function to check if a certain character exists in the font asset.
  598. /// </summary>
  599. /// <param name="character"></param>
  600. /// <returns></returns>
  601. public bool HasCharacter(char character)
  602. {
  603. if (m_CharacterLookupDictionary == null)
  604. return false;
  605. if (m_CharacterLookupDictionary.ContainsKey(character))
  606. return true;
  607. return false;
  608. }
  609. /// <summary>
  610. /// Function to check if a character is contained in the font asset with the option to also check through fallback font assets.
  611. /// </summary>
  612. /// <param name="character"></param>
  613. /// <param name="searchFallbacks"></param>
  614. /// <returns></returns>
  615. public bool HasCharacter(char character, bool searchFallbacks)
  616. {
  617. // Read font asset definition if it hasn't already been done.
  618. if (m_CharacterLookupDictionary == null)
  619. {
  620. ReadFontAssetDefinition();
  621. if (m_CharacterLookupDictionary == null)
  622. return false;
  623. }
  624. // Check font asset
  625. if (m_CharacterLookupDictionary.ContainsKey(character))
  626. return true;
  627. // Check if font asset is dynamic and if so try to add the requested character to it.
  628. if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  629. {
  630. if (TryAddCharacterInternal(character, out TMP_Character temp))
  631. return true;
  632. }
  633. if (searchFallbacks)
  634. {
  635. // Check font asset fallbacks
  636. if (fallbackFontAssetTable != null && fallbackFontAssetTable.Count > 0)
  637. {
  638. for (int i = 0; i < fallbackFontAssetTable.Count && fallbackFontAssetTable[i] != null; i++)
  639. {
  640. if (fallbackFontAssetTable[i].HasCharacter_Internal(character, searchFallbacks))
  641. return true;
  642. }
  643. }
  644. // Check general fallback font assets.
  645. if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  646. {
  647. for (int i = 0; i < TMP_Settings.fallbackFontAssets.Count && TMP_Settings.fallbackFontAssets[i] != null; i++)
  648. {
  649. if (TMP_Settings.fallbackFontAssets[i].m_CharacterLookupDictionary == null)
  650. TMP_Settings.fallbackFontAssets[i].ReadFontAssetDefinition();
  651. if (TMP_Settings.fallbackFontAssets[i].m_CharacterLookupDictionary != null && TMP_Settings.fallbackFontAssets[i].HasCharacter_Internal(character, searchFallbacks))
  652. return true;
  653. }
  654. }
  655. // Check TMP Settings Default Font Asset
  656. if (TMP_Settings.defaultFontAsset != null)
  657. {
  658. if (TMP_Settings.defaultFontAsset.m_CharacterLookupDictionary == null)
  659. TMP_Settings.defaultFontAsset.ReadFontAssetDefinition();
  660. if (TMP_Settings.defaultFontAsset.m_CharacterLookupDictionary != null && TMP_Settings.defaultFontAsset.HasCharacter_Internal(character, searchFallbacks))
  661. return true;
  662. }
  663. }
  664. return false;
  665. }
  666. /// <summary>
  667. /// Function to check if a character is contained in a font asset with the option to also check through fallback font assets.
  668. /// This private implementation does not search the fallback font asset in the TMP Settings file.
  669. /// </summary>
  670. /// <param name="character"></param>
  671. /// <param name="searchFallbacks"></param>
  672. /// <returns></returns>
  673. bool HasCharacter_Internal(char character, bool searchFallbacks)
  674. {
  675. // Read font asset definition if it hasn't already been done.
  676. if (m_CharacterLookupDictionary == null)
  677. {
  678. ReadFontAssetDefinition();
  679. if (m_CharacterLookupDictionary == null)
  680. return false;
  681. }
  682. // Check font asset
  683. if (m_CharacterLookupDictionary.ContainsKey(character))
  684. return true;
  685. if (searchFallbacks)
  686. {
  687. // Check Font Asset Fallback fonts.
  688. if (fallbackFontAssetTable != null && fallbackFontAssetTable.Count > 0)
  689. {
  690. for (int i = 0; i < fallbackFontAssetTable.Count && fallbackFontAssetTable[i] != null; i++)
  691. {
  692. if (fallbackFontAssetTable[i].HasCharacter_Internal(character, searchFallbacks))
  693. return true;
  694. }
  695. }
  696. }
  697. return false;
  698. }
  699. /// <summary>
  700. /// Function to check if certain characters exists in the font asset. Function returns a list of missing characters.
  701. /// </summary>
  702. /// <param name="character"></param>
  703. /// <returns></returns>
  704. public bool HasCharacters(string text, out List<char> missingCharacters)
  705. {
  706. if (m_CharacterLookupDictionary == null)
  707. {
  708. missingCharacters = null;
  709. return false;
  710. }
  711. missingCharacters = new List<char>();
  712. for (int i = 0; i < text.Length; i++)
  713. {
  714. if (!m_CharacterLookupDictionary.ContainsKey(text[i]))
  715. missingCharacters.Add(text[i]);
  716. }
  717. if (missingCharacters.Count == 0)
  718. return true;
  719. return false;
  720. }
  721. /// <summary>
  722. /// Function to check if certain characters exists in the font asset. Function returns false if any characters are missing.
  723. /// </summary>
  724. /// <param name="text">String containing the characters to check</param>
  725. /// <returns></returns>
  726. public bool HasCharacters(string text)
  727. {
  728. if (m_CharacterLookupDictionary == null)
  729. return false;
  730. for (int i = 0; i < text.Length; i++)
  731. {
  732. if (!m_CharacterLookupDictionary.ContainsKey(text[i]))
  733. return false;
  734. }
  735. return true;
  736. }
  737. /// <summary>
  738. /// Function to extract all the characters from a font asset.
  739. /// </summary>
  740. /// <param name="fontAsset"></param>
  741. /// <returns></returns>
  742. public static string GetCharacters(TMP_FontAsset fontAsset)
  743. {
  744. string characters = string.Empty;
  745. for (int i = 0; i < fontAsset.characterTable.Count; i++)
  746. {
  747. characters += (char)fontAsset.characterTable[i].unicode;
  748. }
  749. return characters;
  750. }
  751. /// <summary>
  752. /// Function which returns an array that contains all the characters from a font asset.
  753. /// </summary>
  754. /// <param name="fontAsset"></param>
  755. /// <returns></returns>
  756. public static int[] GetCharactersArray(TMP_FontAsset fontAsset)
  757. {
  758. int[] characters = new int[fontAsset.characterTable.Count];
  759. for (int i = 0; i < fontAsset.characterTable.Count; i++)
  760. {
  761. characters[i] = (int)fontAsset.characterTable[i].unicode;
  762. }
  763. return characters;
  764. }
  765. // ================================================================================
  766. // Properties and functions related to character and glyph additions as well as
  767. // tacking glyphs that need to be added to various font asset atlas textures.
  768. // ================================================================================
  769. /// <summary>
  770. /// Determines if the font asset is already registered to be updated.
  771. /// </summary>
  772. //private bool m_IsAlreadyRegisteredForUpdate;
  773. /// <summary>
  774. /// List of glyphs that need to be added / packed in atlas texture.
  775. /// </summary>
  776. private List<Glyph> m_GlyphsToPack = new List<Glyph>();
  777. /// <summary>
  778. /// List of glyphs that have been packed in the atlas texture and ready to be rendered.
  779. /// </summary>
  780. private List<Glyph> m_GlyphsPacked = new List<Glyph>();
  781. /// <summary>
  782. ///
  783. /// </summary>
  784. private List<Glyph> m_GlyphsToRender = new List<Glyph>();
  785. /// <summary>
  786. /// List used in the process of adding new glyphs to the atlas texture.
  787. /// </summary>
  788. private List<uint> m_GlyphIndexList = new List<uint>();
  789. private List<TMP_Character> m_CharactersToAdd = new List<TMP_Character>();
  790. /// <summary>
  791. /// Internal static array used to avoid allocations when using the GetGlyphPairAdjustmentTable().
  792. /// </summary>
  793. internal static uint[] s_GlyphIndexArray = new uint[16];
  794. /// <summary>
  795. /// Internal static list used to track characters that could not be added to the font asset.
  796. /// </summary>
  797. internal static List<uint> s_MissingCharacterList = new List<uint>(16);
  798. /// <summary>
  799. /// Try adding the characters from the provided string to the font asset.
  800. /// </summary>
  801. /// <param name="unicodes">Array that contains the characters to add to the font asset.</param>
  802. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  803. public bool TryAddCharacters(uint[] unicodes)
  804. {
  805. return TryAddCharacters(unicodes, out uint[] missingUnicodes);
  806. }
  807. /// <summary>
  808. /// Try adding the characters from the provided string to the font asset.
  809. /// </summary>
  810. /// <param name="unicodes">Array that contains the characters to add to the font asset.</param>
  811. /// <param name="missingUnicodes">Array containing the characters that could not be added to the font asset.</param>
  812. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  813. public bool TryAddCharacters(uint[] unicodes, out uint[] missingUnicodes)
  814. {
  815. s_MissingCharacterList.Clear();
  816. // Make sure font asset is set to dynamic and that we have a valid list of characters.
  817. if (unicodes == null || unicodes.Length == 0 || m_AtlasPopulationMode == AtlasPopulationMode.Static)
  818. {
  819. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  820. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this);
  821. else
  822. {
  823. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided Unicode list is Null or Empty.", this);
  824. }
  825. missingUnicodes = unicodes.ToArray();
  826. return false;
  827. }
  828. Profiler.BeginSample("TMP.TryAddCharacter");
  829. // Load font face.
  830. if (FontEngine.LoadFontFace(m_SourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  831. {
  832. Profiler.EndSample();
  833. missingUnicodes = unicodes.ToArray();
  834. return false;
  835. }
  836. // Clear data structures used to track which glyph needs to be added to atlas texture.
  837. m_GlyphIndexList.Clear();
  838. m_CharactersToAdd.Clear();
  839. bool isMissingCharacters = false;
  840. int unicodeCount = unicodes.Length;
  841. for (int i = 0; i < unicodeCount; i++)
  842. {
  843. uint unicode = unicodes[i];
  844. // Check if character is already contained in the character table.
  845. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  846. continue;
  847. // Get the index of the glyph for this unicode value.
  848. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  849. if (glyphIndex == 0)
  850. {
  851. isMissingCharacters = true;
  852. continue;
  853. }
  854. TMP_Character character = new TMP_Character(unicode, glyphIndex);
  855. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  856. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  857. {
  858. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  859. m_CharacterTable.Add(character);
  860. m_CharacterLookupDictionary.Add(unicode, character);
  861. continue;
  862. }
  863. m_GlyphIndexList.Add(glyphIndex);
  864. m_CharactersToAdd.Add(character);
  865. }
  866. if (m_GlyphIndexList.Count == 0)
  867. {
  868. //Debug.LogWarning("No characters will be added to font asset [" + this.name + "] either because they are already present in the font asset or missing from the font file.");
  869. Profiler.EndSample();
  870. missingUnicodes = unicodes.ToArray();
  871. return false;
  872. }
  873. // Resize the Atlas Texture to the appropriate size
  874. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  875. {
  876. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  877. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  878. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  879. }
  880. bool allCharactersAdded = FontEngine.TryAddGlyphsToTexture(m_GlyphIndexList, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out Glyph[] glyphs);
  881. // Add new glyphs to relevant data structures.
  882. for (int i = 0; i < glyphs.Length; i++)
  883. {
  884. Glyph glyph = glyphs[i];
  885. uint glyphIndex = glyph.index;
  886. // Add new glyph to glyph table.
  887. m_GlyphTable.Add(glyph);
  888. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  889. }
  890. // Add new characters to relevant data structures.
  891. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  892. {
  893. TMP_Character character = m_CharactersToAdd[i];
  894. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out Glyph glyph) == false)
  895. {
  896. s_MissingCharacterList.Add(character.unicode);
  897. continue;
  898. }
  899. character.glyph = glyph;
  900. m_CharacterTable.Add(character);
  901. m_CharacterLookupDictionary.Add(character.unicode, character);
  902. }
  903. #if UNITY_EDITOR
  904. // Makes the changes to the font asset persistent.
  905. if (UnityEditor.EditorUtility.IsPersistent(this))
  906. {
  907. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  908. }
  909. #endif
  910. Profiler.EndSample();
  911. missingUnicodes = null;
  912. if (s_MissingCharacterList.Count > 0)
  913. missingUnicodes = s_MissingCharacterList.ToArray();
  914. return allCharactersAdded && !isMissingCharacters;
  915. }
  916. /// <summary>
  917. /// Try adding the characters from the provided string to the font asset.
  918. /// </summary>
  919. /// <param name="characters">String containing the characters to add to the font asset.</param>
  920. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  921. public bool TryAddCharacters(string characters)
  922. {
  923. return TryAddCharacters(characters, out string missingCharacters);
  924. }
  925. /// <summary>
  926. /// Try adding the characters from the provided string to the font asset.
  927. /// </summary>
  928. /// <param name="characters">String containing the characters to add to the font asset.</param>
  929. /// <param name="missingCharacters">String containing the characters that could not be added to the font asset.</param>
  930. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  931. public bool TryAddCharacters(string characters, out string missingCharacters)
  932. {
  933. // Make sure font asset is set to dynamic and that we have a valid list of characters.
  934. if (string.IsNullOrEmpty(characters) || m_AtlasPopulationMode == AtlasPopulationMode.Static)
  935. {
  936. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  937. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this);
  938. else
  939. {
  940. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided character list is Null or Empty.", this);
  941. }
  942. missingCharacters = characters;
  943. return false;
  944. }
  945. // Load font face.
  946. if (FontEngine.LoadFontFace(m_SourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  947. {
  948. missingCharacters = characters;
  949. return false;
  950. }
  951. // Clear data structures used to track which glyph needs to be added to atlas texture.
  952. m_GlyphIndexList.Clear();
  953. m_CharactersToAdd.Clear();
  954. bool isMissingCharacters = false;
  955. int characterCount = characters.Length;
  956. // Iterate over each of the requested characters.
  957. for (int i = 0; i < characterCount; i++)
  958. {
  959. uint unicode = characters[i];
  960. // Check if character is already contained in the character table.
  961. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  962. continue;
  963. // Get the index of the glyph for this unicode value.
  964. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  965. // Skip missing glyphs
  966. if (glyphIndex == 0)
  967. {
  968. // Might want to keep track and report the missing characters.
  969. isMissingCharacters = true;
  970. continue;
  971. }
  972. TMP_Character character = new TMP_Character(unicode, glyphIndex);
  973. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  974. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  975. {
  976. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  977. m_CharacterTable.Add(character);
  978. m_CharacterLookupDictionary.Add(unicode, character);
  979. continue;
  980. }
  981. // Add glyph to list of glyphs to add and glyph lookup map.
  982. m_GlyphIndexList.Add(glyphIndex);
  983. m_CharactersToAdd.Add(character);
  984. }
  985. if (m_GlyphIndexList.Count == 0)
  986. {
  987. missingCharacters = characters;
  988. return false;
  989. }
  990. // Resize the Atlas Texture to the appropriate size
  991. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  992. {
  993. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  994. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  995. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  996. }
  997. bool allCharactersAdded = FontEngine.TryAddGlyphsToTexture(m_GlyphIndexList, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out Glyph[] glyphs);
  998. for (int i = 0; i < glyphs.Length; i++)
  999. {
  1000. Glyph glyph = glyphs[i];
  1001. uint glyphIndex = glyph.index;
  1002. // Add new glyph to glyph table.
  1003. m_GlyphTable.Add(glyph);
  1004. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1005. }
  1006. missingCharacters = string.Empty;
  1007. // Add new characters to relevant data structures.
  1008. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1009. {
  1010. TMP_Character character = m_CharactersToAdd[i];
  1011. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out Glyph glyph) == false)
  1012. {
  1013. // TODO: Revise to avoid string concatenation.
  1014. missingCharacters += (char)character.unicode;
  1015. continue;
  1016. }
  1017. character.glyph = glyph;
  1018. m_CharacterTable.Add(character);
  1019. m_CharacterLookupDictionary.Add(character.unicode, character);
  1020. }
  1021. #if UNITY_EDITOR
  1022. // Makes the changes to the font asset persistent.
  1023. if (UnityEditor.EditorUtility.IsPersistent(this))
  1024. {
  1025. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1026. }
  1027. #endif
  1028. return allCharactersAdded && !isMissingCharacters;
  1029. }
  1030. /// <summary>
  1031. /// NOT USED CURRENTLY - Try adding character using Unicode value to font asset.
  1032. /// </summary>
  1033. /// <param name="unicode">The Unicode value of the character.</param>
  1034. /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param>
  1035. /// <returns>Returns true if the character has been added. False otherwise.</returns>
  1036. internal bool TryAddCharacter_Internal(uint unicode)
  1037. {
  1038. TMP_Character character = null;
  1039. // Check if character is already contained in the character table.
  1040. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1041. return true;
  1042. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1043. if (glyphIndex == 0)
  1044. return false;
  1045. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1046. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1047. {
  1048. character = new TMP_Character(unicode, m_GlyphLookupDictionary[glyphIndex]);
  1049. m_CharacterTable.Add(character);
  1050. m_CharacterLookupDictionary.Add(unicode, character);
  1051. //#if UNITY_EDITOR
  1052. // Makes the changes to the font asset persistent.
  1053. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1054. // Could also add some update registry to handle this.
  1055. //SortGlyphTable();
  1056. //UnityEditor.EditorUtility.SetDirty(this);
  1057. //#endif
  1058. return true;
  1059. }
  1060. // Resize the Atlas Texture to the appropriate size
  1061. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1062. {
  1063. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1064. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1065. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1066. }
  1067. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out Glyph glyph))
  1068. {
  1069. // Add new glyph to glyph table.
  1070. m_GlyphTable.Add(glyph);
  1071. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1072. // Add new character
  1073. character = new TMP_Character(unicode, glyph);
  1074. m_CharacterTable.Add(character);
  1075. m_CharacterLookupDictionary.Add(unicode, character);
  1076. //#if UNITY_EDITOR
  1077. // Makes the changes to the font asset persistent.
  1078. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1079. // Could also add some update registry to handle this.
  1080. //SortGlyphTable();
  1081. //UnityEditor.EditorUtility.SetDirty(this);
  1082. //#endif
  1083. return true;
  1084. }
  1085. return false;
  1086. }
  1087. /// <summary>
  1088. /// To be removed.
  1089. /// </summary>
  1090. /// <param name="unicode"></param>
  1091. /// <param name="glyph"></param>
  1092. internal TMP_Character AddCharacter_Internal(uint unicode, Glyph glyph)
  1093. {
  1094. // Check if character is already contained in the character table.
  1095. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1096. return m_CharacterLookupDictionary[unicode];
  1097. uint glyphIndex = glyph.index;
  1098. // Resize the Atlas Texture to the appropriate size
  1099. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1100. {
  1101. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1102. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1103. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1104. }
  1105. // Check if glyph is already contained in the glyph table.
  1106. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex) == false)
  1107. {
  1108. if (glyph.glyphRect.width == 0 || glyph.glyphRect.width == 0)
  1109. {
  1110. // Glyphs with zero width and / or height can be automatically added to font asset.
  1111. m_GlyphTable.Add(glyph);
  1112. }
  1113. else
  1114. {
  1115. // Try packing new glyph
  1116. if (FontEngine.TryPackGlyphInAtlas(glyph, m_AtlasPadding, GlyphPackingMode.ContactPointRule, m_AtlasRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects) == false)
  1117. {
  1118. // TODO: Add handling to create new atlas texture to fit glyph.
  1119. return null;
  1120. }
  1121. m_GlyphsToRender.Add(glyph);
  1122. }
  1123. }
  1124. // Add character to font asset.
  1125. TMP_Character character = new TMP_Character(unicode, glyph);
  1126. m_CharacterTable.Add(character);
  1127. m_CharacterLookupDictionary.Add(unicode, character);
  1128. //Debug.Log("Adding character [" + (char)unicode + "] with Unicode (" + unicode + ") to [" + this.name + "] font asset.");
  1129. // Schedule glyph to be added to the font atlas texture
  1130. //TM_FontAssetUpdateManager.RegisterFontAssetForUpdate(this);
  1131. UpdateAtlasTexture(); // Temporary until callback system is revised.
  1132. //#if UNITY_EDITOR
  1133. // Makes the changes to the font asset persistent.
  1134. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1135. // Could also add some update registry to handle this.
  1136. //SortGlyphTable();
  1137. //UnityEditor.EditorUtility.SetDirty(this);
  1138. //#endif
  1139. return character;
  1140. }
  1141. /// <summary>
  1142. /// Try adding character using Unicode value to font asset.
  1143. /// Function assumes internal user has already checked to make sure the character is not already contained in the font asset.
  1144. /// </summary>
  1145. /// <param name="unicode">The Unicode value of the character.</param>
  1146. /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param>
  1147. /// <returns>Returns true if the character has been added. False otherwise.</returns>
  1148. internal bool TryAddCharacterInternal(uint unicode, out TMP_Character character)
  1149. {
  1150. character = null;
  1151. // Load font face.
  1152. if (FontEngine.LoadFontFace(sourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1153. return false;
  1154. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1155. if (glyphIndex == 0)
  1156. return false;
  1157. Profiler.BeginSample("TMP.TryAddCharacter");
  1158. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1159. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1160. {
  1161. character = new TMP_Character(unicode, m_GlyphLookupDictionary[glyphIndex]);
  1162. m_CharacterTable.Add(character);
  1163. m_CharacterLookupDictionary.Add(unicode, character);
  1164. if (TMP_Settings.getFontFeaturesAtRuntime)
  1165. UpdateGlyphAdjustmentRecords(unicode, glyphIndex);
  1166. #if UNITY_EDITOR
  1167. // Makes the changes to the font asset persistent.
  1168. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1169. // Could also add some update registry to handle this.
  1170. //SortGlyphTable();
  1171. if (UnityEditor.EditorUtility.IsPersistent(this))
  1172. {
  1173. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1174. }
  1175. #endif
  1176. Profiler.EndSample();
  1177. return true;
  1178. }
  1179. // Resize the Atlas Texture to the appropriate size
  1180. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1181. {
  1182. // TODO: Need texture to be readable.
  1183. if (m_AtlasTextures[m_AtlasTextureIndex].isReadable == false)
  1184. {
  1185. Debug.LogWarning("Unable to add the requested character to font asset [" + this.name + "]'s atlas texture. Please make the texture [" + m_AtlasTextures[m_AtlasTextureIndex].name + "] readable.", m_AtlasTextures[m_AtlasTextureIndex]);
  1186. Profiler.EndSample();
  1187. return false;
  1188. }
  1189. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1190. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1191. }
  1192. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out Glyph glyph))
  1193. {
  1194. // Add new glyph to glyph table.
  1195. m_GlyphTable.Add(glyph);
  1196. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1197. // Add new character
  1198. character = new TMP_Character(unicode, glyph);
  1199. m_CharacterTable.Add(character);
  1200. m_CharacterLookupDictionary.Add(unicode, character);
  1201. m_GlyphIndexList.Add(glyphIndex);
  1202. if (TMP_Settings.getFontFeaturesAtRuntime)
  1203. UpdateGlyphAdjustmentRecords(unicode, glyphIndex);
  1204. #if UNITY_EDITOR
  1205. // Makes the changes to the font asset persistent.
  1206. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1207. // Could also add some update registry to handle this.
  1208. //SortGlyphTable();
  1209. if (UnityEditor.EditorUtility.IsPersistent(this))
  1210. {
  1211. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1212. }
  1213. #endif
  1214. Profiler.EndSample();
  1215. return true;
  1216. }
  1217. Profiler.EndSample();
  1218. return false;
  1219. }
  1220. /// <summary>
  1221. /// Internal function used to get the glyph index for the given unicode.
  1222. /// </summary>
  1223. /// <param name="unicode"></param>
  1224. /// <returns></returns>
  1225. internal uint GetGlyphIndex(uint unicode)
  1226. {
  1227. // Load font face.
  1228. if (FontEngine.LoadFontFace(sourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1229. return 0;
  1230. return FontEngine.GetGlyphIndex(unicode);
  1231. }
  1232. internal void UpdateAtlasTexture()
  1233. {
  1234. // Return if we don't have any glyphs to add to atlas texture.
  1235. // This is possible if UpdateAtlasTexture() was called manually.
  1236. //if (m_GlyphsToPack.Count == 0)
  1237. // return;
  1238. if (m_GlyphsToRender.Count == 0)
  1239. return;
  1240. //Debug.Log("Updating [" + this.name + "]'s atlas texture.");
  1241. // Pack glyphs in the given atlas texture size.
  1242. // TODO: Packing and glyph render modes should be defined in the font asset.
  1243. //FontEngine.PackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_AtlasPadding, GlyphPackingMode.ContactPointRule, GlyphRenderMode.SDFAA, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  1244. //FontEngine.RenderGlyphsToTexture(m_GlyphsPacked, m_AtlasPadding, GlyphRenderMode.SDFAA, m_AtlasTextures[m_AtlasTextureIndex]);
  1245. // Resize the Atlas Texture to the appropriate size
  1246. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1247. {
  1248. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1249. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1250. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1251. }
  1252. FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_AtlasPadding, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  1253. // Apply changes to atlas texture
  1254. m_AtlasTextures[m_AtlasTextureIndex].Apply(false, false);
  1255. // Add glyphs that were successfully packed to the glyph table.
  1256. for (int i = 0; i < m_GlyphsToRender.Count /* m_GlyphsPacked.Count */; i++)
  1257. {
  1258. Glyph glyph = m_GlyphsToRender[i]; // m_GlyphsPacked[i];
  1259. // Update atlas texture index
  1260. glyph.atlasIndex = m_AtlasTextureIndex;
  1261. m_GlyphTable.Add(glyph);
  1262. m_GlyphLookupDictionary.Add(glyph.index, glyph);
  1263. }
  1264. // Clear list of glyphs
  1265. m_GlyphsPacked.Clear();
  1266. m_GlyphsToRender.Clear();
  1267. // Add any remaining glyphs into new atlas texture if multi texture support if enabled.
  1268. if (m_GlyphsToPack.Count > 0)
  1269. {
  1270. /*
  1271. // Create new atlas texture
  1272. Texture2D tex = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true);
  1273. tex.SetPixels32(new Color32[m_AtlasWidth * m_AtlasHeight]);
  1274. tex.Apply();
  1275. m_AtlasTextureIndex++;
  1276. if (m_AtlasTextures.Length == m_AtlasTextureIndex)
  1277. Array.Resize(ref m_AtlasTextures, Mathf.NextPowerOfTwo(m_AtlasTextureIndex + 1));
  1278. m_AtlasTextures[m_AtlasTextureIndex] = tex;
  1279. */
  1280. }
  1281. #if UNITY_EDITOR
  1282. // Makes the changes to the font asset persistent.
  1283. SortGlyphAndCharacterTables();
  1284. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1285. #endif
  1286. }
  1287. internal void UpdateGlyphAdjustmentRecords(uint unicode, uint glyphIndex)
  1288. {
  1289. Profiler.BeginSample("TMP.UpdateGlyphAdjustmentRecords");
  1290. int glyphCount = m_GlyphIndexList.Count;
  1291. if (s_GlyphIndexArray.Length <= glyphCount)
  1292. s_GlyphIndexArray = new uint[Mathf.NextPowerOfTwo(glyphCount + 1)];
  1293. for (int i = 0; i < glyphCount; i++)
  1294. s_GlyphIndexArray[i] = m_GlyphIndexList[i];
  1295. // Clear unused array elements
  1296. Array.Clear(s_GlyphIndexArray, glyphCount, s_GlyphIndexArray.Length - glyphCount);
  1297. // Get glyph pair adjustment records from font file.
  1298. // TODO: Revise FontEngine bindings to use a more efficient function where only the new glyph index is passed.
  1299. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(s_GlyphIndexArray);
  1300. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  1301. {
  1302. Profiler.EndSample();
  1303. return;
  1304. }
  1305. if (m_FontFeatureTable == null)
  1306. m_FontFeatureTable = new TMP_FontFeatureTable();
  1307. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  1308. {
  1309. long pairKey = (long)pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 32 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  1310. // Check if table already contains a pair adjustment record for this key.
  1311. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(pairKey))
  1312. continue;
  1313. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(pairAdjustmentRecords[i]);
  1314. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  1315. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(pairKey, record);
  1316. }
  1317. #if UNITY_EDITOR
  1318. m_FontFeatureTable.SortGlyphPairAdjustmentRecords();
  1319. #endif
  1320. Profiler.EndSample();
  1321. }
  1322. /// <summary>
  1323. /// Clears font asset data including the glyph and character tables and textures.
  1324. /// Function might be changed to Internal and only used in tests.
  1325. /// </summary>
  1326. /// <param name="setAtlasSizeToZero">Will set the atlas texture size to zero width and height if true.</param>
  1327. public void ClearFontAssetData(bool setAtlasSizeToZero = false)
  1328. {
  1329. #if UNITY_EDITOR
  1330. // Record full object undo in the Editor.
  1331. //UnityEditor.Undo.RecordObjects(new UnityEngine.Object[] { this, this.atlasTexture }, "Resetting Font Asset");
  1332. #endif
  1333. // Clear glyph and character tables
  1334. if (m_GlyphTable != null)
  1335. m_GlyphTable.Clear();
  1336. if (m_CharacterTable != null)
  1337. m_CharacterTable.Clear();
  1338. // Clear glyph rectangles
  1339. if (m_UsedGlyphRects != null)
  1340. m_UsedGlyphRects.Clear();
  1341. if (m_FreeGlyphRects != null)
  1342. {
  1343. int packingModifier = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  1344. m_FreeGlyphRects = new List<GlyphRect>() { new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier) };
  1345. }
  1346. if (m_GlyphsToPack != null)
  1347. m_GlyphsToPack.Clear();
  1348. if (m_GlyphsPacked != null)
  1349. m_GlyphsPacked.Clear();
  1350. // Clear Glyph Adjustment Table
  1351. if (m_FontFeatureTable != null && m_FontFeatureTable.m_GlyphPairAdjustmentRecords != null)
  1352. m_FontFeatureTable.glyphPairAdjustmentRecords.Clear();
  1353. m_AtlasTextureIndex = 0;
  1354. // Clear atlas textures
  1355. if (m_AtlasTextures != null)
  1356. {
  1357. for (int i = 0; i < m_AtlasTextures.Length; i++)
  1358. {
  1359. Texture2D texture = m_AtlasTextures[i];
  1360. if (i > 0)
  1361. DestroyImmediate(texture, true);
  1362. if (texture == null)
  1363. continue;
  1364. // TODO: Need texture to be readable.
  1365. if (m_AtlasTextures[i].isReadable == false)
  1366. {
  1367. Debug.LogWarning("Unable to reset font asset [" + this.name + "]'s atlas texture. Please make the texture [" + m_AtlasTextures[i].name + "] readable.", m_AtlasTextures[i]);
  1368. continue;
  1369. }
  1370. if (setAtlasSizeToZero)
  1371. {
  1372. texture.Resize(0, 0, TextureFormat.Alpha8, false);
  1373. }
  1374. else if (texture.width != m_AtlasWidth || texture.height != m_AtlasHeight)
  1375. {
  1376. texture.Resize(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false);
  1377. }
  1378. // Clear texture atlas
  1379. FontEngine.ResetAtlasTexture(texture);
  1380. texture.Apply();
  1381. if (i == 0)
  1382. m_AtlasTexture = texture;
  1383. m_AtlasTextures[i] = texture;
  1384. }
  1385. }
  1386. #if UNITY_EDITOR
  1387. if (UnityEditor.EditorUtility.IsPersistent(this))
  1388. {
  1389. TMP_EditorResourceManager.RegisterResourceForReimport(this);
  1390. }
  1391. #endif
  1392. ReadFontAssetDefinition();
  1393. }
  1394. /// <summary>
  1395. /// Internal method used to upgrade font asset to support Dynamic SDF.
  1396. /// </summary>
  1397. private void UpgradeFontAsset()
  1398. {
  1399. m_Version = "1.1.0";
  1400. Debug.Log("Upgrading font asset [" + this.name + "] to version " + m_Version + ".", this);
  1401. m_FaceInfo.familyName = m_fontInfo.Name;
  1402. m_FaceInfo.styleName = string.Empty;
  1403. m_FaceInfo.pointSize = (int)m_fontInfo.PointSize;
  1404. m_FaceInfo.scale = m_fontInfo.Scale;
  1405. m_FaceInfo.lineHeight = m_fontInfo.LineHeight;
  1406. m_FaceInfo.ascentLine = m_fontInfo.Ascender;
  1407. m_FaceInfo.capLine = m_fontInfo.CapHeight;
  1408. m_FaceInfo.meanLine = m_fontInfo.CenterLine;
  1409. m_FaceInfo.baseline = m_fontInfo.Baseline;
  1410. m_FaceInfo.descentLine = m_fontInfo.Descender;
  1411. m_FaceInfo.superscriptOffset = m_fontInfo.SuperscriptOffset;
  1412. m_FaceInfo.superscriptSize = m_fontInfo.SubSize;
  1413. m_FaceInfo.subscriptOffset = m_fontInfo.SubscriptOffset;
  1414. m_FaceInfo.subscriptSize = m_fontInfo.SubSize;
  1415. m_FaceInfo.underlineOffset = m_fontInfo.Underline;
  1416. m_FaceInfo.underlineThickness = m_fontInfo.UnderlineThickness;
  1417. m_FaceInfo.strikethroughOffset = m_fontInfo.strikethrough;
  1418. m_FaceInfo.strikethroughThickness = m_fontInfo.strikethroughThickness;
  1419. m_FaceInfo.tabWidth = m_fontInfo.TabWidth;
  1420. if (m_AtlasTextures == null || m_AtlasTextures.Length == 0)
  1421. m_AtlasTextures = new Texture2D[1];
  1422. m_AtlasTextures[0] = atlas;
  1423. //atlas = null;
  1424. m_AtlasWidth = (int)m_fontInfo.AtlasWidth;
  1425. m_AtlasHeight = (int)m_fontInfo.AtlasHeight;
  1426. m_AtlasPadding = (int)m_fontInfo.Padding;
  1427. switch(m_CreationSettings.renderMode)
  1428. {
  1429. case 0:
  1430. m_AtlasRenderMode = GlyphRenderMode.SMOOTH_HINTED;
  1431. break;
  1432. case 1:
  1433. m_AtlasRenderMode = GlyphRenderMode.SMOOTH;
  1434. break;
  1435. case 2:
  1436. m_AtlasRenderMode = GlyphRenderMode.RASTER_HINTED;
  1437. break;
  1438. case 3:
  1439. m_AtlasRenderMode = GlyphRenderMode.RASTER;
  1440. break;
  1441. case 6:
  1442. m_AtlasRenderMode = GlyphRenderMode.SDF16;
  1443. break;
  1444. case 7:
  1445. m_AtlasRenderMode = GlyphRenderMode.SDF32;
  1446. break;
  1447. }
  1448. //m_fontInfo = null;
  1449. // Convert font weight table
  1450. if (fontWeights != null)
  1451. {
  1452. m_FontWeightTable[4] = fontWeights[4];
  1453. m_FontWeightTable[7] = fontWeights[7];
  1454. // Clear old fontWeight
  1455. //fontWeights = null;
  1456. }
  1457. // Convert font fallbacks
  1458. if (fallbackFontAssets != null && fallbackFontAssets.Count > 0)
  1459. {
  1460. if (m_FallbackFontAssetTable == null)
  1461. m_FallbackFontAssetTable = new List<TMP_FontAsset>(fallbackFontAssets.Count);
  1462. for (int i = 0; i < fallbackFontAssets.Count; i++)
  1463. m_FallbackFontAssetTable.Add(fallbackFontAssets[i]);
  1464. // Clear old fallbackFontAssets list
  1465. //fallbackFontAssets = null;
  1466. }
  1467. // Check if font asset creation settings contains a reference to the source font file GUID
  1468. if (m_CreationSettings.sourceFontFileGUID != null || m_CreationSettings.sourceFontFileGUID != string.Empty)
  1469. {
  1470. m_SourceFontFileGUID = m_CreationSettings.sourceFontFileGUID;
  1471. }
  1472. else
  1473. {
  1474. Debug.LogWarning("Font asset [" + this.name + "] doesn't have a reference to its source font file. Please assign the appropriate source font file for this asset in the Font Atlas & Material section of font asset inspector.", this);
  1475. }
  1476. // Convert legacy glyph and character tables to new format
  1477. m_GlyphTable.Clear();
  1478. m_CharacterTable.Clear();
  1479. //#if UNITY_EDITOR
  1480. // TODO: This is causing a crash in Unity and related to AssetDatabase.LoadAssetAtPath and Resources.Load()
  1481. // Load font to allow us to get the glyph index.
  1482. //string path = UnityEditor.AssetDatabase.GUIDToAssetPath(m_SourceFontFileGUID);
  1483. //if (path != string.Empty)
  1484. //{
  1485. //m_SourceFontFile_EditorRef = UnityEditor.AssetDatabase.LoadAssetAtPath<Font>(path);
  1486. //FontEngine.LoadFontFace(m_SourceFontFile_EditorRef);
  1487. //}
  1488. //#endif
  1489. bool isSpaceCharacterPresent = false;
  1490. for (int i = 0; i < m_glyphInfoList.Count; i++)
  1491. {
  1492. TMP_Glyph oldGlyph = m_glyphInfoList[i];
  1493. Glyph glyph = new Glyph();
  1494. uint glyphIndex = (uint)i + 1;
  1495. //#if UNITY_EDITOR
  1496. //if (m_SourceFontFile_EditorRef != null)
  1497. // glyphIndex = FontEngine.GetGlyphIndex((uint)oldGlyph.id);
  1498. //#endif
  1499. glyph.index = glyphIndex;
  1500. glyph.glyphRect = new GlyphRect((int)oldGlyph.x, m_AtlasHeight - (int)(oldGlyph.y + oldGlyph.height + 0.5f), (int)(oldGlyph.width + 0.5f), (int)(oldGlyph.height + 0.5f));
  1501. glyph.metrics = new GlyphMetrics(oldGlyph.width, oldGlyph.height, oldGlyph.xOffset, oldGlyph.yOffset, oldGlyph.xAdvance);
  1502. glyph.scale = oldGlyph.scale;
  1503. glyph.atlasIndex = 0;
  1504. m_GlyphTable.Add(glyph);
  1505. TMP_Character character = new TMP_Character((uint)oldGlyph.id, glyph);
  1506. if (oldGlyph.id == 32)
  1507. isSpaceCharacterPresent = true;
  1508. m_CharacterTable.Add(character);
  1509. }
  1510. // Special handling for the synthesized space character
  1511. if (!isSpaceCharacterPresent)
  1512. {
  1513. Debug.Log("Synthesizing Space for [" + this.name + "]");
  1514. Glyph glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, m_FaceInfo.ascentLine / 5), GlyphRect.zero, 1.0f, 0);
  1515. m_GlyphTable.Add(glyph);
  1516. m_CharacterTable.Add(new TMP_Character(32, glyph));
  1517. }
  1518. // Clear legacy glyph info list.
  1519. //m_glyphInfoList.Clear();
  1520. ReadFontAssetDefinition();
  1521. // Convert atlas textures data to new format
  1522. // TODO
  1523. #if UNITY_EDITOR
  1524. if (UnityEditor.EditorUtility.IsPersistent(this))
  1525. {
  1526. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1527. }
  1528. #endif
  1529. }
  1530. /// <summary>
  1531. ///
  1532. /// </summary>
  1533. void UpgradeGlyphAdjustmentTableToFontFeatureTable()
  1534. {
  1535. Debug.Log("Upgrading font asset [" + this.name + "] Glyph Adjustment Table.", this);
  1536. if (m_FontFeatureTable == null)
  1537. m_FontFeatureTable = new TMP_FontFeatureTable();
  1538. int pairCount = m_KerningTable.kerningPairs.Count;
  1539. m_FontFeatureTable.m_GlyphPairAdjustmentRecords = new List<TMP_GlyphPairAdjustmentRecord>(pairCount);
  1540. for (int i = 0; i < pairCount; i++)
  1541. {
  1542. KerningPair pair = m_KerningTable.kerningPairs[i];
  1543. uint firstGlyphIndex = 0;
  1544. if (m_CharacterLookupDictionary.TryGetValue(pair.firstGlyph, out TMP_Character firstCharacter))
  1545. firstGlyphIndex = firstCharacter.glyphIndex;
  1546. uint secondGlyphIndex = 0;
  1547. if (m_CharacterLookupDictionary.TryGetValue(pair.secondGlyph, out TMP_Character secondCharacter))
  1548. secondGlyphIndex = secondCharacter.glyphIndex;
  1549. TMP_GlyphAdjustmentRecord firstAdjustmentRecord = new TMP_GlyphAdjustmentRecord(firstGlyphIndex, new TMP_GlyphValueRecord(pair.firstGlyphAdjustments.xPlacement, pair.firstGlyphAdjustments.yPlacement, pair.firstGlyphAdjustments.xAdvance, pair.firstGlyphAdjustments.yAdvance));
  1550. TMP_GlyphAdjustmentRecord secondAdjustmentRecord = new TMP_GlyphAdjustmentRecord(secondGlyphIndex, new TMP_GlyphValueRecord(pair.secondGlyphAdjustments.xPlacement, pair.secondGlyphAdjustments.yPlacement, pair.secondGlyphAdjustments.xAdvance, pair.secondGlyphAdjustments.yAdvance));
  1551. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(firstAdjustmentRecord, secondAdjustmentRecord);
  1552. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  1553. }
  1554. // TODO: Should clear legacy kerning table.
  1555. m_KerningTable.kerningPairs = null;
  1556. m_KerningTable = null;
  1557. #if UNITY_EDITOR
  1558. if (UnityEditor.EditorUtility.IsPersistent(this))
  1559. {
  1560. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1561. }
  1562. #endif
  1563. }
  1564. }
  1565. }