Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

TMP_FontAsset.cs 152KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.Serialization;
  6. using UnityEngine.TextCore;
  7. using UnityEngine.TextCore.LowLevel;
  8. using Unity.Profiling;
  9. #if UNITY_EDITOR
  10. using UnityEditor;
  11. #endif
  12. namespace TMPro
  13. {
  14. /// <summary>
  15. /// Atlas population modes which ultimately determines the type of font asset.
  16. /// </summary>
  17. public enum AtlasPopulationMode
  18. {
  19. Static = 0x0,
  20. Dynamic = 0x1,
  21. DynamicOS = 0x2
  22. }
  23. [Serializable][ExcludeFromPresetAttribute]
  24. public class TMP_FontAsset : TMP_Asset
  25. {
  26. /// <summary>
  27. /// This field is set when the font asset is first created.
  28. /// </summary>
  29. [SerializeField]
  30. internal string m_SourceFontFileGUID;
  31. #if UNITY_EDITOR
  32. /// <summary>
  33. /// Persistent reference to the source font file maintained in the editor.
  34. /// </summary>
  35. internal Font SourceFont_EditorRef
  36. {
  37. get
  38. {
  39. if (m_SourceFontFile_EditorRef == null)
  40. m_SourceFontFile_EditorRef = GetSourceFontRef?.Invoke(m_SourceFontFileGUID);
  41. return m_SourceFontFile_EditorRef;
  42. }
  43. set
  44. {
  45. m_SourceFontFile_EditorRef = value;
  46. m_SourceFontFileGUID = SetSourceFontGUID?.Invoke(m_SourceFontFile_EditorRef);
  47. if (m_AtlasPopulationMode == AtlasPopulationMode.Static || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS)
  48. m_SourceFontFile = null;
  49. else
  50. m_SourceFontFile = m_SourceFontFile_EditorRef;
  51. }
  52. }
  53. internal Font m_SourceFontFile_EditorRef;
  54. #endif
  55. /// <summary>
  56. /// The settings used in the Font Asset Creator when this font asset was created or edited.
  57. /// </summary>
  58. public FontAssetCreationSettings creationSettings
  59. {
  60. get { return m_CreationSettings; }
  61. set { m_CreationSettings = value; }
  62. }
  63. [SerializeField]
  64. internal FontAssetCreationSettings m_CreationSettings;
  65. /// <summary>
  66. /// Source font file when atlas population mode is set to dynamic. Null when the atlas population mode is set to static.
  67. /// </summary>
  68. public Font sourceFontFile
  69. {
  70. get { return m_SourceFontFile; }
  71. internal set { m_SourceFontFile = value; }
  72. }
  73. [SerializeField]
  74. private Font m_SourceFontFile;
  75. [SerializeField] private string m_SourceFontFilePath;
  76. public AtlasPopulationMode atlasPopulationMode
  77. {
  78. get { return m_AtlasPopulationMode; }
  79. set
  80. {
  81. m_AtlasPopulationMode = value;
  82. #if UNITY_EDITOR
  83. if (m_AtlasPopulationMode == AtlasPopulationMode.Static || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS)
  84. m_SourceFontFile = null;
  85. else if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  86. m_SourceFontFile = m_SourceFontFile_EditorRef;
  87. #endif
  88. }
  89. }
  90. [SerializeField]
  91. private AtlasPopulationMode m_AtlasPopulationMode;
  92. /// <summary>
  93. /// Field used to identify dynamic OS font assets used internally.
  94. /// </summary>
  95. [SerializeField]
  96. internal bool InternalDynamicOS;
  97. /// <summary>
  98. ///
  99. /// </summary>
  100. internal int familyNameHashCode
  101. {
  102. get
  103. {
  104. if (m_FamilyNameHashCode == 0)
  105. m_FamilyNameHashCode = TMP_TextUtilities.GetHashCode(m_FaceInfo.familyName);
  106. return m_FamilyNameHashCode;
  107. }
  108. set => m_FamilyNameHashCode = value;
  109. }
  110. private int m_FamilyNameHashCode;
  111. /// <summary>
  112. ///
  113. /// </summary>
  114. internal int styleNameHashCode
  115. {
  116. get
  117. {
  118. if (m_StyleNameHashCode == 0)
  119. m_StyleNameHashCode = TMP_TextUtilities.GetHashCode(m_FaceInfo.styleName);
  120. return m_StyleNameHashCode;
  121. }
  122. set => m_StyleNameHashCode = value;
  123. }
  124. private int m_StyleNameHashCode;
  125. /// <summary>
  126. /// List of glyphs contained in the font asset.
  127. /// </summary>
  128. public List<Glyph> glyphTable
  129. {
  130. get { return m_GlyphTable; }
  131. internal set { m_GlyphTable = value; }
  132. }
  133. [SerializeField]
  134. internal List<Glyph> m_GlyphTable = new List<Glyph>();
  135. /// <summary>
  136. /// Dictionary used to lookup glyphs contained in the font asset by their index.
  137. /// </summary>
  138. public Dictionary<uint, Glyph> glyphLookupTable
  139. {
  140. get
  141. {
  142. if (m_GlyphLookupDictionary == null)
  143. ReadFontAssetDefinition();
  144. return m_GlyphLookupDictionary;
  145. }
  146. }
  147. internal Dictionary<uint, Glyph> m_GlyphLookupDictionary;
  148. /// <summary>
  149. /// List containing the characters of the given font asset.
  150. /// </summary>
  151. public List<TMP_Character> characterTable
  152. {
  153. get { return m_CharacterTable; }
  154. internal set { m_CharacterTable = value; }
  155. }
  156. [SerializeField]
  157. internal List<TMP_Character> m_CharacterTable = new List<TMP_Character>();
  158. /// <summary>
  159. /// Dictionary used to lookup characters contained in the font asset by their unicode values.
  160. /// </summary>
  161. public Dictionary<uint, TMP_Character> characterLookupTable
  162. {
  163. get
  164. {
  165. if (m_CharacterLookupDictionary == null)
  166. ReadFontAssetDefinition();
  167. return m_CharacterLookupDictionary;
  168. }
  169. }
  170. internal Dictionary<uint, TMP_Character> m_CharacterLookupDictionary;
  171. /// <summary>
  172. /// Determines if the font asset is using a shared atlas texture(s)
  173. /// </summary>
  174. //public bool isUsingDynamicTextures
  175. //{
  176. // get { return m_IsUsingDynamicTextures; }
  177. // set { m_IsUsingDynamicTextures = value; }
  178. //}
  179. //[SerializeField]
  180. //private bool m_IsUsingDynamicTextures;
  181. /// <summary>
  182. /// The font atlas used by this font asset.
  183. /// This is always the texture at index [0] of the fontAtlasTextures.
  184. /// </summary>
  185. public Texture2D atlasTexture
  186. {
  187. get
  188. {
  189. if (m_AtlasTexture == null)
  190. {
  191. m_AtlasTexture = atlasTextures[0];
  192. }
  193. return m_AtlasTexture;
  194. }
  195. }
  196. internal Texture2D m_AtlasTexture;
  197. /// <summary>
  198. /// Array of atlas textures that contain the glyphs used by this font asset.
  199. /// </summary>
  200. public Texture2D[] atlasTextures
  201. {
  202. get
  203. {
  204. if (m_AtlasTextures == null)
  205. {
  206. //
  207. }
  208. //if (m_IsUsingDynamicTextures)
  209. // return TMP_DynamicAtlasTextureGroup.managedDynamicTextures;
  210. return m_AtlasTextures;
  211. }
  212. set
  213. {
  214. m_AtlasTextures = value;
  215. }
  216. }
  217. [SerializeField]
  218. internal Texture2D[] m_AtlasTextures;
  219. /// <summary>
  220. /// Index of the font atlas texture that still has available space to add new glyphs.
  221. /// </summary>
  222. [SerializeField]
  223. internal int m_AtlasTextureIndex;
  224. /// <summary>
  225. /// Number of atlas textures used by this font asset.
  226. /// </summary>
  227. public int atlasTextureCount { get { return m_AtlasTextureIndex + 1; } }
  228. /// <summary>
  229. /// Enables the font asset to create additional atlas textures as needed.
  230. /// </summary>
  231. public bool isMultiAtlasTexturesEnabled
  232. {
  233. get { return m_IsMultiAtlasTexturesEnabled; }
  234. set { m_IsMultiAtlasTexturesEnabled = value; }
  235. }
  236. [SerializeField]
  237. private bool m_IsMultiAtlasTexturesEnabled;
  238. /// <summary>
  239. /// Determines if OpenType font features should be retrieved from the source font file as new characters and glyphs are added dynamically to the font asset.
  240. /// </summary>
  241. public bool getFontFeatures
  242. {
  243. get { return m_GetFontFeatures; }
  244. set { m_GetFontFeatures = value; }
  245. }
  246. [SerializeField]
  247. private bool m_GetFontFeatures = true;
  248. /// <summary>
  249. /// Determines if dynamic font asset data should be cleared before builds.
  250. /// </summary>
  251. internal bool clearDynamicDataOnBuild
  252. {
  253. get { return m_ClearDynamicDataOnBuild; }
  254. set { m_ClearDynamicDataOnBuild = value; }
  255. }
  256. [SerializeField]
  257. private bool m_ClearDynamicDataOnBuild;
  258. /// <summary>
  259. /// The width of the atlas texture(s) used by this font asset.
  260. /// </summary>
  261. public int atlasWidth
  262. {
  263. get { return m_AtlasWidth; }
  264. internal set { m_AtlasWidth = value; }
  265. }
  266. [SerializeField]
  267. internal int m_AtlasWidth;
  268. /// <summary>
  269. /// The height of the atlas texture(s) used by this font asset.
  270. /// </summary>
  271. public int atlasHeight
  272. {
  273. get { return m_AtlasHeight; }
  274. internal set { m_AtlasHeight = value; }
  275. }
  276. [SerializeField]
  277. internal int m_AtlasHeight;
  278. /// <summary>
  279. /// The padding used between glyphs contained in the atlas texture(s) used by this font asset.
  280. /// </summary>
  281. public int atlasPadding
  282. {
  283. get { return m_AtlasPadding; }
  284. internal set { m_AtlasPadding = value; }
  285. }
  286. [SerializeField]
  287. internal int m_AtlasPadding;
  288. public GlyphRenderMode atlasRenderMode
  289. {
  290. get { return m_AtlasRenderMode; }
  291. internal set { m_AtlasRenderMode = value; }
  292. }
  293. [SerializeField]
  294. internal GlyphRenderMode m_AtlasRenderMode;
  295. /// <summary>
  296. /// List of spaces occupied by glyphs in a given texture.
  297. /// </summary>
  298. internal List<GlyphRect> usedGlyphRects
  299. {
  300. get { return m_UsedGlyphRects; }
  301. set { m_UsedGlyphRects = value; }
  302. }
  303. [SerializeField]
  304. private List<GlyphRect> m_UsedGlyphRects;
  305. /// <summary>
  306. /// List of spaces available in a given texture to add new glyphs.
  307. /// </summary>
  308. internal List<GlyphRect> freeGlyphRects
  309. {
  310. get { return m_FreeGlyphRects; }
  311. set { m_FreeGlyphRects = value; }
  312. }
  313. [SerializeField]
  314. private List<GlyphRect> m_FreeGlyphRects;
  315. /// <summary>
  316. /// Table containing the various font features of this font asset.
  317. /// </summary>
  318. public TMP_FontFeatureTable fontFeatureTable
  319. {
  320. get { return m_FontFeatureTable; }
  321. internal set { m_FontFeatureTable = value; }
  322. }
  323. [SerializeField]
  324. internal TMP_FontFeatureTable m_FontFeatureTable = new TMP_FontFeatureTable();
  325. /// <summary>
  326. ///
  327. /// </summary>
  328. [SerializeField] internal bool m_ShouldReimportFontFeatures;
  329. /// <summary>
  330. /// List containing the Fallback font assets for this font.
  331. /// </summary>
  332. public List<TMP_FontAsset> fallbackFontAssetTable
  333. {
  334. get { return m_FallbackFontAssetTable; }
  335. set { m_FallbackFontAssetTable = value; }
  336. }
  337. [SerializeField]
  338. internal List<TMP_FontAsset> m_FallbackFontAssetTable;
  339. /// <summary>
  340. /// Array containing font assets to be used as alternative typefaces for the various potential font weights of this font asset.
  341. /// </summary>
  342. public TMP_FontWeightPair[] fontWeightTable
  343. {
  344. get { return m_FontWeightTable; }
  345. internal set { m_FontWeightTable = value; }
  346. }
  347. [SerializeField]
  348. private TMP_FontWeightPair[] m_FontWeightTable = new TMP_FontWeightPair[10];
  349. // FONT WEIGHTS
  350. /// <summary>
  351. /// Font weights used by font asset prior to version 1.1.0.
  352. /// This is legacy and will be removed at some point in the future.
  353. /// </summary>
  354. [SerializeField]
  355. private TMP_FontWeightPair[] fontWeights = null;
  356. //private int[] m_characterSet; // Array containing all the characters in this font asset.
  357. /// <summary>
  358. /// Defines the dilation of the text when using regular style.
  359. /// </summary>
  360. public float normalStyle = 0;
  361. /// <summary>
  362. /// The spacing between characters when using regular style.
  363. /// </summary>
  364. public float normalSpacingOffset = 0;
  365. /// <summary>
  366. /// Defines the dilation of the text when using bold style.
  367. /// </summary>
  368. public float boldStyle = 0.75f;
  369. /// <summary>
  370. /// The spacing between characters when using regular style.
  371. /// </summary>
  372. public float boldSpacing = 7f;
  373. /// <summary>
  374. /// Defines the slant of the text when using italic style.
  375. /// </summary>
  376. public byte italicStyle = 35;
  377. /// <summary>
  378. ///
  379. /// </summary>
  380. public byte tabSize = 10;
  381. internal bool IsFontAssetLookupTablesDirty;
  382. // ================================================================================
  383. // Legacy fields no longer used since version 1.1.0 release of TMP_FontAssets.
  384. // ================================================================================
  385. /// <summary>
  386. /// The general information about the font.
  387. /// This property and FaceInfo_Legacy type are no longer used in version 1.1.0 of the font asset.
  388. /// </summary>
  389. [Obsolete("The fontInfo property and underlying type is now obsolete. Please use the faceInfo property and FaceInfo type instead.")]
  390. public FaceInfo_Legacy fontInfo
  391. {
  392. get { return m_fontInfo; }
  393. }
  394. [SerializeField]
  395. private FaceInfo_Legacy m_fontInfo = null;
  396. [SerializeField]
  397. internal List<TMP_Glyph> m_glyphInfoList;
  398. [SerializeField]
  399. [FormerlySerializedAs("m_kerningInfo")]
  400. internal KerningTable m_KerningTable = new KerningTable();
  401. [SerializeField]
  402. #pragma warning disable 0649
  403. private List<TMP_FontAsset> fallbackFontAssets;
  404. /// <summary>
  405. ///
  406. /// </summary>
  407. [SerializeField]
  408. public Texture2D atlas; // Should add a property to make this read-only.
  409. // ================================================================================
  410. // Functions used to create font asset at runtime
  411. // ================================================================================
  412. /// <summary>
  413. /// Creates a new font asset instance from the given family name and style.
  414. /// </summary>
  415. /// <param name="familyName">The family name of the source font.</param>
  416. /// <param name="styleName">The style name of the source font face.</param>
  417. /// <param name="pointSize">Optional point size.</param>
  418. /// <returns>An instance of the newly created font asset.</returns>
  419. public static TMP_FontAsset CreateFontAsset(string familyName, string styleName, int pointSize = 90)
  420. {
  421. if (FontEngine.TryGetSystemFontReference(familyName, styleName, out FontReference fontRef))
  422. return CreateFontAsset(fontRef.filePath, fontRef.faceIndex, pointSize, 9, GlyphRenderMode.SDFAA, 1024, 1024, AtlasPopulationMode.DynamicOS, true);
  423. Debug.Log("Unable to find a font file with the specified Family Name [" + familyName + "] and Style [" + styleName + "].");
  424. return null;
  425. }
  426. /// <summary>
  427. /// Creates a new font asset instance from the font file at the given file path.
  428. /// </summary>
  429. /// <param name="fontFilePath">The file path of the font file.</param>
  430. /// <param name="faceIndex">The index of font face.</param>
  431. /// <param name="samplingPointSize">The sampling point size.</param>
  432. /// <param name="atlasPadding">The padding between individual glyphs in the font atlas texture.</param>
  433. /// <param name="renderMode">The atlas render mode.</param>
  434. /// <param name="atlasWidth">The atlas texture width.</param>
  435. /// <param name="atlasHeight">The atlas texture height.</param>
  436. /// <returns>An instance of the newly created font asset.</returns>
  437. public static TMP_FontAsset CreateFontAsset(string fontFilePath, int faceIndex, int samplingPointSize, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight)
  438. {
  439. return CreateFontAsset(fontFilePath, faceIndex, samplingPointSize, atlasPadding, renderMode, atlasWidth, atlasHeight, AtlasPopulationMode.Dynamic, true);
  440. }
  441. static TMP_FontAsset CreateFontAsset(string fontFilePath, int faceIndex, int samplingPointSize, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight, AtlasPopulationMode atlasPopulationMode, bool enableMultiAtlasSupport = true)
  442. {
  443. // Load Font Face
  444. if (FontEngine.LoadFontFace(fontFilePath, samplingPointSize, faceIndex) != FontEngineError.Success)
  445. {
  446. Debug.Log("Unable to load font face from [" + fontFilePath + "].");
  447. return null;
  448. }
  449. TMP_FontAsset fontAsset = CreateFontAssetInstance(null, atlasPadding, renderMode, atlasWidth, atlasHeight, atlasPopulationMode, enableMultiAtlasSupport);
  450. // Set font file path
  451. fontAsset.m_SourceFontFilePath = fontFilePath;
  452. return fontAsset;
  453. }
  454. /// <summary>
  455. /// Creates a new font asset instance from the provided font object.
  456. /// </summary>
  457. /// <param name="font">The source font object.</param>
  458. /// <returns>An instance of the newly created font asset.</returns>
  459. public static TMP_FontAsset CreateFontAsset(Font font)
  460. {
  461. return CreateFontAsset(font, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024);
  462. }
  463. /// <summary>
  464. /// Creates a new font asset instance from the provided font object.
  465. /// </summary>
  466. /// <param name="font">The source font object.</param>
  467. /// <param name="samplingPointSize">The sampling point size.</param>
  468. /// <param name="atlasPadding">The padding between individual glyphs in the font atlas texture.</param>
  469. /// <param name="renderMode">The atlas render mode.</param>
  470. /// <param name="atlasWidth">The atlas texture width.</param>
  471. /// <param name="atlasHeight">The atlas texture height.</param>
  472. /// <param name="atlasPopulationMode">The atlas population mode.</param>
  473. /// <param name="enableMultiAtlasSupport">Enable multi atlas texture.</param>
  474. /// <returns>An instance of the newly created font asset.</returns>
  475. public static TMP_FontAsset CreateFontAsset(Font font, int samplingPointSize, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight, AtlasPopulationMode atlasPopulationMode = AtlasPopulationMode.Dynamic, bool enableMultiAtlasSupport = true)
  476. {
  477. return CreateFontAsset(font, 0, samplingPointSize, atlasPadding, renderMode, atlasWidth, atlasHeight, atlasPopulationMode, enableMultiAtlasSupport);
  478. }
  479. static TMP_FontAsset CreateFontAsset(Font font, int faceIndex, int samplingPointSize, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight, AtlasPopulationMode atlasPopulationMode = AtlasPopulationMode.Dynamic, bool enableMultiAtlasSupport = true)
  480. {
  481. // Load Font Face
  482. if (FontEngine.LoadFontFace(font, samplingPointSize, faceIndex) != FontEngineError.Success)
  483. {
  484. Debug.LogWarning("Unable to load font face for [" + font.name + "]. Make sure \"Include Font Data\" is enabled in the Font Import Settings.", font);
  485. return null;
  486. }
  487. return CreateFontAssetInstance(font, atlasPadding, renderMode, atlasWidth, atlasHeight, atlasPopulationMode, enableMultiAtlasSupport);
  488. }
  489. static TMP_FontAsset CreateFontAssetInstance(Font font, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight, AtlasPopulationMode atlasPopulationMode, bool enableMultiAtlasSupport)
  490. {
  491. // Create new font asset
  492. TMP_FontAsset fontAsset = CreateInstance<TMP_FontAsset>();
  493. fontAsset.m_Version = "1.1.0";
  494. fontAsset.faceInfo = FontEngine.GetFaceInfo();
  495. if (atlasPopulationMode == AtlasPopulationMode.Dynamic && font != null)
  496. {
  497. fontAsset.sourceFontFile = font;
  498. #if UNITY_EDITOR
  499. fontAsset.m_SourceFontFileGUID = SetSourceFontGUID?.Invoke(font);
  500. fontAsset.m_SourceFontFile_EditorRef = font;
  501. #endif
  502. }
  503. fontAsset.atlasPopulationMode = atlasPopulationMode;
  504. fontAsset.clearDynamicDataOnBuild = TMP_Settings.clearDynamicDataOnBuild;
  505. fontAsset.atlasWidth = atlasWidth;
  506. fontAsset.atlasHeight = atlasHeight;
  507. fontAsset.atlasPadding = atlasPadding;
  508. fontAsset.atlasRenderMode = renderMode;
  509. // Initialize array for the font atlas textures.
  510. fontAsset.atlasTextures = new Texture2D[1];
  511. // Create and add font atlas texture.
  512. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  513. TextureFormat texFormat = ((GlyphRasterModes)renderMode & GlyphRasterModes.RASTER_MODE_COLOR) == GlyphRasterModes.RASTER_MODE_COLOR ? TextureFormat.RGBA32 : TextureFormat.Alpha8;
  514. #else
  515. TextureFormat texFormat = TextureFormat.Alpha8;
  516. #endif
  517. Texture2D texture = new Texture2D(1, 1, texFormat, false);
  518. fontAsset.atlasTextures[0] = texture;
  519. fontAsset.isMultiAtlasTexturesEnabled = enableMultiAtlasSupport;
  520. // Add free rectangle of the size of the texture.
  521. int packingModifier;
  522. if (((GlyphRasterModes)renderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  523. {
  524. Material tmp_material = null;
  525. packingModifier = 0;
  526. if (texFormat == TextureFormat.Alpha8)
  527. tmp_material = new Material(ShaderUtilities.ShaderRef_MobileBitmap);
  528. else
  529. tmp_material = new Material(Shader.Find("TextMeshPro/Sprite"));
  530. //tmp_material.name = texture.name + " Material";
  531. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
  532. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
  533. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
  534. fontAsset.material = tmp_material;
  535. }
  536. else
  537. {
  538. packingModifier = 1;
  539. // Optimize by adding static ref to shader.
  540. Material tmp_material = new Material(ShaderUtilities.ShaderRef_MobileSDF);
  541. //tmp_material.name = texture.name + " Material";
  542. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
  543. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
  544. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
  545. tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier);
  546. tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  547. tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  548. fontAsset.material = tmp_material;
  549. }
  550. fontAsset.freeGlyphRects = new List<GlyphRect>(8) {new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier)};
  551. fontAsset.usedGlyphRects = new List<GlyphRect>(8);
  552. // Set the name of the font asset resources for tracking in the profiler
  553. #if UNITY_EDITOR
  554. string fontName = fontAsset.faceInfo.familyName + " - " + fontAsset.faceInfo.styleName;
  555. fontAsset.material.name = fontName + " Material";
  556. fontAsset.atlasTextures[0].name = fontName + " Atlas";
  557. #endif
  558. // TODO: Consider adding support for extracting glyph positioning data
  559. fontAsset.ReadFontAssetDefinition();
  560. return fontAsset;
  561. }
  562. // ================================================================================
  563. //
  564. // ================================================================================
  565. // Editor Only Callbacks
  566. #if UNITY_EDITOR
  567. internal static Action<Texture, TMP_FontAsset> OnFontAssetTextureChanged;
  568. internal static Action<TMP_FontAsset> RegisterResourceForUpdate;
  569. internal static Action<TMP_FontAsset> RegisterResourceForReimport;
  570. internal static Action<Texture2D, bool> SetAtlasTextureIsReadable;
  571. internal static Func<string, Font> GetSourceFontRef;
  572. internal static Func<Font, string> SetSourceFontGUID;
  573. #endif
  574. // Profiler Marker declarations
  575. private static ProfilerMarker k_ReadFontAssetDefinitionMarker = new ProfilerMarker("TMP.ReadFontAssetDefinition");
  576. private static ProfilerMarker k_AddSynthesizedCharactersMarker = new ProfilerMarker("TMP.AddSynthesizedCharacters");
  577. private static ProfilerMarker k_TryAddGlyphMarker = new ProfilerMarker("TMP.TryAddGlyph");
  578. private static ProfilerMarker k_TryAddCharacterMarker = new ProfilerMarker("TMP.TryAddCharacter");
  579. private static ProfilerMarker k_TryAddCharactersMarker = new ProfilerMarker("TMP.TryAddCharacters");
  580. private static ProfilerMarker k_UpdateLigatureSubstitutionRecordsMarker = new ProfilerMarker("TMP.UpdateLigatureSubstitutionRecords");
  581. private static ProfilerMarker k_UpdateGlyphAdjustmentRecordsMarker = new ProfilerMarker("TMP.UpdateGlyphAdjustmentRecords");
  582. private static ProfilerMarker k_UpdateDiacriticalMarkAdjustmentRecordsMarker = new ProfilerMarker("TMP.UpdateDiacriticalAdjustmentRecords");
  583. private static ProfilerMarker k_ClearFontAssetDataMarker = new ProfilerMarker("TMP.ClearFontAssetData");
  584. private static ProfilerMarker k_UpdateFontAssetDataMarker = new ProfilerMarker("TMP.UpdateFontAssetData");
  585. // ================================================================================
  586. //
  587. // ================================================================================
  588. #if UNITY_EDITOR
  589. void Awake()
  590. {
  591. // Check version number of font asset to see if it needs to be upgraded.
  592. if (this.material != null && string.IsNullOrEmpty(m_Version))
  593. UpgradeFontAsset();
  594. }
  595. #endif
  596. private void OnDestroy()
  597. {
  598. DestroyAtlasTextures();
  599. DestroyImmediate(m_Material);
  600. }
  601. #if UNITY_EDITOR
  602. private void OnValidate()
  603. {
  604. // Skip validation until the Editor has been fully loaded.
  605. if (Time.frameCount == 0)
  606. return;
  607. // See TMPB-187
  608. if (EditorApplication.isUpdating)
  609. return;
  610. // Make sure our lookup dictionary have been initialized.
  611. if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null)
  612. ReadFontAssetDefinition();
  613. }
  614. #endif
  615. private static string s_DefaultMaterialSuffix = " Atlas Material";
  616. /// <summary>
  617. /// Reads the various data tables of the font asset and populates various data structures to allow for faster lookup of related font asset data.
  618. /// </summary>
  619. public void ReadFontAssetDefinition()
  620. {
  621. k_ReadFontAssetDefinitionMarker.Begin();
  622. #if UNITY_EDITOR
  623. // Check version number of font asset to see if it needs to be upgraded.
  624. if (this.material != null && string.IsNullOrEmpty(m_Version))
  625. UpgradeFontAsset();
  626. #endif
  627. // Initialize lookup tables for characters and glyphs.
  628. InitializeDictionaryLookupTables();
  629. // Add synthesized characters and adjust face metrics
  630. AddSynthesizedCharactersAndFaceMetrics();
  631. // Set Cap Line using the capital letter 'X'
  632. if (m_FaceInfo.capLine == 0 && m_CharacterLookupDictionary.ContainsKey('X'))
  633. {
  634. uint glyphIndex = m_CharacterLookupDictionary['X'].glyphIndex;
  635. m_FaceInfo.capLine = m_GlyphLookupDictionary[glyphIndex].metrics.horizontalBearingY;
  636. }
  637. // Set Mean Line using the lowercase letter 'x'
  638. if (m_FaceInfo.meanLine == 0 && m_CharacterLookupDictionary.ContainsKey('x'))
  639. {
  640. uint glyphIndex = m_CharacterLookupDictionary['x'].glyphIndex;
  641. m_FaceInfo.meanLine = m_GlyphLookupDictionary[glyphIndex].metrics.horizontalBearingY;
  642. }
  643. // Adjust Font Scale for compatibility reasons
  644. if (m_FaceInfo.scale == 0)
  645. m_FaceInfo.scale = 1.0f;
  646. // Set Strikethrough Offset (if needed)
  647. if (m_FaceInfo.strikethroughOffset == 0)
  648. m_FaceInfo.strikethroughOffset = m_FaceInfo.capLine / 2.5f;
  649. // Set Padding value for legacy font assets.
  650. if (m_AtlasPadding == 0)
  651. {
  652. if (material.HasProperty(ShaderUtilities.ID_GradientScale))
  653. m_AtlasPadding = (int)material.GetFloat(ShaderUtilities.ID_GradientScale) - 1;
  654. }
  655. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  656. // Update Units per EM for pre-existing font assets.
  657. if (m_FaceInfo.unitsPerEM == 0)
  658. m_FaceInfo.unitsPerEM = FontEngine.GetFaceInfo().unitsPerEM;
  659. #endif
  660. // Compute hash codes for various properties of the font asset used for lookup.
  661. hashCode = TMP_TextUtilities.GetHashCode(this.name);
  662. familyNameHashCode = TMP_TextUtilities.GetHashCode(m_FaceInfo.familyName);
  663. styleNameHashCode = TMP_TextUtilities.GetHashCode(m_FaceInfo.styleName);
  664. materialHashCode = TMP_TextUtilities.GetSimpleHashCode(this.name + s_DefaultMaterialSuffix);
  665. // Add reference to font asset in TMP Resource Manager
  666. TMP_ResourceManager.AddFontAsset(this);
  667. IsFontAssetLookupTablesDirty = false;
  668. k_ReadFontAssetDefinitionMarker.End();
  669. }
  670. /// <summary>
  671. /// Read the various data tables of the font asset to populate its different dictionaries to allow for faster lookup of related font asset data.
  672. /// </summary>
  673. internal void InitializeDictionaryLookupTables()
  674. {
  675. // Initialize and populate glyph lookup dictionary
  676. InitializeGlyphLookupDictionary();
  677. // Initialize and populate character lookup dictionary
  678. InitializeCharacterLookupDictionary();
  679. if ((m_AtlasPopulationMode == AtlasPopulationMode.Dynamic || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS) && m_ShouldReimportFontFeatures)
  680. ImportFontFeatures();
  681. //
  682. InitializeLigatureSubstitutionLookupDictionary();
  683. // Initialize and populate glyph pair adjustment records
  684. InitializeGlyphPaidAdjustmentRecordsLookupDictionary();
  685. // Initialize and populate mark to base adjustment records
  686. InitializeMarkToBaseAdjustmentRecordsLookupDictionary();
  687. // Initialize and populate mark to base adjustment records
  688. InitializeMarkToMarkAdjustmentRecordsLookupDictionary();
  689. }
  690. internal void InitializeGlyphLookupDictionary()
  691. {
  692. // Create new instance of the glyph lookup dictionary or clear the existing one.
  693. if (m_GlyphLookupDictionary == null)
  694. m_GlyphLookupDictionary = new Dictionary<uint, Glyph>();
  695. else
  696. m_GlyphLookupDictionary.Clear();
  697. // Initialize or clear list of glyph indexes.
  698. if (m_GlyphIndexList == null)
  699. m_GlyphIndexList = new List<uint>();
  700. else
  701. m_GlyphIndexList.Clear();
  702. // Initialize or clear list of glyph indexes.
  703. if (m_GlyphIndexListNewlyAdded == null)
  704. m_GlyphIndexListNewlyAdded = new List<uint>();
  705. else
  706. m_GlyphIndexListNewlyAdded.Clear();
  707. //
  708. int glyphCount = m_GlyphTable.Count;
  709. // Add glyphs contained in the glyph table to dictionary for faster lookup.
  710. for (int i = 0; i < glyphCount; i++)
  711. {
  712. Glyph glyph = m_GlyphTable[i];
  713. uint index = glyph.index;
  714. // TODO: Not sure it is necessary to check here.
  715. if (m_GlyphLookupDictionary.ContainsKey(index) == false)
  716. {
  717. m_GlyphLookupDictionary.Add(index, glyph);
  718. m_GlyphIndexList.Add(index);
  719. }
  720. }
  721. }
  722. internal void InitializeCharacterLookupDictionary()
  723. {
  724. // Create new instance of the character lookup dictionary or clear the existing one.
  725. if (m_CharacterLookupDictionary == null)
  726. m_CharacterLookupDictionary = new Dictionary<uint, TMP_Character>();
  727. else
  728. m_CharacterLookupDictionary.Clear();
  729. // Add the characters contained in the character table to the dictionary for faster lookup.
  730. for (int i = 0; i < m_CharacterTable.Count; i++)
  731. {
  732. TMP_Character character = m_CharacterTable[i];
  733. uint unicode = character.unicode;
  734. uint glyphIndex = character.glyphIndex;
  735. // Add character along with reference to text asset and glyph
  736. if (m_CharacterLookupDictionary.ContainsKey(unicode) == false)
  737. {
  738. m_CharacterLookupDictionary.Add(unicode, character);
  739. character.textAsset = this;
  740. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  741. }
  742. }
  743. // Clear missing unicode lookup
  744. if (m_MissingUnicodesFromFontFile != null)
  745. m_MissingUnicodesFromFontFile.Clear();
  746. }
  747. internal void InitializeLigatureSubstitutionLookupDictionary()
  748. {
  749. if (m_FontFeatureTable.m_LigatureSubstitutionRecordLookup == null)
  750. m_FontFeatureTable.m_LigatureSubstitutionRecordLookup = new Dictionary<uint, List<LigatureSubstitutionRecord>>();
  751. else
  752. m_FontFeatureTable.m_LigatureSubstitutionRecordLookup.Clear();
  753. List<LigatureSubstitutionRecord> substitutionRecords = m_FontFeatureTable.m_LigatureSubstitutionRecords;
  754. if (substitutionRecords != null)
  755. {
  756. for (int i = 0; i < substitutionRecords.Count; i++)
  757. {
  758. LigatureSubstitutionRecord record = substitutionRecords[i];
  759. // Skip newly added records
  760. if (record.componentGlyphIDs == null || record.componentGlyphIDs.Length == 0)
  761. continue;
  762. uint keyGlyphIndex = record.componentGlyphIDs[0];
  763. if (!m_FontFeatureTable.m_LigatureSubstitutionRecordLookup.ContainsKey(keyGlyphIndex))
  764. m_FontFeatureTable.m_LigatureSubstitutionRecordLookup.Add(keyGlyphIndex, new List<LigatureSubstitutionRecord> {record});
  765. else
  766. m_FontFeatureTable.m_LigatureSubstitutionRecordLookup[keyGlyphIndex].Add(record);
  767. }
  768. }
  769. }
  770. internal void InitializeGlyphPaidAdjustmentRecordsLookupDictionary()
  771. {
  772. // Upgrade Glyph Adjustment Table to the new Font Feature table and Glyph Pair Adjustment Records
  773. if (m_KerningTable != null && m_KerningTable.kerningPairs != null && m_KerningTable.kerningPairs.Count > 0)
  774. UpgradeGlyphAdjustmentTableToFontFeatureTable();
  775. // Read Font Features which will include kerning data.
  776. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup == null)
  777. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup = new Dictionary<uint, GlyphPairAdjustmentRecord>();
  778. else
  779. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.Clear();
  780. List<GlyphPairAdjustmentRecord> glyphPairAdjustmentRecords = m_FontFeatureTable.m_GlyphPairAdjustmentRecords;
  781. if (glyphPairAdjustmentRecords != null)
  782. {
  783. for (int i = 0; i < glyphPairAdjustmentRecords.Count; i++)
  784. {
  785. GlyphPairAdjustmentRecord record = glyphPairAdjustmentRecords[i];
  786. uint key = record.secondAdjustmentRecord.glyphIndex << 16 | record.firstAdjustmentRecord.glyphIndex;
  787. if (!m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.ContainsKey(key))
  788. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.Add(key, record);
  789. }
  790. }
  791. }
  792. internal void InitializeMarkToBaseAdjustmentRecordsLookupDictionary()
  793. {
  794. // Read Mark to Base adjustment records
  795. if (m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup == null)
  796. m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup = new Dictionary<uint, MarkToBaseAdjustmentRecord>();
  797. else
  798. m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.Clear();
  799. List<MarkToBaseAdjustmentRecord> adjustmentRecords = m_FontFeatureTable.m_MarkToBaseAdjustmentRecords;
  800. if (adjustmentRecords != null)
  801. {
  802. for (int i = 0; i < adjustmentRecords.Count; i++)
  803. {
  804. MarkToBaseAdjustmentRecord record = adjustmentRecords[i];
  805. uint key = record.markGlyphID << 16 | record.baseGlyphID;
  806. if (!m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.ContainsKey(key))
  807. m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.Add(key, record);
  808. }
  809. }
  810. }
  811. internal void InitializeMarkToMarkAdjustmentRecordsLookupDictionary()
  812. {
  813. // Read Mark to Base adjustment records
  814. if (m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup == null)
  815. m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup = new Dictionary<uint, MarkToMarkAdjustmentRecord>();
  816. else
  817. m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.Clear();
  818. List<MarkToMarkAdjustmentRecord> adjustmentRecords = m_FontFeatureTable.m_MarkToMarkAdjustmentRecords;
  819. if (adjustmentRecords != null)
  820. {
  821. for (int i = 0; i < adjustmentRecords.Count; i++)
  822. {
  823. MarkToMarkAdjustmentRecord record = adjustmentRecords[i];
  824. uint key = record.combiningMarkGlyphID << 16 | record.baseMarkGlyphID;
  825. if (!m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.ContainsKey(key))
  826. m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.Add(key, record);
  827. }
  828. }
  829. }
  830. internal void AddSynthesizedCharactersAndFaceMetrics()
  831. {
  832. k_AddSynthesizedCharactersMarker.Begin();
  833. bool isFontFaceLoaded = false;
  834. if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS)
  835. {
  836. isFontFaceLoaded = LoadFontFace() == FontEngineError.Success;
  837. if (!isFontFaceLoaded && !InternalDynamicOS && TMP_Settings.warningsDisabled)
  838. Debug.LogWarning("Unable to load font face for [" + this.name + "] font asset.", this);
  839. }
  840. // Only characters not present in the source font file will be synthesized.
  841. // Non visible and control characters with no metrics
  842. // Add End of Text \u0003
  843. AddSynthesizedCharacter(0x03, isFontFaceLoaded, true);
  844. // Add Tab \u0009
  845. AddSynthesizedCharacter(0x09, isFontFaceLoaded, true);
  846. // Add Line Feed (LF) \u000A
  847. AddSynthesizedCharacter(0x0A, isFontFaceLoaded);
  848. // Add Vertical Tab (VT) \u000B
  849. AddSynthesizedCharacter(0x0B, isFontFaceLoaded);
  850. // Add Carriage Return (CR) \u000D
  851. AddSynthesizedCharacter(0x0D, isFontFaceLoaded);
  852. // Add Arabic Letter Mark \u061C
  853. AddSynthesizedCharacter(0x061C, isFontFaceLoaded);
  854. // Add Zero Width Space <ZWSP> \u200B
  855. AddSynthesizedCharacter(0x200B, isFontFaceLoaded);
  856. // Add Zero Width Space <ZWJ> \u200D
  857. //AddSynthesizedCharacter(0x200D, isFontFaceLoaded);
  858. // Add Left-To-Right Mark \u200E
  859. AddSynthesizedCharacter(0x200E, isFontFaceLoaded);
  860. // Add Right-To-Left Mark \u200F
  861. AddSynthesizedCharacter(0x200F, isFontFaceLoaded);
  862. // Add Line Separator \u2028
  863. AddSynthesizedCharacter(0x2028, isFontFaceLoaded);
  864. // Add Paragraph Separator \u2029
  865. AddSynthesizedCharacter(0x2029, isFontFaceLoaded);
  866. // Add Word Joiner <WJ> / Zero Width Non-Breaking Space \u2060
  867. AddSynthesizedCharacter(0x2060, isFontFaceLoaded);
  868. k_AddSynthesizedCharactersMarker.End();
  869. }
  870. void AddSynthesizedCharacter(uint unicode, bool isFontFaceLoaded, bool addImmediately = false)
  871. {
  872. // Check if unicode is already present in the font asset
  873. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  874. return;
  875. Glyph glyph;
  876. if (isFontFaceLoaded)
  877. {
  878. // Check if unicode is present in font file
  879. if (FontEngine.GetGlyphIndex(unicode) != 0)
  880. {
  881. if (addImmediately == false)
  882. return;
  883. //Debug.Log("Adding Unicode [" + unicode.ToString("X4") + "].");
  884. GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_NO_HINTING) == GlyphRasterModes.RASTER_MODE_NO_HINTING
  885. ? GlyphLoadFlags.LOAD_NO_BITMAP | GlyphLoadFlags.LOAD_NO_HINTING
  886. : GlyphLoadFlags.LOAD_NO_BITMAP;
  887. if (FontEngine.TryGetGlyphWithUnicodeValue(unicode, glyphLoadFlags, out glyph))
  888. m_CharacterLookupDictionary.Add(unicode, new TMP_Character(unicode, this, glyph));
  889. return;
  890. }
  891. }
  892. //Debug.Log("Synthesizing Unicode [" + unicode.ToString("X4") + "].");
  893. // Synthesize and add missing glyph and character
  894. glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, 0), GlyphRect.zero, 1.0f, 0);
  895. m_CharacterLookupDictionary.Add(unicode, new TMP_Character(unicode, this, glyph));
  896. }
  897. //internal HashSet<int> FallbackSearchQueryLookup = new HashSet<int>();
  898. internal void AddCharacterToLookupCache(uint unicode, TMP_Character character)
  899. {
  900. m_CharacterLookupDictionary.Add(unicode, character);
  901. // Add font asset to fallback references.
  902. //FallbackSearchQueryLookup.Add(character.textAsset.instanceID);
  903. }
  904. /// <summary>
  905. ///
  906. /// </summary>
  907. /// <returns></returns>
  908. FontEngineError LoadFontFace()
  909. {
  910. if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  911. {
  912. // Font Asset should have a valid reference to a font in the Editor.
  913. #if UNITY_EDITOR
  914. if (m_SourceFontFile == null)
  915. m_SourceFontFile = SourceFont_EditorRef;
  916. #endif
  917. // Try loading the font face from source font object
  918. if (FontEngine.LoadFontFace(m_SourceFontFile, m_FaceInfo.pointSize, m_FaceInfo.faceIndex) == FontEngineError.Success)
  919. return FontEngineError.Success;
  920. // Try loading the font face from file path
  921. if (string.IsNullOrEmpty(m_SourceFontFilePath) == false)
  922. return FontEngine.LoadFontFace(m_SourceFontFilePath, m_FaceInfo.pointSize, m_FaceInfo.faceIndex);
  923. return FontEngineError.Invalid_Face;
  924. }
  925. // Font Asset is Dynamic OS
  926. #if UNITY_EDITOR
  927. if (SourceFont_EditorRef != null)
  928. {
  929. // Try loading the font face from the referenced source font
  930. if (FontEngine.LoadFontFace(m_SourceFontFile_EditorRef, m_FaceInfo.pointSize, m_FaceInfo.faceIndex) == FontEngineError.Success)
  931. return FontEngineError.Success;
  932. }
  933. #endif
  934. return FontEngine.LoadFontFace(m_FaceInfo.familyName, m_FaceInfo.styleName, m_FaceInfo.pointSize);
  935. }
  936. /// <summary>
  937. /// Sort the Character table by Unicode values.
  938. /// </summary>
  939. internal void SortCharacterTable()
  940. {
  941. if (m_CharacterTable != null && m_CharacterTable.Count > 0)
  942. m_CharacterTable = m_CharacterTable.OrderBy(c => c.unicode).ToList();
  943. }
  944. /// <summary>
  945. /// Sort the Glyph table by index values.
  946. /// </summary>
  947. internal void SortGlyphTable()
  948. {
  949. if (m_GlyphTable != null && m_GlyphTable.Count > 0)
  950. m_GlyphTable = m_GlyphTable.OrderBy(c => c.index).ToList();
  951. }
  952. internal void SortFontFeatureTable()
  953. {
  954. m_FontFeatureTable.SortGlyphPairAdjustmentRecords();
  955. m_FontFeatureTable.SortMarkToBaseAdjustmentRecords();
  956. m_FontFeatureTable.SortMarkToMarkAdjustmentRecords();
  957. }
  958. /// <summary>
  959. /// Sort both glyph and character tables.
  960. /// </summary>
  961. internal void SortAllTables()
  962. {
  963. SortGlyphTable();
  964. SortCharacterTable();
  965. SortFontFeatureTable();
  966. }
  967. /// <summary>
  968. /// HashSet of font asset instance ID used in the process of searching for through fallback font assets for a given character or characters.
  969. /// </summary>
  970. private static HashSet<int> k_SearchedFontAssetLookup;
  971. /// <summary>
  972. /// Function to check if a certain character exists in the font asset.
  973. /// </summary>
  974. /// <param name="character"></param>
  975. /// <returns></returns>
  976. public bool HasCharacter(int character)
  977. {
  978. if (characterLookupTable == null)
  979. return false;
  980. return m_CharacterLookupDictionary.ContainsKey((uint)character);
  981. }
  982. /// <summary>
  983. /// Function to check if a character is contained in the font asset with the option to also check potential local fallbacks.
  984. /// </summary>
  985. /// <param name="character"></param>
  986. /// <param name="searchFallbacks"></param>
  987. /// <param name="tryAddCharacter"></param>
  988. /// <returns></returns>
  989. public bool HasCharacter(char character, bool searchFallbacks = false, bool tryAddCharacter = false)
  990. {
  991. // Read font asset definition if it hasn't already been done.
  992. if (characterLookupTable == null)
  993. return false;
  994. // Check font asset
  995. if (m_CharacterLookupDictionary.ContainsKey(character))
  996. return true;
  997. // Check if font asset is dynamic and if so try to add the requested character to it.
  998. if (tryAddCharacter && (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS))
  999. {
  1000. TMP_Character returnedCharacter;
  1001. if (TryAddCharacterInternal(character, out returnedCharacter))
  1002. return true;
  1003. }
  1004. if (searchFallbacks)
  1005. {
  1006. // Initialize or clear font asset lookup
  1007. if (k_SearchedFontAssetLookup == null)
  1008. k_SearchedFontAssetLookup = new HashSet<int>();
  1009. else
  1010. k_SearchedFontAssetLookup.Clear();
  1011. // Add current font asset to lookup
  1012. k_SearchedFontAssetLookup.Add(GetInstanceID());
  1013. // Check font asset fallbacks
  1014. if (fallbackFontAssetTable != null && fallbackFontAssetTable.Count > 0)
  1015. {
  1016. for (int i = 0; i < fallbackFontAssetTable.Count && fallbackFontAssetTable[i] != null; i++)
  1017. {
  1018. TMP_FontAsset fallback = fallbackFontAssetTable[i];
  1019. int fallbackID = fallback.GetInstanceID();
  1020. // Search fallback if not already contained in lookup
  1021. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1022. {
  1023. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  1024. return true;
  1025. }
  1026. }
  1027. }
  1028. // Check general fallback font assets.
  1029. if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  1030. {
  1031. for (int i = 0; i < TMP_Settings.fallbackFontAssets.Count && TMP_Settings.fallbackFontAssets[i] != null; i++)
  1032. {
  1033. TMP_FontAsset fallback = TMP_Settings.fallbackFontAssets[i];
  1034. int fallbackID = fallback.GetInstanceID();
  1035. // Search fallback if not already contained in lookup
  1036. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1037. {
  1038. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  1039. return true;
  1040. }
  1041. }
  1042. }
  1043. // Check TMP Settings Default Font Asset
  1044. if (TMP_Settings.defaultFontAsset != null)
  1045. {
  1046. TMP_FontAsset fallback = TMP_Settings.defaultFontAsset;
  1047. int fallbackID = fallback.GetInstanceID();
  1048. // Search fallback if it has not already been searched
  1049. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1050. {
  1051. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  1052. return true;
  1053. }
  1054. }
  1055. }
  1056. return false;
  1057. }
  1058. /// <summary>
  1059. /// Function to check if a character is contained in a font asset with the option to also check through fallback font assets.
  1060. /// This private implementation does not search the fallback font asset in the TMP Settings file.
  1061. /// </summary>
  1062. /// <param name="character"></param>
  1063. /// <param name="searchFallbacks"></param>
  1064. /// <param name="tryAddCharacter"></param>
  1065. /// <returns></returns>
  1066. bool HasCharacter_Internal(uint character, bool searchFallbacks = false, bool tryAddCharacter = false)
  1067. {
  1068. // Read font asset definition if it hasn't already been done.
  1069. if (m_CharacterLookupDictionary == null)
  1070. {
  1071. ReadFontAssetDefinition();
  1072. if (m_CharacterLookupDictionary == null)
  1073. return false;
  1074. }
  1075. // Check font asset
  1076. if (m_CharacterLookupDictionary.ContainsKey(character))
  1077. return true;
  1078. // Check if fallback is dynamic and if so try to add the requested character to it.
  1079. if (tryAddCharacter && (atlasPopulationMode == AtlasPopulationMode.Dynamic || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS))
  1080. {
  1081. TMP_Character returnedCharacter;
  1082. if (TryAddCharacterInternal(character, out returnedCharacter))
  1083. return true;
  1084. }
  1085. if (searchFallbacks)
  1086. {
  1087. // Check Font Asset Fallback fonts.
  1088. if (fallbackFontAssetTable == null || fallbackFontAssetTable.Count == 0)
  1089. return false;
  1090. for (int i = 0; i < fallbackFontAssetTable.Count && fallbackFontAssetTable[i] != null; i++)
  1091. {
  1092. TMP_FontAsset fallback = fallbackFontAssetTable[i];
  1093. int fallbackID = fallback.GetInstanceID();
  1094. // Search fallback if it has not already been searched
  1095. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1096. {
  1097. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  1098. return true;
  1099. }
  1100. }
  1101. }
  1102. return false;
  1103. }
  1104. /// <summary>
  1105. /// Function to check if certain characters exists in the font asset. Function returns a list of missing characters.
  1106. /// </summary>
  1107. /// <param name="text">String containing the characters to check.</param>
  1108. /// <param name="missingCharacters">List of missing characters.</param>
  1109. /// <returns></returns>
  1110. public bool HasCharacters(string text, out List<char> missingCharacters)
  1111. {
  1112. if (characterLookupTable == null)
  1113. {
  1114. missingCharacters = null;
  1115. return false;
  1116. }
  1117. missingCharacters = new List<char>();
  1118. for (int i = 0; i < text.Length; i++)
  1119. {
  1120. if (!m_CharacterLookupDictionary.ContainsKey(text[i]))
  1121. missingCharacters.Add(text[i]);
  1122. }
  1123. if (missingCharacters.Count == 0)
  1124. return true;
  1125. return false;
  1126. }
  1127. /// <summary>
  1128. /// Function to check if the characters in the given string are contained in the font asset with the option to also check its potential local fallbacks.
  1129. /// </summary>
  1130. /// <param name="text">String containing the characters to check.</param>
  1131. /// <param name="missingCharacters">Array containing the unicode values of the missing characters.</param>
  1132. /// <param name="searchFallbacks">Determines if fallback font assets assigned to this font asset should be searched.</param>
  1133. /// <param name="tryAddCharacter"></param>
  1134. /// <returns>Returns true if all requested characters are available in the font asset and potential fallbacks.</returns>
  1135. public bool HasCharacters(string text, out uint[] missingCharacters, bool searchFallbacks = false, bool tryAddCharacter = false)
  1136. {
  1137. missingCharacters = null;
  1138. // Read font asset definition if it hasn't already been done.
  1139. if (characterLookupTable == null)
  1140. return false;
  1141. // Clear internal list of
  1142. s_MissingCharacterList.Clear();
  1143. for (int i = 0; i < text.Length; i++)
  1144. {
  1145. bool isMissingCharacter = true;
  1146. uint character = text[i];
  1147. if (m_CharacterLookupDictionary.ContainsKey(character))
  1148. continue;
  1149. // Check if fallback is dynamic and if so try to add the requested character to it.
  1150. if (tryAddCharacter && (atlasPopulationMode == AtlasPopulationMode.Dynamic || m_AtlasPopulationMode == AtlasPopulationMode.DynamicOS))
  1151. {
  1152. TMP_Character returnedCharacter;
  1153. if (TryAddCharacterInternal(character, out returnedCharacter))
  1154. continue;
  1155. }
  1156. if (searchFallbacks)
  1157. {
  1158. // Initialize or clear font asset lookup
  1159. if (k_SearchedFontAssetLookup == null)
  1160. k_SearchedFontAssetLookup = new HashSet<int>();
  1161. else
  1162. k_SearchedFontAssetLookup.Clear();
  1163. // Add current font asset to lookup
  1164. k_SearchedFontAssetLookup.Add(GetInstanceID());
  1165. // Check font asset fallbacks
  1166. if (fallbackFontAssetTable != null && fallbackFontAssetTable.Count > 0)
  1167. {
  1168. for (int j = 0; j < fallbackFontAssetTable.Count && fallbackFontAssetTable[j] != null; j++)
  1169. {
  1170. TMP_FontAsset fallback = fallbackFontAssetTable[j];
  1171. int fallbackID = fallback.GetInstanceID();
  1172. // Search fallback if it has not already been searched
  1173. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1174. {
  1175. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter) == false)
  1176. continue;
  1177. isMissingCharacter = false;
  1178. break;
  1179. }
  1180. }
  1181. }
  1182. // Check general fallback font assets.
  1183. if (isMissingCharacter && TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  1184. {
  1185. for (int j = 0; j < TMP_Settings.fallbackFontAssets.Count && TMP_Settings.fallbackFontAssets[j] != null; j++)
  1186. {
  1187. TMP_FontAsset fallback = TMP_Settings.fallbackFontAssets[j];
  1188. int fallbackID = fallback.GetInstanceID();
  1189. // Search fallback if it has not already been searched
  1190. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1191. {
  1192. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter) == false)
  1193. continue;
  1194. isMissingCharacter = false;
  1195. break;
  1196. }
  1197. }
  1198. }
  1199. // Check TMP Settings Default Font Asset
  1200. if (isMissingCharacter && TMP_Settings.defaultFontAsset != null)
  1201. {
  1202. TMP_FontAsset fallback = TMP_Settings.defaultFontAsset;
  1203. int fallbackID = fallback.GetInstanceID();
  1204. // Search fallback if it has not already been searched
  1205. if (k_SearchedFontAssetLookup.Add(fallbackID))
  1206. {
  1207. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  1208. isMissingCharacter = false;
  1209. }
  1210. }
  1211. }
  1212. if (isMissingCharacter)
  1213. s_MissingCharacterList.Add(character);
  1214. }
  1215. if (s_MissingCharacterList.Count > 0)
  1216. {
  1217. missingCharacters = s_MissingCharacterList.ToArray();
  1218. return false;
  1219. }
  1220. return true;
  1221. }
  1222. /// <summary>
  1223. /// Function to check if certain characters exists in the font asset. Function returns false if any characters are missing.
  1224. /// </summary>
  1225. /// <param name="text">String containing the characters to check</param>
  1226. /// <returns></returns>
  1227. public bool HasCharacters(string text)
  1228. {
  1229. if (characterLookupTable == null)
  1230. return false;
  1231. for (int i = 0; i < text.Length; i++)
  1232. {
  1233. if (!m_CharacterLookupDictionary.ContainsKey(text[i]))
  1234. return false;
  1235. }
  1236. return true;
  1237. }
  1238. /// <summary>
  1239. /// Function to extract all the characters from a font asset.
  1240. /// </summary>
  1241. /// <param name="fontAsset"></param>
  1242. /// <returns></returns>
  1243. public static string GetCharacters(TMP_FontAsset fontAsset)
  1244. {
  1245. string characters = string.Empty;
  1246. for (int i = 0; i < fontAsset.characterTable.Count; i++)
  1247. {
  1248. characters += (char)fontAsset.characterTable[i].unicode;
  1249. }
  1250. return characters;
  1251. }
  1252. /// <summary>
  1253. /// Function which returns an array that contains all the characters from a font asset.
  1254. /// </summary>
  1255. /// <param name="fontAsset"></param>
  1256. /// <returns></returns>
  1257. public static int[] GetCharactersArray(TMP_FontAsset fontAsset)
  1258. {
  1259. int[] characters = new int[fontAsset.characterTable.Count];
  1260. for (int i = 0; i < fontAsset.characterTable.Count; i++)
  1261. {
  1262. characters[i] = (int)fontAsset.characterTable[i].unicode;
  1263. }
  1264. return characters;
  1265. }
  1266. /// <summary>
  1267. /// Internal function used to get the glyph index for the given Unicode.
  1268. /// </summary>
  1269. /// <param name="unicode"></param>
  1270. /// <returns></returns>
  1271. internal uint GetGlyphIndex(uint unicode)
  1272. {
  1273. // Check if glyph already exists in font asset.
  1274. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1275. return m_CharacterLookupDictionary[unicode].glyphIndex;
  1276. // Load font face.
  1277. return LoadFontFace() == FontEngineError.Success ? FontEngine.GetGlyphIndex(unicode) : 0;
  1278. }
  1279. /// <summary>
  1280. ///
  1281. /// </summary>
  1282. /// <param name="unicode"></param>
  1283. /// <param name="variantSelectorUnicode"></param>
  1284. /// <returns></returns>
  1285. internal uint GetGlyphVariantIndex(uint unicode, uint variantSelectorUnicode)
  1286. {
  1287. # if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  1288. // Load font face.
  1289. return LoadFontFace() == FontEngineError.Success ? FontEngine.GetVariantGlyphIndex(unicode, variantSelectorUnicode) : 0;
  1290. #else
  1291. return 0;
  1292. #endif
  1293. }
  1294. // ================================================================================
  1295. // Properties and functions related to character and glyph additions as well as
  1296. // tacking glyphs that need to be added to various font asset atlas textures.
  1297. // ================================================================================
  1298. // List and HashSet used for tracking font assets whose font atlas texture and character data needs updating.
  1299. private static List<TMP_FontAsset> k_FontAssets_FontFeaturesUpdateQueue = new List<TMP_FontAsset>();
  1300. private static HashSet<int> k_FontAssets_FontFeaturesUpdateQueueLookup = new HashSet<int>();
  1301. private static List<Texture2D> k_FontAssets_AtlasTexturesUpdateQueue = new List<Texture2D>();
  1302. private static HashSet<int> k_FontAssets_AtlasTexturesUpdateQueueLookup = new HashSet<int>();
  1303. /// <summary>
  1304. ///
  1305. /// </summary>
  1306. /// <param name="fontAsset"></param>
  1307. internal static void RegisterFontAssetForFontFeatureUpdate(TMP_FontAsset fontAsset)
  1308. {
  1309. int instanceID = fontAsset.instanceID;
  1310. if (k_FontAssets_FontFeaturesUpdateQueueLookup.Add(instanceID))
  1311. k_FontAssets_FontFeaturesUpdateQueue.Add(fontAsset);
  1312. }
  1313. /// <summary>
  1314. /// Function called to update the font atlas texture and character data of font assets to which
  1315. /// new characters were added.
  1316. /// </summary>
  1317. internal static void UpdateFontFeaturesForFontAssetsInQueue()
  1318. {
  1319. int count = k_FontAssets_FontFeaturesUpdateQueue.Count;
  1320. for (int i = 0; i < count; i++)
  1321. {
  1322. k_FontAssets_FontFeaturesUpdateQueue[i].UpdateGPOSFontFeaturesForNewlyAddedGlyphs();
  1323. }
  1324. if (count > 0)
  1325. {
  1326. k_FontAssets_FontFeaturesUpdateQueue.Clear();
  1327. k_FontAssets_FontFeaturesUpdateQueueLookup.Clear();
  1328. }
  1329. }
  1330. /// <summary>
  1331. /// Register Atlas Texture for Apply()
  1332. /// </summary>
  1333. /// <param name="texture">The texture on which to call Apply().</param>
  1334. internal static void RegisterAtlasTextureForApply(Texture2D texture)
  1335. {
  1336. int instanceID = texture.GetInstanceID();
  1337. if (k_FontAssets_AtlasTexturesUpdateQueueLookup.Add(instanceID))
  1338. k_FontAssets_AtlasTexturesUpdateQueue.Add(texture);
  1339. }
  1340. /// <summary>
  1341. ///
  1342. /// </summary>
  1343. internal static void UpdateAtlasTexturesInQueue()
  1344. {
  1345. int count = k_FontAssets_AtlasTexturesUpdateQueueLookup.Count;
  1346. for (int i = 0; i < count; i++)
  1347. k_FontAssets_AtlasTexturesUpdateQueue[i].Apply(false, false);
  1348. if (count > 0)
  1349. {
  1350. k_FontAssets_AtlasTexturesUpdateQueue.Clear();
  1351. k_FontAssets_AtlasTexturesUpdateQueueLookup.Clear();
  1352. }
  1353. }
  1354. /// <summary>
  1355. ///
  1356. /// </summary>
  1357. internal static void UpdateFontAssetsInUpdateQueue()
  1358. {
  1359. UpdateAtlasTexturesInQueue();
  1360. UpdateFontFeaturesForFontAssetsInQueue();
  1361. }
  1362. /// <summary>
  1363. ///
  1364. /// </summary>
  1365. //private bool m_IsAlreadyRegisteredForUpdate;
  1366. /// <summary>
  1367. /// List of glyphs that need to be rendered and added to an atlas texture.
  1368. /// </summary>
  1369. private List<Glyph> m_GlyphsToRender = new List<Glyph>();
  1370. /// <summary>
  1371. /// List of glyphs that we just rendered and added to an atlas texture.
  1372. /// </summary>
  1373. private List<Glyph> m_GlyphsRendered = new List<Glyph>();
  1374. /// <summary>
  1375. /// List of all the glyph indexes contained in the font asset.
  1376. /// </summary>
  1377. private List<uint> m_GlyphIndexList = new List<uint>();
  1378. /// <summary>
  1379. /// List of glyph indexes newly added to the font asset.
  1380. /// This list is used in the process of retrieving font features.
  1381. /// </summary>
  1382. private List<uint> m_GlyphIndexListNewlyAdded = new List<uint>();
  1383. /// <summary>
  1384. ///
  1385. /// </summary>
  1386. internal List<uint> m_GlyphsToAdd = new List<uint>();
  1387. internal HashSet<uint> m_GlyphsToAddLookup = new HashSet<uint>();
  1388. internal List<TMP_Character> m_CharactersToAdd = new List<TMP_Character>();
  1389. internal HashSet<uint> m_CharactersToAddLookup = new HashSet<uint>();
  1390. /// <summary>
  1391. /// Internal list used to track characters that could not be added to the font asset.
  1392. /// </summary>
  1393. internal List<uint> s_MissingCharacterList = new List<uint>();
  1394. /// <summary>
  1395. /// Hash table used to track characters that are known to be missing from the font file.
  1396. /// </summary>
  1397. internal HashSet<uint> m_MissingUnicodesFromFontFile = new HashSet<uint>();
  1398. /// <summary>
  1399. /// Internal static array used to avoid allocations when using the GetGlyphPairAdjustmentTable().
  1400. /// </summary>
  1401. internal static uint[] k_GlyphIndexArray;
  1402. /// <summary>
  1403. /// Try adding the characters from the provided string to the font asset.
  1404. /// </summary>
  1405. /// <param name="unicodes">Array that contains the characters to add to the font asset.</param>
  1406. /// <param name="includeFontFeatures"></param>
  1407. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1408. public bool TryAddCharacters(uint[] unicodes, bool includeFontFeatures = false)
  1409. {
  1410. uint[] missingUnicodes;
  1411. return TryAddCharacters(unicodes, out missingUnicodes, includeFontFeatures);
  1412. }
  1413. /// <summary>
  1414. /// Try adding the characters from the provided string to the font asset.
  1415. /// </summary>
  1416. /// <param name="unicodes">Array that contains the characters to add to the font asset.</param>
  1417. /// <param name="missingUnicodes">Array containing the characters that could not be added to the font asset.</param>
  1418. /// <param name="includeFontFeatures"></param>
  1419. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1420. public bool TryAddCharacters(uint[] unicodes, out uint[] missingUnicodes, bool includeFontFeatures = false)
  1421. {
  1422. k_TryAddCharactersMarker.Begin();
  1423. // Make sure font asset is set to dynamic and that we have a valid list of characters.
  1424. if (unicodes == null || unicodes.Length == 0 || m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1425. {
  1426. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1427. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this);
  1428. else
  1429. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided Unicode list is Null or Empty.", this);
  1430. missingUnicodes = null;
  1431. k_TryAddCharactersMarker.End();
  1432. return false;
  1433. }
  1434. // Load font face.
  1435. if (LoadFontFace() != FontEngineError.Success)
  1436. {
  1437. missingUnicodes = unicodes.ToArray();
  1438. k_TryAddCharactersMarker.End();
  1439. return false;
  1440. }
  1441. // Make sure font asset has been initialized
  1442. if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null)
  1443. ReadFontAssetDefinition();
  1444. // Clear lists used to track which character and glyphs were added or missing.
  1445. m_GlyphsToAdd.Clear();
  1446. m_GlyphsToAddLookup.Clear();
  1447. m_CharactersToAdd.Clear();
  1448. m_CharactersToAddLookup.Clear();
  1449. s_MissingCharacterList.Clear();
  1450. bool isMissingCharacters = false;
  1451. int unicodeCount = unicodes.Length;
  1452. for (int i = 0; i < unicodeCount; i++)
  1453. {
  1454. uint unicode = unicodes[i];
  1455. // Check if character is already contained in the character table.
  1456. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1457. continue;
  1458. // Get the index of the glyph for this Unicode value.
  1459. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1460. // Skip missing glyphs
  1461. if (glyphIndex == 0)
  1462. {
  1463. // Special handling for characters with potential alternative glyph representations
  1464. switch (unicode)
  1465. {
  1466. case 0xA0: // Non Breaking Space <NBSP>
  1467. // Use Space
  1468. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  1469. break;
  1470. case 0xAD: // Soft Hyphen <SHY>
  1471. case 0x2011: // Non Breaking Hyphen
  1472. // Use Hyphen Minus
  1473. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  1474. break;
  1475. }
  1476. // Skip to next character if no potential alternative glyph representation is present in font file.
  1477. if (glyphIndex == 0)
  1478. {
  1479. // Add character to list of missing characters.
  1480. s_MissingCharacterList.Add(unicode);
  1481. isMissingCharacters = true;
  1482. continue;
  1483. }
  1484. }
  1485. TMP_Character character = new TMP_Character(unicode, glyphIndex);
  1486. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1487. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1488. {
  1489. // Add a reference to the source text asset and glyph
  1490. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  1491. character.textAsset = this;
  1492. m_CharacterTable.Add(character);
  1493. m_CharacterLookupDictionary.Add(unicode, character);
  1494. continue;
  1495. }
  1496. // Make sure glyph index has not already been added to list of glyphs to add.
  1497. if (m_GlyphsToAddLookup.Add(glyphIndex))
  1498. m_GlyphsToAdd.Add(glyphIndex);
  1499. // Make sure unicode / character has not already been added.
  1500. if (m_CharactersToAddLookup.Add(unicode))
  1501. m_CharactersToAdd.Add(character);
  1502. }
  1503. if (m_GlyphsToAdd.Count == 0)
  1504. {
  1505. //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.");
  1506. missingUnicodes = unicodes;
  1507. k_TryAddCharactersMarker.End();
  1508. return false;
  1509. }
  1510. // Resize the Atlas Texture to the appropriate size
  1511. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  1512. {
  1513. #if UNITY_2021_2_OR_NEWER
  1514. m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight);
  1515. #else
  1516. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1517. #endif
  1518. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1519. }
  1520. Glyph[] glyphs;
  1521. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs);
  1522. // Add new glyphs to relevant font asset data structure
  1523. for (int i = 0; i < glyphs.Length && glyphs[i] != null; i++)
  1524. {
  1525. Glyph glyph = glyphs[i];
  1526. uint glyphIndex = glyph.index;
  1527. glyph.atlasIndex = m_AtlasTextureIndex;
  1528. // Add new glyph to glyph table.
  1529. m_GlyphTable.Add(glyph);
  1530. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1531. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1532. m_GlyphIndexList.Add(glyphIndex);
  1533. }
  1534. // Clear glyph index list to allow
  1535. m_GlyphsToAdd.Clear();
  1536. // Add new characters to relevant data structures as well as track glyphs that could not be added to the current atlas texture.
  1537. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1538. {
  1539. TMP_Character character = m_CharactersToAdd[i];
  1540. Glyph glyph;
  1541. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false)
  1542. {
  1543. m_GlyphsToAdd.Add(character.glyphIndex);
  1544. continue;
  1545. }
  1546. // Add a reference to the source text asset and glyph
  1547. character.glyph = glyph;
  1548. character.textAsset = this;
  1549. m_CharacterTable.Add(character);
  1550. m_CharacterLookupDictionary.Add(character.unicode, character);
  1551. // Remove character from list to add
  1552. m_CharactersToAdd.RemoveAt(i);
  1553. i -= 1;
  1554. }
  1555. // Try adding missing glyphs to
  1556. if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false)
  1557. {
  1558. while (allGlyphsAddedToTexture == false)
  1559. allGlyphsAddedToTexture = TryAddGlyphsToNewAtlasTexture();
  1560. }
  1561. // Get Font Features for the given characters
  1562. if (includeFontFeatures)
  1563. {
  1564. UpdateFontFeaturesForNewlyAddedGlyphs();
  1565. }
  1566. #if UNITY_EDITOR
  1567. // Makes the changes to the font asset persistent.
  1568. RegisterResourceForUpdate?.Invoke(this);
  1569. #endif
  1570. // Populate list of missing characters
  1571. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1572. {
  1573. TMP_Character character = m_CharactersToAdd[i];
  1574. s_MissingCharacterList.Add(character.unicode);
  1575. }
  1576. missingUnicodes = null;
  1577. if (s_MissingCharacterList.Count > 0)
  1578. missingUnicodes = s_MissingCharacterList.ToArray();
  1579. k_TryAddCharactersMarker.End();
  1580. return allGlyphsAddedToTexture && !isMissingCharacters;
  1581. }
  1582. /// <summary>
  1583. /// Try adding the characters from the provided string to the font asset.
  1584. /// </summary>
  1585. /// <param name="characters">String containing the characters to add to the font asset.</param>
  1586. /// <param name="includeFontFeatures"></param>
  1587. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1588. public bool TryAddCharacters(string characters, bool includeFontFeatures = false)
  1589. {
  1590. string missingCharacters;
  1591. return TryAddCharacters(characters, out missingCharacters, includeFontFeatures);
  1592. }
  1593. /// <summary>
  1594. /// Try adding the characters from the provided string to the font asset.
  1595. /// </summary>
  1596. /// <param name="characters">String containing the characters to add to the font asset.</param>
  1597. /// <param name="missingCharacters">String containing the characters that could not be added to the font asset.</param>
  1598. /// <param name="includeFontFeatures"></param>
  1599. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1600. public bool TryAddCharacters(string characters, out string missingCharacters, bool includeFontFeatures = false)
  1601. {
  1602. k_TryAddCharactersMarker.Begin();
  1603. // Make sure font asset is set to dynamic and that we have a valid list of characters.
  1604. if (string.IsNullOrEmpty(characters) || m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1605. {
  1606. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1607. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this);
  1608. else
  1609. {
  1610. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided character list is Null or Empty.", this);
  1611. }
  1612. missingCharacters = characters;
  1613. k_TryAddCharactersMarker.End();
  1614. return false;
  1615. }
  1616. // Load font face.
  1617. if (LoadFontFace() != FontEngineError.Success)
  1618. {
  1619. missingCharacters = characters;
  1620. k_TryAddCharactersMarker.End();
  1621. return false;
  1622. }
  1623. // Make sure font asset has been initialized
  1624. if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null)
  1625. ReadFontAssetDefinition();
  1626. // Clear data structures used to track which glyph needs to be added to atlas texture.
  1627. m_GlyphsToAdd.Clear();
  1628. m_GlyphsToAddLookup.Clear();
  1629. m_CharactersToAdd.Clear();
  1630. m_CharactersToAddLookup.Clear();
  1631. s_MissingCharacterList.Clear();
  1632. bool isMissingCharacters = false;
  1633. int characterCount = characters.Length;
  1634. // Iterate over each of the requested characters.
  1635. for (int i = 0; i < characterCount; i++)
  1636. {
  1637. uint unicode = characters[i];
  1638. // Check if character is already contained in the character table.
  1639. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1640. continue;
  1641. // Get the index of the glyph for this unicode value.
  1642. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1643. // Skip missing glyphs
  1644. if (glyphIndex == 0)
  1645. {
  1646. // Special handling for characters with potential alternative glyph representations
  1647. switch (unicode)
  1648. {
  1649. case 0xA0: // Non Breaking Space <NBSP>
  1650. // Use Space
  1651. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  1652. break;
  1653. case 0xAD: // Soft Hyphen <SHY>
  1654. case 0x2011: // Non Breaking Hyphen
  1655. // Use Hyphen Minus
  1656. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  1657. break;
  1658. }
  1659. // Skip to next character if no potential alternative glyph representation is present in font file.
  1660. if (glyphIndex == 0)
  1661. {
  1662. // Add character to list of missing characters.
  1663. s_MissingCharacterList.Add(unicode);
  1664. isMissingCharacters = true;
  1665. continue;
  1666. }
  1667. }
  1668. TMP_Character character = new TMP_Character(unicode, glyphIndex);
  1669. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1670. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1671. {
  1672. // Add a reference to the source text asset and glyph
  1673. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  1674. character.textAsset = this;
  1675. m_CharacterTable.Add(character);
  1676. m_CharacterLookupDictionary.Add(unicode, character);
  1677. continue;
  1678. }
  1679. // Make sure glyph index has not already been added to list of glyphs to add.
  1680. if (m_GlyphsToAddLookup.Add(glyphIndex))
  1681. m_GlyphsToAdd.Add(glyphIndex);
  1682. // Make sure unicode / character has not already been added.
  1683. if (m_CharactersToAddLookup.Add(unicode))
  1684. m_CharactersToAdd.Add(character);
  1685. }
  1686. if (m_GlyphsToAdd.Count == 0)
  1687. {
  1688. missingCharacters = characters;
  1689. k_TryAddCharactersMarker.End();
  1690. return false;
  1691. }
  1692. // Resize the Atlas Texture to the appropriate size
  1693. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  1694. {
  1695. #if UNITY_2021_2_OR_NEWER
  1696. m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight);
  1697. #else
  1698. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1699. #endif
  1700. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1701. }
  1702. Glyph[] glyphs;
  1703. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs);
  1704. for (int i = 0; i < glyphs.Length && glyphs[i] != null; i++)
  1705. {
  1706. Glyph glyph = glyphs[i];
  1707. uint glyphIndex = glyph.index;
  1708. glyph.atlasIndex = m_AtlasTextureIndex;
  1709. // Add new glyph to glyph table.
  1710. m_GlyphTable.Add(glyph);
  1711. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1712. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1713. m_GlyphIndexList.Add(glyphIndex);
  1714. }
  1715. // Clear glyph index list to track glyphs that were not added to the atlas texture
  1716. m_GlyphsToAdd.Clear();
  1717. // Add new characters to relevant data structures.
  1718. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1719. {
  1720. TMP_Character character = m_CharactersToAdd[i];
  1721. Glyph glyph;
  1722. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false)
  1723. {
  1724. m_GlyphsToAdd.Add(character.glyphIndex);
  1725. continue;
  1726. }
  1727. // Add a reference to the source text asset and glyph
  1728. character.glyph = glyph;
  1729. character.textAsset = this;
  1730. m_CharacterTable.Add(character);
  1731. m_CharacterLookupDictionary.Add(character.unicode, character);
  1732. // Remove character from list to add
  1733. m_CharactersToAdd.RemoveAt(i);
  1734. i -= 1;
  1735. }
  1736. // Try adding glyphs that didn't fit in the current atlas texture to new atlas texture
  1737. if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false)
  1738. {
  1739. while (allGlyphsAddedToTexture == false)
  1740. allGlyphsAddedToTexture = TryAddGlyphsToNewAtlasTexture();
  1741. }
  1742. // Get Font Features for the given characters
  1743. if (includeFontFeatures)
  1744. {
  1745. UpdateFontFeaturesForNewlyAddedGlyphs();
  1746. }
  1747. #if UNITY_EDITOR
  1748. // Makes the changes to the font asset persistent.
  1749. RegisterResourceForUpdate?.Invoke(this);
  1750. #endif
  1751. missingCharacters = string.Empty;
  1752. // Populate list of missing characters
  1753. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1754. {
  1755. TMP_Character character = m_CharactersToAdd[i];
  1756. s_MissingCharacterList.Add(character.unicode);
  1757. }
  1758. if (s_MissingCharacterList.Count > 0)
  1759. missingCharacters = s_MissingCharacterList.UintToString();
  1760. k_TryAddCharactersMarker.End();
  1761. return allGlyphsAddedToTexture && !isMissingCharacters;
  1762. }
  1763. // Functions to remove...
  1764. /*
  1765. /// <summary>
  1766. /// NOT USED CURRENTLY - Try adding character using Unicode value to font asset.
  1767. /// </summary>
  1768. /// <param name="unicode">The Unicode value of the character.</param>
  1769. /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param>
  1770. /// <returns>Returns true if the character has been added. False otherwise.</returns>
  1771. internal bool TryAddCharacter_Internal(uint unicode)
  1772. {
  1773. TMP_Character character = null;
  1774. // Check if character is already contained in the character table.
  1775. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1776. return true;
  1777. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1778. if (glyphIndex == 0)
  1779. return false;
  1780. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1781. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1782. {
  1783. character = new TMP_Character(unicode, m_GlyphLookupDictionary[glyphIndex]);
  1784. m_CharacterTable.Add(character);
  1785. m_CharacterLookupDictionary.Add(unicode, character);
  1786. //#if UNITY_EDITOR
  1787. // Makes the changes to the font asset persistent.
  1788. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1789. // Could also add some update registry to handle this.
  1790. //SortGlyphTable();
  1791. //UnityEditor.EditorUtility.SetDirty(this);
  1792. //#endif
  1793. return true;
  1794. }
  1795. // Resize the Atlas Texture to the appropriate size
  1796. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1
  1797. {
  1798. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1799. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1800. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1801. }
  1802. Glyph glyph;
  1803. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  1804. {
  1805. // Add new glyph to glyph table.
  1806. m_GlyphTable.Add(glyph);
  1807. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1808. // Add new character
  1809. character = new TMP_Character(unicode, glyph);
  1810. m_CharacterTable.Add(character);
  1811. m_CharacterLookupDictionary.Add(unicode, character);
  1812. //#if UNITY_EDITOR
  1813. // Makes the changes to the font asset persistent.
  1814. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1815. // Could also add some update registry to handle this.
  1816. //SortGlyphTable();
  1817. //UnityEditor.EditorUtility.SetDirty(this);
  1818. //#endif
  1819. return true;
  1820. }
  1821. return false;
  1822. }
  1823. /// <summary>
  1824. /// To be removed.
  1825. /// </summary>
  1826. /// <param name="unicode"></param>
  1827. /// <param name="glyph"></param>
  1828. internal TMP_Character AddCharacter_Internal(uint unicode, Glyph glyph)
  1829. {
  1830. // Check if character is already contained in the character table.
  1831. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1832. return m_CharacterLookupDictionary[unicode];
  1833. uint glyphIndex = glyph.index;
  1834. // Resize the Atlas Texture to the appropriate size
  1835. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  1836. {
  1837. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1838. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1839. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1840. }
  1841. // Check if glyph is already contained in the glyph table.
  1842. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex) == false)
  1843. {
  1844. if (glyph.glyphRect.width == 0 || glyph.glyphRect.width == 0)
  1845. {
  1846. // Glyphs with zero width and / or height can be automatically added to font asset.
  1847. m_GlyphTable.Add(glyph);
  1848. }
  1849. else
  1850. {
  1851. // Try packing new glyph
  1852. if (FontEngine.TryPackGlyphInAtlas(glyph, m_AtlasPadding, GlyphPackingMode.ContactPointRule, m_AtlasRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects) == false)
  1853. {
  1854. // TODO: Add handling to create new atlas texture to fit glyph.
  1855. return null;
  1856. }
  1857. //m_GlyphsToRender.Add(glyph);
  1858. }
  1859. }
  1860. // Add character to font asset.
  1861. TMP_Character character = new TMP_Character(unicode, glyph);
  1862. m_CharacterTable.Add(character);
  1863. m_CharacterLookupDictionary.Add(unicode, character);
  1864. //Debug.Log("Adding character [" + (char)unicode + "] with Unicode (" + unicode + ") to [" + this.name + "] font asset.");
  1865. // Schedule glyph to be added to the font atlas texture
  1866. //TM_FontAssetUpdateManager.RegisterFontAssetForUpdate(this);
  1867. //UpdateAtlasTexture(); // Temporary until callback system is revised.
  1868. //#if UNITY_EDITOR
  1869. // Makes the changes to the font asset persistent.
  1870. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1871. // Could also add some update registry to handle this.
  1872. //SortGlyphTable();
  1873. //UnityEditor.EditorUtility.SetDirty(this);
  1874. //#endif
  1875. return character;
  1876. }
  1877. */
  1878. internal bool AddGlyphInternal(uint glyphIndex)
  1879. {
  1880. Glyph glyph;
  1881. return TryAddGlyphInternal(glyphIndex, out glyph);
  1882. }
  1883. /// <summary>
  1884. ///
  1885. /// </summary>
  1886. /// <param name="glyphIndex"></param>
  1887. /// <param name="glyph"></param>
  1888. /// <returns></returns>
  1889. internal bool TryAddGlyphInternal(uint glyphIndex, out Glyph glyph)
  1890. {
  1891. k_TryAddGlyphMarker.Begin();
  1892. glyph = null;
  1893. // Check if glyph is already present in the font asset.
  1894. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1895. {
  1896. glyph = m_GlyphLookupDictionary[glyphIndex];
  1897. k_TryAddGlyphMarker.End();
  1898. return true;
  1899. }
  1900. // Return if font asset is static
  1901. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1902. {
  1903. k_TryAddGlyphMarker.End();
  1904. return false;
  1905. }
  1906. // Load font face.
  1907. if (LoadFontFace() != FontEngineError.Success)
  1908. {
  1909. k_TryAddGlyphMarker.End();
  1910. return false;
  1911. }
  1912. if (m_AtlasTextures[m_AtlasTextureIndex].isReadable == false)
  1913. {
  1914. Debug.LogWarning("Unable to add the requested glyph to font asset [" + this.name + "]'s atlas texture. Please make the texture [" + m_AtlasTextures[m_AtlasTextureIndex].name + "] readable.", m_AtlasTextures[m_AtlasTextureIndex]);
  1915. k_TryAddGlyphMarker.End();
  1916. return false;
  1917. }
  1918. // Resize the Atlas Texture to the appropriate size
  1919. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  1920. {
  1921. #if UNITY_2021_2_OR_NEWER
  1922. m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight);
  1923. #else
  1924. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1925. #endif
  1926. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1927. }
  1928. // Set texture upload mode to batching texture.Apply()
  1929. //FontEngine.SetTextureUploadMode(false);
  1930. // Try adding glyph to local atlas texture
  1931. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  1932. {
  1933. // Update glyph atlas index
  1934. glyph.atlasIndex = m_AtlasTextureIndex;
  1935. // Add new glyph to glyph table.
  1936. m_GlyphTable.Add(glyph);
  1937. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1938. // Add new character
  1939. //character = new TMP_Character(unicode, this, glyph);
  1940. //m_CharacterTable.Add(character);
  1941. //m_CharacterLookupDictionary.Add(unicode, character);
  1942. m_GlyphIndexList.Add(glyphIndex);
  1943. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1944. if (m_GetFontFeatures && TMP_Settings.getFontFeaturesAtRuntime)
  1945. {
  1946. UpdateGSUBFontFeaturesForNewGlyphIndex(glyphIndex);
  1947. RegisterFontAssetForFontFeatureUpdate(this);
  1948. }
  1949. //RegisterAtlasTextureForApply(m_AtlasTextures[m_AtlasTextureIndex]);
  1950. //FontEngine.SetTextureUploadMode(true);
  1951. #if UNITY_EDITOR
  1952. // Makes the changes to the font asset persistent.
  1953. RegisterResourceForUpdate?.Invoke(this);
  1954. #endif
  1955. k_TryAddGlyphMarker.End();
  1956. return true;
  1957. }
  1958. // Add glyph which did not fit in current atlas texture to new atlas texture.
  1959. if (m_IsMultiAtlasTexturesEnabled)
  1960. {
  1961. // Create new atlas texture
  1962. SetupNewAtlasTexture();
  1963. // Try adding glyph to newly created atlas texture
  1964. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  1965. {
  1966. // Update glyph atlas index
  1967. glyph.atlasIndex = m_AtlasTextureIndex;
  1968. // Add new glyph to glyph table.
  1969. m_GlyphTable.Add(glyph);
  1970. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1971. // Add new character
  1972. //character = new TMP_Character(unicode, this, glyph);
  1973. //m_CharacterTable.Add(character);
  1974. //m_CharacterLookupDictionary.Add(unicode, character);
  1975. m_GlyphIndexList.Add(glyphIndex);
  1976. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1977. if (m_GetFontFeatures && TMP_Settings.getFontFeaturesAtRuntime)
  1978. {
  1979. UpdateGSUBFontFeaturesForNewGlyphIndex(glyphIndex);
  1980. RegisterFontAssetForFontFeatureUpdate(this);
  1981. }
  1982. //RegisterAtlasTextureForApply(m_AtlasTextures[m_AtlasTextureIndex]);
  1983. //FontEngine.SetTextureUploadMode(true);
  1984. #if UNITY_EDITOR
  1985. // Make changes to font asset persistent.
  1986. RegisterResourceForUpdate?.Invoke(this);
  1987. #endif
  1988. k_TryAddGlyphMarker.End();
  1989. return true;
  1990. }
  1991. }
  1992. k_TryAddGlyphMarker.End();
  1993. return false;
  1994. }
  1995. /// <summary>
  1996. /// Try adding character using Unicode value to font asset.
  1997. /// Function assumes internal user has already checked to make sure the character is not already contained in the font asset.
  1998. /// </summary>
  1999. /// <param name="unicode">The Unicode value of the character.</param>
  2000. /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param>
  2001. /// <returns>Returns true if the character has been added. False otherwise.</returns>
  2002. internal bool TryAddCharacterInternal(uint unicode, out TMP_Character character)
  2003. {
  2004. k_TryAddCharacterMarker.Begin();
  2005. character = null;
  2006. // Check if the Unicode character is already known to be missing from the source font file.
  2007. if (m_MissingUnicodesFromFontFile.Contains(unicode))
  2008. {
  2009. k_TryAddCharacterMarker.End();
  2010. return false;
  2011. }
  2012. // Load font face.
  2013. if (LoadFontFace() != FontEngineError.Success)
  2014. {
  2015. k_TryAddCharacterMarker.End();
  2016. return false;
  2017. }
  2018. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  2019. if (glyphIndex == 0)
  2020. {
  2021. // Special handling for characters with potential alternative glyph representations
  2022. switch (unicode)
  2023. {
  2024. case 0xA0: // Non Breaking Space <NBSP>
  2025. // Use Space
  2026. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  2027. break;
  2028. case 0xAD: // Soft Hyphen <SHY>
  2029. case 0x2011: // Non Breaking Hyphen
  2030. // Use Hyphen Minus
  2031. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  2032. break;
  2033. }
  2034. // Return if no potential alternative glyph representation is present in font file.
  2035. if (glyphIndex == 0)
  2036. {
  2037. m_MissingUnicodesFromFontFile.Add(unicode);
  2038. k_TryAddCharacterMarker.End();
  2039. return false;
  2040. }
  2041. }
  2042. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  2043. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  2044. {
  2045. character = new TMP_Character(unicode, this, m_GlyphLookupDictionary[glyphIndex]);
  2046. m_CharacterTable.Add(character);
  2047. m_CharacterLookupDictionary.Add(unicode, character);
  2048. #if UNITY_EDITOR
  2049. // Makes the changes to the font asset persistent.
  2050. RegisterResourceForUpdate?.Invoke(this);
  2051. #endif
  2052. k_TryAddCharacterMarker.End();
  2053. return true;
  2054. }
  2055. Glyph glyph = null;
  2056. // TODO: Potential new feature to explore where selected font assets share the same atlas texture(s).
  2057. // Handling if using Dynamic Textures
  2058. //if (m_IsUsingDynamicTextures)
  2059. //{
  2060. // if (TMP_DynamicAtlasTextureGroup.AddGlyphToManagedDynamicTexture(this, glyphIndex, m_AtlasPadding, m_AtlasRenderMode, out glyph))
  2061. // {
  2062. // // Add new glyph to glyph table.
  2063. // m_GlyphTable.Add(glyph);
  2064. // m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  2065. // // Add new character
  2066. // character = new TMP_Character(unicode, glyph);
  2067. // m_CharacterTable.Add(character);
  2068. // m_CharacterLookupDictionary.Add(unicode, character);
  2069. // m_GlyphIndexList.Add(glyphIndex);
  2070. // if (TMP_Settings.getFontFeaturesAtRuntime)
  2071. // {
  2072. // if (k_FontAssetsToUpdateLookup.Add(instanceID))
  2073. // k_FontAssetsToUpdate.Add(this);
  2074. // }
  2075. // return true;
  2076. // }
  2077. //}
  2078. // Make sure atlas texture is readable.
  2079. if (m_AtlasTextures[m_AtlasTextureIndex].isReadable == false)
  2080. {
  2081. 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]);
  2082. k_TryAddCharacterMarker.End();
  2083. return false;
  2084. }
  2085. // Resize the Atlas Texture to the appropriate size
  2086. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  2087. {
  2088. #if UNITY_2021_2_OR_NEWER
  2089. m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight);
  2090. #else
  2091. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  2092. #endif
  2093. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  2094. }
  2095. // Set texture upload mode to batching texture.Apply()
  2096. //FontEngine.SetTextureUploadMode(false);
  2097. // Try adding glyph to local atlas texture
  2098. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  2099. {
  2100. // Update glyph atlas index
  2101. glyph.atlasIndex = m_AtlasTextureIndex;
  2102. // Add new glyph to glyph table.
  2103. m_GlyphTable.Add(glyph);
  2104. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  2105. // Add new character
  2106. character = new TMP_Character(unicode, this, glyph);
  2107. m_CharacterTable.Add(character);
  2108. m_CharacterLookupDictionary.Add(unicode, character);
  2109. m_GlyphIndexList.Add(glyphIndex);
  2110. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  2111. if (m_GetFontFeatures && TMP_Settings.getFontFeaturesAtRuntime)
  2112. {
  2113. UpdateGSUBFontFeaturesForNewGlyphIndex(glyphIndex);
  2114. RegisterFontAssetForFontFeatureUpdate(this);
  2115. }
  2116. //RegisterAtlasTextureForApply(m_AtlasTextures[m_AtlasTextureIndex]);
  2117. //FontEngine.SetTextureUploadMode(true);
  2118. #if UNITY_EDITOR
  2119. // Makes the changes to the font asset persistent.
  2120. RegisterResourceForUpdate?.Invoke(this);
  2121. #endif
  2122. k_TryAddCharacterMarker.End();
  2123. return true;
  2124. }
  2125. // Add glyph which did not fit in current atlas texture to new atlas texture.
  2126. if (m_IsMultiAtlasTexturesEnabled)
  2127. {
  2128. // Create new atlas texture
  2129. SetupNewAtlasTexture();
  2130. // Try adding glyph to newly created atlas texture
  2131. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  2132. {
  2133. // Update glyph atlas index
  2134. glyph.atlasIndex = m_AtlasTextureIndex;
  2135. // Add new glyph to glyph table.
  2136. m_GlyphTable.Add(glyph);
  2137. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  2138. // Add new character
  2139. character = new TMP_Character(unicode, this, glyph);
  2140. m_CharacterTable.Add(character);
  2141. m_CharacterLookupDictionary.Add(unicode, character);
  2142. m_GlyphIndexList.Add(glyphIndex);
  2143. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  2144. if (m_GetFontFeatures && TMP_Settings.getFontFeaturesAtRuntime)
  2145. {
  2146. UpdateGSUBFontFeaturesForNewGlyphIndex(glyphIndex);
  2147. RegisterFontAssetForFontFeatureUpdate(this);
  2148. }
  2149. //RegisterAtlasTextureForApply(m_AtlasTextures[m_AtlasTextureIndex]);
  2150. //FontEngine.SetTextureUploadMode(true);
  2151. #if UNITY_EDITOR
  2152. // Make changes to font asset persistent.
  2153. RegisterResourceForUpdate?.Invoke(this);
  2154. #endif
  2155. k_TryAddCharacterMarker.End();
  2156. return true;
  2157. }
  2158. }
  2159. k_TryAddCharacterMarker.End();
  2160. return false;
  2161. }
  2162. internal bool TryGetCharacter_and_QueueRenderToTexture(uint unicode, out TMP_Character character)
  2163. {
  2164. k_TryAddCharacterMarker.Begin();
  2165. character = null;
  2166. // Check if the Unicode character is already known to be missing from the source font file.
  2167. if (m_MissingUnicodesFromFontFile.Contains(unicode))
  2168. {
  2169. k_TryAddCharacterMarker.End();
  2170. return false;
  2171. }
  2172. // Load font face.
  2173. if (LoadFontFace() != FontEngineError.Success)
  2174. {
  2175. k_TryAddCharacterMarker.End();
  2176. return false;
  2177. }
  2178. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  2179. if (glyphIndex == 0)
  2180. {
  2181. // Special handling for characters with potential alternative glyph representations
  2182. switch (unicode)
  2183. {
  2184. case 0xA0: // Non Breaking Space <NBSP>
  2185. // Use Space
  2186. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  2187. break;
  2188. case 0xAD: // Soft Hyphen <SHY>
  2189. case 0x2011: // Non Breaking Hyphen
  2190. // Use Hyphen Minus
  2191. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  2192. break;
  2193. }
  2194. // Return if no potential alternative glyph representation is present in font file.
  2195. if (glyphIndex == 0)
  2196. {
  2197. m_MissingUnicodesFromFontFile.Add(unicode);
  2198. k_TryAddCharacterMarker.End();
  2199. return false;
  2200. }
  2201. }
  2202. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  2203. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  2204. {
  2205. character = new TMP_Character(unicode, this, m_GlyphLookupDictionary[glyphIndex]);
  2206. m_CharacterTable.Add(character);
  2207. m_CharacterLookupDictionary.Add(unicode, character);
  2208. #if UNITY_EDITOR
  2209. // Makes the changes to the font asset persistent.
  2210. RegisterResourceForUpdate?.Invoke(this);
  2211. #endif
  2212. k_TryAddCharacterMarker.End();
  2213. return true;
  2214. }
  2215. GlyphLoadFlags glyphLoadFlags = (GlyphRasterModes.RASTER_MODE_NO_HINTING & (GlyphRasterModes)m_AtlasRenderMode) == GlyphRasterModes.RASTER_MODE_NO_HINTING
  2216. ? GlyphLoadFlags.LOAD_NO_BITMAP | GlyphLoadFlags.LOAD_NO_HINTING
  2217. : GlyphLoadFlags.LOAD_NO_BITMAP;
  2218. Glyph glyph = null;
  2219. if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
  2220. {
  2221. // Add new glyph to glyph table.
  2222. m_GlyphTable.Add(glyph);
  2223. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  2224. // Add new character
  2225. character = new TMP_Character(unicode, this, glyph);
  2226. m_CharacterTable.Add(character);
  2227. m_CharacterLookupDictionary.Add(unicode, character);
  2228. m_GlyphIndexList.Add(glyphIndex);
  2229. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  2230. if (m_GetFontFeatures && TMP_Settings.getFontFeaturesAtRuntime)
  2231. {
  2232. UpdateGSUBFontFeaturesForNewGlyphIndex(glyphIndex);
  2233. RegisterFontAssetForFontFeatureUpdate(this);
  2234. }
  2235. // Add glyph to list of glyphs to be rendered
  2236. m_GlyphsToRender.Add(glyph);
  2237. // Register font asset to render and add glyphs to atlas textures
  2238. //RegisterFontAssetForAtlasTextureUpdate(this);
  2239. #if UNITY_EDITOR
  2240. // TODO: Consider potential optimization. This could be handled when exiting Play mode if we added any new characters to the asset.
  2241. // Makes the changes to the font asset persistent.
  2242. RegisterResourceForUpdate?.Invoke(this);
  2243. #endif
  2244. k_TryAddCharacterMarker.End();
  2245. return true;
  2246. }
  2247. k_TryAddCharacterMarker.End();
  2248. return false;
  2249. }
  2250. /// <summary>
  2251. /// This function requires an update to the TextCore:FontEngine
  2252. /// </summary>
  2253. internal void TryAddGlyphsToAtlasTextures()
  2254. {
  2255. /*
  2256. // Return if we don't have any glyphs to add.
  2257. if (m_GlyphsToRender.Count == 0)
  2258. return;
  2259. // Resize the Atlas Texture to the appropriate size
  2260. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  2261. {
  2262. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  2263. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  2264. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  2265. }
  2266. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToRender, m_GlyphsRendered, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  2267. // Try adding glyphs that didn't fit in the current atlas texture to new atlas texture
  2268. if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false)
  2269. {
  2270. while (allGlyphsAddedToTexture == false)
  2271. {
  2272. // Create and prepare new atlas texture
  2273. SetupNewAtlasTexture();
  2274. // Try adding remaining glyphs in the newly created atlas texture
  2275. allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToRender, m_GlyphsRendered, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  2276. }
  2277. }
  2278. if (allGlyphsAddedToTexture == false)
  2279. {
  2280. // TODO: Handle case when we have left over glyph to render that didn't fit in the atlas texture.
  2281. Debug.LogError("Unable to add some glyphs to atlas texture.");
  2282. }
  2283. #if UNITY_EDITOR
  2284. // Makes the changes to the font asset persistent.
  2285. if (UnityEditor.EditorUtility.IsPersistent(this))
  2286. {
  2287. //SortGlyphAndCharacterTables();
  2288. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  2289. }
  2290. #endif
  2291. */
  2292. }
  2293. /// <summary>
  2294. ///
  2295. /// </summary>
  2296. /// <returns></returns>
  2297. bool TryAddGlyphsToNewAtlasTexture()
  2298. {
  2299. // Create and prepare new atlas texture
  2300. SetupNewAtlasTexture();
  2301. Glyph[] glyphs;
  2302. // Try adding remaining glyphs in the newly created atlas texture
  2303. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs);
  2304. // Add new glyphs to relevant data structures.
  2305. for (int i = 0; i < glyphs.Length && glyphs[i] != null; i++)
  2306. {
  2307. Glyph glyph = glyphs[i];
  2308. uint glyphIndex = glyph.index;
  2309. glyph.atlasIndex = m_AtlasTextureIndex;
  2310. // Add new glyph to glyph table.
  2311. m_GlyphTable.Add(glyph);
  2312. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  2313. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  2314. m_GlyphIndexList.Add(glyphIndex);
  2315. }
  2316. // Clear glyph index list to allow us to track glyphs
  2317. m_GlyphsToAdd.Clear();
  2318. // Add new characters to relevant data structures as well as track glyphs that could not be added to the current atlas texture.
  2319. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  2320. {
  2321. TMP_Character character = m_CharactersToAdd[i];
  2322. Glyph glyph;
  2323. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false)
  2324. {
  2325. m_GlyphsToAdd.Add(character.glyphIndex);
  2326. continue;
  2327. }
  2328. // Add a reference to the source text asset and glyph
  2329. character.glyph = glyph;
  2330. character.textAsset = this;
  2331. m_CharacterTable.Add(character);
  2332. m_CharacterLookupDictionary.Add(character.unicode, character);
  2333. // Remove character
  2334. m_CharactersToAdd.RemoveAt(i);
  2335. i -= 1;
  2336. }
  2337. return allGlyphsAddedToTexture;
  2338. }
  2339. /// <summary>
  2340. ///
  2341. /// </summary>
  2342. void SetupNewAtlasTexture()
  2343. {
  2344. m_AtlasTextureIndex += 1;
  2345. // Check size of atlas texture array
  2346. if (m_AtlasTextures.Length == m_AtlasTextureIndex)
  2347. Array.Resize(ref m_AtlasTextures, m_AtlasTextures.Length * 2);
  2348. // Initialize new atlas texture
  2349. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2350. TextureFormat texFormat = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_COLOR) == GlyphRasterModes.RASTER_MODE_COLOR ? TextureFormat.RGBA32 : TextureFormat.Alpha8;
  2351. #else
  2352. TextureFormat texFormat = TextureFormat.Alpha8;
  2353. #endif
  2354. m_AtlasTextures[m_AtlasTextureIndex] = new Texture2D(m_AtlasWidth, m_AtlasHeight, texFormat, false);
  2355. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  2356. // Clear packing GlyphRects
  2357. int packingModifier = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  2358. m_FreeGlyphRects.Clear();
  2359. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  2360. m_UsedGlyphRects.Clear();
  2361. #if UNITY_EDITOR
  2362. // Add new texture as sub asset to font asset
  2363. Texture2D tex = m_AtlasTextures[m_AtlasTextureIndex];
  2364. tex.name = atlasTexture.name + " " + m_AtlasTextureIndex;
  2365. OnFontAssetTextureChanged?.Invoke(tex, this);
  2366. #endif
  2367. }
  2368. /// <summary>
  2369. /// Not used currently
  2370. /// </summary>
  2371. internal void UpdateAtlasTexture()
  2372. {
  2373. // Return if we don't have any glyphs to add to atlas texture.
  2374. if (m_GlyphsToRender.Count == 0)
  2375. return;
  2376. //Debug.Log("Updating [" + this.name + "]'s atlas texture.");
  2377. // Pack glyphs in the given atlas texture size.
  2378. // TODO: Packing and glyph render modes should be defined in the font asset.
  2379. //FontEngine.PackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_AtlasPadding, GlyphPackingMode.ContactPointRule, GlyphRenderMode.SDFAA, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  2380. //FontEngine.RenderGlyphsToTexture(m_GlyphsPacked, m_AtlasPadding, GlyphRenderMode.SDFAA, m_AtlasTextures[m_AtlasTextureIndex]);
  2381. // Resize the Atlas Texture to the appropriate size
  2382. if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1)
  2383. {
  2384. #if UNITY_2021_2_OR_NEWER
  2385. m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight);
  2386. #else
  2387. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  2388. #endif
  2389. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  2390. }
  2391. //FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_AtlasPadding, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  2392. // Apply changes to atlas texture
  2393. m_AtlasTextures[m_AtlasTextureIndex].Apply(false, false);
  2394. // Add glyphs that were successfully packed to the glyph table.
  2395. //for (int i = 0; i < m_GlyphsToRender.Count /* m_GlyphsPacked.Count */; i++)
  2396. //{
  2397. // Glyph glyph = m_GlyphsToRender[i]; // m_GlyphsPacked[i];
  2398. // // Update atlas texture index
  2399. // glyph.atlasIndex = m_AtlasTextureIndex;
  2400. // m_GlyphTable.Add(glyph);
  2401. // m_GlyphLookupDictionary.Add(glyph.index, glyph);
  2402. //}
  2403. // Clear list of glyphs
  2404. //m_GlyphsPacked.Clear();
  2405. //m_GlyphsToRender.Clear();
  2406. // Add any remaining glyphs into new atlas texture if multi texture support if enabled.
  2407. //if (m_GlyphsToPack.Count > 0)
  2408. //{
  2409. /*
  2410. // Create new atlas texture
  2411. Texture2D tex = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true);
  2412. tex.SetPixels32(new Color32[m_AtlasWidth * m_AtlasHeight]);
  2413. tex.Apply();
  2414. m_AtlasTextureIndex++;
  2415. if (m_AtlasTextures.Length == m_AtlasTextureIndex)
  2416. Array.Resize(ref m_AtlasTextures, Mathf.NextPowerOfTwo(m_AtlasTextureIndex + 1));
  2417. m_AtlasTextures[m_AtlasTextureIndex] = tex;
  2418. */
  2419. //}
  2420. #if UNITY_EDITOR
  2421. // Makes the changes to the font asset persistent.
  2422. RegisterResourceForUpdate?.Invoke(this);
  2423. #endif
  2424. }
  2425. // ****************************************
  2426. // OPENTYPE - FONT FEATURES
  2427. // ****************************************
  2428. void UpdateFontFeaturesForNewlyAddedGlyphs()
  2429. {
  2430. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2431. UpdateLigatureSubstitutionRecords();
  2432. #endif
  2433. UpdateGlyphAdjustmentRecords();
  2434. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2435. UpdateDiacriticalMarkAdjustmentRecords();
  2436. #endif
  2437. // Clear newly added glyph list
  2438. m_GlyphIndexListNewlyAdded.Clear();
  2439. }
  2440. void UpdateGPOSFontFeaturesForNewlyAddedGlyphs()
  2441. {
  2442. UpdateGlyphAdjustmentRecords();
  2443. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2444. UpdateDiacriticalMarkAdjustmentRecords();
  2445. #endif
  2446. // Clear newly added glyph list
  2447. m_GlyphIndexListNewlyAdded.Clear();
  2448. }
  2449. /// <summary>
  2450. ///
  2451. /// </summary>
  2452. internal void ImportFontFeatures()
  2453. {
  2454. if (LoadFontFace() != FontEngineError.Success)
  2455. return;
  2456. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2457. // Get Pair Adjustment records
  2458. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetAllPairAdjustmentRecords();
  2459. if (pairAdjustmentRecords != null)
  2460. AddPairAdjustmentRecords(pairAdjustmentRecords);
  2461. // Get Mark-to-Base adjustment records
  2462. UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord[] markToBaseRecords = FontEngine.GetAllMarkToBaseAdjustmentRecords();
  2463. if (markToBaseRecords != null)
  2464. AddMarkToBaseAdjustmentRecords(markToBaseRecords);
  2465. // Get Mark-to-Mark adjustment records
  2466. UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord[] markToMarkRecords = FontEngine.GetAllMarkToMarkAdjustmentRecords();
  2467. if (markToMarkRecords != null)
  2468. AddMarkToMarkAdjustmentRecords(markToMarkRecords);
  2469. // Get Ligature Substitution records
  2470. UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[] records = FontEngine.GetAllLigatureSubstitutionRecords();
  2471. if (records != null)
  2472. AddLigatureSubstitutionRecords(records);
  2473. #endif
  2474. m_ShouldReimportFontFeatures = false;
  2475. #if UNITY_EDITOR
  2476. // Makes the changes to the font asset persistent.
  2477. RegisterResourceForUpdate?.Invoke(this);
  2478. #endif
  2479. }
  2480. void UpdateGSUBFontFeaturesForNewGlyphIndex(uint glyphIndex)
  2481. {
  2482. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2483. UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[] records = FontEngine.GetLigatureSubstitutionRecords(glyphIndex);
  2484. if (records != null)
  2485. AddLigatureSubstitutionRecords(records);
  2486. #endif
  2487. }
  2488. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2489. /// <summary>
  2490. ///
  2491. /// </summary>
  2492. internal void UpdateLigatureSubstitutionRecords()
  2493. {
  2494. k_UpdateLigatureSubstitutionRecordsMarker.Begin();
  2495. UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[] records = FontEngine.GetLigatureSubstitutionRecords(m_GlyphIndexListNewlyAdded);
  2496. if (records != null)
  2497. AddLigatureSubstitutionRecords(records);
  2498. k_UpdateLigatureSubstitutionRecordsMarker.End();
  2499. }
  2500. void AddLigatureSubstitutionRecords(UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[] records)
  2501. {
  2502. for (int i = 0; i < records.Length; i++)
  2503. {
  2504. UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord record = records[i];
  2505. if (records[i].componentGlyphIDs == null || records[i].ligatureGlyphID == 0)
  2506. return;
  2507. uint firstComponentGlyphIndex = record.componentGlyphIDs[0];
  2508. LigatureSubstitutionRecord newRecord = new LigatureSubstitutionRecord { componentGlyphIDs = record.componentGlyphIDs, ligatureGlyphID = record.ligatureGlyphID };
  2509. // Check if we already have a record for this new Ligature
  2510. if (m_FontFeatureTable.m_LigatureSubstitutionRecordLookup.TryGetValue(firstComponentGlyphIndex, out List<LigatureSubstitutionRecord> existingRecords))
  2511. {
  2512. foreach (LigatureSubstitutionRecord ligature in existingRecords)
  2513. {
  2514. if (newRecord == ligature)
  2515. return;
  2516. }
  2517. // Add new record to lookup
  2518. m_FontFeatureTable.m_LigatureSubstitutionRecordLookup[firstComponentGlyphIndex].Add(newRecord);
  2519. }
  2520. else
  2521. {
  2522. m_FontFeatureTable.m_LigatureSubstitutionRecordLookup.Add(firstComponentGlyphIndex, new List<LigatureSubstitutionRecord> { newRecord });
  2523. }
  2524. m_FontFeatureTable.m_LigatureSubstitutionRecords.Add(newRecord);
  2525. }
  2526. }
  2527. /// <summary>
  2528. ///
  2529. /// </summary>
  2530. internal void UpdateGlyphAdjustmentRecords()
  2531. {
  2532. k_UpdateGlyphAdjustmentRecordsMarker.Begin();
  2533. GlyphPairAdjustmentRecord[] records = FontEngine.GetPairAdjustmentRecords(m_GlyphIndexListNewlyAdded);
  2534. if (records != null)
  2535. AddPairAdjustmentRecords(records);
  2536. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2537. }
  2538. void AddPairAdjustmentRecords(GlyphPairAdjustmentRecord[] records)
  2539. {
  2540. float emScale = (float)m_FaceInfo.pointSize / m_FaceInfo.unitsPerEM;
  2541. for (int i = 0; i < records.Length; i++)
  2542. {
  2543. GlyphPairAdjustmentRecord record = records[i];
  2544. GlyphAdjustmentRecord first = record.firstAdjustmentRecord;
  2545. GlyphAdjustmentRecord second = record.secondAdjustmentRecord;
  2546. uint firstIndex = first.glyphIndex;
  2547. uint secondIndexIndex = second.glyphIndex;
  2548. if (firstIndex == 0 && secondIndexIndex == 0)
  2549. return;
  2550. uint key = secondIndexIndex << 16 | firstIndex;
  2551. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.ContainsKey(key))
  2552. continue;
  2553. // Adjust values currently in Units per EM to make them relative to Sampling Point Size.
  2554. GlyphValueRecord valueRecord = first.glyphValueRecord;
  2555. valueRecord.xAdvance *= emScale;
  2556. record.firstAdjustmentRecord = new GlyphAdjustmentRecord(firstIndex, valueRecord);
  2557. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2558. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.Add(key, record);
  2559. }
  2560. }
  2561. #else
  2562. /// <summary>
  2563. ///
  2564. /// </summary>
  2565. internal void UpdateGlyphAdjustmentRecords()
  2566. {
  2567. k_UpdateGlyphAdjustmentRecordsMarker.Begin();
  2568. // Get glyph pair adjustment records from font file.
  2569. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentRecords(m_GlyphIndexList, out int recordCount);
  2570. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  2571. {
  2572. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2573. return;
  2574. }
  2575. if (m_FontFeatureTable == null)
  2576. m_FontFeatureTable = new TMP_FontFeatureTable();
  2577. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  2578. {
  2579. uint pairKey = pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 16 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  2580. // Check if table already contains a pair adjustment record for this key.
  2581. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.ContainsKey(pairKey))
  2582. continue;
  2583. GlyphPairAdjustmentRecord record = pairAdjustmentRecords[i];
  2584. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2585. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.Add(pairKey, record);
  2586. }
  2587. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2588. }
  2589. #endif
  2590. /// <summary>
  2591. /// Function used for debugging and performance testing.
  2592. /// </summary>
  2593. /// <param name="glyphIndexes"></param>
  2594. internal void UpdateGlyphAdjustmentRecords(uint[] glyphIndexes)
  2595. {
  2596. k_UpdateGlyphAdjustmentRecordsMarker.Begin();
  2597. // Get glyph pair adjustment records from font file.
  2598. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(glyphIndexes);
  2599. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  2600. {
  2601. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2602. return;
  2603. }
  2604. if (m_FontFeatureTable == null)
  2605. m_FontFeatureTable = new TMP_FontFeatureTable();
  2606. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  2607. {
  2608. uint pairKey = pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 16 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  2609. // Check if table already contains a pair adjustment record for this key.
  2610. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.ContainsKey(pairKey))
  2611. continue;
  2612. GlyphPairAdjustmentRecord record = pairAdjustmentRecords[i];
  2613. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2614. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.Add(pairKey, record);
  2615. }
  2616. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2617. }
  2618. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2619. /// <summary>
  2620. ///
  2621. /// </summary>
  2622. internal void UpdateDiacriticalMarkAdjustmentRecords()
  2623. {
  2624. k_UpdateDiacriticalMarkAdjustmentRecordsMarker.Begin();
  2625. // Get Mark-to-Base adjustment records
  2626. UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord[] markToBaseRecords = FontEngine.GetMarkToBaseAdjustmentRecords(m_GlyphIndexListNewlyAdded);
  2627. if (markToBaseRecords != null)
  2628. AddMarkToBaseAdjustmentRecords(markToBaseRecords);
  2629. // Get Mark-to-Mark adjustment records
  2630. UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord[] markToMarkRecords = FontEngine.GetMarkToMarkAdjustmentRecords(m_GlyphIndexListNewlyAdded);
  2631. if (markToMarkRecords != null)
  2632. AddMarkToMarkAdjustmentRecords(markToMarkRecords);
  2633. k_UpdateDiacriticalMarkAdjustmentRecordsMarker.End();
  2634. }
  2635. /// <summary>
  2636. ///
  2637. /// </summary>
  2638. /// <param name="records"></param>
  2639. void AddMarkToBaseAdjustmentRecords(UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord[] records)
  2640. {
  2641. float emScale = (float)m_FaceInfo.pointSize / m_FaceInfo.unitsPerEM;
  2642. for (int i = 0; i < records.Length; i++)
  2643. {
  2644. UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord record = records[i];
  2645. if (records[i].baseGlyphID == 0 || records[i].markGlyphID == 0)
  2646. return;
  2647. uint key = record.markGlyphID << 16 | record.baseGlyphID;
  2648. if (m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.ContainsKey(key))
  2649. continue;
  2650. MarkToBaseAdjustmentRecord newRecord = new MarkToBaseAdjustmentRecord {
  2651. baseGlyphID = record.baseGlyphID,
  2652. baseGlyphAnchorPoint = new GlyphAnchorPoint() { xCoordinate = record.baseGlyphAnchorPoint.xCoordinate * emScale, yCoordinate = record.baseGlyphAnchorPoint.yCoordinate * emScale },
  2653. markGlyphID = record.markGlyphID,
  2654. markPositionAdjustment = new MarkPositionAdjustment(){ xPositionAdjustment = record.markPositionAdjustment.xPositionAdjustment * emScale, yPositionAdjustment = record.markPositionAdjustment.yPositionAdjustment * emScale} };
  2655. m_FontFeatureTable.MarkToBaseAdjustmentRecords.Add(newRecord);
  2656. m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.Add(key, newRecord);
  2657. }
  2658. }
  2659. /// <summary>
  2660. ///
  2661. /// </summary>
  2662. /// <param name="records"></param>
  2663. void AddMarkToMarkAdjustmentRecords(UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord[] records)
  2664. {
  2665. float emScale = (float)m_FaceInfo.pointSize / m_FaceInfo.unitsPerEM;
  2666. for (int i = 0; i < records.Length; i++)
  2667. {
  2668. UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord record = records[i];
  2669. if (records[i].baseMarkGlyphID == 0 || records[i].combiningMarkGlyphID == 0)
  2670. return;
  2671. uint key = record.combiningMarkGlyphID << 16 | record.baseMarkGlyphID;
  2672. if (m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.ContainsKey(key))
  2673. continue;
  2674. MarkToMarkAdjustmentRecord newRecord = new MarkToMarkAdjustmentRecord {
  2675. baseMarkGlyphID = record.baseMarkGlyphID,
  2676. baseMarkGlyphAnchorPoint = new GlyphAnchorPoint() { xCoordinate = record.baseMarkGlyphAnchorPoint.xCoordinate * emScale, yCoordinate = record.baseMarkGlyphAnchorPoint.yCoordinate * emScale},
  2677. combiningMarkGlyphID = record.combiningMarkGlyphID,
  2678. combiningMarkPositionAdjustment = new MarkPositionAdjustment(){ xPositionAdjustment = record.combiningMarkPositionAdjustment.xPositionAdjustment * emScale, yPositionAdjustment = record.combiningMarkPositionAdjustment.yPositionAdjustment * emScale} };
  2679. m_FontFeatureTable.MarkToMarkAdjustmentRecords.Add(newRecord);
  2680. m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.Add(key, newRecord);
  2681. }
  2682. }
  2683. #endif
  2684. /// <summary>
  2685. /// Internal method to copy generic list data to generic array of the same type.
  2686. /// </summary>
  2687. /// <param name="srcList">Source</param>
  2688. /// <param name="dstArray">Destination</param>
  2689. /// <typeparam name="T">Element type</typeparam>
  2690. void CopyListDataToArray<T>(List<T> srcList, ref T[] dstArray)
  2691. {
  2692. int size = srcList.Count;
  2693. // Make sure destination array is appropriately sized.
  2694. if (dstArray == null)
  2695. dstArray = new T[size];
  2696. else
  2697. Array.Resize(ref dstArray, size);
  2698. for (int i = 0; i < size; i++)
  2699. dstArray[i] = srcList[i];
  2700. }
  2701. /// <summary>
  2702. ///
  2703. /// </summary>
  2704. internal void UpdateFontAssetData()
  2705. {
  2706. k_UpdateFontAssetDataMarker.Begin();
  2707. // Get list of all characters currently contained in the font asset.
  2708. uint[] unicodeCharacters = new uint[m_CharacterTable.Count];
  2709. for (int i = 0; i < m_CharacterTable.Count; i++)
  2710. unicodeCharacters[i] = m_CharacterTable[i].unicode;
  2711. // Clear glyph, character
  2712. ClearCharacterAndGlyphTables();
  2713. // Clear font features
  2714. ClearFontFeaturesTables();
  2715. // Clear atlas textures
  2716. ClearAtlasTextures(true);
  2717. ReadFontAssetDefinition();
  2718. //TMP_ResourceManager.RebuildFontAssetCache();
  2719. // Add existing glyphs and characters back in the font asset (if any)
  2720. if (unicodeCharacters.Length > 0)
  2721. TryAddCharacters(unicodeCharacters, m_GetFontFeatures && TMP_Settings.getFontFeaturesAtRuntime);
  2722. k_UpdateFontAssetDataMarker.End();
  2723. }
  2724. /// <summary>
  2725. /// Clears font asset data including the glyph and character tables and textures.
  2726. /// Function might be changed to Internal and only used in tests.
  2727. /// </summary>
  2728. /// <param name="setAtlasSizeToZero">Will set the atlas texture size to zero width and height if true.</param>
  2729. public void ClearFontAssetData(bool setAtlasSizeToZero = false)
  2730. {
  2731. k_ClearFontAssetDataMarker.Begin();
  2732. #if UNITY_EDITOR
  2733. // Record full object undo in the Editor.
  2734. //UnityEditor.Undo.RecordObjects(new UnityEngine.Object[] { this, this.atlasTexture }, "Resetting Font Asset");
  2735. #endif
  2736. // Clear character and glyph tables
  2737. ClearCharacterAndGlyphTables();
  2738. // Clear font feature tables
  2739. ClearFontFeaturesTables();
  2740. // Clear atlas textures
  2741. ClearAtlasTextures(setAtlasSizeToZero);
  2742. ReadFontAssetDefinition();
  2743. //TMP_ResourceManager.RebuildFontAssetCache();
  2744. #if UNITY_EDITOR
  2745. // Makes the changes to the font asset persistent.
  2746. RegisterResourceForUpdate?.Invoke(this);
  2747. #endif
  2748. k_ClearFontAssetDataMarker.End();
  2749. }
  2750. /// <summary>
  2751. /// Clear character and glyph tables along with atlas textures.
  2752. /// </summary>
  2753. internal void ClearCharacterAndGlyphTablesInternal()
  2754. {
  2755. // Clear character and glyph tables
  2756. ClearCharacterAndGlyphTables();
  2757. // Clear atlas textures
  2758. ClearAtlasTextures(true);
  2759. ReadFontAssetDefinition();
  2760. //TMP_ResourceManager.RebuildFontAssetCache();
  2761. #if UNITY_EDITOR
  2762. // Makes the changes to the font asset persistent.
  2763. RegisterResourceForUpdate?.Invoke(this);
  2764. #endif
  2765. }
  2766. internal void ClearFontFeaturesInternal()
  2767. {
  2768. ClearFontFeaturesTables();
  2769. ReadFontAssetDefinition();
  2770. #if UNITY_EDITOR
  2771. // Makes the changes to the font asset persistent.
  2772. RegisterResourceForUpdate?.Invoke(this);
  2773. #endif
  2774. }
  2775. /// <summary>
  2776. /// Clear character and glyph tables.
  2777. /// </summary>
  2778. void ClearCharacterAndGlyphTables()
  2779. {
  2780. // Clear glyph and character tables
  2781. if (m_GlyphTable != null)
  2782. m_GlyphTable.Clear();
  2783. if (m_CharacterTable != null)
  2784. m_CharacterTable.Clear();
  2785. // Clear glyph rectangles
  2786. if (m_UsedGlyphRects != null)
  2787. m_UsedGlyphRects.Clear();
  2788. if (m_FreeGlyphRects != null)
  2789. {
  2790. int packingModifier = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  2791. m_FreeGlyphRects.Clear();
  2792. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  2793. }
  2794. if (m_GlyphsToRender != null)
  2795. m_GlyphsToRender.Clear();
  2796. if (m_GlyphsRendered != null)
  2797. m_GlyphsRendered.Clear();
  2798. }
  2799. /// <summary>
  2800. /// Clear OpenType font features
  2801. /// </summary>
  2802. void ClearFontFeaturesTables()
  2803. {
  2804. // Clear Ligature Table
  2805. if (m_FontFeatureTable != null && m_FontFeatureTable.m_LigatureSubstitutionRecords != null)
  2806. m_FontFeatureTable.m_LigatureSubstitutionRecords.Clear();
  2807. // Clear Glyph Adjustment Table
  2808. if (m_FontFeatureTable != null && m_FontFeatureTable.m_GlyphPairAdjustmentRecords != null)
  2809. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Clear();
  2810. // Clear Mark-to-Base Adjustment Table
  2811. if (m_FontFeatureTable != null && m_FontFeatureTable.m_MarkToBaseAdjustmentRecords != null)
  2812. m_FontFeatureTable.m_MarkToBaseAdjustmentRecords.Clear();
  2813. // Clear Mark-to-Mark Adjustment Table
  2814. if (m_FontFeatureTable != null && m_FontFeatureTable.m_MarkToMarkAdjustmentRecords != null)
  2815. m_FontFeatureTable.m_MarkToMarkAdjustmentRecords.Clear();
  2816. }
  2817. /// <summary>
  2818. /// Internal function to clear all atlas textures.
  2819. /// </summary>
  2820. /// <param name="setAtlasSizeToZero">Set main atlas texture size to zero if true.</param>
  2821. internal void ClearAtlasTextures(bool setAtlasSizeToZero = false)
  2822. {
  2823. m_AtlasTextureIndex = 0;
  2824. // Return if we don't have any atlas textures
  2825. if (m_AtlasTextures == null)
  2826. return;
  2827. Texture2D texture = null;
  2828. // Clear all additional atlas textures
  2829. for (int i = 1; i < m_AtlasTextures.Length; i++)
  2830. {
  2831. texture = m_AtlasTextures[i];
  2832. if (texture == null)
  2833. continue;
  2834. DestroyImmediate(texture, true);
  2835. #if UNITY_EDITOR
  2836. RegisterResourceForReimport?.Invoke(this);
  2837. #endif
  2838. }
  2839. // Resize atlas texture array down to one texture
  2840. Array.Resize(ref m_AtlasTextures, 1);
  2841. texture = m_AtlasTexture = m_AtlasTextures[0];
  2842. // Clear main atlas texture
  2843. if (texture.isReadable == false)
  2844. {
  2845. #if UNITY_EDITOR
  2846. SetAtlasTextureIsReadable?.Invoke(texture, true);
  2847. #endif
  2848. }
  2849. #if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
  2850. TextureFormat texFormat = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_COLOR) == GlyphRasterModes.RASTER_MODE_COLOR ? TextureFormat.RGBA32 : TextureFormat.Alpha8;
  2851. #else
  2852. TextureFormat texFormat = TextureFormat.Alpha8;
  2853. #endif
  2854. if (setAtlasSizeToZero)
  2855. {
  2856. #if UNITY_2021_2_OR_NEWER
  2857. texture.Reinitialize(1, 1, texFormat, false);
  2858. #else
  2859. texture.Resize(0, 0, texFormat, false);
  2860. #endif
  2861. }
  2862. else if (texture.width != m_AtlasWidth || texture.height != m_AtlasHeight)
  2863. {
  2864. #if UNITY_2021_2_OR_NEWER
  2865. texture.Reinitialize(m_AtlasWidth, m_AtlasHeight, texFormat, false);
  2866. #else
  2867. texture.Resize(m_AtlasWidth, m_AtlasHeight, texFormat, false);
  2868. #endif
  2869. }
  2870. // Clear texture atlas
  2871. FontEngine.ResetAtlasTexture(texture);
  2872. texture.Apply();
  2873. }
  2874. void DestroyAtlasTextures()
  2875. {
  2876. if (m_AtlasTextures == null)
  2877. return;
  2878. for (int i = 0; i < m_AtlasTextures.Length; i++)
  2879. {
  2880. Texture2D tex = m_AtlasTextures[i];
  2881. if (tex != null)
  2882. DestroyImmediate(tex);
  2883. }
  2884. }
  2885. #if UNITY_EDITOR
  2886. /// <summary>
  2887. /// Internal method used to upgrade font asset to support Dynamic SDF.
  2888. /// </summary>
  2889. internal void UpgradeFontAsset()
  2890. {
  2891. m_Version = "1.1.0";
  2892. Debug.Log("Upgrading font asset [" + this.name + "] to version " + m_Version + ".", this);
  2893. m_FaceInfo.familyName = m_fontInfo.Name;
  2894. m_FaceInfo.styleName = string.Empty;
  2895. m_FaceInfo.pointSize = (int)m_fontInfo.PointSize;
  2896. m_FaceInfo.scale = m_fontInfo.Scale;
  2897. m_FaceInfo.lineHeight = m_fontInfo.LineHeight;
  2898. m_FaceInfo.ascentLine = m_fontInfo.Ascender;
  2899. m_FaceInfo.capLine = m_fontInfo.CapHeight;
  2900. m_FaceInfo.meanLine = m_fontInfo.CenterLine;
  2901. m_FaceInfo.baseline = m_fontInfo.Baseline;
  2902. m_FaceInfo.descentLine = m_fontInfo.Descender;
  2903. m_FaceInfo.superscriptOffset = m_fontInfo.SuperscriptOffset;
  2904. m_FaceInfo.superscriptSize = m_fontInfo.SubSize;
  2905. m_FaceInfo.subscriptOffset = m_fontInfo.SubscriptOffset;
  2906. m_FaceInfo.subscriptSize = m_fontInfo.SubSize;
  2907. m_FaceInfo.underlineOffset = m_fontInfo.Underline;
  2908. m_FaceInfo.underlineThickness = m_fontInfo.UnderlineThickness;
  2909. m_FaceInfo.strikethroughOffset = m_fontInfo.strikethrough;
  2910. m_FaceInfo.strikethroughThickness = m_fontInfo.strikethroughThickness;
  2911. m_FaceInfo.tabWidth = m_fontInfo.TabWidth;
  2912. if (m_AtlasTextures == null || m_AtlasTextures.Length == 0)
  2913. m_AtlasTextures = new Texture2D[1];
  2914. m_AtlasTextures[0] = atlas;
  2915. //atlas = null;
  2916. m_AtlasWidth = (int)m_fontInfo.AtlasWidth;
  2917. m_AtlasHeight = (int)m_fontInfo.AtlasHeight;
  2918. m_AtlasPadding = (int)m_fontInfo.Padding;
  2919. switch(m_CreationSettings.renderMode)
  2920. {
  2921. case 0:
  2922. m_AtlasRenderMode = GlyphRenderMode.SMOOTH_HINTED;
  2923. break;
  2924. case 1:
  2925. m_AtlasRenderMode = GlyphRenderMode.SMOOTH;
  2926. break;
  2927. case 2:
  2928. m_AtlasRenderMode = GlyphRenderMode.RASTER_HINTED;
  2929. break;
  2930. case 3:
  2931. m_AtlasRenderMode = GlyphRenderMode.RASTER;
  2932. break;
  2933. case 6:
  2934. m_AtlasRenderMode = GlyphRenderMode.SDF16;
  2935. break;
  2936. case 7:
  2937. m_AtlasRenderMode = GlyphRenderMode.SDF32;
  2938. break;
  2939. }
  2940. //m_fontInfo = null;
  2941. // Convert font weight table
  2942. if (fontWeights != null && fontWeights.Length > 0)
  2943. {
  2944. m_FontWeightTable[4] = fontWeights[4];
  2945. m_FontWeightTable[7] = fontWeights[7];
  2946. // Clear old fontWeight
  2947. //fontWeights = null;
  2948. }
  2949. // Convert font fallbacks
  2950. if (fallbackFontAssets != null && fallbackFontAssets.Count > 0)
  2951. {
  2952. if (m_FallbackFontAssetTable == null)
  2953. m_FallbackFontAssetTable = new List<TMP_FontAsset>(fallbackFontAssets.Count);
  2954. for (int i = 0; i < fallbackFontAssets.Count; i++)
  2955. m_FallbackFontAssetTable.Add(fallbackFontAssets[i]);
  2956. // Clear old fallbackFontAssets list
  2957. //fallbackFontAssets = null;
  2958. }
  2959. // Check if font asset creation settings contains a reference to the source font file GUID
  2960. if (m_CreationSettings.sourceFontFileGUID != null || m_CreationSettings.sourceFontFileGUID != string.Empty)
  2961. {
  2962. m_SourceFontFileGUID = m_CreationSettings.sourceFontFileGUID;
  2963. }
  2964. else
  2965. {
  2966. 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);
  2967. }
  2968. // Convert legacy glyph and character tables to new format
  2969. m_GlyphTable.Clear();
  2970. m_CharacterTable.Clear();
  2971. bool isSpaceCharacterPresent = false;
  2972. for (int i = 0; i < m_glyphInfoList.Count; i++)
  2973. {
  2974. TMP_Glyph oldGlyph = m_glyphInfoList[i];
  2975. Glyph glyph = new Glyph();
  2976. uint glyphIndex = (uint)i + 1;
  2977. glyph.index = glyphIndex;
  2978. 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));
  2979. glyph.metrics = new GlyphMetrics(oldGlyph.width, oldGlyph.height, oldGlyph.xOffset, oldGlyph.yOffset, oldGlyph.xAdvance);
  2980. glyph.scale = oldGlyph.scale;
  2981. glyph.atlasIndex = 0;
  2982. m_GlyphTable.Add(glyph);
  2983. TMP_Character character = new TMP_Character((uint)oldGlyph.id, this, glyph);
  2984. if (oldGlyph.id == 32)
  2985. isSpaceCharacterPresent = true;
  2986. m_CharacterTable.Add(character);
  2987. }
  2988. // Special handling for the synthesized space character
  2989. if (!isSpaceCharacterPresent)
  2990. {
  2991. Debug.Log("Synthesizing Space for [" + this.name + "]");
  2992. Glyph glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, m_FaceInfo.ascentLine / 5), GlyphRect.zero, 1.0f, 0);
  2993. m_GlyphTable.Add(glyph);
  2994. m_CharacterTable.Add(new TMP_Character(32, this, glyph));
  2995. }
  2996. // Clear legacy glyph info list.
  2997. //m_glyphInfoList.Clear();
  2998. ReadFontAssetDefinition();
  2999. // Convert atlas textures data to new format
  3000. // TODO
  3001. // Makes the changes to the font asset persistent.
  3002. RegisterResourceForUpdate?.Invoke(this);
  3003. }
  3004. #endif
  3005. /// <summary>
  3006. ///
  3007. /// </summary>
  3008. void UpgradeGlyphAdjustmentTableToFontFeatureTable()
  3009. {
  3010. Debug.Log("Upgrading font asset [" + this.name + "] Glyph Adjustment Table.", this);
  3011. if (m_FontFeatureTable == null)
  3012. m_FontFeatureTable = new TMP_FontFeatureTable();
  3013. int pairCount = m_KerningTable.kerningPairs.Count;
  3014. m_FontFeatureTable.m_GlyphPairAdjustmentRecords = new List<GlyphPairAdjustmentRecord>(pairCount);
  3015. for (int i = 0; i < pairCount; i++)
  3016. {
  3017. KerningPair pair = m_KerningTable.kerningPairs[i];
  3018. uint firstGlyphIndex = 0;
  3019. TMP_Character firstCharacter;
  3020. if (m_CharacterLookupDictionary.TryGetValue(pair.firstGlyph, out firstCharacter))
  3021. firstGlyphIndex = firstCharacter.glyphIndex;
  3022. uint secondGlyphIndex = 0;
  3023. TMP_Character secondCharacter;
  3024. if (m_CharacterLookupDictionary.TryGetValue(pair.secondGlyph, out secondCharacter))
  3025. secondGlyphIndex = secondCharacter.glyphIndex;
  3026. GlyphAdjustmentRecord firstAdjustmentRecord = new GlyphAdjustmentRecord(firstGlyphIndex, new GlyphValueRecord(pair.firstGlyphAdjustments.xPlacement, pair.firstGlyphAdjustments.yPlacement, pair.firstGlyphAdjustments.xAdvance, pair.firstGlyphAdjustments.yAdvance));
  3027. GlyphAdjustmentRecord secondAdjustmentRecord = new GlyphAdjustmentRecord(secondGlyphIndex, new GlyphValueRecord(pair.secondGlyphAdjustments.xPlacement, pair.secondGlyphAdjustments.yPlacement, pair.secondGlyphAdjustments.xAdvance, pair.secondGlyphAdjustments.yAdvance));
  3028. GlyphPairAdjustmentRecord record = new GlyphPairAdjustmentRecord(firstAdjustmentRecord, secondAdjustmentRecord);
  3029. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  3030. }
  3031. // TODO: Should clear legacy kerning table.
  3032. m_KerningTable.kerningPairs = null;
  3033. m_KerningTable = null;
  3034. #if UNITY_EDITOR
  3035. // Makes the changes to the font asset persistent.
  3036. RegisterResourceForUpdate?.Invoke(this);
  3037. #endif
  3038. }
  3039. }
  3040. }