3
0

UiCanvasComponent.cpp 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362
  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 "UiCanvasComponent.h"
  9. #include "UiElementComponent.h"
  10. #include "UiTransform2dComponent.h"
  11. #include "UiSerialize.h"
  12. #include "UiCanvasFileObject.h"
  13. #include "UiGameEntityContext.h"
  14. #include "UiNavigationHelpers.h"
  15. #include "UiRenderer.h"
  16. #include "LyShine.h"
  17. #include <Random.h>
  18. #include <CryFile.h>
  19. #include <LyShine/Bus/UiInteractableBus.h>
  20. #include <LyShine/Bus/UiInitializationBus.h>
  21. #include <LyShine/Bus/UiNavigationBus.h>
  22. #include <LyShine/Bus/UiTooltipDisplayBus.h>
  23. #include <LyShine/Bus/UiEntityContextBus.h>
  24. #include <LyShine/Bus/UiCanvasUpdateNotificationBus.h>
  25. #include <LyShine/UiSerializeHelpers.h>
  26. #include <LyShine/IDraw2d.h>
  27. #include <AzCore/Math/Crc.h>
  28. #include <AzCore/Memory/Memory.h>
  29. #include <AzCore/Component/ComponentApplicationBus.h>
  30. #include <AzCore/Component/EntityUtils.h>
  31. #include <AzCore/Serialization/SerializeContext.h>
  32. #include <AzCore/Serialization/EditContext.h>
  33. #include <AzCore/Serialization/Utils.h>
  34. #include <AzCore/Asset/AssetSerializer.h>
  35. #include <AzCore/RTTI/BehaviorContext.h>
  36. #include <AzCore/IO/SystemFile.h>
  37. #include <AzCore/std/time.h>
  38. #include <AzCore/std/string/conversions.h>
  39. #include <AzFramework/Input/Devices/Gamepad/InputDeviceGamepad.h>
  40. #include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
  41. #include <AzFramework/Input/Devices/VirtualKeyboard/InputDeviceVirtualKeyboard.h>
  42. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  43. #include <AzFramework/Input/Devices/Touch/InputDeviceTouch.h>
  44. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  45. #include <Atom/RPI.Public/Image/AttachmentImagePool.h>
  46. #include "Animation/UiAnimationSystem.h"
  47. #ifndef _RELEASE
  48. #include <LyShine/Bus/UiRenderBus.h>
  49. #include <LyShine/Bus/UiRenderControlBus.h>
  50. #include <LyShine/Bus/UiImageBus.h>
  51. #include <LyShine/Bus/UiTextBus.h>
  52. #include <LyShine/Bus/UiMaskBus.h>
  53. #include <LyShine/Bus/UiFaderBus.h>
  54. #endif
  55. #include "LyShinePassDataBus.h"
  56. ////////////////////////////////////////////////////////////////////////////////////////////////////
  57. //! UiCanvasNotificationBus Behavior context handler class
  58. class UiCanvasNotificationBusBehaviorHandler
  59. : public UiCanvasNotificationBus::Handler
  60. , public AZ::BehaviorEBusHandler
  61. {
  62. public:
  63. AZ_EBUS_BEHAVIOR_BINDER(UiCanvasNotificationBusBehaviorHandler, "{64014B4F-E12F-4839-99B0-426B5717DB44}", AZ::SystemAllocator,
  64. OnAction,
  65. OnActionMultitouch,
  66. OnEnableStateChanged);
  67. void OnAction(AZ::EntityId entityId, const LyShine::ActionName& actionName) override
  68. {
  69. Call(FN_OnAction, entityId, actionName);
  70. }
  71. void OnActionMultitouch(AZ::EntityId entityId, const LyShine::ActionName& actionName, const AZ::Vector2& position, int multitouchIndex) override
  72. {
  73. Call(FN_OnActionMultitouch, entityId, actionName, position, multitouchIndex);
  74. }
  75. void OnEnableStateChanged(AZ::EntityId canvasEntityId, bool enabled) override
  76. {
  77. Call(FN_OnEnableStateChanged, canvasEntityId, enabled);
  78. }
  79. };
  80. ////////////////////////////////////////////////////////////////////////////////////////////////////
  81. //! UiCanvasInputNotificationBus Behavior context handler class
  82. class UiCanvasInputNotificationBusBehaviorHandler
  83. : public UiCanvasInputNotificationBus::Handler
  84. , public AZ::BehaviorEBusHandler
  85. {
  86. public:
  87. AZ_EBUS_BEHAVIOR_BINDER(UiCanvasInputNotificationBusBehaviorHandler, "{76042EFA-0B61-4E7A-ACC8-296382D46881}", AZ::SystemAllocator,
  88. OnCanvasPrimaryPressed, OnCanvasPrimaryReleased, OnCanvasMultiTouchPressed, OnCanvasMultiTouchReleased, OnCanvasHoverStart, OnCanvasHoverEnd, OnCanvasEnterPressed, OnCanvasEnterReleased);
  89. void OnCanvasPrimaryPressed(AZ::EntityId entityId) override
  90. {
  91. Call(FN_OnCanvasPrimaryPressed, entityId);
  92. }
  93. void OnCanvasPrimaryReleased(AZ::EntityId entityId) override
  94. {
  95. Call(FN_OnCanvasPrimaryReleased, entityId);
  96. }
  97. void OnCanvasMultiTouchPressed(AZ::EntityId entityId, int multiTouchIndex) override
  98. {
  99. Call(FN_OnCanvasMultiTouchPressed, entityId, multiTouchIndex);
  100. }
  101. void OnCanvasMultiTouchReleased(AZ::EntityId entityId, int multiTouchIndex) override
  102. {
  103. Call(FN_OnCanvasMultiTouchReleased, entityId, multiTouchIndex);
  104. }
  105. void OnCanvasHoverStart(AZ::EntityId entityId) override
  106. {
  107. Call(FN_OnCanvasHoverStart, entityId);
  108. }
  109. void OnCanvasHoverEnd(AZ::EntityId entityId) override
  110. {
  111. Call(FN_OnCanvasHoverEnd, entityId);
  112. }
  113. void OnCanvasEnterPressed(AZ::EntityId entityId) override
  114. {
  115. Call(FN_OnCanvasEnterPressed, entityId);
  116. }
  117. void OnCanvasEnterReleased(AZ::EntityId entityId) override
  118. {
  119. Call(FN_OnCanvasEnterReleased, entityId);
  120. }
  121. };
  122. ////////////////////////////////////////////////////////////////////////////////////////////////////
  123. //! UiAnimationNotificationBus Behavior context handler class
  124. class UiAnimationNotificationBusBehaviorHandler
  125. : public UiAnimationNotificationBus::Handler
  126. , public AZ::BehaviorEBusHandler
  127. {
  128. public:
  129. AZ_EBUS_BEHAVIOR_BINDER(UiAnimationNotificationBusBehaviorHandler, "{35D19FE8-5F31-426E-877A-8EEF3A42F99F}", AZ::SystemAllocator,
  130. OnUiAnimationEvent, OnUiTrackEvent);
  131. void OnUiAnimationEvent(IUiAnimationListener::EUiAnimationEvent uiAnimationEvent, AZStd::string animSequenceName) override
  132. {
  133. Call(FN_OnUiAnimationEvent, uiAnimationEvent, animSequenceName);
  134. }
  135. void OnUiTrackEvent(AZStd::string eventName, AZStd::string valueName, AZStd::string animSequenceName) override
  136. {
  137. Call(FN_OnUiTrackEvent, eventName, valueName, animSequenceName);
  138. }
  139. };
  140. ////////////////////////////////////////////////////////////////////////////////////////////////////
  141. //! UiInitializationBus Behavior context handler class
  142. class UiInitializationBusBehaviorHandler
  143. : public UiInitializationBus::Handler
  144. , public AZ::BehaviorEBusHandler
  145. {
  146. public:
  147. AZ_EBUS_BEHAVIOR_BINDER(UiInitializationBusBehaviorHandler, "{2978A8A2-1A88-40C2-A299-ECA68AD1C519}", AZ::SystemAllocator,
  148. InGamePostActivate);
  149. void InGamePostActivate() override
  150. {
  151. Call(FN_InGamePostActivate);
  152. }
  153. };
  154. ////////////////////////////////////////////////////////////////////////////////////////////////////
  155. //! UiCanvasEnabledStateNotificationBus Behavior context handler class
  156. class UiCanvasEnabledStateNotificationBusBehaviorHandler
  157. : public UiCanvasEnabledStateNotificationBus::Handler
  158. , public AZ::BehaviorEBusHandler
  159. {
  160. public:
  161. AZ_EBUS_BEHAVIOR_BINDER(UiCanvasEnabledStateNotificationBusBehaviorHandler, "{CF010D8C-AC69-4F2A-BE87-03432E68A304}", AZ::SystemAllocator,
  162. OnCanvasEnabledStateChanged);
  163. void OnCanvasEnabledStateChanged(AZ::EntityId canvasEntityId, bool enabled) override
  164. {
  165. Call(FN_OnCanvasEnabledStateChanged, canvasEntityId, enabled);
  166. }
  167. };
  168. // Anonymous namespace
  169. ////////////////////////////////////////////////////////////////////////////////////////////////////
  170. namespace
  171. {
  172. LyShine::CanvasId s_lastCanvasId = 0;
  173. ////////////////////////////////////////////////////////////////////////////////////////////////
  174. // test if the given text file starts with the given text string
  175. bool TestFileStartString(const AZStd::string& pathname, const char* expectedStart)
  176. {
  177. // Open the file using CCryFile, this supports it being in the pak file or a standalone file
  178. CCryFile file;
  179. if (!file.Open(pathname.c_str(), "r"))
  180. {
  181. return false;
  182. }
  183. // get the size of the file and the length of the expected start string
  184. size_t fileSize = file.GetLength();
  185. size_t expectedStartLen = strlen(expectedStart);
  186. // if the file is smaller than the expected start string then it is not a valid file
  187. if (fileSize < expectedStartLen)
  188. {
  189. return false;
  190. }
  191. // read in the length of the expected start string
  192. char* buffer = new char[expectedStartLen];
  193. file.ReadRaw(buffer, expectedStartLen);
  194. // match is true if the string read from the file matches the expected start string
  195. bool match = strncmp(expectedStart, buffer, expectedStartLen) == 0;
  196. delete [] buffer;
  197. return match;
  198. }
  199. ////////////////////////////////////////////////////////////////////////////////////////////////
  200. // Check if the given file was saved using AZ serialization
  201. bool IsValidAzSerializedFile(const AZStd::string& pathname)
  202. {
  203. return TestFileStartString(pathname, "<ObjectStream");
  204. }
  205. template<class T, class MapType>
  206. void ReuseOrGenerateNewIdsAndFixRefs(T* object, MapType& newIdMap, AZ::SerializeContext* context)
  207. {
  208. AZ::EntityUtils::ReplaceEntityIds(
  209. object,
  210. [&newIdMap](const AZ::EntityId& originalId, bool /*isEntityId*/) -> AZ::EntityId
  211. {
  212. auto findIt = newIdMap.find(originalId);
  213. if (findIt == newIdMap.end())
  214. {
  215. AZ::EntityId newId = AZ::Entity::MakeId();
  216. newIdMap.insert(AZStd::make_pair(originalId, newId));
  217. return newId;
  218. }
  219. else
  220. {
  221. return findIt->second; // return the previously remapped id
  222. }
  223. }, context);
  224. AZ::EntityUtils::ReplaceEntityRefs(
  225. object,
  226. [&newIdMap](const AZ::EntityId& originalId, bool /*isEntityId*/) -> AZ::EntityId
  227. {
  228. auto findIt = newIdMap.find(originalId);
  229. if (findIt == newIdMap.end())
  230. {
  231. return originalId; // entityId is not being remapped
  232. }
  233. else
  234. {
  235. return findIt->second; // return the remapped id
  236. }
  237. }, context);
  238. }
  239. UiRenderer* GetUiRendererForGame()
  240. {
  241. if (AZ::Interface<ILyShine>::Get())
  242. {
  243. CLyShine* lyShine = static_cast<CLyShine*>(AZ::Interface<ILyShine>::Get());
  244. return lyShine->GetUiRenderer();
  245. }
  246. return nullptr;
  247. }
  248. UiRenderer* GetUiRendererForEditor()
  249. {
  250. if (AZ::Interface<ILyShine>::Get())
  251. {
  252. CLyShine* lyShine = static_cast<CLyShine*>(AZ::Interface<ILyShine>::Get());
  253. return lyShine->GetUiRendererForEditor();
  254. }
  255. return nullptr;
  256. }
  257. bool IsValidInteractable(const AZ::EntityId& entityId)
  258. {
  259. if (!entityId.IsValid())
  260. {
  261. return false;
  262. }
  263. // Check if element is enabled
  264. bool isEnabled = false;
  265. UiElementBus::EventResult(isEnabled, entityId, &UiElementBus::Events::IsEnabled);
  266. if (!isEnabled)
  267. {
  268. return false;
  269. }
  270. // Check if element is handling events and therefore also an interactable
  271. bool canHandleEvents = false;
  272. UiInteractableBus::EventResult(canHandleEvents, entityId, &UiInteractableBus::Events::IsHandlingEvents);
  273. return canHandleEvents;
  274. }
  275. bool IsAttachmentImageAssetCompatible(const AZ::Data::Asset<AZ::RPI::AttachmentImageAsset>& attachmentImageAsset)
  276. {
  277. // Check that the attachment image asset's bind flags are compatible
  278. // - Supports use as a color attachment on a scope
  279. // - Supports read access through a ShaderResourceGroup
  280. const AZ::RHI::ImageDescriptor& imageDescriptor = attachmentImageAsset->GetImageDescriptor();
  281. bool isCompatible = AZ::RHI::CheckBitsAll(imageDescriptor.m_bindFlags,
  282. AZ::RHI::ImageBindFlags::Color | AZ::RHI::ImageBindFlags::ShaderRead);
  283. if (!isCompatible)
  284. {
  285. AZ_Error("UI", false, "Attachment image asset: %s has invalid bindings for rendering a UI Canvas. Please "
  286. "ensure that its BindFlags property includes Color and ShaderRead.", attachmentImageAsset.GetHint().c_str());
  287. return false;
  288. }
  289. // Check that the attachment image asset's pixel format is compatible
  290. isCompatible = (imageDescriptor.m_format == AZ::RHI::Format::R8G8B8A8_UNORM)
  291. || (imageDescriptor.m_format == AZ::RHI::Format::R8G8B8A8_UNORM_SRGB);
  292. if (!isCompatible)
  293. {
  294. AZ_Error("UI", false, "Attachment image asset: %s has an invalid pixel format for rendering a "
  295. "UI Canvas. Please ensure that it contains a Format property with a valid value of "
  296. "19 (R8G8B8A8_UNORM) or 20 (R8G8B8A8_UNORM_SRGB).", attachmentImageAsset.GetHint().c_str());
  297. return false;
  298. }
  299. return true;
  300. }
  301. }
  302. ////////////////////////////////////////////////////////////////////////////////////////////////////
  303. // STATIC MEMBER DATA
  304. ////////////////////////////////////////////////////////////////////////////////////////////////////
  305. const AZ::Vector2 UiCanvasComponent::s_defaultCanvasSize(1280.0f, 720.0f);
  306. const AZ::Color UiCanvasComponent::s_defaultGuideColor(0.25f,1.0f,0.25f,1.0f);
  307. bool UiCanvasComponent::s_handleHoverInputEvents = true;
  308. bool UiCanvasComponent::s_allowClearingHoverInteractableOnHoverInput = true;
  309. ////////////////////////////////////////////////////////////////////////////////////////////////////
  310. // PUBLIC MEMBER FUNCTIONS
  311. ////////////////////////////////////////////////////////////////////////////////////////////////////
  312. ////////////////////////////////////////////////////////////////////////////////////////////////////
  313. UiCanvasComponent::UiCanvasComponent()
  314. : m_uniqueId(0)
  315. , m_rootElement()
  316. , m_lastElementId(0)
  317. , m_canvasToViewportMatrix(AZ::Matrix4x4::CreateIdentity())
  318. , m_viewportToCanvasMatrix(AZ::Matrix4x4::CreateIdentity())
  319. , m_activeInteractableShouldStayActive(false)
  320. , m_isActiveInteractablePressed(false)
  321. , m_lastMousePosition(-1.0f, -1.0f)
  322. , m_id(++s_lastCanvasId)
  323. , m_drawOrder(0)
  324. , m_canvasSize(UiCanvasComponent::s_defaultCanvasSize)
  325. , m_targetCanvasSize(m_canvasSize)
  326. , m_deviceScale(1.0f, 1.0f)
  327. , m_isLoadedInGame(false)
  328. , m_keepLoadedOnLevelUnload(false)
  329. , m_enabled(true)
  330. , m_renderToTexture(false)
  331. , m_isSnapEnabled(false)
  332. , m_snapDistance(10.0f)
  333. , m_snapRotationDegrees(10.0f)
  334. , m_guideColor(s_defaultGuideColor)
  335. , m_guidesAreLocked(false)
  336. , m_entityContext(nullptr)
  337. {
  338. m_navCommandStatus[UiNavigationHelpers::Command::Up] = {0, 0, true};
  339. m_navCommandStatus[UiNavigationHelpers::Command::Down] = {0, 0, true};
  340. m_navCommandStatus[UiNavigationHelpers::Command::Left] = {0, 0, true};
  341. m_navCommandStatus[UiNavigationHelpers::Command::Right] = {0, 0, true};
  342. }
  343. ////////////////////////////////////////////////////////////////////////////////////////////////////
  344. UiCanvasComponent::~UiCanvasComponent()
  345. {
  346. DestroyScheduledElements();
  347. m_uiAnimationSystem.RemoveAllSequences();
  348. // remove all entries from m_elementsNeedingTransformRecompute list, can't use clear since that doesn't set the
  349. // m_next pointers to null except in a debug build.
  350. while (!m_elementsNeedingTransformRecompute.empty())
  351. {
  352. UiElementComponent& elementComponent = m_elementsNeedingTransformRecompute.front();
  353. m_elementsNeedingTransformRecompute.pop_front();
  354. elementComponent.m_next = nullptr; // needed in order to be able to test if an element is in the list.
  355. }
  356. if (m_entityContext)
  357. {
  358. // deactivate all UI elements, this is so that we can detect improper deletion of UI elements by users
  359. // during game play
  360. DeactivateElements();
  361. // Destroy the entity context, this will delete all the UI elements
  362. m_entityContext->DestroyUiContext();
  363. }
  364. if (m_isLoadedInGame)
  365. {
  366. delete m_entityContext;
  367. }
  368. // Unload any active texture atlases
  369. UnloadAtlases();
  370. }
  371. ////////////////////////////////////////////////////////////////////////////////////////////////////
  372. const AZStd::string& UiCanvasComponent::GetPathname()
  373. {
  374. return m_pathname;
  375. }
  376. ////////////////////////////////////////////////////////////////////////////////////////////////////
  377. LyShine::CanvasId UiCanvasComponent::GetCanvasId()
  378. {
  379. return m_id;
  380. }
  381. ////////////////////////////////////////////////////////////////////////////////////////////////////
  382. AZ::u64 UiCanvasComponent::GetUniqueCanvasId()
  383. {
  384. return m_uniqueId;
  385. }
  386. ////////////////////////////////////////////////////////////////////////////////////////////////////
  387. int UiCanvasComponent::GetDrawOrder()
  388. {
  389. return m_drawOrder;
  390. }
  391. ////////////////////////////////////////////////////////////////////////////////////////////////////
  392. void UiCanvasComponent::SetDrawOrder(int drawOrder)
  393. {
  394. m_drawOrder = drawOrder;
  395. UiCanvasOrderNotificationBus::Broadcast(&UiCanvasOrderNotificationBus::Events::OnCanvasDrawOrderChanged, GetEntityId());
  396. }
  397. ////////////////////////////////////////////////////////////////////////////////////////////////////
  398. bool UiCanvasComponent::GetKeepLoadedOnLevelUnload()
  399. {
  400. return m_keepLoadedOnLevelUnload;
  401. }
  402. ////////////////////////////////////////////////////////////////////////////////////////////////////
  403. void UiCanvasComponent::SetKeepLoadedOnLevelUnload(bool keepLoaded)
  404. {
  405. m_keepLoadedOnLevelUnload = keepLoaded;
  406. }
  407. ////////////////////////////////////////////////////////////////////////////////////////////////////
  408. void UiCanvasComponent::RecomputeChangedLayouts()
  409. {
  410. SendRectChangeNotificationsAndRecomputeLayouts();
  411. }
  412. ////////////////////////////////////////////////////////////////////////////////////////////////////
  413. int UiCanvasComponent::GetNumChildElements()
  414. {
  415. int numChildElements = 0;
  416. UiElementBus::EventResult(numChildElements, m_rootElement, &UiElementBus::Events::GetNumChildElements);
  417. return numChildElements;
  418. }
  419. ////////////////////////////////////////////////////////////////////////////////////////////////////
  420. AZ::Entity* UiCanvasComponent::GetChildElement(int index)
  421. {
  422. AZ::Entity* child = nullptr;
  423. UiElementBus::EventResult(child, m_rootElement, &UiElementBus::Events::GetChildElement, index);
  424. return child;
  425. }
  426. ////////////////////////////////////////////////////////////////////////////////////////////////////
  427. AZ::EntityId UiCanvasComponent::GetChildElementEntityId(int index)
  428. {
  429. AZ::EntityId childEntityId;
  430. UiElementBus::EventResult(childEntityId, m_rootElement, &UiElementBus::Events::GetChildEntityId, index);
  431. return childEntityId;
  432. }
  433. ////////////////////////////////////////////////////////////////////////////////////////////////////
  434. LyShine::EntityArray UiCanvasComponent::GetChildElements()
  435. {
  436. LyShine::EntityArray childElements;
  437. UiElementBus::EventResult(childElements, m_rootElement, &UiElementBus::Events::GetChildElements);
  438. return childElements;
  439. }
  440. ////////////////////////////////////////////////////////////////////////////////////////////////////
  441. AZStd::vector<AZ::EntityId> UiCanvasComponent::GetChildElementEntityIds()
  442. {
  443. AZStd::vector<AZ::EntityId> childElementEntityIds;
  444. UiElementBus::EventResult(childElementEntityIds, m_rootElement, &UiElementBus::Events::GetChildEntityIds);
  445. return childElementEntityIds;
  446. }
  447. ////////////////////////////////////////////////////////////////////////////////////////////////////
  448. AZ::Entity* UiCanvasComponent::CreateChildElement(const LyShine::NameType& name)
  449. {
  450. AZ::Entity* child = nullptr;
  451. UiElementBus::EventResult(child, m_rootElement, &UiElementBus::Events::CreateChildElement, name);
  452. return child;
  453. }
  454. ////////////////////////////////////////////////////////////////////////////////////////////////////
  455. AZ::Entity* UiCanvasComponent::FindElementById(LyShine::ElementId id)
  456. {
  457. AZ::Entity* element = nullptr;
  458. UiElementBus::EventResult(element, m_rootElement, &UiElementBus::Events::FindDescendantById, id);
  459. return element;
  460. }
  461. ////////////////////////////////////////////////////////////////////////////////////////////////////
  462. AZ::Entity* UiCanvasComponent::FindElementByName(const LyShine::NameType& name)
  463. {
  464. AZ::Entity* entity = nullptr;
  465. UiElementBus::EventResult(entity, m_rootElement, &UiElementBus::Events::FindDescendantByName, name);
  466. return entity;
  467. }
  468. ////////////////////////////////////////////////////////////////////////////////////////////////////
  469. AZ::EntityId UiCanvasComponent::FindElementEntityIdByName(const LyShine::NameType& name)
  470. {
  471. AZ::EntityId entityId;
  472. UiElementBus::EventResult(entityId, m_rootElement, &UiElementBus::Events::FindDescendantEntityIdByName, name);
  473. return entityId;
  474. }
  475. ////////////////////////////////////////////////////////////////////////////////////////////////////
  476. void UiCanvasComponent::FindElementsByName(const LyShine::NameType& name, LyShine::EntityArray& result)
  477. {
  478. // find all elements with the given name
  479. UiElementBus::Event(
  480. m_rootElement,
  481. &UiElementBus::Events::FindDescendantElements,
  482. [&name](const AZ::Entity* entity)
  483. {
  484. return name == entity->GetName();
  485. },
  486. result);
  487. }
  488. ////////////////////////////////////////////////////////////////////////////////////////////////////
  489. AZ::Entity* UiCanvasComponent::FindElementByHierarchicalName(const LyShine::NameType& name)
  490. {
  491. // start at the root
  492. AZ::Entity* currentEntity = GetRootElement();
  493. bool found = false;
  494. std::size_t lastPos = 0;
  495. while (currentEntity)
  496. {
  497. std::size_t pos = name.find('/', lastPos);
  498. if (pos == lastPos)
  499. {
  500. // skip over any double '/' characters or '/' characters at the start
  501. lastPos++;
  502. }
  503. else if (pos == LyShine::NameType::npos)
  504. {
  505. // '/' not found, use whole remaining string
  506. AZ::Entity* entity = nullptr;
  507. UiElementBus::EventResult(entity, currentEntity->GetId(), &UiElementBus::Events::FindChildByName, name.substr(lastPos));
  508. currentEntity = entity;
  509. if (currentEntity)
  510. {
  511. found = true;
  512. }
  513. break;
  514. }
  515. else
  516. {
  517. // use the part of the string between lastPos and pos (between the '/' characters)
  518. AZ::Entity* entity = nullptr;
  519. UiElementBus::EventResult(
  520. entity, currentEntity->GetId(), &UiElementBus::Events::FindChildByName, name.substr(lastPos, pos - lastPos));
  521. currentEntity = entity;
  522. lastPos = pos + 1;
  523. }
  524. }
  525. return (found) ? currentEntity : nullptr;
  526. }
  527. ////////////////////////////////////////////////////////////////////////////////////////////////////
  528. void UiCanvasComponent::FindElements(AZStd::function<bool(const AZ::Entity*)> predicate, LyShine::EntityArray& result)
  529. {
  530. // find all matching elements
  531. UiElementBus::Event(m_rootElement, &UiElementBus::Events::FindDescendantElements, predicate, result);
  532. }
  533. ////////////////////////////////////////////////////////////////////////////////////////////////////
  534. AZ::Entity* UiCanvasComponent::PickElement(AZ::Vector2 point)
  535. {
  536. AZ::Entity* element = nullptr;
  537. UiElementBus::EventResult(element, m_rootElement, &UiElementBus::Events::FindFrontmostChildContainingPoint, point, m_isLoadedInGame);
  538. return element;
  539. }
  540. ////////////////////////////////////////////////////////////////////////////////////////////////////
  541. LyShine::EntityArray UiCanvasComponent::PickElements(const AZ::Vector2& bound0, const AZ::Vector2& bound1)
  542. {
  543. LyShine::EntityArray elements;
  544. UiElementBus::EventResult(
  545. elements, m_rootElement, &UiElementBus::Events::FindAllChildrenIntersectingRect, bound0, bound1, m_isLoadedInGame);
  546. return elements;
  547. }
  548. ////////////////////////////////////////////////////////////////////////////////////////////////////
  549. AZ::EntityId UiCanvasComponent::FindInteractableToHandleEvent(AZ::Vector2 point)
  550. {
  551. AZ::EntityId interactable;
  552. UiElementBus::EventResult(interactable, m_rootElement, &UiElementBus::Events::FindInteractableToHandleEvent, point);
  553. return interactable;
  554. }
  555. ////////////////////////////////////////////////////////////////////////////////////////////////////
  556. bool UiCanvasComponent::SaveToXml(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname)
  557. {
  558. PrepareAnimationSystemForCanvasSave();
  559. // We are saving to the dev assets (source) not the cache so we use the sourceAssetPathname to save
  560. // the file
  561. bool result = SaveCanvasToFile(sourceAssetPathname, AZ::ObjectStream::ST_XML);
  562. if (result)
  563. {
  564. // We store the asset ID so that we can tell if the same file is being loaded from the game
  565. m_pathname = assetIdPathname;
  566. }
  567. return result;
  568. }
  569. ////////////////////////////////////////////////////////////////////////////////////////////////////
  570. void UiCanvasComponent::FixupCreatedEntities(LyShine::EntityArray topLevelEntities, bool makeUniqueNamesAndIds, AZ::Entity* optionalInsertionPoint)
  571. {
  572. if (makeUniqueNamesAndIds)
  573. {
  574. AZ::EntityId parentEntityId;
  575. if (optionalInsertionPoint)
  576. {
  577. parentEntityId = optionalInsertionPoint->GetId();
  578. }
  579. LyShine::EntityArray namedChildren;
  580. for (auto entity : topLevelEntities)
  581. {
  582. AZStd::string uniqueName = GetUniqueChildName(parentEntityId, entity->GetName(), &namedChildren);
  583. entity->SetName(uniqueName);
  584. namedChildren.push_back(entity);
  585. }
  586. }
  587. AZ::Entity* parent = (optionalInsertionPoint) ? optionalInsertionPoint : GetRootElement();
  588. for (auto entity : topLevelEntities)
  589. {
  590. UiElementComponent* elementComponent = entity->FindComponent<UiElementComponent>();
  591. AZ_Assert(elementComponent, "No element component found on prefab entity");
  592. // recursively visit all the elements and set their canvas and parent pointers
  593. elementComponent->FixupPostLoad(entity, this, parent, makeUniqueNamesAndIds);
  594. }
  595. if (m_isLoadedInGame)
  596. {
  597. // Call InGamePostActivate on all the created entities
  598. for (auto entity : topLevelEntities)
  599. {
  600. InGamePostActivateBottomUp(entity);
  601. }
  602. }
  603. }
  604. ////////////////////////////////////////////////////////////////////////////////////////////////////
  605. void UiCanvasComponent::AddElement(AZ::Entity* element, AZ::Entity* parent, AZ::Entity* insertBefore)
  606. {
  607. if (!parent)
  608. {
  609. parent = GetRootElement();
  610. }
  611. // add this new entity as a child of the parent (insertionPoint or root)
  612. UiElementComponent* parentElementComponent = parent->FindComponent<UiElementComponent>();
  613. AZ_Assert(parentElementComponent, "No element component found on parent entity");
  614. parentElementComponent->AddChild(element, insertBefore);
  615. }
  616. ////////////////////////////////////////////////////////////////////////////////////////////////////
  617. void UiCanvasComponent::ReinitializeElements()
  618. {
  619. // This gets called when a canvas or a slice in the canvas is reloaded. So, for example,
  620. // a Push to Slice in the editor causes a reload of that slice. It is only used in the editor.
  621. AZ::Entity* rootElement = GetRootElement();
  622. UiElementComponent* elementComponent = rootElement->FindComponent<UiElementComponent>();
  623. AZ_Assert(elementComponent, "No element component found on root element entity");
  624. elementComponent->FixupPostLoad(rootElement, this, nullptr, false);
  625. // All or some elements in the UI canvas have been recreated when ReinitializeElements is called.
  626. // This likely requires recompute of the transforms (in particular UiTextComponent requires this
  627. // if text is being wrapped, due to its delayed initialization that relies on OnCanvasSpaceRectChanged
  628. // being called).
  629. UiTransformBus::Event(m_rootElement, &UiTransformBus::Events::SetRecomputeFlags, UiTransformInterface::Recompute::RectAndTransform);
  630. }
  631. ////////////////////////////////////////////////////////////////////////////////////////////////////
  632. AZStd::string UiCanvasComponent::SaveToXmlString()
  633. {
  634. PrepareAnimationSystemForCanvasSave();
  635. AZStd::string charBuffer;
  636. AZ::IO::ByteContainerStream<AZStd::string > charStream(&charBuffer);
  637. [[maybe_unused]] bool success = SaveCanvasToStream(charStream, AZ::ObjectStream::ST_XML);
  638. AZ_Assert(success, "Failed to serialize canvas entity to XML");
  639. return charBuffer;
  640. }
  641. ////////////////////////////////////////////////////////////////////////////////////////////////////
  642. AZStd::string UiCanvasComponent::GetUniqueChildName(AZ::EntityId parentEntityId, AZStd::string baseName, const LyShine::EntityArray* includeChildren)
  643. {
  644. // Get a list of children that the name needs to be unique to
  645. LyShine::EntityArray children;
  646. if (parentEntityId.IsValid())
  647. {
  648. UiElementBus::EventResult(children, parentEntityId, &UiElementBus::Events::GetChildElements);
  649. }
  650. else
  651. {
  652. children = GetChildElements();
  653. }
  654. if (includeChildren)
  655. {
  656. children.insert(children.end(),includeChildren->begin(),includeChildren->end());
  657. }
  658. // First, check if base name is unique
  659. if (IsElementNameUnique(baseName, children))
  660. {
  661. return baseName;
  662. }
  663. // Count trailing digits in base name
  664. int i;
  665. for (i = static_cast<int>(baseName.length() - 1); i >= 0; i--)
  666. {
  667. if (!isdigit(baseName[i]))
  668. {
  669. break;
  670. }
  671. }
  672. int startDigitIndex = i + 1;
  673. int numDigits = static_cast<int>(baseName.length() - startDigitIndex);
  674. int suffix = 1;
  675. if (numDigits > 0)
  676. {
  677. // Set starting suffix
  678. suffix = AZStd::stoi(baseName.substr(startDigitIndex, numDigits));
  679. // Trim the digits from the base name
  680. baseName.erase(startDigitIndex, numDigits);
  681. }
  682. // Keep incrementing suffix until a unique name is found
  683. // NOTE: This could cause a performance issue when large copies are being made in a large canvas
  684. AZStd::string proposedChildName;
  685. do
  686. {
  687. ++suffix;
  688. proposedChildName = baseName;
  689. AZStd::string suffixString = AZStd::string::format("%d", suffix);
  690. // Append leading zeros
  691. int numLeadingZeros = static_cast<int>((suffixString.length() < numDigits) ? numDigits - suffixString.length() : 0);
  692. for (int zeroes = 0; zeroes < numLeadingZeros; zeroes++)
  693. {
  694. proposedChildName.push_back('0');
  695. }
  696. // Append suffix
  697. proposedChildName.append(suffixString);
  698. } while (!IsElementNameUnique(proposedChildName, children));
  699. return proposedChildName;
  700. }
  701. ////////////////////////////////////////////////////////////////////////////////////////////////////
  702. AZ::Entity* UiCanvasComponent::CloneElement(AZ::Entity* sourceEntity, AZ::Entity* parentEntity)
  703. {
  704. return CloneAndAddElementInternal(sourceEntity, parentEntity, nullptr);
  705. }
  706. ////////////////////////////////////////////////////////////////////////////////////////////////////
  707. AZ::EntityId UiCanvasComponent::CloneElementEntityId(AZ::EntityId sourceEntityId, AZ::EntityId parentEntityId, AZ::EntityId insertBeforeId)
  708. {
  709. AZ::EntityId result;
  710. AZ::Entity* sourceEntity = nullptr;
  711. AZ::ComponentApplicationBus::BroadcastResult(sourceEntity, &AZ::ComponentApplicationBus::Events::FindEntity, sourceEntityId);
  712. if (!sourceEntity)
  713. {
  714. AZ_Warning("UI", false, "CloneElementEntityId: Cannot find entity to clone.");
  715. return result;
  716. }
  717. AZ::Entity* parentEntity = nullptr;
  718. if (parentEntityId.IsValid())
  719. {
  720. AZ::ComponentApplicationBus::BroadcastResult(parentEntity, &AZ::ComponentApplicationBus::Events::FindEntity, parentEntityId);
  721. if (!parentEntity)
  722. {
  723. AZ_Warning("UI", false, "CloneElementEntityId: Cannot find parent entity.");
  724. return result;
  725. }
  726. }
  727. else
  728. {
  729. parentEntity = GetRootElement();
  730. }
  731. AZ::Entity* insertBeforeEntity = nullptr;
  732. if (insertBeforeId.IsValid())
  733. {
  734. AZ::ComponentApplicationBus::BroadcastResult(insertBeforeEntity, &AZ::ComponentApplicationBus::Events::FindEntity, insertBeforeId);
  735. if (!insertBeforeEntity)
  736. {
  737. AZ_Warning("UI", false, "CloneElementEntityId: Cannot find insertBefore entity.");
  738. return result;
  739. }
  740. }
  741. AZ::Entity* clonedEntity = CloneAndAddElementInternal(sourceEntity, parentEntity, insertBeforeEntity);
  742. if (clonedEntity)
  743. {
  744. result = clonedEntity->GetId();
  745. }
  746. return result;
  747. }
  748. ////////////////////////////////////////////////////////////////////////////////////////////////////
  749. AZ::Entity* UiCanvasComponent::CloneCanvas(const AZ::Vector2& canvasSize)
  750. {
  751. UiGameEntityContext* entityContext = new UiGameEntityContext();
  752. UiCanvasComponent* canvasComponent = CloneAndInitializeCanvas(entityContext, m_pathname, &canvasSize);
  753. AZ::Entity* newCanvasEntity = nullptr;
  754. if (canvasComponent)
  755. {
  756. newCanvasEntity = canvasComponent->GetEntity();
  757. canvasComponent->m_isLoadedInGame = true;
  758. // The game entity context needs to know its corresponding canvas entity for instantiating dynamic slices
  759. entityContext->SetCanvasEntity(newCanvasEntity->GetId());
  760. }
  761. else
  762. {
  763. delete entityContext;
  764. }
  765. return newCanvasEntity;
  766. }
  767. ////////////////////////////////////////////////////////////////////////////////////////////////////
  768. void UiCanvasComponent::SetCanvasToViewportMatrix(const AZ::Matrix4x4& matrix)
  769. {
  770. if (!m_canvasToViewportMatrix.IsClose(matrix))
  771. {
  772. m_canvasToViewportMatrix = matrix;
  773. m_viewportToCanvasMatrix = m_canvasToViewportMatrix.GetInverseTransform();
  774. UiTransformBus::Event(
  775. GetRootElement()->GetId(), &UiTransformBus::Events::SetRecomputeFlags, UiTransformInterface::Recompute::ViewportTransformOnly);
  776. }
  777. }
  778. ////////////////////////////////////////////////////////////////////////////////////////////////////
  779. const AZ::Matrix4x4& UiCanvasComponent::GetCanvasToViewportMatrix()
  780. {
  781. return m_canvasToViewportMatrix;
  782. }
  783. ////////////////////////////////////////////////////////////////////////////////////////////////////
  784. void UiCanvasComponent::GetViewportToCanvasMatrix(AZ::Matrix4x4& matrix)
  785. {
  786. matrix = m_viewportToCanvasMatrix;
  787. }
  788. ////////////////////////////////////////////////////////////////////////////////////////////////////
  789. AZ::Vector2 UiCanvasComponent::GetCanvasSize()
  790. {
  791. return m_targetCanvasSize;
  792. }
  793. ////////////////////////////////////////////////////////////////////////////////////////////////////
  794. AZ::Vector2 UiCanvasComponent::GetAuthoredCanvasSize()
  795. {
  796. return m_canvasSize;
  797. }
  798. ////////////////////////////////////////////////////////////////////////////////////////////////////
  799. void UiCanvasComponent::SetCanvasSize(const AZ::Vector2& canvasSize)
  800. {
  801. m_canvasSize = canvasSize;
  802. }
  803. ////////////////////////////////////////////////////////////////////////////////////////////////////
  804. void UiCanvasComponent::SetTargetCanvasSize(bool isInGame, const AZ::Vector2& targetCanvasSize)
  805. {
  806. if (m_renderToTexture)
  807. {
  808. // When a canvas is set to render to texture the target canvas size is retrieved from the asset.
  809. // This is typically the same size as the authored canvas size
  810. AZ::Vector2 targetSize(m_canvasSize);
  811. if (m_attachmentImageAsset)
  812. {
  813. AZ::RHI::Size imageSize = m_attachmentImageAsset->GetImageDescriptor().m_size;
  814. targetSize = AZ::Vector2(aznumeric_cast<float>(imageSize.m_width), aznumeric_cast<float>(imageSize.m_height));
  815. }
  816. SetTargetCanvasSizeAndUniformScale(isInGame, targetSize);
  817. }
  818. else
  819. {
  820. SetTargetCanvasSizeAndUniformScale(isInGame, targetCanvasSize);
  821. }
  822. }
  823. ////////////////////////////////////////////////////////////////////////////////////////////////////
  824. AZ::Vector2 UiCanvasComponent::GetDeviceScale()
  825. {
  826. return m_deviceScale;
  827. }
  828. ////////////////////////////////////////////////////////////////////////////////////////////////////
  829. bool UiCanvasComponent::GetIsPixelAligned()
  830. {
  831. return m_isPixelAligned;
  832. }
  833. ////////////////////////////////////////////////////////////////////////////////////////////////////
  834. void UiCanvasComponent::SetIsPixelAligned(bool isPixelAligned)
  835. {
  836. m_isPixelAligned = isPixelAligned;
  837. UiCanvasPixelAlignmentNotificationBus::Event(
  838. GetEntityId(), &UiCanvasPixelAlignmentNotificationBus::Events::OnCanvasPixelAlignmentChange);
  839. }
  840. ////////////////////////////////////////////////////////////////////////////////////////////////////
  841. bool UiCanvasComponent::GetIsTextPixelAligned()
  842. {
  843. return m_isTextPixelAligned;
  844. }
  845. ////////////////////////////////////////////////////////////////////////////////////////////////////
  846. void UiCanvasComponent::SetIsTextPixelAligned(bool isTextPixelAligned)
  847. {
  848. m_isTextPixelAligned = isTextPixelAligned;
  849. UiCanvasPixelAlignmentNotificationBus::Event(
  850. GetEntityId(), &UiCanvasPixelAlignmentNotificationBus::Events::OnCanvasTextPixelAlignmentChange);
  851. }
  852. ////////////////////////////////////////////////////////////////////////////////////////////////////
  853. IUiAnimationSystem* UiCanvasComponent::GetAnimationSystem()
  854. {
  855. return &m_uiAnimationSystem;
  856. }
  857. ////////////////////////////////////////////////////////////////////////////////////////////////////
  858. bool UiCanvasComponent::GetEnabled()
  859. {
  860. return m_enabled;
  861. }
  862. ////////////////////////////////////////////////////////////////////////////////////////////////////
  863. void UiCanvasComponent::SetEnabled(bool enabled)
  864. {
  865. if (m_enabled != enabled)
  866. {
  867. m_enabled = enabled;
  868. MarkRenderGraphDirty();
  869. EBUS_EVENT(UiCanvasNotificationBus, OnEnableStateChanged, GetEntityId(), m_enabled);
  870. UiCanvasEnabledStateNotificationBus::Broadcast(
  871. &UiCanvasEnabledStateNotificationBus::Events::OnCanvasEnabledStateChanged, GetEntityId(), m_enabled);
  872. }
  873. }
  874. ////////////////////////////////////////////////////////////////////////////////////////////////////
  875. bool UiCanvasComponent::GetIsRenderToTexture()
  876. {
  877. return m_renderToTexture;
  878. }
  879. ////////////////////////////////////////////////////////////////////////////////////////////////////
  880. void UiCanvasComponent::SetIsRenderToTexture(bool isRenderToTexture)
  881. {
  882. m_renderToTexture = isRenderToTexture;
  883. }
  884. ////////////////////////////////////////////////////////////////////////////////////////////////////
  885. const AZ::Data::Asset<AZ::RPI::AttachmentImageAsset>& UiCanvasComponent::GetAttachmentImageAsset()
  886. {
  887. return m_attachmentImageAsset;
  888. }
  889. ////////////////////////////////////////////////////////////////////////////////////////////////////
  890. void UiCanvasComponent::SetAttachmentImageAsset(const AZ::Data::Asset<AZ::RPI::AttachmentImageAsset>& attachmentImageAsset)
  891. {
  892. if (m_attachmentImageAsset != attachmentImageAsset)
  893. {
  894. DestroyRenderTarget();
  895. m_attachmentImageAsset = attachmentImageAsset;
  896. MarkRenderGraphDirty();
  897. }
  898. }
  899. ////////////////////////////////////////////////////////////////////////////////////////////////////
  900. bool UiCanvasComponent::GetIsPositionalInputSupported()
  901. {
  902. return m_isPositionalInputSupported;
  903. }
  904. ////////////////////////////////////////////////////////////////////////////////////////////////////
  905. void UiCanvasComponent::SetIsPositionalInputSupported(bool isSupported)
  906. {
  907. m_isPositionalInputSupported = isSupported;
  908. }
  909. ////////////////////////////////////////////////////////////////////////////////////////////////////
  910. bool UiCanvasComponent::GetIsConsumingAllInputEvents()
  911. {
  912. return m_isConsumingAllInputEvents;
  913. }
  914. ////////////////////////////////////////////////////////////////////////////////////////////////////
  915. void UiCanvasComponent::SetIsConsumingAllInputEvents(bool isConsuming)
  916. {
  917. m_isConsumingAllInputEvents = isConsuming;
  918. }
  919. ////////////////////////////////////////////////////////////////////////////////////////////////////
  920. bool UiCanvasComponent::GetIsMultiTouchSupported()
  921. {
  922. return m_isMultiTouchSupported;
  923. }
  924. ////////////////////////////////////////////////////////////////////////////////////////////////////
  925. void UiCanvasComponent::SetIsMultiTouchSupported(bool isSupported)
  926. {
  927. m_isMultiTouchSupported = isSupported;
  928. }
  929. ////////////////////////////////////////////////////////////////////////////////////////////////////
  930. bool UiCanvasComponent::GetIsNavigationSupported()
  931. {
  932. return m_isNavigationSupported;
  933. }
  934. ////////////////////////////////////////////////////////////////////////////////////////////////////
  935. void UiCanvasComponent::SetIsNavigationSupported(bool isSupported)
  936. {
  937. m_isNavigationSupported = isSupported;
  938. SetFirstHoverInteractable();
  939. }
  940. ////////////////////////////////////////////////////////////////////////////////////////////////////
  941. float UiCanvasComponent::GetNavigationThreshold()
  942. {
  943. return m_navigationThreshold;
  944. }
  945. ////////////////////////////////////////////////////////////////////////////////////////////////////
  946. void UiCanvasComponent::SetNavigationThreshold(float navigationThreshold)
  947. {
  948. m_navigationThreshold = navigationThreshold;
  949. }
  950. ////////////////////////////////////////////////////////////////////////////////////////////////////
  951. AZ::u64 UiCanvasComponent::GetNavigationRepeatDelay()
  952. {
  953. return m_navigationRepeatDelay;
  954. }
  955. ////////////////////////////////////////////////////////////////////////////////////////////////////
  956. void UiCanvasComponent::SetNavigationRepeatDelay(AZ::u64 navigationRepeatDelay)
  957. {
  958. m_navigationRepeatDelay = navigationRepeatDelay;
  959. }
  960. ////////////////////////////////////////////////////////////////////////////////////////////////////
  961. AZ::u64 UiCanvasComponent::GetNavigationRepeatPeriod()
  962. {
  963. return m_navigationRepeatPeriod;
  964. }
  965. ////////////////////////////////////////////////////////////////////////////////////////////////////
  966. void UiCanvasComponent::SetNavigationRepeatPeriod(AZ::u64 navigationRepeatPeriod)
  967. {
  968. m_navigationRepeatPeriod = navigationRepeatPeriod;
  969. }
  970. ////////////////////////////////////////////////////////////////////////////////////////////////////
  971. AzFramework::LocalUserId UiCanvasComponent::GetLocalUserIdInputFilter()
  972. {
  973. return m_localUserIdInputFilter;
  974. }
  975. ////////////////////////////////////////////////////////////////////////////////////////////////////
  976. void UiCanvasComponent::SetLocalUserIdInputFilter(AzFramework::LocalUserId localUserId)
  977. {
  978. m_localUserIdInputFilter = localUserId;
  979. }
  980. ////////////////////////////////////////////////////////////////////////////////////////////////////
  981. bool UiCanvasComponent::HandleInputEvent(const AzFramework::InputChannel::Snapshot& inputSnapshot,
  982. const AZ::Vector2* viewportPos,
  983. AzFramework::ModifierKeyMask activeModifierKeys)
  984. {
  985. // Ignore input events if we're not enabled
  986. if (!m_enabled)
  987. {
  988. return false;
  989. }
  990. if (m_localUserIdInputFilter != AzFramework::LocalUserIdAny &&
  991. m_localUserIdInputFilter != inputSnapshot.m_localUserId)
  992. {
  993. // Ignore input events if they were not generated by the desired local user id
  994. return false;
  995. }
  996. if (inputSnapshot.m_channelId == AzFramework::InputDeviceMouse::Movement::X ||
  997. inputSnapshot.m_channelId == AzFramework::InputDeviceMouse::Movement::Y ||
  998. inputSnapshot.m_channelId == AzFramework::InputDeviceMouse::Movement::Z)
  999. {
  1000. // Ignore the individual mouse movement input channels.
  1001. // X, Y are handled through the SystemCursorPosition input channel.
  1002. // Z (scroll wheel) functionality is not currently supported on the canvas level
  1003. return m_isConsumingAllInputEvents;
  1004. }
  1005. if (AzFramework::InputDeviceKeyboard::IsKeyboardDevice(inputSnapshot.m_deviceId) ||
  1006. AzFramework::InputDeviceVirtualKeyboard::IsVirtualKeyboardDevice(inputSnapshot.m_deviceId) ||
  1007. AzFramework::InputDeviceGamepad::IsGamepadDevice(inputSnapshot.m_deviceId))
  1008. {
  1009. return HandleKeyInputEvent(inputSnapshot, activeModifierKeys) || m_isConsumingAllInputEvents;
  1010. }
  1011. else if (viewportPos)
  1012. {
  1013. if (!m_renderToTexture && m_isPositionalInputSupported)
  1014. {
  1015. if (HandleInputPositionalEvent(inputSnapshot, *viewportPos))
  1016. {
  1017. return true;
  1018. }
  1019. }
  1020. }
  1021. return !m_renderToTexture && m_isConsumingAllInputEvents;
  1022. }
  1023. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1024. bool UiCanvasComponent::HandleTextEvent(const AZStd::string& textUTF8)
  1025. {
  1026. // Ignore input events if we're not enabled
  1027. if (!m_enabled)
  1028. {
  1029. return false;
  1030. }
  1031. if (m_activeInteractable.IsValid())
  1032. {
  1033. UiInteractableBus::Event(m_activeInteractable, &UiInteractableBus::Events::HandleTextInput, textUTF8);
  1034. return true;
  1035. }
  1036. return false;
  1037. }
  1038. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1039. bool UiCanvasComponent::HandleInputPositionalEvent(const AzFramework::InputChannel::Snapshot& inputSnapshot,
  1040. AZ::Vector2 viewportPos)
  1041. {
  1042. if (AzFramework::InputDeviceMouse::IsMouseDevice(inputSnapshot.m_deviceId))
  1043. {
  1044. if (m_lastMousePosition != viewportPos)
  1045. {
  1046. // Check if the mouse position has been initialized
  1047. if (m_lastMousePosition.GetX() >= 0.0f && m_lastMousePosition.GetY() >= 0.0f)
  1048. {
  1049. // Mouse moved, resume handling hover input events if there is no active interactable
  1050. if (!m_activeInteractable.IsValid())
  1051. {
  1052. s_handleHoverInputEvents = true;
  1053. }
  1054. }
  1055. m_lastMousePosition = viewportPos;
  1056. }
  1057. }
  1058. //Well treat the first finger input as the 'mouse position'
  1059. if (inputSnapshot.m_channelId == AzFramework::InputDeviceTouch::Touch::Index0)
  1060. {
  1061. if (m_lastMousePosition != viewportPos)
  1062. {
  1063. m_lastMousePosition = viewportPos;
  1064. }
  1065. }
  1066. // Currently we are just interested in mouse events and the primary touch for hover events
  1067. if (AzFramework::InputDeviceMouse::IsMouseDevice(inputSnapshot.m_deviceId) ||
  1068. inputSnapshot.m_channelId == AzFramework::InputDeviceTouch::Touch::Index0)
  1069. {
  1070. if (s_handleHoverInputEvents)
  1071. {
  1072. HandleHoverInputEvent(viewportPos);
  1073. }
  1074. }
  1075. // Currently we are just interested in mouse button 1 events and UI events here
  1076. if (inputSnapshot.m_channelId == AzFramework::InputDeviceMouse::Button::Left ||
  1077. inputSnapshot.m_channelId == AzFramework::InputDeviceTouch::Touch::Index0)
  1078. {
  1079. if (inputSnapshot.m_state == AzFramework::InputChannel::State::Began)
  1080. {
  1081. return HandlePrimaryPress(viewportPos);
  1082. }
  1083. else if (inputSnapshot.m_state == AzFramework::InputChannel::State::Ended)
  1084. {
  1085. if (inputSnapshot.m_channelId == AzFramework::InputDeviceTouch::Touch::Index0)
  1086. {
  1087. ClearHoverInteractable();
  1088. }
  1089. return HandlePrimaryRelease(viewportPos);
  1090. }
  1091. else if (inputSnapshot.m_state == AzFramework::InputChannel::State::Updated)
  1092. {
  1093. return HandlePrimaryUpdate(viewportPos);
  1094. }
  1095. }
  1096. // ...while all other events from touch devices should be treated as multi-touch
  1097. else if (AzFramework::InputDeviceTouch::IsTouchDevice(inputSnapshot.m_deviceId))
  1098. {
  1099. const auto& touchIndexIt = AZStd::find(AzFramework::InputDeviceTouch::Touch::All.cbegin(),
  1100. AzFramework::InputDeviceTouch::Touch::All.cend(),
  1101. inputSnapshot.m_channelId);
  1102. if (touchIndexIt != AzFramework::InputDeviceTouch::Touch::All.cend())
  1103. {
  1104. const int touchindex = static_cast<int>(touchIndexIt - AzFramework::InputDeviceTouch::Touch::All.cbegin());
  1105. if (inputSnapshot.m_state == AzFramework::InputChannel::State::Began)
  1106. {
  1107. return HandleMultiTouchPress(viewportPos, touchindex);
  1108. }
  1109. else if (inputSnapshot.m_state == AzFramework::InputChannel::State::Ended)
  1110. {
  1111. return HandleMultiTouchRelease(viewportPos, touchindex);
  1112. }
  1113. else if (inputSnapshot.m_state == AzFramework::InputChannel::State::Updated)
  1114. {
  1115. return HandleMultiTouchUpdated(viewportPos, touchindex);
  1116. }
  1117. }
  1118. }
  1119. return false;
  1120. }
  1121. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1122. AZ::Vector2 UiCanvasComponent::GetMousePosition()
  1123. {
  1124. return m_lastMousePosition;
  1125. }
  1126. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1127. AZ::EntityId UiCanvasComponent::GetTooltipDisplayElement()
  1128. {
  1129. return m_tooltipDisplayElement;
  1130. }
  1131. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1132. void UiCanvasComponent::SetTooltipDisplayElement(AZ::EntityId entityId)
  1133. {
  1134. m_tooltipDisplayElement = entityId;
  1135. }
  1136. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1137. void UiCanvasComponent::ForceFocusInteractable(AZ::EntityId interactableId)
  1138. {
  1139. if (interactableId.IsValid())
  1140. {
  1141. AZ::EntityId lastHoverInteractable = m_hoverInteractable;
  1142. // Force the interactable to have the hover. Will also auto activate the
  1143. // interactable if the flag is set
  1144. ForceHoverInteractable(interactableId);
  1145. // Will also set as active interactable
  1146. CheckHoverInteractableAndAutoActivate(lastHoverInteractable, UiNavigationHelpers::Command::Unknown, true);
  1147. }
  1148. }
  1149. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1150. void UiCanvasComponent::ForceActiveInteractable(AZ::EntityId interactableId, bool shouldStayActive, AZ::Vector2 point)
  1151. {
  1152. SetHoverInteractable(interactableId);
  1153. SetActiveInteractable(interactableId, shouldStayActive);
  1154. m_lastMousePosition = point;
  1155. }
  1156. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1157. AZ::EntityId UiCanvasComponent::GetHoverInteractable()
  1158. {
  1159. return m_hoverInteractable;
  1160. }
  1161. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1162. void UiCanvasComponent::ForceHoverInteractable(AZ::EntityId newHoverInteractable)
  1163. {
  1164. if (!m_isNavigationSupported)
  1165. {
  1166. AZ_Warning("UI", false, "This UI canvas does not support keyboard/gamepad input events");
  1167. return;
  1168. }
  1169. if (newHoverInteractable.IsValid())
  1170. {
  1171. // Make sure the element is an interactable that is handling events
  1172. if (!IsValidInteractable(newHoverInteractable))
  1173. {
  1174. AZ_Warning("UI", false, "Entity is either not an interactable, not enabled or is not accepting events");
  1175. return;
  1176. }
  1177. // Make sure the active interactable and the hover interactible are the same
  1178. if (m_activeInteractable.IsValid() && (m_activeInteractable != newHoverInteractable))
  1179. {
  1180. ClearActiveInteractable();
  1181. }
  1182. }
  1183. SetHoverInteractable(newHoverInteractable);
  1184. if (m_hoverInteractable.IsValid())
  1185. {
  1186. s_handleHoverInputEvents = false;
  1187. s_allowClearingHoverInteractableOnHoverInput = false;
  1188. AZ::EntityId ancestorInteractable = FindAncestorInteractable(m_hoverInteractable);
  1189. if (ancestorInteractable.IsValid())
  1190. {
  1191. // Send an event that the descendant interactable became the hover interactable via navigation
  1192. UiInteractableBus::Event(
  1193. ancestorInteractable, &UiInteractableBus::Events::HandleDescendantReceivedHoverByNavigation, m_hoverInteractable);
  1194. }
  1195. CheckHoverInteractableAndAutoActivate();
  1196. }
  1197. }
  1198. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1199. void UiCanvasComponent::ClearAllInteractables()
  1200. {
  1201. m_multiTouchInteractablesByTouchIndex.clear();
  1202. ClearActiveInteractable();
  1203. // Clear hover interactable if last input was positional (mouse/touch)
  1204. if (s_handleHoverInputEvents)
  1205. {
  1206. ClearHoverInteractable();
  1207. }
  1208. }
  1209. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1210. void UiCanvasComponent::ForceEnterInputEventOnInteractable(AZ::EntityId interactableId)
  1211. {
  1212. if (!m_isNavigationSupported)
  1213. {
  1214. AZ_Warning("UI", false, "This UI canvas does not support keyboard/gamepad input events");
  1215. return;
  1216. }
  1217. if (!interactableId.IsValid())
  1218. {
  1219. AZ_Warning("UI", false, "EntityId is not valid");
  1220. return;
  1221. }
  1222. // Make sure the element is an interactable that is handling events
  1223. if (!IsValidInteractable(interactableId))
  1224. {
  1225. AZ_Warning("UI", false, "Entity is either not an interactable, not enabled or is not accepting events");
  1226. return;
  1227. }
  1228. // Set the hover interactable to accept the events
  1229. if (m_hoverInteractable != interactableId)
  1230. {
  1231. ForceHoverInteractable(interactableId);
  1232. }
  1233. // Generate Enter key pressed input event
  1234. AzFramework::InputChannel::Snapshot snapshot(AzFramework::InputDeviceKeyboard::Key::EditEnter,
  1235. AzFramework::InputDeviceKeyboard::Id,
  1236. AzFramework::InputChannel::State::Began);
  1237. HandleEnterInputEvent(UiNavigationHelpers::Command::Enter, snapshot);
  1238. // Generate Enter key released input event
  1239. snapshot.m_state = AzFramework::InputChannel::State::Ended;
  1240. HandleEnterInputEvent(UiNavigationHelpers::Command::Enter, snapshot);
  1241. }
  1242. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1243. void UiCanvasComponent::LoadAtlases()
  1244. {
  1245. if (m_atlases.size() > 0)
  1246. {
  1247. // Atlases already loaded
  1248. return;
  1249. }
  1250. for (int i = 0; i < m_atlasPathNames.size(); ++i)
  1251. {
  1252. const AZStd::string& atlasAssetPath = m_atlasPathNames[i].GetAssetPath();
  1253. if (!atlasAssetPath.empty()) // no need to print an error message for empty strings
  1254. {
  1255. TextureAtlasNamespace::TextureAtlas* atlas = nullptr;
  1256. TextureAtlasNamespace::TextureAtlasRequestBus::BroadcastResult(atlas, &TextureAtlasNamespace::TextureAtlasRequests::LoadAtlas, atlasAssetPath);
  1257. if (atlas != nullptr)
  1258. {
  1259. m_atlases.push_back(atlas);
  1260. }
  1261. else
  1262. {
  1263. AZ_Error("UI", false, "UI canvas: %s failed to load texture atlas: %s", m_pathname.c_str(), atlasAssetPath.c_str());
  1264. }
  1265. }
  1266. }
  1267. }
  1268. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1269. void UiCanvasComponent::UnloadAtlases()
  1270. {
  1271. while (m_atlases.size() > 0)
  1272. {
  1273. TextureAtlasNamespace::TextureAtlasRequestBus::Broadcast(&TextureAtlasNamespace::TextureAtlasRequests::UnloadAtlas, m_atlases.back());
  1274. m_atlases.pop_back();
  1275. }
  1276. }
  1277. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1278. void UiCanvasComponent::ReloadAtlases()
  1279. {
  1280. UnloadAtlases();
  1281. LoadAtlases();
  1282. }
  1283. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1284. void UiCanvasComponent::OnEntityDeactivated(const AZ::EntityId& entityId)
  1285. {
  1286. AZ::EntityBus::Handler::BusDisconnect(entityId);
  1287. if (entityId == m_hoverInteractable)
  1288. {
  1289. ClearHoverInteractable();
  1290. // If we are using keyboard/gamepad navigation we should set a new hover interactable
  1291. SetFirstHoverInteractable();
  1292. }
  1293. }
  1294. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1295. void UiCanvasComponent::StartSequence(const AZStd::string& sequenceName)
  1296. {
  1297. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1298. if (sequence)
  1299. {
  1300. m_uiAnimationSystem.AddUiAnimationListener(sequence, this);
  1301. m_uiAnimationSystem.PlaySequence(sequence, nullptr, false, false);
  1302. }
  1303. }
  1304. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1305. void UiCanvasComponent::PlaySequenceRange(const AZStd::string& sequenceName, float startTime, float endTime)
  1306. {
  1307. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1308. if (sequence)
  1309. {
  1310. m_uiAnimationSystem.AddUiAnimationListener(sequence, this);
  1311. m_uiAnimationSystem.PlaySequence(sequence, nullptr, false, false, startTime, endTime);
  1312. }
  1313. }
  1314. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1315. void UiCanvasComponent::StopSequence(const AZStd::string& sequenceName)
  1316. {
  1317. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1318. if (sequence)
  1319. {
  1320. m_uiAnimationSystem.StopSequence(sequence);
  1321. }
  1322. }
  1323. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1324. void UiCanvasComponent::AbortSequence(const AZStd::string& sequenceName)
  1325. {
  1326. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1327. if (sequence)
  1328. {
  1329. m_uiAnimationSystem.AbortSequence(sequence);
  1330. }
  1331. }
  1332. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1333. void UiCanvasComponent::PauseSequence(const AZStd::string& sequenceName)
  1334. {
  1335. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1336. if (sequence)
  1337. {
  1338. sequence->Pause();
  1339. }
  1340. }
  1341. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1342. void UiCanvasComponent::ResumeSequence(const AZStd::string& sequenceName)
  1343. {
  1344. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1345. if (sequence)
  1346. {
  1347. sequence->Resume();
  1348. }
  1349. }
  1350. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1351. void UiCanvasComponent::ResetSequence(const AZStd::string& sequenceName)
  1352. {
  1353. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1354. if (sequence)
  1355. {
  1356. sequence->Reset(true);
  1357. }
  1358. }
  1359. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1360. float UiCanvasComponent::GetSequencePlayingSpeed(const AZStd::string& sequenceName)
  1361. {
  1362. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1363. return m_uiAnimationSystem.GetPlayingSpeed(sequence);
  1364. }
  1365. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1366. void UiCanvasComponent::SetSequencePlayingSpeed(const AZStd::string& sequenceName, float speed)
  1367. {
  1368. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1369. m_uiAnimationSystem.SetPlayingSpeed(sequence, speed);
  1370. }
  1371. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1372. float UiCanvasComponent::GetSequencePlayingTime(const AZStd::string& sequenceName)
  1373. {
  1374. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1375. return m_uiAnimationSystem.GetPlayingTime(sequence);
  1376. }
  1377. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1378. bool UiCanvasComponent::IsSequencePlaying(const AZStd::string& sequenceName)
  1379. {
  1380. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1381. if (sequence)
  1382. {
  1383. return m_uiAnimationSystem.IsPlaying(sequence);
  1384. }
  1385. return false;
  1386. }
  1387. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1388. float UiCanvasComponent::GetSequenceLength(const AZStd::string& sequenceName)
  1389. {
  1390. float length = 0.f;
  1391. IUiAnimSequence* sequence = m_uiAnimationSystem.FindSequence(sequenceName.c_str());
  1392. if (sequence)
  1393. {
  1394. auto range = sequence->GetTimeRange();
  1395. length = range.Length();
  1396. }
  1397. return length;
  1398. }
  1399. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1400. void UiCanvasComponent::SetSequenceStopBehavior(IUiAnimationSystem::ESequenceStopBehavior stopBehavior)
  1401. {
  1402. m_uiAnimationSystem.SetSequenceStopBehavior(stopBehavior);
  1403. }
  1404. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1405. void UiCanvasComponent::ActiveCancelled()
  1406. {
  1407. // currently we are only connected to one UiInteractableActiveNotificationBus so we know it is the
  1408. // pressed interactable. If we could be connected to several we would need to change
  1409. // the ActiveCancelled method to pass the EntityId.
  1410. if (m_activeInteractable.IsValid())
  1411. {
  1412. UiInteractableActiveNotificationBus::Handler::BusDisconnect(m_activeInteractable);
  1413. m_activeInteractable.SetInvalid();
  1414. }
  1415. }
  1416. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1417. // change the active interactable to the given one
  1418. void UiCanvasComponent::ActiveChanged(AZ::EntityId m_newActiveInteractable, bool shouldStayActive)
  1419. {
  1420. // There should always be an active interactable at this point, disconnect from it
  1421. if (m_activeInteractable.IsValid())
  1422. {
  1423. UiInteractableActiveNotificationBus::Handler::BusDisconnect(m_activeInteractable);
  1424. m_activeInteractable.SetInvalid();
  1425. }
  1426. // The m_newActiveInteractable should always be valid but check anyway
  1427. if (m_newActiveInteractable.IsValid())
  1428. {
  1429. m_activeInteractable = m_newActiveInteractable;
  1430. UiInteractableActiveNotificationBus::Handler::BusConnect(m_activeInteractable);
  1431. m_activeInteractableShouldStayActive = shouldStayActive;
  1432. }
  1433. }
  1434. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1435. void UiCanvasComponent::OnUiAnimationEvent(EUiAnimationEvent uiAnimationEvent, IUiAnimSequence* pAnimSequence)
  1436. {
  1437. // Queue the event to prevent deletions during the canvas update
  1438. UiAnimationNotificationBus::QueueEvent(
  1439. GetEntityId(), &UiAnimationNotificationBus::Events::OnUiAnimationEvent, uiAnimationEvent, pAnimSequence->GetName());
  1440. // Stop listening to events
  1441. if ((uiAnimationEvent == EUiAnimationEvent::eUiAnimationEvent_Stopped) || (uiAnimationEvent == EUiAnimationEvent::eUiAnimationEvent_Aborted))
  1442. {
  1443. m_uiAnimationSystem.RemoveUiAnimationListener(pAnimSequence, this);
  1444. }
  1445. }
  1446. void UiCanvasComponent::OnUiTrackEvent(AZStd::string eventName, AZStd::string valueName, IUiAnimSequence* pAnimSequence)
  1447. {
  1448. // Queue the event to prevent deletions during the canvas update
  1449. UiAnimationNotificationBus::QueueEvent(
  1450. GetEntityId(), &UiAnimationNotificationBus::Events::OnUiTrackEvent, eventName, valueName, pAnimSequence->GetName());
  1451. }
  1452. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1453. bool UiCanvasComponent::GetIsSnapEnabled()
  1454. {
  1455. return m_isSnapEnabled;
  1456. }
  1457. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1458. void UiCanvasComponent::SetIsSnapEnabled(bool enabled)
  1459. {
  1460. m_isSnapEnabled = enabled;
  1461. }
  1462. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1463. float UiCanvasComponent::GetSnapDistance()
  1464. {
  1465. return m_snapDistance;
  1466. }
  1467. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1468. void UiCanvasComponent::SetSnapDistance(float distance)
  1469. {
  1470. m_snapDistance = distance;
  1471. }
  1472. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1473. float UiCanvasComponent::GetSnapRotationDegrees()
  1474. {
  1475. return m_snapRotationDegrees;
  1476. }
  1477. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1478. void UiCanvasComponent::SetSnapRotationDegrees(float degrees)
  1479. {
  1480. m_snapRotationDegrees = degrees;
  1481. }
  1482. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1483. AZStd::vector<float> UiCanvasComponent::GetHorizontalGuidePositions()
  1484. {
  1485. return m_horizontalGuidePositions;
  1486. }
  1487. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1488. void UiCanvasComponent::AddHorizontalGuide(float position)
  1489. {
  1490. m_horizontalGuidePositions.push_back(position);
  1491. }
  1492. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1493. void UiCanvasComponent::RemoveHorizontalGuide(int index)
  1494. {
  1495. if (index < m_horizontalGuidePositions.size())
  1496. {
  1497. m_horizontalGuidePositions.erase(m_horizontalGuidePositions.begin() + index);
  1498. }
  1499. else
  1500. {
  1501. AZ_Warning("UI", false, "Index out of range in RemoveHorizontalGuide");
  1502. }
  1503. }
  1504. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1505. void UiCanvasComponent::SetHorizontalGuidePosition(int index, float position)
  1506. {
  1507. if (index < m_horizontalGuidePositions.size())
  1508. {
  1509. m_horizontalGuidePositions[index] = position;
  1510. }
  1511. else
  1512. {
  1513. AZ_Warning("UI", false, "Index out of range in SetHorizontalGuidePosition");
  1514. }
  1515. }
  1516. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1517. AZStd::vector<float> UiCanvasComponent::GetVerticalGuidePositions()
  1518. {
  1519. return m_verticalGuidePositions;
  1520. }
  1521. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1522. void UiCanvasComponent::AddVerticalGuide(float position)
  1523. {
  1524. m_verticalGuidePositions.push_back(position);
  1525. }
  1526. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1527. void UiCanvasComponent::RemoveVerticalGuide(int index)
  1528. {
  1529. if (index < m_verticalGuidePositions.size())
  1530. {
  1531. m_verticalGuidePositions.erase(m_verticalGuidePositions.begin() + index);
  1532. }
  1533. else
  1534. {
  1535. AZ_Warning("UI", false, "Index out of range in RemoveVerticalGuide");
  1536. }
  1537. }
  1538. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1539. void UiCanvasComponent::SetVerticalGuidePosition(int index, float position)
  1540. {
  1541. if (index < m_verticalGuidePositions.size())
  1542. {
  1543. m_verticalGuidePositions[index] = position;
  1544. }
  1545. else
  1546. {
  1547. AZ_Warning("UI", false, "Index out of range in SetVerticalGuidePosition");
  1548. }
  1549. }
  1550. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1551. void UiCanvasComponent::RemoveAllGuides()
  1552. {
  1553. m_horizontalGuidePositions.clear();
  1554. m_verticalGuidePositions.clear();
  1555. }
  1556. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1557. AZ::Color UiCanvasComponent::GetGuideColor()
  1558. {
  1559. return m_guideColor;
  1560. }
  1561. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1562. void UiCanvasComponent::SetGuideColor(const AZ::Color& color)
  1563. {
  1564. m_guideColor = color;
  1565. }
  1566. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1567. bool UiCanvasComponent::GetGuidesAreLocked()
  1568. {
  1569. return m_guidesAreLocked;
  1570. }
  1571. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1572. void UiCanvasComponent::SetGuidesAreLocked(bool areLocked)
  1573. {
  1574. m_guidesAreLocked = areLocked;
  1575. }
  1576. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1577. bool UiCanvasComponent::CheckForOrphanedElements()
  1578. {
  1579. AZ::SliceComponent::EntityList orphanedEntities;
  1580. GetOrphanedElements(orphanedEntities);
  1581. return !orphanedEntities.empty();
  1582. }
  1583. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1584. void UiCanvasComponent::RecoverOrphanedElements()
  1585. {
  1586. AZ::SliceComponent::EntityList orphanedEntities;
  1587. GetOrphanedElements(orphanedEntities);
  1588. // we will put the orphaned elements under a top-level element called this:
  1589. const char* recoveredOrphansName = "RecoveredOrphans";
  1590. // If the recovered orphans element does not already at the top-level of the canvas exist then create it
  1591. AZ::Entity* recoveredOrphansElement = FindElementByHierarchicalName(recoveredOrphansName);
  1592. if (!recoveredOrphansElement)
  1593. {
  1594. recoveredOrphansElement = CreateChildElement(recoveredOrphansName);
  1595. recoveredOrphansElement->Deactivate();
  1596. recoveredOrphansElement->CreateComponent(LyShine::UiTransform2dComponentUuid);
  1597. recoveredOrphansElement->Activate();
  1598. }
  1599. // We have to find the top-level elements within the orphans and add them as children of recoveredOrphansElement.
  1600. // First we make a set of all the orphans that are referenced as children of other orphans.
  1601. AZStd::unordered_set<AZ::EntityId> referencedChildren;
  1602. for (AZ::Entity* orphan : orphanedEntities)
  1603. {
  1604. UiElementComponent* orphanElementComponent = orphan->FindComponent<UiElementComponent>();
  1605. int numChildren = orphanElementComponent->GetNumChildElements();
  1606. for (int i = 0; i < numChildren; ++i)
  1607. {
  1608. AZ::EntityId childId = orphanElementComponent->GetChildEntityId(i);
  1609. referencedChildren.insert(childId);
  1610. }
  1611. }
  1612. // Any orphans that are not in the set are top-level orphans and should be added.
  1613. UiElementComponent* recoveredOrphansElementComponent = recoveredOrphansElement->FindComponent<UiElementComponent>();
  1614. for (AZ::Entity* orphan : orphanedEntities)
  1615. {
  1616. if (referencedChildren.find(orphan->GetId()) == referencedChildren.end())
  1617. {
  1618. // First add the orphan as a child of the recoveredOrphansElement
  1619. recoveredOrphansElementComponent->AddChild(orphan);
  1620. // Then fixup all the parent, canvas, child pointers in the orphan and its children
  1621. UiElementComponent* orphanElementComponent = orphan->FindComponent<UiElementComponent>();
  1622. orphanElementComponent->FixupPostLoad(orphan, this, recoveredOrphansElement, false);
  1623. }
  1624. }
  1625. }
  1626. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1627. void UiCanvasComponent::RemoveOrphanedElements()
  1628. {
  1629. // get the orphaned entities
  1630. AZ::SliceComponent::EntityList orphanedEntities;
  1631. GetOrphanedElements(orphanedEntities);
  1632. // remove the entities from the entity context, this will remove any slice instances and references that become empty
  1633. for (AZ::Entity* orphan : orphanedEntities)
  1634. {
  1635. m_entityContext->DestroyEntity(orphan);
  1636. }
  1637. }
  1638. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1639. void UiCanvasComponent::UpdateCanvasInEditorViewport(float deltaTime, bool isInGame)
  1640. {
  1641. UpdateCanvas(deltaTime, isInGame);
  1642. }
  1643. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1644. void UiCanvasComponent::RenderCanvasInEditorViewport(bool isInGame, AZ::Vector2 viewportSize)
  1645. {
  1646. // When isInGame is true we're rendering the canvas in UI Editor's Preview Mode
  1647. UiRenderer* uiRenderer = GetUiRendererForEditor();
  1648. AZ_Assert(uiRenderer, "Trying to render a canvas in the UI Editor before its UIRenderer has been initialized");
  1649. uiRenderer->BeginUiFrameRender();
  1650. RenderCanvas(isInGame, viewportSize, uiRenderer);
  1651. uiRenderer->EndUiFrameRender();
  1652. }
  1653. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1654. void UiCanvasComponent::MarkRenderGraphDirty()
  1655. {
  1656. // It is possible that the loading screen can result in this being called while we are already
  1657. // rendering this canvas. We never want to set the dirty flag while rendering, if the dirty
  1658. // flag is not already set it could result in an incomplete renderGraph being created since
  1659. // the render graph will be cleared.
  1660. if (!m_isRendering)
  1661. {
  1662. m_renderGraph.SetDirtyFlag(true);
  1663. }
  1664. }
  1665. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1666. AZ::RHI::AttachmentId UiCanvasComponent::UseRenderTarget(const AZ::Name& renderTargetName, AZ::RHI::Size size)
  1667. {
  1668. // Create a render target that UI elements will render to
  1669. AZ::RPI::CreateAttachmentImageRequest createImageRequest;
  1670. AZ::RHI::ImageDescriptor& imageDesc = createImageRequest.m_imageDescriptor;
  1671. imageDesc.m_bindFlags = AZ::RHI::ImageBindFlags::Color | AZ::RHI::ImageBindFlags::ShaderReadWrite;
  1672. imageDesc.m_size = size;
  1673. imageDesc.m_format = AZ::RHI::Format::R8G8B8A8_UNORM;
  1674. createImageRequest.m_imagePool = AZ::RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool().get();
  1675. createImageRequest.m_imageName = renderTargetName;
  1676. createImageRequest.m_isUniqueName = false; // Can't use an unique name since the previous render target's release is delayed
  1677. auto attachmentImage = AZ::RPI::AttachmentImage::Create(createImageRequest);
  1678. if (!attachmentImage)
  1679. {
  1680. AZ_Warning("UI", false, "Failed to create render target");
  1681. return AZ::RHI::AttachmentId();
  1682. }
  1683. m_attachmentImageMap[attachmentImage->GetAttachmentId()] = attachmentImage;
  1684. // Notify LyShine render pass that it needs to rebuild
  1685. QueueRttPassRebuild();
  1686. return attachmentImage->GetAttachmentId();
  1687. }
  1688. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1689. AZ::RHI::AttachmentId UiCanvasComponent::UseRenderTargetAsset(const AZ::Data::Asset<AZ::RPI::AttachmentImageAsset>& attachmentImageAsset)
  1690. {
  1691. AZ::RHI::AttachmentId attachmentId = AZ::RHI::AttachmentId{};
  1692. if (!attachmentImageAsset.GetId().IsValid())
  1693. {
  1694. AZ_Error("UI", false, "UI Canvas (%s) using invalid attachment image! ", m_pathname.c_str());
  1695. return attachmentId;
  1696. }
  1697. // Check that the attachment image asset's properties are compatible for rendering a UI canvas
  1698. if (IsAttachmentImageAssetCompatible(attachmentImageAsset))
  1699. {
  1700. // Instantiate or get an existing image instance for the specified asset
  1701. if (auto attachmentImage = AZ::RPI::AttachmentImage::FindOrCreate(attachmentImageAsset))
  1702. {
  1703. attachmentId = attachmentImage->GetAttachmentId();
  1704. m_attachmentImageMap[attachmentId] = attachmentImage;
  1705. // Notify LyShine render pass that it needs to rebuild
  1706. QueueRttPassRebuild();
  1707. }
  1708. else
  1709. {
  1710. AZ_Error("UI", false, "Failed to find or create render target from asset: %s",
  1711. attachmentImageAsset.GetHint().c_str());
  1712. }
  1713. }
  1714. return attachmentId;
  1715. }
  1716. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1717. void UiCanvasComponent::ReleaseRenderTarget(const AZ::RHI::AttachmentId& attachmentId)
  1718. {
  1719. m_attachmentImageMap.erase(attachmentId);
  1720. // Notify LyShine render pass that it needs to rebuild
  1721. QueueRttPassRebuild();
  1722. }
  1723. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1724. AZ::Data::Instance<AZ::RPI::AttachmentImage> UiCanvasComponent::GetRenderTarget(const AZ::RHI::AttachmentId& attachmentId)
  1725. {
  1726. return m_attachmentImageMap[attachmentId];
  1727. }
  1728. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1729. void UiCanvasComponent::UpdateCanvas(float deltaTime, bool isInGame)
  1730. {
  1731. // Ignore update if we're not enabled
  1732. if (!m_enabled)
  1733. {
  1734. return;
  1735. }
  1736. if (isInGame)
  1737. {
  1738. UiCanvasUpdateNotificationBus::Event(GetEntityId(), &UiCanvasUpdateNotificationBus::Events::Update, deltaTime);
  1739. // update the animation system
  1740. m_uiAnimationSystem.PreUpdate(deltaTime);
  1741. m_uiAnimationSystem.PostUpdate(deltaTime);
  1742. }
  1743. else
  1744. {
  1745. UiCanvasUpdateNotificationBus::Event(GetEntityId(), &UiCanvasUpdateNotificationBus::Events::UpdateInEditor, deltaTime);
  1746. }
  1747. DestroyScheduledElements();
  1748. SendRectChangeNotificationsAndRecomputeLayouts();
  1749. }
  1750. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1751. void UiCanvasComponent::RenderCanvas(bool isInGame, AZ::Vector2 viewportSize, UiRenderer* uiRenderer)
  1752. {
  1753. // Ignore render ops if we're not enabled
  1754. if (!m_enabled)
  1755. {
  1756. return;
  1757. }
  1758. m_renderInEditor = uiRenderer ? true : false;
  1759. if (!uiRenderer)
  1760. {
  1761. uiRenderer = GetUiRendererForGame();
  1762. }
  1763. // It is possible, due to the LoadScreenComponent, for this canvas to have Render called while it is rendering.
  1764. // This is rare but can happen because rendering of text can call FontCreateTexture which results in CreateTextureObject
  1765. // being called, which has a load scren update in it. Rendering the canvas to the render graph while already in the
  1766. // process of doing so can corrupt the render graph by adding an element to an intrusive list that is already in the
  1767. // list.
  1768. // We could prevent this at the CLyShine::Render level. But doing it here with an m_isRendering flag also allows us to
  1769. // check for the error condition where MarkRenderGraphDirty (which clears the render graph) is called during rendering.
  1770. if (m_isRendering)
  1771. {
  1772. return;
  1773. }
  1774. m_isRendering = true;
  1775. if (m_renderGraph.GetDirtyFlag())
  1776. {
  1777. m_renderGraph.ResetGraph();
  1778. bool renderToTexture = !m_renderInEditor && GetIsRenderToTexture();
  1779. if (renderToTexture)
  1780. {
  1781. if (m_attachmentImageId.IsEmpty())
  1782. {
  1783. CreateRenderTarget();
  1784. }
  1785. // we always clear to transparent black - the accumulation of alpha in the render target requires it
  1786. AZ::Color clearColor = AZ::Color::CreateZero();
  1787. // Start building the render to texture node in the render graph
  1788. AZ::Vector2 viewportTopLeft = AZ::Vector2::CreateZero();
  1789. AZ::Data::Instance<AZ::RPI::AttachmentImage> attachmentImage;
  1790. LyShine::RenderToTextureRequestBus::EventResult(attachmentImage, GetEntityId(),
  1791. &LyShine::RenderToTextureRequestBus::Events::GetRenderTarget, m_attachmentImageId);
  1792. m_renderGraph.BeginRenderToTexture(attachmentImage, viewportTopLeft, viewportSize, clearColor);
  1793. }
  1794. else
  1795. {
  1796. if (!m_attachmentImageId.IsEmpty())
  1797. {
  1798. DestroyRenderTarget();
  1799. }
  1800. }
  1801. UiElementBus::Event(m_rootElement, &UiElementBus::Events::RenderElement, &m_renderGraph, isInGame);
  1802. if (renderToTexture)
  1803. {
  1804. // finish building the render to texture node in the render graph
  1805. m_renderGraph.EndRenderToTexture();
  1806. }
  1807. m_renderGraph.SetDirtyFlag(false);
  1808. m_renderGraph.FinalizeGraph();
  1809. }
  1810. if (!m_renderGraph.IsEmpty())
  1811. {
  1812. if (!m_attachmentImageMap.empty())
  1813. {
  1814. // Process any queued pass changes to get rtt draw list tags in sync prior to adding draw calls
  1815. AZ::RPI::PassSystemInterface* passSystem = AZ::RPI::PassSystemInterface::Get();
  1816. passSystem->ProcessQueuedChanges();
  1817. }
  1818. uiRenderer->BeginCanvasRender();
  1819. m_renderGraph.Render(uiRenderer, viewportSize);
  1820. uiRenderer->EndCanvasRender();
  1821. }
  1822. m_isRendering = false;
  1823. }
  1824. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1825. AZ::Entity* UiCanvasComponent::GetRootElement() const
  1826. {
  1827. AZ::Entity* rootEntity = nullptr;
  1828. AZ::ComponentApplicationBus::BroadcastResult(rootEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_rootElement);
  1829. return rootEntity;
  1830. }
  1831. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1832. LyShine::ElementId UiCanvasComponent::GenerateId()
  1833. {
  1834. return ++m_lastElementId;
  1835. }
  1836. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1837. AZ::Vector2 UiCanvasComponent::GetTargetCanvasSize()
  1838. {
  1839. return m_targetCanvasSize;
  1840. }
  1841. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1842. void UiCanvasComponent::ScheduleElementForTransformRecompute(UiElementComponent* elementComponent)
  1843. {
  1844. // Do not add if already in the list
  1845. if (!elementComponent->m_next)
  1846. {
  1847. m_elementsNeedingTransformRecompute.push_back(*elementComponent);
  1848. }
  1849. }
  1850. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1851. void UiCanvasComponent::UnscheduleElementForTransformRecompute(UiElementComponent* elementComponent)
  1852. {
  1853. // Do not erase if not in list
  1854. if (elementComponent->m_next)
  1855. {
  1856. m_elementsNeedingTransformRecompute.erase(ElementComponentSlist::const_iterator_impl(elementComponent));
  1857. elementComponent->m_next = nullptr;
  1858. }
  1859. }
  1860. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1861. void UiCanvasComponent::ScheduleElementDestroy(AZ::EntityId entityId)
  1862. {
  1863. m_elementsScheduledForDestroy.push_back(entityId);
  1864. }
  1865. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1866. void UiCanvasComponent::GetRenderTargets(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies)
  1867. {
  1868. m_renderGraph.GetRenderTargetsAndDependencies(attachmentImagesAndDependencies);
  1869. }
  1870. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1871. void UiCanvasComponent::DestroyScheduledElements()
  1872. {
  1873. for (auto entityId : m_elementsScheduledForDestroy)
  1874. {
  1875. UiElementComponent::DestroyElementEntity(entityId);
  1876. }
  1877. m_elementsScheduledForDestroy.clear();
  1878. }
  1879. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1880. void UiCanvasComponent::QueueRttPassRebuild()
  1881. {
  1882. UiRenderer* uiRenderer = m_renderInEditor ? GetUiRendererForEditor() : GetUiRendererForGame();
  1883. if (uiRenderer && uiRenderer->GetViewportContext()) // can be null in automated testing
  1884. {
  1885. if (const AZ::RPI::ScenePtr& scene = uiRenderer->GetViewportContext()->GetRenderScene())
  1886. {
  1887. AZ::RPI::SceneId sceneId = scene->GetId();
  1888. LyShinePassRequestBus::Event(sceneId, &LyShinePassRequestBus::Events::RebuildRttChildren);
  1889. }
  1890. }
  1891. }
  1892. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1893. #ifndef _RELEASE
  1894. void UiCanvasComponent::GetDebugInfoInteractables(AZ::EntityId& activeInteractable, AZ::EntityId& hoverInteractable) const
  1895. {
  1896. activeInteractable = m_activeInteractable;
  1897. hoverInteractable = m_hoverInteractable;
  1898. }
  1899. void UiCanvasComponent::GetDebugInfoNumElements(DebugInfoNumElements& info) const
  1900. {
  1901. info.m_numElements = 0;
  1902. info.m_numEnabledElements = 0;
  1903. info.m_numRenderElements = 0;
  1904. info.m_numRenderControlElements = 0;
  1905. info.m_numImageElements = 0;
  1906. info.m_numTextElements = 0;
  1907. info.m_numMaskElements = 0;
  1908. info.m_numFaderElements = 0;
  1909. info.m_numInteractableElements = 0;
  1910. info.m_numUpdateElements = static_cast<int>(UiCanvasUpdateNotificationBus::GetNumOfEventHandlers(GetEntityId()));
  1911. DebugInfoCountChildren(m_rootElement, true, info);
  1912. }
  1913. void UiCanvasComponent::GetDebugInfoRenderGraph(LyShineDebug::DebugInfoRenderGraph& info) const
  1914. {
  1915. m_renderGraph.GetDebugInfoRenderGraph(info);
  1916. }
  1917. void UiCanvasComponent::DebugInfoCountChildren(const AZ::EntityId entity, bool parentEnabled, DebugInfoNumElements& info) const
  1918. {
  1919. int numChildElements = 0;
  1920. UiElementBus::EventResult(numChildElements, entity, &UiElementBus::Events::GetNumChildElements);
  1921. info.m_numElements += numChildElements;
  1922. for (int i = 0; i < numChildElements; ++i)
  1923. {
  1924. AZ::EntityId child;
  1925. UiElementBus::EventResult(child, entity, &UiElementBus::Events::GetChildEntityId, i);
  1926. bool isEnabled = false;
  1927. UiElementBus::EventResult(isEnabled, child, &UiElementBus::Events::IsEnabled);
  1928. if (isEnabled && parentEnabled)
  1929. {
  1930. ++info.m_numEnabledElements;
  1931. if (UiRenderBus::FindFirstHandler(child))
  1932. {
  1933. ++info.m_numRenderElements;
  1934. }
  1935. if (UiRenderControlBus::FindFirstHandler(child))
  1936. {
  1937. ++info.m_numRenderControlElements;
  1938. }
  1939. if (UiImageBus::FindFirstHandler(child))
  1940. {
  1941. ++info.m_numImageElements;
  1942. }
  1943. if (UiTextBus::FindFirstHandler(child))
  1944. {
  1945. ++info.m_numTextElements;
  1946. }
  1947. if (UiMaskBus::FindFirstHandler(child))
  1948. {
  1949. ++info.m_numMaskElements;
  1950. }
  1951. if (UiFaderBus::FindFirstHandler(child))
  1952. {
  1953. ++info.m_numFaderElements;
  1954. }
  1955. if (UiInteractableBus::FindFirstHandler(child))
  1956. {
  1957. ++info.m_numInteractableElements;
  1958. }
  1959. }
  1960. DebugInfoCountChildren(child, isEnabled && parentEnabled, info);
  1961. }
  1962. }
  1963. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1964. void UiCanvasComponent::DebugReportDrawCalls(AZ::IO::HandleType fileHandle, LyShineDebug::DebugInfoDrawCallReport& reportInfo, void* context) const
  1965. {
  1966. m_renderGraph.DebugReportDrawCalls(fileHandle, reportInfo, context);
  1967. }
  1968. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1969. void UiCanvasComponent::DebugDisplayElemBounds(IDraw2d* draw2d) const
  1970. {
  1971. DebugDisplayChildElemBounds(draw2d, m_rootElement);
  1972. }
  1973. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1974. void UiCanvasComponent::DebugDisplayChildElemBounds(IDraw2d* draw2d, const AZ::EntityId entity) const
  1975. {
  1976. AZ::u64 time = AZStd::GetTimeUTCMilliSecond();
  1977. uint32 fractionsOfOneSecond = time % 1000;
  1978. uint32 fractionsOfHalfSecond = (fractionsOfOneSecond > 500) ? 1000 - fractionsOfOneSecond : fractionsOfOneSecond;
  1979. float brightness = fractionsOfHalfSecond / 500.0f;
  1980. UiTransformInterface::RectPoints points;
  1981. int numChildElements = 0;
  1982. UiElementBus::EventResult(numChildElements, entity, &UiElementBus::Events::GetNumChildElements);
  1983. for (int i = 0; i < numChildElements; ++i)
  1984. {
  1985. AZ::EntityId child;
  1986. UiElementBus::EventResult(child, entity, &UiElementBus::Events::GetChildEntityId, i);
  1987. bool isEnabled = false;
  1988. UiElementBus::EventResult(isEnabled, child, &UiElementBus::Events::IsEnabled);
  1989. if (isEnabled)
  1990. {
  1991. UiTransformBus::Event(entity, &UiTransformBus::Events::GetViewportSpacePoints, points);
  1992. AZ::Color color(brightness, brightness, brightness, 1.0f);
  1993. draw2d->DrawLine(points.TopLeft(), points.TopRight(), color);
  1994. draw2d->DrawLine(points.TopRight(), points.BottomRight(), color);
  1995. draw2d->DrawLine(points.BottomRight(), points.BottomLeft(), color);
  1996. draw2d->DrawLine(points.BottomLeft(), points.TopLeft(), color);
  1997. DebugDisplayChildElemBounds(draw2d, child);
  1998. }
  1999. }
  2000. }
  2001. #endif
  2002. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2003. // PUBLIC STATIC MEMBER FUNCTIONS
  2004. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2005. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2006. void UiCanvasComponent::Reflect(AZ::ReflectContext* context)
  2007. {
  2008. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  2009. if (serializeContext)
  2010. {
  2011. UiAnimationSystem::Reflect(serializeContext);
  2012. serializeContext->Class<UiCanvasComponent, AZ::Component>()
  2013. ->Version(4, &VersionConverter)
  2014. // Not in properties pane
  2015. ->Field("UniqueId", &UiCanvasComponent::m_uniqueId)
  2016. ->Field("RootElement", &UiCanvasComponent::m_rootElement)
  2017. ->Field("LastElement", &UiCanvasComponent::m_lastElementId)
  2018. ->Field("CanvasSize", &UiCanvasComponent::m_canvasSize)
  2019. ->Field("IsSnapEnabled", &UiCanvasComponent::m_isSnapEnabled)
  2020. // Rendering group
  2021. ->Field("DrawOrder", &UiCanvasComponent::m_drawOrder)
  2022. ->Field("IsPixelAligned", &UiCanvasComponent::m_isPixelAligned)
  2023. ->Field("IsTextPixelAligned", &UiCanvasComponent::m_isTextPixelAligned)
  2024. ->Field("RenderToTexture", &UiCanvasComponent::m_renderToTexture)
  2025. ->Field("AttachmentImageAsset", &UiCanvasComponent::m_attachmentImageAsset)
  2026. // Input group
  2027. ->Field("IsPosInputSupported", &UiCanvasComponent::m_isPositionalInputSupported)
  2028. ->Field("IsConsumingAllInput", &UiCanvasComponent::m_isConsumingAllInputEvents)
  2029. ->Field("IsMultiTouchSupported", &UiCanvasComponent::m_isMultiTouchSupported)
  2030. ->Field("IsNavigationSupported", &UiCanvasComponent::m_isNavigationSupported)
  2031. ->Field("NavigationThreshold", &UiCanvasComponent::m_navigationThreshold)
  2032. ->Field("NavigationRepeatDelay", &UiCanvasComponent::m_navigationRepeatDelay)
  2033. ->Field("NavigationRepeatPeriod", &UiCanvasComponent::m_navigationRepeatPeriod)
  2034. ->Field("FirstHoverElement", &UiCanvasComponent::m_firstHoverInteractable)
  2035. ->Field("AnimSystem", &UiCanvasComponent::m_uiAnimationSystem)
  2036. ->Field("AnimationData", &UiCanvasComponent::m_serializedAnimationData)
  2037. // Tooltips group
  2038. ->Field("TooltipDisplayElement", &UiCanvasComponent::m_tooltipDisplayElement)
  2039. // Editor settings
  2040. ->Field("SnapDistance", &UiCanvasComponent::m_snapDistance)
  2041. ->Field("SnapRotationDegrees", &UiCanvasComponent::m_snapRotationDegrees)
  2042. ->Field("HorizontalGuides", &UiCanvasComponent::m_horizontalGuidePositions)
  2043. ->Field("VerticalGuides", &UiCanvasComponent::m_verticalGuidePositions)
  2044. ->Field("GuideColor", &UiCanvasComponent::m_guideColor)
  2045. ->Field("GuidesLocked", &UiCanvasComponent::m_guidesAreLocked)
  2046. // Texture Atlases
  2047. ->Field("TextureAtlases", &UiCanvasComponent::m_atlasPathNames)
  2048. ;
  2049. // Old SimpleAssetReference<TextureAtlasAsset> TypeId = {6F612FE6-A054-4E49-830C-0288F3C79A52}
  2050. // Performs a sha1 calculation of the following typeids AzFramework::SimpleAssetReference<TextureAtlasAsset> + AZStd::allocator + AZStd::vector
  2051. AZ::TypeId deprecatedTypeId = AZ::TypeId("{6F612FE6-A054-4E49-830C-0288F3C79A52}") + AZ::AzTypeInfo<AZStd::allocator>::Uuid()
  2052. + AZ::TypeId("{A60E3E61-1FF6-4982-B6B8-9E4350C4C679}");
  2053. serializeContext->ClassDeprecate("AZStd::vector<SimpleAssetReference_TextureAtlasAsset>", deprecatedTypeId,
  2054. [](AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& rootElement)
  2055. {
  2056. AZStd::vector<AZ::SerializeContext::DataElementNode> childNodeElements;
  2057. for (int index = 0; index < rootElement.GetNumSubElements(); ++index)
  2058. {
  2059. childNodeElements.push_back(rootElement.GetSubElement(index));
  2060. }
  2061. rootElement.Convert<AZStd::vector<AzFramework::SimpleAssetReference<TextureAtlasNamespace::TextureAtlasAsset>>>(context);
  2062. for (AZ::SerializeContext::DataElementNode& childNodeElement : childNodeElements)
  2063. {
  2064. rootElement.AddElement(AZStd::move(childNodeElement));
  2065. }
  2066. return true;
  2067. });
  2068. AZ::EditContext* ec = serializeContext->GetEditContext();
  2069. if (ec)
  2070. {
  2071. auto editInfo = ec->Class<UiCanvasComponent>("UI Canvas", "These are the properties of the UI canvas.");
  2072. editInfo->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  2073. ->Attribute(AZ::Edit::Attributes::AddableByUser, false)
  2074. ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/UiCanvas.png")
  2075. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/UiCanvas.png")
  2076. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  2077. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Rendering")
  2078. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  2079. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_drawOrder, "Draw order", "The order, relative to other canvases, in which this canvas will draw (higher numbers on top).");
  2080. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_isPixelAligned, "Is pixel aligned", "When checked, all corners of all elements will be rounded to the nearest pixel.")
  2081. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiCanvasComponent::OnPixelAlignmentChange);
  2082. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_isTextPixelAligned, "Is text pixel aligned", "When checked, all text will be rounded to the nearest pixel.")
  2083. ->Attribute(AZ::Edit::Attributes::ChangeNotify, &UiCanvasComponent::OnTextPixelAlignmentChange);
  2084. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_renderToTexture, "Render to texture", "When checked, the canvas is rendered to a texture instead of the full screen.")
  2085. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c));
  2086. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_attachmentImageAsset, "Render Target", "The asset for the attachment image that this canvas renders to.")
  2087. ->Attribute(AZ::Edit::Attributes::Visibility, &UiCanvasComponent::m_renderToTexture);
  2088. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Input")
  2089. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  2090. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_isPositionalInputSupported, "Handle positional", "When checked, positional input (mouse/touch) will automatically be handled.")
  2091. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c));
  2092. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_isConsumingAllInputEvents, "Consume all input", "When checked, all input events will be consumed by this canvas while it is enabled.")
  2093. ->Attribute(AZ::Edit::Attributes::Visibility, &UiCanvasComponent::GetIsPositionalInputSupported);
  2094. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_isMultiTouchSupported, "Handle multi-touch", "When checked, multi-touch input will automatically be handled.")
  2095. ->Attribute(AZ::Edit::Attributes::Visibility, &UiCanvasComponent::GetIsPositionalInputSupported);
  2096. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiCanvasComponent::m_isNavigationSupported, "Handle navigation", "When checked, keyboard/gamepad events will automatically be used for navigation.");
  2097. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_navigationThreshold, "Navigation threshold", "The analog (eg. thumb-stick) input value that must be exceeded before a navigation command will be processed.")
  2098. ->Attribute(AZ::Edit::Attributes::Min, 0.0f)
  2099. ->Attribute(AZ::Edit::Attributes::Max, 1.0f);
  2100. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_navigationRepeatDelay, "Navigation repeat delay", "The delay (milliseconds) before a held navigation command will begin repeating.");
  2101. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_navigationRepeatPeriod, "Navigation repeat period", "The delay (milliseconds) before a held navigation command will continue repeating.");
  2102. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiCanvasComponent::m_firstHoverInteractable, "First focus elem", "The element to receive focus when the canvas loads.")
  2103. ->Attribute("EnumValues", &UiCanvasComponent::PopulateNavigableEntityList);
  2104. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Tooltips")
  2105. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  2106. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiCanvasComponent::m_tooltipDisplayElement, "Tooltip display elem", "The element to be displayed when hovering over an interactable.")
  2107. ->Attribute("EnumValues", &UiCanvasComponent::PopulateTooltipDisplayEntityList);
  2108. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Editor settings")
  2109. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  2110. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_snapDistance, "Snap distance", "The snap grid spacing.")
  2111. ->Attribute(AZ::Edit::Attributes::Min, 1.0f);
  2112. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_snapRotationDegrees, "Snap rotation", "The degrees of rotation to snap to.")
  2113. ->Attribute(AZ::Edit::Attributes::Min, 1.0f)
  2114. ->Attribute(AZ::Edit::Attributes::Max, 359.0f)
  2115. ->Attribute(AZ::Edit::Attributes::Suffix, " degrees");
  2116. editInfo->DataElement(AZ::Edit::UIHandlers::Default, &UiCanvasComponent::m_guideColor, "Guide color", "The color to draw the guide lines on this canvas.");
  2117. editInfo->DataElement("SimpleAssetRef", &UiCanvasComponent::m_atlasPathNames, "Texture atlases", "The texture atlases that this canvas loads.")
  2118. ->Attribute("ChangeNotify", &UiCanvasComponent::ReloadAtlases);
  2119. }
  2120. }
  2121. AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
  2122. if (behaviorContext)
  2123. {
  2124. behaviorContext->EBus<UiCanvasBus>("UiCanvasBus")
  2125. ->Event("GetDrawOrder", &UiCanvasBus::Events::GetDrawOrder)
  2126. ->Event("SetDrawOrder", &UiCanvasBus::Events::SetDrawOrder)
  2127. ->Event("GetKeepLoadedOnLevelUnload", &UiCanvasBus::Events::GetKeepLoadedOnLevelUnload)
  2128. ->Event("SetKeepLoadedOnLevelUnload", &UiCanvasBus::Events::SetKeepLoadedOnLevelUnload)
  2129. ->Event("RecomputeChangedLayouts", &UiCanvasBus::Events::RecomputeChangedLayouts)
  2130. ->Event("GetNumChildElements", &UiCanvasBus::Events::GetNumChildElements)
  2131. ->Event("GetChildElement", &UiCanvasBus::Events::GetChildElementEntityId)
  2132. ->Event("GetChildElements", &UiCanvasBus::Events::GetChildElementEntityIds)
  2133. ->Event("FindElementByName", &UiCanvasBus::Events::FindElementEntityIdByName)
  2134. ->Event("CloneElement", &UiCanvasBus::Events::CloneElementEntityId)
  2135. ->Event("GetIsPixelAligned", &UiCanvasBus::Events::GetIsPixelAligned)
  2136. ->Event("SetIsPixelAligned", &UiCanvasBus::Events::SetIsPixelAligned)
  2137. ->Event("GetIsTextPixelAligned", &UiCanvasBus::Events::GetIsTextPixelAligned)
  2138. ->Event("SetIsTextPixelAligned", &UiCanvasBus::Events::SetIsTextPixelAligned)
  2139. ->Event("GetEnabled", &UiCanvasBus::Events::GetEnabled)
  2140. ->Event("SetEnabled", &UiCanvasBus::Events::SetEnabled)
  2141. ->Event("GetIsRenderToTexture", &UiCanvasBus::Events::GetIsRenderToTexture)
  2142. ->Event("SetIsRenderToTexture", &UiCanvasBus::Events::SetIsRenderToTexture)
  2143. ->Event("GetAttachmentImageAsset", &UiCanvasBus::Events::GetAttachmentImageAsset)
  2144. ->Event("SetAttachmentImageAsset", &UiCanvasBus::Events::SetAttachmentImageAsset)
  2145. ->Event("GetIsPositionalInputSupported", &UiCanvasBus::Events::GetIsPositionalInputSupported)
  2146. ->Event("SetIsPositionalInputSupported", &UiCanvasBus::Events::SetIsPositionalInputSupported)
  2147. ->Event("GetIsConsumingAllInputEvents", &UiCanvasBus::Events::GetIsConsumingAllInputEvents)
  2148. ->Event("SetIsConsumingAllInputEvents", &UiCanvasBus::Events::SetIsConsumingAllInputEvents)
  2149. ->Event("GetIsMultiTouchSupported", &UiCanvasBus::Events::GetIsMultiTouchSupported)
  2150. ->Event("SetIsMultiTouchSupported", &UiCanvasBus::Events::SetIsMultiTouchSupported)
  2151. ->Event("GetIsNavigationSupported", &UiCanvasBus::Events::GetIsNavigationSupported)
  2152. ->Event("SetIsNavigationSupported", &UiCanvasBus::Events::SetIsNavigationSupported)
  2153. ->Event("GetNavigationThreshold", &UiCanvasBus::Events::GetNavigationThreshold)
  2154. ->Event("SetNavigationThreshold", &UiCanvasBus::Events::SetNavigationThreshold)
  2155. ->Event("GetNavigationRepeatDelay", &UiCanvasBus::Events::GetNavigationRepeatDelay)
  2156. ->Event("SetNavigationRepeatDelay", &UiCanvasBus::Events::SetNavigationRepeatDelay)
  2157. ->Event("GetNavigationRepeatPeriod", &UiCanvasBus::Events::GetNavigationRepeatPeriod)
  2158. ->Event("SetNavigationRepeatPeriod", &UiCanvasBus::Events::SetNavigationRepeatPeriod)
  2159. ->Event("GetTooltipDisplayElement", &UiCanvasBus::Events::GetTooltipDisplayElement)
  2160. ->Event("SetTooltipDisplayElement", &UiCanvasBus::Events::SetTooltipDisplayElement)
  2161. ->Event("GetHoverInteractable", &UiCanvasBus::Events::GetHoverInteractable)
  2162. ->Event("ForceHoverInteractable", &UiCanvasBus::Events::ForceHoverInteractable)
  2163. ->Event("GetMousePosition", &UiCanvasBus::Events::GetMousePosition)
  2164. ->Event("GetCanvasSize", &UiCanvasBus::Events::GetCanvasSize)
  2165. ->Event("GetAuthoredCanvasSize", &UiCanvasBus::Events::GetAuthoredCanvasSize)
  2166. ->Event("ForceEnterInputEventOnInteractable", &UiCanvasBus::Events::ForceEnterInputEventOnInteractable);
  2167. behaviorContext->EBus<UiCanvasNotificationBus>("UiCanvasNotificationBus")
  2168. ->Handler<UiCanvasNotificationBusBehaviorHandler>();
  2169. behaviorContext->EBus<UiAnimationBus>("UiAnimationBus")
  2170. ->Event("StartSequence", &UiAnimationBus::Events::StartSequence)
  2171. ->Event("PlaySequenceRange", &UiAnimationBus::Events::PlaySequenceRange)
  2172. ->Event("StopSequence", &UiAnimationBus::Events::StopSequence)
  2173. ->Event("AbortSequence", &UiAnimationBus::Events::AbortSequence)
  2174. ->Event("PauseSequence", &UiAnimationBus::Events::PauseSequence)
  2175. ->Event("ResumeSequence", &UiAnimationBus::Events::ResumeSequence)
  2176. ->Event("ResetSequence", &UiAnimationBus::Events::ResetSequence)
  2177. ->Event("GetSequencePlayingSpeed", &UiAnimationBus::Events::GetSequencePlayingSpeed)
  2178. ->Event("SetSequencePlayingSpeed", &UiAnimationBus::Events::SetSequencePlayingSpeed)
  2179. ->Event("GetSequencePlayingTime", &UiAnimationBus::Events::GetSequencePlayingTime)
  2180. ->Event("IsSequencePlaying", &UiAnimationBus::Events::IsSequencePlaying)
  2181. ->Event("GetSequenceLength", &UiAnimationBus::Events::GetSequenceLength)
  2182. ->Event("SetSequenceStopBehavior", &UiAnimationBus::Events::SetSequenceStopBehavior);
  2183. behaviorContext->Enum<(int)IUiAnimationListener::EUiAnimationEvent::eUiAnimationEvent_Started>("eUiAnimationEvent_Started")
  2184. ->Enum<(int)IUiAnimationListener::EUiAnimationEvent::eUiAnimationEvent_Stopped>("eUiAnimationEvent_Stopped")
  2185. ->Enum<(int)IUiAnimationListener::EUiAnimationEvent::eUiAnimationEvent_Aborted>("eUiAnimationEvent_Aborted")
  2186. ->Enum<(int)IUiAnimationListener::EUiAnimationEvent::eUiAnimationEvent_Updated>("eUiAnimationEvent_Updated");
  2187. behaviorContext->Enum<(int)IUiAnimationSystem::ESequenceStopBehavior::eSSB_LeaveTime>("eSSB_LeaveTime")
  2188. ->Enum<(int)IUiAnimationSystem::ESequenceStopBehavior::eSSB_GotoEndTime>("eSSB_GotoEndTime")
  2189. ->Enum<(int)IUiAnimationSystem::ESequenceStopBehavior::eSSB_GotoStartTime>("eSSB_GotoStartTime");
  2190. behaviorContext->EBus<UiAnimationNotificationBus>("UiAnimationNotificationBus")
  2191. ->Handler<UiAnimationNotificationBusBehaviorHandler>();
  2192. behaviorContext->EBus<UiInitializationBus>("UiInitializationBus")
  2193. ->Handler<UiInitializationBusBehaviorHandler>();
  2194. behaviorContext->EBus<UiCanvasInputNotificationBus>("UiCanvasInputNotificationBus")
  2195. ->Handler<UiCanvasInputNotificationBusBehaviorHandler>();
  2196. behaviorContext->EBus<UiCanvasEnabledStateNotificationBus>("UiCanvasEnabledStateNotificationBus")
  2197. ->Handler<UiCanvasEnabledStateNotificationBusBehaviorHandler>();
  2198. }
  2199. }
  2200. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2201. void UiCanvasComponent::Initialize()
  2202. {
  2203. s_handleHoverInputEvents = true;
  2204. s_allowClearingHoverInteractableOnHoverInput = true;
  2205. }
  2206. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2207. void UiCanvasComponent::Shutdown()
  2208. {
  2209. }
  2210. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2211. // PROTECTED MEMBER FUNCTIONS
  2212. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2213. void UiCanvasComponent::Init()
  2214. {
  2215. // We don't know whether we're in editor or game yet, but if we're in the editor
  2216. // we need to know the authored canvas size to ensure certain properties are displayed
  2217. // correctly in the editor window. If we're in game, the target canvas size will be
  2218. // initialized to the viewport on the first render loop.
  2219. m_targetCanvasSize = m_canvasSize;
  2220. if (m_uniqueId == 0)
  2221. {
  2222. // Initialize unique Id
  2223. m_uniqueId = CreateUniqueId();
  2224. }
  2225. }
  2226. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2227. void UiCanvasComponent::Activate()
  2228. {
  2229. UiCanvasBus::Handler::BusConnect(GetEntityId());
  2230. UiCanvasComponentImplementationBus::Handler::BusConnect(GetEntityId());
  2231. UiEditorCanvasBus::Handler::BusConnect(GetEntityId());
  2232. UiAnimationBus::Handler::BusConnect(GetEntityId());
  2233. LyShine::RenderToTextureRequestBus::Handler::BusConnect(GetEntityId());
  2234. // Reconnect to buses that we connect to intermittently
  2235. // This will only happen if we have been deactivated and reactivated at runtime
  2236. if (m_hoverInteractable.IsValid())
  2237. {
  2238. AZ::EntityBus::Handler::BusConnect(m_hoverInteractable);
  2239. }
  2240. if (m_activeInteractable.IsValid())
  2241. {
  2242. UiInteractableActiveNotificationBus::Handler::BusConnect(m_activeInteractable);
  2243. }
  2244. LoadAtlases();
  2245. m_layoutManager = new UiLayoutManager(GetEntityId());
  2246. }
  2247. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2248. void UiCanvasComponent::Deactivate()
  2249. {
  2250. UiCanvasBus::Handler::BusDisconnect();
  2251. UiCanvasComponentImplementationBus::Handler::BusDisconnect();
  2252. UiEditorCanvasBus::Handler::BusDisconnect();
  2253. UiAnimationBus::Handler::BusDisconnect();
  2254. LyShine::RenderToTextureRequestBus::Handler::BusDisconnect();
  2255. // disconnect from any other buses we could be connected to
  2256. if (m_hoverInteractable.IsValid() && AZ::EntityBus::Handler::BusIsConnectedId(m_hoverInteractable))
  2257. {
  2258. AZ::EntityBus::Handler::BusDisconnect(m_hoverInteractable);
  2259. }
  2260. if (m_activeInteractable.IsValid() && UiInteractableActiveNotificationBus::Handler::BusIsConnectedId(m_activeInteractable))
  2261. {
  2262. UiInteractableActiveNotificationBus::Handler::BusDisconnect(m_activeInteractable);
  2263. }
  2264. m_multiTouchInteractablesByTouchIndex.clear();
  2265. if (m_renderToTexture)
  2266. {
  2267. DestroyRenderTarget();
  2268. }
  2269. // Destroy owned render targets
  2270. m_attachmentImageMap.clear();
  2271. //! Notify LyShine pass that it needs to rebuild
  2272. QueueRttPassRebuild();
  2273. delete m_layoutManager;
  2274. m_layoutManager = nullptr;
  2275. m_renderGraph.ResetGraph();
  2276. }
  2277. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2278. // PRIVATE MEMBER FUNCTIONS
  2279. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2280. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2281. bool UiCanvasComponent::HandleHoverInputEvent(AZ::Vector2 point)
  2282. {
  2283. bool result = false;
  2284. // We don't change the active interactable here. Some interactables may want to still be considered
  2285. // pressed if the mouse moves outside their bounds while they are pressed.
  2286. // However, the active interactable does influence how hover works, if there is an active
  2287. // interactable then that is the only one that can be the hoverInteractable
  2288. AZ::EntityId latestHoverInteractable;
  2289. if (m_activeInteractable.IsValid())
  2290. {
  2291. // check if the mouse is hovering over the active interactable
  2292. bool hoveringOnActive = false;
  2293. UiTransformBus::EventResult(hoveringOnActive, m_activeInteractable, &UiTransformBus::Events::IsPointInRect, point);
  2294. if (hoveringOnActive)
  2295. {
  2296. latestHoverInteractable = m_activeInteractable;
  2297. }
  2298. }
  2299. else
  2300. {
  2301. // there is no active interactable
  2302. // find the interactable that the mouse is hovering over (if any)
  2303. UiElementBus::EventResult(latestHoverInteractable, m_rootElement, &UiElementBus::Events::FindInteractableToHandleEvent, point);
  2304. }
  2305. if (latestHoverInteractable.IsValid())
  2306. {
  2307. s_allowClearingHoverInteractableOnHoverInput = true;
  2308. }
  2309. if (m_hoverInteractable.IsValid() && m_hoverInteractable != latestHoverInteractable)
  2310. {
  2311. // we were hovering over an interactable but now we are hovering over nothing or a different interactable
  2312. if (s_allowClearingHoverInteractableOnHoverInput)
  2313. {
  2314. ClearHoverInteractable();
  2315. }
  2316. }
  2317. if (latestHoverInteractable.IsValid() && !m_hoverInteractable.IsValid())
  2318. {
  2319. // we are now hovering over something and we aren't tracking that yet
  2320. SetHoverInteractable(latestHoverInteractable);
  2321. UiInteractableBus::EventResult(result, m_hoverInteractable, &UiInteractableBus::Events::IsHandlingEvents);
  2322. }
  2323. // if there is an active interactable then we send mouse position updates to that interactable
  2324. if (m_activeInteractable.IsValid())
  2325. {
  2326. UiInteractableBus::Event(m_activeInteractable, &UiInteractableBus::Events::InputPositionUpdate, point);
  2327. }
  2328. return result;
  2329. }
  2330. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2331. bool UiCanvasComponent::HandleKeyInputEvent(const AzFramework::InputChannel::Snapshot& inputSnapshot, AzFramework::ModifierKeyMask activeModifierKeys)
  2332. {
  2333. bool result = false;
  2334. // Allow the active interactable to handle the key input first
  2335. if (m_activeInteractable.IsValid())
  2336. {
  2337. if (inputSnapshot.m_state == AzFramework::InputChannel::State::Began ||
  2338. AzFramework::InputDeviceVirtualKeyboard::IsVirtualKeyboardDevice(inputSnapshot.m_deviceId)) // Virtual keyboard events don't have state
  2339. {
  2340. UiInteractableBus::EventResult(
  2341. result, m_activeInteractable, &UiInteractableBus::Events::HandleKeyInputBegan, inputSnapshot, activeModifierKeys);
  2342. }
  2343. }
  2344. if (!result && m_isNavigationSupported)
  2345. {
  2346. const UiNavigationHelpers::Command command = UiNavigationHelpers::MapInputChannelIdToUiNavigationCommand(inputSnapshot.m_channelId, activeModifierKeys);
  2347. if (command != UiNavigationHelpers::Command::Unknown)
  2348. {
  2349. // Handle directional navigation input. Navigation is performed if there is no active interactable, or if the
  2350. // active interactable is not pressed and is set to auto-activate
  2351. bool handleDirectionalNavigation = false;
  2352. if (!m_activeInteractable.IsValid())
  2353. {
  2354. handleDirectionalNavigation = true;
  2355. }
  2356. else if (!m_isActiveInteractablePressed)
  2357. {
  2358. // Check if the active interactable automatically goes to an active state
  2359. UiInteractableBus::EventResult(
  2360. handleDirectionalNavigation, m_activeInteractable, &UiInteractableBus::Events::GetIsAutoActivationEnabled);
  2361. }
  2362. if (handleDirectionalNavigation)
  2363. {
  2364. AZ::EntityId oldHoverInteractable = m_hoverInteractable;
  2365. result = HandleNavigationInputEvent(command, inputSnapshot);
  2366. if (m_hoverInteractable != oldHoverInteractable)
  2367. {
  2368. s_handleHoverInputEvents = false;
  2369. s_allowClearingHoverInteractableOnHoverInput = false;
  2370. AZ::EntityId ancestorInteractable = FindAncestorInteractable(m_hoverInteractable);
  2371. if (ancestorInteractable.IsValid())
  2372. {
  2373. // Send an event that the descendant interactable became the hover interactable via navigation
  2374. UiInteractableBus::Event(
  2375. ancestorInteractable,
  2376. &UiInteractableBus::Events::HandleDescendantReceivedHoverByNavigation,
  2377. m_hoverInteractable);
  2378. }
  2379. ClearActiveInteractable();
  2380. // Check if this hover interactable should automatically go to an active state
  2381. CheckHoverInteractableAndAutoActivate(oldHoverInteractable, command);
  2382. }
  2383. }
  2384. if (!result)
  2385. {
  2386. // Handle enter input
  2387. result = HandleEnterInputEvent(command, inputSnapshot);
  2388. }
  2389. if (!result)
  2390. {
  2391. // Handle back input
  2392. result = HandleBackInputEvent(command, inputSnapshot);
  2393. }
  2394. if (!result)
  2395. {
  2396. // If there is any active or hover interactable then we consider this event handled.
  2397. // Otherwise we can end up sending events to underlying canvases even though there
  2398. // is an interactable in this canvas that should block the events
  2399. if (m_activeInteractable.IsValid() || m_hoverInteractable.IsValid())
  2400. {
  2401. result = true;
  2402. }
  2403. }
  2404. }
  2405. }
  2406. return result;
  2407. }
  2408. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2409. bool UiCanvasComponent::HandleEnterInputEvent(UiNavigationHelpers::Command command, const AzFramework::InputChannel::Snapshot& inputSnapshot)
  2410. {
  2411. bool result = false;
  2412. if (command == UiNavigationHelpers::Command::Enter)
  2413. {
  2414. // The key is the Enter key. If there is any active or hover interactable then we consider this event handled.
  2415. // Otherwise we can end up sending Enter events to underlying canvases even though there is an interactable
  2416. // in this canvas that should block the events
  2417. if (m_activeInteractable.IsValid() || m_hoverInteractable.IsValid())
  2418. {
  2419. result = true;
  2420. }
  2421. if (inputSnapshot.m_state == AzFramework::InputChannel::State::Began)
  2422. {
  2423. AZ::EntityId prevHoverInteractable = m_hoverInteractable;
  2424. // Enter key was pressed. The press can activate an interactable and also deactivate an interactable
  2425. // Check if there's an interactable to deactivate
  2426. if (m_activeInteractable.IsValid() && m_activeInteractableShouldStayActive)
  2427. {
  2428. DeactivateInteractableByKeyInput(inputSnapshot);
  2429. }
  2430. else
  2431. {
  2432. // Check if there's a hover interactable to make active
  2433. if (m_hoverInteractable.IsValid())
  2434. {
  2435. // clear any active interactable
  2436. ClearActiveInteractable();
  2437. // if the hover interactable can handle enter pressed events then
  2438. // it becomes the currently pressed interactable for the canvas
  2439. bool handled = false;
  2440. bool shouldStayActive = false;
  2441. UiInteractableBus::EventResult(
  2442. handled, m_hoverInteractable, &UiInteractableBus::Events::HandleEnterPressed, shouldStayActive);
  2443. if (handled)
  2444. {
  2445. SetActiveInteractable(m_hoverInteractable, shouldStayActive);
  2446. s_handleHoverInputEvents = false;
  2447. s_allowClearingHoverInteractableOnHoverInput = false;
  2448. m_isActiveInteractablePressed = true;
  2449. }
  2450. }
  2451. }
  2452. // Send a notification to listeners telling them who was just pressed (can be noone)
  2453. UiCanvasInputNotificationBus::Event(
  2454. GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasEnterPressed, prevHoverInteractable);
  2455. }
  2456. else if (inputSnapshot.m_state == AzFramework::InputChannel::State::Ended)
  2457. {
  2458. AZ::EntityId prevActiveInteractable = m_activeInteractable;
  2459. // Enter key has been released. Check if the active interactable should stay active
  2460. if (m_activeInteractable.IsValid() && (m_activeInteractable == m_hoverInteractable))
  2461. {
  2462. UiInteractableBus::Event(m_activeInteractable, &UiInteractableBus::Events::HandleEnterReleased);
  2463. if (!m_activeInteractableShouldStayActive)
  2464. {
  2465. ClearActiveInteractable();
  2466. }
  2467. else
  2468. {
  2469. // Interactable should stay active, so check if if it has a descendant interactable
  2470. // that it should pass the hover to
  2471. CheckActiveInteractableAndPassHoverToDescendant();
  2472. }
  2473. m_isActiveInteractablePressed = false;
  2474. }
  2475. // Send a notification to listeners telling them who was just released (can be noone)
  2476. UiCanvasInputNotificationBus::Event(
  2477. GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasEnterReleased, prevActiveInteractable);
  2478. }
  2479. }
  2480. return result;
  2481. }
  2482. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2483. bool UiCanvasComponent::HandleBackInputEvent(UiNavigationHelpers::Command command, const AzFramework::InputChannel::Snapshot& inputSnapshot)
  2484. {
  2485. bool result = false;
  2486. if (command == UiNavigationHelpers::Command::Back)
  2487. {
  2488. if (inputSnapshot.m_state == AzFramework::InputChannel::State::Began)
  2489. {
  2490. // Back has two purposes:
  2491. // 1. If there is an active interactable, and it's not set to auto-activate, pressing back deactivates the interactable
  2492. // 2. If there is a hover interactable, and it's a child of another interactable, then pressing back moves focus from the child
  2493. // to the parent
  2494. // First check if there is an active interactable to deactivate
  2495. if (m_activeInteractable.IsValid())
  2496. {
  2497. // Deactivate this interactable
  2498. result = DeactivateInteractableByKeyInput(inputSnapshot);
  2499. }
  2500. else if (m_hoverInteractable.IsValid())
  2501. {
  2502. result = PassHoverToAncestorByKeyInput(inputSnapshot);
  2503. }
  2504. }
  2505. }
  2506. return result;
  2507. }
  2508. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2509. bool UiCanvasComponent::HandleNavigationInputEvent(UiNavigationHelpers::Command command, const AzFramework::InputChannel::Snapshot& inputSnapshot)
  2510. {
  2511. bool result = false;
  2512. if (command == UiNavigationHelpers::Command::Up ||
  2513. command == UiNavigationHelpers::Command::Down ||
  2514. command == UiNavigationHelpers::Command::Left ||
  2515. command == UiNavigationHelpers::Command::Right)
  2516. {
  2517. // If the stick is no longer pushed, we allow navigating in that direction again
  2518. auto navCommandStatus = m_navCommandStatus.find(command);
  2519. if (inputSnapshot.m_state == AzFramework::InputChannel::State::Ended)
  2520. {
  2521. navCommandStatus->second.navigationCount = 0;
  2522. navCommandStatus->second.allowNavigation = true;
  2523. }
  2524. // Prevent navigation in this direction for the specified period of time
  2525. const AZ::u64 time = AZStd::GetTimeUTCMilliSecond();
  2526. if (!navCommandStatus->second.allowNavigation)
  2527. {
  2528. // The 'navigation repeat delay' is different to the 'navigation repeat period' so that we
  2529. // can have a longer delay before the first repeated navigation command vs all subsequent
  2530. // navigation command repeats. For example, the default values result in a delay of 300ms
  2531. // before a held navigation command will begin repeated, but then while it remains held it
  2532. // will continue to repeat every 150ms
  2533. const AZ::u64 timeSinceLastNavigation = time - navCommandStatus->second.lastNavigationTime;
  2534. if ((navCommandStatus->second.navigationCount > 1 && timeSinceLastNavigation >= m_navigationRepeatPeriod) ||
  2535. (timeSinceLastNavigation >= m_navigationRepeatDelay))
  2536. {
  2537. navCommandStatus->second.allowNavigation = true;
  2538. }
  2539. else
  2540. {
  2541. return false;
  2542. }
  2543. }
  2544. // Check if the thumb-stick was pushed far enough
  2545. if (inputSnapshot.m_value >= m_navigationThreshold)
  2546. {
  2547. // Don't allow navigating in this direction again until the stick is released or enough time has elapsed.
  2548. navCommandStatus->second.lastNavigationTime = time;
  2549. navCommandStatus->second.allowNavigation = false;
  2550. ++navCommandStatus->second.navigationCount;
  2551. AZ::EntityId firstHoverInteractable = GetFirstHoverInteractable();
  2552. // Find the interactable to navigate to
  2553. if (!m_hoverInteractable.IsValid())
  2554. {
  2555. SetHoverInteractable(firstHoverInteractable);
  2556. }
  2557. else
  2558. {
  2559. AZ::EntityId curInteractable = m_hoverInteractable;
  2560. while (curInteractable.IsValid())
  2561. {
  2562. AZ::EntityId ancestorInteractable = UiNavigationHelpers::FindAncestorNavigableInteractable(curInteractable);
  2563. LyShine::EntityArray navigableElements;
  2564. UiNavigationHelpers::FindNavigableInteractables(ancestorInteractable.IsValid() ? ancestorInteractable : m_rootElement, curInteractable, navigableElements);
  2565. AZ::EntityId nextEntityId = UiNavigationHelpers::GetNextElement(curInteractable, command,
  2566. navigableElements, firstHoverInteractable, IsValidInteractable, ancestorInteractable);
  2567. if (nextEntityId.IsValid())
  2568. {
  2569. SetHoverInteractable(nextEntityId);
  2570. break;
  2571. }
  2572. else
  2573. {
  2574. // Check if parent interactable was auto-activated
  2575. bool autoActivated = false;
  2576. UiInteractableBus::EventResult(
  2577. autoActivated, ancestorInteractable, &UiInteractableBus::Events::GetIsAutoActivationEnabled);
  2578. if (autoActivated)
  2579. {
  2580. curInteractable = ancestorInteractable;
  2581. }
  2582. else
  2583. {
  2584. break;
  2585. }
  2586. }
  2587. }
  2588. }
  2589. result = m_hoverInteractable.IsValid();
  2590. }
  2591. }
  2592. return result;
  2593. }
  2594. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2595. bool UiCanvasComponent::DeactivateInteractableByKeyInput(const AzFramework::InputChannel::Snapshot& inputSnapshot)
  2596. {
  2597. // Check if the active interactable automatically went to an active state. If it did
  2598. // not automatically go into its active state, then we deactivate the active interactable.
  2599. // Otherwise, the only way to deactivate the interactable is by navigating away from it
  2600. // using the directional keys
  2601. bool autoActivated = false;
  2602. UiInteractableBus::EventResult(autoActivated, m_activeInteractable, &UiInteractableBus::Events::GetIsAutoActivationEnabled);
  2603. if (!autoActivated)
  2604. {
  2605. // Clear the active interactable
  2606. AZ::EntityId prevActiveInteractable = m_activeInteractable;
  2607. ClearActiveInteractable();
  2608. if (AzFramework::InputDeviceGamepad::IsGamepadDevice(inputSnapshot.m_deviceId))
  2609. {
  2610. SetHoverInteractable(prevActiveInteractable);
  2611. s_handleHoverInputEvents = false;
  2612. s_allowClearingHoverInteractableOnHoverInput = false;
  2613. }
  2614. return true;
  2615. }
  2616. return false;
  2617. }
  2618. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2619. bool UiCanvasComponent::PassHoverToAncestorByKeyInput([[maybe_unused]] const AzFramework::InputChannel::Snapshot& inputSnapshot)
  2620. {
  2621. bool result = false;
  2622. // Check if the hover interactable has an ancestor that's also an interactable
  2623. AZ::EntityId ancestorInteractable = UiNavigationHelpers::FindAncestorNavigableInteractable(m_hoverInteractable, true);
  2624. if (ancestorInteractable.IsValid())
  2625. {
  2626. AZ::EntityId descendantInteractable = m_hoverInteractable;
  2627. SetHoverInteractable(ancestorInteractable);
  2628. UiInteractableBus::Event(
  2629. ancestorInteractable, &UiInteractableBus::Events::HandleReceivedHoverByNavigatingFromDescendant, descendantInteractable);
  2630. result = true;
  2631. }
  2632. return result;
  2633. }
  2634. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2635. bool UiCanvasComponent::HandlePrimaryPress(AZ::Vector2 point)
  2636. {
  2637. bool result = false;
  2638. // use the pressed position to select the interactable being pressed
  2639. AZ::EntityId interactableEntity;
  2640. UiElementBus::EventResult(interactableEntity, m_rootElement, &UiElementBus::Events::FindInteractableToHandleEvent, point);
  2641. // Clear the previous active interactable if it's different from the new active interactable
  2642. if (!interactableEntity.IsValid() || (interactableEntity != m_activeInteractable))
  2643. {
  2644. if (m_activeInteractable.IsValid())
  2645. {
  2646. ClearActiveInteractable();
  2647. }
  2648. }
  2649. if (interactableEntity.IsValid())
  2650. {
  2651. // if there is an interactable at that point and it can handle pressed events then
  2652. // it becomes the currently pressed interactable for the canvas
  2653. bool handled = false;
  2654. bool shouldStayActive = false;
  2655. UiInteractableBus::EventResult(handled, interactableEntity, &UiInteractableBus::Events::HandlePressed, point, shouldStayActive);
  2656. if (handled)
  2657. {
  2658. SetActiveInteractable(interactableEntity, shouldStayActive);
  2659. m_isActiveInteractablePressed = true;
  2660. result = true;
  2661. }
  2662. }
  2663. // Resume handling hover input events
  2664. s_handleHoverInputEvents = true;
  2665. s_allowClearingHoverInteractableOnHoverInput = true;
  2666. // Send a notification to listeners telling them who was just pressed (can be noone)
  2667. UiCanvasInputNotificationBus::Event(GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasPrimaryPressed, interactableEntity);
  2668. return result;
  2669. }
  2670. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2671. bool UiCanvasComponent::HandlePrimaryUpdate([[maybe_unused]] AZ::Vector2 point)
  2672. {
  2673. bool result = false;
  2674. if (m_activeInteractable.IsValid())
  2675. {
  2676. result = true;
  2677. }
  2678. return result;
  2679. }
  2680. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2681. bool UiCanvasComponent::HandlePrimaryRelease(AZ::Vector2 point)
  2682. {
  2683. bool result = false;
  2684. AZ::EntityId prevActiveInteractable = m_activeInteractable;
  2685. // touch was released, if there is a currently pressed interactable let it handle the release
  2686. if (m_activeInteractable.IsValid())
  2687. {
  2688. UiInteractableBus::Event(m_activeInteractable, &UiInteractableBus::Events::HandleReleased, point);
  2689. if (!m_activeInteractableShouldStayActive)
  2690. {
  2691. UiInteractableActiveNotificationBus::Handler::BusDisconnect(m_activeInteractable);
  2692. m_activeInteractable.SetInvalid();
  2693. }
  2694. m_isActiveInteractablePressed = false;
  2695. result = true;
  2696. }
  2697. // Send a notification to listeners telling them who was just released
  2698. UiCanvasInputNotificationBus::Event(
  2699. GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasPrimaryReleased, prevActiveInteractable);
  2700. return result;
  2701. }
  2702. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2703. bool UiCanvasComponent::HandleMultiTouchPress(AZ::Vector2 point, int multiTouchIndex)
  2704. {
  2705. bool result = false;
  2706. if (m_isMultiTouchSupported)
  2707. {
  2708. AZ::EntityId interactableEntity;
  2709. UiElementBus::EventResult(interactableEntity, m_rootElement, &UiElementBus::Events::FindInteractableToHandleEvent, point);
  2710. if (interactableEntity.IsValid() && !IsInteractableActiveOrPressed(interactableEntity))
  2711. {
  2712. UiInteractableBus::EventResult(
  2713. result, interactableEntity, &UiInteractableBus::Events::HandleMultiTouchPressed, point, multiTouchIndex);
  2714. if (result)
  2715. {
  2716. m_multiTouchInteractablesByTouchIndex[multiTouchIndex] = interactableEntity;
  2717. }
  2718. }
  2719. // Send a notification to listeners telling them who was just pressed (can be noone)
  2720. UiCanvasInputNotificationBus::Event(
  2721. GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasMultiTouchPressed, interactableEntity, multiTouchIndex);
  2722. }
  2723. return result;
  2724. }
  2725. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2726. bool UiCanvasComponent::HandleMultiTouchRelease(AZ::Vector2 point, int multiTouchIndex)
  2727. {
  2728. bool result = false;
  2729. if (m_isMultiTouchSupported)
  2730. {
  2731. // Get the corresponding interactable from the map before removing it. It should always already
  2732. // exist in the map, but if not this will just insert an invalid entity id then remove it again
  2733. AZ::EntityId multiTouchInteractable = m_multiTouchInteractablesByTouchIndex[multiTouchIndex];
  2734. m_multiTouchInteractablesByTouchIndex.erase(multiTouchIndex);
  2735. if (multiTouchInteractable.IsValid())
  2736. {
  2737. UiInteractableBus::Event(multiTouchInteractable, &UiInteractableBus::Events::HandleMultiTouchReleased, point, multiTouchIndex);
  2738. result = true;
  2739. }
  2740. // Send a notification to listeners telling them who was just released
  2741. UiCanvasInputNotificationBus::Event(
  2742. GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasMultiTouchReleased, multiTouchInteractable, multiTouchIndex);
  2743. }
  2744. return result;
  2745. }
  2746. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2747. bool UiCanvasComponent::HandleMultiTouchUpdated(AZ::Vector2 point, int multiTouchIndex)
  2748. {
  2749. bool result = false;
  2750. if (m_isMultiTouchSupported)
  2751. {
  2752. auto it = m_multiTouchInteractablesByTouchIndex.find(multiTouchIndex);
  2753. if (it != m_multiTouchInteractablesByTouchIndex.end() && it->second.IsValid())
  2754. {
  2755. UiInteractableBus::Event(it->second, &UiInteractableBus::Events::MultiTouchPositionUpdate, point, multiTouchIndex);
  2756. result = true;
  2757. }
  2758. }
  2759. return result;
  2760. }
  2761. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2762. bool UiCanvasComponent::IsInteractableActiveOrPressed(AZ::EntityId interactableId) const
  2763. {
  2764. if (interactableId == m_activeInteractable)
  2765. {
  2766. return true;
  2767. }
  2768. for (const auto& multiTouchInteractableByTouchIndex : m_multiTouchInteractablesByTouchIndex)
  2769. {
  2770. if (interactableId == multiTouchInteractableByTouchIndex.second)
  2771. {
  2772. return true;
  2773. }
  2774. }
  2775. return false;
  2776. }
  2777. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2778. void UiCanvasComponent::SetHoverInteractable(AZ::EntityId newHoverInteractable)
  2779. {
  2780. if (m_hoverInteractable != newHoverInteractable)
  2781. {
  2782. ClearHoverInteractable();
  2783. m_hoverInteractable = newHoverInteractable;
  2784. if (m_hoverInteractable.IsValid())
  2785. {
  2786. UiInteractableBus::Event(m_hoverInteractable, &UiInteractableBus::Events::HandleHoverStart);
  2787. UiCanvasInputNotificationBus::Event(
  2788. GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasHoverStart, m_hoverInteractable);
  2789. // we want to know if this entity is deactivated or destroyed
  2790. // (unlikely: while hovered over we can't be in edit mode, could happen from C++ interface though)
  2791. AZ::EntityBus::Handler::BusConnect(m_hoverInteractable);
  2792. }
  2793. }
  2794. }
  2795. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2796. void UiCanvasComponent::ClearHoverInteractable()
  2797. {
  2798. if (m_hoverInteractable.IsValid())
  2799. {
  2800. UiInteractableBus::Event(m_hoverInteractable, &UiInteractableBus::Events::HandleHoverEnd);
  2801. UiCanvasInputNotificationBus::Event(GetEntityId(), &UiCanvasInputNotificationBus::Events::OnCanvasHoverEnd, m_hoverInteractable);
  2802. AZ::EntityBus::Handler::BusDisconnect(m_hoverInteractable);
  2803. m_hoverInteractable.SetInvalid();
  2804. }
  2805. }
  2806. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2807. void UiCanvasComponent::SetActiveInteractable(AZ::EntityId newActiveInteractable, bool shouldStayActive)
  2808. {
  2809. if (m_activeInteractable != newActiveInteractable)
  2810. {
  2811. ClearActiveInteractable();
  2812. m_activeInteractable = newActiveInteractable;
  2813. if (m_activeInteractable.IsValid())
  2814. {
  2815. UiInteractableActiveNotificationBus::Handler::BusConnect(m_activeInteractable);
  2816. m_activeInteractableShouldStayActive = shouldStayActive;
  2817. }
  2818. }
  2819. }
  2820. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2821. void UiCanvasComponent::ClearActiveInteractable()
  2822. {
  2823. if (m_activeInteractable.IsValid())
  2824. {
  2825. UiInteractableBus::Event(m_activeInteractable, &UiInteractableBus::Events::LostActiveStatus);
  2826. UiInteractableActiveNotificationBus::Handler::BusDisconnect(m_activeInteractable);
  2827. m_activeInteractable.SetInvalid();
  2828. }
  2829. }
  2830. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2831. void UiCanvasComponent::CheckHoverInteractableAndAutoActivate(AZ::EntityId prevHoverInteractable, UiNavigationHelpers::Command command, bool forceAutoActivate)
  2832. {
  2833. // Check if this hover interactable should automatically go to an active state
  2834. bool autoActivate = false;
  2835. UiInteractableBus::EventResult(autoActivate, m_hoverInteractable, &UiInteractableBus::Events::GetIsAutoActivationEnabled);
  2836. if (autoActivate || forceAutoActivate)
  2837. {
  2838. bool handled = false;
  2839. UiInteractableBus::EventResult(handled, m_hoverInteractable, &UiInteractableBus::Events::HandleAutoActivation);
  2840. if (handled)
  2841. {
  2842. SetActiveInteractable(m_hoverInteractable, true);
  2843. CheckActiveInteractableAndPassHoverToDescendant(prevHoverInteractable, command);
  2844. }
  2845. }
  2846. }
  2847. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2848. void UiCanvasComponent::CheckActiveInteractableAndPassHoverToDescendant(AZ::EntityId prevHoverInteractable, UiNavigationHelpers::Command command)
  2849. {
  2850. AZ::EntityId hoverInteractable;
  2851. if (prevHoverInteractable.IsValid())
  2852. {
  2853. LyShine::EntityArray navigableElements;
  2854. UiNavigationHelpers::FindNavigableInteractables(m_activeInteractable, AZ::EntityId(), navigableElements);
  2855. if (!navigableElements.empty())
  2856. {
  2857. hoverInteractable = UiNavigationHelpers::SearchForNextElement(prevHoverInteractable, command, navigableElements, m_activeInteractable);
  2858. }
  2859. }
  2860. if (!hoverInteractable.IsValid())
  2861. {
  2862. hoverInteractable = FindFirstHoverInteractable(m_activeInteractable);
  2863. }
  2864. if (hoverInteractable.IsValid())
  2865. {
  2866. // Send an event that the descendant interactable became the hover interactable via navigation
  2867. UiInteractableBus::Event(
  2868. m_activeInteractable, &UiInteractableBus::Events::HandleDescendantReceivedHoverByNavigation, hoverInteractable);
  2869. ClearActiveInteractable();
  2870. SetHoverInteractable(hoverInteractable);
  2871. CheckHoverInteractableAndAutoActivate(prevHoverInteractable, command);
  2872. }
  2873. }
  2874. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2875. AZ::EntityId UiCanvasComponent::FindAncestorInteractable(AZ::EntityId entityId)
  2876. {
  2877. AZ::EntityId parent;
  2878. UiElementBus::EventResult(parent, entityId, &UiElementBus::Events::GetParentEntityId);
  2879. while (parent.IsValid())
  2880. {
  2881. if (UiInteractableBus::FindFirstHandler(parent))
  2882. {
  2883. break;
  2884. }
  2885. AZ::EntityId newParent = parent;
  2886. parent.SetInvalid();
  2887. UiElementBus::EventResult(parent, newParent, &UiElementBus::Events::GetParentEntityId);
  2888. }
  2889. return parent;
  2890. }
  2891. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2892. AZ::EntityId UiCanvasComponent::GetFirstHoverInteractable()
  2893. {
  2894. AZ::EntityId hoverInteractable;
  2895. if (m_firstHoverInteractable.IsValid())
  2896. {
  2897. // Make sure that this interactable exists
  2898. AZ::Entity* hoverEntity = nullptr;
  2899. AZ::ComponentApplicationBus::BroadcastResult(
  2900. hoverEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_firstHoverInteractable);
  2901. if (hoverEntity)
  2902. {
  2903. if (UiNavigationHelpers::IsElementInteractableAndNavigable(m_firstHoverInteractable))
  2904. {
  2905. hoverInteractable = m_firstHoverInteractable;
  2906. }
  2907. }
  2908. }
  2909. if (!hoverInteractable.IsValid())
  2910. {
  2911. hoverInteractable = FindFirstHoverInteractable();
  2912. }
  2913. return hoverInteractable;
  2914. }
  2915. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2916. AZ::EntityId UiCanvasComponent::FindFirstHoverInteractable(AZ::EntityId parentElement)
  2917. {
  2918. if (!parentElement.IsValid())
  2919. {
  2920. parentElement = m_rootElement;
  2921. }
  2922. LyShine::EntityArray navigableElements;
  2923. UiNavigationHelpers::FindNavigableInteractables(parentElement, AZ::EntityId(), navigableElements);
  2924. UiTransformInterface::Rect parentRect;
  2925. AZ::Matrix4x4 transformFromViewport;
  2926. if (parentElement != m_rootElement)
  2927. {
  2928. UiTransformBus::Event(parentElement, &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  2929. UiTransformBus::Event(parentElement, &UiTransformBus::Events::GetTransformFromViewport, transformFromViewport);
  2930. }
  2931. else
  2932. {
  2933. transformFromViewport = AZ::Matrix4x4::CreateIdentity();
  2934. parentRect.Set(0.0f, m_targetCanvasSize.GetX(), 0.0f, m_targetCanvasSize.GetY());
  2935. }
  2936. // Go through the navigable elements and find the closest element to the top left of its parent
  2937. float shortestDist = FLT_MAX;
  2938. float shortestOutsideDist = FLT_MAX;
  2939. AZ::EntityId closestElement;
  2940. AZ::EntityId closestOutsideElement;
  2941. for (auto navigableElement : navigableElements)
  2942. {
  2943. UiTransformInterface::RectPoints points;
  2944. UiTransformBus::Event(navigableElement->GetId(), &UiTransformBus::Events::GetViewportSpacePoints, points);
  2945. points = points.Transform(transformFromViewport);
  2946. AZ::Vector2 topLeft = points.GetAxisAlignedTopLeft() - AZ::Vector2(parentRect.left, parentRect.top);
  2947. AZ::Vector2 center = points.GetCenter();
  2948. float dist = topLeft.GetLength();
  2949. bool inside = (center.GetX() >= parentRect.left &&
  2950. center.GetX() <= parentRect.right &&
  2951. center.GetY() >= parentRect.top &&
  2952. center.GetY() <= parentRect.bottom);
  2953. if (inside)
  2954. {
  2955. // Calculate a value from 0 to 1 representing how close the element is to the top of the screen
  2956. float yDistValue = topLeft.GetY() / parentRect.GetHeight();
  2957. // Calculate final distance value biased by y distance value
  2958. const float distMultConstant = 1.0f;
  2959. dist += dist * distMultConstant * yDistValue;
  2960. if (dist < shortestDist)
  2961. {
  2962. shortestDist = dist;
  2963. closestElement = navigableElement->GetId();
  2964. }
  2965. }
  2966. else
  2967. {
  2968. if (dist < shortestOutsideDist)
  2969. {
  2970. shortestOutsideDist = dist;
  2971. closestOutsideElement = navigableElement->GetId();
  2972. }
  2973. }
  2974. }
  2975. if (!closestElement.IsValid())
  2976. {
  2977. closestElement = closestOutsideElement;
  2978. }
  2979. return closestElement;
  2980. }
  2981. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2982. void UiCanvasComponent::SetFirstHoverInteractable()
  2983. {
  2984. bool setHoverInteractable = false;
  2985. if (s_handleHoverInputEvents)
  2986. {
  2987. // Check if there is a mouse or touch input device
  2988. const AzFramework::InputDevice* mouseDevice = AzFramework::InputDeviceRequests::FindInputDevice(AzFramework::InputDeviceMouse::Id);
  2989. const AzFramework::InputDevice* touchDevice = AzFramework::InputDeviceRequests::FindInputDevice(AzFramework::InputDeviceTouch::Id);
  2990. if ((!mouseDevice || !mouseDevice->IsConnected()) &&
  2991. (!touchDevice || !touchDevice->IsConnected()))
  2992. {
  2993. // No mouse or touch input device available so set a hover interactable
  2994. setHoverInteractable = true;
  2995. }
  2996. }
  2997. else
  2998. {
  2999. // Not handling hover input events so set a hover interactable
  3000. setHoverInteractable = true;
  3001. }
  3002. if (setHoverInteractable)
  3003. {
  3004. AZ::EntityId hoverInteractable = GetFirstHoverInteractable();
  3005. if (hoverInteractable.IsValid())
  3006. {
  3007. SetHoverInteractable(hoverInteractable);
  3008. s_handleHoverInputEvents = false;
  3009. s_allowClearingHoverInteractableOnHoverInput = false;
  3010. CheckHoverInteractableAndAutoActivate();
  3011. }
  3012. }
  3013. }
  3014. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3015. void UiCanvasComponent::PrepareAnimationSystemForCanvasSave()
  3016. {
  3017. m_serializedAnimationData.m_serializeData.clear();
  3018. }
  3019. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3020. void UiCanvasComponent::RestoreAnimationSystemAfterCanvasLoad(bool remapIds, UiElementComponent::EntityIdMap* entityIdMap)
  3021. {
  3022. // NOTE: this is legacy code for loading old format animation data. The latest canvas format
  3023. // uses the AZ serialization system for animation data.
  3024. const char* buffer = m_serializedAnimationData.m_serializeData.c_str();
  3025. size_t size = m_serializedAnimationData.m_serializeData.length();
  3026. if (size > 0)
  3027. {
  3028. // found old format animation data
  3029. // serialize back from loaded string and then clear string
  3030. XmlNodeRef xmlNode = gEnv->pSystem->LoadXmlFromBuffer(buffer, size);
  3031. m_uiAnimationSystem.Serialize(xmlNode, true);
  3032. m_serializedAnimationData.m_serializeData.clear();
  3033. }
  3034. // go through the sequences and fixup the entity Ids
  3035. // NOTE: for a latest format canvas these have probably already been remapped by ReplaceEntityRefs
  3036. // This function will leave them alone if that are not in the remap table
  3037. m_uiAnimationSystem.InitPostLoad(remapIds, entityIdMap);
  3038. }
  3039. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3040. UiCanvasComponent* UiCanvasComponent::CloneAndInitializeCanvas(UiEntityContext* entityContext, const AZStd::string& assetIdPathname, const AZ::Vector2* canvasSize)
  3041. {
  3042. UiCanvasComponent* canvasComponent = nullptr;
  3043. // Clone the root slice entity
  3044. // Do this in a way that handles this canvas being a Editor canvas.
  3045. // If it is an editor canvas then slices will be flattened and Editor components will be
  3046. // replaced with runtime components.
  3047. AZ::Entity* clonedRootSliceEntity = nullptr;
  3048. AZStd::string rootSliceBuffer;
  3049. AZ::IO::ByteContainerStream<AZStd::string > rootSliceStream(&rootSliceBuffer);
  3050. if (m_entityContext->SaveToStreamForGame(rootSliceStream, AZ::ObjectStream::ST_XML))
  3051. {
  3052. rootSliceStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  3053. clonedRootSliceEntity = AZ::Utils::LoadObjectFromStream<AZ::Entity>(rootSliceStream);
  3054. }
  3055. // Clone the canvas entity
  3056. AZ::Entity* sourceCanvasEntity = GetEntity();
  3057. AZ::Entity* clonedCanvasEntity = nullptr;
  3058. AZStd::string canvasBuffer;
  3059. AZ::IO::ByteContainerStream<AZStd::string > canvasStream(&canvasBuffer);
  3060. if (m_entityContext->SaveCanvasEntityToStreamForGame(sourceCanvasEntity, canvasStream, AZ::ObjectStream::ST_XML))
  3061. {
  3062. canvasStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  3063. clonedCanvasEntity = AZ::Utils::LoadObjectFromStream<AZ::Entity>(canvasStream);
  3064. }
  3065. if (clonedCanvasEntity && clonedRootSliceEntity)
  3066. {
  3067. // complete initialization of cloned entities, we assume this is NOT for editor
  3068. // since we only do this when using canvas in game that is already loaded in editor
  3069. canvasComponent = FixupPostLoad(clonedCanvasEntity, clonedRootSliceEntity, false, entityContext, canvasSize);
  3070. }
  3071. if (canvasComponent)
  3072. {
  3073. canvasComponent->m_pathname = assetIdPathname;
  3074. canvasComponent->m_isLoadedInGame = true;
  3075. }
  3076. return canvasComponent;
  3077. }
  3078. void UiCanvasComponent::DeactivateElements()
  3079. {
  3080. AZ::SliceComponent::EntityIdSet entities;
  3081. AZ::SliceComponent* rootSlice;
  3082. AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSlice, m_entityContext->GetContextId(),
  3083. &AzFramework::SliceEntityOwnershipServiceRequests::GetRootSlice);
  3084. bool result = rootSlice->GetEntityIds(entities);
  3085. if (result)
  3086. {
  3087. for (AZ::EntityId& entityId : entities)
  3088. {
  3089. // Look up the entity by ID, as sometimes one of the entities owns others
  3090. // that will be destroyed when it's destroyed. Since we store pointers,
  3091. // those will point to freed memory.
  3092. AZ::Entity* entity = nullptr;
  3093. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, entityId);
  3094. if (entity && entity->GetState() == AZ::Entity::State::Active)
  3095. {
  3096. entity->Deactivate();
  3097. }
  3098. }
  3099. }
  3100. }
  3101. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3102. AZStd::vector<AZ::EntityId> UiCanvasComponent::GetEntityIdsOfElementAndDescendants(AZ::Entity* entity)
  3103. {
  3104. AZStd::vector<AZ::EntityId> entitiesInPrefab;
  3105. entitiesInPrefab.push_back(entity->GetId());
  3106. LyShine::EntityArray descendantEntities;
  3107. UiElementBus::Event(
  3108. entity->GetId(),
  3109. &UiElementBus::Events::FindDescendantElements,
  3110. [](const AZ::Entity*)
  3111. {
  3112. return true;
  3113. },
  3114. descendantEntities);
  3115. for (auto descendant : descendantEntities)
  3116. {
  3117. entitiesInPrefab.push_back(descendant->GetId());
  3118. }
  3119. return entitiesInPrefab;
  3120. }
  3121. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3122. void UiCanvasComponent::SetTargetCanvasSizeAndUniformScale(bool isInGame, AZ::Vector2 canvasSize)
  3123. {
  3124. AZ::Vector2 oldTargetCanvasSize = m_targetCanvasSize;
  3125. AZ::Vector2 oldDeviceScale = m_deviceScale;
  3126. if (isInGame)
  3127. {
  3128. // Set the target canvas size to the canvas size specified by the caller
  3129. m_targetCanvasSize = canvasSize;
  3130. // set the device scale
  3131. m_deviceScale.SetX(m_targetCanvasSize.GetX() / m_canvasSize.GetX());
  3132. m_deviceScale.SetY(m_targetCanvasSize.GetY() / m_canvasSize.GetY());
  3133. }
  3134. else
  3135. {
  3136. // While in the editor, the only resolution we care about is the canvas' authored
  3137. // size, so we set that as our target size for display purposes.
  3138. m_targetCanvasSize = m_canvasSize;
  3139. }
  3140. // if the target canvas size or the uniform device scale changed then this will affect the
  3141. // element transforms so force them to recompute
  3142. if (oldTargetCanvasSize != m_targetCanvasSize || oldDeviceScale != m_deviceScale)
  3143. {
  3144. UiTransformInterface::Recompute recompute;
  3145. if (oldTargetCanvasSize != m_targetCanvasSize)
  3146. {
  3147. recompute = (oldDeviceScale != m_deviceScale) ? UiTransformInterface::Recompute::RectAndTransform : UiTransformInterface::Recompute::RectOnly;
  3148. }
  3149. else
  3150. {
  3151. recompute = UiTransformInterface::Recompute::TransformOnly;
  3152. }
  3153. UiTransformBus::Event(GetRootElement()->GetId(), &UiTransformBus::Events::SetRecomputeFlags, recompute);
  3154. UiCanvasSizeNotificationBus::Broadcast(&UiCanvasSizeNotificationBus::Events::OnCanvasSizeOrScaleChange, GetEntityId());
  3155. }
  3156. }
  3157. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3158. bool UiCanvasComponent::IsElementNameUnique(const AZStd::string& elementName, const LyShine::EntityArray& elements)
  3159. {
  3160. for (auto element : elements)
  3161. {
  3162. if (element->GetName() == elementName)
  3163. {
  3164. return false;
  3165. }
  3166. }
  3167. return true;
  3168. }
  3169. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3170. UiCanvasComponent::EntityComboBoxVec UiCanvasComponent::PopulateNavigableEntityList()
  3171. {
  3172. EntityComboBoxVec result;
  3173. // Add a first entry for "None"
  3174. result.push_back(AZStd::make_pair(AZ::EntityId(), "<None>"));
  3175. // Get a list of all navigable elements
  3176. LyShine::EntityArray navigableElements;
  3177. auto checkNavigable = [](const AZ::Entity* entity)
  3178. {
  3179. UiNavigationInterface::NavigationMode navigationMode = UiNavigationInterface::NavigationMode::None;
  3180. UiNavigationBus::EventResult(navigationMode, entity->GetId(), &UiNavigationBus::Events::GetNavigationMode);
  3181. return (navigationMode != UiNavigationInterface::NavigationMode::None);
  3182. };
  3183. FindElements(checkNavigable, navigableElements);
  3184. // Sort the elements by name
  3185. AZStd::sort(navigableElements.begin(), navigableElements.end(),
  3186. [](const AZ::Entity* e1, const AZ::Entity* e2) { return e1->GetName() < e2->GetName(); });
  3187. // Add their names to the StringList and their IDs to the id list
  3188. for (auto navigableEntity : navigableElements)
  3189. {
  3190. result.push_back(AZStd::make_pair(navigableEntity->GetId(), navigableEntity->GetName()));
  3191. }
  3192. return result;
  3193. }
  3194. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3195. UiCanvasComponent::EntityComboBoxVec UiCanvasComponent::PopulateTooltipDisplayEntityList()
  3196. {
  3197. EntityComboBoxVec result;
  3198. // Add a first entry for "None"
  3199. result.push_back(AZStd::make_pair(AZ::EntityId(), "<None>"));
  3200. // Get a list of all tooltip display elements
  3201. LyShine::EntityArray tooltipDisplayElements;
  3202. auto checkTooltipDisplay = [](const AZ::Entity* entity)
  3203. {
  3204. // Check for component on entity
  3205. return UiTooltipDisplayBus::FindFirstHandler(entity->GetId()) ? true : false;
  3206. };
  3207. FindElements(checkTooltipDisplay, tooltipDisplayElements);
  3208. // Sort the elements by name
  3209. AZStd::sort(tooltipDisplayElements.begin(), tooltipDisplayElements.end(),
  3210. [](const AZ::Entity* e1, const AZ::Entity* e2) { return e1->GetName() < e2->GetName(); });
  3211. // Add their names to the StringList and their IDs to the id list
  3212. for (auto tooltipDisplayEntity : tooltipDisplayElements)
  3213. {
  3214. result.push_back(AZStd::make_pair(tooltipDisplayEntity->GetId(), tooltipDisplayEntity->GetName()));
  3215. }
  3216. return result;
  3217. }
  3218. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3219. void UiCanvasComponent::OnPixelAlignmentChange()
  3220. {
  3221. UiCanvasPixelAlignmentNotificationBus::Event(
  3222. GetEntityId(), &UiCanvasPixelAlignmentNotificationBus::Events::OnCanvasPixelAlignmentChange);
  3223. }
  3224. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3225. void UiCanvasComponent::OnTextPixelAlignmentChange()
  3226. {
  3227. UiCanvasPixelAlignmentNotificationBus::Event(
  3228. GetEntityId(), &UiCanvasPixelAlignmentNotificationBus::Events::OnCanvasTextPixelAlignmentChange);
  3229. }
  3230. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3231. void UiCanvasComponent::CreateRenderTarget()
  3232. {
  3233. if (m_canvasSize.GetX() <= 0 || m_canvasSize.GetY() <= 0)
  3234. {
  3235. gEnv->pSystem->Warning(VALIDATOR_MODULE_SHINE, VALIDATOR_WARNING, VALIDATOR_FLAG_FILE,
  3236. m_pathname.c_str(),
  3237. "Invalid render target width/height for UI canvas: %s",
  3238. m_pathname.c_str());
  3239. return;
  3240. }
  3241. // Create a render target for the canvas
  3242. m_attachmentImageId = UseRenderTargetAsset(m_attachmentImageAsset);
  3243. AZ_Error("UI", !m_attachmentImageId.IsEmpty(), "Failed to acquire a render target for UI canvas: %s", m_pathname.c_str());
  3244. }
  3245. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3246. void UiCanvasComponent::DestroyRenderTarget()
  3247. {
  3248. if (!m_attachmentImageId.IsEmpty())
  3249. {
  3250. LyShine::RenderToTextureRequestBus::Event(GetEntityId(),
  3251. &LyShine::RenderToTextureRequestBus::Events::ReleaseRenderTarget, m_attachmentImageId);
  3252. m_attachmentImageId = AZ::RHI::AttachmentId{};
  3253. }
  3254. }
  3255. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3256. bool UiCanvasComponent::SaveCanvasToFile(const AZStd::string& pathname, AZ::DataStream::StreamType streamType)
  3257. {
  3258. // Note: This is ok for saving in tools, but we should use the streamer to write objects directly (no memory store)
  3259. AZStd::vector<AZ::u8> dstData;
  3260. AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8> > dstByteStream(&dstData);
  3261. if (!SaveCanvasToStream(dstByteStream, streamType))
  3262. {
  3263. return false;
  3264. }
  3265. AZ::IO::SystemFile file;
  3266. file.Open(pathname.c_str(), AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY);
  3267. if (!file.IsOpen())
  3268. {
  3269. file.Close();
  3270. return false;
  3271. }
  3272. file.Write(dstData.data(), dstData.size());
  3273. file.Close();
  3274. return true;
  3275. }
  3276. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3277. bool UiCanvasComponent::SaveCanvasToStream(AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType)
  3278. {
  3279. UiCanvasFileObject fileObject;
  3280. fileObject.m_canvasEntity = this->GetEntity();
  3281. AzFramework::RootSliceAsset rootSliceAsset;
  3282. AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSliceAsset, m_entityContext->GetContextId(),
  3283. &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::GetRootAsset);
  3284. fileObject.m_rootSliceEntity = rootSliceAsset->GetEntity();
  3285. if (!AZ::Utils::SaveObjectToStream<UiCanvasFileObject>(stream, streamType, &fileObject))
  3286. {
  3287. return false;
  3288. }
  3289. return true;
  3290. }
  3291. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3292. void UiCanvasComponent::SendRectChangeNotificationsAndRecomputeLayouts()
  3293. {
  3294. // Send canvas space rect change notifications. Handlers may mark
  3295. // layouts for a recompute
  3296. SendRectChangeNotifications();
  3297. // Recompute invalid layouts
  3298. if (m_layoutManager->HasMarkedLayouts())
  3299. {
  3300. m_layoutManager->RecomputeMarkedLayouts();
  3301. // The layout recompute may have caused child size changes, so
  3302. // send canvas space rect change notifications again
  3303. // NOTE: this is expensive so we don't do it unless there were marked layouts
  3304. SendRectChangeNotifications();
  3305. // Remove the newly marked layouts since they have been marked due
  3306. // to their parents recomputing them
  3307. m_layoutManager->UnmarkAllLayouts();
  3308. }
  3309. }
  3310. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3311. void UiCanvasComponent::SendRectChangeNotifications()
  3312. {
  3313. // While we know there are transforms that need re-computing
  3314. while (!m_elementsNeedingTransformRecompute.empty())
  3315. {
  3316. // get the front element from the list and remove it from the list
  3317. UiElementComponent& elementComponent = m_elementsNeedingTransformRecompute.front();
  3318. m_elementsNeedingTransformRecompute.pop_front();
  3319. elementComponent.m_next = nullptr; // needed in order to be able to test if an element is in the list.
  3320. // Get the transform component from the element and (if valid) recompute its transforms
  3321. UiTransform2dComponent* transformComponent = elementComponent.GetTransform2dComponent();
  3322. if (transformComponent)
  3323. {
  3324. // tell this transform to recompute (this can result in other elements being added to m_elementsNeedingTransformRecompute)
  3325. transformComponent->RecomputeTransformsAndSendNotifications();
  3326. }
  3327. }
  3328. }
  3329. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3330. void UiCanvasComponent::InitializeLayouts()
  3331. {
  3332. m_layoutManager->ComputeLayoutForElementAndDescendants(GetRootElement()->GetId());
  3333. }
  3334. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3335. void UiCanvasComponent::InGamePostActivateBottomUp(AZ::Entity* entity)
  3336. {
  3337. if (!entity)
  3338. {
  3339. return;
  3340. }
  3341. LyShine::EntityArray childElements;
  3342. UiElementBus::EventResult(childElements, entity->GetId(), &UiElementBus::Events::GetChildElements);
  3343. for (auto child : childElements)
  3344. {
  3345. InGamePostActivateBottomUp(child);
  3346. }
  3347. UiInitializationBus::Event(entity->GetId(), &UiInitializationBus::Events::InGamePostActivate);
  3348. }
  3349. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3350. AZ::Entity* UiCanvasComponent::CloneAndAddElementInternal(AZ::Entity* sourceEntity, AZ::Entity* parentEntity, AZ::Entity* insertBeforeEntity)
  3351. {
  3352. // first check that the given entity really is a UI element - i.e. it has a UiElementComponent
  3353. UiElementComponent* sourceElementComponent = sourceEntity->FindComponent<UiElementComponent>();
  3354. if (!sourceElementComponent)
  3355. {
  3356. AZ_Warning("UI", false, "CloneElement: The entity to be cloned must have an element component");
  3357. return nullptr;
  3358. }
  3359. // also check that the given parent entity is part of this canvas (if one is specified)
  3360. if (parentEntity)
  3361. {
  3362. AZ::EntityId parentCanvasId;
  3363. UiElementBus::EventResult(parentCanvasId, parentEntity->GetId(), &UiElementBus::Events::GetCanvasEntityId);
  3364. if (parentCanvasId != GetEntityId())
  3365. {
  3366. AZ_Warning("UI", false, "CloneElement: The parent entity must belong to this canvas");
  3367. return nullptr;
  3368. }
  3369. }
  3370. // If no parent entity specified then the parent is the root element
  3371. AZ::Entity* parent = (parentEntity) ? parentEntity : GetRootElement();
  3372. // also check that the given InsertBefore entity is a child of the parent
  3373. if (insertBeforeEntity)
  3374. {
  3375. AZ::Entity* insertBeforeParent;
  3376. UiElementBus::EventResult(insertBeforeParent, insertBeforeEntity->GetId(), &UiElementBus::Events::GetParent);
  3377. if (insertBeforeParent != parent)
  3378. {
  3379. AZ_Warning("UI", false, "CloneElement: The insertBefore entity must be a child of the parent");
  3380. return nullptr;
  3381. }
  3382. }
  3383. AZ::SerializeContext* context = nullptr;
  3384. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  3385. AZ_Assert(context, "No serialization context found");
  3386. AZStd::vector<AZ::EntityId> entitiesToClone = GetEntityIdsOfElementAndDescendants(sourceEntity);
  3387. AzFramework::EntityList clonedEntities;
  3388. m_entityContext->CloneUiEntities(entitiesToClone, clonedEntities);
  3389. AZ::Entity* clonedRootEntity = clonedEntities[0];
  3390. UiElementComponent* elementComponent = clonedRootEntity->FindComponent<UiElementComponent>();
  3391. AZ_Assert(elementComponent, "The cloned entity must have an element component");
  3392. // recursively set the canvas and parent pointers
  3393. elementComponent->FixupPostLoad(clonedRootEntity, this, parent, true);
  3394. // add this new entity as a child of the parent (parentEntity or root)
  3395. UiElementComponent* parentElementComponent = parent->FindComponent<UiElementComponent>();
  3396. AZ_Assert(parentElementComponent, "No element component found on parent entity");
  3397. parentElementComponent->AddChild(clonedRootEntity, insertBeforeEntity);
  3398. if (m_isLoadedInGame)
  3399. {
  3400. // Call InGamePostActivate on all the created entities
  3401. InGamePostActivateBottomUp(clonedRootEntity);
  3402. }
  3403. return clonedRootEntity;
  3404. }
  3405. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3406. void UiCanvasComponent::GetOrphanedElements(AZ::SliceComponent::EntityList& orphanedEntities)
  3407. {
  3408. AZ::SliceComponent::EntityList entities;
  3409. AZ::SliceComponent* rootSlice;
  3410. AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSlice, m_entityContext->GetContextId(),
  3411. &AzFramework::SliceEntityOwnershipServiceRequests::GetRootSlice);
  3412. rootSlice->GetEntities(entities);
  3413. // We want to quickly check that every UiElement entity is referenced from the canvas.
  3414. // We know that at this point all referenced elements have had FixupPostLoad called but
  3415. // and orphans would not have had it called.
  3416. // This means that referenced children have a non-null parent (except the root element).
  3417. // We can use this data to make a list of all orphaned children.
  3418. for (AZ::Entity* entity : entities)
  3419. {
  3420. AZ::Entity* parent = nullptr;
  3421. UiElementBus::EventResult(parent, entity->GetId(), &UiElementBus::Events::GetParent);
  3422. if (!parent)
  3423. {
  3424. if (m_rootElement != entity->GetId())
  3425. {
  3426. // This is an entity that is not referenced by the canvas.
  3427. // If it has a UiElementComponent on it then it is definitely an orphan
  3428. UiElementComponent* elementComponent = entity->FindComponent<UiElementComponent>();
  3429. if (elementComponent)
  3430. {
  3431. // Add to ths list of orphans
  3432. orphanedEntities.push_back(entity);
  3433. }
  3434. else
  3435. {
  3436. // This is some unknown entity. In theory the slice system could create such things but it does
  3437. // not appear to.
  3438. AZ_Warning("UI", false, "Found entity with no UiElementComponent in a UI canvas root slice.");
  3439. }
  3440. }
  3441. }
  3442. }
  3443. }
  3444. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3445. // PRIVATE STATIC MEMBER FUNCTIONS
  3446. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3447. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3448. AZ::u64 UiCanvasComponent::CreateUniqueId()
  3449. {
  3450. AZ::u64 utcTime = AZStd::GetTimeUTCMilliSecond();
  3451. uint32 r = cry_random_uint32();
  3452. AZ::u64 id = utcTime << 32 | r;
  3453. return id;
  3454. }
  3455. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3456. UiCanvasComponent* UiCanvasComponent::CreateCanvasInternal(UiEntityContext* entityContext, bool forEditor)
  3457. {
  3458. // create a new empty canvas, give it a name to avoid serialization generating one based on
  3459. // the ID (which in some cases caused diffs to fail in the editor)
  3460. AZ::Entity* canvasEntity = aznew AZ::Entity("UiCanvasEntity");
  3461. UiCanvasComponent* canvasComponent = canvasEntity->CreateComponent<UiCanvasComponent>();
  3462. // Initialize the UiEntityContext
  3463. canvasComponent->m_entityContext = entityContext;
  3464. canvasComponent->m_entityContext->InitUiContext();
  3465. // Give the canvas a unique identifier. Used for canvas metrics
  3466. canvasComponent->m_uniqueId = CreateUniqueId();
  3467. // This is the dummy root node of the canvas.
  3468. // It needs an element component and a transform component.
  3469. AZ::Entity* rootEntity = canvasComponent->m_entityContext->CreateEntity("_root");
  3470. canvasComponent->m_rootElement = rootEntity->GetId();
  3471. AZ_Assert(rootEntity, "Failed to create root element entity");
  3472. rootEntity->Deactivate(); // so we can add components
  3473. UiElementComponent* elementComponent = rootEntity->CreateComponent<UiElementComponent>();
  3474. AZ_Assert(elementComponent, "Failed to add UiElementComponent to entity");
  3475. elementComponent->SetCanvas(canvasComponent, canvasComponent->GenerateId());
  3476. [[maybe_unused]] AZ::Component* transformComponent = rootEntity->CreateComponent<UiTransform2dComponent>();
  3477. AZ_Assert(transformComponent, "Failed to add transform2d component to entity");
  3478. rootEntity->Activate(); // re-activate
  3479. // init the canvas entity (the canvas entity is not part of the EntityContext so is not automatically initialized)
  3480. canvasEntity->Init();
  3481. canvasEntity->Activate();
  3482. canvasComponent->m_isLoadedInGame = !forEditor;
  3483. return canvasComponent;
  3484. }
  3485. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3486. UiCanvasComponent* UiCanvasComponent::LoadCanvasInternal(const AZStd::string& pathnameToOpen, bool forEditor, const AZStd::string& assetIdPathname, UiEntityContext* entityContext,
  3487. const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable, AZ::EntityId previousCanvasId)
  3488. {
  3489. UiCanvasComponent* canvasComponent = nullptr;
  3490. // Currently LoadObjectFromFile will hang if the file cannot be parsed
  3491. // (LMBR-10078). So first check that it is in the right format
  3492. if (IsValidAzSerializedFile(pathnameToOpen))
  3493. {
  3494. // Open a stream on the input path
  3495. AZ::IO::FileIOStream stream(pathnameToOpen.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary);
  3496. if (!stream.IsOpen())
  3497. {
  3498. AZ_Warning("UI", false, "Cannot open UI canvas file \"%s\".", pathnameToOpen.c_str());
  3499. }
  3500. else
  3501. {
  3502. // Read in the canvas from the stream
  3503. UiCanvasFileObject* canvasFileObject = UiCanvasFileObject::LoadCanvasFromStream(stream);
  3504. AZ_Assert(canvasFileObject, "Failed to load canvas");
  3505. if (canvasFileObject)
  3506. {
  3507. AZ::Entity* canvasEntity = canvasFileObject->m_canvasEntity;
  3508. AZ::Entity* rootSliceEntity = canvasFileObject->m_rootSliceEntity;
  3509. AZ_Assert(canvasEntity && rootSliceEntity, "Failed to load canvas");
  3510. if (canvasEntity && rootSliceEntity)
  3511. {
  3512. // file loaded OK
  3513. // no need to check if a canvas with this EntityId is already loaded since we are going
  3514. // to generate new entity IDs for all entities loaded from the file.
  3515. // complete initialization of loaded entities
  3516. canvasComponent = FixupPostLoad(canvasEntity, rootSliceEntity, forEditor, entityContext, nullptr, previousRemapTable, previousCanvasId);
  3517. if (canvasComponent)
  3518. {
  3519. // The canvas size may get reset on the first call to RenderCanvas to set the size to
  3520. // viewport size. So we'll recompute again on first render.
  3521. UiTransformBus::Event(
  3522. canvasComponent->GetRootElement()->GetId(),
  3523. &UiTransformBus::Events::SetRecomputeFlags,
  3524. UiTransformInterface::Recompute::RectAndTransform);
  3525. canvasComponent->m_pathname = assetIdPathname;
  3526. canvasComponent->m_isLoadedInGame = !forEditor;
  3527. }
  3528. else
  3529. {
  3530. // cleanup, don't delete rootSliceEntity, deleting the canvasEntity cleans up the EntityContext and root slice
  3531. delete canvasEntity;
  3532. }
  3533. }
  3534. // UiCanvasFileObject is a simple container for the canvas pointers, its destructor
  3535. // doesn't destroy the canvas, but we need to delete it nonetheless to avoid leaking.
  3536. delete canvasFileObject;
  3537. }
  3538. }
  3539. }
  3540. else
  3541. {
  3542. // this file is not a valid canvas file
  3543. gEnv->pSystem->Warning(VALIDATOR_MODULE_SHINE, VALIDATOR_WARNING, VALIDATOR_FLAG_FILE,
  3544. pathnameToOpen.c_str(),
  3545. "Invalid XML format or couldn't load file for UI canvas file: %s",
  3546. pathnameToOpen.c_str());
  3547. }
  3548. return canvasComponent;
  3549. }
  3550. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3551. UiCanvasComponent* UiCanvasComponent::FixupReloadedCanvasForEditorInternal(AZ::Entity* newCanvasEntity,
  3552. AZ::Entity* rootSliceEntity, UiEntityContext* entityContext,
  3553. LyShine::CanvasId existingId, const AZStd::string& existingPathname)
  3554. {
  3555. UiCanvasComponent* newCanvasComponent = FixupPostLoad(newCanvasEntity, rootSliceEntity, true, entityContext);
  3556. if (newCanvasComponent)
  3557. {
  3558. newCanvasComponent->m_id = existingId;
  3559. newCanvasComponent->m_pathname = existingPathname;
  3560. }
  3561. return newCanvasComponent;
  3562. }
  3563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3564. UiCanvasComponent* UiCanvasComponent::FixupPostLoad(AZ::Entity* canvasEntity, AZ::Entity* rootSliceEntity, bool forEditor, UiEntityContext* entityContext, const AZ::Vector2* canvasSize,
  3565. const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable, AZ::EntityId previousCanvasId)
  3566. {
  3567. // When we load in game we always generate new entity IDs.
  3568. bool makeNewEntityIds = (forEditor) ? false : true;
  3569. // When we load in the editor, check if there is another canvas open that has the same entityId
  3570. if (forEditor)
  3571. {
  3572. AZ::Entity* foundEntity = nullptr;
  3573. AZ::ComponentApplicationBus::BroadcastResult(foundEntity, &AZ::ComponentApplicationBus::Events::FindEntity, canvasEntity->GetId());
  3574. if (foundEntity)
  3575. {
  3576. makeNewEntityIds = true;
  3577. }
  3578. }
  3579. UiCanvasComponent* canvasComponent = canvasEntity->FindComponent<UiCanvasComponent>();
  3580. AZ_Assert(canvasComponent, "No canvas component found on loaded entity");
  3581. if (!canvasComponent)
  3582. {
  3583. return nullptr; // unlikely to happen but perhaps possible if a non-canvas file was opened
  3584. }
  3585. // Initialize the entity context for the new canvas and init and activate all the entities
  3586. // in the root slice
  3587. canvasComponent->m_entityContext = entityContext;
  3588. canvasComponent->m_entityContext->InitUiContext();
  3589. // Load atlases before initializing child components
  3590. canvasComponent->LoadAtlases();
  3591. bool isLoadingRootEntitySuccessful = false;
  3592. if (previousRemapTable)
  3593. {
  3594. // We are reloading a canvas and we want to use the same entity ID mapping (from editor entity to game entity) as in the previously
  3595. // loaded canvas. The code below is similar to what HandleLoadedRootSliceEntity does for remapping except that if the existing
  3596. // mapping table already contains an entry for an editor entity ID it will use the existing mapping
  3597. AZ::SliceComponent* newRootSlice = rootSliceEntity->FindComponent<AZ::SliceComponent>();
  3598. AZ::SerializeContext* context = nullptr;
  3599. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  3600. AZ_Assert(context, "No serialization context found");
  3601. AZ::SliceComponent::InstantiatedContainer entityContainer(false);
  3602. newRootSlice->GetEntities(entityContainer.m_entities);
  3603. canvasComponent->m_editorToGameEntityIdMap = *previousRemapTable;
  3604. ReuseOrGenerateNewIdsAndFixRefs(&entityContainer, canvasComponent->m_editorToGameEntityIdMap, context);
  3605. AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(isLoadingRootEntitySuccessful,
  3606. canvasComponent->m_entityContext->GetContextId(),
  3607. &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::HandleRootEntityReloadedFromStream, rootSliceEntity, false, nullptr);
  3608. if (!isLoadingRootEntitySuccessful)
  3609. {
  3610. return nullptr;
  3611. }
  3612. }
  3613. else
  3614. {
  3615. // we are not reloading a canvas so we let the EntityContext HandleLoadedRootSliceEntity do the entity ID remapping as usual
  3616. AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(isLoadingRootEntitySuccessful,
  3617. canvasComponent->m_entityContext->GetContextId(),
  3618. &AzFramework::SliceEntityOwnershipServiceRequestBus::Events::HandleRootEntityReloadedFromStream, rootSliceEntity,
  3619. makeNewEntityIds, &canvasComponent->m_editorToGameEntityIdMap);
  3620. if (!isLoadingRootEntitySuccessful)
  3621. {
  3622. return nullptr;
  3623. }
  3624. }
  3625. // For the canvas entity itself, handle ID mapping and initialization
  3626. {
  3627. if (previousCanvasId.IsValid())
  3628. {
  3629. canvasEntity->SetId(previousCanvasId);
  3630. }
  3631. else if (makeNewEntityIds)
  3632. {
  3633. AZ::EntityId newId = AZ::Entity::MakeId();
  3634. canvasEntity->SetId(newId);
  3635. }
  3636. // remap entity IDs such as m_rootElement and any entity IDs in the animation data
  3637. if (makeNewEntityIds)
  3638. {
  3639. // new IDs were generated so we should fix up any internal EntityRefs
  3640. AZ::SerializeContext* context = nullptr;
  3641. AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  3642. AZ_Assert(context, "No serialization context found");
  3643. ReuseOrGenerateNewIdsAndFixRefs(canvasEntity, canvasComponent->m_editorToGameEntityIdMap, context);
  3644. }
  3645. canvasEntity->Init();
  3646. canvasEntity->Activate();
  3647. }
  3648. AZ::Entity* rootElement = canvasComponent->GetRootElement();
  3649. UiElementComponent* elementComponent = rootElement->FindComponent<UiElementComponent>();
  3650. AZ_Assert(elementComponent, "No element component found on root element entity");
  3651. // Need to remapIds too (actually I don't think this needs to remap anymore)
  3652. canvasComponent->RestoreAnimationSystemAfterCanvasLoad(makeNewEntityIds, &canvasComponent->m_editorToGameEntityIdMap);
  3653. bool fixupSuccess = elementComponent->FixupPostLoad(rootElement, canvasComponent, nullptr, false);
  3654. if (!fixupSuccess)
  3655. {
  3656. return nullptr;
  3657. }
  3658. // Initialize the target canvas size and uniform scale
  3659. // This should be done before calling InGamePostActivate so that the
  3660. // canvas space rects of the elements are accurate
  3661. UiRenderer* uiRenderer = forEditor ? GetUiRendererForEditor() : GetUiRendererForGame();
  3662. if (uiRenderer) // can be null in automated testing
  3663. {
  3664. AZ::Vector2 targetCanvasSize;
  3665. if (canvasSize)
  3666. {
  3667. targetCanvasSize = *canvasSize;
  3668. }
  3669. else
  3670. {
  3671. targetCanvasSize = uiRenderer->GetViewportSize();
  3672. }
  3673. canvasComponent->SetTargetCanvasSizeAndUniformScale(!forEditor, targetCanvasSize);
  3674. }
  3675. // Set this before calling InGamePostActivate on the created entities. InGamePostActivate could
  3676. // call CloneElement which checks this flag
  3677. canvasComponent->m_isLoadedInGame = !forEditor;
  3678. // Initialize transform properties of children of layout elements
  3679. canvasComponent->InitializeLayouts();
  3680. if (!forEditor)
  3681. {
  3682. // Call InGamePostActivate on all the created entities when loading in game
  3683. canvasComponent->InGamePostActivateBottomUp(rootElement);
  3684. }
  3685. // Set the first hover interactable
  3686. if (canvasComponent->m_isNavigationSupported)
  3687. {
  3688. canvasComponent->SetFirstHoverInteractable();
  3689. }
  3690. return canvasComponent;
  3691. }
  3692. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3693. bool UiCanvasComponent::VersionConverter(AZ::SerializeContext& context,
  3694. AZ::SerializeContext::DataElementNode& classElement)
  3695. {
  3696. // conversion from version 1 to 2:
  3697. if (classElement.GetVersion() < 2)
  3698. {
  3699. // No need to actually convert anything because the CanvasFileObject takes care of it
  3700. // But it makes sense to bump the version number because the m_rootElement is now an EntityId
  3701. // rather than an Entity*
  3702. }
  3703. // conversion from version 2 to 3:
  3704. // - Need to convert Vec2 to AZ::Vector2
  3705. if (classElement.GetVersion() < 3)
  3706. {
  3707. if (!LyShine::ConvertSubElementFromVec2ToVector2(context, classElement, "CanvasSize"))
  3708. {
  3709. return false;
  3710. }
  3711. }
  3712. // conversion from version 3 to 4:
  3713. // - Need to remove render target name as it was replaced with attachment image asset
  3714. if (classElement.GetVersion() < 4)
  3715. {
  3716. if (!LyShine::RemoveRenderTargetAsString(context, classElement, "RenderTargetName"))
  3717. {
  3718. return false;
  3719. }
  3720. }
  3721. return true;
  3722. }