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

TMPro_UGUI_Private.cs 242KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677
  1. using System;
  2. using Unity.Profiling;
  3. using UnityEngine;
  4. using UnityEngine.TextCore;
  5. using UnityEngine.UI;
  6. using Object = UnityEngine.Object;
  7. #pragma warning disable 0414 // Disabled a few warnings related to serialized variables not used in this script but used in the editor.
  8. #pragma warning disable 0618 // Disabled warning due to SetVertices being deprecated until new release with SetMesh() is available.
  9. namespace TMPro
  10. {
  11. public partial class TextMeshProUGUI
  12. {
  13. [SerializeField]
  14. private bool m_hasFontAssetChanged = false; // Used to track when font properties have changed.
  15. protected TMP_SubMeshUI[] m_subTextObjects = new TMP_SubMeshUI[8];
  16. private float m_previousLossyScaleY = -1; // Used for Tracking lossy scale changes in the transform;
  17. private Vector3[] m_RectTransformCorners = new Vector3[4];
  18. private CanvasRenderer m_canvasRenderer;
  19. private Canvas m_canvas;
  20. private float m_CanvasScaleFactor;
  21. private bool m_isFirstAllocation; // Flag to determine if this is the first allocation of the buffers.
  22. private int m_max_characters = 8; // Determines the initial allocation and size of the character array / buffer.
  23. //private int m_max_numberOfLines = 4; // Determines the initial allocation and maximum number of lines of text.
  24. // MASKING RELATED PROPERTIES
  25. // This property is now obsolete and used for compatibility with previous releases (prior to release 0.1.54).
  26. [SerializeField]
  27. private Material m_baseMaterial;
  28. private bool m_isScrollRegionSet;
  29. //private Mask m_mask;
  30. [SerializeField]
  31. private Vector4 m_maskOffset;
  32. // Matrix used to animated Env Map
  33. private Matrix4x4 m_EnvMapMatrix = new Matrix4x4();
  34. //private bool m_isEnabled;
  35. [NonSerialized]
  36. private bool m_isRegisteredForEvents;
  37. // Profiler Marker declarations
  38. private static ProfilerMarker k_GenerateTextMarker = new ProfilerMarker("TMP.GenerateText");
  39. private static ProfilerMarker k_SetArraySizesMarker = new ProfilerMarker("TMP.SetArraySizes");
  40. private static ProfilerMarker k_GenerateTextPhaseIMarker = new ProfilerMarker("TMP GenerateText - Phase I");
  41. private static ProfilerMarker k_ParseMarkupTextMarker = new ProfilerMarker("TMP Parse Markup Text");
  42. private static ProfilerMarker k_CharacterLookupMarker = new ProfilerMarker("TMP Lookup Character & Glyph Data");
  43. private static ProfilerMarker k_HandleGPOSFeaturesMarker = new ProfilerMarker("TMP Handle GPOS Features");
  44. private static ProfilerMarker k_CalculateVerticesPositionMarker = new ProfilerMarker("TMP Calculate Vertices Position");
  45. private static ProfilerMarker k_ComputeTextMetricsMarker = new ProfilerMarker("TMP Compute Text Metrics");
  46. private static ProfilerMarker k_HandleVisibleCharacterMarker = new ProfilerMarker("TMP Handle Visible Character");
  47. private static ProfilerMarker k_HandleWhiteSpacesMarker = new ProfilerMarker("TMP Handle White Space & Control Character");
  48. private static ProfilerMarker k_HandleHorizontalLineBreakingMarker = new ProfilerMarker("TMP Handle Horizontal Line Breaking");
  49. private static ProfilerMarker k_HandleVerticalLineBreakingMarker = new ProfilerMarker("TMP Handle Vertical Line Breaking");
  50. private static ProfilerMarker k_SaveGlyphVertexDataMarker = new ProfilerMarker("TMP Save Glyph Vertex Data");
  51. private static ProfilerMarker k_ComputeCharacterAdvanceMarker = new ProfilerMarker("TMP Compute Character Advance");
  52. private static ProfilerMarker k_HandleCarriageReturnMarker = new ProfilerMarker("TMP Handle Carriage Return");
  53. private static ProfilerMarker k_HandleLineTerminationMarker = new ProfilerMarker("TMP Handle Line Termination");
  54. private static ProfilerMarker k_SavePageInfoMarker = new ProfilerMarker("TMP Save Text Extent & Page Info");
  55. private static ProfilerMarker k_SaveProcessingStatesMarker = new ProfilerMarker("TMP Save Processing States");
  56. private static ProfilerMarker k_GenerateTextPhaseIIMarker = new ProfilerMarker("TMP GenerateText - Phase II");
  57. private static ProfilerMarker k_GenerateTextPhaseIIIMarker = new ProfilerMarker("TMP GenerateText - Phase III");
  58. protected override void Awake()
  59. {
  60. //Debug.Log("***** Awake() called on object ID " + GetInstanceID() + ". *****");
  61. #if UNITY_EDITOR
  62. // Special handling for TMP Settings and importing Essential Resources
  63. if (TMP_Settings.instance == null)
  64. {
  65. if (m_isWaitingOnResourceLoad == false)
  66. TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
  67. m_isWaitingOnResourceLoad = true;
  68. return;
  69. }
  70. #endif
  71. // Cache Reference to the Canvas
  72. m_canvas = this.canvas;
  73. m_isOrthographic = true;
  74. // Cache Reference to RectTransform.
  75. m_rectTransform = gameObject.GetComponent<RectTransform>();
  76. if (m_rectTransform == null)
  77. m_rectTransform = gameObject.AddComponent<RectTransform>();
  78. // Cache a reference to the CanvasRenderer.
  79. m_canvasRenderer = GetComponent<CanvasRenderer>();
  80. if (m_canvasRenderer == null)
  81. m_canvasRenderer = gameObject.AddComponent<CanvasRenderer> ();
  82. if (m_mesh == null)
  83. {
  84. m_mesh = new Mesh();
  85. m_mesh.hideFlags = HideFlags.HideAndDontSave;
  86. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  87. m_mesh.name = "TextMeshPro UI Mesh";
  88. #endif
  89. // Create new TextInfo for the text object.
  90. m_textInfo = new TMP_TextInfo(this);
  91. }
  92. // Load TMP Settings for new text object instances.
  93. LoadDefaultSettings();
  94. // Load the font asset and assign material to renderer.
  95. LoadFontAsset();
  96. // Allocate our initial buffers.
  97. if (m_TextProcessingArray == null)
  98. m_TextProcessingArray = new UnicodeChar[m_max_characters];
  99. m_cached_TextElement = new TMP_Character();
  100. m_isFirstAllocation = true;
  101. // Check to make sure Sub Text Objects are tracked correctly in the event a Prefab is used.
  102. TMP_SubMeshUI[] subTextObjects = GetComponentsInChildren<TMP_SubMeshUI>();
  103. if (subTextObjects.Length > 0)
  104. {
  105. int subTextObjectCount = subTextObjects.Length;
  106. if (subTextObjectCount + 1 > m_subTextObjects.Length)
  107. Array.Resize(ref m_subTextObjects, subTextObjectCount + 1);
  108. for (int i = 0; i < subTextObjectCount; i++)
  109. m_subTextObjects[i + 1] = subTextObjects[i];
  110. }
  111. // Set flags to ensure our text is parsed and redrawn.
  112. m_havePropertiesChanged = true;
  113. m_isAwake = true;
  114. }
  115. protected override void OnEnable()
  116. {
  117. //Debug.Log("***** OnEnable() called on object ID " + GetInstanceID() + ". *****");
  118. // Return if Awake() has not been called on the text object.
  119. if (m_isAwake == false)
  120. return;
  121. if (!m_isRegisteredForEvents)
  122. {
  123. //Debug.Log("Registering for Events.");
  124. #if UNITY_EDITOR
  125. // Register Callbacks for various events.
  126. TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Add(ON_MATERIAL_PROPERTY_CHANGED);
  127. TMPro_EventManager.FONT_PROPERTY_EVENT.Add(ON_FONT_PROPERTY_CHANGED);
  128. TMPro_EventManager.TEXTMESHPRO_UGUI_PROPERTY_EVENT.Add(ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED);
  129. TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Add(ON_DRAG_AND_DROP_MATERIAL);
  130. TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Add(ON_TEXT_STYLE_CHANGED);
  131. TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Add(ON_COLOR_GRADIENT_CHANGED);
  132. TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Add(ON_TMP_SETTINGS_CHANGED);
  133. UnityEditor.PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdate;
  134. #endif
  135. m_isRegisteredForEvents = true;
  136. }
  137. // Cache Reference to the Canvas
  138. m_canvas = GetCanvas();
  139. SetActiveSubMeshes(true);
  140. // Register Graphic Component to receive event triggers
  141. GraphicRegistry.RegisterGraphicForCanvas(m_canvas, this);
  142. // Register text object for internal updates
  143. if (m_IsTextObjectScaleStatic == false)
  144. TMP_UpdateManager.RegisterTextObjectForUpdate(this);
  145. ComputeMarginSize();
  146. SetAllDirty();
  147. RecalculateClipping();
  148. RecalculateMasking();
  149. }
  150. protected override void OnDisable()
  151. {
  152. //Debug.Log("***** OnDisable() called on object ID " + GetInstanceID() + ". *****");
  153. // Return if Awake() has not been called on the text object.
  154. if (m_isAwake == false)
  155. return;
  156. //if (m_MaskMaterial != null)
  157. //{
  158. // TMP_MaterialManager.ReleaseStencilMaterial(m_MaskMaterial);
  159. // m_MaskMaterial = null;
  160. //}
  161. // UnRegister Graphic Component
  162. GraphicRegistry.UnregisterGraphicForCanvas(m_canvas, this);
  163. CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild((ICanvasElement)this);
  164. TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
  165. if (m_canvasRenderer != null)
  166. m_canvasRenderer.Clear();
  167. SetActiveSubMeshes(false);
  168. LayoutRebuilder.MarkLayoutForRebuild(m_rectTransform);
  169. RecalculateClipping();
  170. RecalculateMasking();
  171. }
  172. protected override void OnDestroy()
  173. {
  174. //Debug.Log("***** OnDestroy() called on object ID " + GetInstanceID() + ". *****");
  175. // UnRegister Graphic Component
  176. GraphicRegistry.UnregisterGraphicForCanvas(m_canvas, this);
  177. TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
  178. // Clean up remaining mesh
  179. if (m_mesh != null)
  180. DestroyImmediate(m_mesh);
  181. // Clean up mask material
  182. if (m_MaskMaterial != null)
  183. {
  184. TMP_MaterialManager.ReleaseStencilMaterial(m_MaskMaterial);
  185. m_MaskMaterial = null;
  186. }
  187. #if UNITY_EDITOR
  188. // Unregister the event this object was listening to
  189. TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Remove(ON_MATERIAL_PROPERTY_CHANGED);
  190. TMPro_EventManager.FONT_PROPERTY_EVENT.Remove(ON_FONT_PROPERTY_CHANGED);
  191. TMPro_EventManager.TEXTMESHPRO_UGUI_PROPERTY_EVENT.Remove(ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED);
  192. TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Remove(ON_DRAG_AND_DROP_MATERIAL);
  193. TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Remove(ON_TEXT_STYLE_CHANGED);
  194. TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Remove(ON_COLOR_GRADIENT_CHANGED);
  195. TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Remove(ON_TMP_SETTINGS_CHANGED);
  196. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  197. UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdate;
  198. #endif
  199. m_isRegisteredForEvents = false;
  200. }
  201. #if UNITY_EDITOR
  202. protected override void Reset()
  203. {
  204. //Debug.Log("***** Reset() *****"); //has been called.");
  205. // Return if Awake() has not been called on the text object.
  206. if (m_isAwake == false)
  207. return;
  208. LoadDefaultSettings();
  209. LoadFontAsset();
  210. m_havePropertiesChanged = true;
  211. }
  212. protected override void OnValidate()
  213. {
  214. //Debug.Log("***** OnValidate() ***** Frame:" + Time.frameCount); // ID " + GetInstanceID()); // New Material [" + m_sharedMaterial.name + "] with ID " + m_sharedMaterial.GetInstanceID() + ". Base Material is [" + m_baseMaterial.name + "] with ID " + m_baseMaterial.GetInstanceID() + ". Previous Base Material is [" + (m_lastBaseMaterial == null ? "Null" : m_lastBaseMaterial.name) + "].");
  215. if (m_isAwake == false)
  216. return;
  217. // Handle Font Asset changes in the inspector.
  218. if (m_fontAsset == null || m_hasFontAssetChanged)
  219. {
  220. LoadFontAsset();
  221. m_hasFontAssetChanged = false;
  222. }
  223. if (m_canvasRenderer == null || m_canvasRenderer.GetMaterial() == null || m_canvasRenderer.GetMaterial().GetTexture(ShaderUtilities.ID_MainTex) == null || m_fontAsset == null || m_fontAsset.atlasTexture.GetInstanceID() != m_canvasRenderer.GetMaterial().GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  224. {
  225. LoadFontAsset();
  226. m_hasFontAssetChanged = false;
  227. }
  228. m_padding = GetPaddingForMaterial();
  229. ComputeMarginSize();
  230. m_inputSource = TextInputSources.TextInputBox;
  231. m_havePropertiesChanged = true;
  232. m_isPreferredWidthDirty = true;
  233. m_isPreferredHeightDirty = true;
  234. SetAllDirty();
  235. }
  236. /// <summary>
  237. /// Callback received when Prefabs are updated.
  238. /// </summary>
  239. /// <param name="go">The affected GameObject</param>
  240. void OnPrefabInstanceUpdate(GameObject go)
  241. {
  242. // Remove Callback if this prefab has been deleted.
  243. if (this == null)
  244. {
  245. UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdate;
  246. return;
  247. }
  248. if (go == this.gameObject)
  249. {
  250. TMP_SubMeshUI[] subTextObjects = GetComponentsInChildren<TMP_SubMeshUI>();
  251. if (subTextObjects.Length > 0)
  252. {
  253. for (int i = 0; i < subTextObjects.Length; i++)
  254. m_subTextObjects[i + 1] = subTextObjects[i];
  255. }
  256. }
  257. }
  258. // Event received when TMP resources have been loaded.
  259. void ON_RESOURCES_LOADED()
  260. {
  261. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  262. if (this == null)
  263. return;
  264. m_isWaitingOnResourceLoad = false;
  265. Awake();
  266. OnEnable();
  267. }
  268. // Event received when custom material editor properties are changed.
  269. void ON_MATERIAL_PROPERTY_CHANGED(bool isChanged, Material mat)
  270. {
  271. //Debug.Log("ON_MATERIAL_PROPERTY_CHANGED event received."); // Targeted Material is: " + mat.name + " m_sharedMaterial: " + m_sharedMaterial.name + " with ID:" + m_sharedMaterial.GetInstanceID() + " m_renderer.sharedMaterial: " + m_canvasRenderer.GetMaterial() + " Masking Material:" + m_MaskMaterial.GetInstanceID());
  272. ShaderUtilities.GetShaderPropertyIDs(); // Initialize ShaderUtilities and get shader property IDs.
  273. int materialID = mat.GetInstanceID();
  274. int sharedMaterialID = m_sharedMaterial.GetInstanceID();
  275. int maskingMaterialID = m_MaskMaterial == null ? 0 : m_MaskMaterial.GetInstanceID();
  276. if (m_canvasRenderer == null || m_canvasRenderer.GetMaterial() == null)
  277. {
  278. if (m_canvasRenderer == null) return;
  279. if (m_fontAsset != null)
  280. {
  281. m_canvasRenderer.SetMaterial(m_fontAsset.material, m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex));
  282. //Debug.LogWarning("No Material was assigned to " + name + ". " + m_fontAsset.material.name + " was assigned.");
  283. }
  284. else
  285. Debug.LogWarning("No Font Asset assigned to " + name + ". Please assign a Font Asset.", this);
  286. }
  287. if (m_canvasRenderer.GetMaterial() != m_sharedMaterial && m_fontAsset == null) // || m_renderer.sharedMaterials.Contains(mat))
  288. {
  289. //Debug.Log("ON_MATERIAL_PROPERTY_CHANGED Called on Target ID: " + GetInstanceID() + ". Previous Material:" + m_sharedMaterial + " New Material:" + m_uiRenderer.GetMaterial()); // on Object ID:" + GetInstanceID() + ". m_sharedMaterial: " + m_sharedMaterial.name + " m_renderer.sharedMaterial: " + m_renderer.sharedMaterial.name);
  290. m_sharedMaterial = m_canvasRenderer.GetMaterial();
  291. }
  292. // Make sure material properties are synchronized between the assigned material and masking material.
  293. if (m_MaskMaterial != null)
  294. {
  295. UnityEditor.Undo.RecordObject(m_MaskMaterial, "Material Property Changes");
  296. UnityEditor.Undo.RecordObject(m_sharedMaterial, "Material Property Changes");
  297. if (materialID == sharedMaterialID)
  298. {
  299. //Debug.Log("Copy base material properties to masking material if not null.");
  300. float stencilID = m_MaskMaterial.GetFloat(ShaderUtilities.ID_StencilID);
  301. float stencilComp = m_MaskMaterial.GetFloat(ShaderUtilities.ID_StencilComp);
  302. //float stencilOp = m_MaskMaterial.GetFloat(ShaderUtilities.ID_StencilOp);
  303. //float stencilRead = m_MaskMaterial.GetFloat(ShaderUtilities.ID_StencilReadMask);
  304. //float stencilWrite = m_MaskMaterial.GetFloat(ShaderUtilities.ID_StencilWriteMask);
  305. m_MaskMaterial.CopyPropertiesFromMaterial(mat);
  306. m_MaskMaterial.shaderKeywords = mat.shaderKeywords;
  307. m_MaskMaterial.SetFloat(ShaderUtilities.ID_StencilID, stencilID);
  308. m_MaskMaterial.SetFloat(ShaderUtilities.ID_StencilComp, stencilComp);
  309. //m_MaskMaterial.SetFloat(ShaderUtilities.ID_StencilOp, stencilOp);
  310. //m_MaskMaterial.SetFloat(ShaderUtilities.ID_StencilReadMask, stencilID);
  311. //m_MaskMaterial.SetFloat(ShaderUtilities.ID_StencilWriteMask, 0);
  312. }
  313. else if (materialID == maskingMaterialID)
  314. {
  315. // Update the padding
  316. GetPaddingForMaterial(mat);
  317. m_sharedMaterial.CopyPropertiesFromMaterial(mat);
  318. m_sharedMaterial.shaderKeywords = mat.shaderKeywords;
  319. m_sharedMaterial.SetFloat(ShaderUtilities.ID_StencilID, 0);
  320. m_sharedMaterial.SetFloat(ShaderUtilities.ID_StencilComp, 8);
  321. //m_sharedMaterial.SetFloat(ShaderUtilities.ID_StencilOp, 0);
  322. //m_sharedMaterial.SetFloat(ShaderUtilities.ID_StencilReadMask, 255);
  323. //m_sharedMaterial.SetFloat(ShaderUtilities.ID_StencilWriteMask, 255);
  324. }
  325. }
  326. m_padding = GetPaddingForMaterial();
  327. m_havePropertiesChanged = true;
  328. SetVerticesDirty();
  329. //SetMaterialDirty();
  330. }
  331. // Event received when font asset properties are changed in Font Inspector
  332. void ON_FONT_PROPERTY_CHANGED(bool isChanged, Object font)
  333. {
  334. if (MaterialReference.Contains(m_materialReferences, (TMP_FontAsset) font))
  335. {
  336. //Debug.Log("ON_FONT_PROPERTY_CHANGED event received.");
  337. m_havePropertiesChanged = true;
  338. UpdateMeshPadding();
  339. SetLayoutDirty();
  340. SetVerticesDirty();
  341. }
  342. }
  343. // Event received when UNDO / REDO Event alters the properties of the object.
  344. void ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED(bool isChanged, Object obj)
  345. {
  346. //Debug.Log("Event Received by " + obj);
  347. if (obj == this)
  348. {
  349. //Debug.Log("Undo / Redo Event Received by Object ID:" + GetInstanceID());
  350. m_havePropertiesChanged = true;
  351. ComputeMarginSize(); // Review this change
  352. SetVerticesDirty();
  353. }
  354. }
  355. // Event to Track Material Changed resulting from Drag-n-drop.
  356. void ON_DRAG_AND_DROP_MATERIAL(GameObject obj, Material currentMaterial, Material newMaterial)
  357. {
  358. //Debug.Log("Drag-n-Drop Event - Receiving Object ID " + GetInstanceID() + ". Sender ID " + obj.GetInstanceID()); // + ". Prefab Parent is " + UnityEditor.PrefabUtility.GetPrefabParent(gameObject).GetInstanceID()); // + ". New Material is " + newMaterial.name + " with ID " + newMaterial.GetInstanceID() + ". Base Material is " + m_baseMaterial.name + " with ID " + m_baseMaterial.GetInstanceID());
  359. // Check if event applies to this current object
  360. #if UNITY_2018_2_OR_NEWER
  361. if (obj == gameObject || UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) == obj)
  362. #else
  363. if (obj == gameObject || UnityEditor.PrefabUtility.GetPrefabParent(gameObject) == obj)
  364. #endif
  365. {
  366. UnityEditor.Undo.RecordObject(this, "Material Assignment");
  367. UnityEditor.Undo.RecordObject(m_canvasRenderer, "Material Assignment");
  368. m_sharedMaterial = newMaterial;
  369. m_padding = GetPaddingForMaterial();
  370. m_havePropertiesChanged = true;
  371. SetVerticesDirty();
  372. SetMaterialDirty();
  373. }
  374. }
  375. // Event received when Text Styles are changed.
  376. void ON_TEXT_STYLE_CHANGED(bool isChanged)
  377. {
  378. m_havePropertiesChanged = true;
  379. SetVerticesDirty();
  380. }
  381. /// <summary>
  382. /// Event received when a Color Gradient Preset is modified.
  383. /// </summary>
  384. /// <param name="textObject"></param>
  385. void ON_COLOR_GRADIENT_CHANGED(Object gradient)
  386. {
  387. m_havePropertiesChanged = true;
  388. SetVerticesDirty();
  389. }
  390. /// <summary>
  391. /// Event received when the TMP Settings are changed.
  392. /// </summary>
  393. void ON_TMP_SETTINGS_CHANGED()
  394. {
  395. m_defaultSpriteAsset = null;
  396. m_havePropertiesChanged = true;
  397. SetAllDirty();
  398. }
  399. #endif
  400. // Function which loads either the default font or a newly assigned font asset. This function also assigned the appropriate material to the renderer.
  401. protected override void LoadFontAsset()
  402. {
  403. //Debug.Log("***** LoadFontAsset() *****"); //TextMeshPro LoadFontAsset() has been called."); // Current Font Asset is " + (font != null ? font.name: "Null") );
  404. ShaderUtilities.GetShaderPropertyIDs(); // Initialize & Get shader property IDs.
  405. if (m_fontAsset == null)
  406. {
  407. if (TMP_Settings.defaultFontAsset != null)
  408. m_fontAsset = TMP_Settings.defaultFontAsset;
  409. else
  410. m_fontAsset = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
  411. if (m_fontAsset == null)
  412. {
  413. Debug.LogWarning("The LiberationSans SDF Font Asset was not found. There is no Font Asset assigned to " + gameObject.name + ".", this);
  414. return;
  415. }
  416. if (m_fontAsset.characterLookupTable == null)
  417. {
  418. Debug.Log("Dictionary is Null!");
  419. }
  420. m_sharedMaterial = m_fontAsset.material;
  421. }
  422. else
  423. {
  424. // Read font definition if needed.
  425. if (m_fontAsset.characterLookupTable == null)
  426. m_fontAsset.ReadFontAssetDefinition();
  427. // Added for compatibility with previous releases.
  428. if (m_sharedMaterial == null && m_baseMaterial != null)
  429. {
  430. m_sharedMaterial = m_baseMaterial;
  431. m_baseMaterial = null;
  432. }
  433. // If font atlas texture doesn't match the assigned material font atlas, switch back to default material specified in the Font Asset.
  434. if (m_sharedMaterial == null || m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex) == null || m_fontAsset.atlasTexture.GetInstanceID() != m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  435. {
  436. if (m_fontAsset.material == null)
  437. Debug.LogWarning("The Font Atlas Texture of the Font Asset " + m_fontAsset.name + " assigned to " + gameObject.name + " is missing.", this);
  438. else
  439. m_sharedMaterial = m_fontAsset.material;
  440. }
  441. }
  442. // Find and cache Underline & Ellipsis characters.
  443. GetSpecialCharacters(m_fontAsset);
  444. m_padding = GetPaddingForMaterial();
  445. SetMaterialDirty();
  446. }
  447. /// <summary>
  448. /// Method to retrieve the parent Canvas.
  449. /// </summary>
  450. private Canvas GetCanvas()
  451. {
  452. Canvas canvas = null;
  453. var list = TMP_ListPool<Canvas>.Get();
  454. gameObject.GetComponentsInParent(false, list);
  455. if (list.Count > 0)
  456. {
  457. // Find the first active and enabled canvas.
  458. for (int i = 0; i < list.Count; ++i)
  459. {
  460. if (list[i].isActiveAndEnabled)
  461. {
  462. canvas = list[i];
  463. break;
  464. }
  465. }
  466. }
  467. TMP_ListPool<Canvas>.Release(list);
  468. return canvas;
  469. }
  470. /// <summary>
  471. /// Method used when animating the Env Map on the material.
  472. /// </summary>
  473. void UpdateEnvMapMatrix()
  474. {
  475. if (!m_sharedMaterial.HasProperty(ShaderUtilities.ID_EnvMap) || m_sharedMaterial.GetTexture(ShaderUtilities.ID_EnvMap) == null)
  476. return;
  477. //Debug.Log("Updating Env Matrix...");
  478. Vector3 rotation = m_sharedMaterial.GetVector(ShaderUtilities.ID_EnvMatrixRotation);
  479. m_EnvMapMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(rotation), Vector3.one);
  480. m_sharedMaterial.SetMatrix(ShaderUtilities.ID_EnvMatrix, m_EnvMapMatrix);
  481. }
  482. // Enable Masking in the Shader
  483. void EnableMasking()
  484. {
  485. if (m_fontMaterial == null)
  486. {
  487. m_fontMaterial = CreateMaterialInstance(m_sharedMaterial);
  488. m_canvasRenderer.SetMaterial(m_fontMaterial, m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex));
  489. }
  490. m_sharedMaterial = m_fontMaterial;
  491. if (m_sharedMaterial.HasProperty(ShaderUtilities.ID_ClipRect))
  492. {
  493. m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  494. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  495. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  496. UpdateMask(); // Update Masking Coordinates
  497. }
  498. m_isMaskingEnabled = true;
  499. //m_uiRenderer.SetMaterial(m_sharedMaterial, null);
  500. //m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
  501. //m_alignmentPadding = ShaderUtilities.GetFontExtent(m_sharedMaterial);
  502. /*
  503. Material mat = m_uiRenderer.GetMaterial();
  504. if (mat.HasProperty(ShaderUtilities.ID_MaskCoord))
  505. {
  506. mat.EnableKeyword("MASK_SOFT");
  507. mat.DisableKeyword("MASK_HARD");
  508. mat.DisableKeyword("MASK_OFF");
  509. m_isMaskingEnabled = true;
  510. UpdateMask();
  511. }
  512. */
  513. }
  514. // Enable Masking in the Shader
  515. void DisableMasking()
  516. {
  517. /*
  518. if (m_fontMaterial != null)
  519. {
  520. if (m_stencilID > 0)
  521. m_sharedMaterial = m_MaskMaterial;
  522. else
  523. m_sharedMaterial = m_baseMaterial;
  524. m_canvasRenderer.SetMaterial(m_sharedMaterial, m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex));
  525. DestroyImmediate(m_fontMaterial);
  526. }
  527. m_isMaskingEnabled = false;
  528. */
  529. /*
  530. if (m_maskingMaterial != null && m_stencilID == 0)
  531. {
  532. m_sharedMaterial = m_baseMaterial;
  533. m_uiRenderer.SetMaterial(m_sharedMaterial, null);
  534. }
  535. else if (m_stencilID > 0)
  536. {
  537. m_sharedMaterial.EnableKeyword("MASK_OFF");
  538. m_sharedMaterial.DisableKeyword("MASK_HARD");
  539. m_sharedMaterial.DisableKeyword("MASK_SOFT");
  540. }
  541. */
  542. /*
  543. Material mat = m_uiRenderer.GetMaterial();
  544. if (mat.HasProperty(ShaderUtilities.ID_MaskCoord))
  545. {
  546. mat.EnableKeyword("MASK_OFF");
  547. mat.DisableKeyword("MASK_HARD");
  548. mat.DisableKeyword("MASK_SOFT");
  549. m_isMaskingEnabled = false;
  550. UpdateMask();
  551. }
  552. */
  553. }
  554. // Update & recompute Mask offset
  555. void UpdateMask()
  556. {
  557. //Debug.Log("Updating Mask...");
  558. if (m_rectTransform != null)
  559. {
  560. //Material mat = m_uiRenderer.GetMaterial();
  561. //if (mat == null || (m_overflowMode == TextOverflowModes.ScrollRect && m_isScrollRegionSet))
  562. // return;
  563. if (!ShaderUtilities.isInitialized)
  564. ShaderUtilities.GetShaderPropertyIDs();
  565. //Debug.Log("Setting Mask for the first time.");
  566. m_isScrollRegionSet = true;
  567. float softnessX = Mathf.Min(Mathf.Min(m_margin.x, m_margin.z), m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessX));
  568. float softnessY = Mathf.Min(Mathf.Min(m_margin.y, m_margin.w), m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessY));
  569. softnessX = softnessX > 0 ? softnessX : 0;
  570. softnessY = softnessY > 0 ? softnessY : 0;
  571. float width = (m_rectTransform.rect.width - Mathf.Max(m_margin.x, 0) - Mathf.Max(m_margin.z, 0)) / 2 + softnessX;
  572. float height = (m_rectTransform.rect.height - Mathf.Max(m_margin.y, 0) - Mathf.Max(m_margin.w, 0)) / 2 + softnessY;
  573. Vector2 center = m_rectTransform.localPosition + new Vector3((0.5f - m_rectTransform.pivot.x) * m_rectTransform.rect.width + (Mathf.Max(m_margin.x, 0) - Mathf.Max(m_margin.z, 0)) / 2, (0.5f - m_rectTransform.pivot.y) * m_rectTransform.rect.height + (-Mathf.Max(m_margin.y, 0) + Mathf.Max(m_margin.w, 0)) / 2);
  574. //Vector2 center = m_rectTransform.localPosition + new Vector3((0.5f - m_rectTransform.pivot.x) * m_rectTransform.rect.width + (margin.x - margin.z) / 2, (0.5f - m_rectTransform.pivot.y) * m_rectTransform.rect.height + (-margin.y + margin.w) / 2);
  575. Vector4 mask = new Vector4(center.x, center.y, width, height);
  576. //Debug.Log(mask);
  577. //Rect rect = new Rect(0, 0, m_rectTransform.rect.width + margin.x + margin.z, m_rectTransform.rect.height + margin.y + margin.w);
  578. //int softness = (int)m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessX) / 2;
  579. m_sharedMaterial.SetVector(ShaderUtilities.ID_ClipRect, mask);
  580. }
  581. }
  582. // Function called internally when a new material is assigned via the fontMaterial property.
  583. protected override Material GetMaterial(Material mat)
  584. {
  585. // Get Shader PropertyIDs if they haven't been cached already.
  586. ShaderUtilities.GetShaderPropertyIDs();
  587. // Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
  588. // This can occur when the Duplicate Material Context menu is used on an inactive object.
  589. //if (m_canvasRenderer == null)
  590. // m_canvasRenderer = GetComponent<CanvasRenderer>();
  591. // Create Instance Material only if the new material is not the same instance previously used.
  592. if (m_fontMaterial == null || m_fontMaterial.GetInstanceID() != mat.GetInstanceID())
  593. m_fontMaterial = CreateMaterialInstance(mat);
  594. m_sharedMaterial = m_fontMaterial;
  595. m_padding = GetPaddingForMaterial();
  596. m_ShouldRecalculateStencil = true;
  597. SetVerticesDirty();
  598. SetMaterialDirty();
  599. return m_sharedMaterial;
  600. }
  601. /// <summary>
  602. /// Method returning instances of the materials used by the text object.
  603. /// </summary>
  604. /// <returns></returns>
  605. protected override Material[] GetMaterials(Material[] mats)
  606. {
  607. int materialCount = m_textInfo.materialCount;
  608. if (m_fontMaterials == null)
  609. m_fontMaterials = new Material[materialCount];
  610. else if (m_fontMaterials.Length != materialCount)
  611. TMP_TextInfo.Resize(ref m_fontMaterials, materialCount, false);
  612. // Get instances of the materials
  613. for (int i = 0; i < materialCount; i++)
  614. {
  615. if (i == 0)
  616. m_fontMaterials[i] = fontMaterial;
  617. else
  618. m_fontMaterials[i] = m_subTextObjects[i].material;
  619. }
  620. m_fontSharedMaterials = m_fontMaterials;
  621. return m_fontMaterials;
  622. }
  623. // Function called internally when a new shared material is assigned via the fontSharedMaterial property.
  624. protected override void SetSharedMaterial(Material mat)
  625. {
  626. // Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
  627. // This can occur when the Duplicate Material Context menu is used on an inactive object.
  628. //if (m_canvasRenderer == null)
  629. // m_canvasRenderer = GetComponent<CanvasRenderer>();
  630. m_sharedMaterial = mat;
  631. m_padding = GetPaddingForMaterial();
  632. SetMaterialDirty();
  633. }
  634. /// <summary>
  635. /// Method returning an array containing the materials used by the text object.
  636. /// </summary>
  637. /// <returns></returns>
  638. protected override Material[] GetSharedMaterials()
  639. {
  640. int materialCount = m_textInfo.materialCount;
  641. if (m_fontSharedMaterials == null)
  642. m_fontSharedMaterials = new Material[materialCount];
  643. else if (m_fontSharedMaterials.Length != materialCount)
  644. TMP_TextInfo.Resize(ref m_fontSharedMaterials, materialCount, false);
  645. for (int i = 0; i < materialCount; i++)
  646. {
  647. if (i == 0)
  648. m_fontSharedMaterials[i] = m_sharedMaterial;
  649. else
  650. m_fontSharedMaterials[i] = m_subTextObjects[i].sharedMaterial;
  651. }
  652. return m_fontSharedMaterials;
  653. }
  654. /// <summary>
  655. /// Method used to assign new materials to the text and sub text objects.
  656. /// </summary>
  657. protected override void SetSharedMaterials(Material[] materials)
  658. {
  659. int materialCount = m_textInfo.materialCount;
  660. // Check allocation of the fontSharedMaterials array.
  661. if (m_fontSharedMaterials == null)
  662. m_fontSharedMaterials = new Material[materialCount];
  663. else if (m_fontSharedMaterials.Length != materialCount)
  664. TMP_TextInfo.Resize(ref m_fontSharedMaterials, materialCount, false);
  665. // Only assign as many materials as the text object contains.
  666. for (int i = 0; i < materialCount; i++)
  667. {
  668. if (i == 0)
  669. {
  670. // Only assign new material if the font atlas textures match.
  671. if (materials[i].GetTexture(ShaderUtilities.ID_MainTex) == null || materials[i].GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  672. continue;
  673. m_sharedMaterial = m_fontSharedMaterials[i] = materials[i];
  674. m_padding = GetPaddingForMaterial(m_sharedMaterial);
  675. }
  676. else
  677. {
  678. // Only assign new material if the font atlas textures match.
  679. if (materials[i].GetTexture(ShaderUtilities.ID_MainTex) == null || materials[i].GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_subTextObjects[i].sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  680. continue;
  681. // Only assign a new material if none were specified in the text input.
  682. if (m_subTextObjects[i].isDefaultMaterial)
  683. m_subTextObjects[i].sharedMaterial = m_fontSharedMaterials[i] = materials[i];
  684. }
  685. }
  686. }
  687. // This function will create an instance of the Font Material.
  688. protected override void SetOutlineThickness(float thickness)
  689. {
  690. // Use material instance if one exists. Otherwise, create a new instance of the shared material.
  691. if (m_fontMaterial != null && m_sharedMaterial.GetInstanceID() != m_fontMaterial.GetInstanceID())
  692. {
  693. m_sharedMaterial = m_fontMaterial;
  694. m_canvasRenderer.SetMaterial(m_sharedMaterial, m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex));
  695. }
  696. else if(m_fontMaterial == null)
  697. {
  698. m_fontMaterial = CreateMaterialInstance(m_sharedMaterial);
  699. m_sharedMaterial = m_fontMaterial;
  700. m_canvasRenderer.SetMaterial(m_sharedMaterial, m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex));
  701. }
  702. thickness = Mathf.Clamp01(thickness);
  703. m_sharedMaterial.SetFloat(ShaderUtilities.ID_OutlineWidth, thickness);
  704. m_padding = GetPaddingForMaterial();
  705. }
  706. // This function will create an instance of the Font Material.
  707. protected override void SetFaceColor(Color32 color)
  708. {
  709. // Use material instance if one exists. Otherwise, create a new instance of the shared material.
  710. if (m_fontMaterial == null)
  711. m_fontMaterial = CreateMaterialInstance(m_sharedMaterial);
  712. m_sharedMaterial = m_fontMaterial;
  713. m_padding = GetPaddingForMaterial();
  714. m_sharedMaterial.SetColor(ShaderUtilities.ID_FaceColor, color);
  715. }
  716. // This function will create an instance of the Font Material.
  717. protected override void SetOutlineColor(Color32 color)
  718. {
  719. // Use material instance if one exists. Otherwise, create a new instance of the shared material.
  720. if (m_fontMaterial == null)
  721. m_fontMaterial = CreateMaterialInstance(m_sharedMaterial);
  722. m_sharedMaterial = m_fontMaterial;
  723. m_padding = GetPaddingForMaterial();
  724. m_sharedMaterial.SetColor(ShaderUtilities.ID_OutlineColor, color);
  725. }
  726. // Sets the Render Queue and Ztest mode
  727. protected override void SetShaderDepth()
  728. {
  729. if (m_canvas == null || m_sharedMaterial == null)
  730. return;
  731. if (m_canvas.renderMode == RenderMode.ScreenSpaceOverlay || m_isOverlay)
  732. {
  733. // Should this use an instanced material?
  734. m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 0);
  735. }
  736. else
  737. { // TODO: This section needs to be tested.
  738. m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 4);
  739. }
  740. }
  741. // Sets the Culling mode of the material
  742. protected override void SetCulling()
  743. {
  744. if (m_isCullingEnabled)
  745. {
  746. Material mat = materialForRendering;
  747. if (mat != null)
  748. mat.SetFloat("_CullMode", 2);
  749. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  750. {
  751. mat = m_subTextObjects[i].materialForRendering;
  752. if (mat != null)
  753. {
  754. mat.SetFloat(ShaderUtilities.ShaderTag_CullMode, 2);
  755. }
  756. }
  757. }
  758. else
  759. {
  760. Material mat = materialForRendering;
  761. if (mat != null)
  762. mat.SetFloat("_CullMode", 0);
  763. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  764. {
  765. mat = m_subTextObjects[i].materialForRendering;
  766. if (mat != null)
  767. {
  768. mat.SetFloat(ShaderUtilities.ShaderTag_CullMode, 0);
  769. }
  770. }
  771. }
  772. }
  773. // Set Perspective Correction Mode based on whether Camera is Orthographic or Perspective
  774. void SetPerspectiveCorrection()
  775. {
  776. if (m_isOrthographic)
  777. m_sharedMaterial.SetFloat(ShaderUtilities.ID_PerspectiveFilter, 0.0f);
  778. else
  779. m_sharedMaterial.SetFloat(ShaderUtilities.ID_PerspectiveFilter, 0.875f);
  780. }
  781. // Function to allocate the necessary buffers to render the text. This function is called whenever the buffer size needs to be increased.
  782. void SetMeshArrays(int size)
  783. {
  784. m_textInfo.meshInfo[0].ResizeMeshInfo(size);
  785. m_canvasRenderer.SetMesh(m_textInfo.meshInfo[0].mesh);
  786. }
  787. // This function parses through the Char[] to determine how many characters will be visible. It then makes sure the arrays are large enough for all those characters.
  788. internal override int SetArraySizes(UnicodeChar[] unicodeChars)
  789. {
  790. k_SetArraySizesMarker.Begin();
  791. int spriteCount = 0;
  792. m_totalCharacterCount = 0;
  793. m_isUsingBold = false;
  794. m_isParsingText = false;
  795. tag_NoParsing = false;
  796. m_FontStyleInternal = m_fontStyle;
  797. m_fontStyleStack.Clear();
  798. m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? FontWeight.Bold : m_fontWeight;
  799. m_FontWeightStack.SetDefault(m_FontWeightInternal);
  800. m_currentFontAsset = m_fontAsset;
  801. m_currentMaterial = m_sharedMaterial;
  802. m_currentMaterialIndex = 0;
  803. m_materialReferenceStack.SetDefault(new MaterialReference(m_currentMaterialIndex, m_currentFontAsset, null, m_currentMaterial, m_padding));
  804. m_materialReferenceIndexLookup.Clear();
  805. MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  806. // Set allocations for the text object's TextInfo
  807. if (m_textInfo == null)
  808. m_textInfo = new TMP_TextInfo(m_InternalTextProcessingArraySize);
  809. else if (m_textInfo.characterInfo.Length < m_InternalTextProcessingArraySize)
  810. TMP_TextInfo.Resize(ref m_textInfo.characterInfo, m_InternalTextProcessingArraySize, false);
  811. m_textElementType = TMP_TextElementType.Character;
  812. // Handling for Underline special character
  813. #region Setup Underline Special Character
  814. /*
  815. GetUnderlineSpecialCharacter(m_currentFontAsset);
  816. if (m_Underline.character != null)
  817. {
  818. if (m_Underline.fontAsset.GetInstanceID() != m_currentFontAsset.GetInstanceID())
  819. {
  820. if (TMP_Settings.matchMaterialPreset && m_currentMaterial.GetInstanceID() != m_Underline.fontAsset.material.GetInstanceID())
  821. m_Underline.material = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_Underline.fontAsset.material);
  822. else
  823. m_Underline.material = m_Underline.fontAsset.material;
  824. m_Underline.materialIndex = MaterialReference.AddMaterialReference(m_Underline.material, m_Underline.fontAsset, m_materialReferences, m_materialReferenceIndexLookup);
  825. m_materialReferences[m_Underline.materialIndex].referenceCount = 0;
  826. }
  827. }
  828. */
  829. #endregion
  830. // Handling for Ellipsis special character
  831. #region Setup Ellipsis Special Character
  832. if (m_overflowMode == TextOverflowModes.Ellipsis)
  833. {
  834. GetEllipsisSpecialCharacter(m_currentFontAsset);
  835. if (m_Ellipsis.character != null)
  836. {
  837. if (m_Ellipsis.fontAsset.GetInstanceID() != m_currentFontAsset.GetInstanceID())
  838. {
  839. if (TMP_Settings.matchMaterialPreset && m_currentMaterial.GetInstanceID() != m_Ellipsis.fontAsset.material.GetInstanceID())
  840. m_Ellipsis.material = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_Ellipsis.fontAsset.material);
  841. else
  842. m_Ellipsis.material = m_Ellipsis.fontAsset.material;
  843. m_Ellipsis.materialIndex = MaterialReference.AddMaterialReference(m_Ellipsis.material, m_Ellipsis.fontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  844. m_materialReferences[m_Ellipsis.materialIndex].referenceCount = 0;
  845. }
  846. }
  847. else
  848. {
  849. m_overflowMode = TextOverflowModes.Truncate;
  850. if (!TMP_Settings.warningsDisabled)
  851. Debug.LogWarning("The character used for Ellipsis is not available in font asset [" + m_currentFontAsset.name + "] or any potential fallbacks. Switching Text Overflow mode to Truncate.", this);
  852. }
  853. }
  854. #endregion
  855. // Clear Linked Text object content if we have any.
  856. if (m_overflowMode == TextOverflowModes.Linked && m_linkedTextComponent != null && !m_isCalculatingPreferredValues)
  857. {
  858. TMP_Text linkedComponent = m_linkedTextComponent;
  859. while (linkedComponent != null)
  860. {
  861. linkedComponent.text = String.Empty;
  862. linkedComponent.ClearMesh();
  863. linkedComponent.textInfo.Clear();
  864. linkedComponent = linkedComponent.linkedTextComponent;
  865. }
  866. }
  867. // Parsing XML tags in the text
  868. for (int i = 0; i < unicodeChars.Length && unicodeChars[i].unicode != 0; i++)
  869. {
  870. //Make sure the characterInfo array can hold the next text element.
  871. if (m_textInfo.characterInfo == null || m_totalCharacterCount >= m_textInfo.characterInfo.Length)
  872. TMP_TextInfo.Resize(ref m_textInfo.characterInfo, m_totalCharacterCount + 1, true);
  873. int unicode = unicodeChars[i].unicode;
  874. // PARSE XML TAGS
  875. #region PARSE XML TAGS
  876. if (m_isRichText && unicode == 60) // if Char '<'
  877. {
  878. int prev_MaterialIndex = m_currentMaterialIndex;
  879. int endTagIndex;
  880. // Check if Tag is Valid
  881. if (ValidateHtmlTag(unicodeChars, i + 1, out endTagIndex))
  882. {
  883. int tagStartIndex = unicodeChars[i].stringIndex;
  884. i = endTagIndex;
  885. if ((m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold)
  886. m_isUsingBold = true;
  887. if (m_textElementType == TMP_TextElementType.Sprite)
  888. {
  889. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  890. m_textInfo.characterInfo[m_totalCharacterCount].character = (char)(57344 + m_spriteIndex);
  891. m_textInfo.characterInfo[m_totalCharacterCount].spriteIndex = m_spriteIndex;
  892. m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
  893. m_textInfo.characterInfo[m_totalCharacterCount].spriteAsset = m_currentSpriteAsset;
  894. m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
  895. m_textInfo.characterInfo[m_totalCharacterCount].textElement = m_currentSpriteAsset.spriteCharacterTable[m_spriteIndex];
  896. m_textInfo.characterInfo[m_totalCharacterCount].elementType = m_textElementType;
  897. m_textInfo.characterInfo[m_totalCharacterCount].index = tagStartIndex;
  898. m_textInfo.characterInfo[m_totalCharacterCount].stringLength = unicodeChars[i].stringIndex - tagStartIndex + 1;
  899. // Restore element type and material index to previous values.
  900. m_textElementType = TMP_TextElementType.Character;
  901. m_currentMaterialIndex = prev_MaterialIndex;
  902. spriteCount += 1;
  903. m_totalCharacterCount += 1;
  904. }
  905. continue;
  906. }
  907. }
  908. #endregion
  909. bool isUsingAlternativeTypeface = false;
  910. bool isUsingFallbackOrAlternativeTypeface = false;
  911. TMP_FontAsset prev_fontAsset = m_currentFontAsset;
  912. Material prev_material = m_currentMaterial;
  913. int prev_materialIndex = m_currentMaterialIndex;
  914. // Handle Font Styles like LowerCase, UpperCase and SmallCaps.
  915. #region Handling of LowerCase, UpperCase and SmallCaps Font Styles
  916. if (m_textElementType == TMP_TextElementType.Character)
  917. {
  918. if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
  919. {
  920. // If this character is lowercase, switch to uppercase.
  921. if (char.IsLower((char)unicode))
  922. unicode = char.ToUpper((char)unicode);
  923. }
  924. else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
  925. {
  926. // If this character is uppercase, switch to lowercase.
  927. if (char.IsUpper((char)unicode))
  928. unicode = char.ToLower((char)unicode);
  929. }
  930. else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
  931. {
  932. // Only convert lowercase characters to uppercase.
  933. if (char.IsLower((char)unicode))
  934. unicode = char.ToUpper((char)unicode);
  935. }
  936. }
  937. #endregion
  938. // Lookup the Glyph data for each character and cache it.
  939. #region LOOKUP GLYPH
  940. TMP_TextElement character = GetTextElement((uint)unicode, m_currentFontAsset, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  941. // Check if Lowercase or Uppercase variant of the character is available.
  942. /* Not sure this is necessary anyone as it is very unlikely with recursive search through fallback fonts.
  943. if (glyph == null)
  944. {
  945. if (char.IsLower((char)c))
  946. {
  947. if (m_currentFontAsset.characterDictionary.TryGetValue(char.ToUpper((char)c), out glyph))
  948. c = chars[i] = char.ToUpper((char)c);
  949. }
  950. else if (char.IsUpper((char)c))
  951. {
  952. if (m_currentFontAsset.characterDictionary.TryGetValue(char.ToLower((char)c), out glyph))
  953. c = chars[i] = char.ToLower((char)c);
  954. }
  955. }*/
  956. // Special handling for missing character.
  957. // Replace missing glyph by the Square (9633) glyph or possibly the Space (32) glyph.
  958. if (character == null)
  959. {
  960. // Save the original unicode character
  961. int srcGlyph = unicode;
  962. // Try replacing the missing glyph character by TMP Settings Missing Glyph or Square (9633) character.
  963. unicode = unicodeChars[i].unicode = TMP_Settings.missingGlyphCharacter == 0 ? 9633 : TMP_Settings.missingGlyphCharacter;
  964. // Check for the missing glyph character in the currently assigned font asset and its fallbacks
  965. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_currentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  966. if (character == null)
  967. {
  968. // Search for the missing glyph character in the TMP Settings Fallback list.
  969. if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  970. character = TMP_FontAssetUtilities.GetCharacterFromFontAssets((uint)unicode, m_currentFontAsset, TMP_Settings.fallbackFontAssets, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  971. }
  972. if (character == null)
  973. {
  974. // Search for the missing glyph in the TMP Settings Default Font Asset.
  975. if (TMP_Settings.defaultFontAsset != null)
  976. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, TMP_Settings.defaultFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  977. }
  978. if (character == null)
  979. {
  980. // Use Space (32) Glyph from the currently assigned font asset.
  981. unicode = unicodeChars[i].unicode = 32;
  982. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_currentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  983. }
  984. if (character == null)
  985. {
  986. // Use End of Text (0x03) Glyph from the currently assigned font asset.
  987. unicode = unicodeChars[i].unicode = 0x03;
  988. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_currentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  989. }
  990. if (!TMP_Settings.warningsDisabled)
  991. {
  992. string formattedWarning = srcGlyph > 0xFFFF
  993. ? string.Format("The character with Unicode value \\U{0:X8} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4} in text object [{3}].", srcGlyph, m_fontAsset.name, character.unicode, this.name)
  994. : string.Format("The character with Unicode value \\u{0:X4} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4} in text object [{3}].", srcGlyph, m_fontAsset.name, character.unicode, this.name);
  995. Debug.LogWarning(formattedWarning, this);
  996. }
  997. }
  998. if (character.elementType == TextElementType.Character)
  999. {
  1000. if (character.textAsset.instanceID != m_currentFontAsset.instanceID)
  1001. {
  1002. isUsingFallbackOrAlternativeTypeface = true;
  1003. m_currentFontAsset = character.textAsset as TMP_FontAsset;
  1004. }
  1005. }
  1006. #endregion
  1007. // Save text element data
  1008. m_textInfo.characterInfo[m_totalCharacterCount].elementType = TMP_TextElementType.Character;
  1009. m_textInfo.characterInfo[m_totalCharacterCount].textElement = character;
  1010. m_textInfo.characterInfo[m_totalCharacterCount].isUsingAlternateTypeface = isUsingAlternativeTypeface;
  1011. m_textInfo.characterInfo[m_totalCharacterCount].character = (char)unicode;
  1012. m_textInfo.characterInfo[m_totalCharacterCount].index = unicodeChars[i].stringIndex;
  1013. m_textInfo.characterInfo[m_totalCharacterCount].stringLength = unicodeChars[i].length;
  1014. m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
  1015. // Special handling if the character is a sprite.
  1016. if (character.elementType == TextElementType.Sprite)
  1017. {
  1018. TMP_SpriteAsset spriteAssetRef = character.textAsset as TMP_SpriteAsset;
  1019. m_currentMaterialIndex = MaterialReference.AddMaterialReference(spriteAssetRef.material, spriteAssetRef, ref m_materialReferences, m_materialReferenceIndexLookup);
  1020. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1021. m_textInfo.characterInfo[m_totalCharacterCount].elementType = TMP_TextElementType.Sprite;
  1022. m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
  1023. m_textInfo.characterInfo[m_totalCharacterCount].spriteAsset = spriteAssetRef;
  1024. m_textInfo.characterInfo[m_totalCharacterCount].spriteIndex = (int)character.glyphIndex;
  1025. // Restore element type and material index to previous values.
  1026. m_textElementType = TMP_TextElementType.Character;
  1027. m_currentMaterialIndex = prev_materialIndex;
  1028. spriteCount += 1;
  1029. m_totalCharacterCount += 1;
  1030. continue;
  1031. }
  1032. if (isUsingFallbackOrAlternativeTypeface && m_currentFontAsset.instanceID != m_fontAsset.instanceID)
  1033. {
  1034. // Create Fallback material instance matching current material preset if necessary
  1035. if (TMP_Settings.matchMaterialPreset)
  1036. m_currentMaterial = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_currentFontAsset.material);
  1037. else
  1038. m_currentMaterial = m_currentFontAsset.material;
  1039. m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1040. }
  1041. // Handle Multi Atlas Texture support
  1042. if (character != null && character.glyph.atlasIndex > 0)
  1043. {
  1044. m_currentMaterial = TMP_MaterialManager.GetFallbackMaterial(m_currentFontAsset, m_currentMaterial, character.glyph.atlasIndex);
  1045. m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1046. isUsingFallbackOrAlternativeTypeface = true;
  1047. }
  1048. if (!char.IsWhiteSpace((char)unicode) && unicode != 0x200B)
  1049. {
  1050. // Limit the mesh of the main text object to 65535 vertices and use sub objects for the overflow.
  1051. if (m_materialReferences[m_currentMaterialIndex].referenceCount < 16383)
  1052. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1053. else
  1054. {
  1055. m_currentMaterialIndex = MaterialReference.AddMaterialReference(new Material(m_currentMaterial), m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1056. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1057. }
  1058. }
  1059. m_textInfo.characterInfo[m_totalCharacterCount].material = m_currentMaterial;
  1060. m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
  1061. m_materialReferences[m_currentMaterialIndex].isFallbackMaterial = isUsingFallbackOrAlternativeTypeface;
  1062. // Restore previous font asset and material if fallback font was used.
  1063. if (isUsingFallbackOrAlternativeTypeface)
  1064. {
  1065. m_materialReferences[m_currentMaterialIndex].fallbackMaterial = prev_material;
  1066. m_currentFontAsset = prev_fontAsset;
  1067. m_currentMaterial = prev_material;
  1068. m_currentMaterialIndex = prev_materialIndex;
  1069. }
  1070. m_totalCharacterCount += 1;
  1071. }
  1072. // Early return if we are calculating the preferred values.
  1073. if (m_isCalculatingPreferredValues)
  1074. {
  1075. m_isCalculatingPreferredValues = false;
  1076. k_SetArraySizesMarker.End();
  1077. return m_totalCharacterCount;
  1078. }
  1079. // Save material and sprite count.
  1080. m_textInfo.spriteCount = spriteCount;
  1081. int materialCount = m_textInfo.materialCount = m_materialReferenceIndexLookup.Count;
  1082. // Check if we need to resize the MeshInfo array for handling different materials.
  1083. if (materialCount > m_textInfo.meshInfo.Length)
  1084. TMP_TextInfo.Resize(ref m_textInfo.meshInfo, materialCount, false);
  1085. // Resize SubTextObject array if necessary
  1086. if (materialCount > m_subTextObjects.Length)
  1087. TMP_TextInfo.Resize(ref m_subTextObjects, Mathf.NextPowerOfTwo(materialCount + 1));
  1088. // Resize CharacterInfo[] if allocations are excessive
  1089. if (m_VertexBufferAutoSizeReduction && m_textInfo.characterInfo.Length - m_totalCharacterCount > 256)
  1090. TMP_TextInfo.Resize(ref m_textInfo.characterInfo, Mathf.Max(m_totalCharacterCount + 1, 256), true);
  1091. // Iterate through the material references to set the mesh buffer allocations
  1092. for (int i = 0; i < materialCount; i++)
  1093. {
  1094. // Add new sub text object for each material reference
  1095. if (i > 0)
  1096. {
  1097. if (m_subTextObjects[i] == null)
  1098. {
  1099. m_subTextObjects[i] = TMP_SubMeshUI.AddSubTextObject(this, m_materialReferences[i]);
  1100. // Not sure this is necessary
  1101. m_textInfo.meshInfo[i].vertices = null;
  1102. }
  1103. //else if (m_subTextObjects[i].gameObject.activeInHierarchy == false)
  1104. // m_subTextObjects[i].gameObject.SetActive(true);
  1105. // Make sure the pivots are synchronized
  1106. if (m_rectTransform.pivot != m_subTextObjects[i].rectTransform.pivot)
  1107. m_subTextObjects[i].rectTransform.pivot = m_rectTransform.pivot;
  1108. // Check if the material has changed.
  1109. if (m_subTextObjects[i].sharedMaterial == null || m_subTextObjects[i].sharedMaterial.GetInstanceID() != m_materialReferences[i].material.GetInstanceID())
  1110. {
  1111. m_subTextObjects[i].sharedMaterial = m_materialReferences[i].material;
  1112. m_subTextObjects[i].fontAsset = m_materialReferences[i].fontAsset;
  1113. m_subTextObjects[i].spriteAsset = m_materialReferences[i].spriteAsset;
  1114. }
  1115. // Check if we need to use a Fallback Material
  1116. if (m_materialReferences[i].isFallbackMaterial)
  1117. {
  1118. m_subTextObjects[i].fallbackMaterial = m_materialReferences[i].material;
  1119. m_subTextObjects[i].fallbackSourceMaterial = m_materialReferences[i].fallbackMaterial;
  1120. }
  1121. }
  1122. int referenceCount = m_materialReferences[i].referenceCount;
  1123. // Check to make sure our buffers allocations can accommodate the required text elements.
  1124. if (m_textInfo.meshInfo[i].vertices == null || m_textInfo.meshInfo[i].vertices.Length < referenceCount * 4)
  1125. {
  1126. if (m_textInfo.meshInfo[i].vertices == null)
  1127. {
  1128. if (i == 0)
  1129. m_textInfo.meshInfo[i] = new TMP_MeshInfo(m_mesh, referenceCount + 1);
  1130. else
  1131. m_textInfo.meshInfo[i] = new TMP_MeshInfo(m_subTextObjects[i].mesh, referenceCount + 1);
  1132. }
  1133. else
  1134. m_textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.NextPowerOfTwo(referenceCount + 1));
  1135. }
  1136. else if (m_VertexBufferAutoSizeReduction && referenceCount > 0 && m_textInfo.meshInfo[i].vertices.Length / 4 - referenceCount > 256)
  1137. {
  1138. // Resize vertex buffers if allocations are excessive.
  1139. //Debug.Log("Reducing the size of the vertex buffers.");
  1140. m_textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.NextPowerOfTwo(referenceCount + 1));
  1141. }
  1142. // Assign material reference
  1143. m_textInfo.meshInfo[i].material = m_materialReferences[i].material;
  1144. }
  1145. //TMP_MaterialManager.CleanupFallbackMaterials();
  1146. // Clean up unused SubMeshes
  1147. for (int i = materialCount; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  1148. {
  1149. if (i < m_textInfo.meshInfo.Length)
  1150. {
  1151. m_subTextObjects[i].canvasRenderer.SetMesh(null);
  1152. // TODO: Figure out a way to handle this without running into Unity's Rebuild loop issue.
  1153. //m_subTextObjects[i].gameObject.SetActive(false);
  1154. }
  1155. }
  1156. k_SetArraySizesMarker.End();
  1157. return m_totalCharacterCount;
  1158. }
  1159. // Added to sort handle the potential issue with OnWillRenderObject() not getting called when objects are not visible by camera.
  1160. //void OnBecameInvisible()
  1161. //{
  1162. // if (m_mesh != null)
  1163. // m_mesh.bounds = new Bounds(transform.position, new Vector3(1000, 1000, 0));
  1164. //}
  1165. /// <summary>
  1166. /// Update the margin width and height
  1167. /// </summary>
  1168. public override void ComputeMarginSize()
  1169. {
  1170. if (this.rectTransform != null)
  1171. {
  1172. //Debug.Log("*** ComputeMarginSize() *** Current RectTransform's Width is " + m_rectTransform.rect.width + " and Height is " + m_rectTransform.rect.height); // + " and size delta is " + m_rectTransform.sizeDelta);
  1173. Rect rect = m_rectTransform.rect;
  1174. m_marginWidth = rect.width - m_margin.x - m_margin.z;
  1175. m_marginHeight = rect.height - m_margin.y - m_margin.w;
  1176. // Cache current RectTransform width and pivot referenced in OnRectTransformDimensionsChange() to get around potential rounding error in the reported width of the RectTransform.
  1177. m_PreviousRectTransformSize = rect.size;
  1178. m_PreviousPivotPosition = m_rectTransform.pivot;
  1179. // Update the corners of the RectTransform
  1180. m_RectTransformCorners = GetTextContainerLocalCorners();
  1181. }
  1182. }
  1183. /// <summary>
  1184. ///
  1185. /// </summary>
  1186. protected override void OnDidApplyAnimationProperties()
  1187. {
  1188. m_havePropertiesChanged = true;
  1189. SetVerticesDirty();
  1190. SetLayoutDirty();
  1191. //Debug.Log("Animation Properties have changed.");
  1192. }
  1193. protected override void OnCanvasHierarchyChanged()
  1194. {
  1195. base.OnCanvasHierarchyChanged();
  1196. m_canvas = canvas;
  1197. if (!m_isAwake || !isActiveAndEnabled)
  1198. return;
  1199. // Special handling to stop InternalUpdate calls when parent Canvas is disabled.
  1200. if (m_canvas == null || m_canvas.enabled == false)
  1201. TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
  1202. else if (m_IsTextObjectScaleStatic == false)
  1203. TMP_UpdateManager.RegisterTextObjectForUpdate(this);
  1204. }
  1205. protected override void OnTransformParentChanged()
  1206. {
  1207. //Debug.Log("***** OnTransformParentChanged *****");
  1208. base.OnTransformParentChanged();
  1209. m_canvas = this.canvas;
  1210. ComputeMarginSize();
  1211. m_havePropertiesChanged = true;
  1212. }
  1213. protected override void OnRectTransformDimensionsChange()
  1214. {
  1215. //Debug.Log("*** OnRectTransformDimensionsChange() *** ActiveInHierarchy: " + this.gameObject.activeInHierarchy + " Frame: " + Time.frameCount);
  1216. // Make sure object is active in Hierarchy
  1217. if (!this.gameObject.activeInHierarchy)
  1218. return;
  1219. // Check if Canvas scale factor has changed as this requires an update of the SDF Scale.
  1220. bool hasCanvasScaleFactorChanged = false;
  1221. if (m_canvas != null && m_CanvasScaleFactor != m_canvas.scaleFactor)
  1222. {
  1223. m_CanvasScaleFactor = m_canvas.scaleFactor;
  1224. hasCanvasScaleFactorChanged = true;
  1225. }
  1226. // Ignore changes to RectTransform SizeDelta that are very small and typically the result of rounding errors when using RectTransform in Anchor Stretch mode.
  1227. if (hasCanvasScaleFactorChanged == false &&
  1228. rectTransform != null &&
  1229. Mathf.Abs(m_rectTransform.rect.width - m_PreviousRectTransformSize.x) < 0.0001f && Mathf.Abs(m_rectTransform.rect.height - m_PreviousRectTransformSize.y) < 0.0001f &&
  1230. Mathf.Abs(m_rectTransform.pivot.x - m_PreviousPivotPosition.x) < 0.0001f && Mathf.Abs(m_rectTransform.pivot.y - m_PreviousPivotPosition.y) < 0.0001f)
  1231. {
  1232. return;
  1233. }
  1234. ComputeMarginSize();
  1235. UpdateSubObjectPivot();
  1236. SetVerticesDirty();
  1237. SetLayoutDirty();
  1238. }
  1239. /// <summary>
  1240. /// Function used as a replacement for LateUpdate to check if the transform or scale of the text object has changed.
  1241. /// </summary>
  1242. internal override void InternalUpdate()
  1243. {
  1244. // We need to update the SDF scale or possibly regenerate the text object if lossy scale has changed.
  1245. if (m_havePropertiesChanged == false)
  1246. {
  1247. float lossyScaleY = m_rectTransform.lossyScale.y;
  1248. // Ignore very small lossy scale changes as their effect on SDF Scale would not be visually noticeable.
  1249. // Do not update SDF Scale if the text is null or empty
  1250. if (Mathf.Abs(lossyScaleY - m_previousLossyScaleY) > 0.0001f && m_TextProcessingArray[0].unicode != 0)
  1251. {
  1252. float scaleDelta = lossyScaleY / m_previousLossyScaleY;
  1253. UpdateSDFScale(scaleDelta);
  1254. m_previousLossyScaleY = lossyScaleY;
  1255. }
  1256. }
  1257. // Added to handle legacy animation mode.
  1258. if (m_isUsingLegacyAnimationComponent)
  1259. {
  1260. //if (m_havePropertiesChanged)
  1261. m_havePropertiesChanged = true;
  1262. OnPreRenderCanvas();
  1263. }
  1264. }
  1265. /// <summary>
  1266. /// Function called when the text needs to be updated.
  1267. /// </summary>
  1268. void OnPreRenderCanvas()
  1269. {
  1270. //Debug.Log("*** OnPreRenderCanvas() *** Frame: " + Time.frameCount);
  1271. // Make sure object is active and that we have a valid Canvas.
  1272. if (!m_isAwake || (this.IsActive() == false && m_ignoreActiveState == false))
  1273. return;
  1274. if (m_canvas == null) { m_canvas = this.canvas; if (m_canvas == null) return; }
  1275. // Check if we have a font asset assigned. Return if we don't because no one likes to see purple squares on screen.
  1276. if (m_fontAsset == null)
  1277. {
  1278. Debug.LogWarning("Please assign a Font Asset to this " + transform.name + " gameobject.", this);
  1279. return;
  1280. }
  1281. if (m_havePropertiesChanged || m_isLayoutDirty)
  1282. {
  1283. //Debug.Log("Properties have changed!"); // Assigned Material is:" + m_sharedMaterial); // New Text is: " + m_text + ".");
  1284. // Update mesh padding if necessary.
  1285. if (checkPaddingRequired)
  1286. UpdateMeshPadding();
  1287. // Reparse the text as input may have changed or been truncated.
  1288. ParseInputText();
  1289. TMP_FontAsset.UpdateFontFeaturesForFontAssetsInQueue();
  1290. // Reset Font min / max used with Auto-sizing
  1291. if (m_enableAutoSizing)
  1292. m_fontSize = Mathf.Clamp(m_fontSizeBase, m_fontSizeMin, m_fontSizeMax);
  1293. m_maxFontSize = m_fontSizeMax;
  1294. m_minFontSize = m_fontSizeMin;
  1295. m_lineSpacingDelta = 0;
  1296. m_charWidthAdjDelta = 0;
  1297. m_isTextTruncated = false;
  1298. m_havePropertiesChanged = false;
  1299. m_isLayoutDirty = false;
  1300. m_ignoreActiveState = false;
  1301. // Reset Text Auto Size iteration tracking.
  1302. m_IsAutoSizePointSizeSet = false;
  1303. m_AutoSizeIterationCount = 0;
  1304. // The GenerateTextMesh function is potentially called repeatedly when text auto size is enabled.
  1305. // This is a revised implementation to remove the use of recursion which could potentially result in stack overflow issues.
  1306. while (m_IsAutoSizePointSizeSet == false)
  1307. {
  1308. GenerateTextMesh();
  1309. m_AutoSizeIterationCount += 1;
  1310. }
  1311. }
  1312. }
  1313. /// <summary>
  1314. /// This is the main function that is responsible for creating / displaying the text.
  1315. /// </summary>
  1316. protected virtual void GenerateTextMesh()
  1317. {
  1318. k_GenerateTextMarker.Begin();
  1319. // Early exit if no font asset was assigned. This should not be needed since LiberationSans SDF will be assigned by default.
  1320. if (m_fontAsset == null || m_fontAsset.characterLookupTable == null)
  1321. {
  1322. Debug.LogWarning("Can't Generate Mesh! No Font Asset has been assigned to Object ID: " + this.GetInstanceID());
  1323. m_IsAutoSizePointSizeSet = true;
  1324. k_GenerateTextMarker.End();
  1325. return;
  1326. }
  1327. // Clear TextInfo
  1328. if (m_textInfo != null)
  1329. m_textInfo.Clear();
  1330. // Early exit if we don't have any Text to generate.
  1331. if (m_TextProcessingArray == null || m_TextProcessingArray.Length == 0 || m_TextProcessingArray[0].unicode == 0)
  1332. {
  1333. // Clear mesh and upload changes to the mesh.
  1334. ClearMesh();
  1335. m_preferredWidth = 0;
  1336. m_preferredHeight = 0;
  1337. // Event indicating the text has been regenerated.
  1338. TMPro_EventManager.ON_TEXT_CHANGED(this);
  1339. m_IsAutoSizePointSizeSet = true;
  1340. k_GenerateTextMarker.End();
  1341. return;
  1342. }
  1343. m_currentFontAsset = m_fontAsset;
  1344. m_currentMaterial = m_sharedMaterial;
  1345. m_currentMaterialIndex = 0;
  1346. m_materialReferenceStack.SetDefault(new MaterialReference(m_currentMaterialIndex, m_currentFontAsset, null, m_currentMaterial, m_padding));
  1347. m_currentSpriteAsset = m_spriteAsset;
  1348. // Stop all Sprite Animations
  1349. if (m_spriteAnimator != null)
  1350. m_spriteAnimator.StopAllAnimations();
  1351. // Total character count is computed when the text is parsed.
  1352. int totalCharacterCount = m_totalCharacterCount;
  1353. // Calculate the scale of the font based on selected font size and sampling point size.
  1354. // baseScale is calculated using the font asset assigned to the text object.
  1355. float baseScale = (m_fontSize / m_fontAsset.m_FaceInfo.pointSize * m_fontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f));
  1356. float currentElementScale = baseScale;
  1357. float currentEmScale = m_fontSize * 0.01f * (m_isOrthographic ? 1 : 0.1f);
  1358. m_fontScaleMultiplier = 1;
  1359. m_currentFontSize = m_fontSize;
  1360. m_sizeStack.SetDefault(m_currentFontSize);
  1361. float fontSizeDelta = 0;
  1362. int charCode = 0; // Holds the character code of the currently being processed character.
  1363. m_FontStyleInternal = m_fontStyle; // Set the default style.
  1364. m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? FontWeight.Bold : m_fontWeight;
  1365. m_FontWeightStack.SetDefault(m_FontWeightInternal);
  1366. m_fontStyleStack.Clear();
  1367. m_lineJustification = m_HorizontalAlignment; // m_textAlignment; // Sets the line justification mode to match editor alignment.
  1368. m_lineJustificationStack.SetDefault(m_lineJustification);
  1369. float padding = 0;
  1370. float style_padding = 0; // Extra padding required to accommodate Bold style.
  1371. float boldSpacingAdjustment = 0;
  1372. //float bold_xAdvance_multiplier = 1; // Used to increase spacing between character when style is bold.
  1373. m_baselineOffset = 0; // Used by subscript characters.
  1374. m_baselineOffsetStack.Clear();
  1375. // Underline
  1376. bool beginUnderline = false;
  1377. Vector3 underline_start = Vector3.zero; // Used to track where underline starts & ends.
  1378. Vector3 underline_end = Vector3.zero;
  1379. // Strike-through
  1380. bool beginStrikethrough = false;
  1381. Vector3 strikethrough_start = Vector3.zero;
  1382. Vector3 strikethrough_end = Vector3.zero;
  1383. // Text Highlight
  1384. bool beginHighlight = false;
  1385. Vector3 highlight_start = Vector3.zero;
  1386. Vector3 highlight_end = Vector3.zero;
  1387. m_fontColor32 = m_fontColor;
  1388. Color32 vertexColor;
  1389. m_htmlColor = m_fontColor32;
  1390. m_underlineColor = m_htmlColor;
  1391. m_strikethroughColor = m_htmlColor;
  1392. m_colorStack.SetDefault(m_htmlColor);
  1393. m_underlineColorStack.SetDefault(m_htmlColor);
  1394. m_strikethroughColorStack.SetDefault(m_htmlColor);
  1395. m_HighlightStateStack.SetDefault(new HighlightState(m_htmlColor, TMP_Offset.zero));
  1396. m_colorGradientPreset = null;
  1397. m_colorGradientStack.SetDefault(null);
  1398. m_ItalicAngle = m_currentFontAsset.italicStyle;
  1399. m_ItalicAngleStack.SetDefault(m_ItalicAngle);
  1400. // Clear the Style stack.
  1401. //m_styleStack.Clear();
  1402. // Clear the Action stack.
  1403. m_actionStack.Clear();
  1404. m_isFXMatrixSet = false;
  1405. m_lineOffset = 0; // Amount of space between lines (font line spacing + m_linespacing).
  1406. m_lineHeight = TMP_Math.FLOAT_UNSET;
  1407. float lineGap = m_currentFontAsset.m_FaceInfo.lineHeight - (m_currentFontAsset.m_FaceInfo.ascentLine - m_currentFontAsset.m_FaceInfo.descentLine);
  1408. m_cSpacing = 0; // Amount of space added between characters as a result of the use of the <cspace> tag.
  1409. m_monoSpacing = 0;
  1410. m_xAdvance = 0; // Used to track the position of each character.
  1411. tag_LineIndent = 0; // Used for indentation of text.
  1412. tag_Indent = 0;
  1413. m_indentStack.SetDefault(0);
  1414. tag_NoParsing = false;
  1415. //m_isIgnoringAlignment = false;
  1416. m_characterCount = 0; // Total characters in the char[]
  1417. // Tracking of line information
  1418. m_firstCharacterOfLine = m_firstVisibleCharacter;
  1419. m_lastCharacterOfLine = 0;
  1420. m_firstVisibleCharacterOfLine = 0;
  1421. m_lastVisibleCharacterOfLine = 0;
  1422. m_maxLineAscender = k_LargeNegativeFloat;
  1423. m_maxLineDescender = k_LargePositiveFloat;
  1424. m_lineNumber = 0;
  1425. m_startOfLineAscender = 0;
  1426. m_startOfLineDescender = 0;
  1427. m_lineVisibleCharacterCount = 0;
  1428. bool isStartOfNewLine = true;
  1429. m_IsDrivenLineSpacing = false;
  1430. m_firstOverflowCharacterIndex = -1;
  1431. m_pageNumber = 0;
  1432. int pageToDisplay = Mathf.Clamp(m_pageToDisplay - 1, 0, m_textInfo.pageInfo.Length - 1);
  1433. m_textInfo.ClearPageInfo();
  1434. Vector4 margins = m_margin;
  1435. float marginWidth = m_marginWidth > 0 ? m_marginWidth : 0;
  1436. float marginHeight = m_marginHeight > 0 ? m_marginHeight : 0;
  1437. m_marginLeft = 0;
  1438. m_marginRight = 0;
  1439. m_width = -1;
  1440. float widthOfTextArea = marginWidth + 0.0001f - m_marginLeft - m_marginRight;
  1441. // Need to initialize these Extents structures
  1442. m_meshExtents.min = k_LargePositiveVector2;
  1443. m_meshExtents.max = k_LargeNegativeVector2;
  1444. // Initialize lineInfo
  1445. m_textInfo.ClearLineInfo();
  1446. // Tracking of the highest Ascender
  1447. m_maxCapHeight = 0;
  1448. m_maxTextAscender = 0;
  1449. m_ElementDescender = 0;
  1450. m_PageAscender = 0;
  1451. float maxVisibleDescender = 0;
  1452. bool isMaxVisibleDescenderSet = false;
  1453. m_isNewPage = false;
  1454. // Initialize struct to track states of word wrapping
  1455. bool isFirstWordOfLine = true;
  1456. m_isNonBreakingSpace = false;
  1457. bool ignoreNonBreakingSpace = false;
  1458. //bool isLastCharacterCJK = false;
  1459. int lastSoftLineBreak = 0;
  1460. CharacterSubstitution characterToSubstitute = new CharacterSubstitution(-1, 0);
  1461. bool isSoftHyphenIgnored = false;
  1462. // Save character and line state before we begin layout.
  1463. SaveWordWrappingState(ref m_SavedWordWrapState, -1, -1);
  1464. SaveWordWrappingState(ref m_SavedLineState, -1, -1);
  1465. SaveWordWrappingState(ref m_SavedEllipsisState, -1, -1);
  1466. SaveWordWrappingState(ref m_SavedLastValidState, -1, -1);
  1467. SaveWordWrappingState(ref m_SavedSoftLineBreakState, -1, -1);
  1468. m_EllipsisInsertionCandidateStack.Clear();
  1469. // Safety Tracker
  1470. int restoreCount = 0;
  1471. k_GenerateTextPhaseIMarker.Begin();
  1472. // Parse through Character buffer to read HTML tags and begin creating mesh.
  1473. for (int i = 0; i < m_TextProcessingArray.Length && m_TextProcessingArray[i].unicode != 0; i++)
  1474. {
  1475. charCode = m_TextProcessingArray[i].unicode;
  1476. if (restoreCount > 5)
  1477. {
  1478. Debug.LogError("Line breaking recursion max threshold hit... Character [" + charCode + "] index: " + i);
  1479. characterToSubstitute.index = m_characterCount;
  1480. characterToSubstitute.unicode = 0x03;
  1481. }
  1482. // Parse Rich Text Tag
  1483. #region Parse Rich Text Tag
  1484. if (m_isRichText && charCode == 60) // '<'
  1485. {
  1486. k_ParseMarkupTextMarker.Begin();
  1487. m_isParsingText = true;
  1488. m_textElementType = TMP_TextElementType.Character;
  1489. int endTagIndex;
  1490. // Check if Tag is valid. If valid, skip to the end of the validated tag.
  1491. if (ValidateHtmlTag(m_TextProcessingArray, i + 1, out endTagIndex))
  1492. {
  1493. i = endTagIndex;
  1494. // Continue to next character or handle the sprite element
  1495. if (m_textElementType == TMP_TextElementType.Character)
  1496. {
  1497. k_ParseMarkupTextMarker.End();
  1498. continue;
  1499. }
  1500. }
  1501. k_ParseMarkupTextMarker.End();
  1502. }
  1503. else
  1504. {
  1505. m_textElementType = m_textInfo.characterInfo[m_characterCount].elementType;
  1506. m_currentMaterialIndex = m_textInfo.characterInfo[m_characterCount].materialReferenceIndex;
  1507. m_currentFontAsset = m_textInfo.characterInfo[m_characterCount].fontAsset;
  1508. }
  1509. #endregion End Parse Rich Text Tag
  1510. int previousMaterialIndex = m_currentMaterialIndex;
  1511. bool isUsingAltTypeface = m_textInfo.characterInfo[m_characterCount].isUsingAlternateTypeface;
  1512. m_isParsingText = false;
  1513. // Handle potential character substitutions
  1514. #region Character Substitutions
  1515. bool isInjectingCharacter = false;
  1516. if (characterToSubstitute.index == m_characterCount)
  1517. {
  1518. charCode = (int)characterToSubstitute.unicode;
  1519. m_textElementType = TMP_TextElementType.Character;
  1520. isInjectingCharacter = true;
  1521. switch (charCode)
  1522. {
  1523. case 0x03:
  1524. m_textInfo.characterInfo[m_characterCount].textElement = m_currentFontAsset.characterLookupTable[0x03];
  1525. m_isTextTruncated = true;
  1526. break;
  1527. case 0x2D:
  1528. //
  1529. break;
  1530. case 0x2026:
  1531. m_textInfo.characterInfo[m_characterCount].textElement = m_Ellipsis.character;
  1532. m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Character;
  1533. m_textInfo.characterInfo[m_characterCount].fontAsset = m_Ellipsis.fontAsset;
  1534. m_textInfo.characterInfo[m_characterCount].material = m_Ellipsis.material;
  1535. m_textInfo.characterInfo[m_characterCount].materialReferenceIndex = m_Ellipsis.materialIndex;
  1536. // Indicates the source parsing data has been modified.
  1537. m_isTextTruncated = true;
  1538. // End Of Text
  1539. characterToSubstitute.index = m_characterCount + 1;
  1540. characterToSubstitute.unicode = 0x03;
  1541. break;
  1542. }
  1543. }
  1544. #endregion
  1545. // When using Linked text, mark character as ignored and skip to next character.
  1546. #region Linked Text
  1547. if (m_characterCount < m_firstVisibleCharacter && charCode != 0x03)
  1548. {
  1549. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  1550. m_textInfo.characterInfo[m_characterCount].character = (char)0x200B;
  1551. m_textInfo.characterInfo[m_characterCount].lineNumber = 0;
  1552. m_characterCount += 1;
  1553. continue;
  1554. }
  1555. #endregion
  1556. // Handle Font Styles like LowerCase, UpperCase and SmallCaps.
  1557. #region Handling of LowerCase, UpperCase and SmallCaps Font Styles
  1558. float smallCapsMultiplier = 1.0f;
  1559. if (m_textElementType == TMP_TextElementType.Character)
  1560. {
  1561. if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
  1562. {
  1563. // If this character is lowercase, switch to uppercase.
  1564. if (char.IsLower((char)charCode))
  1565. charCode = char.ToUpper((char)charCode);
  1566. }
  1567. else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
  1568. {
  1569. // If this character is uppercase, switch to lowercase.
  1570. if (char.IsUpper((char)charCode))
  1571. charCode = char.ToLower((char)charCode);
  1572. }
  1573. else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
  1574. {
  1575. if (char.IsLower((char)charCode))
  1576. {
  1577. smallCapsMultiplier = 0.8f;
  1578. charCode = char.ToUpper((char)charCode);
  1579. }
  1580. }
  1581. }
  1582. #endregion
  1583. // Look up Character Data from Dictionary and cache it.
  1584. #region Look up Character Data
  1585. k_CharacterLookupMarker.Begin();
  1586. float baselineOffset = 0;
  1587. float elementAscentLine = 0;
  1588. float elementDescentLine = 0;
  1589. if (m_textElementType == TMP_TextElementType.Sprite)
  1590. {
  1591. // If a sprite is used as a fallback then get a reference to it and set the color to white.
  1592. m_currentSpriteAsset = m_textInfo.characterInfo[m_characterCount].spriteAsset;
  1593. m_spriteIndex = m_textInfo.characterInfo[m_characterCount].spriteIndex;
  1594. TMP_SpriteCharacter sprite = m_currentSpriteAsset.spriteCharacterTable[m_spriteIndex];
  1595. if (sprite == null)
  1596. {
  1597. k_CharacterLookupMarker.End();
  1598. continue;
  1599. }
  1600. // Sprites are assigned in the E000 Private Area + sprite Index
  1601. if (charCode == 60)
  1602. charCode = 57344 + m_spriteIndex;
  1603. else
  1604. m_spriteColor = s_colorWhite;
  1605. float fontScale = (m_currentFontSize / m_currentFontAsset.faceInfo.pointSize * m_currentFontAsset.faceInfo.scale * (m_isOrthographic ? 1 : 0.1f));
  1606. // The sprite scale calculations are based on the font asset assigned to the text object.
  1607. if (m_currentSpriteAsset.m_FaceInfo.pointSize > 0)
  1608. {
  1609. float spriteScale = m_currentFontSize / m_currentSpriteAsset.m_FaceInfo.pointSize * m_currentSpriteAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1610. currentElementScale = sprite.m_Scale * sprite.m_Glyph.scale * spriteScale;
  1611. elementAscentLine = m_currentSpriteAsset.m_FaceInfo.ascentLine;
  1612. baselineOffset = m_currentSpriteAsset.m_FaceInfo.baseline * fontScale * m_fontScaleMultiplier * m_currentSpriteAsset.m_FaceInfo.scale;
  1613. elementDescentLine = m_currentSpriteAsset.m_FaceInfo.descentLine;
  1614. }
  1615. else
  1616. {
  1617. float spriteScale = m_currentFontSize / m_currentFontAsset.m_FaceInfo.pointSize * m_currentFontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1618. currentElementScale = m_currentFontAsset.m_FaceInfo.ascentLine / sprite.m_Glyph.metrics.height * sprite.m_Scale * sprite.m_Glyph.scale * spriteScale;
  1619. float scaleDelta = spriteScale / currentElementScale;
  1620. elementAscentLine = m_currentFontAsset.m_FaceInfo.ascentLine * scaleDelta;
  1621. baselineOffset = m_currentFontAsset.m_FaceInfo.baseline * fontScale * m_fontScaleMultiplier * m_currentFontAsset.m_FaceInfo.scale;
  1622. elementDescentLine = m_currentFontAsset.m_FaceInfo.descentLine * scaleDelta;
  1623. }
  1624. m_cached_TextElement = sprite;
  1625. m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Sprite;
  1626. m_textInfo.characterInfo[m_characterCount].scale = currentElementScale;
  1627. m_textInfo.characterInfo[m_characterCount].spriteAsset = m_currentSpriteAsset;
  1628. m_textInfo.characterInfo[m_characterCount].fontAsset = m_currentFontAsset;
  1629. m_textInfo.characterInfo[m_characterCount].materialReferenceIndex = m_currentMaterialIndex;
  1630. m_currentMaterialIndex = previousMaterialIndex;
  1631. padding = 0;
  1632. }
  1633. else if (m_textElementType == TMP_TextElementType.Character)
  1634. {
  1635. m_cached_TextElement = m_textInfo.characterInfo[m_characterCount].textElement;
  1636. if (m_cached_TextElement == null)
  1637. {
  1638. k_CharacterLookupMarker.End();
  1639. continue;
  1640. }
  1641. m_currentFontAsset = m_textInfo.characterInfo[m_characterCount].fontAsset;
  1642. m_currentMaterial = m_textInfo.characterInfo[m_characterCount].material;
  1643. m_currentMaterialIndex = m_textInfo.characterInfo[m_characterCount].materialReferenceIndex;
  1644. // Special handling if replaced character was a line feed where in this case we have to use the scale of the previous character.
  1645. float adjustedScale;
  1646. if (isInjectingCharacter && m_TextProcessingArray[i].unicode == 0x0A && m_characterCount != m_firstCharacterOfLine)
  1647. adjustedScale = m_textInfo.characterInfo[m_characterCount - 1].pointSize * smallCapsMultiplier / m_currentFontAsset.m_FaceInfo.pointSize * m_currentFontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1648. else
  1649. adjustedScale = m_currentFontSize * smallCapsMultiplier / m_currentFontAsset.m_FaceInfo.pointSize * m_currentFontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1650. // Special handling for injected Ellipsis
  1651. if (isInjectingCharacter && charCode == 0x2026)
  1652. {
  1653. elementAscentLine = 0;
  1654. elementDescentLine = 0;
  1655. }
  1656. else
  1657. {
  1658. elementAscentLine = m_currentFontAsset.m_FaceInfo.ascentLine;
  1659. elementDescentLine = m_currentFontAsset.m_FaceInfo.descentLine;
  1660. }
  1661. currentElementScale = adjustedScale * m_fontScaleMultiplier * m_cached_TextElement.m_Scale * m_cached_TextElement.m_Glyph.scale;
  1662. baselineOffset = m_currentFontAsset.m_FaceInfo.baseline * adjustedScale * m_fontScaleMultiplier * m_currentFontAsset.m_FaceInfo.scale;
  1663. m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Character;
  1664. m_textInfo.characterInfo[m_characterCount].scale = currentElementScale;
  1665. padding = m_currentMaterialIndex == 0 ? m_padding : m_subTextObjects[m_currentMaterialIndex].padding;
  1666. }
  1667. k_CharacterLookupMarker.End();
  1668. #endregion
  1669. // Handle Soft Hyphen
  1670. #region Handle Soft Hyphen
  1671. float currentElementUnmodifiedScale = currentElementScale;
  1672. if (charCode == 0xAD || charCode == 0x03)
  1673. currentElementScale = 0;
  1674. #endregion
  1675. // Store some of the text object's information
  1676. m_textInfo.characterInfo[m_characterCount].character = (char)charCode;
  1677. m_textInfo.characterInfo[m_characterCount].pointSize = m_currentFontSize;
  1678. m_textInfo.characterInfo[m_characterCount].color = m_htmlColor;
  1679. m_textInfo.characterInfo[m_characterCount].underlineColor = m_underlineColor;
  1680. m_textInfo.characterInfo[m_characterCount].strikethroughColor = m_strikethroughColor;
  1681. m_textInfo.characterInfo[m_characterCount].highlightState = m_HighlightStateStack.current;
  1682. m_textInfo.characterInfo[m_characterCount].style = m_FontStyleInternal;
  1683. // Cache glyph metrics
  1684. GlyphMetrics currentGlyphMetrics = m_cached_TextElement.m_Glyph.metrics;
  1685. // Optimization to avoid calling this more than once per character.
  1686. bool isWhiteSpace = charCode <= 0xFFFF && char.IsWhiteSpace((char)charCode);
  1687. // Handle Kerning if Enabled.
  1688. #region Handle Kerning
  1689. TMP_GlyphValueRecord glyphAdjustments = new TMP_GlyphValueRecord();
  1690. float characterSpacingAdjustment = m_characterSpacing;
  1691. m_GlyphHorizontalAdvanceAdjustment = 0;
  1692. if (m_enableKerning)
  1693. {
  1694. k_HandleGPOSFeaturesMarker.Begin();
  1695. TMP_GlyphPairAdjustmentRecord adjustmentPair;
  1696. uint baseGlyphIndex = m_cached_TextElement.m_GlyphIndex;
  1697. if (m_characterCount < totalCharacterCount - 1)
  1698. {
  1699. uint nextGlyphIndex = m_textInfo.characterInfo[m_characterCount + 1].textElement.m_GlyphIndex;
  1700. uint key = nextGlyphIndex << 16 | baseGlyphIndex;
  1701. if (m_currentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.TryGetValue(key, out adjustmentPair))
  1702. {
  1703. glyphAdjustments = adjustmentPair.m_FirstAdjustmentRecord.m_GlyphValueRecord;
  1704. characterSpacingAdjustment = (adjustmentPair.m_FeatureLookupFlags & FontFeatureLookupFlags.IgnoreSpacingAdjustments) == FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment;
  1705. }
  1706. }
  1707. if (m_characterCount >= 1)
  1708. {
  1709. uint previousGlyphIndex = m_textInfo.characterInfo[m_characterCount - 1].textElement.m_GlyphIndex;
  1710. uint key = baseGlyphIndex << 16 | previousGlyphIndex;
  1711. if (m_currentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.TryGetValue(key, out adjustmentPair))
  1712. {
  1713. glyphAdjustments += adjustmentPair.m_SecondAdjustmentRecord.m_GlyphValueRecord;
  1714. characterSpacingAdjustment = (adjustmentPair.m_FeatureLookupFlags & FontFeatureLookupFlags.IgnoreSpacingAdjustments) == FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment;
  1715. }
  1716. }
  1717. m_GlyphHorizontalAdvanceAdjustment = glyphAdjustments.xAdvance;
  1718. k_HandleGPOSFeaturesMarker.End();
  1719. }
  1720. #endregion
  1721. // Initial Implementation for RTL support.
  1722. #region Handle Right-to-Left
  1723. if (m_isRightToLeft)
  1724. {
  1725. m_xAdvance -= currentGlyphMetrics.horizontalAdvance * (1 - m_charWidthAdjDelta) * currentElementScale;
  1726. if (isWhiteSpace || charCode == 0x200B)
  1727. m_xAdvance -= m_wordSpacing * currentEmScale;
  1728. }
  1729. #endregion
  1730. // Handle Mono Spacing
  1731. #region Handle Mono Spacing
  1732. float monoAdvance = 0;
  1733. if (m_monoSpacing != 0)
  1734. {
  1735. monoAdvance = (m_monoSpacing / 2 - (currentGlyphMetrics.width / 2 + currentGlyphMetrics.horizontalBearingX) * currentElementScale) * (1 - m_charWidthAdjDelta);
  1736. m_xAdvance += monoAdvance;
  1737. }
  1738. #endregion
  1739. // Set Padding based on selected font style
  1740. #region Handle Style Padding
  1741. if (m_textElementType == TMP_TextElementType.Character && !isUsingAltTypeface && ((m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold)) // Checks for any combination of Bold Style.
  1742. {
  1743. if (m_currentMaterial != null && m_currentMaterial.HasProperty(ShaderUtilities.ID_GradientScale))
  1744. {
  1745. float gradientScale = m_currentMaterial.GetFloat(ShaderUtilities.ID_GradientScale);
  1746. style_padding = m_currentFontAsset.boldStyle / 4.0f * gradientScale * m_currentMaterial.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
  1747. // Clamp overall padding to Gradient Scale size.
  1748. if (style_padding + padding > gradientScale)
  1749. padding = gradientScale - style_padding;
  1750. }
  1751. else
  1752. style_padding = 0;
  1753. boldSpacingAdjustment = m_currentFontAsset.boldSpacing;
  1754. }
  1755. else
  1756. {
  1757. if (m_currentMaterial != null && m_currentMaterial.HasProperty(ShaderUtilities.ID_GradientScale) && m_currentMaterial.HasProperty(ShaderUtilities.ID_ScaleRatio_A))
  1758. {
  1759. float gradientScale = m_currentMaterial.GetFloat(ShaderUtilities.ID_GradientScale);
  1760. style_padding = m_currentFontAsset.normalStyle / 4.0f * gradientScale * m_currentMaterial.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
  1761. // Clamp overall padding to Gradient Scale size.
  1762. if (style_padding + padding > gradientScale)
  1763. padding = gradientScale - style_padding;
  1764. }
  1765. else
  1766. style_padding = 0;
  1767. boldSpacingAdjustment = 0;
  1768. }
  1769. #endregion Handle Style Padding
  1770. // Determine the position of the vertices of the Character or Sprite.
  1771. #region Calculate Vertices Position
  1772. k_CalculateVerticesPositionMarker.Begin();
  1773. Vector3 top_left;
  1774. top_left.x = m_xAdvance + ((currentGlyphMetrics.horizontalBearingX - padding - style_padding + glyphAdjustments.m_XPlacement) * currentElementScale * (1 - m_charWidthAdjDelta));
  1775. top_left.y = baselineOffset + (currentGlyphMetrics.horizontalBearingY + padding + glyphAdjustments.m_YPlacement) * currentElementScale - m_lineOffset + m_baselineOffset;
  1776. top_left.z = 0;
  1777. Vector3 bottom_left;
  1778. bottom_left.x = top_left.x;
  1779. bottom_left.y = top_left.y - ((currentGlyphMetrics.height + padding * 2) * currentElementScale);
  1780. bottom_left.z = 0;
  1781. Vector3 top_right;
  1782. top_right.x = bottom_left.x + ((currentGlyphMetrics.width + padding * 2 + style_padding * 2) * currentElementScale * (1 - m_charWidthAdjDelta));
  1783. top_right.y = top_left.y;
  1784. top_right.z = 0;
  1785. Vector3 bottom_right;
  1786. bottom_right.x = top_right.x;
  1787. bottom_right.y = bottom_left.y;
  1788. bottom_right.z = 0;
  1789. k_CalculateVerticesPositionMarker.End();
  1790. #endregion
  1791. // Check if we need to Shear the rectangles for Italic styles
  1792. #region Handle Italic & Shearing
  1793. if (m_textElementType == TMP_TextElementType.Character && !isUsingAltTypeface && ((m_FontStyleInternal & FontStyles.Italic) == FontStyles.Italic))
  1794. {
  1795. // Shift Top vertices forward by half (Shear Value * height of character) and Bottom vertices back by same amount.
  1796. float shear_value = m_ItalicAngle * 0.01f;
  1797. Vector3 topShear = new Vector3(shear_value * ((currentGlyphMetrics.horizontalBearingY + padding + style_padding) * currentElementScale), 0, 0);
  1798. Vector3 bottomShear = new Vector3(shear_value * (((currentGlyphMetrics.horizontalBearingY - currentGlyphMetrics.height - padding - style_padding)) * currentElementScale), 0, 0);
  1799. Vector3 shearAdjustment = new Vector3((topShear.x - bottomShear.x) / 2, 0, 0);
  1800. top_left = top_left + topShear - shearAdjustment;
  1801. bottom_left = bottom_left + bottomShear - shearAdjustment;
  1802. top_right = top_right + topShear - shearAdjustment;
  1803. bottom_right = bottom_right + bottomShear - shearAdjustment;
  1804. }
  1805. #endregion Handle Italics & Shearing
  1806. // Handle Character Rotation
  1807. #region Handle Character Rotation
  1808. if (m_isFXMatrixSet)
  1809. {
  1810. // Apply scale matrix when simulating Condensed text.
  1811. if (m_FXMatrix.lossyScale.x != 1)
  1812. {
  1813. //top_left = m_FXMatrix.MultiplyPoint3x4(top_left);
  1814. //bottom_left = m_FXMatrix.MultiplyPoint3x4(bottom_left);
  1815. //top_right = m_FXMatrix.MultiplyPoint3x4(top_right);
  1816. //bottom_right = m_FXMatrix.MultiplyPoint3x4(bottom_right);
  1817. }
  1818. Vector3 positionOffset = (top_right + bottom_left) / 2;
  1819. top_left = m_FXMatrix.MultiplyPoint3x4(top_left - positionOffset) + positionOffset;
  1820. bottom_left = m_FXMatrix.MultiplyPoint3x4(bottom_left - positionOffset) + positionOffset;
  1821. top_right = m_FXMatrix.MultiplyPoint3x4(top_right - positionOffset) + positionOffset;
  1822. bottom_right = m_FXMatrix.MultiplyPoint3x4(bottom_right - positionOffset) + positionOffset;
  1823. }
  1824. #endregion
  1825. // Store vertex information for the character or sprite.
  1826. m_textInfo.characterInfo[m_characterCount].bottomLeft = bottom_left;
  1827. m_textInfo.characterInfo[m_characterCount].topLeft = top_left;
  1828. m_textInfo.characterInfo[m_characterCount].topRight = top_right;
  1829. m_textInfo.characterInfo[m_characterCount].bottomRight = bottom_right;
  1830. m_textInfo.characterInfo[m_characterCount].origin = m_xAdvance;
  1831. m_textInfo.characterInfo[m_characterCount].baseLine = baselineOffset - m_lineOffset + m_baselineOffset;
  1832. m_textInfo.characterInfo[m_characterCount].aspectRatio = (top_right.x - bottom_left.x) / (top_left.y - bottom_left.y);
  1833. // Compute text metrics
  1834. #region Compute Ascender & Descender values
  1835. k_ComputeTextMetricsMarker.Begin();
  1836. // Element Ascender in line space
  1837. float elementAscender = m_textElementType == TMP_TextElementType.Character
  1838. ? elementAscentLine * currentElementScale / smallCapsMultiplier + m_baselineOffset
  1839. : elementAscentLine * currentElementScale + m_baselineOffset;
  1840. // Element Descender in line space
  1841. float elementDescender = m_textElementType == TMP_TextElementType.Character
  1842. ? elementDescentLine * currentElementScale / smallCapsMultiplier + m_baselineOffset
  1843. : elementDescentLine * currentElementScale + m_baselineOffset;
  1844. float adjustedAscender = elementAscender;
  1845. float adjustedDescender = elementDescender;
  1846. bool isFirstCharacterOfLine = m_characterCount == m_firstCharacterOfLine;
  1847. // Max line ascender and descender in line space
  1848. if (isFirstCharacterOfLine || isWhiteSpace == false)
  1849. {
  1850. // Special handling for Superscript and Subscript where we use the unadjusted line ascender and descender
  1851. if (m_baselineOffset != 0)
  1852. {
  1853. adjustedAscender = Mathf.Max((elementAscender - m_baselineOffset) / m_fontScaleMultiplier, adjustedAscender);
  1854. adjustedDescender = Mathf.Min((elementDescender - m_baselineOffset) / m_fontScaleMultiplier, adjustedDescender);
  1855. }
  1856. m_maxLineAscender = Mathf.Max(adjustedAscender, m_maxLineAscender);
  1857. m_maxLineDescender = Mathf.Min(adjustedDescender, m_maxLineDescender);
  1858. }
  1859. // Element Ascender and Descender in object space
  1860. if (isFirstCharacterOfLine || isWhiteSpace == false)
  1861. {
  1862. m_textInfo.characterInfo[m_characterCount].adjustedAscender = adjustedAscender;
  1863. m_textInfo.characterInfo[m_characterCount].adjustedDescender = adjustedDescender;
  1864. m_ElementAscender = m_textInfo.characterInfo[m_characterCount].ascender = elementAscender - m_lineOffset;
  1865. m_ElementDescender = m_textInfo.characterInfo[m_characterCount].descender = elementDescender - m_lineOffset;
  1866. }
  1867. else
  1868. {
  1869. m_textInfo.characterInfo[m_characterCount].adjustedAscender = m_maxLineAscender;
  1870. m_textInfo.characterInfo[m_characterCount].adjustedDescender = m_maxLineDescender;
  1871. m_ElementAscender = m_textInfo.characterInfo[m_characterCount].ascender = m_maxLineAscender - m_lineOffset;
  1872. m_ElementDescender = m_textInfo.characterInfo[m_characterCount].descender = m_maxLineDescender - m_lineOffset;
  1873. }
  1874. // Max text object ascender and cap height
  1875. if (m_lineNumber == 0 || m_isNewPage)
  1876. {
  1877. if (isFirstCharacterOfLine || isWhiteSpace == false)
  1878. {
  1879. m_maxTextAscender = m_maxLineAscender;
  1880. m_maxCapHeight = Mathf.Max(m_maxCapHeight, m_currentFontAsset.m_FaceInfo.capLine * currentElementScale / smallCapsMultiplier);
  1881. }
  1882. }
  1883. // Page ascender
  1884. if (m_lineOffset == 0)
  1885. {
  1886. if (isFirstCharacterOfLine || isWhiteSpace == false)
  1887. m_PageAscender = m_PageAscender > elementAscender ? m_PageAscender : elementAscender;
  1888. }
  1889. k_ComputeTextMetricsMarker.End();
  1890. #endregion
  1891. // Set Characters to not visible by default.
  1892. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  1893. bool isJustifiedOrFlush = (m_lineJustification & HorizontalAlignmentOptions.Flush) == HorizontalAlignmentOptions.Flush || (m_lineJustification & HorizontalAlignmentOptions.Justified) == HorizontalAlignmentOptions.Justified;
  1894. // Setup Mesh for visible text elements. ie. not a SPACE / LINEFEED / CARRIAGE RETURN.
  1895. #region Handle Visible Characters
  1896. if (charCode == 9 || (isWhiteSpace == false && charCode != 0x200B && charCode != 0xAD && charCode != 0x03) || (charCode == 0xAD && isSoftHyphenIgnored == false) || m_textElementType == TMP_TextElementType.Sprite)
  1897. {
  1898. k_HandleVisibleCharacterMarker.Begin();
  1899. m_textInfo.characterInfo[m_characterCount].isVisible = true;
  1900. #region Experimental Margin Shaper
  1901. //Vector2 shapedMargins;
  1902. //if (marginShaper)
  1903. //{
  1904. // shapedMargins = m_marginShaper.GetShapedMargins(m_textInfo.characterInfo[m_characterCount].baseLine);
  1905. // if (shapedMargins.x < margins.x)
  1906. // {
  1907. // shapedMargins.x = m_marginLeft;
  1908. // }
  1909. // else
  1910. // {
  1911. // shapedMargins.x += m_marginLeft - margins.x;
  1912. // }
  1913. // if (shapedMargins.y < margins.z)
  1914. // {
  1915. // shapedMargins.y = m_marginRight;
  1916. // }
  1917. // else
  1918. // {
  1919. // shapedMargins.y += m_marginRight - margins.z;
  1920. // }
  1921. //}
  1922. //else
  1923. //{
  1924. // shapedMargins.x = m_marginLeft;
  1925. // shapedMargins.y = m_marginRight;
  1926. //}
  1927. //width = marginWidth + 0.0001f - shapedMargins.x - shapedMargins.y;
  1928. //if (m_width != -1 && m_width < width)
  1929. //{
  1930. // width = m_width;
  1931. //}
  1932. //m_textInfo.lineInfo[m_lineNumber].marginLeft = shapedMargins.x;
  1933. #endregion
  1934. float marginLeft = m_marginLeft;
  1935. float marginRight = m_marginRight;
  1936. // Injected characters do not override margins
  1937. if (isInjectingCharacter)
  1938. {
  1939. marginLeft = m_textInfo.lineInfo[m_lineNumber].marginLeft;
  1940. marginRight = m_textInfo.lineInfo[m_lineNumber].marginRight;
  1941. }
  1942. widthOfTextArea = m_width != -1 ? Mathf.Min(marginWidth + 0.0001f - marginLeft - marginRight, m_width) : marginWidth + 0.0001f - marginLeft - marginRight;
  1943. // Calculate the line breaking width of the text.
  1944. float textWidth = Mathf.Abs(m_xAdvance) + (!m_isRightToLeft ? currentGlyphMetrics.horizontalAdvance : 0) * (1 - m_charWidthAdjDelta) * (charCode == 0xAD ? currentElementUnmodifiedScale : currentElementScale);
  1945. float textHeight = m_maxTextAscender - (m_maxLineDescender - m_lineOffset) + (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0);
  1946. int testedCharacterCount = m_characterCount;
  1947. // Handling of current line Vertical Bounds
  1948. #region Current Line Vertical Bounds Check
  1949. if (textHeight > marginHeight + 0.0001f)
  1950. {
  1951. k_HandleVerticalLineBreakingMarker.Begin();
  1952. // Set isTextOverflowing and firstOverflowCharacterIndex
  1953. if (m_firstOverflowCharacterIndex == -1)
  1954. m_firstOverflowCharacterIndex = m_characterCount;
  1955. // Check if Auto-Size is enabled
  1956. if (m_enableAutoSizing)
  1957. {
  1958. // Handle Line spacing adjustments
  1959. #region Line Spacing Adjustments
  1960. if (m_lineSpacingDelta > m_lineSpacingMax && m_lineOffset > 0 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  1961. {
  1962. float adjustmentDelta = (marginHeight - textHeight) / m_lineNumber;
  1963. m_lineSpacingDelta = Mathf.Max(m_lineSpacingDelta + adjustmentDelta / baseScale, m_lineSpacingMax);
  1964. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Line Spacing. Delta of [" + m_lineSpacingDelta.ToString("f3") + "].");
  1965. k_HandleVerticalLineBreakingMarker.End();
  1966. k_HandleVisibleCharacterMarker.End();
  1967. k_GenerateTextPhaseIMarker.End();
  1968. k_GenerateTextMarker.End();
  1969. return;
  1970. }
  1971. #endregion
  1972. // Handle Text Auto-sizing resulting from text exceeding vertical bounds.
  1973. #region Text Auto-Sizing (Text greater than vertical bounds)
  1974. if (m_fontSize > m_fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  1975. {
  1976. m_maxFontSize = m_fontSize;
  1977. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  1978. m_fontSize -= sizeDelta;
  1979. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  1980. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  1981. k_HandleVerticalLineBreakingMarker.End();
  1982. k_HandleVisibleCharacterMarker.End();
  1983. k_GenerateTextPhaseIMarker.End();
  1984. k_GenerateTextMarker.End();
  1985. return;
  1986. }
  1987. #endregion Text Auto-Sizing
  1988. }
  1989. // Handle Vertical Overflow on current line
  1990. switch (m_overflowMode)
  1991. {
  1992. case TextOverflowModes.Overflow:
  1993. case TextOverflowModes.ScrollRect:
  1994. case TextOverflowModes.Masking:
  1995. // Nothing happens as vertical bounds are ignored in this mode.
  1996. break;
  1997. case TextOverflowModes.Truncate:
  1998. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  1999. characterToSubstitute.index = testedCharacterCount;
  2000. characterToSubstitute.unicode = 0x03;
  2001. k_HandleVerticalLineBreakingMarker.End();
  2002. k_HandleVisibleCharacterMarker.End();
  2003. continue;
  2004. case TextOverflowModes.Ellipsis:
  2005. if (m_EllipsisInsertionCandidateStack.Count == 0)
  2006. {
  2007. i = -1;
  2008. m_characterCount = 0;
  2009. characterToSubstitute.index = 0;
  2010. characterToSubstitute.unicode = 0x03;
  2011. m_firstCharacterOfLine = 0;
  2012. k_HandleVerticalLineBreakingMarker.End();
  2013. k_HandleVisibleCharacterMarker.End();
  2014. continue;
  2015. }
  2016. var ellipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2017. i = RestoreWordWrappingState(ref ellipsisState);
  2018. i -= 1;
  2019. m_characterCount -= 1;
  2020. characterToSubstitute.index = m_characterCount;
  2021. characterToSubstitute.unicode = 0x2026;
  2022. restoreCount += 1;
  2023. k_HandleVerticalLineBreakingMarker.End();
  2024. k_HandleVisibleCharacterMarker.End();
  2025. continue;
  2026. case TextOverflowModes.Linked:
  2027. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2028. if (m_linkedTextComponent != null)
  2029. {
  2030. m_linkedTextComponent.text = text;
  2031. m_linkedTextComponent.m_inputSource = m_inputSource;
  2032. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2033. m_linkedTextComponent.ForceMeshUpdate();
  2034. m_isTextTruncated = true;
  2035. }
  2036. // Truncate remaining text
  2037. characterToSubstitute.index = testedCharacterCount;
  2038. characterToSubstitute.unicode = 0x03;
  2039. k_HandleVerticalLineBreakingMarker.End();
  2040. k_HandleVisibleCharacterMarker.End();
  2041. continue;
  2042. case TextOverflowModes.Page:
  2043. // End layout of text if first character / page doesn't fit.
  2044. if (i < 0 || testedCharacterCount == 0)
  2045. {
  2046. i = -1;
  2047. m_characterCount = 0;
  2048. characterToSubstitute.index = 0;
  2049. characterToSubstitute.unicode = 0x03;
  2050. k_HandleVerticalLineBreakingMarker.End();
  2051. k_HandleVisibleCharacterMarker.End();
  2052. continue;
  2053. }
  2054. else if (m_maxLineAscender - m_maxLineDescender > marginHeight + 0.0001f)
  2055. {
  2056. // Current line exceeds the height of the text container
  2057. // as such we stop on the previous line.
  2058. i = RestoreWordWrappingState(ref m_SavedLineState);
  2059. characterToSubstitute.index = testedCharacterCount;
  2060. characterToSubstitute.unicode = 0x03;
  2061. k_HandleVerticalLineBreakingMarker.End();
  2062. k_HandleVisibleCharacterMarker.End();
  2063. continue;
  2064. }
  2065. // Go back to previous line and re-layout
  2066. i = RestoreWordWrappingState(ref m_SavedLineState);
  2067. m_isNewPage = true;
  2068. m_firstCharacterOfLine = m_characterCount;
  2069. m_maxLineAscender = k_LargeNegativeFloat;
  2070. m_maxLineDescender = k_LargePositiveFloat;
  2071. m_startOfLineAscender = 0;
  2072. m_xAdvance = 0 + tag_Indent;
  2073. m_lineOffset = 0;
  2074. m_maxTextAscender = 0;
  2075. m_PageAscender = 0;
  2076. m_lineNumber += 1;
  2077. m_pageNumber += 1;
  2078. // Should consider saving page data here
  2079. k_HandleVerticalLineBreakingMarker.End();
  2080. k_HandleVisibleCharacterMarker.End();
  2081. continue;
  2082. }
  2083. k_HandleVerticalLineBreakingMarker.End();
  2084. }
  2085. #endregion
  2086. // Handling of Horizontal Bounds
  2087. #region Current Line Horizontal Bounds Check
  2088. if (textWidth > widthOfTextArea * (isJustifiedOrFlush ? 1.05f : 1.0f))
  2089. {
  2090. k_HandleHorizontalLineBreakingMarker.Begin();
  2091. // Handle Line Breaking (if still possible)
  2092. if (m_enableWordWrapping && m_characterCount != m_firstCharacterOfLine)
  2093. {
  2094. // Restore state to previous safe line breaking
  2095. i = RestoreWordWrappingState(ref m_SavedWordWrapState);
  2096. // Compute potential new line offset in the event a line break is needed.
  2097. float lineOffsetDelta = 0;
  2098. if (m_lineHeight == TMP_Math.FLOAT_UNSET)
  2099. {
  2100. float ascender = m_textInfo.characterInfo[m_characterCount].adjustedAscender;
  2101. lineOffsetDelta = (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0) - m_maxLineDescender + ascender + (lineGap + m_lineSpacingDelta) * baseScale + m_lineSpacing * currentEmScale;
  2102. }
  2103. else
  2104. {
  2105. lineOffsetDelta = m_lineHeight + m_lineSpacing * currentEmScale;
  2106. m_IsDrivenLineSpacing = true;
  2107. }
  2108. // Calculate new text height
  2109. float newTextHeight = m_maxTextAscender + lineOffsetDelta + m_lineOffset - m_textInfo.characterInfo[m_characterCount].adjustedDescender;
  2110. // Replace Soft Hyphen by Hyphen Minus 0x2D
  2111. #region Handle Soft Hyphenation
  2112. if (m_textInfo.characterInfo[m_characterCount - 1].character == 0xAD && isSoftHyphenIgnored == false)
  2113. {
  2114. // Only inject Hyphen Minus if new line is possible
  2115. if (m_overflowMode == TextOverflowModes.Overflow || newTextHeight < marginHeight + 0.0001f)
  2116. {
  2117. characterToSubstitute.index = m_characterCount - 1;
  2118. characterToSubstitute.unicode = 0x2D;
  2119. i -= 1;
  2120. m_characterCount -= 1;
  2121. k_HandleHorizontalLineBreakingMarker.End();
  2122. k_HandleVisibleCharacterMarker.End();
  2123. continue;
  2124. }
  2125. }
  2126. isSoftHyphenIgnored = false;
  2127. // Ignore Soft Hyphen to prevent it from wrapping
  2128. if (m_textInfo.characterInfo[m_characterCount].character == 0xAD)
  2129. {
  2130. isSoftHyphenIgnored = true;
  2131. k_HandleHorizontalLineBreakingMarker.End();
  2132. k_HandleVisibleCharacterMarker.End();
  2133. continue;
  2134. }
  2135. #endregion
  2136. // Adjust character spacing before breaking up word if auto size is enabled
  2137. if (m_enableAutoSizing && isFirstWordOfLine)
  2138. {
  2139. // Handle Character Width Adjustments
  2140. #region Character Width Adjustments
  2141. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2142. {
  2143. float adjustedTextWidth = textWidth;
  2144. // Determine full width of the text
  2145. if (m_charWidthAdjDelta > 0)
  2146. adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2147. float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2148. m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2149. m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2150. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2151. k_HandleHorizontalLineBreakingMarker.End();
  2152. k_HandleVisibleCharacterMarker.End();
  2153. k_GenerateTextPhaseIMarker.End();
  2154. k_GenerateTextMarker.End();
  2155. return;
  2156. }
  2157. #endregion
  2158. // Handle Text Auto-sizing resulting from text exceeding vertical bounds.
  2159. #region Text Auto-Sizing (Text greater than vertical bounds)
  2160. if (m_fontSize > m_fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2161. {
  2162. m_maxFontSize = m_fontSize;
  2163. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2164. m_fontSize -= sizeDelta;
  2165. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2166. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2167. k_HandleHorizontalLineBreakingMarker.End();
  2168. k_HandleVisibleCharacterMarker.End();
  2169. k_GenerateTextPhaseIMarker.End();
  2170. k_GenerateTextMarker.End();
  2171. return;
  2172. }
  2173. #endregion Text Auto-Sizing
  2174. }
  2175. // Special handling if first word of line and non breaking space
  2176. int savedSoftLineBreakingSpace = m_SavedSoftLineBreakState.previous_WordBreak;
  2177. if (isFirstWordOfLine && savedSoftLineBreakingSpace != -1)
  2178. {
  2179. if (savedSoftLineBreakingSpace != lastSoftLineBreak)
  2180. {
  2181. i = RestoreWordWrappingState(ref m_SavedSoftLineBreakState);
  2182. lastSoftLineBreak = savedSoftLineBreakingSpace;
  2183. // check if soft hyphen
  2184. if (m_textInfo.characterInfo[m_characterCount - 1].character == 0xAD)
  2185. {
  2186. characterToSubstitute.index = m_characterCount - 1;
  2187. characterToSubstitute.unicode = 0x2D;
  2188. i -= 1;
  2189. m_characterCount -= 1;
  2190. k_HandleHorizontalLineBreakingMarker.End();
  2191. k_HandleVisibleCharacterMarker.End();
  2192. continue;
  2193. }
  2194. }
  2195. }
  2196. // Determine if new line of text would exceed the vertical bounds of text container
  2197. if (newTextHeight > marginHeight + 0.0001f)
  2198. {
  2199. k_HandleVerticalLineBreakingMarker.Begin();
  2200. // Set isTextOverflowing and firstOverflowCharacterIndex
  2201. if (m_firstOverflowCharacterIndex == -1)
  2202. m_firstOverflowCharacterIndex = m_characterCount;
  2203. // Check if Auto-Size is enabled
  2204. if (m_enableAutoSizing)
  2205. {
  2206. // Handle Line spacing adjustments
  2207. #region Line Spacing Adjustments
  2208. if (m_lineSpacingDelta > m_lineSpacingMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2209. {
  2210. float adjustmentDelta = (marginHeight - newTextHeight) / (m_lineNumber + 1);
  2211. m_lineSpacingDelta = Mathf.Max(m_lineSpacingDelta + adjustmentDelta / baseScale, m_lineSpacingMax);
  2212. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Line Spacing. Delta of [" + m_lineSpacingDelta.ToString("f3") + "].");
  2213. k_HandleVerticalLineBreakingMarker.End();
  2214. k_HandleHorizontalLineBreakingMarker.End();
  2215. k_HandleVisibleCharacterMarker.End();
  2216. k_GenerateTextPhaseIMarker.End();
  2217. k_GenerateTextMarker.End();
  2218. return;
  2219. }
  2220. #endregion
  2221. // Handle Character Width Adjustments
  2222. #region Character Width Adjustments
  2223. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2224. {
  2225. float adjustedTextWidth = textWidth;
  2226. // Determine full width of the text
  2227. if (m_charWidthAdjDelta > 0)
  2228. adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2229. float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2230. m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2231. m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2232. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2233. k_HandleVerticalLineBreakingMarker.End();
  2234. k_HandleHorizontalLineBreakingMarker.End();
  2235. k_HandleVisibleCharacterMarker.End();
  2236. k_GenerateTextPhaseIMarker.End();
  2237. k_GenerateTextMarker.End();
  2238. return;
  2239. }
  2240. #endregion
  2241. // Handle Text Auto-sizing resulting from text exceeding vertical bounds.
  2242. #region Text Auto-Sizing (Text greater than vertical bounds)
  2243. if (m_fontSize > m_fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2244. {
  2245. m_maxFontSize = m_fontSize;
  2246. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2247. m_fontSize -= sizeDelta;
  2248. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2249. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2250. k_HandleVerticalLineBreakingMarker.End();
  2251. k_HandleHorizontalLineBreakingMarker.End();
  2252. k_HandleVisibleCharacterMarker.End();
  2253. k_GenerateTextPhaseIMarker.End();
  2254. k_GenerateTextMarker.End();
  2255. return;
  2256. }
  2257. #endregion Text Auto-Sizing
  2258. }
  2259. // Check Text Overflow Modes
  2260. switch (m_overflowMode)
  2261. {
  2262. case TextOverflowModes.Overflow:
  2263. case TextOverflowModes.ScrollRect:
  2264. case TextOverflowModes.Masking:
  2265. InsertNewLine(i, baseScale, currentElementScale, currentEmScale, m_GlyphHorizontalAdvanceAdjustment, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender);
  2266. isStartOfNewLine = true;
  2267. isFirstWordOfLine = true;
  2268. k_HandleVerticalLineBreakingMarker.End();
  2269. k_HandleHorizontalLineBreakingMarker.End();
  2270. k_HandleVisibleCharacterMarker.End();
  2271. continue;
  2272. case TextOverflowModes.Truncate:
  2273. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2274. characterToSubstitute.index = testedCharacterCount;
  2275. characterToSubstitute.unicode = 0x03;
  2276. k_HandleVerticalLineBreakingMarker.End();
  2277. k_HandleHorizontalLineBreakingMarker.End();
  2278. k_HandleVisibleCharacterMarker.End();
  2279. continue;
  2280. case TextOverflowModes.Ellipsis:
  2281. if (m_EllipsisInsertionCandidateStack.Count == 0)
  2282. {
  2283. i = -1;
  2284. m_characterCount = 0;
  2285. characterToSubstitute.index = 0;
  2286. characterToSubstitute.unicode = 0x03;
  2287. m_firstCharacterOfLine = 0;
  2288. k_HandleVerticalLineBreakingMarker.End();
  2289. k_HandleHorizontalLineBreakingMarker.End();
  2290. k_HandleVisibleCharacterMarker.End();
  2291. continue;
  2292. }
  2293. var ellipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2294. i = RestoreWordWrappingState(ref ellipsisState);
  2295. i -= 1;
  2296. m_characterCount -= 1;
  2297. characterToSubstitute.index = m_characterCount;
  2298. characterToSubstitute.unicode = 0x2026;
  2299. restoreCount += 1;
  2300. k_HandleVerticalLineBreakingMarker.End();
  2301. k_HandleHorizontalLineBreakingMarker.End();
  2302. k_HandleVisibleCharacterMarker.End();
  2303. continue;
  2304. case TextOverflowModes.Linked:
  2305. if (m_linkedTextComponent != null)
  2306. {
  2307. m_linkedTextComponent.text = text;
  2308. m_linkedTextComponent.m_inputSource = m_inputSource;
  2309. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2310. m_linkedTextComponent.ForceMeshUpdate();
  2311. m_isTextTruncated = true;
  2312. }
  2313. // Truncate remaining text
  2314. characterToSubstitute.index = m_characterCount;
  2315. characterToSubstitute.unicode = 0x03;
  2316. k_HandleVerticalLineBreakingMarker.End();
  2317. k_HandleHorizontalLineBreakingMarker.End();
  2318. k_HandleVisibleCharacterMarker.End();
  2319. continue;
  2320. case TextOverflowModes.Page:
  2321. // Add new page
  2322. m_isNewPage = true;
  2323. InsertNewLine(i, baseScale, currentElementScale, currentEmScale, m_GlyphHorizontalAdvanceAdjustment, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender);
  2324. m_startOfLineAscender = 0;
  2325. m_lineOffset = 0;
  2326. m_maxTextAscender = 0;
  2327. m_PageAscender = 0;
  2328. m_pageNumber += 1;
  2329. isStartOfNewLine = true;
  2330. isFirstWordOfLine = true;
  2331. k_HandleVerticalLineBreakingMarker.End();
  2332. k_HandleHorizontalLineBreakingMarker.End();
  2333. k_HandleVisibleCharacterMarker.End();
  2334. continue;
  2335. }
  2336. }
  2337. else
  2338. {
  2339. //if (m_enableAutoSizing && isFirstWordOfLine)
  2340. //{
  2341. // // Handle Character Width Adjustments
  2342. // #region Character Width Adjustments
  2343. // if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2344. // {
  2345. // //m_AutoSizeIterationCount = 0;
  2346. // float adjustedTextWidth = textWidth;
  2347. // // Determine full width of the text
  2348. // if (m_charWidthAdjDelta > 0)
  2349. // adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2350. // float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2351. // m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2352. // m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2353. // //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2354. // GenerateTextMesh();
  2355. // return;
  2356. // }
  2357. // #endregion
  2358. //}
  2359. // New line of text does not exceed vertical bounds of text container
  2360. InsertNewLine(i, baseScale, currentElementScale, currentEmScale, m_GlyphHorizontalAdvanceAdjustment, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender);
  2361. isStartOfNewLine = true;
  2362. isFirstWordOfLine = true;
  2363. k_HandleHorizontalLineBreakingMarker.End();
  2364. k_HandleVisibleCharacterMarker.End();
  2365. continue;
  2366. }
  2367. }
  2368. else
  2369. {
  2370. if (m_enableAutoSizing && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2371. {
  2372. // Handle Character Width Adjustments
  2373. #region Character Width Adjustments
  2374. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100)
  2375. {
  2376. float adjustedTextWidth = textWidth;
  2377. // Determine full width of the text
  2378. if (m_charWidthAdjDelta > 0)
  2379. adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2380. float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2381. m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2382. m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2383. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2384. k_HandleHorizontalLineBreakingMarker.End();
  2385. k_HandleVisibleCharacterMarker.End();
  2386. k_GenerateTextPhaseIMarker.End();
  2387. k_GenerateTextMarker.End();
  2388. return;
  2389. }
  2390. #endregion
  2391. // Handle Text Auto-sizing resulting from text exceeding horizontal bounds.
  2392. #region Text Exceeds Horizontal Bounds - Reducing Point Size
  2393. if (m_fontSize > m_fontSizeMin)
  2394. {
  2395. // Reset character width adjustment delta
  2396. //m_charWidthAdjDelta = 0;
  2397. // Adjust Point Size
  2398. m_maxFontSize = m_fontSize;
  2399. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2400. m_fontSize -= sizeDelta;
  2401. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2402. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2403. k_HandleHorizontalLineBreakingMarker.End();
  2404. k_HandleVisibleCharacterMarker.End();
  2405. k_GenerateTextPhaseIMarker.End();
  2406. k_GenerateTextMarker.End();
  2407. return;
  2408. }
  2409. #endregion
  2410. }
  2411. // Check Text Overflow Modes
  2412. switch (m_overflowMode)
  2413. {
  2414. case TextOverflowModes.Overflow:
  2415. case TextOverflowModes.ScrollRect:
  2416. case TextOverflowModes.Masking:
  2417. // Nothing happens as horizontal bounds are ignored in this mode.
  2418. break;
  2419. case TextOverflowModes.Truncate:
  2420. i = RestoreWordWrappingState(ref m_SavedWordWrapState);
  2421. characterToSubstitute.index = testedCharacterCount;
  2422. characterToSubstitute.unicode = 0x03;
  2423. k_HandleHorizontalLineBreakingMarker.End();
  2424. k_HandleVisibleCharacterMarker.End();
  2425. continue;
  2426. case TextOverflowModes.Ellipsis:
  2427. if (m_EllipsisInsertionCandidateStack.Count == 0)
  2428. {
  2429. i = -1;
  2430. m_characterCount = 0;
  2431. characterToSubstitute.index = 0;
  2432. characterToSubstitute.unicode = 0x03;
  2433. m_firstCharacterOfLine = 0;
  2434. k_HandleHorizontalLineBreakingMarker.End();
  2435. k_HandleVisibleCharacterMarker.End();
  2436. continue;
  2437. }
  2438. var ellipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2439. i = RestoreWordWrappingState(ref ellipsisState);
  2440. i -= 1;
  2441. m_characterCount -= 1;
  2442. characterToSubstitute.index = m_characterCount;
  2443. characterToSubstitute.unicode = 0x2026;
  2444. restoreCount += 1;
  2445. k_HandleHorizontalLineBreakingMarker.End();
  2446. k_HandleVisibleCharacterMarker.End();
  2447. continue;
  2448. case TextOverflowModes.Linked:
  2449. i = RestoreWordWrappingState(ref m_SavedWordWrapState);
  2450. if (m_linkedTextComponent != null)
  2451. {
  2452. m_linkedTextComponent.text = text;
  2453. m_linkedTextComponent.m_inputSource = m_inputSource;
  2454. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2455. m_linkedTextComponent.ForceMeshUpdate();
  2456. m_isTextTruncated = true;
  2457. }
  2458. // Truncate text the overflows the vertical bounds
  2459. characterToSubstitute.index = m_characterCount;
  2460. characterToSubstitute.unicode = 0x03;
  2461. k_HandleHorizontalLineBreakingMarker.End();
  2462. k_HandleVisibleCharacterMarker.End();
  2463. continue;
  2464. }
  2465. }
  2466. k_HandleHorizontalLineBreakingMarker.End();
  2467. }
  2468. #endregion
  2469. // Special handling of characters that are not ignored at the end of a line.
  2470. if (charCode == 9)
  2471. {
  2472. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  2473. m_lastVisibleCharacterOfLine = m_characterCount;
  2474. m_textInfo.lineInfo[m_lineNumber].spaceCount += 1;
  2475. m_textInfo.spaceCount += 1;
  2476. }
  2477. else if (charCode == 0xAD)
  2478. {
  2479. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  2480. }
  2481. else
  2482. {
  2483. // Determine Vertex Color
  2484. if (m_overrideHtmlColors)
  2485. vertexColor = m_fontColor32;
  2486. else
  2487. vertexColor = m_htmlColor;
  2488. k_SaveGlyphVertexDataMarker.Begin();
  2489. // Store Character & Sprite Vertex Information
  2490. if (m_textElementType == TMP_TextElementType.Character)
  2491. {
  2492. // Save Character Vertex Data
  2493. SaveGlyphVertexInfo(padding, style_padding, vertexColor);
  2494. }
  2495. else if (m_textElementType == TMP_TextElementType.Sprite)
  2496. {
  2497. SaveSpriteVertexInfo(vertexColor);
  2498. }
  2499. k_SaveGlyphVertexDataMarker.End();
  2500. if (isStartOfNewLine)
  2501. {
  2502. isStartOfNewLine = false;
  2503. m_firstVisibleCharacterOfLine = m_characterCount;
  2504. }
  2505. m_lineVisibleCharacterCount += 1;
  2506. m_lastVisibleCharacterOfLine = m_characterCount;
  2507. m_textInfo.lineInfo[m_lineNumber].marginLeft = marginLeft;
  2508. m_textInfo.lineInfo[m_lineNumber].marginRight = marginRight;
  2509. }
  2510. k_HandleVisibleCharacterMarker.End();
  2511. }
  2512. else
  2513. {
  2514. k_HandleWhiteSpacesMarker.Begin();
  2515. // Special handling for text overflow linked mode
  2516. #region Check Vertical Bounds
  2517. if (m_overflowMode == TextOverflowModes.Linked && (charCode == 10 || charCode == 11))
  2518. {
  2519. float textHeight = m_maxTextAscender - (m_maxLineDescender - m_lineOffset) + (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0);
  2520. int testedCharacterCount = m_characterCount;
  2521. if (textHeight > marginHeight + 0.0001f)
  2522. {
  2523. // Set isTextOverflowing and firstOverflowCharacterIndex
  2524. if (m_firstOverflowCharacterIndex == -1)
  2525. m_firstOverflowCharacterIndex = m_characterCount;
  2526. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2527. if (m_linkedTextComponent != null)
  2528. {
  2529. m_linkedTextComponent.text = text;
  2530. m_linkedTextComponent.m_inputSource = m_inputSource;
  2531. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2532. m_linkedTextComponent.ForceMeshUpdate();
  2533. m_isTextTruncated = true;
  2534. }
  2535. // Truncate remaining text
  2536. characterToSubstitute.index = testedCharacterCount;
  2537. characterToSubstitute.unicode = 0x03;
  2538. k_HandleWhiteSpacesMarker.End();
  2539. continue;
  2540. }
  2541. }
  2542. #endregion
  2543. // Track # of spaces per line which is used for line justification.
  2544. if ((charCode == 10 || charCode == 11 || charCode == 0xA0 || charCode == 0x2007 || charCode == 0x2028 || charCode == 0x2029 || char.IsSeparator((char)charCode)) && charCode != 0xAD && charCode != 0x200B && charCode != 0x2060)
  2545. {
  2546. m_textInfo.lineInfo[m_lineNumber].spaceCount += 1;
  2547. m_textInfo.spaceCount += 1;
  2548. }
  2549. if (charCode == 0xA0)
  2550. m_textInfo.lineInfo[m_lineNumber].controlCharacterCount += 1;
  2551. k_HandleWhiteSpacesMarker.End();
  2552. }
  2553. #endregion Handle Visible Characters
  2554. // Tracking of potential insertion positions for Ellipsis character
  2555. #region Track Potential Insertion Location for Ellipsis
  2556. if (m_overflowMode == TextOverflowModes.Ellipsis && (isInjectingCharacter == false || charCode == 0x2D))
  2557. {
  2558. float fontScale = m_currentFontSize / m_Ellipsis.fontAsset.m_FaceInfo.pointSize * m_Ellipsis.fontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  2559. float scale = fontScale * m_fontScaleMultiplier * m_Ellipsis.character.m_Scale * m_Ellipsis.character.m_Glyph.scale;
  2560. float marginLeft = m_marginLeft;
  2561. float marginRight = m_marginRight;
  2562. // Use the scale and margins of the previous character if Line Feed (LF) is not the first character of a line.
  2563. if (charCode == 0x0A && m_characterCount != m_firstCharacterOfLine)
  2564. {
  2565. fontScale = m_textInfo.characterInfo[m_characterCount - 1].pointSize / m_Ellipsis.fontAsset.m_FaceInfo.pointSize * m_Ellipsis.fontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  2566. scale = fontScale * m_fontScaleMultiplier * m_Ellipsis.character.m_Scale * m_Ellipsis.character.m_Glyph.scale;
  2567. marginLeft = m_textInfo.lineInfo[m_lineNumber].marginLeft;
  2568. marginRight = m_textInfo.lineInfo[m_lineNumber].marginRight;
  2569. }
  2570. float textHeight = m_maxTextAscender - (m_maxLineDescender - m_lineOffset) + (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0);
  2571. float textWidth = Mathf.Abs(m_xAdvance) + (!m_isRightToLeft ? m_Ellipsis.character.m_Glyph.metrics.horizontalAdvance : 0) * (1 - m_charWidthAdjDelta) * scale;
  2572. float widthOfTextAreaForEllipsis = m_width != -1 ? Mathf.Min(marginWidth + 0.0001f - marginLeft - marginRight, m_width) : marginWidth + 0.0001f - marginLeft - marginRight;
  2573. if (textWidth < widthOfTextAreaForEllipsis * (isJustifiedOrFlush ? 1.05f : 1.0f) && textHeight < marginHeight + 0.0001f)
  2574. {
  2575. SaveWordWrappingState(ref m_SavedEllipsisState, i, m_characterCount);
  2576. m_EllipsisInsertionCandidateStack.Push(m_SavedEllipsisState);
  2577. }
  2578. }
  2579. #endregion
  2580. // Store Rectangle positions for each Character.
  2581. #region Store Character Data
  2582. m_textInfo.characterInfo[m_characterCount].lineNumber = m_lineNumber;
  2583. m_textInfo.characterInfo[m_characterCount].pageNumber = m_pageNumber;
  2584. if (charCode != 10 && charCode != 11 && charCode != 13 && isInjectingCharacter == false /* && charCode != 8230 */ || m_textInfo.lineInfo[m_lineNumber].characterCount == 1)
  2585. m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
  2586. #endregion Store Character Data
  2587. // Handle xAdvance & Tabulation Stops. Tab stops at every 25% of Font Size.
  2588. #region XAdvance, Tabulation & Stops
  2589. k_ComputeCharacterAdvanceMarker.Begin();
  2590. if (charCode == 9)
  2591. {
  2592. float tabSize = m_currentFontAsset.m_FaceInfo.tabWidth * m_currentFontAsset.tabSize * currentElementScale;
  2593. float tabs = Mathf.Ceil(m_xAdvance / tabSize) * tabSize;
  2594. m_xAdvance = tabs > m_xAdvance ? tabs : m_xAdvance + tabSize;
  2595. }
  2596. else if (m_monoSpacing != 0)
  2597. {
  2598. m_xAdvance += (m_monoSpacing - monoAdvance + ((m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment) * currentEmScale) + m_cSpacing) * (1 - m_charWidthAdjDelta);
  2599. if (isWhiteSpace || charCode == 0x200B)
  2600. m_xAdvance += m_wordSpacing * currentEmScale;
  2601. }
  2602. else if (m_isRightToLeft)
  2603. {
  2604. m_xAdvance -= ((glyphAdjustments.m_XAdvance * currentElementScale + (m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_cSpacing) * (1 - m_charWidthAdjDelta));
  2605. if (isWhiteSpace || charCode == 0x200B)
  2606. m_xAdvance -= m_wordSpacing * currentEmScale;
  2607. }
  2608. else
  2609. {
  2610. float scaleFXMultiplier = 1;
  2611. if (m_isFXMatrixSet) scaleFXMultiplier = m_FXMatrix.lossyScale.x;
  2612. m_xAdvance += ((currentGlyphMetrics.horizontalAdvance * scaleFXMultiplier + glyphAdjustments.m_XAdvance) * currentElementScale + (m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_cSpacing) * (1 - m_charWidthAdjDelta);
  2613. if (isWhiteSpace || charCode == 0x200B)
  2614. m_xAdvance += m_wordSpacing * currentEmScale;
  2615. }
  2616. // Store xAdvance information
  2617. m_textInfo.characterInfo[m_characterCount].xAdvance = m_xAdvance;
  2618. k_ComputeCharacterAdvanceMarker.End();
  2619. #endregion Tabulation & Stops
  2620. // Handle Carriage Return
  2621. #region Carriage Return
  2622. if (charCode == 13)
  2623. {
  2624. k_HandleCarriageReturnMarker.Begin();
  2625. m_xAdvance = 0 + tag_Indent;
  2626. k_HandleCarriageReturnMarker.End();
  2627. }
  2628. #endregion Carriage Return
  2629. // Handle Line Spacing Adjustments + Word Wrapping & special case for last line.
  2630. #region Check for Line Feed and Last Character
  2631. if (charCode == 10 || charCode == 11 || charCode == 0x03 || charCode == 0x2028 || charCode == 0x2029 || (charCode == 0x2D && isInjectingCharacter) || m_characterCount == totalCharacterCount - 1)
  2632. {
  2633. k_HandleLineTerminationMarker.Begin();
  2634. // Adjust current line spacing (if necessary) before inserting new line
  2635. float baselineAdjustmentDelta = m_maxLineAscender - m_startOfLineAscender;
  2636. if (m_lineOffset > 0 && Math.Abs(baselineAdjustmentDelta) > 0.01f && m_IsDrivenLineSpacing == false && !m_isNewPage)
  2637. {
  2638. //Debug.Log("Line Feed - Adjusting Line Spacing on line #" + m_lineNumber);
  2639. AdjustLineOffset(m_firstCharacterOfLine, m_characterCount, baselineAdjustmentDelta);
  2640. m_ElementDescender -= baselineAdjustmentDelta;
  2641. m_lineOffset += baselineAdjustmentDelta;
  2642. // Adjust saved ellipsis state only if we are adjusting the same line number
  2643. if (m_SavedEllipsisState.lineNumber == m_lineNumber)
  2644. {
  2645. m_SavedEllipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2646. m_SavedEllipsisState.startOfLineAscender += baselineAdjustmentDelta;
  2647. m_SavedEllipsisState.lineOffset += baselineAdjustmentDelta;
  2648. m_EllipsisInsertionCandidateStack.Push(m_SavedEllipsisState);
  2649. }
  2650. }
  2651. m_isNewPage = false;
  2652. // Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well.
  2653. float lineAscender = m_maxLineAscender - m_lineOffset;
  2654. float lineDescender = m_maxLineDescender - m_lineOffset;
  2655. // Update maxDescender and maxVisibleDescender
  2656. m_ElementDescender = m_ElementDescender < lineDescender ? m_ElementDescender : lineDescender;
  2657. if (!isMaxVisibleDescenderSet)
  2658. maxVisibleDescender = m_ElementDescender;
  2659. if (m_useMaxVisibleDescender && (m_characterCount >= m_maxVisibleCharacters || m_lineNumber >= m_maxVisibleLines))
  2660. isMaxVisibleDescenderSet = true;
  2661. // Save Line Information
  2662. m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex = m_firstCharacterOfLine;
  2663. m_textInfo.lineInfo[m_lineNumber].firstVisibleCharacterIndex = m_firstVisibleCharacterOfLine = m_firstCharacterOfLine > m_firstVisibleCharacterOfLine ? m_firstCharacterOfLine : m_firstVisibleCharacterOfLine;
  2664. m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex = m_lastCharacterOfLine = m_characterCount;
  2665. m_textInfo.lineInfo[m_lineNumber].lastVisibleCharacterIndex = m_lastVisibleCharacterOfLine = m_lastVisibleCharacterOfLine < m_firstVisibleCharacterOfLine ? m_firstVisibleCharacterOfLine : m_lastVisibleCharacterOfLine;
  2666. m_textInfo.lineInfo[m_lineNumber].characterCount = m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex - m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex + 1;
  2667. m_textInfo.lineInfo[m_lineNumber].visibleCharacterCount = m_lineVisibleCharacterCount;
  2668. m_textInfo.lineInfo[m_lineNumber].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_firstVisibleCharacterOfLine].bottomLeft.x, lineDescender);
  2669. m_textInfo.lineInfo[m_lineNumber].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].topRight.x, lineAscender);
  2670. m_textInfo.lineInfo[m_lineNumber].length = m_textInfo.lineInfo[m_lineNumber].lineExtents.max.x - (padding * currentElementScale);
  2671. m_textInfo.lineInfo[m_lineNumber].width = widthOfTextArea;
  2672. if (m_textInfo.lineInfo[m_lineNumber].characterCount == 1)
  2673. m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
  2674. float maxAdvanceOffset = ((m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale - m_cSpacing) * (1 - m_charWidthAdjDelta);
  2675. if (m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].isVisible)
  2676. m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].xAdvance + (m_isRightToLeft ? maxAdvanceOffset : - maxAdvanceOffset);
  2677. else
  2678. m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastCharacterOfLine].xAdvance + (m_isRightToLeft ? maxAdvanceOffset : - maxAdvanceOffset);
  2679. m_textInfo.lineInfo[m_lineNumber].baseline = 0 - m_lineOffset;
  2680. m_textInfo.lineInfo[m_lineNumber].ascender = lineAscender;
  2681. m_textInfo.lineInfo[m_lineNumber].descender = lineDescender;
  2682. m_textInfo.lineInfo[m_lineNumber].lineHeight = lineAscender - lineDescender + lineGap * baseScale;
  2683. // Add new line if not last line or character.
  2684. if (charCode == 10 || charCode == 11 || charCode == 0x2D || charCode == 0x2028 || charCode == 0x2029)
  2685. {
  2686. // Store the state of the line before starting on the new line.
  2687. SaveWordWrappingState(ref m_SavedLineState, i, m_characterCount);
  2688. m_lineNumber += 1;
  2689. isStartOfNewLine = true;
  2690. ignoreNonBreakingSpace = false;
  2691. isFirstWordOfLine = true;
  2692. m_firstCharacterOfLine = m_characterCount + 1;
  2693. m_lineVisibleCharacterCount = 0;
  2694. // Check to make sure Array is large enough to hold a new line.
  2695. if (m_lineNumber >= m_textInfo.lineInfo.Length)
  2696. ResizeLineExtents(m_lineNumber);
  2697. float lastVisibleAscender = m_textInfo.characterInfo[m_characterCount].adjustedAscender;
  2698. // Apply Line Spacing with special handling for VT char(11)
  2699. if (m_lineHeight == TMP_Math.FLOAT_UNSET)
  2700. {
  2701. float lineOffsetDelta = 0 - m_maxLineDescender + lastVisibleAscender + (lineGap + m_lineSpacingDelta) * baseScale + (m_lineSpacing + (charCode == 10 || charCode == 0x2029 ? m_paragraphSpacing : 0)) * currentEmScale;
  2702. m_lineOffset += lineOffsetDelta;
  2703. m_IsDrivenLineSpacing = false;
  2704. }
  2705. else
  2706. {
  2707. m_lineOffset += m_lineHeight + (m_lineSpacing + (charCode == 10 || charCode == 0x2029 ? m_paragraphSpacing : 0)) * currentEmScale;
  2708. m_IsDrivenLineSpacing = true;
  2709. }
  2710. m_maxLineAscender = k_LargeNegativeFloat;
  2711. m_maxLineDescender = k_LargePositiveFloat;
  2712. m_startOfLineAscender = lastVisibleAscender;
  2713. m_xAdvance = 0 + tag_LineIndent + tag_Indent;
  2714. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  2715. SaveWordWrappingState(ref m_SavedLastValidState, i, m_characterCount);
  2716. m_characterCount += 1;
  2717. k_HandleLineTerminationMarker.End();
  2718. continue;
  2719. }
  2720. // If End of Text
  2721. if (charCode == 0x03)
  2722. i = m_TextProcessingArray.Length;
  2723. k_HandleLineTerminationMarker.End();
  2724. }
  2725. #endregion Check for Linefeed or Last Character
  2726. // Store Rectangle positions for each Character.
  2727. #region Save CharacterInfo for the current character.
  2728. k_SavePageInfoMarker.Begin();
  2729. // Determine the bounds of the Mesh.
  2730. if (m_textInfo.characterInfo[m_characterCount].isVisible)
  2731. {
  2732. m_meshExtents.min.x = Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[m_characterCount].bottomLeft.x);
  2733. m_meshExtents.min.y = Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[m_characterCount].bottomLeft.y);
  2734. m_meshExtents.max.x = Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[m_characterCount].topRight.x);
  2735. m_meshExtents.max.y = Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[m_characterCount].topRight.y);
  2736. //m_meshExtents.min = new Vector2(Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[m_characterCount].bottomLeft.x), Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[m_characterCount].bottomLeft.y));
  2737. //m_meshExtents.max = new Vector2(Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[m_characterCount].topRight.x), Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[m_characterCount].topRight.y));
  2738. }
  2739. // Save pageInfo Data
  2740. if (m_overflowMode == TextOverflowModes.Page && charCode != 10 && charCode != 11 && charCode != 13 && charCode != 0x2028 && charCode != 0x2029) // && m_pageNumber < 16)
  2741. {
  2742. // Check if we need to increase allocations for the pageInfo array.
  2743. if (m_pageNumber + 1 > m_textInfo.pageInfo.Length)
  2744. TMP_TextInfo.Resize(ref m_textInfo.pageInfo, m_pageNumber + 1, true);
  2745. m_textInfo.pageInfo[m_pageNumber].ascender = m_PageAscender;
  2746. m_textInfo.pageInfo[m_pageNumber].descender = m_ElementDescender < m_textInfo.pageInfo[m_pageNumber].descender
  2747. ? m_ElementDescender
  2748. : m_textInfo.pageInfo[m_pageNumber].descender;
  2749. if (m_pageNumber == 0 && m_characterCount == 0)
  2750. m_textInfo.pageInfo[m_pageNumber].firstCharacterIndex = m_characterCount;
  2751. else if (m_characterCount > 0 && m_pageNumber != m_textInfo.characterInfo[m_characterCount - 1].pageNumber)
  2752. {
  2753. m_textInfo.pageInfo[m_pageNumber - 1].lastCharacterIndex = m_characterCount - 1;
  2754. m_textInfo.pageInfo[m_pageNumber].firstCharacterIndex = m_characterCount;
  2755. }
  2756. else if (m_characterCount == totalCharacterCount - 1)
  2757. m_textInfo.pageInfo[m_pageNumber].lastCharacterIndex = m_characterCount;
  2758. }
  2759. k_SavePageInfoMarker.End();
  2760. #endregion Saving CharacterInfo
  2761. // Save State of Mesh Creation for handling of Word Wrapping
  2762. #region Save Word Wrapping State
  2763. if (m_enableWordWrapping || m_overflowMode == TextOverflowModes.Truncate || m_overflowMode == TextOverflowModes.Ellipsis || m_overflowMode == TextOverflowModes.Linked)
  2764. {
  2765. k_SaveProcessingStatesMarker.Begin();
  2766. if ((isWhiteSpace || charCode == 0x200B || charCode == 0x2D || charCode == 0xAD) && (!m_isNonBreakingSpace || ignoreNonBreakingSpace) && charCode != 0xA0 && charCode != 0x2007 && charCode != 0x2011 && charCode != 0x202F && charCode != 0x2060)
  2767. {
  2768. // We store the state of numerous variables for the most recent Space, LineFeed or Carriage Return to enable them to be restored
  2769. // for Word Wrapping.
  2770. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  2771. isFirstWordOfLine = false;
  2772. //isLastCharacterCJK = false;
  2773. // Reset soft line breaking point since we now have a valid hard break point.
  2774. m_SavedSoftLineBreakState.previous_WordBreak = -1;
  2775. }
  2776. // Handling for East Asian characters
  2777. else if (m_isNonBreakingSpace == false &&
  2778. ((charCode > 0x1100 && charCode < 0x11ff || /* Hangul Jamo */
  2779. charCode > 0xA960 && charCode < 0xA97F || /* Hangul Jamo Extended-A */
  2780. charCode > 0xAC00 && charCode < 0xD7FF)&& /* Hangul Syllables */
  2781. TMP_Settings.useModernHangulLineBreakingRules == false ||
  2782. (charCode > 0x2E80 && charCode < 0x9FFF || /* CJK */
  2783. charCode > 0xF900 && charCode < 0xFAFF || /* CJK Compatibility Ideographs */
  2784. charCode > 0xFE30 && charCode < 0xFE4F || /* CJK Compatibility Forms */
  2785. charCode > 0xFF00 && charCode < 0xFFEF))) /* CJK Halfwidth */
  2786. {
  2787. bool isCurrentLeadingCharacter = TMP_Settings.linebreakingRules.leadingCharacters.ContainsKey(charCode);
  2788. bool isNextFollowingCharacter = m_characterCount < totalCharacterCount - 1 && TMP_Settings.linebreakingRules.followingCharacters.ContainsKey(m_textInfo.characterInfo[m_characterCount + 1].character);
  2789. if (isCurrentLeadingCharacter == false)
  2790. {
  2791. if (isNextFollowingCharacter == false)
  2792. {
  2793. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  2794. isFirstWordOfLine = false;
  2795. }
  2796. if (isFirstWordOfLine)
  2797. {
  2798. // Special handling for non-breaking space and soft line breaks
  2799. if (isWhiteSpace)
  2800. SaveWordWrappingState(ref m_SavedSoftLineBreakState, i, m_characterCount);
  2801. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  2802. }
  2803. }
  2804. else
  2805. {
  2806. if (isFirstWordOfLine && isFirstCharacterOfLine)
  2807. {
  2808. // Special handling for non-breaking space and soft line breaks
  2809. if (isWhiteSpace)
  2810. SaveWordWrappingState(ref m_SavedSoftLineBreakState, i, m_characterCount);
  2811. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  2812. }
  2813. }
  2814. //isLastCharacterCJK = true;
  2815. }
  2816. else if (isFirstWordOfLine)
  2817. {
  2818. // Special handling for non-breaking space and soft line breaks
  2819. if (isWhiteSpace || (charCode == 0xAD && isSoftHyphenIgnored == false))
  2820. SaveWordWrappingState(ref m_SavedSoftLineBreakState, i, m_characterCount);
  2821. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  2822. //isLastCharacterCJK = false;
  2823. }
  2824. k_SaveProcessingStatesMarker.End();
  2825. }
  2826. #endregion Save Word Wrapping State
  2827. SaveWordWrappingState(ref m_SavedLastValidState, i, m_characterCount);
  2828. m_characterCount += 1;
  2829. }
  2830. // Check Auto Sizing and increase font size to fill text container.
  2831. #region Check Auto-Sizing (Upper Font Size Bounds)
  2832. fontSizeDelta = m_maxFontSize - m_minFontSize;
  2833. if (/* !m_isCharacterWrappingEnabled && */ m_enableAutoSizing && fontSizeDelta > 0.051f && m_fontSize < m_fontSizeMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2834. {
  2835. // Reset character width adjustment delta
  2836. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100)
  2837. m_charWidthAdjDelta = 0;
  2838. m_minFontSize = m_fontSize;
  2839. float sizeDelta = Mathf.Max((m_maxFontSize - m_fontSize) / 2, 0.05f);
  2840. m_fontSize += sizeDelta;
  2841. m_fontSize = Mathf.Min((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMax);
  2842. //Debug.Log("[" + m_AutoSizeIterationCount + "] Increasing Point Size from [" + m_minFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2843. k_GenerateTextPhaseIMarker.End();
  2844. k_GenerateTextMarker.End();
  2845. return;
  2846. }
  2847. #endregion End Auto-sizing Check
  2848. m_IsAutoSizePointSizeSet = true;
  2849. if (m_AutoSizeIterationCount >= m_AutoSizeMaxIterationCount)
  2850. Debug.Log("Auto Size Iteration Count: " + m_AutoSizeIterationCount + ". Final Point Size: " + m_fontSize);
  2851. // If there are no visible characters or only character is End of Text (0x03)... no need to continue
  2852. if (m_characterCount == 0 || (m_characterCount == 1 && charCode == 0x03))
  2853. {
  2854. ClearMesh();
  2855. // Event indicating the text has been regenerated.
  2856. TMPro_EventManager.ON_TEXT_CHANGED(this);
  2857. k_GenerateTextPhaseIMarker.End();
  2858. k_GenerateTextMarker.End();
  2859. return;
  2860. }
  2861. // End Sampling of Phase I
  2862. k_GenerateTextPhaseIMarker.End();
  2863. // *** PHASE II of Text Generation ***
  2864. k_GenerateTextPhaseIIMarker.Begin();
  2865. int last_vert_index = m_materialReferences[m_Underline.materialIndex].referenceCount * 4;
  2866. // Partial clear of the vertices array to mark unused vertices as degenerate.
  2867. m_textInfo.meshInfo[0].Clear(false);
  2868. // Handle Text Alignment
  2869. #region Text Vertical Alignment
  2870. Vector3 anchorOffset = Vector3.zero;
  2871. Vector3[] corners = m_RectTransformCorners; // GetTextContainerLocalCorners();
  2872. // Handle Vertical Text Alignment
  2873. switch (m_VerticalAlignment)
  2874. {
  2875. // Top Vertically
  2876. case VerticalAlignmentOptions.Top:
  2877. if (m_overflowMode != TextOverflowModes.Page)
  2878. anchorOffset = corners[1] + new Vector3(0 + margins.x, 0 - m_maxTextAscender - margins.y, 0);
  2879. else
  2880. anchorOffset = corners[1] + new Vector3(0 + margins.x, 0 - m_textInfo.pageInfo[pageToDisplay].ascender - margins.y, 0);
  2881. break;
  2882. // Middle Vertically
  2883. case VerticalAlignmentOptions.Middle:
  2884. if (m_overflowMode != TextOverflowModes.Page)
  2885. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_maxTextAscender + margins.y + maxVisibleDescender - margins.w) / 2, 0);
  2886. else
  2887. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_textInfo.pageInfo[pageToDisplay].ascender + margins.y + m_textInfo.pageInfo[pageToDisplay].descender - margins.w) / 2, 0);
  2888. break;
  2889. // Bottom Vertically
  2890. case VerticalAlignmentOptions.Bottom:
  2891. if (m_overflowMode != TextOverflowModes.Page)
  2892. anchorOffset = corners[0] + new Vector3(0 + margins.x, 0 - maxVisibleDescender + margins.w, 0);
  2893. else
  2894. anchorOffset = corners[0] + new Vector3(0 + margins.x, 0 - m_textInfo.pageInfo[pageToDisplay].descender + margins.w, 0);
  2895. break;
  2896. // Baseline Vertically
  2897. case VerticalAlignmentOptions.Baseline:
  2898. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0, 0);
  2899. break;
  2900. // Midline Vertically
  2901. case VerticalAlignmentOptions.Geometry:
  2902. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_meshExtents.max.y + margins.y + m_meshExtents.min.y - margins.w) / 2, 0);
  2903. break;
  2904. // Capline Vertically
  2905. case VerticalAlignmentOptions.Capline:
  2906. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_maxCapHeight - margins.y - margins.w) / 2, 0);
  2907. break;
  2908. }
  2909. #endregion
  2910. // Initialization for Second Pass
  2911. Vector3 justificationOffset = Vector3.zero;
  2912. Vector3 offset = Vector3.zero;
  2913. int vert_index_X4 = 0;
  2914. int sprite_index_X4 = 0;
  2915. int wordCount = 0;
  2916. int lineCount = 0;
  2917. int lastLine = 0;
  2918. bool isFirstSeperator = false;
  2919. bool isStartOfWord = false;
  2920. int wordFirstChar = 0;
  2921. int wordLastChar = 0;
  2922. // Second Pass : Line Justification, UV Mapping, Character & Line Visibility & more.
  2923. // Variables used to handle Canvas Render Modes and SDF Scaling
  2924. bool isCameraAssigned = m_canvas.worldCamera == null ? false : true;
  2925. float lossyScale = m_previousLossyScaleY = this.transform.lossyScale.y;
  2926. RenderMode canvasRenderMode = m_canvas.renderMode;
  2927. float canvasScaleFactor = m_canvas.scaleFactor;
  2928. Color32 underlineColor = Color.white;
  2929. Color32 strikethroughColor = Color.white;
  2930. HighlightState highlightState = new HighlightState(new Color32(255, 255, 0, 64), TMP_Offset.zero);
  2931. float xScale = 0;
  2932. float xScaleMax = 0;
  2933. float underlineStartScale = 0;
  2934. float underlineEndScale = 0;
  2935. float underlineMaxScale = 0;
  2936. float underlineBaseLine = k_LargePositiveFloat;
  2937. int lastPage = 0;
  2938. float strikethroughPointSize = 0;
  2939. float strikethroughScale = 0;
  2940. float strikethroughBaseline = 0;
  2941. TMP_CharacterInfo[] characterInfos = m_textInfo.characterInfo;
  2942. #region Handle Line Justification & UV Mapping & Character Visibility & More
  2943. for (int i = 0; i < m_characterCount; i++)
  2944. {
  2945. TMP_FontAsset currentFontAsset = characterInfos[i].fontAsset;
  2946. char unicode = characterInfos[i].character;
  2947. int currentLine = characterInfos[i].lineNumber;
  2948. TMP_LineInfo lineInfo = m_textInfo.lineInfo[currentLine];
  2949. lineCount = currentLine + 1;
  2950. HorizontalAlignmentOptions lineAlignment = lineInfo.alignment;
  2951. // Process Line Justification
  2952. #region Handle Line Justification
  2953. switch (lineAlignment)
  2954. {
  2955. case HorizontalAlignmentOptions.Left:
  2956. if (!m_isRightToLeft)
  2957. justificationOffset = new Vector3(0 + lineInfo.marginLeft, 0, 0);
  2958. else
  2959. justificationOffset = new Vector3(0 - lineInfo.maxAdvance, 0, 0);
  2960. break;
  2961. case HorizontalAlignmentOptions.Center:
  2962. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width / 2 - lineInfo.maxAdvance / 2, 0, 0);
  2963. break;
  2964. case HorizontalAlignmentOptions.Geometry:
  2965. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width / 2 - (lineInfo.lineExtents.min.x + lineInfo.lineExtents.max.x) / 2, 0, 0);
  2966. break;
  2967. case HorizontalAlignmentOptions.Right:
  2968. if (!m_isRightToLeft)
  2969. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width - lineInfo.maxAdvance, 0, 0);
  2970. else
  2971. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0);
  2972. break;
  2973. case HorizontalAlignmentOptions.Justified:
  2974. case HorizontalAlignmentOptions.Flush:
  2975. // Skip Zero Width Characters
  2976. if (unicode == 0x0A || unicode == 0xAD || unicode == 0x200B || unicode == 0x2060 || unicode == 0x03) break;
  2977. char lastCharOfCurrentLine = characterInfos[lineInfo.lastCharacterIndex].character;
  2978. bool isFlush = (lineAlignment & HorizontalAlignmentOptions.Flush) == HorizontalAlignmentOptions.Flush;
  2979. // In Justified mode, all lines are justified except the last one.
  2980. // In Flush mode, all lines are justified.
  2981. if (char.IsControl(lastCharOfCurrentLine) == false && currentLine < m_lineNumber || isFlush || lineInfo.maxAdvance > lineInfo.width)
  2982. {
  2983. // First character of each line.
  2984. if (currentLine != lastLine || i == 0 || i == m_firstVisibleCharacter)
  2985. {
  2986. if (!m_isRightToLeft)
  2987. justificationOffset = new Vector3(lineInfo.marginLeft, 0, 0);
  2988. else
  2989. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0);
  2990. if (char.IsSeparator(unicode))
  2991. isFirstSeperator = true;
  2992. else
  2993. isFirstSeperator = false;
  2994. }
  2995. else
  2996. {
  2997. float gap = !m_isRightToLeft ? lineInfo.width - lineInfo.maxAdvance : lineInfo.width + lineInfo.maxAdvance;
  2998. int visibleCount = lineInfo.visibleCharacterCount - 1 + lineInfo.controlCharacterCount;
  2999. // Get the number of spaces for each line ignoring the last character if it is not visible (ie. a space or linefeed).
  3000. int spaces = (characterInfos[lineInfo.lastCharacterIndex].isVisible ? lineInfo.spaceCount : lineInfo.spaceCount - 1) - lineInfo.controlCharacterCount;
  3001. if (isFirstSeperator) { spaces -= 1; visibleCount += 1; }
  3002. float ratio = spaces > 0 ? m_wordWrappingRatios : 1;
  3003. if (spaces < 1) spaces = 1;
  3004. if (unicode != 0xA0 && (unicode == 9 || char.IsSeparator((char)unicode)))
  3005. {
  3006. if (!m_isRightToLeft)
  3007. justificationOffset += new Vector3(gap * (1 - ratio) / spaces, 0, 0);
  3008. else
  3009. justificationOffset -= new Vector3(gap * (1 - ratio) / spaces, 0, 0);
  3010. }
  3011. else
  3012. {
  3013. if (!m_isRightToLeft)
  3014. justificationOffset += new Vector3(gap * ratio / visibleCount, 0, 0);
  3015. else
  3016. justificationOffset -= new Vector3(gap * ratio / visibleCount, 0, 0);
  3017. }
  3018. }
  3019. }
  3020. else
  3021. {
  3022. if (!m_isRightToLeft)
  3023. justificationOffset = new Vector3(lineInfo.marginLeft, 0, 0); // Keep last line left justified.
  3024. else
  3025. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0); // Keep last line right justified.
  3026. }
  3027. //Debug.Log("Char [" + (char)charCode + "] Code:" + charCode + " Line # " + currentLine + " Offset:" + justificationOffset + " # Spaces:" + lineInfo.spaceCount + " # Characters:" + lineInfo.characterCount);
  3028. break;
  3029. }
  3030. #endregion End Text Justification
  3031. offset = anchorOffset + justificationOffset;
  3032. // Handle UV2 mapping options and packing of scale information into UV2.
  3033. #region Handling of UV2 mapping & Scale packing
  3034. bool isCharacterVisible = characterInfos[i].isVisible;
  3035. if (isCharacterVisible)
  3036. {
  3037. TMP_TextElementType elementType = characterInfos[i].elementType;
  3038. switch (elementType)
  3039. {
  3040. // CHARACTERS
  3041. case TMP_TextElementType.Character:
  3042. Extents lineExtents = lineInfo.lineExtents;
  3043. float uvOffset = (m_uvLineOffset * currentLine) % 1; // + m_uvOffset.x;
  3044. // Setup UV2 based on Character Mapping Options Selected
  3045. #region Handle UV Mapping Options
  3046. switch (m_horizontalMapping)
  3047. {
  3048. case TextureMappingOptions.Character:
  3049. characterInfos[i].vertex_BL.uv2.x = 0; //+ m_uvOffset.x;
  3050. characterInfos[i].vertex_TL.uv2.x = 0; //+ m_uvOffset.x;
  3051. characterInfos[i].vertex_TR.uv2.x = 1; //+ m_uvOffset.x;
  3052. characterInfos[i].vertex_BR.uv2.x = 1; //+ m_uvOffset.x;
  3053. break;
  3054. case TextureMappingOptions.Line:
  3055. if (m_textAlignment != TextAlignmentOptions.Justified)
  3056. {
  3057. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3058. characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3059. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3060. characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3061. break;
  3062. }
  3063. else // Special Case if Justified is used in Line Mode.
  3064. {
  3065. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3066. characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3067. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3068. characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3069. break;
  3070. }
  3071. case TextureMappingOptions.Paragraph:
  3072. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3073. characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3074. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3075. characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3076. break;
  3077. case TextureMappingOptions.MatchAspect:
  3078. switch (m_verticalMapping)
  3079. {
  3080. case TextureMappingOptions.Character:
  3081. characterInfos[i].vertex_BL.uv2.y = 0; // + m_uvOffset.y;
  3082. characterInfos[i].vertex_TL.uv2.y = 1; // + m_uvOffset.y;
  3083. characterInfos[i].vertex_TR.uv2.y = 0; // + m_uvOffset.y;
  3084. characterInfos[i].vertex_BR.uv2.y = 1; // + m_uvOffset.y;
  3085. break;
  3086. case TextureMappingOptions.Line:
  3087. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - lineExtents.min.y) / (lineExtents.max.y - lineExtents.min.y) + uvOffset;
  3088. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - lineExtents.min.y) / (lineExtents.max.y - lineExtents.min.y) + uvOffset;
  3089. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3090. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3091. break;
  3092. case TextureMappingOptions.Paragraph:
  3093. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y) + uvOffset;
  3094. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y) + uvOffset;
  3095. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3096. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3097. break;
  3098. case TextureMappingOptions.MatchAspect:
  3099. Debug.Log("ERROR: Cannot Match both Vertical & Horizontal.");
  3100. break;
  3101. }
  3102. //float xDelta = 1 - (_uv2s[vert_index + 0].y * textMeshCharacterInfo[i].AspectRatio); // Left aligned
  3103. float xDelta = (1 - ((characterInfos[i].vertex_BL.uv2.y + characterInfos[i].vertex_TL.uv2.y) * characterInfos[i].aspectRatio)) / 2; // Center of Rectangle
  3104. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.uv2.y * characterInfos[i].aspectRatio) + xDelta + uvOffset;
  3105. characterInfos[i].vertex_TL.uv2.x = characterInfos[i].vertex_BL.uv2.x;
  3106. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TL.uv2.y * characterInfos[i].aspectRatio) + xDelta + uvOffset;
  3107. characterInfos[i].vertex_BR.uv2.x = characterInfos[i].vertex_TR.uv2.x;
  3108. break;
  3109. }
  3110. switch (m_verticalMapping)
  3111. {
  3112. case TextureMappingOptions.Character:
  3113. characterInfos[i].vertex_BL.uv2.y = 0; // + m_uvOffset.y;
  3114. characterInfos[i].vertex_TL.uv2.y = 1; // + m_uvOffset.y;
  3115. characterInfos[i].vertex_TR.uv2.y = 1; // + m_uvOffset.y;
  3116. characterInfos[i].vertex_BR.uv2.y = 0; // + m_uvOffset.y;
  3117. break;
  3118. case TextureMappingOptions.Line:
  3119. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - lineInfo.descender) / (lineInfo.ascender - lineInfo.descender); // + m_uvOffset.y;
  3120. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - lineInfo.descender) / (lineInfo.ascender - lineInfo.descender); // + m_uvOffset.y;
  3121. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3122. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3123. break;
  3124. case TextureMappingOptions.Paragraph:
  3125. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y); // + m_uvOffset.y;
  3126. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y); // + m_uvOffset.y;
  3127. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3128. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3129. break;
  3130. case TextureMappingOptions.MatchAspect:
  3131. float yDelta = (1 - ((characterInfos[i].vertex_BL.uv2.x + characterInfos[i].vertex_TR.uv2.x) / characterInfos[i].aspectRatio)) / 2; // Center of Rectangle
  3132. characterInfos[i].vertex_BL.uv2.y = yDelta + (characterInfos[i].vertex_BL.uv2.x / characterInfos[i].aspectRatio); // + m_uvOffset.y;
  3133. characterInfos[i].vertex_TL.uv2.y = yDelta + (characterInfos[i].vertex_TR.uv2.x / characterInfos[i].aspectRatio); // + m_uvOffset.y;
  3134. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3135. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3136. break;
  3137. }
  3138. #endregion
  3139. // Pack UV's so that we can pass Xscale needed for Shader to maintain 1:1 ratio.
  3140. #region Pack Scale into UV2
  3141. xScale = characterInfos[i].scale * (1 - m_charWidthAdjDelta);
  3142. if (!characterInfos[i].isUsingAlternateTypeface && (characterInfos[i].style & FontStyles.Bold) == FontStyles.Bold) xScale *= -1;
  3143. switch (canvasRenderMode)
  3144. {
  3145. case RenderMode.ScreenSpaceOverlay:
  3146. xScale *= Mathf.Abs(lossyScale) / canvasScaleFactor;
  3147. break;
  3148. case RenderMode.ScreenSpaceCamera:
  3149. xScale *= isCameraAssigned ? Mathf.Abs(lossyScale) : 1;
  3150. break;
  3151. case RenderMode.WorldSpace:
  3152. xScale *= Mathf.Abs(lossyScale);
  3153. break;
  3154. }
  3155. // isBold is encoded in the X value and SDF Scale in Y.
  3156. //Vector2 vertexData = new Vector2((characterInfos[i].style & FontStyles.Bold) == FontStyles.Bold ? 1 : 0, xScale);
  3157. //characterInfos[i].vertex_BL.uv2 = vertexData;
  3158. //characterInfos[i].vertex_TL.uv2 = vertexData;
  3159. //characterInfos[i].vertex_TR.uv2 = vertexData;
  3160. //characterInfos[i].vertex_BR.uv2 = vertexData;
  3161. float x0 = characterInfos[i].vertex_BL.uv2.x;
  3162. float y0 = characterInfos[i].vertex_BL.uv2.y;
  3163. float x1 = characterInfos[i].vertex_TR.uv2.x;
  3164. float y1 = characterInfos[i].vertex_TR.uv2.y;
  3165. float dx = (int)x0;
  3166. float dy = (int)y0;
  3167. x0 = x0 - dx;
  3168. x1 = x1 - dx;
  3169. y0 = y0 - dy;
  3170. y1 = y1 - dy;
  3171. // Optimization to avoid having a vector2 returned from the Pack UV function.
  3172. characterInfos[i].vertex_BL.uv2.x = PackUV(x0, y0); characterInfos[i].vertex_BL.uv2.y = xScale;
  3173. characterInfos[i].vertex_TL.uv2.x = PackUV(x0, y1); characterInfos[i].vertex_TL.uv2.y = xScale;
  3174. characterInfos[i].vertex_TR.uv2.x = PackUV(x1, y1); characterInfos[i].vertex_TR.uv2.y = xScale;
  3175. characterInfos[i].vertex_BR.uv2.x = PackUV(x1, y0); characterInfos[i].vertex_BR.uv2.y = xScale;
  3176. #endregion
  3177. break;
  3178. // SPRITES
  3179. case TMP_TextElementType.Sprite:
  3180. // Nothing right now
  3181. break;
  3182. }
  3183. // Handle maxVisibleCharacters, maxVisibleLines and Overflow Page Mode.
  3184. #region Handle maxVisibleCharacters / maxVisibleLines / Page Mode
  3185. if (i < m_maxVisibleCharacters && wordCount < m_maxVisibleWords && currentLine < m_maxVisibleLines && m_overflowMode != TextOverflowModes.Page)
  3186. {
  3187. characterInfos[i].vertex_BL.position += offset;
  3188. characterInfos[i].vertex_TL.position += offset;
  3189. characterInfos[i].vertex_TR.position += offset;
  3190. characterInfos[i].vertex_BR.position += offset;
  3191. }
  3192. else if (i < m_maxVisibleCharacters && wordCount < m_maxVisibleWords && currentLine < m_maxVisibleLines && m_overflowMode == TextOverflowModes.Page && characterInfos[i].pageNumber == pageToDisplay)
  3193. {
  3194. characterInfos[i].vertex_BL.position += offset;
  3195. characterInfos[i].vertex_TL.position += offset;
  3196. characterInfos[i].vertex_TR.position += offset;
  3197. characterInfos[i].vertex_BR.position += offset;
  3198. }
  3199. else
  3200. {
  3201. characterInfos[i].vertex_BL.position = Vector3.zero;
  3202. characterInfos[i].vertex_TL.position = Vector3.zero;
  3203. characterInfos[i].vertex_TR.position = Vector3.zero;
  3204. characterInfos[i].vertex_BR.position = Vector3.zero;
  3205. characterInfos[i].isVisible = false;
  3206. }
  3207. #endregion
  3208. // Fill Vertex Buffers for the various types of element
  3209. if (elementType == TMP_TextElementType.Character)
  3210. {
  3211. FillCharacterVertexBuffers(i, vert_index_X4);
  3212. }
  3213. else if (elementType == TMP_TextElementType.Sprite)
  3214. {
  3215. FillSpriteVertexBuffers(i, sprite_index_X4);
  3216. }
  3217. }
  3218. #endregion
  3219. // Apply Alignment and Justification Offset
  3220. m_textInfo.characterInfo[i].bottomLeft += offset;
  3221. m_textInfo.characterInfo[i].topLeft += offset;
  3222. m_textInfo.characterInfo[i].topRight += offset;
  3223. m_textInfo.characterInfo[i].bottomRight += offset;
  3224. m_textInfo.characterInfo[i].origin += offset.x;
  3225. m_textInfo.characterInfo[i].xAdvance += offset.x;
  3226. m_textInfo.characterInfo[i].ascender += offset.y;
  3227. m_textInfo.characterInfo[i].descender += offset.y;
  3228. m_textInfo.characterInfo[i].baseLine += offset.y;
  3229. // Update MeshExtents
  3230. if (isCharacterVisible)
  3231. {
  3232. //m_meshExtents.min = new Vector2(Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[i].bottomLeft.x), Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[i].bottomLeft.y));
  3233. //m_meshExtents.max = new Vector2(Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[i].topRight.x), Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[i].topLeft.y));
  3234. }
  3235. // Need to recompute lineExtent to account for the offset from justification.
  3236. #region Adjust lineExtents resulting from alignment offset
  3237. if (currentLine != lastLine || i == m_characterCount - 1)
  3238. {
  3239. // Update the previous line's extents
  3240. if (currentLine != lastLine)
  3241. {
  3242. m_textInfo.lineInfo[lastLine].baseline += offset.y;
  3243. m_textInfo.lineInfo[lastLine].ascender += offset.y;
  3244. m_textInfo.lineInfo[lastLine].descender += offset.y;
  3245. m_textInfo.lineInfo[lastLine].maxAdvance += offset.x;
  3246. m_textInfo.lineInfo[lastLine].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[lastLine].firstCharacterIndex].bottomLeft.x, m_textInfo.lineInfo[lastLine].descender);
  3247. m_textInfo.lineInfo[lastLine].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[lastLine].lastVisibleCharacterIndex].topRight.x, m_textInfo.lineInfo[lastLine].ascender);
  3248. }
  3249. // Update the current line's extents
  3250. if (i == m_characterCount - 1)
  3251. {
  3252. m_textInfo.lineInfo[currentLine].baseline += offset.y;
  3253. m_textInfo.lineInfo[currentLine].ascender += offset.y;
  3254. m_textInfo.lineInfo[currentLine].descender += offset.y;
  3255. m_textInfo.lineInfo[currentLine].maxAdvance += offset.x;
  3256. m_textInfo.lineInfo[currentLine].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[currentLine].firstCharacterIndex].bottomLeft.x, m_textInfo.lineInfo[currentLine].descender);
  3257. m_textInfo.lineInfo[currentLine].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[currentLine].lastVisibleCharacterIndex].topRight.x, m_textInfo.lineInfo[currentLine].ascender);
  3258. }
  3259. }
  3260. #endregion
  3261. // Track Word Count per line and for the object
  3262. #region Track Word Count
  3263. if (char.IsLetterOrDigit(unicode) || unicode == 0x2D || unicode == 0xAD || unicode == 0x2010 || unicode == 0x2011)
  3264. {
  3265. if (isStartOfWord == false)
  3266. {
  3267. isStartOfWord = true;
  3268. wordFirstChar = i;
  3269. }
  3270. // If last character is a word
  3271. if (isStartOfWord && i == m_characterCount - 1)
  3272. {
  3273. int size = m_textInfo.wordInfo.Length;
  3274. int index = m_textInfo.wordCount;
  3275. if (m_textInfo.wordCount + 1 > size)
  3276. TMP_TextInfo.Resize(ref m_textInfo.wordInfo, size + 1);
  3277. wordLastChar = i;
  3278. m_textInfo.wordInfo[index].firstCharacterIndex = wordFirstChar;
  3279. m_textInfo.wordInfo[index].lastCharacterIndex = wordLastChar;
  3280. m_textInfo.wordInfo[index].characterCount = wordLastChar - wordFirstChar + 1;
  3281. m_textInfo.wordInfo[index].textComponent = this;
  3282. wordCount += 1;
  3283. m_textInfo.wordCount += 1;
  3284. m_textInfo.lineInfo[currentLine].wordCount += 1;
  3285. }
  3286. }
  3287. else if (isStartOfWord || i == 0 && (!char.IsPunctuation(unicode) || char.IsWhiteSpace(unicode) || unicode == 0x200B || i == m_characterCount - 1))
  3288. {
  3289. if (i > 0 && i < characterInfos.Length - 1 && i < m_characterCount && (unicode == 39 || unicode == 8217) && char.IsLetterOrDigit(characterInfos[i - 1].character) && char.IsLetterOrDigit(characterInfos[i + 1].character))
  3290. {
  3291. }
  3292. else
  3293. {
  3294. wordLastChar = i == m_characterCount - 1 && char.IsLetterOrDigit(unicode) ? i : i - 1;
  3295. isStartOfWord = false;
  3296. int size = m_textInfo.wordInfo.Length;
  3297. int index = m_textInfo.wordCount;
  3298. if (m_textInfo.wordCount + 1 > size)
  3299. TMP_TextInfo.Resize(ref m_textInfo.wordInfo, size + 1);
  3300. m_textInfo.wordInfo[index].firstCharacterIndex = wordFirstChar;
  3301. m_textInfo.wordInfo[index].lastCharacterIndex = wordLastChar;
  3302. m_textInfo.wordInfo[index].characterCount = wordLastChar - wordFirstChar + 1;
  3303. m_textInfo.wordInfo[index].textComponent = this;
  3304. wordCount += 1;
  3305. m_textInfo.wordCount += 1;
  3306. m_textInfo.lineInfo[currentLine].wordCount += 1;
  3307. }
  3308. }
  3309. #endregion
  3310. // Setup & Handle Underline
  3311. #region Underline
  3312. // NOTE: Need to figure out how underline will be handled with multiple fonts and which font will be used for the underline.
  3313. bool isUnderline = (m_textInfo.characterInfo[i].style & FontStyles.Underline) == FontStyles.Underline;
  3314. if (isUnderline)
  3315. {
  3316. bool isUnderlineVisible = true;
  3317. int currentPage = m_textInfo.characterInfo[i].pageNumber;
  3318. m_textInfo.characterInfo[i].underlineVertexIndex = last_vert_index;
  3319. if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && currentPage + 1 != m_pageToDisplay))
  3320. isUnderlineVisible = false;
  3321. // We only use the scale of visible characters.
  3322. if (!char.IsWhiteSpace(unicode) && unicode != 0x200B)
  3323. {
  3324. underlineMaxScale = Mathf.Max(underlineMaxScale, m_textInfo.characterInfo[i].scale);
  3325. xScaleMax = Mathf.Max(xScaleMax, Mathf.Abs(xScale));
  3326. underlineBaseLine = Mathf.Min(currentPage == lastPage ? underlineBaseLine : k_LargePositiveFloat, m_textInfo.characterInfo[i].baseLine + font.m_FaceInfo.underlineOffset * underlineMaxScale);
  3327. lastPage = currentPage; // Need to track pages to ensure we reset baseline for the new pages.
  3328. }
  3329. if (beginUnderline == false && isUnderlineVisible == true && i <= lineInfo.lastVisibleCharacterIndex && unicode != 10 && unicode != 11 && unicode != 13)
  3330. {
  3331. if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(unicode))
  3332. { }
  3333. else
  3334. {
  3335. beginUnderline = true;
  3336. underlineStartScale = m_textInfo.characterInfo[i].scale;
  3337. if (underlineMaxScale == 0)
  3338. {
  3339. underlineMaxScale = underlineStartScale;
  3340. xScaleMax = xScale;
  3341. }
  3342. underline_start = new Vector3(m_textInfo.characterInfo[i].bottomLeft.x, underlineBaseLine, 0);
  3343. underlineColor = m_textInfo.characterInfo[i].underlineColor;
  3344. }
  3345. }
  3346. // End Underline if text only contains one character.
  3347. if (beginUnderline && m_characterCount == 1)
  3348. {
  3349. beginUnderline = false;
  3350. underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
  3351. underlineEndScale = m_textInfo.characterInfo[i].scale;
  3352. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3353. underlineMaxScale = 0;
  3354. xScaleMax = 0;
  3355. underlineBaseLine = k_LargePositiveFloat;
  3356. }
  3357. else if (beginUnderline && (i == lineInfo.lastCharacterIndex || i >= lineInfo.lastVisibleCharacterIndex))
  3358. {
  3359. // Terminate underline at previous visible character if space or carriage return.
  3360. if (char.IsWhiteSpace(unicode) || unicode == 0x200B)
  3361. {
  3362. int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
  3363. underline_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, underlineBaseLine, 0);
  3364. underlineEndScale = m_textInfo.characterInfo[lastVisibleCharacterIndex].scale;
  3365. }
  3366. else
  3367. { // End underline if last character of the line.
  3368. underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
  3369. underlineEndScale = m_textInfo.characterInfo[i].scale;
  3370. }
  3371. beginUnderline = false;
  3372. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3373. underlineMaxScale = 0;
  3374. xScaleMax = 0;
  3375. underlineBaseLine = k_LargePositiveFloat;
  3376. }
  3377. else if (beginUnderline && !isUnderlineVisible)
  3378. {
  3379. beginUnderline = false;
  3380. underline_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, underlineBaseLine, 0);
  3381. underlineEndScale = m_textInfo.characterInfo[i - 1].scale;
  3382. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3383. underlineMaxScale = 0;
  3384. xScaleMax = 0;
  3385. underlineBaseLine = k_LargePositiveFloat;
  3386. }
  3387. else if (beginUnderline && i < m_characterCount - 1 && !underlineColor.Compare(m_textInfo.characterInfo[i + 1].underlineColor))
  3388. {
  3389. // End underline if underline color has changed.
  3390. beginUnderline = false;
  3391. underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
  3392. underlineEndScale = m_textInfo.characterInfo[i].scale;
  3393. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3394. underlineMaxScale = 0;
  3395. xScaleMax = 0;
  3396. underlineBaseLine = k_LargePositiveFloat;
  3397. }
  3398. }
  3399. else
  3400. {
  3401. // End Underline
  3402. if (beginUnderline == true)
  3403. {
  3404. beginUnderline = false;
  3405. underline_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, underlineBaseLine, 0);
  3406. underlineEndScale = m_textInfo.characterInfo[i - 1].scale;
  3407. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3408. underlineMaxScale = 0;
  3409. xScaleMax = 0;
  3410. underlineBaseLine = k_LargePositiveFloat;
  3411. }
  3412. }
  3413. #endregion
  3414. // Setup & Handle Strikethrough
  3415. #region Strikethrough
  3416. // NOTE: Need to figure out how underline will be handled with multiple fonts and which font will be used for the underline.
  3417. bool isStrikethrough = (m_textInfo.characterInfo[i].style & FontStyles.Strikethrough) == FontStyles.Strikethrough;
  3418. float strikethroughOffset = currentFontAsset.m_FaceInfo.strikethroughOffset;
  3419. if (isStrikethrough)
  3420. {
  3421. bool isStrikeThroughVisible = true;
  3422. m_textInfo.characterInfo[i].strikethroughVertexIndex = last_vert_index;
  3423. if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && m_textInfo.characterInfo[i].pageNumber + 1 != m_pageToDisplay))
  3424. isStrikeThroughVisible = false;
  3425. if (beginStrikethrough == false && isStrikeThroughVisible && i <= lineInfo.lastVisibleCharacterIndex && unicode != 10 && unicode != 11 && unicode != 13)
  3426. {
  3427. if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(unicode))
  3428. { }
  3429. else
  3430. {
  3431. beginStrikethrough = true;
  3432. strikethroughPointSize = m_textInfo.characterInfo[i].pointSize;
  3433. strikethroughScale = m_textInfo.characterInfo[i].scale;
  3434. strikethrough_start = new Vector3(m_textInfo.characterInfo[i].bottomLeft.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3435. strikethroughColor = m_textInfo.characterInfo[i].strikethroughColor;
  3436. strikethroughBaseline = m_textInfo.characterInfo[i].baseLine;
  3437. //Debug.Log("Char [" + currentCharacter + "] Start Strikethrough POS: " + strikethrough_start);
  3438. }
  3439. }
  3440. // End Strikethrough if text only contains one character.
  3441. if (beginStrikethrough && m_characterCount == 1)
  3442. {
  3443. beginStrikethrough = false;
  3444. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3445. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3446. }
  3447. else if (beginStrikethrough && i == lineInfo.lastCharacterIndex)
  3448. {
  3449. // Terminate Strikethrough at previous visible character if space or carriage return.
  3450. if (char.IsWhiteSpace(unicode) || unicode == 0x200B)
  3451. {
  3452. int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
  3453. strikethrough_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, m_textInfo.characterInfo[lastVisibleCharacterIndex].baseLine + strikethroughOffset * strikethroughScale, 0);
  3454. }
  3455. else
  3456. {
  3457. // Terminate Strikethrough at last character of line.
  3458. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3459. }
  3460. beginStrikethrough = false;
  3461. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3462. }
  3463. else if (beginStrikethrough && i < m_characterCount && (m_textInfo.characterInfo[i + 1].pointSize != strikethroughPointSize || !TMP_Math.Approximately(m_textInfo.characterInfo[i + 1].baseLine + offset.y, strikethroughBaseline)))
  3464. {
  3465. // Terminate Strikethrough if scale changes.
  3466. beginStrikethrough = false;
  3467. int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
  3468. if (i > lastVisibleCharacterIndex)
  3469. strikethrough_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, m_textInfo.characterInfo[lastVisibleCharacterIndex].baseLine + strikethroughOffset * strikethroughScale, 0);
  3470. else
  3471. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3472. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3473. //Debug.Log("Char [" + currentCharacter + "] at Index: " + i + " End Strikethrough POS: " + strikethrough_end + " Baseline: " + m_textInfo.characterInfo[i].baseLine.ToString("f3"));
  3474. }
  3475. else if (beginStrikethrough && i < m_characterCount && currentFontAsset.GetInstanceID() != characterInfos[i + 1].fontAsset.GetInstanceID())
  3476. {
  3477. // Terminate Strikethrough if font asset changes.
  3478. beginStrikethrough = false;
  3479. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3480. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3481. }
  3482. else if (beginStrikethrough && !isStrikeThroughVisible)
  3483. {
  3484. // Terminate Strikethrough if character is not visible.
  3485. beginStrikethrough = false;
  3486. strikethrough_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, m_textInfo.characterInfo[i - 1].baseLine + strikethroughOffset * strikethroughScale, 0);
  3487. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3488. }
  3489. }
  3490. else
  3491. {
  3492. // End Strikethrough
  3493. if (beginStrikethrough == true)
  3494. {
  3495. beginStrikethrough = false;
  3496. strikethrough_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, m_textInfo.characterInfo[i - 1].baseLine + strikethroughOffset * strikethroughScale, 0);
  3497. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3498. }
  3499. }
  3500. #endregion
  3501. // HANDLE TEXT HIGHLIGHTING
  3502. #region Text Highlighting
  3503. bool isHighlight = (m_textInfo.characterInfo[i].style & FontStyles.Highlight) == FontStyles.Highlight;
  3504. if (isHighlight)
  3505. {
  3506. bool isHighlightVisible = true;
  3507. int currentPage = m_textInfo.characterInfo[i].pageNumber;
  3508. if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && currentPage + 1 != m_pageToDisplay))
  3509. isHighlightVisible = false;
  3510. if (beginHighlight == false && isHighlightVisible == true && i <= lineInfo.lastVisibleCharacterIndex && unicode != 10 && unicode != 11 && unicode != 13)
  3511. {
  3512. if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(unicode))
  3513. { }
  3514. else
  3515. {
  3516. beginHighlight = true;
  3517. highlight_start = k_LargePositiveVector2;
  3518. highlight_end = k_LargeNegativeVector2;
  3519. highlightState = m_textInfo.characterInfo[i].highlightState;
  3520. }
  3521. }
  3522. if (beginHighlight)
  3523. {
  3524. TMP_CharacterInfo currentCharacter = m_textInfo.characterInfo[i];
  3525. HighlightState currentState = currentCharacter.highlightState;
  3526. bool isColorTransition = false;
  3527. // Handle Highlight color changes
  3528. if (highlightState != currentCharacter.highlightState)
  3529. {
  3530. // Adjust previous highlight section to prevent a gaps between sections.
  3531. highlight_end.x = (highlight_end.x - highlightState.padding.right + currentCharacter.bottomLeft.x) / 2;
  3532. highlight_start.y = Mathf.Min(highlight_start.y, currentCharacter.descender);
  3533. highlight_end.y = Mathf.Max(highlight_end.y, currentCharacter.ascender);
  3534. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3535. beginHighlight = true;
  3536. highlight_start = new Vector2(highlight_end.x, currentCharacter.descender - currentState.padding.bottom);
  3537. highlight_end = new Vector2(currentCharacter.topRight.x + currentState.padding.right, currentCharacter.ascender + currentState.padding.top);
  3538. highlightState = currentCharacter.highlightState;
  3539. isColorTransition = true;
  3540. }
  3541. if (!isColorTransition)
  3542. {
  3543. // Use the Min / Max Extents of the Highlight area to handle different character sizes and fonts.
  3544. highlight_start.x = Mathf.Min(highlight_start.x, currentCharacter.bottomLeft.x - highlightState.padding.left);
  3545. highlight_start.y = Mathf.Min(highlight_start.y, currentCharacter.descender - highlightState.padding.bottom);
  3546. highlight_end.x = Mathf.Max(highlight_end.x, currentCharacter.topRight.x + highlightState.padding.right);
  3547. highlight_end.y = Mathf.Max(highlight_end.y, currentCharacter.ascender + highlightState.padding.top);
  3548. }
  3549. }
  3550. // End Highlight if text only contains one character.
  3551. if (beginHighlight && m_characterCount == 1)
  3552. {
  3553. beginHighlight = false;
  3554. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3555. }
  3556. else if (beginHighlight && (i == lineInfo.lastCharacterIndex || i >= lineInfo.lastVisibleCharacterIndex))
  3557. {
  3558. beginHighlight = false;
  3559. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3560. }
  3561. else if (beginHighlight && !isHighlightVisible)
  3562. {
  3563. beginHighlight = false;
  3564. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3565. }
  3566. }
  3567. else
  3568. {
  3569. // End Highlight
  3570. if (beginHighlight == true)
  3571. {
  3572. beginHighlight = false;
  3573. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3574. }
  3575. }
  3576. #endregion
  3577. lastLine = currentLine;
  3578. }
  3579. #endregion
  3580. // Set vertex count for Underline geometry
  3581. //m_textInfo.meshInfo[m_Underline.materialIndex].vertexCount = last_vert_index;
  3582. // METRICS ABOUT THE TEXT OBJECT
  3583. m_textInfo.characterCount = m_characterCount;
  3584. m_textInfo.spriteCount = m_spriteCount;
  3585. m_textInfo.lineCount = lineCount;
  3586. m_textInfo.wordCount = wordCount != 0 && m_characterCount > 0 ? wordCount : 1;
  3587. m_textInfo.pageCount = m_pageNumber + 1;
  3588. // End Sampling of Phase II
  3589. k_GenerateTextPhaseIIMarker.End();
  3590. // Phase III - Update Mesh Vertex Data
  3591. k_GenerateTextPhaseIIIMarker.Begin();
  3592. if (m_renderMode == TextRenderFlags.Render && IsActive())
  3593. {
  3594. // Event to allow users to modify the content of the text info before the text is rendered.
  3595. OnPreRenderText?.Invoke(m_textInfo);
  3596. // Must ensure the Canvas support the additional vertex attributes used by TMP.
  3597. // This could be optimized based on canvas render mode settings but gets complicated to handle with multiple text objects using different material presets.
  3598. if (m_canvas.additionalShaderChannels != (AdditionalCanvasShaderChannels)25)
  3599. m_canvas.additionalShaderChannels |= (AdditionalCanvasShaderChannels)25;
  3600. // Sort the geometry of the text object if needed.
  3601. if (m_geometrySortingOrder != VertexSortingOrder.Normal)
  3602. m_textInfo.meshInfo[0].SortGeometry(VertexSortingOrder.Reverse);
  3603. // Upload Mesh Data
  3604. m_mesh.MarkDynamic();
  3605. m_mesh.vertices = m_textInfo.meshInfo[0].vertices;
  3606. m_mesh.uv = m_textInfo.meshInfo[0].uvs0;
  3607. m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
  3608. //m_mesh.uv4 = m_textInfo.meshInfo[0].uvs4;
  3609. m_mesh.colors32 = m_textInfo.meshInfo[0].colors32;
  3610. // Compute Bounds for the mesh. Manual computation is more efficient then using Mesh.RecalcualteBounds.
  3611. m_mesh.RecalculateBounds();
  3612. //m_mesh.bounds = new Bounds(new Vector3((m_meshExtents.max.x + m_meshExtents.min.x) / 2, (m_meshExtents.max.y + m_meshExtents.min.y) / 2, 0) + offset, new Vector3(m_meshExtents.max.x - m_meshExtents.min.x, m_meshExtents.max.y - m_meshExtents.min.y, 0));
  3613. m_canvasRenderer.SetMesh(m_mesh);
  3614. // Cache CanvasRenderer color of the parent text object.
  3615. Color parentBaseColor = m_canvasRenderer.GetColor();
  3616. bool isCullTransparentMeshEnabled = m_canvasRenderer.cullTransparentMesh;
  3617. for (int i = 1; i < m_textInfo.materialCount; i++)
  3618. {
  3619. // Clear unused vertices
  3620. m_textInfo.meshInfo[i].ClearUnusedVertices();
  3621. if (m_subTextObjects[i] == null) continue;
  3622. // Sort the geometry of the sub-text objects if needed.
  3623. if (m_geometrySortingOrder != VertexSortingOrder.Normal)
  3624. m_textInfo.meshInfo[i].SortGeometry(VertexSortingOrder.Reverse);
  3625. //m_subTextObjects[i].mesh.MarkDynamic();
  3626. m_subTextObjects[i].mesh.vertices = m_textInfo.meshInfo[i].vertices;
  3627. m_subTextObjects[i].mesh.uv = m_textInfo.meshInfo[i].uvs0;
  3628. m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  3629. //m_subTextObjects[i].mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
  3630. m_subTextObjects[i].mesh.colors32 = m_textInfo.meshInfo[i].colors32;
  3631. m_subTextObjects[i].mesh.RecalculateBounds();
  3632. m_subTextObjects[i].canvasRenderer.SetMesh(m_subTextObjects[i].mesh);
  3633. // Set CanvasRenderer color to match the parent text object.
  3634. m_subTextObjects[i].canvasRenderer.SetColor(parentBaseColor);
  3635. // Make sure Cull Transparent Mesh of the sub objects matches the parent
  3636. m_subTextObjects[i].canvasRenderer.cullTransparentMesh = isCullTransparentMeshEnabled;
  3637. // Sync RaycastTarget property with parent text object
  3638. m_subTextObjects[i].raycastTarget = this.raycastTarget;
  3639. }
  3640. }
  3641. // Event indicating the text has been regenerated.
  3642. TMPro_EventManager.ON_TEXT_CHANGED(this);
  3643. //Debug.Log("***** Done rendering text object ID " + GetInstanceID() + ". *****");
  3644. // End Sampling
  3645. k_GenerateTextPhaseIIIMarker.End();
  3646. k_GenerateTextMarker.End();
  3647. }
  3648. /// <summary>
  3649. /// Method to return the local corners of the Text Container or RectTransform.
  3650. /// </summary>
  3651. /// <returns></returns>
  3652. protected override Vector3[] GetTextContainerLocalCorners()
  3653. {
  3654. if (m_rectTransform == null) m_rectTransform = this.rectTransform;
  3655. m_rectTransform.GetLocalCorners(m_RectTransformCorners);
  3656. return m_RectTransformCorners;
  3657. }
  3658. /// <summary>
  3659. /// Method to Enable or Disable child SubMesh objects.
  3660. /// </summary>
  3661. /// <param name="state"></param>
  3662. protected override void SetActiveSubMeshes(bool state)
  3663. {
  3664. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  3665. {
  3666. if (m_subTextObjects[i].enabled != state)
  3667. m_subTextObjects[i].enabled = state;
  3668. }
  3669. }
  3670. /// <summary>
  3671. /// Destroy Sub Mesh Objects
  3672. /// </summary>
  3673. protected override void DestroySubMeshObjects()
  3674. {
  3675. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  3676. DestroyImmediate(m_subTextObjects[i]);
  3677. }
  3678. /// <summary>
  3679. /// Method returning the compound bounds of the text object and child sub objects.
  3680. /// </summary>
  3681. /// <returns></returns>
  3682. protected override Bounds GetCompoundBounds()
  3683. {
  3684. Bounds mainBounds = m_mesh.bounds;
  3685. Vector3 min = mainBounds.min;
  3686. Vector3 max = mainBounds.max;
  3687. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  3688. {
  3689. Bounds subBounds = m_subTextObjects[i].mesh.bounds;
  3690. min.x = min.x < subBounds.min.x ? min.x : subBounds.min.x;
  3691. min.y = min.y < subBounds.min.y ? min.y : subBounds.min.y;
  3692. max.x = max.x > subBounds.max.x ? max.x : subBounds.max.x;
  3693. max.y = max.y > subBounds.max.y ? max.y : subBounds.max.y;
  3694. }
  3695. Vector3 center = (min + max) / 2;
  3696. Vector2 size = max - min;
  3697. return new Bounds(center, size);
  3698. }
  3699. internal override Rect GetCanvasSpaceClippingRect()
  3700. {
  3701. if (m_canvas == null || m_canvas.rootCanvas == null || m_mesh == null)
  3702. return Rect.zero;
  3703. Transform rootCanvasTransform = m_canvas.rootCanvas.transform;
  3704. Bounds compoundBounds = GetCompoundBounds();
  3705. Vector2 position = rootCanvasTransform.InverseTransformPoint(m_rectTransform.position);
  3706. Vector2 canvasLossyScale = rootCanvasTransform.lossyScale;
  3707. Vector2 lossyScale = m_rectTransform.lossyScale / canvasLossyScale;
  3708. return new Rect(position + compoundBounds.min * lossyScale, compoundBounds.size * lossyScale);
  3709. }
  3710. /// <summary>
  3711. /// Method to Update Scale in UV2
  3712. /// </summary>
  3713. //void UpdateSDFScale(float lossyScale)
  3714. //{
  3715. // // TODO: Resolve - Underline / Strikethrough segments not getting their SDF Scale adjusted.
  3716. // //Debug.Log("Updating SDF Scale.");
  3717. // // Return if we don't have a valid reference to a Canvas.
  3718. // if (m_canvas == null)
  3719. // {
  3720. // m_canvas = GetCanvas();
  3721. // if (m_canvas == null) return;
  3722. // }
  3723. // lossyScale = lossyScale == 0 ? 1 : lossyScale;
  3724. // float xScale = 0;
  3725. // float canvasScaleFactor = m_canvas.scaleFactor;
  3726. // if (m_canvas.renderMode == RenderMode.ScreenSpaceOverlay)
  3727. // xScale = lossyScale / canvasScaleFactor;
  3728. // else if (m_canvas.renderMode == RenderMode.ScreenSpaceCamera)
  3729. // xScale = m_canvas.worldCamera != null ? lossyScale : 1;
  3730. // else
  3731. // xScale = lossyScale;
  3732. // // Iterate through each of the characters.
  3733. // for (int i = 0; i < m_textInfo.characterCount; i++)
  3734. // {
  3735. // // Only update scale for visible characters.
  3736. // if (m_textInfo.characterInfo[i].isVisible && m_textInfo.characterInfo[i].elementType == TMP_TextElementType.Character)
  3737. // {
  3738. // float scale = xScale * m_textInfo.characterInfo[i].scale * (1 - m_charWidthAdjDelta);
  3739. // if (!m_textInfo.characterInfo[i].isUsingAlternateTypeface && (m_textInfo.characterInfo[i].style & FontStyles.Bold) == FontStyles.Bold) scale *= -1;
  3740. // int index = m_textInfo.characterInfo[i].materialReferenceIndex;
  3741. // int vertexIndex = m_textInfo.characterInfo[i].vertexIndex;
  3742. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 0].y = scale;
  3743. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 1].y = scale;
  3744. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 2].y = scale;
  3745. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 3].y = scale;
  3746. // }
  3747. // }
  3748. // // Push the updated uv2 scale information to the meshes.
  3749. // for (int i = 0; i < m_textInfo.materialCount; i++)
  3750. // {
  3751. // if (i == 0)
  3752. // {
  3753. // m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
  3754. // m_canvasRenderer.SetMesh(m_mesh);
  3755. // }
  3756. // else
  3757. // {
  3758. // m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  3759. // m_subTextObjects[i].canvasRenderer.SetMesh(m_subTextObjects[i].mesh);
  3760. // }
  3761. // }
  3762. //}
  3763. /// <summary>
  3764. /// Method to update the SDF Scale in UV2.
  3765. /// </summary>
  3766. /// <param name="scaleDelta"></param>
  3767. void UpdateSDFScale(float scaleDelta)
  3768. {
  3769. if (scaleDelta == 0 || scaleDelta == float.PositiveInfinity || scaleDelta == float.NegativeInfinity)
  3770. {
  3771. m_havePropertiesChanged = true;
  3772. OnPreRenderCanvas();
  3773. return;
  3774. }
  3775. for (int materialIndex = 0; materialIndex < m_textInfo.materialCount; materialIndex ++)
  3776. {
  3777. TMP_MeshInfo meshInfo = m_textInfo.meshInfo[materialIndex];
  3778. for (int i = 0; i < meshInfo.uvs2.Length; i++)
  3779. {
  3780. meshInfo.uvs2[i].y *= Mathf.Abs(scaleDelta);
  3781. }
  3782. }
  3783. // Push the updated uv2 scale information to the meshes.
  3784. for (int i = 0; i < m_textInfo.materialCount; i++)
  3785. {
  3786. if (i == 0)
  3787. {
  3788. m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
  3789. m_canvasRenderer.SetMesh(m_mesh);
  3790. }
  3791. else
  3792. {
  3793. m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  3794. m_subTextObjects[i].canvasRenderer.SetMesh(m_subTextObjects[i].mesh);
  3795. }
  3796. }
  3797. }
  3798. }
  3799. }