UiTextComponent.cpp 217 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "UiTextComponent.h"
  9. #include <AzCore/Math/Crc.h>
  10. #include <AzCore/Math/MathUtils.h>
  11. #include <AzCore/Serialization/SerializeContext.h>
  12. #include <AzCore/Serialization/EditContext.h>
  13. #include <AzCore/RTTI/BehaviorContext.h>
  14. #include <AzCore/std/string/conversions.h>
  15. #include <AzCore/std/string/regex.h>
  16. #include <AzFramework/API/ApplicationAPI.h>
  17. #include <LyShine/Bus/UiTransform2dBus.h>
  18. #include <LyShine/Bus/UiElementBus.h>
  19. #include <LyShine/Bus/UiLayoutManagerBus.h>
  20. #include <LyShine/Bus/UiCanvasBus.h>
  21. #include <LyShine/UiSerializeHelpers.h>
  22. #include <LyShine/IRenderGraph.h>
  23. #include <LyShine/IDraw2d.h>
  24. #include <ILocalizationManager.h>
  25. #include "UiSerialize.h"
  26. #include "TextMarkup.h"
  27. #include "UiTextComponentOffsetsSelector.h"
  28. #include "StringUtfUtils.h"
  29. #include "UiLayoutHelpers.h"
  30. #include "RenderGraph.h"
  31. #include <AtomLyIntegration/AtomFont/FFont.h>
  32. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  33. namespace
  34. {
  35. AZStd::string DefaultDisplayedTextFunction(const AZStd::string& originalText)
  36. {
  37. // By default, the text component renders the string contents as-is
  38. return originalText;
  39. }
  40. bool RemoveV4MarkupFlag(
  41. [[maybe_unused]] AZ::SerializeContext& context,
  42. AZ::SerializeContext::DataElementNode& classElement)
  43. {
  44. int index = classElement.FindElement(AZ_CRC("SupportMarkup", 0x5e81a9c7));
  45. if (index != -1)
  46. {
  47. classElement.RemoveElement(index);
  48. }
  49. return true;
  50. }
  51. bool AddV8EnableMarkupFlag(
  52. AZ::SerializeContext& context,
  53. AZ::SerializeContext::DataElementNode& classElement)
  54. {
  55. // This element is a pre-version-8 text component. Prior to version 8 there was no MarkupEnabled
  56. // flag and markup was always enabled. Going forward, for new components we want to default to
  57. // markupEnabled = false because of the performance hit of parsing text strings for XML.
  58. // However, we want to be backward compatible with old data so for pre-version-8 components
  59. // we set the flag to true.
  60. // We considered searching the text string for characters such as "<&@" and only turning it on
  61. // if they were found. But the problem is that data patches do not come through version conversion
  62. // currently. So there could be markup in the text string in the data patch but we would not turn
  63. // the flag on. So the markup would stop working.
  64. // Just for safety check that the flag doesn't already exist
  65. int index = classElement.FindElement(AZ_CRC("MarkupEnabled"));
  66. if (index == -1)
  67. {
  68. // The element does not exist (it really never should at this version)
  69. // Add a data element, setting the flag to true
  70. int newElementIndex = classElement.AddElementWithData<bool>(context, "MarkupEnabled", true);
  71. if (newElementIndex == -1)
  72. {
  73. // Error adding the new data element
  74. AZ_Error("Serialization", false, "AddElement failed for MarkupEnabled element");
  75. return false;
  76. }
  77. }
  78. return true;
  79. }
  80. bool ConvertV3FontFileNameIfDefault(
  81. AZ::SerializeContext& context,
  82. AZ::SerializeContext::DataElementNode& classElement)
  83. {
  84. int index = classElement.FindElement(AZ_CRC("FontFileName", 0x44defd6f));
  85. if (index != -1)
  86. {
  87. AZ::SerializeContext::DataElementNode& fontFileNameNode = classElement.GetSubElement(index);
  88. index = fontFileNameNode.FindElement(AZ_CRC("BaseClass1", 0xd4925735));
  89. if (index != -1)
  90. {
  91. AZ::SerializeContext::DataElementNode& baseClassNode = fontFileNameNode.GetSubElement(index);
  92. index = baseClassNode.FindElement(AZ_CRC("AssetPath", 0x2c355179));
  93. if (index != -1)
  94. {
  95. AZ::SerializeContext::DataElementNode& assetPathNode = baseClassNode.GetSubElement(index);
  96. AZStd::string oldData;
  97. if (!assetPathNode.GetData(oldData))
  98. {
  99. AZ_Error("Serialization", false, "Element AssetPath is not a AZStd::string.");
  100. return false;
  101. }
  102. if (oldData == "default")
  103. {
  104. if (!assetPathNode.SetData(context, AZStd::string("default-ui")))
  105. {
  106. AZ_Error("Serialization", false, "Unable to set AssetPath data.");
  107. return false;
  108. }
  109. // The effect indicies have flip-flopped between the "default" and "default-ui"
  110. // fonts. Handle the conversion here.
  111. index = classElement.FindElement(AZ_CRC("EffectIndex", 0x4d3320e3));
  112. if (index != -1)
  113. {
  114. AZ::SerializeContext::DataElementNode& effectIndexNode = classElement.GetSubElement(index);
  115. uint32 effectIndex = 0;
  116. if (!effectIndexNode.GetData(effectIndex))
  117. {
  118. AZ_Error("Serialization", false, "Element EffectIndex is not an int.");
  119. return false;
  120. }
  121. uint32 newEffectIndex = effectIndex;
  122. // Only handle converting indices 1 and 0 in the rare (?) case that the user added
  123. // their own effects to the default font.
  124. if (newEffectIndex == 1)
  125. {
  126. newEffectIndex = 0;
  127. }
  128. else if (newEffectIndex == 0)
  129. {
  130. newEffectIndex = 1;
  131. }
  132. if (!effectIndexNode.SetData(context, newEffectIndex))
  133. {
  134. AZ_Error("Serialization", false, "Unable to set EffectIndex data.");
  135. return false;
  136. }
  137. }
  138. }
  139. }
  140. }
  141. }
  142. return true;
  143. }
  144. //! Migrate legacy shrink-to-fit setting to new ShrinkToFit enum.
  145. //!
  146. //! As of V8 of text component, the "shrink to fit" setting was a value of
  147. //! the WrapTextSetting enum. With V9, a new ShrinkToFit enum was introduced
  148. //! and offered an additional "width-only" option (previously, shrink-to-fit
  149. //! only performed uniform scaling along both axes).
  150. bool ConvertV8ShrinkToFitSetting(
  151. AZ::SerializeContext& context,
  152. AZ::SerializeContext::DataElementNode& classElement)
  153. {
  154. int index = classElement.FindElement(AZ_CRC("WrapTextSetting"));
  155. if (index != -1)
  156. {
  157. AZ::SerializeContext::DataElementNode& wrapTextSettingNode = classElement.GetSubElement(index);
  158. int oldWrapTextValue = 0;
  159. if (!wrapTextSettingNode.GetData<int>(oldWrapTextValue))
  160. {
  161. AZ_Error("Serialization", false, "Element WrapTextSetting is not an int.");
  162. return false;
  163. }
  164. // Check if WrapTextSetting is set to the legacy "ShrinkToFit" enum value.
  165. static const int shrinkToFitValue = 2;
  166. const bool shrinkToFitSettingNeedsUpdating = oldWrapTextValue == shrinkToFitValue;
  167. if (shrinkToFitSettingNeedsUpdating)
  168. {
  169. // It wasn't possible to word-wrap and have shrink-to-fit before, so we just
  170. // reset the wrap text setting to NoWrap to maintain backwards compatibilty.
  171. if (!wrapTextSettingNode.SetData<int>(context, static_cast<int>(UiTextInterface::WrapTextSetting::NoWrap)))
  172. {
  173. AZ_Error("Serialization", false, "Unable to set WrapTextSetting to NoWrap (%d).", static_cast<int>(UiTextInterface::WrapTextSetting::NoWrap));
  174. return false;
  175. }
  176. // If ShrinkToFit doesn't exist yet, add it
  177. index = classElement.FindElement(AZ_CRC("ShrinkToFit"));
  178. if (index == -1)
  179. {
  180. index = classElement.AddElement<int>(context, "ShrinkToFit");
  181. if (index == -1)
  182. {
  183. // Error adding the new sub element
  184. AZ_Error("Serialization", false, "Failed to create ShrinkToFit node");
  185. return false;
  186. }
  187. }
  188. // Legacy shrink-to-fit only applied uniform scaling along both axes. So here we use
  189. // the Uniform setting of ShrinkToFit to maintain backwards compatibility.
  190. AZ::SerializeContext::DataElementNode& shrinkToFitNode = classElement.GetSubElement(index);
  191. if (!shrinkToFitNode.SetData<int>(context, static_cast<int>(UiTextInterface::ShrinkToFit::Uniform)))
  192. {
  193. AZ_Error("Serialization", false, "Unable to set ShrinkToFit to Uniform (%d).", static_cast<int>(UiTextInterface::ShrinkToFit::Uniform));
  194. return false;
  195. }
  196. }
  197. }
  198. return true;
  199. }
  200. //! Remove an older OverflowMode setting that no longer has any effect.
  201. //!
  202. //! There used to be an overflow mode setting called "ResizeToText". It
  203. //! was removed, but some canvases still have the enum value set to it,
  204. //! which would now set those text fields to ellipsis, which isn't intended.
  205. //!
  206. //! Reset the field back to zero (overflow) since the property hasn't had any
  207. //! effect since ResizeToText was removed anyways.
  208. bool ConvertV8LegacyOverflowModeSetting(
  209. AZ::SerializeContext& context,
  210. AZ::SerializeContext::DataElementNode& classElement)
  211. {
  212. int index = classElement.FindElement(AZ_CRC("OverflowMode"));
  213. if (index != -1)
  214. {
  215. AZ::SerializeContext::DataElementNode& overflowModeSettingNode = classElement.GetSubElement(index);
  216. int oldOverflowModeValue = 0;
  217. if (!overflowModeSettingNode.GetData<int>(oldOverflowModeValue))
  218. {
  219. AZ_Error("Serialization", false, "Element OverflowMode is not an int.");
  220. return false;
  221. }
  222. // Check if OverflowMode is set to the legacy "ResizeToText" enum value.
  223. static const int legacyResizeToTextValue = 2;
  224. const bool overflowModeSettingNeedsUpdating = oldOverflowModeValue == legacyResizeToTextValue;
  225. if (overflowModeSettingNeedsUpdating)
  226. {
  227. // This value enum was removed without version conversion. Since it hasn't had any effect
  228. // up to this point, we just reset the OverflowMode back to default (overflow).
  229. if (!overflowModeSettingNode.SetData<int>(context, static_cast<int>(UiTextInterface::OverflowMode::OverflowText)))
  230. {
  231. AZ_Error("Serialization", false, "Unable to set OverflowMode to OverflowText (%d).", static_cast<int>(UiTextInterface::OverflowMode::OverflowText));
  232. return false;
  233. }
  234. }
  235. }
  236. return true;
  237. }
  238. void SanitizeUserEnteredNewlineChar(AZStd::string& stringToSanitize)
  239. {
  240. // Convert user-entered newline delimiters to proper ones before wrapping
  241. // the text so they can be correctly accounted for.
  242. static const AZStd::string NewlineDelimiter("\n");
  243. static const AZStd::regex UserInputNewlineDelimiter("\\\\n");
  244. stringToSanitize = AZStd::regex_replace(stringToSanitize, UserInputNewlineDelimiter, NewlineDelimiter);
  245. }
  246. //! Builds a list of DrawBatch objects from a XML tag tree.
  247. //!
  248. //! A DrawBatch is essentially render "state" for text. This method tries
  249. //! to determine what the current state is that should be applied based
  250. //! on the tag tree traversal. Once all of a tag's children are
  251. //! traversed, and a new DrawBatch was created, the batch is popped off
  252. //! the batch stack and moved into the DrawBatch output list.
  253. //!
  254. //! Example usage:
  255. //!
  256. //! TextMarkup::Tag markupRoot;
  257. //! if (TextMarkup::ParseMarkupBuffer(markupText, markupRoot))
  258. //! {
  259. //! AZStd::stack<UiTextComponent::DrawBatch> batchStack;
  260. //! AZStd::stack<FontFamily*> fontFamilyStack;
  261. //! fontFamilyStack.push(m_fontFamily.get());
  262. //! BuildDrawBatches(drawBatches, batchStack, fontFamilyStack, &markupRoot);
  263. //! }
  264. //!
  265. //! \param output List of DrawBatch objects built based on tag tree contents
  266. //! \param fontFamilyRefs List of Font Family's that output (strongly) references.
  267. //! \param inlineImages List of Inline Images that are created while building the draw batches
  268. //! \param fontHeight The height of the font
  269. //! \param fontAscent The ascent of the font
  270. //! \param batchStack The DrawBatch on "top" of the stack is the state that is currently active.
  271. //! \param fontFamilyStack The FontFamily on top of the stack is the font family that's currently active.
  272. //! The font family can change when the font tag is encountered.
  273. //! \param currentTag Current tag being visited in the parsed tag tree.
  274. void BuildDrawBatches(
  275. UiTextComponent::DrawBatchContainer& output,
  276. UiTextComponent::FontFamilyRefSet& fontFamilyRefs,
  277. UiTextComponent::InlineImageContainer& inlineImages,
  278. float fontHeight,
  279. float fontAscent,
  280. AZStd::stack<UiTextComponent::DrawBatch>& batchStack,
  281. AZStd::stack<FontFamily*>& fontFamilyStack,
  282. const TextMarkup::Tag* currentTag,
  283. int& clickableId)
  284. {
  285. TextMarkup::TagType type = currentTag->GetType();
  286. const bool isRoot = type == TextMarkup::TagType::Root;
  287. bool newBatchStackPushed = false;
  288. // Root tag doesn't push any new state
  289. if (!isRoot)
  290. {
  291. if (batchStack.empty())
  292. {
  293. batchStack.push(UiTextComponent::DrawBatch());
  294. newBatchStackPushed = true;
  295. // For new batches, use the Font Family's "normal" font by default
  296. batchStack.top().font = fontFamilyStack.top()->normal;
  297. }
  298. // Prevent creating a new DrawBatch if the "current" batch has
  299. // no text associated with it yet.
  300. else if (!batchStack.top().text.empty())
  301. {
  302. // Create a copy of the top
  303. batchStack.push(batchStack.top());
  304. newBatchStackPushed = true;
  305. // We assume that a DrawBatch will eventually get its own
  306. // text assigned, but in case no character was specified
  307. // in the markup, we explicitly clear the text here to avoid
  308. // showing duplicate text.
  309. batchStack.top().text.clear();
  310. }
  311. }
  312. // We need the previous batch for all cases except the root case
  313. // (where there is no previous batch). To streamline handling this
  314. // case, we just create an unused default-constructed DrawBatch
  315. // for the root case.
  316. const UiTextComponent::DrawBatch& prevBatch = batchStack.empty() ? UiTextComponent::DrawBatch() : batchStack.top();
  317. bool newFontFamilyPushed = false;
  318. switch (type)
  319. {
  320. case TextMarkup::TagType::Text:
  321. {
  322. batchStack.top().text = (static_cast<const TextMarkup::TextTag*>(currentTag))->text;
  323. // Replace escaped newlines with actual newlines
  324. batchStack.top().text = AZStd::regex_replace(batchStack.top().text, AZStd::regex("\\\\n"), "\n");
  325. break;
  326. }
  327. case TextMarkup::TagType::Image:
  328. {
  329. const TextMarkup::ImageTag* pImageTag = static_cast<const TextMarkup::ImageTag*>(currentTag);
  330. // Image tag isn't affected by any other tag so add a new draw batch directly to the output
  331. UiTextComponent::InlineImage::VAlign vAlign = UiTextComponent::InlineImage::VAlign::Baseline;
  332. if (pImageTag->m_vAlign == "baseline")
  333. {
  334. vAlign = UiTextComponent::InlineImage::VAlign::Baseline;
  335. }
  336. else if (pImageTag->m_vAlign == "top")
  337. {
  338. vAlign = UiTextComponent::InlineImage::VAlign::Top;
  339. }
  340. else if (pImageTag->m_vAlign == "center")
  341. {
  342. vAlign = UiTextComponent::InlineImage::VAlign::Center;
  343. }
  344. else if (pImageTag->m_vAlign == "bottom")
  345. {
  346. vAlign = UiTextComponent::InlineImage::VAlign::Bottom;
  347. }
  348. float imageHeight = fontAscent;
  349. if (pImageTag->m_height == "fontHeight")
  350. {
  351. imageHeight = fontHeight;
  352. }
  353. else if (pImageTag->m_height == "fontAscent")
  354. {
  355. imageHeight = fontAscent;
  356. }
  357. else if (!pImageTag->m_height.empty())
  358. {
  359. imageHeight = AZ::GetMax(0.0f, AZStd::stof(pImageTag->m_height));
  360. }
  361. UiTextComponent::InlineImage* inlineImage = new UiTextComponent::InlineImage(pImageTag->m_imagePathname,
  362. imageHeight,
  363. pImageTag->m_scale,
  364. vAlign,
  365. pImageTag->m_yOffset,
  366. pImageTag->m_leftPadding,
  367. pImageTag->m_rightPadding);
  368. inlineImages.push_back(inlineImage);
  369. UiTextComponent::DrawBatch drawBatch;
  370. drawBatch.image = inlineImages.back();
  371. output.push_back(drawBatch);
  372. break;
  373. }
  374. case TextMarkup::TagType::Bold:
  375. {
  376. if (prevBatch.font == fontFamilyStack.top()->bold)
  377. {
  378. // adjacent bold tags, no need to push a new batch
  379. break;
  380. }
  381. else if (prevBatch.font == fontFamilyStack.top()->italic)
  382. {
  383. // We're on a bold tag, but current font applied is
  384. // italic, so we apply the bold-italic font.
  385. batchStack.top().font = fontFamilyStack.top()->boldItalic;
  386. }
  387. else
  388. {
  389. batchStack.top().font = fontFamilyStack.top()->bold;
  390. }
  391. break;
  392. }
  393. case TextMarkup::TagType::Italic:
  394. {
  395. if (prevBatch.font == fontFamilyStack.top()->italic)
  396. {
  397. // adjacent italic tags, no need to push a new batch
  398. break;
  399. }
  400. else if (prevBatch.font == fontFamilyStack.top()->bold)
  401. {
  402. // We're on an italic tag, but current font applied is
  403. // bold, so we apply the bold-italic font.
  404. batchStack.top().font = fontFamilyStack.top()->boldItalic;
  405. }
  406. else
  407. {
  408. batchStack.top().font = fontFamilyStack.top()->italic;
  409. }
  410. break;
  411. }
  412. case TextMarkup::TagType::Anchor:
  413. {
  414. const TextMarkup::AnchorTag* pAnchorTag = static_cast<const TextMarkup::AnchorTag*>(currentTag);
  415. batchStack.top().action = pAnchorTag->action;
  416. batchStack.top().data = pAnchorTag->data;
  417. batchStack.top().clickableId = ++clickableId;
  418. break;
  419. }
  420. case TextMarkup::TagType::Font:
  421. {
  422. const TextMarkup::FontTag* pFontTag = static_cast<const TextMarkup::FontTag*>(currentTag);
  423. if (!(pFontTag->face.empty()))
  424. {
  425. FontFamilyPtr pFontFamily = gEnv->pCryFont->GetFontFamily(pFontTag->face.c_str());
  426. if (!pFontFamily)
  427. {
  428. pFontFamily = gEnv->pCryFont->LoadFontFamily(pFontTag->face.c_str());
  429. }
  430. // Still need to check for pFontFamily validity since
  431. // Font Family load could have failed.
  432. if (pFontFamily)
  433. {
  434. // Important to strongly reference the Font Family
  435. // here otherwise it will de-ref once we go out of
  436. // scope (and possibly unload).
  437. fontFamilyRefs.insert(pFontFamily);
  438. if (fontFamilyStack.top() != pFontFamily.get())
  439. {
  440. fontFamilyStack.push(pFontFamily.get());
  441. newFontFamilyPushed = true;
  442. // Reset font to default face for new font family
  443. batchStack.top().font = pFontFamily->normal;
  444. }
  445. }
  446. else
  447. {
  448. AZ_Warning("UiTextComponent", false, "Failed to find font family referenced in markup (BuildDrawBatches): %s", pFontTag->face.c_str());
  449. }
  450. }
  451. const bool newColorNeeded = pFontTag->color != prevBatch.color;
  452. const bool tagHasValidColor = pFontTag->color != TextMarkup::ColorInvalid;
  453. if (newColorNeeded && tagHasValidColor)
  454. {
  455. batchStack.top().color = pFontTag->color;
  456. }
  457. break;
  458. }
  459. default:
  460. {
  461. break;
  462. }
  463. }
  464. // We only want to push a DrawBatch when it has text to display. We
  465. // store character data in separate tags. So when a bold tag is
  466. // traversed, we haven't yet visited its child character data:
  467. // <b> <!-- Bold tag DrawBatch created, no text yet -->
  468. // <ch>Child character data here</ch>
  469. // </b>
  470. if (!batchStack.empty() && !batchStack.top().text.empty())
  471. {
  472. output.push_back(batchStack.top());
  473. }
  474. // Depth-first traversal of children tags.
  475. auto iter = currentTag->children.begin();
  476. for (; iter != currentTag->children.end(); ++iter)
  477. {
  478. BuildDrawBatches(output, fontFamilyRefs, inlineImages, fontHeight, fontAscent, batchStack, fontFamilyStack, *iter, clickableId);
  479. }
  480. // Children visited, clear newly created DrawBatch state.
  481. if (newBatchStackPushed)
  482. {
  483. batchStack.pop();
  484. }
  485. // Clear FontFamily state also.
  486. if (newFontFamilyPushed)
  487. {
  488. fontFamilyStack.pop();
  489. }
  490. }
  491. void BuildDrawBatchesAndAssignClickableIds(
  492. UiTextComponent::DrawBatchContainer& output,
  493. UiTextComponent::FontFamilyRefSet& fontFamilyRefs,
  494. UiTextComponent::InlineImageContainer& inlineImages,
  495. float fontHeight,
  496. float fontAscent,
  497. AZStd::stack<UiTextComponent::DrawBatch>& batchStack,
  498. AZStd::stack<FontFamily*>& fontFamilyStack,
  499. const TextMarkup::Tag* currentTag)
  500. {
  501. int clickableId = -1;
  502. BuildDrawBatches(
  503. output,
  504. fontFamilyRefs,
  505. inlineImages,
  506. fontHeight,
  507. fontAscent,
  508. batchStack,
  509. fontFamilyStack,
  510. currentTag,
  511. clickableId
  512. );
  513. }
  514. //! Use the given width and font context to insert newline breaks in the given DrawBatchList.
  515. //! This code is largely adapted from FFont::WrapText to work with DrawBatch objects.
  516. void InsertNewlinesToWrapText(
  517. UiTextComponent::DrawBatchContainer& drawBatches,
  518. const STextDrawContext& ctx,
  519. float elementWidth)
  520. {
  521. if (drawBatches.empty())
  522. {
  523. return;
  524. }
  525. // Keep track of the last space char we encountered as ideal
  526. // locations for inserting newlines for word-wrapping. We also need
  527. // to track which DrawBatch contained the last-encountered space.
  528. const char* pLastSpace = NULL;
  529. UiTextComponent::DrawBatch* lastSpaceBatch = nullptr;
  530. int lastSpace = -1;
  531. int lastSpaceIndexInBatch = -1;
  532. float lastSpaceWidth = 0.0f;
  533. int curChar = 0;
  534. float curLineWidth = 0.0f;
  535. float biggestLineWidth = 0.0f;
  536. // When iterating over batches, we need to know the previous
  537. // character, which we can only obtain if we keep track of the last
  538. // batch we iterated on.
  539. UiTextComponent::DrawBatch* prevBatch = &drawBatches.front();
  540. // Map draw batches to text indices where spaces should be restored
  541. // (more details below); this happens after we've inserted newlines
  542. // for word-wrapping.
  543. using SpaceIndices = AZStd::vector < int >;
  544. AZStd::unordered_map<UiTextComponent::DrawBatch*, SpaceIndices> batchSpaceIndices;
  545. // Iterate over all drawbatches, calculating line length and add newlines
  546. // when element width is exceeded. Reset line length when a newline is added
  547. // or a newline is encountered.
  548. for (UiTextComponent::DrawBatch& drawBatch : drawBatches)
  549. {
  550. // If this entry ultimately ends up not having any space char
  551. // indices associated with it, we will simply skip iterating over
  552. // it later.
  553. batchSpaceIndices.insert(&drawBatch);
  554. int batchCurChar = 0;
  555. Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
  556. uint32_t prevCh = 0;
  557. while (uint32_t ch = *pChar)
  558. {
  559. size_t maxSize = 5;
  560. char codepoint[5] = { 0 };
  561. char* codepointPtr = codepoint;
  562. Utf8::Unchecked::octet_iterator<AZStd::string::iterator>::to_utf8_sequence(ch, codepointPtr, maxSize);
  563. float curCharWidth = drawBatch.font->GetTextSize(codepoint, true, ctx).x;
  564. if (prevCh && ctx.m_kerningEnabled)
  565. {
  566. curCharWidth += drawBatch.font->GetKerning(prevCh, ch, ctx).x;
  567. }
  568. if (prevCh)
  569. {
  570. curCharWidth += ctx.m_tracking;
  571. }
  572. prevCh = ch;
  573. // keep track of spaces
  574. // they are good for splitting the string
  575. if (ch == ' ')
  576. {
  577. lastSpace = curChar;
  578. lastSpaceIndexInBatch = batchCurChar;
  579. lastSpaceBatch = &drawBatch;
  580. lastSpaceWidth = curLineWidth + curCharWidth;
  581. pLastSpace = pChar.base();
  582. assert(*pLastSpace == ' ');
  583. }
  584. bool prevCharWasNewline = false;
  585. const bool isFirstChar = pChar.base() == drawBatch.text.c_str();
  586. if (ch && !isFirstChar)
  587. {
  588. const char* pPrevCharStr = pChar.base() - 1;
  589. prevCharWasNewline = pPrevCharStr[0] == '\n';
  590. }
  591. else if (isFirstChar)
  592. {
  593. // Since prevBatch is initialized to front of drawBatches,
  594. // check to ensure there was a previous batch.
  595. const bool prevBatchValid = prevBatch != &drawBatch;
  596. if (prevBatchValid && !prevBatch->text.empty())
  597. {
  598. prevCharWasNewline = prevBatch->text.at(prevBatch->text.length() - 1) == '\n';
  599. }
  600. }
  601. // line must contain some content, otherwise single characters larger than
  602. // the element width would wrap themselves.
  603. const bool lineContainsContent = curLineWidth > 0.0f;
  604. // if line exceed allowed width, split it
  605. const bool lineWidthExceeded = lineContainsContent && (curLineWidth + curCharWidth) > elementWidth;
  606. if (prevCharWasNewline || (lineWidthExceeded && ch))
  607. {
  608. if (prevCharWasNewline)
  609. {
  610. // Reset the current line width to account for newline
  611. curLineWidth = curCharWidth;
  612. }
  613. else if ((lastSpace > 0) && ((curChar - lastSpace) < 16) && (curChar - lastSpace >= 0)) // 16 is the default threshold
  614. {
  615. *(char*)pLastSpace = '\n'; // This is safe inside UTF-8 because space is single-byte codepoint
  616. batchSpaceIndices.at(lastSpaceBatch).push_back(lastSpaceIndexInBatch);
  617. if (lastSpaceWidth > biggestLineWidth)
  618. {
  619. biggestLineWidth = lastSpaceWidth;
  620. }
  621. curLineWidth = curLineWidth - lastSpaceWidth + curCharWidth;
  622. }
  623. else
  624. {
  625. char* pBuf = pChar.base();
  626. AZStd::string::size_type bytesProcessed = pBuf - drawBatch.text.c_str();
  627. drawBatch.text.insert(bytesProcessed, "\n"); // Insert the newline, this invalidates the iterator
  628. pBuf = drawBatch.text.data() + bytesProcessed; // In case reallocation occurs, we ensure we are inside the new buffer
  629. assert(*pBuf == '\n');
  630. pChar = Utf8::Unchecked::octet_iterator(pBuf); // pChar once again points inside the target string, at the current character
  631. ++pChar;
  632. assert(*pChar == ch);
  633. ++curChar;
  634. ++batchCurChar;
  635. if (curLineWidth > biggestLineWidth)
  636. {
  637. biggestLineWidth = curLineWidth;
  638. }
  639. curLineWidth = curCharWidth;
  640. }
  641. lastSpaceWidth = 0;
  642. lastSpace = 0;
  643. }
  644. else
  645. {
  646. curLineWidth += curCharWidth;
  647. }
  648. curChar += LyShine::GetMultiByteCharSize(ch);
  649. batchCurChar += LyShine::GetMultiByteCharSize(ch);
  650. ++pChar;
  651. }
  652. prevBatch = &drawBatch;
  653. }
  654. // We insert newline breaks (perform word-wrapping) in-place for
  655. // formatting purposes, but we restore the original delimiting
  656. // space characters now. This resolves a lot of issues with indices
  657. // mismatching between the rendered string content and the original
  658. // string.
  659. //
  660. // This seems unintuitive since (above) we simply (in some cases)
  661. // replace the space character with newline, so inserting an additional
  662. // space now would mismatch the original string contents even further.
  663. // However, since draw batch "lines" are delimited by newline, the
  664. // newline character will eventually be removed (because it will be
  665. // implied). So at this part in the pipeline, the strings will not
  666. // match in content or length, but eventually will.
  667. for (auto& batchSpaceList : batchSpaceIndices)
  668. {
  669. UiTextComponent::DrawBatch* drawBatch = batchSpaceList.first;
  670. const SpaceIndices& spaceIndices = batchSpaceList.second;
  671. int insertOffset = 0;
  672. for (const int spaceIndex : spaceIndices)
  673. {
  674. drawBatch->text.insert(spaceIndex + insertOffset, 1, ' ');
  675. // Each time we insert, our indices our off by one.
  676. ++insertOffset;
  677. }
  678. }
  679. }
  680. //! Given a "flat" list of DrawBatches, separate them by newline and place in output.
  681. void CreateBatchLines(
  682. UiTextComponent::DrawBatchLines& output,
  683. UiTextComponent::DrawBatchContainer& drawBatches,
  684. FontFamily* defaultFontFamily)
  685. {
  686. UiTextComponent::DrawBatchLineContainer& lineList = output.batchLines;
  687. lineList.push_back(UiTextComponent::DrawBatchLine());
  688. for (UiTextComponent::DrawBatch& drawBatch : drawBatches)
  689. {
  690. AZStd::string::size_type newlineIndex = drawBatch.text.find('\n');
  691. if (newlineIndex == AZStd::string::npos)
  692. {
  693. lineList.back().drawBatchList.push_back(drawBatch);
  694. continue;
  695. }
  696. while (newlineIndex != AZStd::string::npos)
  697. {
  698. // Found a newline within a single drawbatch, so split
  699. // into two batches, one for the current line, and one
  700. // for the following.
  701. UiTextComponent::DrawBatchContainer& currentLine = lineList.back().drawBatchList;
  702. lineList.push_back(UiTextComponent::DrawBatchLine());
  703. UiTextComponent::DrawBatchContainer& newLine = lineList.back().drawBatchList;
  704. const bool moreCharactersAfterNewline = drawBatch.text.length() - 1 > newlineIndex;
  705. // Note that we purposely build the string such that the newline
  706. // character is truncated from the string. If it were included,
  707. // it would be doubly-accounted for in the renderer.
  708. UiTextComponent::DrawBatch splitBatch(drawBatch);
  709. splitBatch.text = drawBatch.text.substr(0, newlineIndex);
  710. currentLine.push_back(splitBatch);
  711. // Start a new newline
  712. if (moreCharactersAfterNewline)
  713. {
  714. const AZStd::string::size_type endOfStringIndex = drawBatch.text.length() - newlineIndex - 1;
  715. drawBatch.text = drawBatch.text.substr(newlineIndex + 1, endOfStringIndex);
  716. newlineIndex = drawBatch.text.find('\n');
  717. if (newlineIndex == AZStd::string::npos)
  718. {
  719. newLine.push_back(drawBatch);
  720. }
  721. }
  722. else
  723. {
  724. break;
  725. }
  726. }
  727. }
  728. // Push an empty DrawBatch if the string happened to end with a
  729. // newline but no following text (e.g. "Hello\n").
  730. // :TODO: is this still needed? Can the final DrawBatchLine be removed
  731. // altogether if it has no content?
  732. if (lineList.back().drawBatchList.empty())
  733. {
  734. lineList.back().drawBatchList.push_back(UiTextComponent::DrawBatch());
  735. lineList.back().drawBatchList.front().font = defaultFontFamily->normal;
  736. }
  737. }
  738. void AssignLineSizes(
  739. UiTextComponent::DrawBatchLines& output,
  740. [[maybe_unused]] FontFamily* fontFamily,
  741. const STextDrawContext& ctx,
  742. bool excludeTrailingSpace = true)
  743. {
  744. output.height = 0.0f;
  745. for (UiTextComponent::DrawBatchLine& drawBatchLine : output.batchLines)
  746. {
  747. // First calculate the batch sizes
  748. for (auto drawBatchIterator = drawBatchLine.drawBatchList.begin(); drawBatchIterator != drawBatchLine.drawBatchList.end(); ++drawBatchIterator)
  749. {
  750. // Exclude trailing space from the last batch in the line
  751. bool excludeTrailingSpaceFromLine = excludeTrailingSpace ? (AZStd::next(drawBatchIterator) == drawBatchLine.drawBatchList.end()) : false;
  752. drawBatchIterator->CalculateSize(ctx, excludeTrailingSpaceFromLine);
  753. }
  754. // Calculate the batch y offsets from the text y position based on the text's baseline
  755. for (UiTextComponent::DrawBatch& drawBatch : drawBatchLine.drawBatchList)
  756. {
  757. drawBatch.CalculateYOffset(ctx.m_size.y, output.baseline);
  758. }
  759. // Figure out the highest batch offset above the text y position
  760. float minYOffset = 0.0f;
  761. for (UiTextComponent::DrawBatch& drawBatch : drawBatchLine.drawBatchList)
  762. {
  763. minYOffset = AZ::GetMin<float>(minYOffset, drawBatch.yOffset);
  764. }
  765. // Update the batch y offsets so they all become a positive offset from the y draw position of the batch line
  766. for (UiTextComponent::DrawBatch& drawBatch : drawBatchLine.drawBatchList)
  767. {
  768. drawBatch.yOffset -= minYOffset;
  769. }
  770. // Now calculate the size of the line
  771. float width = 0.0f;
  772. float height = 0.0f;
  773. for (const UiTextComponent::DrawBatch& drawBatch : drawBatchLine.drawBatchList)
  774. {
  775. width += drawBatch.size.GetX();
  776. height = AZ::GetMax<float>(height, drawBatch.yOffset + drawBatch.size.GetY());
  777. }
  778. drawBatchLine.lineSize.SetX(width);
  779. drawBatchLine.lineSize.SetY(height);
  780. output.height += height;
  781. }
  782. }
  783. //! Takes a flat list of draw batches (created by the Draw Batch Builder) and groups them
  784. //! by line, taking the element width into account, and also taking any newline characters
  785. //! that may already exist within the character data of the DrawBatch objects
  786. void BatchAwareWrapText(
  787. UiTextComponent::DrawBatchLines& output,
  788. UiTextComponent::DrawBatchContainer& drawBatches,
  789. FontFamily* fontFamily,
  790. const STextDrawContext& ctx,
  791. float elementWidth,
  792. bool excludeTrailingSpaceWidth = true)
  793. {
  794. InsertNewlinesToWrapText(drawBatches, ctx, elementWidth);
  795. CreateBatchLines(output, drawBatches, fontFamily);
  796. AssignLineSizes(output, fontFamily, ctx, excludeTrailingSpaceWidth);
  797. }
  798. //! Takes a flat list of draw batches (created by the Draw Batch Builder) that may contain
  799. //! non-text elements (such as images) and groups them by line, taking the element width into
  800. //! account, and also taking any newline characters that may already exist within the character
  801. //! data of the DrawBatch objects
  802. void BatchAwareWrapTextWithImages(
  803. UiTextComponent::DrawBatchLines& output,
  804. UiTextComponent::DrawBatchContainer& drawBatches,
  805. FontFamily* fontFamily,
  806. const STextDrawContext& ctx,
  807. float elementWidth,
  808. bool excludeTrailingSpaceWidth = true
  809. )
  810. {
  811. // Create batch lines based on existing newline characters
  812. CreateBatchLines(output, drawBatches, fontFamily);
  813. // Iterate over each line and split the line if it runs over the allowed width
  814. for (auto batchLinesIterator = output.batchLines.begin(); batchLinesIterator != output.batchLines.end(); batchLinesIterator++)
  815. {
  816. UiTextComponent::DrawBatchLine newBatchLineOut;
  817. // Check whether the line exceeds the allowed width and split the line if needed
  818. bool split = batchLinesIterator->CheckAndSplitLine(ctx, elementWidth, newBatchLineOut);
  819. if (split && !newBatchLineOut.drawBatchList.empty())
  820. {
  821. // Insert new line
  822. output.batchLines.insert_after(batchLinesIterator, newBatchLineOut);
  823. }
  824. }
  825. AssignLineSizes(output, fontFamily, ctx, excludeTrailingSpaceWidth);
  826. }
  827. //! Returns the maximum scale value along the X and Y axes for the given entity's transform.
  828. float GetMax2dTransformScale(AZ::EntityId entityId)
  829. {
  830. AZ::Matrix4x4 elementTransform = AZ::Matrix4x4::CreateIdentity();
  831. UiTransformBus::Event(entityId, &UiTransformBus::Events::GetTransformToCanvasSpace, elementTransform);
  832. const AZ::Vector3 elementScale = elementTransform.RetrieveScale();
  833. return AZ::GetMax<float>(elementScale.GetX(), elementScale.GetY());
  834. }
  835. //! Returns the size of the given font after scale-to-device and entity transform scales have been applied.
  836. int CalcRequestFontSize(float fontSize, AZ::EntityId entityId)
  837. {
  838. const float max2dTransformScale = GetMax2dTransformScale(entityId);
  839. return static_cast<int>(fontSize * max2dTransformScale);
  840. }
  841. //! Clips an inline image markup quad and UVs to the defined region
  842. //!
  843. //! \param imageQuad Array of 4 vertices defining the image quad
  844. //! \param uvs Array of 4 UV coordinates for the textured quad
  845. //! \param points Region to clip quad and UVs to
  846. //! \param drawBatch The DrawBatch containing the inline image
  847. //! \param imageStartPos Upper-left coordinate of unclipped image
  848. //! \param imageEndPos Bottom-right coordinate of unclipped image
  849. void ClipImageQuadAndUvs(
  850. AZ::Vector3* imageQuad,
  851. AZ::Vector2* uvs,
  852. const UiTransformInterface::RectPoints& points,
  853. const UiTextComponent::DrawBatch& drawBatch,
  854. const AZ::Vector2& imageStartPos,
  855. const AZ::Vector2& imageEndPos)
  856. {
  857. const bool imageLeftOfElement = imageStartPos.GetX() < points.TopLeft().GetX();
  858. const bool imageRightOfElement = imageEndPos.GetX() > points.TopRight().GetX();
  859. const bool imageTopOfElement = imageStartPos.GetY() < points.TopLeft().GetY();
  860. const bool imageBottomOfElement = imageEndPos.GetY() > points.BottomLeft().GetY();
  861. if (imageLeftOfElement)
  862. {
  863. imageQuad[0].SetX(AZStd::GetMin<float>(points.TopLeft().GetX(), imageEndPos.GetX()));
  864. imageQuad[3].SetX(imageQuad[0].GetX());
  865. const float diff = points.TopLeft().GetX() - imageStartPos.GetX();
  866. const float uvScale = diff / drawBatch.image->m_size.GetX();
  867. uvs[0].SetX(uvScale);
  868. uvs[3].SetX(uvScale);
  869. }
  870. if (imageRightOfElement)
  871. {
  872. imageQuad[1].SetX(AZStd::GetMax<float>(points.TopRight().GetX(), imageStartPos.GetX()));
  873. imageQuad[2].SetX(imageQuad[1].GetX());
  874. const float diff = imageEndPos.GetX() - points.TopRight().GetX();
  875. const float uvScale = diff / drawBatch.image->m_size.GetX();
  876. uvs[1].SetX(1.0f - uvScale);
  877. uvs[2].SetX(1.0f - uvScale);
  878. }
  879. if (imageTopOfElement)
  880. {
  881. imageQuad[0].SetY(AZStd::GetMin<float>(points.TopLeft().GetY(), imageEndPos.GetY()));
  882. imageQuad[1].SetY(imageQuad[0].GetY());
  883. const float diff = points.TopLeft().GetY() - imageStartPos.GetY();
  884. const float uvScale = diff / drawBatch.image->m_size.GetY();
  885. uvs[0].SetY(uvScale);
  886. uvs[1].SetY(uvScale);
  887. }
  888. if (imageBottomOfElement)
  889. {
  890. imageQuad[2].SetY(AZStd::GetMax<float>(points.BottomLeft().GetY(), imageStartPos.GetY()));
  891. imageQuad[3].SetY(imageQuad[2].GetY());
  892. const float diff = imageEndPos.GetY() - points.BottomLeft().GetY();
  893. const float uvScale = diff / drawBatch.image->m_size.GetY();
  894. uvs[2].SetY(1.0f - uvScale);
  895. uvs[3].SetY(1.0f - uvScale);
  896. }
  897. }
  898. //! Returns the maximum number of non-overflowing lines the given element can display.
  899. //!
  900. //! Note that this assumes the lines have been word-wrapped and don't overflow horizontally.
  901. int GetNumNonOverflowingLinesForElement(
  902. const UiTextComponent::DrawBatchLineContainer& batchLines,
  903. const AZ::Vector2& currentElementSize,
  904. float lineSpacing)
  905. {
  906. int maxLinesElementCanHold = 0;
  907. float nonOverflowingLineHeight = 0.0f;
  908. for (const auto& batchLine : batchLines)
  909. {
  910. float lineHeight = batchLine.lineSize.GetY();
  911. // Only consider line spacing when there are multiple lines (this
  912. // also handles the case when there is only one line).
  913. if (maxLinesElementCanHold >= 1)
  914. {
  915. lineHeight += lineSpacing;
  916. }
  917. // Add up the lines that fit vertically within the element
  918. if (nonOverflowingLineHeight + lineHeight < currentElementSize.GetY())
  919. {
  920. maxLinesElementCanHold++;
  921. nonOverflowingLineHeight += lineHeight;
  922. }
  923. else
  924. {
  925. break;
  926. }
  927. }
  928. // It's possible the element can't accommodate a single line of text (too small for text),
  929. // so in this case we just say the element can accommodate one line anyways to avoid
  930. // div by zero checks etc.
  931. maxLinesElementCanHold = AZStd::GetMax<int>(maxLinesElementCanHold, 1);
  932. return maxLinesElementCanHold;
  933. }
  934. //! Converts the vertex format used by FFont to the format being used by the dynamic draw context in LyShine.
  935. //!
  936. //! Note that the formats are currently identical, but this may change with the removal of more legacy code
  937. void FontVertexToUiVertex(const SVF_P2F_C4B_T2F_F4B* fontVertices, LyShine::UiPrimitiveVertex* uiVertices, int numVertices)
  938. {
  939. for (int i = 0; i < numVertices; ++i)
  940. {
  941. uiVertices[i].xy = fontVertices[i].xy;
  942. uiVertices[i].color.dcolor = fontVertices[i].color.dcolor;
  943. uiVertices[i].st = fontVertices[i].st;
  944. uiVertices[i].texIndex = fontVertices[i].texIndex;
  945. uiVertices[i].texHasColorChannel = fontVertices[i].texHasColorChannel;
  946. uiVertices[i].texIndex2 = fontVertices[i].texIndex2;
  947. uiVertices[i].pad = fontVertices[i].pad;
  948. }
  949. }
  950. } // anonymous namespace
  951. ////////////////////////////////////////////////////////////////////////////////////////////////////
  952. // PUBLIC MEMBER FUNCTIONS
  953. ////////////////////////////////////////////////////////////////////////////////////////////////////
  954. ////////////////////////////////////////////////////////////////////////////////////////////////////
  955. UiTextComponent::InlineImage::InlineImage(const AZStd::string& texturePathname,
  956. float height,
  957. float scale,
  958. VAlign vAlign,
  959. float yOffset,
  960. float leftPadding,
  961. float rightPadding)
  962. {
  963. m_filepath = texturePathname;
  964. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePath, m_filepath);
  965. m_texture.reset();
  966. m_size = AZ::Vector2(0.0f, 0.0f);
  967. m_vAlign = vAlign;
  968. m_yOffset = yOffset;
  969. m_leftPadding = leftPadding;
  970. m_rightPadding = rightPadding;
  971. m_atlas = nullptr;
  972. TextureAtlasNamespace::TextureAtlasRequestBus::BroadcastResult(m_atlas, &TextureAtlasNamespace::TextureAtlasRequests::FindAtlasContainingImage, m_filepath);
  973. if (m_atlas)
  974. {
  975. m_texture = m_atlas->GetTexture();
  976. m_coordinates = m_atlas->GetAtlasCoordinates(m_filepath);
  977. m_size = AZ::Vector2(static_cast<float>(m_coordinates.GetWidth()), static_cast<float>(m_coordinates.GetHeight()));
  978. }
  979. else
  980. {
  981. // Load the texture
  982. m_texture = Draw2dHelper::LoadTexture(m_filepath);
  983. if (m_texture)
  984. {
  985. AZ::RHI::Size size = m_texture->GetDescriptor().m_size;
  986. m_size = AZ::Vector2(static_cast<float>(size.m_width), static_cast<float>(size.m_height));
  987. }
  988. }
  989. // Adjust size to the specified height while keeping the aspect ratio
  990. float aspectRatio = m_size.GetY() != 0.0f ? m_size.GetX() / m_size.GetY() : 1.0f;
  991. m_size.SetY(height);
  992. m_size.SetX(m_size.GetY() * aspectRatio);
  993. // Apply specified scale
  994. m_size *= scale;
  995. }
  996. ////////////////////////////////////////////////////////////////////////////////////////////////////
  997. UiTextComponent::InlineImage::~InlineImage()
  998. {
  999. }
  1000. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1001. bool UiTextComponent::InlineImage::OnAtlasLoaded(const TextureAtlasNamespace::TextureAtlas* atlas)
  1002. {
  1003. if (!m_atlas)
  1004. {
  1005. m_coordinates = atlas->GetAtlasCoordinates(m_filepath);
  1006. if (m_coordinates.GetWidth() > 0)
  1007. {
  1008. m_atlas = atlas;
  1009. m_texture = m_atlas->GetTexture();
  1010. return true;
  1011. }
  1012. }
  1013. return false;
  1014. }
  1015. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1016. bool UiTextComponent::InlineImage::OnAtlasUnloaded(const TextureAtlasNamespace::TextureAtlas* atlas)
  1017. {
  1018. if (m_atlas == atlas)
  1019. {
  1020. TextureAtlasNamespace::TextureAtlasRequestBus::BroadcastResult(m_atlas, &TextureAtlasNamespace::TextureAtlasRequests::FindAtlasContainingImage, m_filepath);
  1021. if (m_atlas)
  1022. {
  1023. m_texture = m_atlas->GetTexture();
  1024. m_coordinates = m_atlas->GetAtlasCoordinates(m_filepath);
  1025. }
  1026. else
  1027. {
  1028. // Load the texture
  1029. m_texture = Draw2dHelper::LoadTexture(m_filepath);
  1030. }
  1031. return true;
  1032. }
  1033. return false;
  1034. }
  1035. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1036. UiTextComponent::DrawBatch::DrawBatch()
  1037. : color(TextMarkup::ColorInvalid)
  1038. , font(nullptr)
  1039. , image(nullptr)
  1040. , size(0.0f, 0.0f)
  1041. , yOffset(0.0f)
  1042. {
  1043. }
  1044. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1045. UiTextComponent::DrawBatch::Type UiTextComponent::DrawBatch::GetType() const
  1046. {
  1047. if (image)
  1048. {
  1049. return UiTextComponent::DrawBatch::Type::Image;
  1050. }
  1051. return UiTextComponent::DrawBatch::Type::Text;
  1052. }
  1053. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1054. void UiTextComponent::DrawBatch::CalculateSize(const STextDrawContext& ctx, bool excludeTrailingSpace)
  1055. {
  1056. if (GetType() == UiTextComponent::DrawBatch::Type::Text)
  1057. {
  1058. AZStd::string displayString(text);
  1059. // For now, we only use batch text size for rendering purposes,
  1060. // so we don't account for trailing spaces to avoid alignment
  1061. // and formatting issues. In the future, we may need to
  1062. // calculate batch size by use case (rendering, "true" size,
  1063. // etc.). rather than assume one-size-fits-all.
  1064. // Trim right
  1065. if (excludeTrailingSpace)
  1066. {
  1067. if (displayString.length() > 0)
  1068. {
  1069. AZStd::string::size_type endpos = displayString.find_last_not_of(" \t\n\v\f\r");
  1070. if ((endpos != AZStd::string::npos) && (endpos != displayString.length() - 1))
  1071. {
  1072. displayString.erase(endpos + 1);
  1073. }
  1074. }
  1075. }
  1076. Vec2 textSize = font->GetTextSize(displayString.c_str(), true, ctx);
  1077. size = AZ::Vector2(textSize.x, textSize.y);
  1078. }
  1079. else if (GetType() == UiTextComponent::DrawBatch::Type::Image)
  1080. {
  1081. size = image->m_size;
  1082. size.SetX(size.GetX() + image->m_leftPadding + image->m_rightPadding);
  1083. }
  1084. else
  1085. {
  1086. AZ_Assert(false, "Unknown DrawBatch Type");
  1087. size = AZ::Vector2(0.0f, 0.0f);
  1088. }
  1089. }
  1090. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1091. void UiTextComponent::DrawBatch::CalculateYOffset(float fontSize, float baseline)
  1092. {
  1093. if (GetType() == UiTextComponent::DrawBatch::Type::Text)
  1094. {
  1095. yOffset = 0.0f;
  1096. }
  1097. else if (GetType() == UiTextComponent::DrawBatch::Type::Image)
  1098. {
  1099. float imageHeight = size.GetY();
  1100. switch (image->m_vAlign)
  1101. {
  1102. case InlineImage::VAlign::Baseline:
  1103. {
  1104. yOffset = (baseline - imageHeight);
  1105. }
  1106. break;
  1107. case InlineImage::VAlign::Top:
  1108. {
  1109. yOffset = 0.0f;
  1110. }
  1111. break;
  1112. case InlineImage::VAlign::Center:
  1113. {
  1114. yOffset = (fontSize - imageHeight) / 2.0f;
  1115. }
  1116. break;
  1117. case InlineImage::VAlign::Bottom:
  1118. {
  1119. yOffset = fontSize - imageHeight;
  1120. }
  1121. break;
  1122. }
  1123. yOffset += image->m_yOffset;
  1124. }
  1125. else
  1126. {
  1127. AZ_Assert(false, "Unknown DrawBatch Type");
  1128. yOffset = 0.0f;
  1129. }
  1130. }
  1131. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1132. int UiTextComponent::DrawBatch::GetNumChars() const
  1133. {
  1134. if (GetType() == UiTextComponent::DrawBatch::Type::Text)
  1135. {
  1136. return LyShine::GetUtf8StringLength(text);
  1137. }
  1138. else if (GetType() == UiTextComponent::DrawBatch::Type::Image)
  1139. {
  1140. return 1;
  1141. }
  1142. else
  1143. {
  1144. AZ_Assert(false, "Unknown DrawBatch Type");
  1145. return 0;
  1146. }
  1147. }
  1148. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1149. bool UiTextComponent::DrawBatch::GetOverflowInfo(const STextDrawContext& ctx,
  1150. float availableWidth, bool skipFirstChar, OverflowInfo& overflowInfoOut)
  1151. {
  1152. overflowInfoOut.overflowIndex = -1;
  1153. overflowInfoOut.overflowCharIsSpace = false;
  1154. overflowInfoOut.widthUntilOverflowOrTotalWidth = -1.0f;
  1155. overflowInfoOut.overflowCharWidth = -1.0f;
  1156. overflowInfoOut.lastSpaceIndex = -1;
  1157. overflowInfoOut.isSpaceAtEnd = false;
  1158. if (GetType() == UiTextComponent::DrawBatch::Type::Text)
  1159. {
  1160. int batchCurChar = 0;
  1161. float width = 0.0f;
  1162. float maxEffectOffsetX = font->GetMaxEffectOffset(ctx.m_fxIdx).x;
  1163. Utf8::Unchecked::octet_iterator pChar(text.data());
  1164. uint32_t prevCh = 0;
  1165. while (uint32_t ch = *pChar)
  1166. {
  1167. size_t maxSize = 5;
  1168. char codepoint[5] = { 0 };
  1169. char* codepointPtr = codepoint;
  1170. Utf8::Unchecked::octet_iterator<AZStd::string::iterator>::to_utf8_sequence(ch, codepointPtr, maxSize);
  1171. float curCharWidth = font->GetTextSize(codepoint, true, ctx).x;
  1172. if (prevCh)
  1173. {
  1174. curCharWidth -= maxEffectOffsetX;
  1175. }
  1176. if (prevCh && ctx.m_kerningEnabled)
  1177. {
  1178. curCharWidth += font->GetKerning(prevCh, ch, ctx).x;
  1179. }
  1180. if (prevCh)
  1181. {
  1182. curCharWidth += ctx.m_tracking;
  1183. }
  1184. prevCh = ch;
  1185. const bool lineWidthExceeded = (width + curCharWidth) > availableWidth;
  1186. if (lineWidthExceeded)
  1187. {
  1188. if (!skipFirstChar || batchCurChar != 0)
  1189. {
  1190. overflowInfoOut.overflowIndex = batchCurChar;
  1191. overflowInfoOut.overflowCharIsSpace = (ch == ' ');
  1192. overflowInfoOut.widthUntilOverflowOrTotalWidth = width;
  1193. overflowInfoOut.overflowCharWidth = curCharWidth;
  1194. return true;
  1195. }
  1196. }
  1197. // keep track of spaces
  1198. // they are good for splitting the string
  1199. if (ch == ' ')
  1200. {
  1201. overflowInfoOut.lastSpaceIndex = batchCurChar;
  1202. }
  1203. width += curCharWidth;
  1204. batchCurChar += 1;
  1205. ++pChar;
  1206. if (ch == ' ' && !*pChar)
  1207. {
  1208. overflowInfoOut.isSpaceAtEnd = true;
  1209. }
  1210. }
  1211. overflowInfoOut.widthUntilOverflowOrTotalWidth = width;
  1212. return false;
  1213. }
  1214. else if (GetType() == UiTextComponent::DrawBatch::Type::Image)
  1215. {
  1216. float totalImageSize = image->m_size.GetX() + image->m_leftPadding + image->m_rightPadding;
  1217. if (!skipFirstChar && totalImageSize > availableWidth)
  1218. {
  1219. overflowInfoOut.overflowIndex = 0;
  1220. overflowInfoOut.overflowCharIsSpace = false;
  1221. overflowInfoOut.widthUntilOverflowOrTotalWidth = 0.0f;
  1222. overflowInfoOut.overflowCharWidth = totalImageSize;
  1223. return true;
  1224. }
  1225. else
  1226. {
  1227. overflowInfoOut.widthUntilOverflowOrTotalWidth = totalImageSize;
  1228. return false;
  1229. }
  1230. }
  1231. else
  1232. {
  1233. AZ_Assert(false, "Unknown DrawBatch Type");
  1234. return false;
  1235. }
  1236. }
  1237. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1238. void UiTextComponent::DrawBatch::Split(int atCharIndex, DrawBatch& newDrawBatchOut)
  1239. {
  1240. newDrawBatchOut = *this;
  1241. if (GetType() == UiTextComponent::DrawBatch::Type::Text)
  1242. {
  1243. AZ_Assert(atCharIndex >= 0 && atCharIndex < LyShine::GetUtf8StringLength(text), "Text index out of range. Can't split batch");
  1244. // Set text for new batch
  1245. int numBytesToSplit = LyShine::GetByteLengthOfUtf8Chars(text.c_str(), atCharIndex);
  1246. newDrawBatchOut.text = text.substr(numBytesToSplit);
  1247. // Update this batch's text
  1248. text = atCharIndex > 0 ? text.substr(0, numBytesToSplit) : "";
  1249. }
  1250. else if (GetType() == UiTextComponent::DrawBatch::Type::Image)
  1251. {
  1252. AZ_Assert(atCharIndex == 0, "Image index out of range. Can't split batch");
  1253. // Update this batch's image
  1254. image = nullptr;
  1255. }
  1256. else
  1257. {
  1258. AZ_Assert(false, "Unknown DrawBatch Type");
  1259. }
  1260. }
  1261. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1262. UiTextComponent::DrawBatchLine::DrawBatchLine()
  1263. : lineSize(0.0f, 0.0f)
  1264. {
  1265. }
  1266. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1267. bool UiTextComponent::DrawBatchLine::CheckAndSplitLine(const STextDrawContext& ctx,
  1268. float maxWidth,
  1269. DrawBatchLine& newDrawBatchLineOut)
  1270. {
  1271. bool lineSplit = false;
  1272. // Allow a space at the end of the line to overflow. This is to remain consistent with the non-image
  1273. // line split implementation. If the space at the end of the line was simply removed, the character
  1274. // indexes wouldn't match the localized text character indexes, and would cause issues with cursor positioning
  1275. const bool allowSpaceToOverflow = true;
  1276. // Keep track of available width left
  1277. float availableWidth = maxWidth;
  1278. // Keep track of the last good place to split the line, such as a space
  1279. UiTextComponent::DrawBatchContainer::iterator lastBatchWithSpaceIterator = drawBatchList.end();
  1280. int lastSpaceIndexInBatch = -1;
  1281. int isLastSpaceAtEndOfBatch = false;
  1282. int numCharsSinceLastSpace = -1;
  1283. // Iterate over the line's draw batches and split the line if they run over the allowed width
  1284. UiTextComponent::DrawBatchContainer::iterator drawBatchIterator = drawBatchList.begin();
  1285. while (drawBatchIterator != drawBatchList.end())
  1286. {
  1287. int numCharsInBatch = drawBatchIterator->GetNumChars();
  1288. // Can't split the first char of the first batch in the line even if it is wider than the available width
  1289. bool skipFirstChar = (drawBatchIterator == drawBatchList.begin());
  1290. // Check whether current batch is overflowing and get overflow info
  1291. UiTextComponent::DrawBatch::OverflowInfo overflowInfoOut;
  1292. bool overflowing = drawBatchIterator->GetOverflowInfo(ctx, availableWidth, skipFirstChar, overflowInfoOut);
  1293. // Check if this batch has a space and remember for later
  1294. if (overflowInfoOut.lastSpaceIndex >= 0)
  1295. {
  1296. // Remember the space unless it's the first character in the line (we don't want to end up with a line consisting of just one space)
  1297. if (overflowInfoOut.lastSpaceIndex > 0 || drawBatchIterator != drawBatchList.begin())
  1298. {
  1299. lastBatchWithSpaceIterator = drawBatchIterator;
  1300. lastSpaceIndexInBatch = overflowInfoOut.lastSpaceIndex;
  1301. isLastSpaceAtEndOfBatch = overflowInfoOut.isSpaceAtEnd;
  1302. numCharsSinceLastSpace = (overflowing ? overflowInfoOut.overflowIndex : numCharsInBatch - 1) - lastSpaceIndexInBatch;
  1303. }
  1304. }
  1305. else
  1306. {
  1307. if (lastBatchWithSpaceIterator != drawBatchList.end())
  1308. {
  1309. numCharsSinceLastSpace += (overflowing ? overflowInfoOut.overflowIndex : numCharsInBatch);
  1310. }
  1311. }
  1312. const int maxCharsSinceLastSpace = 16;
  1313. if (numCharsSinceLastSpace > maxCharsSinceLastSpace)
  1314. {
  1315. // Space is now too far away
  1316. lastBatchWithSpaceIterator = drawBatchList.end();
  1317. lastSpaceIndexInBatch = -1;
  1318. isLastSpaceAtEndOfBatch = false;
  1319. numCharsSinceLastSpace = -1;
  1320. }
  1321. if (overflowing)
  1322. {
  1323. // Find a batch to split
  1324. UiTextComponent::DrawBatchContainer::iterator splitBatchIterator = drawBatchList.end();
  1325. int splitBatchAtIndex = -1;
  1326. // First check whether the overflow character is a space that we should allow to overflow
  1327. if (allowSpaceToOverflow && overflowInfoOut.overflowCharIsSpace)
  1328. {
  1329. // Allow this space to overflow
  1330. // Check if the space is the last character in the batch
  1331. if (overflowInfoOut.overflowIndex == numCharsInBatch - 1)
  1332. {
  1333. // Just move on to the next batch
  1334. availableWidth -= overflowInfoOut.widthUntilOverflowOrTotalWidth + overflowInfoOut.overflowCharWidth;
  1335. }
  1336. else
  1337. {
  1338. // Split one character after the space
  1339. splitBatchIterator = drawBatchIterator;
  1340. splitBatchAtIndex = overflowInfoOut.overflowIndex + 1;
  1341. }
  1342. }
  1343. // Next check if there's a batch that contains a space for splitting
  1344. else if (lastBatchWithSpaceIterator != drawBatchList.end())
  1345. {
  1346. // Split the last batch that has a space
  1347. if (isLastSpaceAtEndOfBatch && lastBatchWithSpaceIterator != drawBatchIterator)
  1348. {
  1349. // The space is at the end of the batch but there is a batch after it so move the next batch to a new line
  1350. splitBatchIterator = lastBatchWithSpaceIterator;
  1351. ++splitBatchIterator;
  1352. splitBatchAtIndex = 0;
  1353. }
  1354. else
  1355. {
  1356. // Split the batch that has the space
  1357. // We know there's another character after the space because either overflow occurred in the last batch
  1358. // or the space wasn't the last character in a previous batch
  1359. splitBatchIterator = lastBatchWithSpaceIterator;
  1360. splitBatchAtIndex = lastSpaceIndexInBatch + 1;
  1361. }
  1362. }
  1363. else
  1364. {
  1365. // Must split the current batch
  1366. splitBatchIterator = drawBatchIterator;
  1367. splitBatchAtIndex = overflowInfoOut.overflowIndex;
  1368. }
  1369. if (splitBatchIterator != drawBatchList.end())
  1370. {
  1371. UiTextComponent::DrawBatch newDrawBatchOut;
  1372. // Create a new line
  1373. newDrawBatchLineOut.drawBatchList.clear();
  1374. if (splitBatchAtIndex > 0)
  1375. {
  1376. // Split the batch
  1377. splitBatchIterator->Split(splitBatchAtIndex, newDrawBatchOut);
  1378. // Add the new draw batch to the new batch line
  1379. newDrawBatchLineOut.drawBatchList.push_back(newDrawBatchOut);
  1380. // Keep the current batch in its own line
  1381. ++splitBatchIterator;
  1382. }
  1383. // Add the remaining draw batches to the new batch line
  1384. if (splitBatchIterator != drawBatchList.end())
  1385. {
  1386. newDrawBatchLineOut.drawBatchList.splice(newDrawBatchLineOut.drawBatchList.end(), drawBatchList, splitBatchIterator, drawBatchList.end());
  1387. }
  1388. lineSplit = true;
  1389. break;
  1390. }
  1391. }
  1392. else
  1393. {
  1394. availableWidth -= overflowInfoOut.widthUntilOverflowOrTotalWidth; // subtract total width
  1395. }
  1396. ++drawBatchIterator;
  1397. }
  1398. return lineSplit;
  1399. }
  1400. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1401. UiTextComponent::DrawBatchLines::~DrawBatchLines()
  1402. {
  1403. Clear();
  1404. }
  1405. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1406. void UiTextComponent::DrawBatchLines::Clear()
  1407. {
  1408. batchLines.clear();
  1409. fontFamilyRefs.clear();
  1410. for (auto image : inlineImages)
  1411. {
  1412. delete image;
  1413. }
  1414. inlineImages.clear();
  1415. height = 0.0f;
  1416. }
  1417. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1418. UiTextComponent::UiTextComponent()
  1419. : m_text("My string")
  1420. , m_color(1.0f, 1.0f, 1.0f, 1.0f)
  1421. , m_alpha(1.0f)
  1422. , m_fontSize(32)
  1423. , m_requestFontSize(static_cast<int>(m_fontSize))
  1424. , m_textHAlignment(IDraw2d::HAlign::Center)
  1425. , m_textVAlignment(IDraw2d::VAlign::Center)
  1426. , m_charSpacing(0.0f)
  1427. , m_lineSpacing(0.0f)
  1428. , m_currFontSize(m_fontSize)
  1429. , m_currCharSpacing(m_charSpacing)
  1430. , m_font(nullptr)
  1431. , m_fontFamily(nullptr)
  1432. , m_fontEffectIndex(0)
  1433. , m_displayedTextFunction(DefaultDisplayedTextFunction)
  1434. , m_overrideColor(m_color)
  1435. , m_overrideAlpha(m_alpha)
  1436. , m_overrideFontFamily(nullptr)
  1437. , m_overrideFontEffectIndex(m_fontEffectIndex)
  1438. , m_isColorOverridden(false)
  1439. , m_isAlphaOverridden(false)
  1440. , m_isFontFamilyOverridden(false)
  1441. , m_isFontEffectOverridden(false)
  1442. , m_textSelectionColor(0.0f, 0.0f, 0.0f, 1.0f)
  1443. , m_selectionStart(-1)
  1444. , m_selectionEnd(-1)
  1445. , m_cursorLineNumHint(-1)
  1446. , m_overflowMode(OverflowMode::OverflowText)
  1447. , m_wrapTextSetting(WrapTextSetting::NoWrap)
  1448. , m_clipOffset(0.0f)
  1449. , m_clipOffsetMultiplier(1.0f)
  1450. , m_isMarkupEnabled(false)
  1451. {
  1452. static const AZStd::string DefaultUi("default-ui");
  1453. m_fontFilename.SetAssetPath(DefaultUi.c_str());
  1454. if (gEnv && gEnv->pCryFont) // these will be null in RC.exe
  1455. {
  1456. m_fontFamily = gEnv->pCryFont->GetFontFamily(DefaultUi.c_str());
  1457. if (!m_fontFamily)
  1458. {
  1459. m_fontFamily = gEnv->pCryFont->LoadFontFamily(DefaultUi.c_str());
  1460. }
  1461. }
  1462. if (m_fontFamily)
  1463. {
  1464. m_font = m_fontFamily->normal;
  1465. }
  1466. }
  1467. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1468. UiTextComponent::~UiTextComponent()
  1469. {
  1470. FreeRenderCacheMemory();
  1471. }
  1472. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1473. void UiTextComponent::ResetOverrides()
  1474. {
  1475. bool fontChanged = false;
  1476. bool colorChanged = false;
  1477. bool alphaChanged = false;
  1478. if (m_overrideColor != m_color)
  1479. {
  1480. m_overrideColor = m_color;
  1481. colorChanged = true;
  1482. }
  1483. if (m_overrideAlpha != m_alpha)
  1484. {
  1485. m_overrideAlpha = m_alpha;
  1486. alphaChanged = true;
  1487. }
  1488. if (m_overrideFontFamily != m_fontFamily)
  1489. {
  1490. m_overrideFontFamily = m_fontFamily;
  1491. fontChanged = true;
  1492. }
  1493. if (m_overrideFontEffectIndex != m_fontEffectIndex)
  1494. {
  1495. m_overrideFontEffectIndex = m_fontEffectIndex;
  1496. fontChanged = true;
  1497. }
  1498. m_isColorOverridden = false;
  1499. m_isAlphaOverridden = false;
  1500. m_isFontFamilyOverridden = false;
  1501. m_isFontEffectOverridden = false;
  1502. if (fontChanged)
  1503. {
  1504. MarkDrawBatchLinesDirty(true);
  1505. }
  1506. else if (colorChanged)
  1507. {
  1508. MarkRenderCacheDirty();
  1509. }
  1510. else if (alphaChanged)
  1511. {
  1512. if (m_drawBatchLines.m_fontEffectHasTransparency)
  1513. {
  1514. MarkRenderCacheDirty();
  1515. }
  1516. else
  1517. {
  1518. // alpha changed but there is no transparency in font effect so we need RenderGraph to be rebuilt but not render cache
  1519. MarkRenderGraphDirty();
  1520. }
  1521. }
  1522. }
  1523. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1524. void UiTextComponent::SetOverrideColor(const AZ::Color& color)
  1525. {
  1526. m_overrideColor.Set(color.GetAsVector3());
  1527. m_isColorOverridden = true;
  1528. MarkRenderCacheDirty();
  1529. }
  1530. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1531. void UiTextComponent::SetOverrideAlpha(float alpha)
  1532. {
  1533. float oldOverrideAlpha = m_overrideAlpha;
  1534. m_overrideAlpha = alpha;
  1535. m_isAlphaOverridden = true;
  1536. if (m_overrideAlpha != oldOverrideAlpha)
  1537. {
  1538. if (m_drawBatchLines.m_fontEffectHasTransparency)
  1539. {
  1540. MarkRenderCacheDirty();
  1541. }
  1542. else
  1543. {
  1544. // alpha changed but there is no transparency in font effect so we need RenderGraph to be rebuilt but not render cache
  1545. MarkRenderGraphDirty();
  1546. }
  1547. }
  1548. }
  1549. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1550. void UiTextComponent::SetOverrideFont(FontFamilyPtr fontFamily)
  1551. {
  1552. m_overrideFontFamily = fontFamily;
  1553. m_isFontFamilyOverridden = true;
  1554. MarkDrawBatchLinesDirty(true);
  1555. }
  1556. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1557. void UiTextComponent::SetOverrideFontEffect(unsigned int fontEffectIndex)
  1558. {
  1559. m_overrideFontEffectIndex = fontEffectIndex;
  1560. m_isFontEffectOverridden = true;
  1561. MarkDrawBatchLinesDirty(true);
  1562. }
  1563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1564. void UiTextComponent::Render(LyShine::IRenderGraph* renderGraph)
  1565. {
  1566. // get fade value (tracked by UiRenderer) and compute alpha for text
  1567. float fade = renderGraph->GetAlphaFade();
  1568. float finalAlpha = fade * m_overrideAlpha;
  1569. uint8 finalAlphaByte = static_cast<uint8>(finalAlpha * 255.0f);
  1570. // if we have any cached text batches that have transparency in their font effects then we need to
  1571. // regenerate the render cache if alpha has changed. This is fairly unusual so it still
  1572. // makes sense to not mark the render cache dirty on most fades or alpha changes.
  1573. if (m_drawBatchLines.m_fontEffectHasTransparency)
  1574. {
  1575. if (!m_renderCache.m_batches.empty() && m_renderCache.m_batches[0]->m_color.a != finalAlphaByte)
  1576. {
  1577. MarkRenderCacheDirty();
  1578. }
  1579. }
  1580. // If the cache is out of date then regenerate it
  1581. if (m_renderCache.m_isDirty)
  1582. {
  1583. RenderToCache(finalAlpha);
  1584. m_renderCache.m_isDirty = false;
  1585. }
  1586. else
  1587. {
  1588. // Check font texture version for each cached batch and update batch if out of date.
  1589. // This will happen if the quads for a text string are generated and a required glyph is not in the texture.
  1590. // The font texture is then updated. This means that any existing cached quads could be invalid since one
  1591. // or more glyphs they are using could have been removed from the font texture.
  1592. // The CanvasManager listens for the OnFontTextureUpdated event and will cause all
  1593. // render graphs to be rebuilt when any font texture has changed.
  1594. UpdateTextRenderBatchesForFontTextureChange();
  1595. }
  1596. if (finalAlphaByte == 0)
  1597. {
  1598. // do not render anything if alpha is zero (alpha cannot be overridden by markup)
  1599. // NOTE: this test needs to be done after regenerating the cache. Otherwise m_renderCache.m_isDirty
  1600. // can stay true, which means that the rendergraph doesn't get marked dirty on changes to this
  1601. // component.
  1602. return;
  1603. }
  1604. // these settings are the same for background rect, inline images and text
  1605. bool isTextureSRGB = false;
  1606. bool isTexturePremultipliedAlpha = false;
  1607. LyShine::BlendMode blendMode = LyShine::BlendMode::Normal;
  1608. // if there is a background rect (not typical - used for text selection) then draw it
  1609. // this is not optimized by caching since it is typically only visible on one text component at a time
  1610. if (m_selectionStart != -1)
  1611. {
  1612. UiTransformInterface::RectPointsArray rectPoints;
  1613. GetTextBoundingBoxPrivate(GetDrawBatchLines(), m_selectionStart, m_selectionEnd, rectPoints);
  1614. auto systemImage = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::White);
  1615. bool isClampTextureMode = true;
  1616. uint32 packedColor = (m_textSelectionColor.GetA8() << 24) | (m_textSelectionColor.GetR8() << 16) | (m_textSelectionColor.GetG8() << 8) | m_textSelectionColor.GetB8();
  1617. for (UiTransformInterface::RectPoints& rect : rectPoints)
  1618. {
  1619. LyShine::UiPrimitive* primitive = renderGraph->GetDynamicQuadPrimitive(rect.pt, packedColor);
  1620. primitive->m_next = nullptr;
  1621. renderGraph->AddPrimitive(primitive, systemImage, isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode);
  1622. }
  1623. }
  1624. // Render the image batches
  1625. if (!m_renderCache.m_imageBatches.empty())
  1626. {
  1627. for (auto batch : m_renderCache.m_imageBatches)
  1628. {
  1629. AZ::Data::Instance<AZ::RPI::Image> texture = batch->m_texture;
  1630. // If the fade value has changed we need to update the alpha values in the vertex colors but we do
  1631. // not want to touch or recompute the RGB values
  1632. if (batch->m_cachedPrimitive.m_vertices[0].color.a != finalAlphaByte)
  1633. {
  1634. for (int i = 0; i < 4; ++i)
  1635. {
  1636. batch->m_cachedPrimitive.m_vertices[i].color.a = finalAlphaByte;
  1637. }
  1638. }
  1639. bool isClampTextureMode = true;
  1640. renderGraph->AddPrimitive(&batch->m_cachedPrimitive, texture,
  1641. isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode);
  1642. }
  1643. }
  1644. // Render the text batches
  1645. STextDrawContext fontContext(m_renderCache.m_fontContext);
  1646. for (RenderCacheBatch* batch : m_renderCache.m_batches)
  1647. {
  1648. AZ::FFont* font = static_cast<AZ::FFont*>(batch->m_font); // LYSHINE_ATOM_TODO - move IFont.h out of CryCommon/engine code
  1649. AZ::Data::Instance<AZ::RPI::Image> fontImage = font->GetFontImage();
  1650. if (fontImage)
  1651. {
  1652. // update alpha values in the verts if alpha has changed (due to fader or SetAlpha).
  1653. // We never do this if any font effect used has transparency since in that case
  1654. // not all of the verts will have the same alpha. We handle that case above
  1655. // by regenerating the render cache in that case.
  1656. if (!m_drawBatchLines.m_fontEffectHasTransparency && batch->m_color.a != finalAlphaByte)
  1657. {
  1658. for (int i=0; i < batch->m_cachedPrimitive.m_numVertices; ++i)
  1659. {
  1660. batch->m_cachedPrimitive.m_vertices[i].color.a = finalAlphaByte;
  1661. }
  1662. batch->m_color.a = finalAlphaByte;
  1663. }
  1664. // We always use wrap mode for text (isClamp false). This is historically what was done
  1665. // in CryFont and without it characters that are on the left of the font texture look bad
  1666. // because there is no padding on the left of the glyphs.
  1667. bool isClampTextureMode = false;
  1668. renderGraph->AddPrimitive(&batch->m_cachedPrimitive, fontImage,
  1669. isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode);
  1670. }
  1671. }
  1672. }
  1673. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1674. AZStd::string UiTextComponent::GetText()
  1675. {
  1676. return m_text;
  1677. }
  1678. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1679. void UiTextComponent::SetText(const AZStd::string& text)
  1680. {
  1681. if (m_text != text)
  1682. {
  1683. m_text = text;
  1684. // This method is used by text input so it has historically always avoided localization
  1685. m_locText = m_text;
  1686. // the text changed so if markup is enabled the XML parsing should report warnings on next parse
  1687. if (m_isMarkupEnabled)
  1688. {
  1689. m_textNeedsXmlValidation = true;
  1690. }
  1691. MarkDrawBatchLinesDirty(true);
  1692. }
  1693. }
  1694. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1695. AZStd::string UiTextComponent::GetTextWithFlags(GetTextFlags flags)
  1696. {
  1697. if (flags == UiTextInterface::GetLocalized)
  1698. {
  1699. return m_locText;
  1700. }
  1701. else
  1702. {
  1703. return m_text;
  1704. }
  1705. }
  1706. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1707. void UiTextComponent::SetTextWithFlags(const AZStd::string& text, SetTextFlags flags)
  1708. {
  1709. bool changed = false;
  1710. if (m_text != text)
  1711. {
  1712. m_text = text;
  1713. changed = true;
  1714. }
  1715. AZStd::string locText;
  1716. if ((flags & UiTextInterface::SetLocalized) == UiTextInterface::SetLocalized)
  1717. {
  1718. locText = GetLocalizedText(m_text);
  1719. }
  1720. else
  1721. {
  1722. locText = m_text;
  1723. }
  1724. // a previous call could have had a different value for UiTextInterface::SetLocalized flag but same text
  1725. if (changed || m_locText != locText)
  1726. {
  1727. m_locText = locText;
  1728. changed = true;
  1729. }
  1730. // supported for backward compatibility, now we have the isMarkupEnabled flag the caller could just set that to false
  1731. if ((flags& UiTextInterface::SetEscapeMarkup) == UiTextInterface::SetEscapeMarkup)
  1732. {
  1733. if (m_isMarkupEnabled)
  1734. {
  1735. m_isMarkupEnabled = false;
  1736. changed = true;
  1737. }
  1738. }
  1739. if (changed)
  1740. {
  1741. // The text changed so draw batches will need recalculation
  1742. MarkDrawBatchLinesDirty(true);
  1743. // the text changed so if markup is enabled the XML parsing should report warnings on next parse
  1744. if (m_isMarkupEnabled)
  1745. {
  1746. m_textNeedsXmlValidation = true;
  1747. }
  1748. }
  1749. }
  1750. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1751. AZ::Color UiTextComponent::GetColor()
  1752. {
  1753. return AZ::Color::CreateFromVector3AndFloat(m_color.GetAsVector3(), m_alpha);
  1754. }
  1755. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1756. void UiTextComponent::SetColor(const AZ::Color& color)
  1757. {
  1758. m_color.Set(color.GetAsVector3());
  1759. m_alpha = color.GetA();
  1760. AZ::Color oldOverrideColor = m_overrideColor;
  1761. float oldOverrideAlpha = m_overrideAlpha;
  1762. if (!m_isColorOverridden)
  1763. {
  1764. m_overrideColor = m_color;
  1765. }
  1766. if (!m_isAlphaOverridden)
  1767. {
  1768. m_overrideAlpha = m_alpha;
  1769. }
  1770. // Usually, only a color change requires regenerating render cache.
  1771. // The exception is if we have font effects with separate alpha in which case the
  1772. // m_fontEffectHasTransparency flag is set.
  1773. if (m_overrideColor != oldOverrideColor)
  1774. {
  1775. MarkRenderCacheDirty();
  1776. }
  1777. else if (m_overrideAlpha != oldOverrideAlpha)
  1778. {
  1779. if (m_drawBatchLines.m_fontEffectHasTransparency)
  1780. {
  1781. MarkRenderCacheDirty();
  1782. }
  1783. else
  1784. {
  1785. // alpha changed so we need RenderGraph to be rebuilt but not render cache
  1786. MarkRenderGraphDirty();
  1787. }
  1788. }
  1789. }
  1790. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1791. LyShine::PathnameType UiTextComponent::GetFont()
  1792. {
  1793. return m_fontFilename.GetAssetPath().c_str();
  1794. }
  1795. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1796. void UiTextComponent::SetFont(const LyShine::PathnameType& fontPath)
  1797. {
  1798. // the input string could be in any form but must be a game path - not a full path.
  1799. // Make it normalized
  1800. AZStd::string newPath = fontPath;
  1801. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::Bus::Events::NormalizePath, newPath);
  1802. if (m_fontFilename.GetAssetPath() != newPath)
  1803. {
  1804. ChangeFont(newPath);
  1805. }
  1806. }
  1807. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1808. int UiTextComponent::GetFontEffect()
  1809. {
  1810. return m_fontEffectIndex;
  1811. }
  1812. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1813. void UiTextComponent::SetFontEffect(int effectIndex)
  1814. {
  1815. if (m_fontEffectIndex != static_cast<unsigned int>(effectIndex))
  1816. {
  1817. m_fontEffectIndex = effectIndex;
  1818. m_overrideFontEffectIndex = effectIndex;
  1819. MarkDrawBatchLinesDirty(true);
  1820. }
  1821. }
  1822. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1823. AZStd::string UiTextComponent::GetFontEffectName(int effectIndex)
  1824. {
  1825. const char* effectName = m_font->GetEffectName(effectIndex);
  1826. return AZStd::string(effectName);
  1827. }
  1828. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1829. void UiTextComponent::SetFontEffectByName(const AZStd::string& effectName)
  1830. {
  1831. unsigned int effectId = m_font->GetEffectId(effectName.c_str());
  1832. SetFontEffect(static_cast<int>(effectId));
  1833. }
  1834. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1835. float UiTextComponent::GetFontSize()
  1836. {
  1837. return m_fontSize;
  1838. }
  1839. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1840. void UiTextComponent::SetFontSize(float fontSize)
  1841. {
  1842. if (m_fontSize != fontSize)
  1843. {
  1844. m_fontSize = fontSize;
  1845. m_isRequestFontSizeDirty = true;
  1846. m_currFontSize = m_fontSize;
  1847. MarkDrawBatchLinesDirty(true);
  1848. }
  1849. }
  1850. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1851. void UiTextComponent::GetTextAlignment(IDraw2d::HAlign& horizontalAlignment,
  1852. IDraw2d::VAlign& verticalAlignment)
  1853. {
  1854. horizontalAlignment = m_textHAlignment;
  1855. verticalAlignment = m_textVAlignment;
  1856. }
  1857. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1858. void UiTextComponent::SetTextAlignment(IDraw2d::HAlign horizontalAlignment,
  1859. IDraw2d::VAlign verticalAlignment)
  1860. {
  1861. m_textHAlignment = horizontalAlignment;
  1862. m_textVAlignment = verticalAlignment;
  1863. MarkRenderCacheDirty();
  1864. }
  1865. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1866. IDraw2d::HAlign UiTextComponent::GetHorizontalTextAlignment()
  1867. {
  1868. return m_textHAlignment;
  1869. }
  1870. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1871. void UiTextComponent::SetHorizontalTextAlignment(IDraw2d::HAlign alignment)
  1872. {
  1873. m_textHAlignment = alignment;
  1874. MarkRenderCacheDirty();
  1875. }
  1876. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1877. IDraw2d::VAlign UiTextComponent::GetVerticalTextAlignment()
  1878. {
  1879. return m_textVAlignment;
  1880. }
  1881. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1882. void UiTextComponent::SetVerticalTextAlignment(IDraw2d::VAlign alignment)
  1883. {
  1884. m_textVAlignment = alignment;
  1885. MarkRenderCacheDirty();
  1886. }
  1887. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1888. float UiTextComponent::GetCharacterSpacing()
  1889. {
  1890. return m_charSpacing;
  1891. }
  1892. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1893. void UiTextComponent::SetCharacterSpacing(float characterSpacing)
  1894. {
  1895. m_charSpacing = characterSpacing;
  1896. m_currCharSpacing = characterSpacing;
  1897. // Recompute the text since we might have more lines to draw now (for word wrap)
  1898. OnTextWidthPropertyChanged();
  1899. InvalidateLayout();
  1900. MarkRenderCacheDirty();
  1901. }
  1902. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1903. float UiTextComponent::GetLineSpacing()
  1904. {
  1905. return m_lineSpacing;
  1906. }
  1907. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1908. void UiTextComponent::SetLineSpacing(float lineSpacing)
  1909. {
  1910. m_lineSpacing = lineSpacing;
  1911. InvalidateLayout();
  1912. MarkRenderCacheDirty();
  1913. }
  1914. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1915. int UiTextComponent::GetCharIndexFromPoint(AZ::Vector2 point, bool mustBeInBoundingBox)
  1916. {
  1917. // get the input point into untransformed canvas space
  1918. AZ::Vector3 point3(point.GetX(), point.GetY(), 0.0f);
  1919. AZ::Matrix4x4 transform;
  1920. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetTransformFromViewport, transform);
  1921. point3 = transform * point3;
  1922. AZ::Vector2 pointInCanvasSpace(point3.GetX(), point3.GetY());
  1923. return GetCharIndexFromCanvasSpacePoint(pointInCanvasSpace, mustBeInBoundingBox);
  1924. }
  1925. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1926. int UiTextComponent::GetCharIndexFromCanvasSpacePoint(AZ::Vector2 point, bool mustBeInBoundingBox)
  1927. {
  1928. // get the bounding rectangle of the text itself in untransformed canvas space
  1929. UiTransformInterface::RectPoints rect;
  1930. GetTextRect(rect);
  1931. // Since the text rect differs from the clipping rect, we have to adjust
  1932. // the user's input by the clipping offset to match the selection with
  1933. // the contents on-screen.
  1934. point.SetX(point.GetX() + CalculateHorizontalClipOffset());
  1935. // first test if the point is in the bounding box
  1936. // point is in rect if it is within rect or exactly on edge
  1937. bool isInRect = false;
  1938. if (point.GetX() >= rect.TopLeft().GetX() &&
  1939. point.GetX() <= rect.BottomRight().GetX() &&
  1940. point.GetY() >= rect.TopLeft().GetY() &&
  1941. point.GetY() <= rect.BottomRight().GetY())
  1942. {
  1943. isInRect = true;
  1944. }
  1945. if (mustBeInBoundingBox && !isInRect)
  1946. {
  1947. return -1;
  1948. }
  1949. // Get point relative to this element's TopLeft() rect. We use this offset
  1950. // to see how far along we've iterated over the rendered string size and
  1951. // whether or not the index has been found.
  1952. AZ::Vector2 pickOffset = AZ::Vector2(point.GetX() - rect.TopLeft().GetX(),
  1953. point.GetY() - rect.TopLeft().GetY());
  1954. int requestFontSize = GetRequestFontSize();
  1955. const DrawBatchLines& drawBatchLines = GetDrawBatchLines();
  1956. STextDrawContext fontContext(GetTextDrawContextPrototype(requestFontSize, drawBatchLines.fontSizeScale));
  1957. int indexIter = 0;
  1958. float lastSubstrX = 0;
  1959. float accumulatedHeight = m_fontSize;
  1960. const bool multiLineText = drawBatchLines.batchLines.size() > 1;
  1961. uint32_t lineCounter = 0;
  1962. // Iterate over each rendered line of text
  1963. for (const DrawBatchLine& batchLine : drawBatchLines.batchLines)
  1964. {
  1965. ++lineCounter;
  1966. // Iterate to the line containing the point
  1967. if (multiLineText && pickOffset.GetY() >= accumulatedHeight)
  1968. {
  1969. // Increment indexIter by number of characters on this line
  1970. for (const DrawBatch& drawBatch : batchLine.drawBatchList)
  1971. {
  1972. indexIter += LyShine::GetUtf8StringLength(drawBatch.text);
  1973. }
  1974. accumulatedHeight += m_fontSize;
  1975. continue;
  1976. }
  1977. // In some cases, we may want the cursor to be displayed on the end
  1978. // of a preceding line, and in others, we may want the cursor to be
  1979. // displaying at the beginning of the following line. We resolve this
  1980. // ambiguity by assigning a "hint" to the offsets calculator on where
  1981. // to place the cursor.
  1982. m_cursorLineNumHint = lineCounter;
  1983. // This index allows us to index relative to the current line of text
  1984. // we're iterating on.
  1985. int curLineIndexIter = 0;
  1986. // Iterate across the line
  1987. for (const DrawBatch& drawBatch : batchLine.drawBatchList)
  1988. {
  1989. Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
  1990. while (uint32_t ch = *pChar)
  1991. {
  1992. ++pChar;
  1993. curLineIndexIter += LyShine::GetMultiByteCharSize(ch);
  1994. // Iterate across each character of text until the width
  1995. // exceeds the X pick offset.
  1996. AZStd::string subString(drawBatch.text.substr(0, curLineIndexIter));
  1997. Vec2 sizeSoFar = m_font->GetTextSize(subString.c_str(), true, fontContext);
  1998. float charWidth = sizeSoFar.x - lastSubstrX;
  1999. // pickOffset is a screen-position and the text position changes
  2000. // based on its alignment. We add an offset here to account for
  2001. // the location of the text on-screen for different alignments.
  2002. float alignedOffset = 0.0f;
  2003. if (m_textHAlignment == IDraw2d::HAlign::Center)
  2004. {
  2005. alignedOffset = 0.5f * (rect.GetAxisAlignedSize().GetX() - batchLine.lineSize.GetX());
  2006. }
  2007. else if (m_textHAlignment == IDraw2d::HAlign::Right)
  2008. {
  2009. alignedOffset = rect.GetAxisAlignedSize().GetX() - batchLine.lineSize.GetX();
  2010. }
  2011. if (pickOffset.GetX() <= alignedOffset + lastSubstrX + (charWidth * 0.5f))
  2012. {
  2013. return indexIter;
  2014. }
  2015. lastSubstrX = sizeSoFar.x;
  2016. ++indexIter;
  2017. }
  2018. }
  2019. return indexIter;
  2020. }
  2021. // We can reach here if the point is just on the boundary of the rect.
  2022. // In this case, there are no more lines of text to iterate on, so just
  2023. // assume the user is trying to get to the end of the string.
  2024. return indexIter;
  2025. }
  2026. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2027. AZ::Vector2 UiTextComponent::GetPointFromCharIndex(int index)
  2028. {
  2029. // Left and right offsets for determining the position of the beginning
  2030. // and end of the selection.
  2031. LineOffsets top, middle, bottom;
  2032. GetOffsetsFromSelectionInternal(top, middle, bottom, index, index);
  2033. UiTransformInterface::RectPoints rect;
  2034. GetTextRect(rect);
  2035. // LineOffsets values don't take on-screen position with alignment
  2036. // into account, so we adjust the offset here.
  2037. float alignedOffset = 0.0f;
  2038. if (m_textHAlignment == IDraw2d::HAlign::Center)
  2039. {
  2040. alignedOffset = 0.5f * (rect.GetAxisAlignedSize().GetX() - top.batchLineLength);
  2041. }
  2042. else if (m_textHAlignment == IDraw2d::HAlign::Right)
  2043. {
  2044. alignedOffset = rect.GetAxisAlignedSize().GetX() - top.batchLineLength;
  2045. }
  2046. // Calculate left and right rect positions for start and end selection
  2047. rect.TopLeft().SetX(alignedOffset + rect.TopLeft().GetX() + top.left.GetX());
  2048. // Finally, add the y-offset to position the cursor on the correct line
  2049. // of text.
  2050. rect.TopLeft().SetY(rect.TopLeft().GetY() + top.left.GetY());
  2051. return rect.TopLeft();
  2052. }
  2053. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2054. AZ::Color UiTextComponent::GetSelectionColor()
  2055. {
  2056. return m_textSelectionColor;
  2057. }
  2058. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2059. void UiTextComponent::GetSelectionRange(int& startIndex, int& endIndex)
  2060. {
  2061. startIndex = m_selectionStart;
  2062. endIndex = m_selectionEnd;
  2063. }
  2064. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2065. void UiTextComponent::SetSelectionRange(int startIndex, int endIndex, const AZ::Color& textSelectionColor)
  2066. {
  2067. m_selectionStart = startIndex;
  2068. m_selectionEnd = endIndex;
  2069. m_textSelectionColor = textSelectionColor;
  2070. // The render cache stores positions based on these values so mark it dirty
  2071. MarkRenderCacheDirty();
  2072. }
  2073. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2074. void UiTextComponent::ClearSelectionRange()
  2075. {
  2076. m_selectionStart = m_selectionEnd = -1;
  2077. // The render cache stores positions based on these values so mark it dirty
  2078. MarkRenderCacheDirty();
  2079. }
  2080. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2081. AZ::Vector2 UiTextComponent::GetTextSize()
  2082. {
  2083. // First ensure that the text wrapping is in sync with the element's width.
  2084. // If the element's transform flag is dirty, then the text wrapping does not reflect the current
  2085. // width of the element. Sync it up by checking and handling a change in canvas space size.
  2086. // The notification handler will prepare the text again
  2087. bool canvasSpaceSizeChanged = false;
  2088. UiTransformBus::EventResult(canvasSpaceSizeChanged, GetEntityId(), &UiTransformBus::Events::HasCanvasSpaceSizeChanged);
  2089. if (canvasSpaceSizeChanged)
  2090. {
  2091. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::NotifyAndResetCanvasSpaceRectChange);
  2092. }
  2093. return GetTextSizeFromDrawBatchLines(GetDrawBatchLines());
  2094. }
  2095. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2096. float UiTextComponent::GetTextWidth()
  2097. {
  2098. return GetTextSize().GetX();
  2099. }
  2100. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2101. float UiTextComponent::GetTextHeight()
  2102. {
  2103. return GetTextSize().GetY();
  2104. }
  2105. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2106. void UiTextComponent::GetTextBoundingBox(int startIndex, int endIndex, UiTransformInterface::RectPointsArray& rectPoints)
  2107. {
  2108. // compute the bounding box of the specified area of text
  2109. GetTextBoundingBoxPrivate(GetDrawBatchLines(), startIndex, endIndex, rectPoints);
  2110. }
  2111. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2112. void UiTextComponent::GetTextBoundingBoxPrivate(const DrawBatchLines& drawBatchLines, int startIndex, int endIndex, UiTransformInterface::RectPointsArray& rectPoints)
  2113. {
  2114. // Multi-line selection can be broken up into three pairs of offsets
  2115. // representing the first (top) and last (bottom) lines, and everything
  2116. // in-between (middle).
  2117. LineOffsets top, middle, bottom;
  2118. GetOffsetsFromSelectionInternal(top, middle, bottom, startIndex, endIndex);
  2119. AZStd::stack<LineOffsets*> lineOffsetsStack;
  2120. lineOffsetsStack.push(&bottom);
  2121. lineOffsetsStack.push(&middle);
  2122. lineOffsetsStack.push(&top);
  2123. // Build rectPoints array depending on how many lines of text are selected
  2124. rectPoints.push_back(UiTransformInterface::RectPoints());
  2125. AZ::Vector2 zeroVector = AZ::Vector2::CreateZero();
  2126. if (middle.left != zeroVector || middle.right != zeroVector)
  2127. {
  2128. rectPoints.push_back(UiTransformInterface::RectPoints());
  2129. }
  2130. if (bottom.left != zeroVector || bottom.right != zeroVector)
  2131. {
  2132. rectPoints.push_back(UiTransformInterface::RectPoints());
  2133. }
  2134. // Build RectPoints geometry based on selected lines of text
  2135. for (UiTransformInterface::RectPoints& rect : rectPoints)
  2136. {
  2137. LineOffsets* lineOffsets = lineOffsetsStack.top();
  2138. lineOffsetsStack.pop();
  2139. AZ::Vector2& leftOffset = lineOffsets->left;
  2140. AZ::Vector2& rightOffset = lineOffsets->right;
  2141. // GetTextSize() returns the max width and height that this text component
  2142. // occupies on-screen.
  2143. AZ::Vector2 textSize(GetTextSizeFromDrawBatchLines(drawBatchLines));
  2144. // For a multi-line selection, the width of our selection will span the
  2145. // entire text element width. Otherwise, we need to adjust the text
  2146. // size to only account for the current line width.
  2147. const bool multiLineSection = leftOffset.GetY() < rightOffset.GetY();
  2148. if (!multiLineSection)
  2149. {
  2150. textSize.SetX(lineOffsets->batchLineLength);
  2151. }
  2152. GetTextRect(rect, textSize);
  2153. rect.TopLeft().SetX(rect.TopLeft().GetX() + leftOffset.GetX());
  2154. rect.BottomLeft().SetX(rect.BottomLeft().GetX() + leftOffset.GetX());
  2155. rect.TopRight().SetX(rect.TopLeft().GetX() + rightOffset.GetX());
  2156. rect.BottomRight().SetX(rect.BottomLeft().GetX() + rightOffset.GetX());
  2157. // Finally, add the y-offset to position the cursor on the correct line
  2158. // of text.
  2159. rect.TopLeft().SetY(rect.TopLeft().GetY() + leftOffset.GetY());
  2160. rect.TopRight().SetY(rect.TopRight().GetY() + leftOffset.GetY());
  2161. rightOffset.SetY(rightOffset.GetY() > 0.0f ? rightOffset.GetY() : m_fontSize);
  2162. rect.BottomLeft().SetY(rect.TopLeft().GetY() + rightOffset.GetY());
  2163. rect.BottomRight().SetY(rect.TopRight().GetY() + rightOffset.GetY());
  2164. // Adjust cursor position to account for clipped text
  2165. if (ShouldClip())
  2166. {
  2167. UiTransformInterface::RectPoints elemRect;
  2168. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, elemRect);
  2169. AZ::Vector2 elemSize = elemRect.GetAxisAlignedSize();
  2170. const float displayedTextWidth = GetTextSize().GetX();
  2171. // When we render clipped text, we offset its draw position in order to
  2172. // clip the text properly and keep the visible text within the bounds of
  2173. // the element. Here, we account for that offset in order to render the
  2174. // cursor position at the correct location.
  2175. const bool textOverflowing = displayedTextWidth > elemSize.GetX();
  2176. if (textOverflowing)
  2177. {
  2178. const float rectOffset = CalculateHorizontalClipOffset();
  2179. rect.TopLeft().SetX(rect.TopLeft().GetX() - rectOffset);
  2180. rect.BottomLeft().SetX(rect.BottomLeft().GetX() - rectOffset);
  2181. rect.TopRight().SetX(rect.TopRight().GetX() - rectOffset);
  2182. rect.BottomRight().SetX(rect.BottomRight().GetX() - rectOffset);
  2183. // For clipped selections we can end up with a rect that is too big
  2184. // for the clipped boundaries. Here, we restrict the selection rect
  2185. // size to match the boundaries of the element's size.
  2186. rect.TopLeft().SetX(AZStd::GetMax<float>(elemRect.TopLeft().GetX(), rect.TopLeft().GetX()));
  2187. rect.BottomLeft().SetX(AZStd::GetMax<float>(elemRect.BottomLeft().GetX(), rect.BottomLeft().GetX()));
  2188. rect.TopRight().SetX(AZStd::GetMin<float>(elemRect.TopRight().GetX(), rect.TopRight().GetX()));
  2189. rect.BottomRight().SetX(AZStd::GetMin<float>(elemRect.BottomRight().GetX(), rect.BottomRight().GetX()));
  2190. }
  2191. }
  2192. // now we have the rect in untransformed canvas space, so transform it to viewport space
  2193. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::RotateAndScalePoints, rect);
  2194. // if the start and end indices are the same we want to draw a cursor
  2195. if (startIndex == endIndex)
  2196. {
  2197. // we want to make the rect one pixel wide in transformed space.
  2198. // Get the transform to viewport for the text entity
  2199. AZ::Matrix4x4 transformToViewport;
  2200. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetTransformToViewport, transformToViewport);
  2201. // take a sample vector along X-axis and transform it then normalize it
  2202. AZ::Vector3 offset(100.0f, 0.0f, 0.0f);
  2203. AZ::Vector3 transformedOffset3 = transformToViewport.Multiply3x3(offset);
  2204. transformedOffset3.NormalizeSafe();
  2205. AZ::Vector2 transformedOffset(transformedOffset3.GetX(), transformedOffset3.GetY());
  2206. // to help with scaled and rotated text round the offset to nearest pixels
  2207. transformedOffset = Draw2dHelper::RoundXY(transformedOffset, IDraw2d::Rounding::Nearest);
  2208. // before making it exactly one pixel wide, round the left edge to either the nearest pixel or round down
  2209. // (nearest looks best for fonts smaller than 32 and down looks best for fonts larger than 32).
  2210. // Really a better solution would be to draw a textured quad. In the 32 pt proportional font there is
  2211. // usually exactly 2 pixels between characters so by picking one pixel to draw the line on we either make
  2212. // it closer to one character or the other. If we had a text cursor texture we could draw a 4 pixel wide
  2213. // quad and it would look better. A cursor would also look smoother when rotated than a one pixel line.
  2214. // NOTE: The positions of text characters themselves will always be rounded DOWN to a pixel in the
  2215. // font rendering
  2216. IDraw2d::Rounding round = (m_fontSize < 32) ? IDraw2d::Rounding::Nearest : IDraw2d::Rounding::Down;
  2217. rect.TopLeft() = Draw2dHelper::RoundXY(rect.TopLeft(), round);
  2218. rect.BottomLeft() = Draw2dHelper::RoundXY(rect.BottomLeft(), round);
  2219. // now add the unit vector to the two left hand corners of the transformed rect
  2220. // to get the two right hand corners.
  2221. // it will now be one pixel wide in transformed space
  2222. rect.TopRight() = rect.TopLeft() + AZ::Vector2(transformedOffset);
  2223. rect.BottomRight() = rect.BottomLeft() + AZ::Vector2(transformedOffset);
  2224. }
  2225. }
  2226. }
  2227. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2228. void UiTextComponent::SetDisplayedTextFunction(const DisplayedTextFunction& displayedTextFunction)
  2229. {
  2230. if (displayedTextFunction)
  2231. {
  2232. m_displayedTextFunction = displayedTextFunction;
  2233. }
  2234. else
  2235. {
  2236. // For null function objects, we fall back on our default implementation
  2237. m_displayedTextFunction = DefaultDisplayedTextFunction;
  2238. }
  2239. MarkRenderCacheDirty();
  2240. }
  2241. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2242. UiTextInterface::OverflowMode UiTextComponent::GetOverflowMode()
  2243. {
  2244. return m_overflowMode;
  2245. }
  2246. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2247. void UiTextComponent::SetOverflowMode(OverflowMode overflowMode)
  2248. {
  2249. if (m_overflowMode != overflowMode)
  2250. {
  2251. m_overflowMode = overflowMode;
  2252. MarkDrawBatchLinesDirty(false);
  2253. }
  2254. }
  2255. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2256. UiTextInterface::WrapTextSetting UiTextComponent::GetWrapText()
  2257. {
  2258. return m_wrapTextSetting;
  2259. }
  2260. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2261. void UiTextComponent::SetWrapText(WrapTextSetting wrapSetting)
  2262. {
  2263. if (m_wrapTextSetting != wrapSetting)
  2264. {
  2265. m_wrapTextSetting = wrapSetting;
  2266. MarkDrawBatchLinesDirty(false);
  2267. }
  2268. }
  2269. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2270. UiTextInterface::ShrinkToFit UiTextComponent::GetShrinkToFit()
  2271. {
  2272. return m_shrinkToFit;
  2273. }
  2274. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2275. void UiTextComponent::SetShrinkToFit(ShrinkToFit shrinkToFit)
  2276. {
  2277. if (m_shrinkToFit != shrinkToFit)
  2278. {
  2279. m_shrinkToFit = shrinkToFit;
  2280. MarkDrawBatchLinesDirty(false);
  2281. }
  2282. }
  2283. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2284. bool UiTextComponent::GetIsMarkupEnabled()
  2285. {
  2286. return m_isMarkupEnabled;
  2287. }
  2288. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2289. void UiTextComponent::SetIsMarkupEnabled(bool isEnabled)
  2290. {
  2291. if (m_isMarkupEnabled != isEnabled)
  2292. {
  2293. m_isMarkupEnabled = isEnabled;
  2294. OnMarkupEnabledChange();
  2295. }
  2296. }
  2297. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2298. float UiTextComponent::GetMinimumShrinkScale()
  2299. {
  2300. return m_minShrinkScale;
  2301. }
  2302. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2303. void UiTextComponent::SetMinimumShrinkScale(float minShrinkScale)
  2304. {
  2305. // Guard against negative shrink scales
  2306. m_minShrinkScale = AZ::GetMax<float>(0.0f, minShrinkScale);
  2307. }
  2308. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2309. void UiTextComponent::GetClickableTextRects(UiClickableTextInterface::ClickableTextRects& clickableTextRects)
  2310. {
  2311. UiTransformInterface::RectPoints points;
  2312. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, points);
  2313. AZ::Vector2 pos = CalculateAlignedPositionWithYOffset(points);
  2314. const DrawBatchLines& drawBatchLines = GetDrawBatchLines();
  2315. float newlinePosYIncrement = 0.0f;
  2316. for (auto& drawBatchLine : drawBatchLines.batchLines)
  2317. {
  2318. float xDrawPosOffset = 0.0f;
  2319. AZ::Vector2 alignedPosition;
  2320. if (m_textHAlignment == IDraw2d::HAlign::Left && m_textVAlignment == IDraw2d::VAlign::Top)
  2321. {
  2322. alignedPosition = pos;
  2323. }
  2324. else
  2325. {
  2326. alignedPosition = Draw2dHelper::Align(pos, drawBatchLine.lineSize, m_textHAlignment, IDraw2d::VAlign::Top); // y is already aligned
  2327. }
  2328. alignedPosition.SetY(alignedPosition.GetY() + newlinePosYIncrement);
  2329. for (auto& drawBatch : drawBatchLine.drawBatchList)
  2330. {
  2331. if (drawBatch.GetType() == UiTextComponent::DrawBatch::Type::Text)
  2332. {
  2333. if (ShouldClip())
  2334. {
  2335. alignedPosition.SetX(alignedPosition.GetX() - CalculateHorizontalClipOffset());
  2336. }
  2337. alignedPosition.SetX(alignedPosition.GetX() + xDrawPosOffset);
  2338. Vec2 textSize(drawBatch.size.GetX(), drawBatch.size.GetY());
  2339. xDrawPosOffset = textSize.x;
  2340. if (drawBatch.IsClickable())
  2341. {
  2342. UiClickableTextInterface::ClickableTextRect clickableRect;
  2343. clickableRect.rect.left = alignedPosition.GetX();
  2344. clickableRect.rect.right = clickableRect.rect.left + drawBatch.size.GetX();
  2345. clickableRect.rect.top = alignedPosition.GetY();
  2346. clickableRect.rect.bottom = clickableRect.rect.top + drawBatchLine.lineSize.GetY();
  2347. clickableRect.action = drawBatch.action;
  2348. clickableRect.data = drawBatch.data;
  2349. clickableRect.id = drawBatch.clickableId;
  2350. clickableTextRects.push_back(clickableRect);
  2351. }
  2352. }
  2353. else if (drawBatch.GetType() == UiTextComponent::DrawBatch::Type::Image)
  2354. {
  2355. xDrawPosOffset = drawBatch.size.GetX();
  2356. }
  2357. else
  2358. {
  2359. AZ_Assert(false, "Unknown DrawBatch Type");
  2360. }
  2361. }
  2362. newlinePosYIncrement += drawBatchLine.lineSize.GetY() + m_lineSpacing;
  2363. }
  2364. }
  2365. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2366. void UiTextComponent::SetClickableTextColor(int id, const AZ::Color& color)
  2367. {
  2368. if (id < 0)
  2369. {
  2370. return;
  2371. }
  2372. bool clickableIdFound = false;
  2373. for (auto& drawBatchLine : m_drawBatchLines.batchLines)
  2374. {
  2375. for (auto& drawBatch : drawBatchLine.drawBatchList)
  2376. {
  2377. if (drawBatch.IsClickable())
  2378. {
  2379. if (id == drawBatch.clickableId)
  2380. {
  2381. // Don't return here. We purposely continue iterating in
  2382. // case there are subsequent draw batches (especially
  2383. // across multiple draw batch lines) with the same ID.
  2384. // This will occur with word-wrapped text.
  2385. drawBatch.color = color.GetAsVector3();
  2386. MarkRenderCacheDirty();
  2387. clickableIdFound = true;
  2388. }
  2389. else if (clickableIdFound)
  2390. {
  2391. // However, we can end iteration if we found a matching
  2392. // ID but we've moved on to non-matching clickable IDs.
  2393. // Since IDs are unique to a text component, there are no
  2394. // other batches with the same ID.
  2395. return;
  2396. }
  2397. }
  2398. }
  2399. }
  2400. }
  2401. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2402. void UiTextComponent::PropertyValuesChanged()
  2403. {
  2404. if (!m_isColorOverridden)
  2405. {
  2406. m_overrideColor = m_color;
  2407. }
  2408. if (!m_isAlphaOverridden)
  2409. {
  2410. m_overrideAlpha = m_alpha;
  2411. }
  2412. if (!m_isFontFamilyOverridden)
  2413. {
  2414. m_overrideFontFamily = m_fontFamily;
  2415. }
  2416. if (!m_isFontEffectOverridden)
  2417. {
  2418. m_overrideFontEffectIndex = m_fontEffectIndex;
  2419. }
  2420. // If any of the properties that affect line width changed
  2421. if (m_currFontSize != m_fontSize || m_currCharSpacing != m_charSpacing)
  2422. {
  2423. OnTextWidthPropertyChanged();
  2424. m_currFontSize = m_fontSize;
  2425. m_currCharSpacing = m_charSpacing;
  2426. }
  2427. MarkRenderCacheDirty();
  2428. }
  2429. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2430. void UiTextComponent::OnCanvasSpaceRectChanged([[maybe_unused]] AZ::EntityId entityId, const UiTransformInterface::Rect& oldRect, const UiTransformInterface::Rect& newRect)
  2431. {
  2432. // If old rect equals new rect, size changed due to initialization
  2433. const bool sizeChanged = (oldRect == newRect) || (!oldRect.GetSize().IsClose(newRect.GetSize(), 0.05f));
  2434. if (sizeChanged)
  2435. {
  2436. // OnCanvasSpaceRectChanged (with a size change) is called on the first canvas update, any calculation of
  2437. // the draw batches before the first call to OnCanvasSpaceRectChanged may be using the wrong size so we
  2438. // call MarkDrawBatchLinesDirty on the initialization case..
  2439. MarkDrawBatchLinesDirty(false);
  2440. if (m_wrapTextSetting != UiTextInterface::WrapTextSetting::NoWrap)
  2441. {
  2442. // Invalidate the element's layout since element width affects text height (ex. text element has a layout fitter that is set to fit height)
  2443. AZ::EntityId canvasEntityId;
  2444. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  2445. UiLayoutManagerBus::Event(canvasEntityId, &UiLayoutManagerBus::Events::MarkToRecomputeLayout, GetEntityId());
  2446. }
  2447. }
  2448. // If size did not change, then the position must have changed for this method to be called, so notify listeners that
  2449. // the clickable text rects have changed and invalidate the render cache.
  2450. UiClickableTextNotificationsBus::Event(GetEntityId(), &UiClickableTextNotificationsBus::Events::OnClickableTextChanged);
  2451. MarkRenderCacheDirty();
  2452. }
  2453. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2454. void UiTextComponent::OnTransformToViewportChanged()
  2455. {
  2456. // Request size is correlated with transformation scale, so it must be
  2457. // updated when the scale changes.
  2458. m_isRequestFontSizeDirty = true;
  2459. MarkRenderCacheDirty();
  2460. }
  2461. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2462. float UiTextComponent::GetMinWidth()
  2463. {
  2464. return 0.0f;
  2465. }
  2466. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2467. float UiTextComponent::GetMinHeight()
  2468. {
  2469. return 0.0f;
  2470. }
  2471. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2472. float UiTextComponent::GetTargetWidth(float maxWidth)
  2473. {
  2474. // Calculate draw batch lines based on max width. If unlimited, don't wrap text
  2475. bool forceNoWrap = !LyShine::IsUiLayoutCellSizeSpecified(maxWidth);
  2476. // Trailing space width needs to be included in the total line width so the element width is
  2477. // assigned enough space to include the trailing space. Otherwise, when calculating batch lines
  2478. // for rendering, a new empty line will be added to account for the newline that gets added
  2479. // due to not having enough room for the trailing space
  2480. bool excludeTrailingSpaceWidth = false;
  2481. DrawBatchLines drawBatchLines;
  2482. CalculateDrawBatchLines(drawBatchLines, forceNoWrap, maxWidth, excludeTrailingSpaceWidth);
  2483. // Since we don't know about max height, we can't return an exact target width when overflow
  2484. // handling is enabled because font scaling can change the max width of the draw batch lines.
  2485. // However, the extra width should be minimal
  2486. // Calculate the target width based on the draw batch line sizes
  2487. float textWidth = 0.0f;
  2488. for (const DrawBatchLine& drawBatchLine : drawBatchLines.batchLines)
  2489. {
  2490. textWidth = AZ::GetMax(drawBatchLine.lineSize.GetX(), textWidth);
  2491. }
  2492. if (m_wrapTextSetting != UiTextInterface::WrapTextSetting::NoWrap)
  2493. {
  2494. // In order for the wrapping to remain the same after the resize, the
  2495. // text element width would need to match the string width exactly. To accommodate
  2496. // for slight variation in size, add a small value to ensure that the string will fit
  2497. // inside the text element's bounds. The downside to this is there may be extra space
  2498. // at the bottom, but this is unlikely.
  2499. const float epsilon = 0.01f;
  2500. textWidth += epsilon;
  2501. }
  2502. return textWidth;
  2503. }
  2504. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2505. float UiTextComponent::GetTargetHeight(float maxHeight)
  2506. {
  2507. // Since target height is calculated after widths are assigned, it can rely on the element's width
  2508. // Check if draw batch lines should be calculated to determine target height, or whether we can
  2509. // use the existing draw batch lines. Overflow mode and shrink to fit mode are based on available height,
  2510. // so we can't rely on current draw batch lines if max height is specified
  2511. const bool haveMaxHeight = LyShine::IsUiLayoutCellSizeSpecified(maxHeight);
  2512. const bool ellipsis = m_overflowMode == OverflowMode::Ellipsis;
  2513. const bool shrinkToFit = m_shrinkToFit == ShrinkToFit::Uniform;
  2514. const bool handleOverflow = haveMaxHeight && (ellipsis || shrinkToFit);
  2515. const bool handleNoOverflow = !haveMaxHeight && (m_drawBatchLines.fontSizeScale.GetY() != 1.0f);
  2516. bool calculateBatchLines = m_areDrawBatchLinesDirty || handleOverflow || handleNoOverflow;
  2517. if (!calculateBatchLines)
  2518. {
  2519. // Check if the element's size has changed, but we haven't received a callback about it yet to mark
  2520. // draw batches dirty (typically done by the Layout Manager after ApplyLayoutWidth and before ApplyLayoutHeight)
  2521. bool canvasSpaceSizeChanged = false;
  2522. UiTransformBus::EventResult(canvasSpaceSizeChanged, GetEntityId(), &UiTransformBus::Events::HasCanvasSpaceSizeChanged);
  2523. calculateBatchLines = canvasSpaceSizeChanged;
  2524. }
  2525. AZ::Vector2 textSize;
  2526. if (calculateBatchLines)
  2527. {
  2528. // Calculate the draw batch lines
  2529. DrawBatchLines drawBatchLines;
  2530. CalculateDrawBatchLines(drawBatchLines);
  2531. if (handleOverflow)
  2532. {
  2533. // Handle overflow to get an accurate height after the font scale has been determined.
  2534. // The font scale is calculated with fixed increments and may end up being a little smaller
  2535. // than necessary leaving extra height. This step could be eliminated if we can find a more
  2536. // optimal font scale, but that could come with a performance cost.
  2537. // Extra height may also be considered acceptable since the same side effect occurs with
  2538. // fixed height text elements, and there may be extra width as well. However, since we're
  2539. // calculating an optimal height here, we try to be as accurate as possible
  2540. HandleShrinkToFit(drawBatchLines, maxHeight);
  2541. HandleEllipsis(drawBatchLines, maxHeight);
  2542. }
  2543. textSize = GetTextSizeFromDrawBatchLines(drawBatchLines);
  2544. }
  2545. else
  2546. {
  2547. textSize = GetTextSizeFromDrawBatchLines(m_drawBatchLines);
  2548. }
  2549. float textHeight = textSize.GetY();
  2550. if (handleOverflow && m_wrapTextSetting != UiTextInterface::WrapTextSetting::NoWrap)
  2551. {
  2552. // In order for the overflow handling to remain the same after the text element is resized to this
  2553. // new height, the new height must match the height retrieved from GetCanvasSpacePointsNoScaleRotate
  2554. // exactly. However, there is a slight variation in the value that is used to set the element height
  2555. // and the height retrieved from GetCanvasSpacePointsNoScaleRotate. To accommodate for this, add a
  2556. // small value to try and make the overflow handling as close to how it was calculated here as possible
  2557. const float epsilon = 0.01f;
  2558. textHeight += epsilon;
  2559. }
  2560. return textHeight;
  2561. }
  2562. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2563. float UiTextComponent::GetExtraWidthRatio()
  2564. {
  2565. return 1.0f;
  2566. }
  2567. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2568. float UiTextComponent::GetExtraHeightRatio()
  2569. {
  2570. return 1.0f;
  2571. }
  2572. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2573. void UiTextComponent::OnFontsReloaded()
  2574. {
  2575. // All old font pointers have been deleted and the old font family pointers have been removed from the CryFont list.
  2576. // New fonts and font family objects have been created and added to the CryFont list.
  2577. // However, the old font family objects are still around because we have a shared pointer to them.
  2578. // Clear the font family shared pointers since they should no longer be used (their fonts have been deleted).
  2579. // When the last one is cleared, the font family's custom deleter will be called and the object will be deleted.
  2580. // This is OK because the custom deleter doesn't do anything if the font family is not in the CryFont's list (which it isn't)
  2581. m_font = nullptr;
  2582. m_fontFamily = nullptr;
  2583. m_overrideFontFamily = nullptr;
  2584. m_isFontFamilyOverridden = false;
  2585. // the font family may have been deleted and reloaded so make sure we update m_fontFamily
  2586. ChangeFont(m_fontFilename.GetAssetPath());
  2587. // It's possible that the font failed to load. If it did, try to load and use the default font but leave the
  2588. // assigned font path the same
  2589. if (!m_fontFamily || !m_font)
  2590. {
  2591. AZStd::string assignedFontFilepath = m_fontFilename.GetAssetPath();
  2592. ChangeFont("");
  2593. m_fontFilename.SetAssetPath(assignedFontFilepath.c_str());
  2594. }
  2595. }
  2596. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2597. void UiTextComponent::LanguageChanged()
  2598. {
  2599. OnTextChange();
  2600. }
  2601. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2602. void UiTextComponent::OnCanvasTextPixelAlignmentChange()
  2603. {
  2604. MarkDrawBatchLinesDirty(true);
  2605. }
  2606. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2607. void UiTextComponent::OnAtlasLoaded(const TextureAtlasNamespace::TextureAtlas* atlas)
  2608. {
  2609. bool atlasUsageChanged = false;
  2610. for (auto image : m_drawBatchLines.inlineImages)
  2611. {
  2612. if (image->OnAtlasLoaded(atlas))
  2613. {
  2614. atlasUsageChanged = true;
  2615. }
  2616. }
  2617. if (atlasUsageChanged)
  2618. {
  2619. MarkRenderCacheDirty();
  2620. }
  2621. }
  2622. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2623. void UiTextComponent::OnAtlasUnloaded(const TextureAtlasNamespace::TextureAtlas* atlas)
  2624. {
  2625. bool atlasUsageChanged = false;
  2626. for (auto image : m_drawBatchLines.inlineImages)
  2627. {
  2628. if (image->OnAtlasUnloaded(atlas))
  2629. {
  2630. atlasUsageChanged = true;
  2631. }
  2632. }
  2633. if (atlasUsageChanged)
  2634. {
  2635. MarkRenderCacheDirty();
  2636. }
  2637. }
  2638. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2639. //! UiTextNotificationsBusBehaviorHandler Behavior context handler class
  2640. class UiTextNotificationsBusBehaviorHandler
  2641. : public UiTextNotificationsBus::Handler
  2642. , public AZ::BehaviorEBusHandler
  2643. {
  2644. public:
  2645. AZ_EBUS_BEHAVIOR_BINDER(
  2646. UiTextNotificationsBusBehaviorHandler, "{ACCB73DC-86DD-4D1C-85B3-1E016BDAA495}", AZ::SystemAllocator, OnLayoutInvalidated);
  2647. void OnLayoutInvalidated() override
  2648. {
  2649. Call(FN_OnLayoutInvalidated);
  2650. }
  2651. };
  2652. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2653. // PUBLIC STATIC MEMBER FUNCTIONS
  2654. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2655. void UiTextComponent::Reflect(AZ::ReflectContext* context)
  2656. {
  2657. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  2658. if (serializeContext)
  2659. {
  2660. serializeContext->Class<UiTextComponent, AZ::Component>()
  2661. ->Version(9, &VersionConverter)
  2662. ->Field("Text", &UiTextComponent::m_text)
  2663. ->Field("MarkupEnabled", &UiTextComponent::m_isMarkupEnabled)
  2664. ->Field("Color", &UiTextComponent::m_color)
  2665. ->Field("Alpha", &UiTextComponent::m_alpha)
  2666. ->Field("FontFileName", &UiTextComponent::m_fontFilename)
  2667. ->Field("FontSize", &UiTextComponent::m_fontSize)
  2668. ->Field("EffectIndex", &UiTextComponent::m_fontEffectIndex)
  2669. ->Field("TextHAlignment", &UiTextComponent::m_textHAlignment)
  2670. ->Field("TextVAlignment", &UiTextComponent::m_textVAlignment)
  2671. ->Field("CharacterSpacing", &UiTextComponent::m_charSpacing)
  2672. ->Field("LineSpacing", &UiTextComponent::m_lineSpacing)
  2673. ->Field("OverflowMode", &UiTextComponent::m_overflowMode)
  2674. ->Field("WrapTextSetting", &UiTextComponent::m_wrapTextSetting)
  2675. ->Field("ShrinkToFit", &UiTextComponent::m_shrinkToFit)
  2676. ->Field("MinShrinkScale", &UiTextComponent::m_minShrinkScale);
  2677. AZ::EditContext* ec = serializeContext->GetEditContext();
  2678. if (ec)
  2679. {
  2680. auto editInfo = ec->Class<UiTextComponent>("Text", "A visual component that draws a text string");
  2681. editInfo->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  2682. ->Attribute(AZ::Edit::Attributes::Category, "UI")
  2683. ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/UiText.png")
  2684. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/UiText.png")
  2685. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("UI", 0x27ff46b0))
  2686. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  2687. editInfo->DataElement(0, &UiTextComponent::m_text, "Text", "The text string")
  2688. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnTextChange)
  2689. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties);
  2690. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiTextComponent::m_isMarkupEnabled, "Enable markup", "Enable to support XML markup in the text string")
  2691. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnMarkupEnabledChange);
  2692. editInfo->DataElement(AZ::Edit::UIHandlers::Color, &UiTextComponent::m_color, "Color", "The color to draw the text string")
  2693. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnColorChange);
  2694. editInfo->DataElement(AZ::Edit::UIHandlers::Slider, &UiTextComponent::m_alpha, "Alpha", "The transparency of the text string")
  2695. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnColorChange)
  2696. ->Attribute(AZ::Edit::Attributes::Min, 0.0f)
  2697. ->Attribute(AZ::Edit::Attributes::Max, 1.0f);
  2698. editInfo->DataElement("SimpleAssetRef", &UiTextComponent::m_fontFilename, "Font path", "The pathname to the font")
  2699. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnFontPathnameChange)
  2700. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties);
  2701. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTextComponent::m_fontEffectIndex, "Font effect", "The font effect (from font file)")
  2702. ->Attribute("EnumValues", &UiTextComponent::PopulateFontEffectList)
  2703. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnFontEffectChange)
  2704. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties);
  2705. editInfo->DataElement(AZ::Edit::UIHandlers::SpinBox, &UiTextComponent::m_fontSize, "Font size", "The size of the font in points")
  2706. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnFontSizeChange)
  2707. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties)
  2708. ->Attribute(AZ::Edit::Attributes::Min, 0.0f)
  2709. ->Attribute(AZ::Edit::Attributes::Step, 1.0f);
  2710. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTextComponent::m_textHAlignment, "Horizontal text alignment", "How to align the text within the rect")
  2711. ->EnumAttribute(IDraw2d::HAlign::Left, "Left")
  2712. ->EnumAttribute(IDraw2d::HAlign::Center, "Center")
  2713. ->EnumAttribute(IDraw2d::HAlign::Right, "Right")
  2714. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnAlignmentChange);
  2715. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTextComponent::m_textVAlignment, "Vertical text alignment", "How to align the text within the rect")
  2716. ->EnumAttribute(IDraw2d::VAlign::Top, "Top")
  2717. ->EnumAttribute(IDraw2d::VAlign::Center, "Center")
  2718. ->EnumAttribute(IDraw2d::VAlign::Bottom, "Bottom")
  2719. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnAlignmentChange);
  2720. editInfo->DataElement(0, &UiTextComponent::m_charSpacing, "Character Spacing",
  2721. "The spacing in 1/1000th of ems to add between each two consecutive characters.\n"
  2722. "One em is equal to the currently specified font size.")
  2723. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnCharSpacingChange)
  2724. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties);
  2725. editInfo->DataElement(0, &UiTextComponent::m_lineSpacing, "Line Spacing", "The amount of pixels to add between each two consecutive lines.")
  2726. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnLineSpacingChange)
  2727. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties);
  2728. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTextComponent::m_overflowMode, "Overflow mode", "How text should fit within the element")
  2729. ->EnumAttribute(OverflowMode::OverflowText, "Overflow")
  2730. ->EnumAttribute(OverflowMode::ClipText, "Clip text")
  2731. ->EnumAttribute(OverflowMode::Ellipsis, "Ellipsis")
  2732. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnOverflowChange);
  2733. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTextComponent::m_wrapTextSetting, "Wrap text", "Determines whether text is wrapped")
  2734. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnWrapTextSettingChange)
  2735. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties)
  2736. ->EnumAttribute(WrapTextSetting::NoWrap, "No wrap")
  2737. ->EnumAttribute(WrapTextSetting::Wrap, "Wrap text");
  2738. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTextComponent::m_shrinkToFit, "Shrink to Fit", "Shrinks overflowing text to fit element bounds")
  2739. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnShrinkToFitChange)
  2740. ->EnumAttribute(ShrinkToFit::None, "None")
  2741. ->EnumAttribute(ShrinkToFit::Uniform, "Uniform")
  2742. ->EnumAttribute(ShrinkToFit::WidthOnly, "Width Only");
  2743. editInfo->DataElement(AZ::Edit::UIHandlers::SpinBox, &UiTextComponent::m_minShrinkScale, "Minimum Shrink Scale", "Smallest scale that can be applied when 'Shrink to Fit' is specified")
  2744. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiTextComponent::OnMinShrinkScaleChange)
  2745. ->Attribute(AZ::Edit::Attributes::Min, 0.0f)
  2746. ->Attribute(AZ::Edit::Attributes::Max, 1.0f);
  2747. }
  2748. }
  2749. AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
  2750. if (behaviorContext)
  2751. {
  2752. behaviorContext->EBus<UiTextBus>("UiTextBus")
  2753. ->Event("GetText", &UiTextBus::Events::GetText)
  2754. ->Event("SetText", &UiTextBus::Events::SetText)
  2755. ->Event("GetColor", &UiTextBus::Events::GetColor)
  2756. ->Event("SetColor", &UiTextBus::Events::SetColor)
  2757. ->Event("GetFont", &UiTextBus::Events::GetFont)
  2758. ->Event("SetFont", &UiTextBus::Events::SetFont)
  2759. ->Event("GetFontEffect", &UiTextBus::Events::GetFontEffect)
  2760. ->Event("SetFontEffect", &UiTextBus::Events::SetFontEffect)
  2761. ->Event("GetFontEffectName", &UiTextBus::Events::GetFontEffectName)
  2762. ->Event("SetFontEffectByName", &UiTextBus::Events::SetFontEffectByName)
  2763. ->Event("GetFontSize", &UiTextBus::Events::GetFontSize)
  2764. ->Event("SetFontSize", &UiTextBus::Events::SetFontSize)
  2765. ->Event("GetHorizontalTextAlignment", &UiTextBus::Events::GetHorizontalTextAlignment)
  2766. ->Event("SetHorizontalTextAlignment", &UiTextBus::Events::SetHorizontalTextAlignment)
  2767. ->Event("GetVerticalTextAlignment", &UiTextBus::Events::GetVerticalTextAlignment)
  2768. ->Event("SetVerticalTextAlignment", &UiTextBus::Events::SetVerticalTextAlignment)
  2769. ->Event("GetCharacterSpacing", &UiTextBus::Events::GetCharacterSpacing)
  2770. ->Event("SetCharacterSpacing", &UiTextBus::Events::SetCharacterSpacing)
  2771. ->Event("GetLineSpacing", &UiTextBus::Events::GetLineSpacing)
  2772. ->Event("SetLineSpacing", &UiTextBus::Events::SetLineSpacing)
  2773. ->Event("GetOverflowMode", &UiTextBus::Events::GetOverflowMode)
  2774. ->Event("SetOverflowMode", &UiTextBus::Events::SetOverflowMode)
  2775. ->Event("GetWrapText", &UiTextBus::Events::GetWrapText)
  2776. ->Event("SetWrapText", &UiTextBus::Events::SetWrapText)
  2777. ->Event("GetShrinkToFit", &UiTextBus::Events::GetShrinkToFit)
  2778. ->Event("SetShrinkToFit", &UiTextBus::Events::SetShrinkToFit)
  2779. ->Event("GetIsMarkupEnabled", &UiTextBus::Events::GetIsMarkupEnabled)
  2780. ->Event("SetIsMarkupEnabled", &UiTextBus::Events::SetIsMarkupEnabled)
  2781. ->Event("GetTextWidth", &UiTextBus::Events::GetTextWidth)
  2782. ->Event("GetTextHeight", &UiTextBus::Events::GetTextHeight)
  2783. ->Event("GetTextSize", &UiTextBus::Events::GetTextSize)
  2784. ->VirtualProperty("FontSize", "GetFontSize", "SetFontSize")
  2785. ->VirtualProperty("Color", "GetColor", "SetColor")
  2786. ->VirtualProperty("CharacterSpacing", "GetCharacterSpacing", "SetCharacterSpacing")
  2787. ->VirtualProperty("LineSpacing", "GetLineSpacing", "SetLineSpacing");
  2788. behaviorContext->Class<UiTextComponent>()->RequestBus("UiTextBus");
  2789. behaviorContext->EBus<UiTextNotificationsBus>("UiTextNotificationsBus")->Handler<UiTextNotificationsBusBehaviorHandler>();
  2790. behaviorContext->EBus<UiClickableTextBus>("UiClickableTextBus")
  2791. ->Event("SetClickableTextColor", &UiClickableTextBus::Events::SetClickableTextColor);
  2792. behaviorContext
  2793. ->Enum<(int)UiTextInterface::OverflowMode::OverflowText>("eUiTextOverflowMode_OverflowText")
  2794. ->Enum<(int)UiTextInterface::OverflowMode::ClipText>("eUiTextOverflowMode_ClipText")
  2795. ->Enum<(int)UiTextInterface::OverflowMode::Ellipsis>("eUiTextOverflowMode_Ellipsis")
  2796. ->Enum<(int)UiTextInterface::WrapTextSetting::NoWrap>("eUiTextWrapTextSetting_NoWrap")
  2797. ->Enum<(int)UiTextInterface::WrapTextSetting::Wrap>("eUiTextWrapTextSetting_Wrap")
  2798. ->Enum<(int)UiTextInterface::ShrinkToFit::None>("eUiTextShrinkToFit_None")
  2799. ->Enum<(int)UiTextInterface::ShrinkToFit::Uniform>("eUiTextShrinkToFit_Uniform")
  2800. ->Enum<(int)UiTextInterface::ShrinkToFit::WidthOnly>("eUiTextShrinkToFit_WidthOnly");
  2801. }
  2802. }
  2803. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2804. // PROTECTED MEMBER FUNCTIONS
  2805. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2806. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2807. void UiTextComponent::Init()
  2808. {
  2809. m_overrideColor = m_color;
  2810. m_overrideAlpha = m_alpha;
  2811. m_overrideFontFamily = m_fontFamily;
  2812. m_overrideFontEffectIndex = m_fontEffectIndex;
  2813. m_requestFontSize = static_cast<int>(m_fontSize);
  2814. // If this is called from RC.exe for example these pointers will not be set. In that case
  2815. // we only need to be able to load, init and save the component. It will never be
  2816. // activated.
  2817. if (!gEnv || !gEnv->pCryFont || !gEnv->pSystem)
  2818. {
  2819. return;
  2820. }
  2821. // if the font is not the one specified by the path (e.g. after loading using serialization)
  2822. if (gEnv->pCryFont->GetFontFamily(m_fontFilename.GetAssetPath().c_str()) != m_fontFamily)
  2823. {
  2824. ChangeFont(m_fontFilename.GetAssetPath());
  2825. }
  2826. // all saved UiTextComponents are assumed to want to try localization of the text string
  2827. m_locText = GetLocalizedText(m_text);
  2828. MarkDrawBatchLinesDirty(false);
  2829. }
  2830. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2831. void UiTextComponent::Activate()
  2832. {
  2833. UiVisualBus::Handler::BusConnect(GetEntityId());
  2834. UiRenderBus::Handler::BusConnect(GetEntityId());
  2835. UiTextBus::Handler::BusConnect(GetEntityId());
  2836. UiClickableTextBus::Handler::BusConnect(GetEntityId());
  2837. UiAnimateEntityBus::Handler::BusConnect(GetEntityId());
  2838. UiTransformChangeNotificationBus::Handler::BusConnect(GetEntityId());
  2839. UiLayoutCellDefaultBus::Handler::BusConnect(GetEntityId());
  2840. FontNotificationBus::Handler::BusConnect();
  2841. LanguageChangeNotificationBus::Handler::BusConnect();
  2842. // When we are activated the transform could have changed so we will always need to recompute the
  2843. // draw batch lines before they are used. Also, we pass true to invalidate the layout,
  2844. // if this is the first time the entity has been activated this has no effect since the canvas
  2845. // is not known. But if a Text component has just been added onto an existing entity
  2846. // we need to invalidate the layout in case that affects things when there is a parent layout
  2847. // component.
  2848. MarkDrawBatchLinesDirty(true);
  2849. }
  2850. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2851. void UiTextComponent::Deactivate()
  2852. {
  2853. UiVisualBus::Handler::BusDisconnect();
  2854. UiRenderBus::Handler::BusDisconnect();
  2855. UiTextBus::Handler::BusDisconnect();
  2856. UiClickableTextBus::Handler::BusDisconnect();
  2857. UiAnimateEntityBus::Handler::BusDisconnect();
  2858. UiTransformChangeNotificationBus::Handler::BusDisconnect();
  2859. UiLayoutCellDefaultBus::Handler::BusDisconnect();
  2860. FontNotificationBus::Handler::BusDisconnect();
  2861. LanguageChangeNotificationBus::Handler::BusDisconnect();
  2862. if (UiCanvasPixelAlignmentNotificationBus::Handler::BusIsConnected())
  2863. {
  2864. UiCanvasPixelAlignmentNotificationBus::Handler::BusDisconnect();
  2865. }
  2866. TextureAtlasNamespace::TextureAtlasNotificationBus::Handler::BusDisconnect();
  2867. // We could be about to remove this component and then reactivate the entity
  2868. // which could affect the layout if there is a parent layout component
  2869. InvalidateLayout();
  2870. // reduce memory use when deactivated
  2871. ClearRenderCache();
  2872. }
  2873. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2874. void UiTextComponent::ChangeFont(const AZStd::string& fontFileName)
  2875. {
  2876. AZStd::string fileName = fontFileName;
  2877. if (fileName.empty())
  2878. {
  2879. fileName = "default-ui";
  2880. }
  2881. FontFamilyPtr fontFamily = gEnv->pCryFont->GetFontFamily(fileName.c_str());
  2882. if (!fontFamily)
  2883. {
  2884. fontFamily = gEnv->pCryFont->LoadFontFamily(fileName.c_str());
  2885. }
  2886. if (fontFamily)
  2887. {
  2888. m_fontFamily = fontFamily;
  2889. m_font = m_fontFamily->normal;
  2890. // we know that the input path is a root relative and normalized pathname
  2891. m_fontFilename.SetAssetPath(fileName.c_str());
  2892. // the font has changed so check that the font effect is valid
  2893. unsigned int numEffects = m_font->GetNumEffects();
  2894. if (m_fontEffectIndex >= numEffects)
  2895. {
  2896. m_fontEffectIndex = 0;
  2897. AZ_Warning("UiTextComponent", false, "Font effect index is out of range for changed font, resetting index to 0");
  2898. }
  2899. if (!m_isFontFamilyOverridden)
  2900. {
  2901. m_overrideFontFamily = m_fontFamily;
  2902. if (m_overrideFontEffectIndex >= numEffects)
  2903. {
  2904. m_overrideFontEffectIndex = m_fontEffectIndex;
  2905. }
  2906. }
  2907. // When the font changes, we need to rebuild our draw batches
  2908. MarkDrawBatchLinesDirty(true);
  2909. }
  2910. else
  2911. {
  2912. AZ_Warning("UiTextComponent", false, "Failed to find font family referenced in markup (ChangeFont): %s", fileName.c_str());
  2913. }
  2914. MarkRenderCacheDirty();
  2915. }
  2916. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2917. void UiTextComponent::GetTextRect(UiTransformInterface::RectPoints& rect)
  2918. {
  2919. GetTextRect(rect, GetTextSize());
  2920. }
  2921. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2922. void UiTextComponent::GetTextRect(UiTransformInterface::RectPoints& rect, const AZ::Vector2& textSize)
  2923. {
  2924. // get the "no scale rotate" element box
  2925. UiTransformInterface::RectPoints elemRect;
  2926. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, elemRect);
  2927. // given the text alignment work out the box of the actual text
  2928. rect = elemRect;
  2929. switch (m_textHAlignment)
  2930. {
  2931. case IDraw2d::HAlign::Left:
  2932. rect.BottomRight().SetX(rect.TopLeft().GetX() + textSize.GetX());
  2933. rect.TopRight().SetX(rect.BottomRight().GetX());
  2934. break;
  2935. case IDraw2d::HAlign::Center:
  2936. {
  2937. float centerX = (rect.TopLeft().GetX() + rect.TopRight().GetX()) * 0.5f;
  2938. float halfWidth = textSize.GetX() * 0.5f;
  2939. rect.BottomLeft().SetX(centerX - halfWidth);
  2940. rect.TopLeft().SetX(rect.BottomLeft().GetX());
  2941. rect.BottomRight().SetX(centerX + halfWidth);
  2942. rect.TopRight().SetX(rect.BottomRight().GetX());
  2943. break;
  2944. }
  2945. case IDraw2d::HAlign::Right:
  2946. rect.BottomLeft().SetX(rect.TopRight().GetX() - textSize.GetX());
  2947. rect.TopLeft().SetX(rect.BottomLeft().GetX());
  2948. break;
  2949. }
  2950. switch (m_textVAlignment)
  2951. {
  2952. case IDraw2d::VAlign::Top:
  2953. rect.BottomLeft().SetY(rect.TopLeft().GetY() + textSize.GetY());
  2954. rect.BottomRight().SetY(rect.BottomLeft().GetY());
  2955. break;
  2956. case IDraw2d::VAlign::Center:
  2957. {
  2958. float centerY = (rect.TopLeft().GetY() + rect.BottomLeft().GetY()) * 0.5f;
  2959. float halfHeight = textSize.GetY() * 0.5f;
  2960. rect.TopLeft().SetY(centerY - halfHeight);
  2961. rect.TopRight().SetY(rect.TopLeft().GetY());
  2962. rect.BottomLeft().SetY(centerY + halfHeight);
  2963. rect.BottomRight().SetY(rect.BottomLeft().GetY());
  2964. break;
  2965. }
  2966. case IDraw2d::VAlign::Bottom:
  2967. rect.TopLeft().SetY(rect.BottomLeft().GetY() - textSize.GetY());
  2968. rect.TopRight().SetY(rect.TopLeft().GetY());
  2969. break;
  2970. }
  2971. }
  2972. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2973. void UiTextComponent::OnTextChange()
  2974. {
  2975. // When text is changed in the editor we always try to localize it
  2976. m_locText = GetLocalizedText(m_text);
  2977. MarkDrawBatchLinesDirty(true);
  2978. // the text changed so if markup is enabled the XML parsing should report warnings on next parse
  2979. if (m_isMarkupEnabled)
  2980. {
  2981. m_textNeedsXmlValidation = true;
  2982. }
  2983. }
  2984. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2985. void UiTextComponent::OnColorChange()
  2986. {
  2987. m_overrideColor = m_color;
  2988. m_overrideAlpha = m_alpha;
  2989. MarkRenderCacheDirty();
  2990. }
  2991. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2992. void UiTextComponent::OnAlignmentChange()
  2993. {
  2994. MarkRenderCacheDirty();
  2995. }
  2996. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2997. void UiTextComponent::OnOverflowChange()
  2998. {
  2999. // Overflow modes like ellipsis actually change the contents of the draw batches,
  3000. // so they need to be re-generated when the overflow setting changes.
  3001. MarkDrawBatchLinesDirty(true);
  3002. }
  3003. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3004. void UiTextComponent::OnFontSizeChange()
  3005. {
  3006. m_isRequestFontSizeDirty = true;
  3007. // We need to re-prepare the text for rendering, however this may not be
  3008. // very efficient since completely re-preparing the text (parsing markup,
  3009. // preparing batches, etc.) may not be necessary.
  3010. MarkDrawBatchLinesDirty(true);
  3011. }
  3012. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3013. AZ::u32 UiTextComponent::OnFontPathnameChange()
  3014. {
  3015. // we should be guaranteed that the asset path in the simple asset ref is root relative and
  3016. // normalized. But just to be safe we make sure is normalized
  3017. AZStd::string fontPath = m_fontFilename.GetAssetPath();
  3018. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::Bus::Events::NormalizePath, fontPath);
  3019. m_fontFilename.SetAssetPath(fontPath.c_str());
  3020. // if the font we have loaded has a different pathname to the one we want then change
  3021. // the font (Release the old one and Load or AddRef the new one)
  3022. if (gEnv->pCryFont->GetFontFamily(fontPath.c_str()) != m_fontFamily)
  3023. {
  3024. ChangeFont(m_fontFilename.GetAssetPath());
  3025. }
  3026. return AZ::Edit::PropertyRefreshLevels::AttributesAndValues;
  3027. }
  3028. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3029. void UiTextComponent::OnFontEffectChange()
  3030. {
  3031. m_overrideFontEffectIndex = m_fontEffectIndex;
  3032. MarkDrawBatchLinesDirty(true);
  3033. }
  3034. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3035. void UiTextComponent::OnWrapTextSettingChange()
  3036. {
  3037. MarkDrawBatchLinesDirty(true);
  3038. }
  3039. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3040. void UiTextComponent::OnShrinkToFitChange()
  3041. {
  3042. // Batches need to be re-configured since shrink-to-fit affects
  3043. // sizing information.
  3044. MarkDrawBatchLinesDirty(true);
  3045. }
  3046. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3047. void UiTextComponent::OnMinShrinkScaleChange()
  3048. {
  3049. // Batches need to be re-configured since shrink-to-fit affects
  3050. // sizing information.
  3051. MarkDrawBatchLinesDirty(true);
  3052. }
  3053. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3054. void UiTextComponent::OnCharSpacingChange()
  3055. {
  3056. InvalidateLayout();
  3057. OnTextWidthPropertyChanged();
  3058. }
  3059. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3060. void UiTextComponent::OnLineSpacingChange()
  3061. {
  3062. // If shrink-to-fit applies, we need to re-create draw batch lines in
  3063. // order to ensure overflow conditions are properly applied.
  3064. if (m_shrinkToFit != ShrinkToFit::None)
  3065. {
  3066. MarkDrawBatchLinesDirty(true);
  3067. }
  3068. else
  3069. {
  3070. InvalidateLayout();
  3071. MarkRenderCacheDirty();
  3072. }
  3073. }
  3074. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3075. void UiTextComponent::OnMarkupEnabledChange()
  3076. {
  3077. MarkDrawBatchLinesDirty(true);
  3078. if (m_isMarkupEnabled)
  3079. {
  3080. m_textNeedsXmlValidation = true;
  3081. }
  3082. }
  3083. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3084. UiTextComponent::FontEffectComboBoxVec UiTextComponent::PopulateFontEffectList()
  3085. {
  3086. FontEffectComboBoxVec result;
  3087. AZStd::vector<AZ::EntityId> entityIdList;
  3088. if (m_font)
  3089. {
  3090. unsigned int numEffects = m_font->GetNumEffects();
  3091. for (unsigned int i = 0; i < numEffects; ++i)
  3092. {
  3093. const char* name = m_font->GetEffectName(i);
  3094. result.push_back(AZStd::make_pair(i, name));
  3095. }
  3096. }
  3097. return result;
  3098. }
  3099. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3100. float UiTextComponent::CalculateHorizontalClipOffset()
  3101. {
  3102. const bool cursorIsValid = m_selectionStart >= 0;
  3103. if (ShouldClip() && m_wrapTextSetting != WrapTextSetting::Wrap && cursorIsValid)
  3104. {
  3105. UiTransformInterface::RectPoints points;
  3106. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, points);
  3107. int requestFontSize = GetRequestFontSize();
  3108. const DrawBatchLines& drawBatchLines = GetDrawBatchLines();
  3109. STextDrawContext fontContext(GetTextDrawContextPrototype(requestFontSize, drawBatchLines.fontSizeScale));
  3110. const AZStd::string displayedText(m_displayedTextFunction(m_locText));
  3111. const AZ::Vector2 displayedTextSize(GetTextSize());
  3112. const AZ::Vector2 elemSize(points.GetAxisAlignedSize());
  3113. const bool textOverflowing = displayedTextSize.GetX() > elemSize.GetX();
  3114. if (textOverflowing)
  3115. {
  3116. // Get size of text from beginning of the string to the end of
  3117. // the text selection. This forms the basis of the assumptions
  3118. // for the left and center-justified text cases, specifically for
  3119. // calculating the following boolean variables for each case:
  3120. // - cursorAtFirstChar
  3121. // - cursorClippedRight
  3122. // - cursorClippedLeft
  3123. int bytesToSelectionEnd = LyShine::GetByteLengthOfUtf8Chars(displayedText.c_str(), m_selectionEnd);
  3124. AZStd::string leftString(displayedText.substr(0, bytesToSelectionEnd));
  3125. Vec2 leftSize(m_font->GetTextSize(leftString.c_str(), true, fontContext));
  3126. if (m_textHAlignment == IDraw2d::HAlign::Left)
  3127. {
  3128. // Positive clip offset will scroll text left
  3129. m_clipOffsetMultiplier = 1.0f;
  3130. // Positive clip offsets scroll the text left, and negative
  3131. // scrolls the text right. Zero is the minimum for left-
  3132. // aligned since there is no text to scroll to before the first
  3133. // character in the string.
  3134. const float clipOffsetMin = 0.0f;
  3135. // Width of the clipping area to the left of the visible text
  3136. const float clipOffsetLeft = m_clipOffset;
  3137. // We calculate the clip offset differently based on where
  3138. // the cursor position is currently located.
  3139. const bool cursorAtFirstChar = leftSize.x == 0.0f;
  3140. const bool cursorClippedRight = leftSize.x > elemSize.GetX() + clipOffsetLeft;
  3141. const bool cursorClippedLeft = leftSize.x < clipOffsetLeft;
  3142. if (cursorAtFirstChar)
  3143. {
  3144. m_clipOffset = clipOffsetMin;
  3145. }
  3146. else if (cursorClippedRight)
  3147. {
  3148. // Scroll the text left to display characters to the
  3149. // right of the clipping area. The amount scrolled by is
  3150. // the clipped and non-clipped widths added together and
  3151. // subtracted from the string size to the left of the cursor.
  3152. m_clipOffset += leftSize.x - elemSize.GetX() - clipOffsetLeft;
  3153. }
  3154. else if (cursorClippedLeft)
  3155. {
  3156. // Cursor is clipped to the left, so scroll the text
  3157. // right by decreasing the clip offset.
  3158. m_clipOffset = leftSize.x;
  3159. }
  3160. }
  3161. else if (m_textHAlignment == IDraw2d::HAlign::Center)
  3162. {
  3163. // At zero offset, text is displayed centered. Negative
  3164. // values scroll text to the right, so to display the first
  3165. // char in the string, we would need to scroll by half of the
  3166. // total clipped text.
  3167. const float clipOffsetMin = -0.5f * (displayedTextSize.GetX() - elemSize.GetX());
  3168. // Width of the clipped text to the left of the visible text. Adjusted
  3169. // by the min clipping value when the offset becomes negative.
  3170. const float clipOffsetLeft = m_clipOffset >= 0.0f ? m_clipOffset : m_clipOffset - clipOffsetMin;
  3171. const bool cursorAtFirstChar = leftSize.x == 0.0f;
  3172. const bool cursorClippedRight = leftSize.x > elemSize.GetX() + clipOffsetLeft;
  3173. const bool cursorClippedLeft = leftSize.x < clipOffsetLeft;
  3174. if (cursorAtFirstChar)
  3175. {
  3176. m_clipOffset = clipOffsetMin;
  3177. m_clipOffsetMultiplier = 1.0f;
  3178. }
  3179. else if (cursorClippedRight)
  3180. {
  3181. // Similar to left-aligned text, but we adjust our offset
  3182. // multiplier to account for half of the width already
  3183. // being accounted for in centered-alignment logic elsewhere.
  3184. m_clipOffset += leftSize.x - elemSize.GetX() - clipOffsetLeft;
  3185. m_clipOffsetMultiplier = 0.5f;
  3186. }
  3187. else if (cursorClippedLeft)
  3188. {
  3189. const float prevClipOffset = m_clipOffset;
  3190. m_clipOffset = leftSize.x;
  3191. // Obtain a multiplier that, when multiplied by the new
  3192. // offset, returns the current offset value, minus the
  3193. // difference between the current and new offsets (to
  3194. // account for the clipped space).
  3195. const float clipOffsetInverse = 1.0f / m_clipOffset;
  3196. m_clipOffsetMultiplier = clipOffsetInverse * (prevClipOffset * (m_clipOffsetMultiplier - 1) + leftSize.x);
  3197. }
  3198. }
  3199. // Handle right-alignment
  3200. else
  3201. {
  3202. // Get the size of the text following the text selection. This
  3203. // is in contrast to left and center-aligned text, simply
  3204. // because it's more intuitive when dealing with right-
  3205. // aligned text, for the following conditions:
  3206. // - cursorAtFirstChar
  3207. // - cursorClippedRight
  3208. // - cursorClippedLeft
  3209. AZStd::string rightString(displayedText.substr(bytesToSelectionEnd, displayedText.length() - bytesToSelectionEnd));
  3210. Vec2 rightSize(m_font->GetTextSize(rightString.c_str(), true, fontContext));
  3211. // Negative offset will scroll text to the right
  3212. m_clipOffsetMultiplier = -1.0f;
  3213. // Clip offset 0 means the text is text is furthest to the
  3214. // right (for right-justified text).
  3215. const float clipOffsetMin = 0.0f;
  3216. // The difference between the total string size and element
  3217. // size results in the total width that is clipped. When
  3218. // the offset reaches this max value, the text is scrolled
  3219. // furthest to the right (displaying the left-most character
  3220. // in the string).
  3221. const float clipOffsetMax = -1.0f * (displayedTextSize.GetX() - elemSize.GetX());
  3222. // Amout of clipped text to the right of the non-clipped text
  3223. const float clipOffsetRight = m_clipOffset;
  3224. // Amout of clipped text to the left of the non-clipped text
  3225. const float clipOffsetLeft = clipOffsetRight > 0.0f ? fabs(clipOffsetMax) - clipOffsetRight : 0.0f;
  3226. const bool cursorAtFirstChar = rightSize.x == 0.0f;
  3227. const bool cursorClippedRight = leftSize.x > elemSize.GetX() + clipOffsetLeft;
  3228. const bool cursorClippedLeft = rightSize.x > elemSize.GetX() + clipOffsetRight;
  3229. if (cursorAtFirstChar)
  3230. {
  3231. m_clipOffset = clipOffsetMin;
  3232. }
  3233. else if (cursorClippedRight)
  3234. {
  3235. // The way the math is setup, if clip offset is zero, we
  3236. // would subtract from the offset amount each frame.
  3237. if (m_clipOffset != 0.0f)
  3238. {
  3239. m_clipOffset -= leftSize.x - elemSize.GetX() - clipOffsetLeft;
  3240. }
  3241. }
  3242. else if (cursorClippedLeft)
  3243. {
  3244. m_clipOffset += rightSize.x - elemSize.GetX() - clipOffsetRight;
  3245. }
  3246. }
  3247. }
  3248. else
  3249. {
  3250. m_clipOffset = 0.0f;
  3251. }
  3252. }
  3253. return m_clipOffset * m_clipOffsetMultiplier;
  3254. }
  3255. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3256. void UiTextComponent::MarkDrawBatchLinesDirty(bool invalidateLayout)
  3257. {
  3258. m_areDrawBatchLinesDirty = true;
  3259. m_drawBatchLines.Clear();
  3260. // Setting this saves Render() from having to check multiple flags.
  3261. MarkRenderCacheDirty();
  3262. if (invalidateLayout)
  3263. {
  3264. InvalidateLayout();
  3265. EBUS_EVENT_ID(GetEntityId(), UiTextNotificationsBus, OnLayoutInvalidated);
  3266. }
  3267. }
  3268. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3269. const UiTextComponent::DrawBatchLines& UiTextComponent::GetDrawBatchLines()
  3270. {
  3271. if (m_areDrawBatchLinesDirty)
  3272. {
  3273. // Reset the font size scale here so that the draw batches will be built at their original
  3274. // (unaltered) size. Otherwise overflow handling could operate based on sizing info
  3275. // that was calculated based on a previous overflow operation.
  3276. m_drawBatchLines.fontSizeScale = AZ::Vector2(1.0f, 1.0f);
  3277. CalculateDrawBatchLines(m_drawBatchLines);
  3278. HandleOverflowText(m_drawBatchLines);
  3279. m_areDrawBatchLinesDirty = false;
  3280. // m_drawBatchLines has changed so render cache is invalid
  3281. MarkRenderCacheDirty();
  3282. UiClickableTextNotificationsBus::Event(GetEntityId(), &UiClickableTextNotificationsBus::Events::OnClickableTextChanged);
  3283. }
  3284. return m_drawBatchLines;
  3285. }
  3286. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3287. void UiTextComponent::CalculateDrawBatchLines(
  3288. UiTextComponent::DrawBatchLines& drawBatchLinesOut,
  3289. bool forceNoWrap,
  3290. float availableWidth,
  3291. bool excludeTrailingSpaceWidth
  3292. )
  3293. {
  3294. bool wrapText = !forceNoWrap && (m_wrapTextSetting == WrapTextSetting::Wrap);
  3295. if (wrapText && availableWidth < 0.0f)
  3296. {
  3297. // Set available width to the width of the text element
  3298. if (UiTransformBus::FindFirstHandler(GetEntityId()))
  3299. {
  3300. // Getting info from the TransformBus could trigger OnCanvasSpaceRectChanged,
  3301. // which would cause this method to be called again. Call this first before
  3302. // we start building our string content! Otherwise drawbatches etc. will end
  3303. // up in a potentially undefined state.
  3304. UiTransformInterface::RectPoints points;
  3305. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, points);
  3306. availableWidth = points.GetAxisAlignedSize().GetX();
  3307. }
  3308. else
  3309. {
  3310. availableWidth = 100.0f; // abritrary width to use in unlikely edge case where there is no active transform component
  3311. }
  3312. }
  3313. // Clear the draw batch lines, but keep the images around until the new ones are created.
  3314. // This is to prevent the same texture from being unloaded and then re-loaded right away
  3315. InlineImageContainer prevInlineImages;
  3316. prevInlineImages = drawBatchLinesOut.inlineImages;
  3317. drawBatchLinesOut.inlineImages.clear();
  3318. drawBatchLinesOut.Clear();
  3319. int requestFontSize = GetRequestFontSize();
  3320. STextDrawContext fontContext(GetTextDrawContextPrototype(requestFontSize, drawBatchLinesOut.fontSizeScale));
  3321. // Set the baseline
  3322. drawBatchLinesOut.baseline = m_font->GetBaseline(fontContext);
  3323. UiTextComponent::DrawBatchContainer drawBatches;
  3324. TextMarkup::Tag markupRoot;
  3325. AZStd::string markupText(m_locText);
  3326. SanitizeUserEnteredNewlineChar(m_locText);
  3327. // Only attempt to parse the string for XML markup if the markup enabled flag is set (it is expensive)
  3328. bool suppressXmlWarnings = !m_textNeedsXmlValidation;
  3329. m_textNeedsXmlValidation = false;
  3330. if (m_isMarkupEnabled && TextMarkup::ParseMarkupBuffer(markupText, markupRoot, suppressXmlWarnings))
  3331. {
  3332. AZStd::stack<UiTextComponent::DrawBatch> batchStack;
  3333. AZStd::stack<FontFamily*> fontFamilyStack;
  3334. fontFamilyStack.push(m_overrideFontFamily.get());
  3335. float fontAscent = m_font->GetAscender(fontContext);
  3336. BuildDrawBatchesAndAssignClickableIds(drawBatches, drawBatchLinesOut.fontFamilyRefs, drawBatchLinesOut.inlineImages, m_fontSize, fontAscent, batchStack, fontFamilyStack, &markupRoot);
  3337. // go over the generated batches to scale empty space and look for font effects with transparency
  3338. IFFont* prevFont = nullptr;
  3339. drawBatchLinesOut.m_fontEffectHasTransparency = false;
  3340. for (auto& drawBatch : drawBatches)
  3341. {
  3342. if (drawBatch.image)
  3343. {
  3344. // Scale empty space (created by horizontal and vertical padding/offset with markup),
  3345. // otherwise element contents will scale unevenly with text.
  3346. drawBatch.image->m_leftPadding *= drawBatchLinesOut.fontSizeScale.GetX();
  3347. drawBatch.image->m_rightPadding *= drawBatchLinesOut.fontSizeScale.GetX();
  3348. drawBatch.image->m_yOffset *= drawBatchLinesOut.fontSizeScale.GetY();
  3349. // For uniform shrink-to-fit, the ascender (defaultImageHeight) gets assigned the
  3350. // scaled Y axis value from the font context, but for width-only shrink-to-fit, we
  3351. // need to apply the scale since the image is only scaled along the X-axis (and
  3352. // not included in the ascender/default image height).
  3353. if (m_shrinkToFit == ShrinkToFit::WidthOnly)
  3354. {
  3355. drawBatch.image->m_size.SetX(drawBatch.image->m_size.GetX() * drawBatchLinesOut.fontSizeScale.GetX());
  3356. }
  3357. }
  3358. else
  3359. {
  3360. // text batch, check for fonts with transparency in effects
  3361. if (!drawBatchLinesOut.m_fontEffectHasTransparency && drawBatch.font != prevFont)
  3362. {
  3363. IFFont* font = drawBatch.font;
  3364. // note that markup can change fonts but not the font effect index, the same
  3365. // font effect index is used for all batches (we may change this at some point).
  3366. if (font->DoesEffectHaveTransparency(fontContext.m_fxIdx))
  3367. {
  3368. drawBatchLinesOut.m_fontEffectHasTransparency = true;
  3369. }
  3370. prevFont = font;
  3371. }
  3372. }
  3373. }
  3374. }
  3375. else
  3376. {
  3377. IFFont* font = m_overrideFontFamily->normal;
  3378. drawBatches.push_back(DrawBatch());
  3379. drawBatches.front().font = font;
  3380. drawBatches.front().text = m_locText;
  3381. // If the font effect we are using has any passes with alpha of less than 1 (not common) then
  3382. // we set a flag in the batch lines since it affects how we can update the alpha in the cache
  3383. drawBatchLinesOut.m_fontEffectHasTransparency = font->DoesEffectHaveTransparency(fontContext.m_fxIdx);
  3384. }
  3385. // Remove old images now. This is to prevent the same images from unloading and then re-loading right away
  3386. for (auto image : prevInlineImages)
  3387. {
  3388. delete image;
  3389. }
  3390. prevInlineImages.clear();
  3391. // Check if we have any inline images that require us to connect to the texture atlas bus
  3392. if (drawBatchLinesOut.inlineImages.size() > 0)
  3393. {
  3394. if (!TextureAtlasNamespace::TextureAtlasNotificationBus::Handler::BusIsConnected())
  3395. {
  3396. TextureAtlasNamespace::TextureAtlasNotificationBus::Handler::BusConnect();
  3397. }
  3398. }
  3399. else
  3400. {
  3401. TextureAtlasNamespace::TextureAtlasNotificationBus::Handler::BusDisconnect();
  3402. }
  3403. // Go through the drawBatchLines and apply the text transform
  3404. for (DrawBatch& drawBatch : drawBatches)
  3405. {
  3406. if (drawBatch.GetType() == UiTextComponent::DrawBatch::Type::Text)
  3407. {
  3408. drawBatch.text = m_displayedTextFunction(drawBatch.text);
  3409. // If the font changed recently, then the font texture is empty, and won't be
  3410. // populated until the frame renders. If the glyphs aren't mapped to the
  3411. // font texture, then their sizes will be reported as zero/missing, which
  3412. // causes issues with alignment.
  3413. gEnv->pCryFont->AddCharsToFontTextures(m_fontFamily, drawBatch.text.c_str(), requestFontSize, requestFontSize);
  3414. }
  3415. }
  3416. if (wrapText)
  3417. {
  3418. if (drawBatchLinesOut.inlineImages.empty())
  3419. {
  3420. BatchAwareWrapText(drawBatchLinesOut, drawBatches, m_fontFamily.get(), fontContext, availableWidth, excludeTrailingSpaceWidth);
  3421. }
  3422. else
  3423. {
  3424. BatchAwareWrapTextWithImages(drawBatchLinesOut, drawBatches, m_fontFamily.get(), fontContext, availableWidth, excludeTrailingSpaceWidth);
  3425. }
  3426. }
  3427. else
  3428. {
  3429. CreateBatchLines(drawBatchLinesOut, drawBatches, m_fontFamily.get());
  3430. AssignLineSizes(drawBatchLinesOut, m_fontFamily.get(), fontContext, excludeTrailingSpaceWidth);
  3431. }
  3432. }
  3433. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3434. void UiTextComponent::RenderToCache(float alpha)
  3435. {
  3436. if (!m_overrideFontFamily)
  3437. {
  3438. return;
  3439. }
  3440. if (!UiCanvasPixelAlignmentNotificationBus::Handler::BusIsConnected())
  3441. {
  3442. AZ::EntityId canvasEntityId;
  3443. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  3444. UiCanvasPixelAlignmentNotificationBus::Handler::BusConnect(canvasEntityId);
  3445. }
  3446. int requestFontSize = GetRequestFontSize();
  3447. const DrawBatchLines& drawBatchLines = GetDrawBatchLines();
  3448. STextDrawContext fontContext(GetTextDrawContextPrototype(requestFontSize, drawBatchLines.fontSizeScale));
  3449. fontContext.SetOverrideViewProjMatrices(false);
  3450. ColorF color = LyShine::MakeColorF(m_overrideColor.GetAsVector3(), alpha);
  3451. color.srgb2rgb(); // the colors are specified in sRGB but we want linear colors in the shader
  3452. fontContext.SetColor(color);
  3453. // FFont.cpp uses the alpha value of the color to decide whether to use the color, if the alpha value is zero
  3454. // (in a ColorB format) then the color set via SetColor is ignored and it usually ends up drawing with an alpha of 1.
  3455. // This is not what we want. In fact, if the alpha is zero we will not end up rendering anything (due to the early
  3456. // out in UiTextComponent::Render()). So... we set the alpha to any non-zero value so that we do have something in
  3457. // the render cache. This means that if a fader is at zero and then is faded up, we still have something in the
  3458. // cache to modify the alpha values of.
  3459. if (!fontContext.IsColorOverridden())
  3460. {
  3461. color.a = 1.0f;
  3462. fontContext.SetColor(color);
  3463. }
  3464. // Tell the font system how to we are aligning the text
  3465. // The font system uses these alignment flags to force text to be in the safe zone
  3466. // depending on overscan etc
  3467. int flags = 0;
  3468. if (m_textHAlignment == IDraw2d::HAlign::Center)
  3469. {
  3470. flags |= eDrawText_Center;
  3471. }
  3472. else if (m_textHAlignment == IDraw2d::HAlign::Right)
  3473. {
  3474. flags |= eDrawText_Right;
  3475. }
  3476. if (m_textVAlignment == IDraw2d::VAlign::Center)
  3477. {
  3478. flags |= eDrawText_CenterV;
  3479. }
  3480. else if (m_textVAlignment == IDraw2d::VAlign::Bottom)
  3481. {
  3482. flags |= eDrawText_Bottom;
  3483. }
  3484. flags |= eDrawText_UseTransform;
  3485. fontContext.SetFlags(flags);
  3486. AZ::Matrix4x4 transform;
  3487. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetTransformToViewport, transform);
  3488. float transFloats[16];
  3489. transform.StoreToRowMajorFloat16(transFloats);
  3490. Matrix34 transform34(transFloats[0], transFloats[1], transFloats[2], transFloats[3],
  3491. transFloats[4], transFloats[5], transFloats[6], transFloats[7],
  3492. transFloats[8], transFloats[9], transFloats[10], transFloats[11]);
  3493. fontContext.SetTransform(transform34);
  3494. // Get the rect that positions the text prior to scale and rotate. The scale and rotate transform
  3495. // will be applied inside the font draw.
  3496. UiTransformInterface::RectPoints points;
  3497. UiTransformBus::Event(GetEntityId(), &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, points);
  3498. if (ShouldClip())
  3499. {
  3500. fontContext.EnableClipping(true);
  3501. const AZ::Vector2 elemSize(points.GetAxisAlignedSize());
  3502. // Set the clipping rect to be the same size and position of this
  3503. // element's rect.
  3504. fontContext.SetClippingRect(
  3505. points.TopLeft().GetX(),
  3506. points.TopLeft().GetY(),
  3507. elemSize.GetX(),
  3508. elemSize.GetY());
  3509. }
  3510. m_renderCache.m_fontContext = fontContext;
  3511. AZ::Vector2 pos = CalculateAlignedPositionWithYOffset(points);
  3512. RenderDrawBatchLines(drawBatchLines, pos, points, transform, fontContext);
  3513. }
  3514. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3515. void UiTextComponent::RenderDrawBatchLines(
  3516. const DrawBatchLines& drawBatchLines,
  3517. const AZ::Vector2& pos,
  3518. const UiTransformInterface::RectPoints& points,
  3519. const AZ::Matrix4x4& transformToViewport,
  3520. STextDrawContext& fontContext)
  3521. {
  3522. // For each newline-delimited string, we increment the draw call Y pos
  3523. // by the font size
  3524. float newlinePosYIncrement = 0.0f;
  3525. const ColorB origColor(fontContext.m_colorOverride);
  3526. for (const DrawBatchLine& drawBatchLine : drawBatchLines.batchLines)
  3527. {
  3528. float xDrawPosOffset = 0.0f;
  3529. AZ::Vector2 alignedPosition;
  3530. if (m_textHAlignment == IDraw2d::HAlign::Left && m_textVAlignment == IDraw2d::VAlign::Top)
  3531. {
  3532. alignedPosition = pos;
  3533. }
  3534. else
  3535. {
  3536. alignedPosition = Draw2dHelper::Align(pos, drawBatchLine.lineSize, m_textHAlignment, IDraw2d::VAlign::Top); // y is already aligned
  3537. }
  3538. alignedPosition.SetY(alignedPosition.GetY() + newlinePosYIncrement);
  3539. for (const DrawBatch& drawBatch : drawBatchLine.drawBatchList)
  3540. {
  3541. if (drawBatch.GetType() == UiTextComponent::DrawBatch::Type::Text)
  3542. {
  3543. if (ShouldClip())
  3544. {
  3545. alignedPosition.SetX(alignedPosition.GetX() - CalculateHorizontalClipOffset());
  3546. }
  3547. alignedPosition.SetX(alignedPosition.GetX() + xDrawPosOffset);
  3548. Vec2 textSize(drawBatch.size.GetX(), drawBatch.size.GetY());
  3549. xDrawPosOffset = textSize.x;
  3550. ColorB batchColor = origColor;
  3551. const bool drawBatchHasColorAssigned = drawBatch.color != TextMarkup::ColorInvalid;
  3552. if (drawBatchHasColorAssigned)
  3553. {
  3554. ColorF color = LyShine::MakeColorF(drawBatch.color, 1.0f); // need ColorF to do srgb conversion
  3555. color.srgb2rgb(); // the colors are specified in markup in sRGB but we want linear colors in the shader
  3556. batchColor = color;
  3557. }
  3558. fontContext.m_colorOverride = batchColor;
  3559. uint32 numQuads = drawBatch.font->GetNumQuadsForText(drawBatch.text.c_str(), true, fontContext);
  3560. if (numQuads > 0)
  3561. {
  3562. RenderCacheBatch* cacheBatch = new RenderCacheBatch;
  3563. cacheBatch->m_position = alignedPosition;
  3564. cacheBatch->m_position.SetY(cacheBatch->m_position.GetY() + drawBatch.yOffset);
  3565. cacheBatch->m_text = drawBatch.text;
  3566. cacheBatch->m_font = drawBatch.font;
  3567. cacheBatch->m_color = batchColor;
  3568. cacheBatch->m_cachedPrimitive.m_vertices = new LyShine::UiPrimitiveVertex[numQuads * 4];
  3569. cacheBatch->m_cachedPrimitive.m_indices = new uint16[numQuads * 6];
  3570. AZStd::vector<SVF_P2F_C4B_T2F_F4B> vertices(numQuads * 4);
  3571. uint32 numQuadsWritten = cacheBatch->m_font->WriteTextQuadsToBuffers(
  3572. vertices.data(), cacheBatch->m_cachedPrimitive.m_indices, numQuads,
  3573. cacheBatch->m_position.GetX(), cacheBatch->m_position.GetY(), 1.0f, cacheBatch->m_text.c_str(), true, fontContext);
  3574. AZ_Assert(numQuadsWritten <= numQuads, "value returned from WriteTextQuadsToBuffers is larger than size allocated");
  3575. if (numQuadsWritten == 0)
  3576. {
  3577. delete cacheBatch;
  3578. continue;
  3579. }
  3580. int numVertices = numQuadsWritten * 4;
  3581. FontVertexToUiVertex(vertices.data(), cacheBatch->m_cachedPrimitive.m_vertices, numVertices);
  3582. cacheBatch->m_cachedPrimitive.m_numVertices = numVertices;
  3583. cacheBatch->m_cachedPrimitive.m_numIndices = numQuadsWritten * 6;
  3584. cacheBatch->m_fontTextureVersion = drawBatch.font->GetFontTextureVersion();
  3585. m_renderCache.m_batches.push_back(cacheBatch);
  3586. }
  3587. }
  3588. else if (drawBatch.GetType() == UiTextComponent::DrawBatch::Type::Image)
  3589. {
  3590. alignedPosition.SetX(alignedPosition.GetX() + xDrawPosOffset);
  3591. xDrawPosOffset = drawBatch.size.GetX();
  3592. const AZ::Vector2 imageStartPos = AZ::Vector2(
  3593. alignedPosition.GetX() + drawBatch.image->m_leftPadding,
  3594. alignedPosition.GetY() + drawBatch.yOffset);
  3595. const AZ::Vector2 imageEndPos = AZ::Vector2(
  3596. imageStartPos.GetX() + drawBatch.image->m_size.GetX(),
  3597. imageStartPos.GetY() + drawBatch.image->m_size.GetY());
  3598. AZ::Vector3 imageQuad[4];
  3599. imageQuad[0] = AZ::Vector3(imageStartPos.GetX(), imageStartPos.GetY(), 1.0f);
  3600. imageQuad[1] = AZ::Vector3(imageEndPos.GetX(), imageQuad[0].GetY(), 1.0f);
  3601. imageQuad[2] = AZ::Vector3(imageQuad[1].GetX(), imageEndPos.GetY(), 1.0f);
  3602. imageQuad[3] = AZ::Vector3(imageQuad[0].GetX(), imageQuad[2].GetY(), 1.0f);
  3603. AZ::Vector2 uvs[4];
  3604. if (drawBatch.image->m_atlas)
  3605. {
  3606. uvs[0] = AZ::Vector2(static_cast<float>(drawBatch.image->m_coordinates.GetLeft()) / drawBatch.image->m_atlas->GetWidth(),
  3607. static_cast<float>(drawBatch.image->m_coordinates.GetTop()) / drawBatch.image->m_atlas->GetHeight());
  3608. uvs[2] = AZ::Vector2(static_cast<float>(drawBatch.image->m_coordinates.GetRight()) / drawBatch.image->m_atlas->GetWidth(),
  3609. static_cast<float>(drawBatch.image->m_coordinates.GetBottom()) / drawBatch.image->m_atlas->GetHeight());
  3610. uvs[1] = AZ::Vector2(uvs[2].GetX(), uvs[0].GetY());
  3611. uvs[3] = AZ::Vector2(uvs[0].GetX(), uvs[2].GetY());
  3612. }
  3613. else
  3614. {
  3615. uvs[0] = AZ::Vector2(0.0f, 0.0f);
  3616. uvs[1] = AZ::Vector2(1.0f, 0.0f);
  3617. uvs[2] = AZ::Vector2(1.0f, 1.0f);
  3618. uvs[3] = AZ::Vector2(0.0f, 1.0f);
  3619. }
  3620. if (ShouldClip())
  3621. {
  3622. ClipImageQuadAndUvs(imageQuad, uvs, points, drawBatch, imageStartPos, imageEndPos);
  3623. }
  3624. for (int i = 0; i < 4; ++i)
  3625. {
  3626. imageQuad[i] = transformToViewport * imageQuad[i];
  3627. }
  3628. static const uint32 packedColor = (255u << 24) | (255u << 16) | (255u << 8) | 255u;
  3629. RenderCacheImageBatch* cacheImageBatch = new RenderCacheImageBatch;
  3630. cacheImageBatch->m_texture = drawBatch.image->m_texture;
  3631. cacheImageBatch->m_cachedPrimitive.m_vertices = new LyShine::UiPrimitiveVertex[4];
  3632. for (int i = 0; i < 4; ++i)
  3633. {
  3634. cacheImageBatch->m_cachedPrimitive.m_vertices[i].xy = Vec2(imageQuad[i].GetX(), imageQuad[i].GetY());
  3635. cacheImageBatch->m_cachedPrimitive.m_vertices[i].color.dcolor = packedColor;
  3636. cacheImageBatch->m_cachedPrimitive.m_vertices[i].st = Vec2(uvs[i].GetX(), uvs[i].GetY());
  3637. cacheImageBatch->m_cachedPrimitive.m_vertices[i].texIndex = 0;
  3638. cacheImageBatch->m_cachedPrimitive.m_vertices[i].texHasColorChannel = 1;
  3639. cacheImageBatch->m_cachedPrimitive.m_vertices[i].texIndex2 = 0;
  3640. cacheImageBatch->m_cachedPrimitive.m_vertices[i].pad = 0;
  3641. }
  3642. cacheImageBatch->m_cachedPrimitive.m_numVertices = 4;
  3643. static uint16 indices[6] = { 0, 1, 2, 2, 3, 0 };
  3644. cacheImageBatch->m_cachedPrimitive.m_indices = indices;
  3645. cacheImageBatch->m_cachedPrimitive.m_numIndices = 6;
  3646. m_renderCache.m_imageBatches.push_back(cacheImageBatch);
  3647. }
  3648. else
  3649. {
  3650. AZ_Assert(false, "Unknown DrawBatch Type");
  3651. }
  3652. }
  3653. newlinePosYIncrement += drawBatchLine.lineSize.GetY() + m_lineSpacing;
  3654. }
  3655. }
  3656. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3657. void UiTextComponent::UpdateTextRenderBatchesForFontTextureChange()
  3658. {
  3659. STextDrawContext fontContext = m_renderCache.m_fontContext;
  3660. for (RenderCacheBatch* cacheBatch : m_renderCache.m_batches)
  3661. {
  3662. if (cacheBatch->m_fontTextureVersion != cacheBatch->m_font->GetFontTextureVersion())
  3663. {
  3664. uint32 numExistingQuads = cacheBatch->m_cachedPrimitive.m_numVertices / 4;
  3665. fontContext.m_colorOverride = cacheBatch->m_color;
  3666. uint32 numQuads = cacheBatch->m_font->GetNumQuadsForText(cacheBatch->m_text.c_str(), true, fontContext);
  3667. if (numExistingQuads < numQuads)
  3668. {
  3669. delete [] cacheBatch->m_cachedPrimitive.m_vertices;
  3670. delete [] cacheBatch->m_cachedPrimitive.m_indices;
  3671. cacheBatch->m_cachedPrimitive.m_vertices = new LyShine::UiPrimitiveVertex[numQuads * 4];
  3672. cacheBatch->m_cachedPrimitive.m_indices = new uint16[numQuads * 6];
  3673. }
  3674. AZStd::vector<SVF_P2F_C4B_T2F_F4B> vertices(numQuads * 4);
  3675. uint32 numQuadsWritten = cacheBatch->m_font->WriteTextQuadsToBuffers(
  3676. vertices.data(), cacheBatch->m_cachedPrimitive.m_indices, numQuads,
  3677. cacheBatch->m_position.GetX(), cacheBatch->m_position.GetY(), 1.0f, cacheBatch->m_text.c_str(), true, fontContext);
  3678. int numVertices = numQuadsWritten * 4;
  3679. FontVertexToUiVertex(vertices.data(), cacheBatch->m_cachedPrimitive.m_vertices, numVertices);
  3680. cacheBatch->m_cachedPrimitive.m_numVertices = numVertices;
  3681. cacheBatch->m_cachedPrimitive.m_numIndices = numQuadsWritten * 6;
  3682. cacheBatch->m_fontTextureVersion = cacheBatch->m_font->GetFontTextureVersion();
  3683. }
  3684. }
  3685. }
  3686. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3687. STextDrawContext UiTextComponent::GetTextDrawContextPrototype(int requestFontSize, const AZ::Vector2& fontSizeScale) const
  3688. {
  3689. STextDrawContext ctx;
  3690. ctx.SetEffect(m_overrideFontEffectIndex);
  3691. ctx.SetSizeIn800x600(false);
  3692. // Shrink-to-fit scaling (fontSizeScale) gets applied to font size, but not request size.
  3693. // This means that re-rendered fonts will not re-render characters that are scaled via
  3694. // shrink-to-fit - a scale transformation is applied for these characters instead. For
  3695. // higher quality font scaling with shrink-to-fit, consider taking m_fontSizeScale into
  3696. // account.
  3697. ctx.SetSize(Vec2(m_fontSize * fontSizeScale.GetX(), m_fontSize * fontSizeScale.GetY()));
  3698. ctx.m_requestSize = Vec2i(requestFontSize, requestFontSize);
  3699. ctx.m_processSpecialChars = false;
  3700. ctx.m_tracking = (m_charSpacing * ctx.m_size.x) / 1000.0f; // m_charSpacing units are 1/1000th of ems, 1 em is equal to font size.
  3701. // It's important that we base the character spacing based on the
  3702. // the scaled font size since this is the size the characters will be
  3703. // rendered at. Because spacing is relative to font size, basing the
  3704. // the spacing on the unscaled font size (m_fontSize) would produce
  3705. // visually inaccurate results, such as when shrink-to-fit is being
  3706. // used.
  3707. AZ::EntityId canvasId;
  3708. UiElementBus::EventResult(canvasId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  3709. UiCanvasBus::EventResult(ctx.m_pixelAligned, canvasId, &UiCanvasBus::Events::GetIsTextPixelAligned);
  3710. return ctx;
  3711. }
  3712. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3713. void UiTextComponent::OnTextWidthPropertyChanged()
  3714. {
  3715. if (m_wrapTextSetting == UiTextInterface::WrapTextSetting::NoWrap &&
  3716. m_overflowMode != OverflowMode::Ellipsis &&
  3717. m_shrinkToFit == ShrinkToFit::None &&
  3718. !m_areDrawBatchLinesDirty)
  3719. {
  3720. // Recompute the line sizes so that they are aligned properly (else the sizes will be aligned
  3721. // according to their original width)
  3722. // NOTE:: The AssignLineSizes call modifies the draw batch lines in place so we don't use GetDrawBatchLines here.
  3723. // We only get here if m_drawBatchLines is not dirty.
  3724. int requestFontSize = GetRequestFontSize();
  3725. STextDrawContext fontContext(GetTextDrawContextPrototype(requestFontSize, m_drawBatchLines.fontSizeScale));
  3726. AssignLineSizes(m_drawBatchLines, m_fontFamily.get(), fontContext, true);
  3727. MarkRenderCacheDirty();
  3728. }
  3729. else
  3730. {
  3731. // Recompute even the lines, because since we have new widths, we might have more lines due
  3732. // to word wrap
  3733. MarkDrawBatchLinesDirty(true);
  3734. }
  3735. }
  3736. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3737. void UiTextComponent::HandleOverflowText(UiTextComponent::DrawBatchLines& drawBatchLinesOut)
  3738. {
  3739. HandleShrinkToFit(drawBatchLinesOut);
  3740. HandleEllipsis(drawBatchLinesOut);
  3741. }
  3742. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3743. void UiTextComponent::HandleShrinkToFit(UiTextComponent::DrawBatchLines& drawBatchLinesOut, float availableHeight)
  3744. {
  3745. const bool useShrinkToFit = m_shrinkToFit != ShrinkToFit::None;
  3746. if (!useShrinkToFit)
  3747. {
  3748. return;
  3749. }
  3750. AZ::Vector2 textSize = GetTextSizeFromDrawBatchLines(drawBatchLinesOut);
  3751. AZ::Vector2 currentElementSize; // This needs to be computed with the unscaled size. This is because scaling happens after the text is laid out.
  3752. UiTransformBus::EventResult(currentElementSize, GetEntityId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  3753. if (availableHeight >= 0.0f)
  3754. {
  3755. currentElementSize.SetY(availableHeight);
  3756. }
  3757. const bool textOverflowsElementBounds = GetTextOverflowsBounds(textSize, currentElementSize);
  3758. const bool textOverflowsElementBoundsX = textSize.GetX() > currentElementSize.GetX();
  3759. const bool shrinkToFitNotNeeded = !textOverflowsElementBounds || (!textOverflowsElementBoundsX && m_shrinkToFit == ShrinkToFit::WidthOnly);
  3760. if (shrinkToFitNotNeeded)
  3761. {
  3762. return;
  3763. }
  3764. // Calculate the scaling we need to apply to the font size scale to get
  3765. // the text content to fit within the element. Note that this scale could
  3766. // be limited by m_minShrinkScale.
  3767. AZ::Vector2 scaleXy = AZ::Vector2(
  3768. currentElementSize.GetX() / textSize.GetX(),
  3769. currentElementSize.GetY() / textSize.GetY());
  3770. if (m_shrinkToFit == ShrinkToFit::Uniform)
  3771. {
  3772. const bool textOverflowsElementBoundsY = textSize.GetY() > currentElementSize.GetY();
  3773. const bool noWrap = m_wrapTextSetting == WrapTextSetting::NoWrap;
  3774. const bool notMultiLine = drawBatchLinesOut.batchLines.size() <= 1;
  3775. const bool wrappingNotNeeded = noWrap || notMultiLine;
  3776. if (wrappingNotNeeded)
  3777. {
  3778. HandleUniformShrinkToFitWithScale(drawBatchLinesOut, scaleXy);
  3779. }
  3780. // Some cases produce small (fractional) amounts of overflow along X axis even
  3781. // for word-wrapped cases. Here we check if shrink-to-fit is actually needed by
  3782. // verifying that the text contents overflows the Y-axis bounds of the element.
  3783. else if (textOverflowsElementBoundsY)
  3784. {
  3785. HandleShrinkToFitWithWrapping(drawBatchLinesOut, currentElementSize, textSize);
  3786. }
  3787. // Draw batches need to be re-populated with new font size scale applied
  3788. CalculateDrawBatchLines(drawBatchLinesOut);
  3789. }
  3790. else if (m_shrinkToFit == ShrinkToFit::WidthOnly)
  3791. {
  3792. if (m_wrapTextSetting == WrapTextSetting::NoWrap)
  3793. {
  3794. drawBatchLinesOut.fontSizeScale.SetX(AZ::GetMax<float>(m_minShrinkScale, scaleXy.GetX()));
  3795. // Draw batches need to be re-populated with new font size scale applied
  3796. CalculateDrawBatchLines(drawBatchLinesOut);
  3797. }
  3798. else
  3799. {
  3800. AZ_Assert(m_wrapTextSetting == WrapTextSetting::Wrap, "A new WrapTextSetting other than Wrap has been added. We need to account for that new setting here.");
  3801. HandleShrinkToFitWithWrapping(drawBatchLinesOut, currentElementSize, textSize);
  3802. }
  3803. }
  3804. }
  3805. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3806. void UiTextComponent::HandleUniformShrinkToFitWithScale(UiTextComponent::DrawBatchLines& drawBatchLinesOut, const AZ::Vector2& scaleVec)
  3807. {
  3808. float minScale = AZ::GetMin<float>(scaleVec.GetX(), scaleVec.GetY());
  3809. minScale = AZ::GetMax<float>(m_minShrinkScale, minScale);
  3810. drawBatchLinesOut.fontSizeScale = AZ::Vector2(minScale, minScale);
  3811. }
  3812. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3813. void UiTextComponent::HandleShrinkToFitWithWrapping(
  3814. UiTextComponent::DrawBatchLines& drawBatchLinesOut, const AZ::Vector2& currentElementSize, const AZ::Vector2& textSize)
  3815. {
  3816. if (m_shrinkToFit == ShrinkToFit::None)
  3817. {
  3818. return;
  3819. }
  3820. const float lineHeight = drawBatchLinesOut.batchLines.front().lineSize.GetY();
  3821. // Sizing sanity checks
  3822. {
  3823. // Sizes less than one pixel are considered invalid
  3824. const float minPixelSize = 1.0f;
  3825. const bool textAndLineHeightsInvalid = lineHeight < minPixelSize || textSize.GetX() < minPixelSize;
  3826. const bool elementSizeInvalid = currentElementSize.IsLessThan(AZ::Vector2::CreateOne());
  3827. const bool invalidSizing = textAndLineHeightsInvalid || elementSizeInvalid;
  3828. if (invalidSizing)
  3829. {
  3830. return;
  3831. }
  3832. }
  3833. int maxLinesElementCanHold = GetNumNonOverflowingLinesForElement(drawBatchLinesOut.batchLines, currentElementSize, m_lineSpacing);
  3834. if (maxLinesElementCanHold <= 0)
  3835. {
  3836. return;
  3837. }
  3838. if (m_shrinkToFit == ShrinkToFit::WidthOnly)
  3839. {
  3840. HandleWidthOnlyShrinkToFitWithWrapping(drawBatchLinesOut, currentElementSize, maxLinesElementCanHold);
  3841. }
  3842. else if (m_shrinkToFit == ShrinkToFit::Uniform)
  3843. {
  3844. HandleUniformShrinkToFitWithWrapping(drawBatchLinesOut, currentElementSize, maxLinesElementCanHold);
  3845. }
  3846. else
  3847. {
  3848. AZ_Assert(false, "Unexpected shrink-to-fit mode given.");
  3849. }
  3850. }
  3851. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3852. void UiTextComponent::HandleWidthOnlyShrinkToFitWithWrapping(
  3853. UiTextComponent::DrawBatchLines& drawBatchLinesOut,
  3854. const AZ::Vector2& currentElementSize,
  3855. int maxLinesElementCanHold)
  3856. {
  3857. bool textStillOverflows = true;
  3858. while (textStillOverflows)
  3859. {
  3860. // Consider the sizes of all overflowing lines when calculating the
  3861. // scale to reduce the number of times we need to iterate.
  3862. int numOverflowingLines = static_cast<int>(drawBatchLinesOut.batchLines.size() - maxLinesElementCanHold);
  3863. DrawBatchLineContainer::reverse_iterator riter;
  3864. int overflowLineCount = 0;
  3865. float overflowingLineSize = 0.0f;
  3866. for (riter = drawBatchLinesOut.batchLines.rbegin();
  3867. riter != drawBatchLinesOut.batchLines.rend() && overflowLineCount < numOverflowingLines;
  3868. ++riter, ++overflowLineCount)
  3869. {
  3870. DrawBatchLine& batchLine = *riter;
  3871. overflowingLineSize += batchLine.lineSize.GetX();
  3872. }
  3873. // If overflowing line size is empty (zero width), assume its an empty line and give
  3874. // it the width of the element.
  3875. const bool invalidLineSize = overflowingLineSize < 1.0f;
  3876. overflowingLineSize = invalidLineSize ? currentElementSize.GetX() : overflowingLineSize;
  3877. // Determine the total horizontal space the element can accommodate by adding up
  3878. // the width of the total number of lines the element can hold
  3879. const float nonOverflowingWidth = maxLinesElementCanHold * currentElementSize.GetX();
  3880. // Get the scale necessary to fit all of the text within the element
  3881. const float shrinkScale = nonOverflowingWidth / (nonOverflowingWidth + overflowingLineSize);
  3882. // Limit the shrink scale by the minimum shrink scale
  3883. const float newShrinkScale = AZ::GetMax<float>(drawBatchLinesOut.fontSizeScale.GetX() * shrinkScale, m_minShrinkScale);
  3884. drawBatchLinesOut.fontSizeScale.SetX(newShrinkScale);
  3885. // Rebuild the draw batches with the new font size scaling
  3886. CalculateDrawBatchLines(drawBatchLinesOut);
  3887. // Early out if minimum scale was reached or we're at a very small scale
  3888. const bool minScaleThresholdReached = drawBatchLinesOut.fontSizeScale.GetX() < 0.05f;
  3889. const bool useMinShrinkScale = m_minShrinkScale > 0.0f;
  3890. const bool minShrinkScaleReached = drawBatchLinesOut.fontSizeScale.GetX() <= m_minShrinkScale;
  3891. const bool exitDueToSmallScaleApplied = useMinShrinkScale ? minShrinkScaleReached : minScaleThresholdReached;
  3892. if (exitDueToSmallScaleApplied)
  3893. {
  3894. break;
  3895. }
  3896. maxLinesElementCanHold = GetNumNonOverflowingLinesForElement(drawBatchLinesOut.batchLines, currentElementSize, m_lineSpacing);
  3897. // Just because we applied a scale doesn't mean the text fits. This is due to word wrap.
  3898. // Even though we calculate the exact scale to accmmodate all the characters for the
  3899. // max number of lines the element can hold, word-wrap divides the characters unevenly
  3900. // across the total space required by the text, because overflowing words/characters are
  3901. // wrapped to the next line (and a character is "atomic" and can't be divided arbitrarily
  3902. // to accommodate space).
  3903. textStillOverflows = drawBatchLinesOut.batchLines.size() > maxLinesElementCanHold;
  3904. }
  3905. }
  3906. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3907. void UiTextComponent::HandleUniformShrinkToFitWithWrapping(
  3908. UiTextComponent::DrawBatchLines& drawBatchLinesOut,
  3909. const AZ::Vector2& currentElementSize,
  3910. int maxLinesElementCanHold)
  3911. {
  3912. // First, the font scale is reduced by a fractional multiplier until the text no longer overflows.
  3913. // Then, the font scale is incremented by a fixed amount until the largest font scale that
  3914. // does not overflow the text is found
  3915. // Font scale increment value for when the text no longer overflows
  3916. const float fontScaleIncrement = 0.05f;
  3917. float curFontScale = drawBatchLinesOut.fontSizeScale.GetX();
  3918. // This keeps track of the last known largest scale that fits the text
  3919. // to the element bounds with word wrap.
  3920. float bestScaleFoundSoFar = curFontScale;
  3921. // Calculate a default scale multiplier used to reduce the font scale by a percentage
  3922. // until the text no longer overflows.
  3923. // The default scale multiplier is the ratio of available height to the required height.
  3924. // It is made a multiple of fontScaleIncrement so that the final font scale is consistent
  3925. // with the element's height. Otherwise, the font scale could end up getting bigger when
  3926. // the element's size becomes smaller
  3927. const AZ::Vector2 curTextSize = GetTextSizeFromDrawBatchLines(drawBatchLinesOut);
  3928. const float overflowFactor = curTextSize.GetY() > 0.0f ? (currentElementSize.GetY() / curTextSize.GetY()) : 1.0f;
  3929. const float defaultScaleMultiplierUnclamped = floorf(overflowFactor / fontScaleIncrement) * fontScaleIncrement;
  3930. const float defaultScaleMultiplier = AZ::GetClamp<float>(defaultScaleMultiplierUnclamped, fontScaleIncrement, 1.0f - fontScaleIncrement);
  3931. // If min shrink scale applies, and it's bigger than the default scale multplier,
  3932. // we set the scale to be half the difference between 1.0f (no scale) and the
  3933. // min shrink scale (a "half step"). This gives a starting point that avoids
  3934. // applying a scale that is too small too soon (esp for text that "almost fits"
  3935. // the element bounds).
  3936. const float minShrinkScaleHalfStep = (1.0f - m_minShrinkScale) * 0.5f + m_minShrinkScale;
  3937. const bool useMinShrinkScale = m_minShrinkScale > 0.0f;
  3938. const float scaleMultiplierUnclamped = useMinShrinkScale ? minShrinkScaleHalfStep : defaultScaleMultiplier;
  3939. const float scaleMultiplier = AZStd::GetMax<float>(defaultScaleMultiplier, scaleMultiplierUnclamped);
  3940. // Text always starts out overflowing
  3941. bool textStillOverflows = true;
  3942. // When we've reached a font scale that fits the text within the element
  3943. // bounds, we enter an "adjust phase" where the scale gradually increases until
  3944. // the text overflows once more. As the scale increases, we keep track of the
  3945. // last scale to fit the text within bestScaleFoundSoFar.
  3946. bool scaleAdjustPhase = false;
  3947. while (textStillOverflows || scaleAdjustPhase)
  3948. {
  3949. if (textStillOverflows)
  3950. {
  3951. // Decrease current font scale value
  3952. curFontScale *= scaleMultiplier;
  3953. }
  3954. // Rebuild the draw batches with the new font size scaling
  3955. drawBatchLinesOut.fontSizeScale.Set(curFontScale, curFontScale);
  3956. CalculateDrawBatchLines(drawBatchLinesOut);
  3957. maxLinesElementCanHold = GetNumNonOverflowingLinesForElement(drawBatchLinesOut.batchLines, currentElementSize, m_lineSpacing);
  3958. // Just because we applied a scale doesn't mean the text fits. This is due to word wrap.
  3959. // Even though we calculate the exact scale to accmmodate all the characters for the
  3960. // max number of lines the element can hold, word-wrap divides the characters unevenly
  3961. // across the total space required by the text, because overflowing words/characters are
  3962. // wrapped to the next line (and a character is "atomic" and can't be divided arbitrarily
  3963. // to accommodate space).
  3964. textStillOverflows = drawBatchLinesOut.batchLines.size() > maxLinesElementCanHold;
  3965. if (textStillOverflows && !scaleAdjustPhase)
  3966. {
  3967. // Early out if minimum scale was reached or we're at a very small scale
  3968. const bool minScaleThresholdReached = curFontScale < fontScaleIncrement;
  3969. const bool minShrinkScaleReached = curFontScale <= m_minShrinkScale;
  3970. const bool exitDueToSmallScaleApplied = useMinShrinkScale ? minShrinkScaleReached : minScaleThresholdReached;
  3971. if (exitDueToSmallScaleApplied)
  3972. {
  3973. // Set final font scale
  3974. float minFontScale = useMinShrinkScale ? m_minShrinkScale : fontScaleIncrement;
  3975. drawBatchLinesOut.fontSizeScale.Set(minFontScale, minFontScale);
  3976. break;
  3977. }
  3978. }
  3979. // Text is no longer overflowing, begin scaling the text back up until we find
  3980. // a better fit.
  3981. if (!textStillOverflows)
  3982. {
  3983. bestScaleFoundSoFar = curFontScale;
  3984. // Increment current font scale value by a small fixed amount
  3985. curFontScale += fontScaleIncrement;
  3986. scaleAdjustPhase = true;
  3987. }
  3988. // Text is overflowing. If we're in the "adjust phase", assume that the last known
  3989. // scale that fits the text is the best fit and exit the loop.
  3990. else if (scaleAdjustPhase)
  3991. {
  3992. // Make sure final font scale is within min/max
  3993. float minFontScale = useMinShrinkScale ? m_minShrinkScale : fontScaleIncrement;
  3994. bestScaleFoundSoFar = AZ::GetClamp<float>(bestScaleFoundSoFar, minFontScale, 1.0f);
  3995. // Set final font scale
  3996. drawBatchLinesOut.fontSizeScale.Set(bestScaleFoundSoFar, bestScaleFoundSoFar);
  3997. break;
  3998. }
  3999. }
  4000. }
  4001. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4002. void UiTextComponent::HandleEllipsis(UiTextComponent::DrawBatchLines& drawBatchLinesOut, float availableHeight)
  4003. {
  4004. if (m_overflowMode != OverflowMode::Ellipsis)
  4005. {
  4006. return;
  4007. }
  4008. AZ::Vector2 textSize = GetTextSizeFromDrawBatchLines(drawBatchLinesOut);
  4009. AZ::Vector2 currentElementSize; // This needs to be computed with the unscaled size. This is because scaling happens after the text is laid out.
  4010. UiTransformBus::EventResult(currentElementSize, GetEntityId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  4011. if (availableHeight >= 0.0f)
  4012. {
  4013. currentElementSize.SetY(availableHeight);
  4014. }
  4015. const bool textOverflowsElementBounds = GetTextOverflowsBounds(textSize, currentElementSize);
  4016. const bool textOverflowsElementBoundsX = textSize.GetX() > currentElementSize.GetX();
  4017. const bool onlyOneLine = drawBatchLinesOut.batchLines.size() == 1;
  4018. const bool noEllipsisNeeded = !textOverflowsElementBoundsX && onlyOneLine;
  4019. // No need to handle ellipsis if the text doesn't overflow, OR if the text is ONLY
  4020. // overflowing vertically and there is only one line overflowing (in which case,
  4021. // the content will start to clip). If we don't check for this condition, the
  4022. // ellipsis text will unnecessarily be added to the end of the displayed text.
  4023. if (!textOverflowsElementBounds || noEllipsisNeeded)
  4024. {
  4025. return;
  4026. }
  4027. // Iterate through batch lines until the first overflowing line is found. The
  4028. // line that precedes the overflowing line is the line that will contain the
  4029. // ellipsis. Also gather lines that overflow the element bounds so they can
  4030. // be truncated.
  4031. DrawBatchLineContainer::iterator lineToEllipsis = drawBatchLinesOut.batchLines.begin();
  4032. DrawBatchLineIters linesToRemove;
  4033. GetLineToEllipsisAndLinesToTruncate(drawBatchLinesOut, &lineToEllipsis, linesToRemove, currentElementSize);
  4034. int requestFontSize = GetRequestFontSize();
  4035. STextDrawContext ctx(GetTextDrawContextPrototype(requestFontSize, drawBatchLinesOut.fontSizeScale));
  4036. DrawBatchLine* lineToEllipsisPtr = &(*lineToEllipsis);
  4037. while (lineToEllipsisPtr)
  4038. {
  4039. // We need to know the starting position of each draw batch on this line
  4040. // so that we can apply the ellipsis at the proper position in the text.
  4041. DrawBatchStartPositions startPositions;
  4042. GetDrawBatchStartPositions(startPositions, lineToEllipsisPtr, currentElementSize);
  4043. SetBatchLineFontPointers(lineToEllipsisPtr);
  4044. // Now that we have the line that we need to ellipse (esp in multi-line/word-wrap
  4045. // situations), we need to get the draw batch on the line whose contents need to
  4046. // be modified to include the ellipse.
  4047. const char* ellipseText = "...";
  4048. float drawBatchStartPos = 0.0f;
  4049. float ellipsisPos = 0.0f;
  4050. DrawBatch* drawBatchToEllipse = GetDrawBatchToEllipseAndPositions(ellipseText, ctx, currentElementSize, &startPositions, &drawBatchStartPos, &ellipsisPos);
  4051. TruncateDrawBatches(lineToEllipsisPtr, drawBatchToEllipse);
  4052. // Get the index of the draw batch text to insert the ellipsis text
  4053. int ellipsisCharPos = GetStartEllipseIndexInDrawBatch(drawBatchToEllipse, ctx, drawBatchStartPos, ellipsisPos);
  4054. InsertEllipsisText(ellipseText, ellipsisCharPos, drawBatchToEllipse);
  4055. // Treat the drawbatch as text so ellipsis text renders
  4056. drawBatchToEllipse->image = nullptr;
  4057. // Remove all content if the only content being displayed is ellipsis text
  4058. const bool batchContainsOnlyEllipsis = ellipseText == drawBatchToEllipse->text;
  4059. const bool noOtherBatches = 1 == lineToEllipsisPtr->drawBatchList.size();
  4060. const bool removeBatchContainingOnlyEllipsis = batchContainsOnlyEllipsis && noOtherBatches;
  4061. if (removeBatchContainingOnlyEllipsis)
  4062. {
  4063. linesToRemove.push_back(lineToEllipsis);
  4064. }
  4065. else
  4066. {
  4067. // Otherwise, we found a line that contains content in addition to ellipsis
  4068. break;
  4069. }
  4070. // Once we've reached the first line of text, we're done (since we're iterating backwards)
  4071. if (lineToEllipsis == drawBatchLinesOut.batchLines.begin())
  4072. {
  4073. break;
  4074. }
  4075. // Continue iterating towards the top of text until we find a line that
  4076. // can display the ellipsis
  4077. --lineToEllipsis;
  4078. lineToEllipsisPtr = &(*lineToEllipsis);
  4079. }
  4080. // For the case when we've removed every possible line, we'll just clip instead
  4081. // of truncate. Otherwise, we need to truncate lines follow ellipsis.
  4082. const bool linesFollowingEllipsisNeedTruncating = drawBatchLinesOut.batchLines.size() > linesToRemove.size();
  4083. if (linesFollowingEllipsisNeedTruncating)
  4084. {
  4085. // Truncate all lines following ellipsis
  4086. for (const auto& drawBatchLineIter : linesToRemove)
  4087. {
  4088. drawBatchLinesOut.batchLines.erase(drawBatchLineIter);
  4089. }
  4090. }
  4091. // Line sizes need to be updated to reflect ellipsis text insertion as well as batch
  4092. // lines being truncated (past the ellipsis line).
  4093. AssignLineSizes(drawBatchLinesOut, m_fontFamily.get(), ctx);
  4094. }
  4095. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4096. void UiTextComponent::GetLineToEllipsisAndLinesToTruncate(UiTextComponent::DrawBatchLines& drawBatchLinesOut,
  4097. DrawBatchLineContainer::iterator* lineToEllipsis, DrawBatchLineIters& linesToRemove, const AZ::Vector2& currentElementSize)
  4098. {
  4099. // Keep track of height of all text as we iterate through the batch lines
  4100. float totalTextHeight = 0.0f;
  4101. DrawBatchLineContainer::iterator prevBatchLine = *lineToEllipsis;
  4102. bool foundLineToEllipsis = false;
  4103. for (auto iter = drawBatchLinesOut.batchLines.begin(); iter != drawBatchLinesOut.batchLines.end(); ++iter)
  4104. {
  4105. DrawBatchLine& batchLine = *iter;
  4106. totalTextHeight += batchLine.lineSize.GetY();
  4107. const bool lineOverflowsVertically = totalTextHeight > currentElementSize.GetY();
  4108. const bool lineOverflowsHorizontally = batchLine.lineSize.GetX() > currentElementSize.GetX();
  4109. const bool lineDoesntOverflow = !lineOverflowsVertically && !lineOverflowsHorizontally;
  4110. if (foundLineToEllipsis)
  4111. {
  4112. // All other lines following the ellipsis are truncated.
  4113. linesToRemove.push_back(iter);
  4114. continue;
  4115. }
  4116. else if (lineDoesntOverflow)
  4117. {
  4118. prevBatchLine = iter;
  4119. continue;
  4120. }
  4121. // Prevent the first line of text from being removed, even if the text
  4122. // is overflowing. With ellipsis enabled, this content will be clipped.
  4123. const bool firstLine = iter == drawBatchLinesOut.batchLines.begin();
  4124. if (lineOverflowsVertically && !firstLine)
  4125. {
  4126. // The line we want to ellipse occurs prior to the
  4127. // first overflowing line.
  4128. *lineToEllipsis = prevBatchLine;
  4129. linesToRemove.push_back(iter);
  4130. }
  4131. else if (lineOverflowsHorizontally)
  4132. {
  4133. // The first line to overflow horizontally gets ellipsis
  4134. *lineToEllipsis = iter;
  4135. }
  4136. foundLineToEllipsis = true;
  4137. }
  4138. }
  4139. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4140. void UiTextComponent::GetDrawBatchStartPositions(DrawBatchStartPositions& startPositions, DrawBatchLine* lineToEllipsis, [[maybe_unused]] const AZ::Vector2& currentElementSize)
  4141. {
  4142. float currentLineSize = 0.0f;
  4143. for (DrawBatch& drawBatch : lineToEllipsis->drawBatchList)
  4144. {
  4145. DrawBatchStartPosPair startPosPair(&drawBatch, currentLineSize);
  4146. startPositions.emplace_back(startPosPair);
  4147. currentLineSize += drawBatch.size.GetX();
  4148. }
  4149. }
  4150. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4151. UiTextComponent::DrawBatch* UiTextComponent::GetDrawBatchToEllipseAndPositions(const char* ellipseText,
  4152. const STextDrawContext& ctx,
  4153. const AZ::Vector2& currentElementSize,
  4154. DrawBatchStartPositions* startPositions,
  4155. float* drawBatchStartPos,
  4156. float* ellipsisPos)
  4157. {
  4158. // Iterate backwards through draw batches on this line, until we find a draw batch
  4159. // that can contain the ellipsis text within the bounds of the element.
  4160. auto drawBatchToEllipseIter = startPositions->rbegin();
  4161. DrawBatch* drawBatchToEllipse = (*drawBatchToEllipseIter).first;
  4162. float ellipsisSize = 0.0f;
  4163. while (drawBatchToEllipse)
  4164. {
  4165. const bool prevBatchIsValid = AZStd::next(drawBatchToEllipseIter) != startPositions->rend();
  4166. const bool prevBatchIsImage = prevBatchIsValid && (*AZStd::next(drawBatchToEllipseIter)).first->image != nullptr;
  4167. const bool moreBatchesPriorToImage = prevBatchIsImage && startPositions->size() > 2;
  4168. const bool moreTextBatches = !prevBatchIsImage && startPositions->size() > 1;
  4169. const bool moreDrawBatchesAvailable = moreBatchesPriorToImage || moreTextBatches;
  4170. // The size of the ellipsis text can change based on the font being used in the draw batch
  4171. ellipsisSize = drawBatchToEllipse->font->GetTextSize(ellipseText, true, ctx).x;
  4172. // Calculate where the ellipsis must start in order to be contained within the
  4173. // element bounds. Also, guard against narrow elements that aren't wide enough
  4174. // to accommodate ellipsis.
  4175. *ellipsisPos = AZStd::GetMax<float>(0.0f, currentElementSize.GetX() - ellipsisSize);
  4176. *drawBatchStartPos = startPositions->back().second;
  4177. const bool drawBatchOccursAfterEllipsis = *ellipsisPos <= *drawBatchStartPos;
  4178. const bool getPrevDrawBatch = drawBatchOccursAfterEllipsis && moreDrawBatchesAvailable;
  4179. if (getPrevDrawBatch)
  4180. {
  4181. startPositions->pop_back();
  4182. drawBatchToEllipseIter = startPositions->rbegin();
  4183. drawBatchToEllipse = (*drawBatchToEllipseIter).first;
  4184. }
  4185. else
  4186. {
  4187. // Found a draw batch whose start position can contain the ellipsis
  4188. // within the bounds of the element.
  4189. break;
  4190. }
  4191. }
  4192. return drawBatchToEllipse;
  4193. }
  4194. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4195. void UiTextComponent::TruncateDrawBatches(UiTextComponent::DrawBatchLine* lineToTruncate, const UiTextComponent::DrawBatch* truncateAfterBatch)
  4196. {
  4197. bool truncateBatchFound = false;
  4198. lineToTruncate->drawBatchList.remove_if(
  4199. [&truncateBatchFound, truncateAfterBatch](const UiTextComponent::DrawBatch& drawBatch)
  4200. {
  4201. if (truncateBatchFound)
  4202. {
  4203. return true;
  4204. }
  4205. else
  4206. {
  4207. truncateBatchFound = &drawBatch == truncateAfterBatch;
  4208. return false;
  4209. }
  4210. });
  4211. }
  4212. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4213. int UiTextComponent::GetStartEllipseIndexInDrawBatch(const DrawBatch* drawBatchToEllipse,
  4214. const STextDrawContext& ctx,
  4215. const float drawBatchStartPos,
  4216. const float ellipsePos)
  4217. {
  4218. float overflowStringSize = 0.0f;
  4219. int ellipsisCharPos = 0;
  4220. Utf8::Unchecked::octet_iterator pChar(drawBatchToEllipse->text.data());
  4221. uint32_t stringBufferIndex = 0;
  4222. uint32_t prevCh = 0;
  4223. while (uint32_t ch = *pChar)
  4224. {
  4225. ++pChar;
  4226. size_t maxSize = 5;
  4227. char codepoint[5] = { 0 };
  4228. char* codepointPtr = codepoint;
  4229. Utf8::Unchecked::octet_iterator<AZStd::string::iterator>::to_utf8_sequence(ch, codepointPtr, maxSize);
  4230. overflowStringSize += drawBatchToEllipse->font->GetTextSize(codepoint, true, ctx).x;
  4231. if (prevCh && ctx.m_kerningEnabled)
  4232. {
  4233. overflowStringSize += drawBatchToEllipse->font->GetKerning(prevCh, ch, ctx).x;
  4234. }
  4235. if (prevCh)
  4236. {
  4237. overflowStringSize += ctx.m_tracking;
  4238. }
  4239. prevCh = ch;
  4240. const float overflowStartPos = drawBatchStartPos + overflowStringSize;
  4241. const bool ellipseCharPosFound = overflowStartPos > ellipsePos;
  4242. stringBufferIndex += LyShine::GetMultiByteCharSize(ch);
  4243. if (ellipseCharPosFound)
  4244. {
  4245. const bool insertEllipsisFollowingFirstChar = ellipsisCharPos == 0;
  4246. ellipsisCharPos = insertEllipsisFollowingFirstChar ? stringBufferIndex : ellipsisCharPos;
  4247. break;
  4248. }
  4249. ellipsisCharPos = stringBufferIndex;
  4250. }
  4251. return ellipsisCharPos;
  4252. }
  4253. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4254. void UiTextComponent::InsertEllipsisText(const char* ellipseText,
  4255. const int ellipsisCharPos,
  4256. DrawBatch* drawBatchToEllipse)
  4257. {
  4258. drawBatchToEllipse->text = drawBatchToEllipse->text.substr(0, ellipsisCharPos) + ellipseText;
  4259. }
  4260. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4261. void UiTextComponent::SetBatchLineFontPointers(DrawBatchLine* batchLine)
  4262. {
  4263. IFFont* ellipsisFont = m_font;
  4264. for (auto drawBatchIter = batchLine->drawBatchList.begin();
  4265. drawBatchIter != batchLine->drawBatchList.end();
  4266. drawBatchIter++)
  4267. {
  4268. DrawBatch* iterBatchPtr = &(*drawBatchIter);
  4269. // Assign the last valid font ptr to this batch (note that batches
  4270. // already containing valid font pointers will simply have that
  4271. // font re-assigned back to them).
  4272. ellipsisFont = iterBatchPtr->font ? iterBatchPtr->font : ellipsisFont;
  4273. iterBatchPtr->font = ellipsisFont;
  4274. }
  4275. }
  4276. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4277. bool UiTextComponent::GetTextOverflowsBounds(const AZ::Vector2& textSize, const AZ::Vector2& elementSize) const
  4278. {
  4279. const bool textOverflowsElementBoundsX = textSize.GetX() > elementSize.GetX();
  4280. const bool textOverflowsElementBoundsY = textSize.GetY() > elementSize.GetY();
  4281. return textOverflowsElementBoundsX || textOverflowsElementBoundsY;
  4282. }
  4283. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4284. AZ::Vector2 UiTextComponent::GetTextSizeFromDrawBatchLines(const UiTextComponent::DrawBatchLines& drawBatchLines) const
  4285. {
  4286. AZ::Vector2 size = AZ::Vector2(0.0f, 0.0f);
  4287. for (const DrawBatchLine& drawBatchLine : drawBatchLines.batchLines)
  4288. {
  4289. size.SetX(AZ::GetMax(drawBatchLine.lineSize.GetX(), size.GetX()));
  4290. size.SetY(size.GetY() + drawBatchLine.lineSize.GetY());
  4291. }
  4292. // Add the extra line spacing to the Y size
  4293. if (drawBatchLines.batchLines.size() > 0)
  4294. {
  4295. size.SetY(size.GetY() + (drawBatchLines.batchLines.size() - 1) * m_lineSpacing);
  4296. }
  4297. return size;
  4298. }
  4299. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4300. AZStd::string UiTextComponent::GetLocalizedText([[maybe_unused]] const AZStd::string& text)
  4301. {
  4302. AZStd::string locText;
  4303. LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::LocalizeString_ch, m_text.c_str(), locText, false);
  4304. return locText.c_str();
  4305. }
  4306. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4307. AZ::Vector2 UiTextComponent::CalculateAlignedPositionWithYOffset(const UiTransformInterface::RectPoints& points)
  4308. {
  4309. AZ::Vector2 pos = AZ::Vector2::CreateZero();
  4310. const DrawBatchLines& drawBatchLines = GetDrawBatchLines();
  4311. size_t numLinesOfText = drawBatchLines.batchLines.size();
  4312. switch (m_textHAlignment)
  4313. {
  4314. case IDraw2d::HAlign::Left:
  4315. pos.SetX(points.TopLeft().GetX());
  4316. break;
  4317. case IDraw2d::HAlign::Center:
  4318. {
  4319. float width = points.TopRight().GetX() - points.TopLeft().GetX();
  4320. pos.SetX(points.TopLeft().GetX() + width * 0.5f);
  4321. break;
  4322. }
  4323. case IDraw2d::HAlign::Right:
  4324. pos.SetX(points.TopRight().GetX());
  4325. break;
  4326. }
  4327. switch (m_textVAlignment)
  4328. {
  4329. case IDraw2d::VAlign::Top:
  4330. pos.SetY(points.TopLeft().GetY());
  4331. break;
  4332. case IDraw2d::VAlign::Center:
  4333. {
  4334. float height = points.BottomLeft().GetY() - points.TopLeft().GetY();
  4335. pos.SetY(points.TopLeft().GetY() + height * 0.5f);
  4336. break;
  4337. }
  4338. case IDraw2d::VAlign::Bottom:
  4339. pos.SetY(points.BottomLeft().GetY());
  4340. break;
  4341. }
  4342. // For bottom-aligned text, we need to offset the vertical draw position
  4343. // such that the text never displays below the max Y position
  4344. if (m_textVAlignment == IDraw2d::VAlign::Bottom)
  4345. {
  4346. pos.SetY(pos.GetY() - (drawBatchLines.height + m_lineSpacing * (numLinesOfText - 1)));
  4347. }
  4348. // Centered alignment is obtained by offsetting by half the height of the
  4349. // entire text
  4350. else if (m_textVAlignment == IDraw2d::VAlign::Center)
  4351. {
  4352. pos.SetY(pos.GetY() - ((drawBatchLines.height + m_lineSpacing * (numLinesOfText - 1)) * 0.5f));
  4353. }
  4354. return pos;
  4355. }
  4356. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4357. // PRIVATE STATIC MEMBER FUNCTIONS
  4358. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4359. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4360. bool UiTextComponent::VersionConverter(AZ::SerializeContext& context,
  4361. AZ::SerializeContext::DataElementNode& classElement)
  4362. {
  4363. // conversion from version 1: Need to convert Color to Color and Alpha
  4364. // conversion from version 1 or 2: Need to convert Text from CryString to AzString
  4365. AZ_Assert(classElement.GetVersion() > 2, "Unsupported UiTextComponent version: %d", classElement.GetVersion());
  4366. // Versions prior to v4: Change default font
  4367. if (classElement.GetVersion() <= 3)
  4368. {
  4369. if (!ConvertV3FontFileNameIfDefault(context, classElement))
  4370. {
  4371. return false;
  4372. }
  4373. }
  4374. // V4: remove deprecated "supports markup" flag
  4375. if (classElement.GetVersion() == 4)
  4376. {
  4377. if (!RemoveV4MarkupFlag(context, classElement))
  4378. {
  4379. return false;
  4380. }
  4381. }
  4382. // conversion from version 5 to current: Strip off any leading forward slashes from font path
  4383. if (classElement.GetVersion() <= 5)
  4384. {
  4385. if (!LyShine::RemoveLeadingForwardSlashesFromAssetPath(context, classElement, "FontFileName"))
  4386. {
  4387. return false;
  4388. }
  4389. }
  4390. // conversion from version 6 to current: Need to convert ColorF to AZ::Color
  4391. if (classElement.GetVersion() <= 6)
  4392. {
  4393. if (!LyShine::ConvertSubElementFromVector3ToAzColor(context, classElement, "Color"))
  4394. {
  4395. return false;
  4396. }
  4397. }
  4398. // conversion from version 7 to current: The m_isMarkupEnabled flag was added. It defaults to false for new components.
  4399. // But if old data is loaded it should default to true for backward compatibility
  4400. if (classElement.GetVersion() <= 7)
  4401. {
  4402. if (!AddV8EnableMarkupFlag(context, classElement))
  4403. {
  4404. return false;
  4405. }
  4406. }
  4407. // conversion from version 8 to current:
  4408. // - "shrink to fit" wrap text setting now becomes the "uniform" value of the new "shrink to fit" enum
  4409. // - legacy "ResizeToText" overflow mode (enum value 2) gets reset back to zero (overflow)
  4410. if (classElement.GetVersion() <= 8)
  4411. {
  4412. if (!ConvertV8ShrinkToFitSetting(context, classElement))
  4413. {
  4414. return false;
  4415. }
  4416. if (!ConvertV8LegacyOverflowModeSetting(context, classElement))
  4417. {
  4418. return false;
  4419. }
  4420. }
  4421. return true;
  4422. }
  4423. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4424. void UiTextComponent::GetOffsetsFromSelectionInternal(LineOffsets& top, LineOffsets& middle, LineOffsets& bottom, int selectionStart, int selectionEnd)
  4425. {
  4426. const int localLastIndex = AZStd::GetMax<int>(selectionStart, selectionEnd);
  4427. int requestFontSize = GetRequestFontSize();
  4428. const DrawBatchLines& drawBatchLines = GetDrawBatchLines();
  4429. if (!drawBatchLines.inlineImages.empty())
  4430. {
  4431. // CalculateOffsets below does not work for draw batch lines with images in them. Images can never be entered
  4432. // in a text input BUT they can be in the initial starting string entered in the UI Editor.
  4433. // For now we just do not support selection (avoids a crash in CalculateOffsets).
  4434. // Text input in general will not work correctly with any markup in the text and will disable markup as soon
  4435. // as the text string is modified.
  4436. return;
  4437. }
  4438. STextDrawContext fontContext(GetTextDrawContextPrototype(requestFontSize, drawBatchLines.fontSizeScale));
  4439. UiTextComponentOffsetsSelector offsetsSelector(
  4440. drawBatchLines,
  4441. fontContext,
  4442. m_fontSize,
  4443. AZStd::GetMin<int>(selectionStart, selectionEnd),
  4444. localLastIndex,
  4445. GetLineNumberFromCharIndex(drawBatchLines, localLastIndex),
  4446. m_cursorLineNumHint);
  4447. offsetsSelector.CalculateOffsets(top, middle, bottom);
  4448. }
  4449. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4450. int UiTextComponent::GetLineNumberFromCharIndex(const DrawBatchLines& drawBatchLines, const int soughtIndex) const
  4451. {
  4452. int lineCounter = 0;
  4453. int indexIter = 0;
  4454. // Iterate across the lines of text until soughtIndex is found,
  4455. // incrementing lineCounter along the way and ultimately returning its
  4456. // value when the index is found.
  4457. for (const DrawBatchLine& batchLine : drawBatchLines.batchLines)
  4458. {
  4459. lineCounter++;
  4460. for (const DrawBatch& drawBatch : batchLine.drawBatchList)
  4461. {
  4462. Utf8::Unchecked::octet_iterator pChar(drawBatch.text.data());
  4463. while (*pChar)
  4464. {
  4465. ++pChar;
  4466. if (indexIter == soughtIndex)
  4467. {
  4468. return lineCounter;
  4469. }
  4470. ++indexIter;
  4471. }
  4472. }
  4473. }
  4474. // Note that it's possible for sought index to be one past the end of
  4475. // the line string, in which case we count the soughtIndex as being on
  4476. // that line anyways.
  4477. return lineCounter;
  4478. }
  4479. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4480. void UiTextComponent::InvalidateLayout() const
  4481. {
  4482. // Invalidate the parent's layout
  4483. AZ::EntityId canvasEntityId;
  4484. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  4485. UiLayoutManagerBus::Event(
  4486. canvasEntityId, &UiLayoutManagerBus::Events::MarkToRecomputeLayoutsAffectedByLayoutCellChange, GetEntityId(), true);
  4487. // Invalidate the element's layout
  4488. UiLayoutManagerBus::Event(canvasEntityId, &UiLayoutManagerBus::Events::MarkToRecomputeLayout, GetEntityId());
  4489. }
  4490. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4491. void UiTextComponent::CheckLayoutFitterAndRefreshEditorTransformProperties() const
  4492. {
  4493. UiLayoutHelpers::CheckFitterAndRefreshEditorTransformProperties(GetEntityId());
  4494. }
  4495. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4496. void UiTextComponent::MarkRenderCacheDirty()
  4497. {
  4498. if (!m_renderCache.m_isDirty)
  4499. {
  4500. ClearRenderCache();
  4501. }
  4502. }
  4503. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4504. void UiTextComponent::MarkRenderGraphDirty()
  4505. {
  4506. // tell the canvas to invalidate the render graph
  4507. AZ::EntityId canvasEntityId;
  4508. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  4509. UiCanvasComponentImplementationBus::Event(canvasEntityId, &UiCanvasComponentImplementationBus::Events::MarkRenderGraphDirty);
  4510. }
  4511. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4512. void UiTextComponent::ClearRenderCache()
  4513. {
  4514. // at the moment, any change to the render cache requires the graph is cleared because a render node
  4515. // in the graph has a list of primitives, if a primitive is removed it breaks the graph.
  4516. MarkRenderGraphDirty();
  4517. // As mentioned above it is ONLY valid to clear this and delete the image batches when the render graph
  4518. // has been cleared. Otherwise the graph intrusive lists will have pointers to deleted structures.
  4519. FreeRenderCacheMemory();
  4520. m_renderCache.m_isDirty = true;
  4521. }
  4522. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4523. void UiTextComponent::FreeRenderCacheMemory()
  4524. {
  4525. for (RenderCacheImageBatch* imageBatch : m_renderCache.m_imageBatches)
  4526. {
  4527. delete [] imageBatch->m_cachedPrimitive.m_vertices;
  4528. delete imageBatch;
  4529. }
  4530. for (RenderCacheBatch* textBatch : m_renderCache.m_batches)
  4531. {
  4532. delete [] textBatch->m_cachedPrimitive.m_vertices;
  4533. delete [] textBatch->m_cachedPrimitive.m_indices;
  4534. delete textBatch;
  4535. }
  4536. m_renderCache.m_batches.clear();
  4537. m_renderCache.m_imageBatches.clear();
  4538. }
  4539. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4540. bool UiTextComponent::ShouldClip()
  4541. {
  4542. return m_overflowMode == OverflowMode::ClipText || m_overflowMode == OverflowMode::Ellipsis;
  4543. }
  4544. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4545. int UiTextComponent::GetRequestFontSize()
  4546. {
  4547. if (m_isRequestFontSizeDirty)
  4548. {
  4549. m_requestFontSize = CalcRequestFontSize(m_fontSize, GetEntityId());
  4550. m_isRequestFontSizeDirty = false;
  4551. }
  4552. return m_requestFontSize;
  4553. }
  4554. #include "Tests/internal/test_UiTextComponent.cpp"