UiCanvasManager.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  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 "UiCanvasManager.h"
  9. #include <LyShine/IDraw2d.h>
  10. #include "UiCanvasFileObject.h"
  11. #include "UiCanvasComponent.h"
  12. #include "UiGameEntityContext.h"
  13. #include <CryCommon/StlUtils.h>
  14. #include <LyShine/UiSerializeHelpers.h>
  15. #include <AzCore/Memory/Memory.h>
  16. #include <AzCore/Component/ComponentApplicationBus.h>
  17. #include <AzCore/Component/TickBus.h>
  18. #include <AzCore/Asset/AssetManagerBus.h>
  19. #include <AzFramework/API/ApplicationAPI.h>
  20. #include <AzFramework/Input/Channels/InputChannel.h>
  21. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  22. #include <AzFramework/StringFunc/StringFunc.h>
  23. #include <AzFramework/Viewport/CameraState.h>
  24. #include <AzFramework/Viewport/ViewportScreen.h>
  25. #include <LyShine/Bus/UiCursorBus.h>
  26. #include <LyShine/Bus/World/UiCanvasOnMeshBus.h>
  27. #include <LyShine/Bus/World/UiCanvasRefBus.h>
  28. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  29. #include <Atom/RPI.Public/View.h>
  30. #ifndef _RELEASE
  31. #include <AzFramework/IO/LocalFileIO.h>
  32. #endif
  33. #include <AzFramework/Entity/GameEntityContextBus.h>
  34. #include <AzFramework/Render/Intersector.h>
  35. #include <MathConversion.h>
  36. #include "LyShine.h"
  37. ////////////////////////////////////////////////////////////////////////////////////////////////////
  38. // Anonymous namespace
  39. ////////////////////////////////////////////////////////////////////////////////////////////////////
  40. namespace
  41. {
  42. ////////////////////////////////////////////////////////////////////////////////////////////////
  43. // Compare function used for sorting
  44. bool CompareCanvasDrawOrder(UiCanvasComponent* a, UiCanvasComponent* b)
  45. {
  46. return a->GetDrawOrder() < b->GetDrawOrder();
  47. }
  48. ////////////////////////////////////////////////////////////////////////////////////////////////
  49. // Transform the pathname so that a) it works for opening a file that could be in a Gem or in
  50. // a pak file, and b) so that it is in a consistent form that can be used for string comparison
  51. AZStd::string GetAssePathFromUserDefinedPath(const AZStd::string& userPath)
  52. {
  53. if (userPath.empty())
  54. {
  55. AZ_Warning("UI", false, "Given UI canvas path is empty.")
  56. return userPath;
  57. }
  58. AZStd::string assetPath = userPath;
  59. // Check if extension needs to be fixed up
  60. const AZStd::string canvasExtension("uicanvas");
  61. bool validExtension = AzFramework::StringFunc::Path::IsExtension(assetPath.c_str(), canvasExtension.c_str(), true);
  62. if (!validExtension)
  63. {
  64. // Fix extension
  65. AZ_Warning("UI", !AzFramework::StringFunc::Path::HasExtension(assetPath.c_str()), "Given UI canvas path \"%s\" has an invalid extension. Replacing extension with \"%s\".",
  66. userPath.c_str(), canvasExtension.c_str());
  67. AzFramework::StringFunc::Path::ReplaceExtension(assetPath, canvasExtension.c_str());
  68. }
  69. // Normalize path
  70. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::Bus::Events::NormalizePathKeepCase, assetPath);
  71. // Check for any leading slashes as the specified path should be a relative path to the @products@ alias.
  72. // This eliminates inconsistencies between lower level file opens on different platforms
  73. int numCharsToErase = 0;
  74. for (; numCharsToErase < assetPath.length(); ++numCharsToErase)
  75. {
  76. if (assetPath[numCharsToErase] != '/')
  77. {
  78. break;
  79. }
  80. }
  81. if (numCharsToErase > 0)
  82. {
  83. // Remove leading slashes
  84. AZ_Warning("UI", false, "Given UI canvas path \"%s\" has invalid leading slashes that make the path not relative. "
  85. "Removing the invalid leading slashes.", userPath.c_str());
  86. assetPath.erase(0, numCharsToErase);
  87. }
  88. return assetPath;
  89. }
  90. }
  91. ////////////////////////////////////////////////////////////////////////////////////////////////////
  92. // PUBLIC MEMBER FUNCTIONS
  93. ////////////////////////////////////////////////////////////////////////////////////////////////////
  94. ////////////////////////////////////////////////////////////////////////////////////////////////////
  95. UiCanvasManager::UiCanvasManager()
  96. : m_latestViewportSize(UiCanvasComponent::s_defaultCanvasSize)
  97. , m_localUserIdInputFilter(AzFramework::LocalUserIdAny)
  98. {
  99. UiCanvasManagerBus::Handler::BusConnect();
  100. UiCanvasOrderNotificationBus::Handler::BusConnect();
  101. UiCanvasEnabledStateNotificationBus::Handler::BusConnect();
  102. FontNotificationBus::Handler::BusConnect();
  103. AzFramework::AssetCatalogEventBus::Handler::BusConnect();
  104. }
  105. ////////////////////////////////////////////////////////////////////////////////////////////////////
  106. UiCanvasManager::~UiCanvasManager()
  107. {
  108. UiCanvasManagerBus::Handler::BusDisconnect();
  109. UiCanvasOrderNotificationBus::Handler::BusDisconnect();
  110. UiCanvasEnabledStateNotificationBus::Handler::BusDisconnect();
  111. FontNotificationBus::Handler::BusDisconnect();
  112. AzFramework::AssetCatalogEventBus::Handler::BusDisconnect();
  113. // destroy ALL the loaded canvases, whether loaded in game or in Editor
  114. for (auto canvas : (m_loadedCanvases))
  115. {
  116. delete canvas->GetEntity();
  117. }
  118. for (auto canvas : (m_loadedCanvasesInEditor))
  119. {
  120. delete canvas->GetEntity();
  121. }
  122. AZ_Assert(m_recursionGuardCount == 0, "Destroying the UiCanvasManager while it is processing canvases");
  123. DeleteCanvasesQueuedForDeletion();
  124. }
  125. ////////////////////////////////////////////////////////////////////////////////////////////////////
  126. AZ::EntityId UiCanvasManager::CreateCanvas()
  127. {
  128. // Prevent in-game canvas from being created when we are in the editor in a simulation mode
  129. // but not in game mode (ex. AI/Physics mode or Preview mode)
  130. if (gEnv && gEnv->IsEditor() && gEnv->IsEditing())
  131. {
  132. return AZ::EntityId();
  133. }
  134. UiGameEntityContext* entityContext = new UiGameEntityContext();
  135. UiCanvasComponent* canvasComponent = UiCanvasComponent::CreateCanvasInternal(entityContext, false);
  136. m_loadedCanvases.push_back(canvasComponent);
  137. SortCanvasesByDrawOrder();
  138. // The game entity context needs to know its corresponding canvas entity for instantiating dynamic slices
  139. entityContext->SetCanvasEntity(canvasComponent->GetEntityId());
  140. // When we create a canvas in game we want it to have the correct viewport size from the first frame rather
  141. // than having to wait a frame to have it updated
  142. canvasComponent->SetTargetCanvasSize(true, m_latestViewportSize);
  143. return canvasComponent->GetEntityId();
  144. }
  145. ////////////////////////////////////////////////////////////////////////////////////////////////////
  146. AZ::EntityId UiCanvasManager::LoadCanvas(const AZStd::string& assetIdPathname)
  147. {
  148. // Prevent canvas from being loaded when we are in the editor in a simulation mode
  149. // but not in game mode (ex. AI/Physics mode or Preview mode).
  150. // NOTE: Normal Preview mode load does not come through here since we clone the canvas rather than load it
  151. if (gEnv && gEnv->IsEditor() && gEnv->IsEditing())
  152. {
  153. return AZ::EntityId();
  154. }
  155. UiGameEntityContext* entityContext = new UiGameEntityContext();
  156. AZ::EntityId canvasEntityId = LoadCanvasInternal(assetIdPathname, false, "", entityContext);
  157. if (!canvasEntityId.IsValid())
  158. {
  159. delete entityContext;
  160. }
  161. else
  162. {
  163. // The game entity context needs to know its corresponding canvas entity for instantiating dynamic slices
  164. entityContext->SetCanvasEntity(canvasEntityId);
  165. UiCanvasManagerNotificationBus::Broadcast(&UiCanvasManagerNotificationBus::Events::OnCanvasLoaded, canvasEntityId);
  166. }
  167. return canvasEntityId;
  168. }
  169. ////////////////////////////////////////////////////////////////////////////////////////////////////
  170. void UiCanvasManager::UnloadCanvas(AZ::EntityId canvasEntityId)
  171. {
  172. ReleaseCanvasDeferred(canvasEntityId);
  173. }
  174. ////////////////////////////////////////////////////////////////////////////////////////////////////
  175. AZ::EntityId UiCanvasManager::FindLoadedCanvasByPathName(const AZStd::string& assetIdPathName, bool loadIfNotFound)
  176. {
  177. // this is only used for finding canvases loaded in game
  178. UiCanvasComponent* canvasComponent = FindCanvasComponentByPathname(assetIdPathName.c_str());
  179. AZ::EntityId canvasId = canvasComponent ? canvasComponent->GetEntityId() : AZ::EntityId();
  180. if (!canvasId.IsValid() && loadIfNotFound)
  181. {
  182. canvasId = LoadCanvas(assetIdPathName);
  183. }
  184. return canvasId;
  185. }
  186. ////////////////////////////////////////////////////////////////////////////////////////////////////
  187. UiCanvasManager::CanvasEntityList UiCanvasManager::GetLoadedCanvases()
  188. {
  189. CanvasEntityList list;
  190. for (auto canvasComponent : m_loadedCanvases)
  191. {
  192. list.push_back(canvasComponent->GetEntityId());
  193. }
  194. return list;
  195. }
  196. ////////////////////////////////////////////////////////////////////////////////////////////////////
  197. void UiCanvasManager::SetLocalUserIdInputFilterForAllCanvases(AzFramework::LocalUserId localUserId)
  198. {
  199. m_localUserIdInputFilter = localUserId;
  200. for (auto canvasComponent : m_loadedCanvases)
  201. {
  202. canvasComponent->SetLocalUserIdInputFilter(m_localUserIdInputFilter);
  203. }
  204. }
  205. ////////////////////////////////////////////////////////////////////////////////////////////////////
  206. void UiCanvasManager::OnCanvasDrawOrderChanged([[maybe_unused]] AZ::EntityId canvasEntityId)
  207. {
  208. SortCanvasesByDrawOrder();
  209. }
  210. ////////////////////////////////////////////////////////////////////////////////////////////////////
  211. void UiCanvasManager::OnCanvasEnabledStateChanged(AZ::EntityId canvasEntityId, bool enabled)
  212. {
  213. if (enabled)
  214. {
  215. bool isConsumingAllInputEvents = false;
  216. UiCanvasBus::EventResult(isConsumingAllInputEvents, canvasEntityId, &UiCanvasBus::Events::GetIsConsumingAllInputEvents);
  217. if (isConsumingAllInputEvents)
  218. {
  219. AzFramework::InputChannelRequestBus::Broadcast(&AzFramework::InputChannelRequests::ResetState);
  220. UiCanvasBus::Broadcast(&UiCanvasBus::Events::ClearAllInteractables);
  221. }
  222. }
  223. // Update hover state for loaded canvases
  224. m_generateMousePositionInputEvent = true;
  225. }
  226. ////////////////////////////////////////////////////////////////////////////////////////////////////
  227. void UiCanvasManager::GenerateMousePositionInputEvent()
  228. {
  229. const AzFramework::InputDevice* mouseDevice = AzFramework::InputDeviceRequests::FindInputDevice(AzFramework::InputDeviceMouse::Id);
  230. if (mouseDevice && mouseDevice->IsConnected())
  231. {
  232. // Create a game input event for the system cursor position
  233. const AzFramework::InputChannel::Snapshot inputSnapshot(AzFramework::InputDeviceMouse::SystemCursorPosition,
  234. AzFramework::InputDeviceMouse::Id,
  235. AzFramework::InputChannel::State::Updated);
  236. // Get the current system cursor viewport position
  237. AZ::Vector2 systemCursorPositionNormalized(0.0f, 0.0f);
  238. AzFramework::InputSystemCursorRequestBus::EventResult(systemCursorPositionNormalized,
  239. AzFramework::InputDeviceMouse::Id,
  240. &AzFramework::InputSystemCursorRequests::GetSystemCursorPositionNormalized);
  241. AZ::Vector2 cursorViewportPos(systemCursorPositionNormalized.GetX() * m_latestViewportSize.GetX(),
  242. systemCursorPositionNormalized.GetY() * m_latestViewportSize.GetY());
  243. // Handle the input event
  244. HandleInputEventForLoadedCanvases(inputSnapshot, cursorViewportPos, AzFramework::ModifierKeyMask::None, true);
  245. }
  246. }
  247. ////////////////////////////////////////////////////////////////////////////////////////////////////
  248. void UiCanvasManager::OnFontsReloaded()
  249. {
  250. m_fontTextureHasChanged = true;
  251. }
  252. ////////////////////////////////////////////////////////////////////////////////////////////////////
  253. void UiCanvasManager::OnFontTextureUpdated([[maybe_unused]] IFFont* font)
  254. {
  255. m_fontTextureHasChanged = true;
  256. }
  257. ////////////////////////////////////////////////////////////////////////////////////////////////////
  258. void UiCanvasManager::GetRenderTargets(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies)
  259. {
  260. for (auto canvas : m_loadedCanvases)
  261. {
  262. LyShine::AttachmentImagesAndDependencies canvasTargets;
  263. canvas->GetRenderTargets(canvasTargets);
  264. attachmentImagesAndDependencies.insert(attachmentImagesAndDependencies.end(), canvasTargets.begin(), canvasTargets.end());
  265. }
  266. }
  267. ////////////////////////////////////////////////////////////////////////////////////////////////////
  268. void UiCanvasManager::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId)
  269. {
  270. // get AssetInfo from asset id
  271. AZ::Data::AssetInfo assetInfo;
  272. AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId);
  273. if (assetInfo.m_assetType != LyShine::CanvasAsset::TYPEINFO_Uuid())
  274. {
  275. // this is not a UI canvas asset
  276. return;
  277. }
  278. // get pathname from asset id
  279. AZStd::string assetPath;
  280. AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetPath, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetPathById, assetId);
  281. CanvasList reloadedCanvases; // keep track of the reloaded canvases and add them to m_loadedCanvases after the loop
  282. AZStd::vector<AZ::EntityId> unloadedCanvases; // also keep track of any canvases that fail to reload and are unloaded
  283. // loop over all canvases loaded in game and reload any canvases loaded from this canvas asset
  284. // NOTE: this could be improved by using AssetId for the comparison rather than pathnames
  285. auto iter = m_loadedCanvases.begin();
  286. while (iter != m_loadedCanvases.end())
  287. {
  288. UiCanvasComponent* canvasComponent = *iter;
  289. if (assetPath == canvasComponent->GetPathname())
  290. {
  291. AZ::EntityId existingCanvasEntityId = canvasComponent->GetEntityId();
  292. //Before unloading the existing canvas, make a copy of its mapping table
  293. AZ::SliceComponent::EntityIdToEntityIdMap existingRemapTable = canvasComponent->GetEditorToGameEntityIdMap();
  294. // unload the canvas, just deleting the canvas entity does this
  295. AZ::Entity* existingCanvasEntity = canvasComponent->GetEntity();
  296. delete existingCanvasEntity;
  297. // Remove the deleted canvas entry in the m_loadedCanvases vector and move the iterator to the next
  298. iter = m_loadedCanvases.erase(iter);
  299. // reload canvas with the same entity IDs (except for new entities, deleted entities etc)
  300. UiGameEntityContext* entityContext = new UiGameEntityContext();
  301. AZStd::string pathname(assetPath.c_str());
  302. UiCanvasComponent* newCanvasComponent = UiCanvasComponent::LoadCanvasInternal(pathname, false, "", entityContext, &existingRemapTable, existingCanvasEntityId);
  303. if (!newCanvasComponent)
  304. {
  305. delete entityContext;
  306. unloadedCanvases.push_back(existingCanvasEntityId);
  307. }
  308. else
  309. {
  310. // The game entity context needs to know its corresponding canvas entity for instantiating dynamic slices
  311. entityContext->SetCanvasEntity(newCanvasComponent->GetEntityId());
  312. reloadedCanvases.push_back(newCanvasComponent);
  313. }
  314. }
  315. else
  316. {
  317. ++iter; // we did not delete this canvas - move to next in list
  318. }
  319. }
  320. // add the successfully reloaded canvases at the end
  321. m_loadedCanvases.insert(m_loadedCanvases.end(), reloadedCanvases.begin(), reloadedCanvases.end());
  322. // In case any draw orders changed resort
  323. SortCanvasesByDrawOrder();
  324. // notify any listeners of any UI canvases that were reloaded
  325. for (auto reloadedCanvasComponent : reloadedCanvases)
  326. {
  327. UiCanvasManagerNotificationBus::Broadcast(
  328. &UiCanvasManagerNotificationBus::Events::OnCanvasReloaded, reloadedCanvasComponent->GetEntityId());
  329. }
  330. // notify any listeners of any UI canvases that were unloaded
  331. for (auto unloadedCanvas : unloadedCanvases)
  332. {
  333. UiCanvasManagerNotificationBus::Broadcast(&UiCanvasManagerNotificationBus::Events::OnCanvasUnloaded, unloadedCanvas);
  334. }
  335. }
  336. ////////////////////////////////////////////////////////////////////////////////////////////////////
  337. AZ::EntityId UiCanvasManager::CreateCanvasInEditor(UiEntityContext* entityContext)
  338. {
  339. UiCanvasComponent* canvasComponent = UiCanvasComponent::CreateCanvasInternal(entityContext, true);
  340. m_loadedCanvasesInEditor.push_back(canvasComponent);
  341. return canvasComponent->GetEntityId();
  342. }
  343. ////////////////////////////////////////////////////////////////////////////////////////////////////
  344. AZ::EntityId UiCanvasManager::LoadCanvasInEditor(const AZStd::string& assetIdPathname, const AZStd::string& sourceAssetPathname, UiEntityContext* entityContext)
  345. {
  346. return LoadCanvasInternal(assetIdPathname.c_str(), true, sourceAssetPathname.c_str(), entityContext);
  347. }
  348. ////////////////////////////////////////////////////////////////////////////////////////////////////
  349. AZ::EntityId UiCanvasManager::ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext)
  350. {
  351. // Load new canvas from xml
  352. AZ::IO::MemoryStream memoryStream(xmlString.c_str(), xmlString.size());
  353. AZ::Entity* rootSliceEntity = nullptr;
  354. AZ::Entity* newCanvasEntity = UiCanvasFileObject::LoadCanvasEntitiesFromStream(memoryStream, rootSliceEntity);
  355. if (newCanvasEntity && rootSliceEntity)
  356. {
  357. // Find the old canvas to replace
  358. UiCanvasComponent* oldCanvasComponent = nullptr;
  359. for (auto canvas : (m_loadedCanvasesInEditor))
  360. {
  361. if (canvas->GetEntityId() == newCanvasEntity->GetId())
  362. {
  363. oldCanvasComponent = canvas;
  364. break;
  365. }
  366. }
  367. AZ_Assert(oldCanvasComponent, "Canvas not found");
  368. if (oldCanvasComponent)
  369. {
  370. LyShine::CanvasId oldCanvasId = oldCanvasComponent->GetCanvasId();
  371. const AZStd::string oldPathname = oldCanvasComponent->GetPathname();
  372. AZ::Matrix4x4 oldCanvasToViewportMatrix = oldCanvasComponent->GetCanvasToViewportMatrix();
  373. // Delete the old canvas. We assume this is for editor
  374. ReleaseCanvas(oldCanvasComponent->GetEntityId(), true);
  375. // Complete initialization of new canvas. We assume this is for editor
  376. UiCanvasComponent* newCanvasComponent = UiCanvasComponent::FixupReloadedCanvasForEditorInternal(
  377. newCanvasEntity, rootSliceEntity, entityContext, oldCanvasId, oldPathname);
  378. newCanvasComponent->SetCanvasToViewportMatrix(oldCanvasToViewportMatrix);
  379. // Add new canvas to the list of loaded canvases
  380. m_loadedCanvasesInEditor.push_back(newCanvasComponent);
  381. return newCanvasComponent->GetEntityId();
  382. }
  383. else
  384. {
  385. delete newCanvasEntity;
  386. }
  387. }
  388. return AZ::EntityId();
  389. }
  390. ////////////////////////////////////////////////////////////////////////////////////////////////////
  391. void UiCanvasManager::ReleaseCanvas(AZ::EntityId canvasEntityId, bool forEditor)
  392. {
  393. if(!canvasEntityId.IsValid())
  394. {
  395. AZ_Warning("UI", false, "%s has been invoked with an Invalid Canvas Entity ID. No Canvas can be released", AZ_FUNCTION_SIGNATURE);
  396. return;
  397. }
  398. // if we are currently processing canvases for input handling or update then defer the deletion of the canvas
  399. if (!forEditor && m_recursionGuardCount > 0)
  400. {
  401. ReleaseCanvasDeferred(canvasEntityId);
  402. return;
  403. }
  404. AZ::Entity* canvasEntity = nullptr;
  405. AZ::ComponentApplicationBus::BroadcastResult(canvasEntity, &AZ::ComponentApplicationBus::Events::FindEntity, canvasEntityId);
  406. AZ_Assert(canvasEntity, "Canvas entity not found by ID");
  407. if (canvasEntity)
  408. {
  409. UiCanvasComponent* canvasComponent = canvasEntity->FindComponent<UiCanvasComponent>();
  410. AZ_Assert(canvasComponent, "Canvas entity has no canvas component");
  411. if (canvasComponent)
  412. {
  413. if (forEditor)
  414. {
  415. stl::find_and_erase(m_loadedCanvasesInEditor, canvasComponent);
  416. delete canvasEntity;
  417. }
  418. else
  419. {
  420. stl::find_and_erase(m_loadedCanvases, canvasComponent);
  421. delete canvasEntity;
  422. UiCanvasManagerNotificationBus::Broadcast(&UiCanvasManagerNotificationBus::Events::OnCanvasUnloaded, canvasEntityId);
  423. // Update hover state for loaded canvases
  424. m_generateMousePositionInputEvent = true;
  425. }
  426. }
  427. }
  428. }
  429. ////////////////////////////////////////////////////////////////////////////////////////////////////
  430. void UiCanvasManager::ReleaseCanvasDeferred(AZ::EntityId canvasEntityId)
  431. {
  432. if (!canvasEntityId.IsValid())
  433. {
  434. AZ_Warning("UI", false, "%s has been invoked with an Invalid Canvas Entity ID. No Canvas can be released", AZ_FUNCTION_SIGNATURE);
  435. return;
  436. }
  437. AZ::Entity* canvasEntity = nullptr;
  438. AZ::ComponentApplicationBus::BroadcastResult(canvasEntity, &AZ::ComponentApplicationBus::Events::FindEntity, canvasEntityId);
  439. AZ_Assert(canvasEntity, "Canvas entity not found by ID");
  440. if (canvasEntity)
  441. {
  442. UiCanvasComponent* canvasComponent = canvasEntity->FindComponent<UiCanvasComponent>();
  443. AZ_Assert(canvasComponent, "Canvas entity has no canvas component");
  444. if (canvasComponent)
  445. {
  446. // Remove canvas component from list of loaded canvases
  447. stl::find_and_erase(m_loadedCanvases, canvasComponent);
  448. // Deactivate elements of the canvas
  449. canvasComponent->DeactivateElements();
  450. // Deactivate the canvas element
  451. canvasEntity->Deactivate();
  452. UiCanvasManagerNotificationBus::Broadcast(&UiCanvasManagerNotificationBus::Events::OnCanvasUnloaded, canvasEntityId);
  453. // Queue UI canvas deletion. This is because this function could have been triggered in input processing of
  454. // a component within the canvas. i.e. there could be a member function of the canvas or one of it's child entities
  455. // on the callstack. Unfortunately, just delaying until the next tick is not enough - pressing a button could cause
  456. // unloading of an entire level which could flush the tick bus. So we have to use our own queue.
  457. QueueCanvasForDeletion(canvasEntityId);
  458. // Update hover state for loaded canvases
  459. m_generateMousePositionInputEvent = true;
  460. }
  461. }
  462. }
  463. ////////////////////////////////////////////////////////////////////////////////////////////////////
  464. AZ::EntityId UiCanvasManager::FindCanvasById(LyShine::CanvasId id)
  465. {
  466. // this is only used for finding canvases loaded in game
  467. for (auto canvas : m_loadedCanvases)
  468. {
  469. if (canvas->GetCanvasId() == id)
  470. {
  471. return canvas->GetEntityId();
  472. }
  473. }
  474. return AZ::EntityId();
  475. }
  476. ////////////////////////////////////////////////////////////////////////////////////////////////////
  477. void UiCanvasManager::SetTargetSizeForLoadedCanvases(AZ::Vector2 viewportSize)
  478. {
  479. for (auto canvas : m_loadedCanvases)
  480. {
  481. canvas->SetTargetCanvasSize(true, viewportSize);
  482. }
  483. m_latestViewportSize = viewportSize;
  484. }
  485. ////////////////////////////////////////////////////////////////////////////////////////////////////
  486. void UiCanvasManager::UpdateLoadedCanvases(float deltaTime)
  487. {
  488. // make a temporary copy of the list in case the update code ends up releasing or loading canvases during iterating over the list
  489. auto loadedCanvases = m_loadedCanvases;
  490. // Update all the canvases loaded in game.
  491. // It is unlikely this will call out to client code that could remove a canvas but we have no
  492. // control over what custom components do so we increment the count that will defer all canvas deletion
  493. m_recursionGuardCount++;
  494. if (m_generateMousePositionInputEvent)
  495. {
  496. // Update hover state for loaded canvases
  497. m_generateMousePositionInputEvent = false;
  498. GenerateMousePositionInputEvent();
  499. }
  500. for (auto canvas : loadedCanvases)
  501. {
  502. canvas->UpdateCanvas(deltaTime, true);
  503. }
  504. m_recursionGuardCount--;
  505. // If not being called recursively from other canvas processing then immediately do any deferred canvas deletes
  506. DeleteCanvasesQueuedForDeletion();
  507. }
  508. ////////////////////////////////////////////////////////////////////////////////////////////////////
  509. void UiCanvasManager::RenderLoadedCanvases()
  510. {
  511. // Render all the canvases loaded in game
  512. // canvases loaded in editor are rendered by the viewport window
  513. // If any font texture has changed we force all canvases to rebuild the render graph. Individual text components
  514. // that use this font will also have got the notification and will have set a flag in their render cache
  515. // to indicate that the font texture has changed. This allows them to regenerate the quads with no reallocation.
  516. if (m_fontTextureHasChanged)
  517. {
  518. for (auto canvas : m_loadedCanvases)
  519. {
  520. canvas->MarkRenderGraphDirty();
  521. }
  522. m_fontTextureHasChanged = false;
  523. }
  524. for (auto canvas : m_loadedCanvases)
  525. {
  526. // In game we render full screen so the viewport size and target canvas size are the same.
  527. // For render targets, the target canvas size is always the authored canvas size
  528. AZ::Vector2 viewportSize = canvas->GetTargetCanvasSize();
  529. canvas->RenderCanvas(true, viewportSize);
  530. }
  531. }
  532. ////////////////////////////////////////////////////////////////////////////////////////////////////
  533. void UiCanvasManager::DestroyLoadedCanvases(bool keepCrossLevelCanvases)
  534. {
  535. // Find all the canvases loaded in game (but not loaded in editor) that need destroying
  536. AZStd::vector<AZ::EntityId> canvasesToUnload;
  537. canvasesToUnload.reserve(m_loadedCanvases.size());
  538. for (auto canvas : m_loadedCanvases)
  539. {
  540. if (!(keepCrossLevelCanvases && canvas->GetKeepLoadedOnLevelUnload()))
  541. {
  542. canvasesToUnload.push_back(canvas->GetEntityId());
  543. }
  544. }
  545. // Unload the canvases. This will also send the OnCanvasUnloaded notification which
  546. // ensures that components such as UiCanvasAsserRefComponent can clean up properly
  547. for (auto canvasEntityId : canvasesToUnload)
  548. {
  549. UnloadCanvas(canvasEntityId);
  550. }
  551. }
  552. ////////////////////////////////////////////////////////////////////////////////////////////////////
  553. void UiCanvasManager::OnLoadScreenUnloaded()
  554. {
  555. // Mark all render graphs dirty in case the loaded canvases were already rendered before their textures were
  556. // done loading. This happens when a load screen is being rendered during a level load. When other canvases
  557. // associated with the level are loaded, they also get rendered by the UiLoadScreenComponent, but their texture
  558. // loading is delayed until further down the level load process. Once a canvas is rendered, its render graph's
  559. // dirty flag is cleared, so the render graph needs to be marked dirty again after the textures are loaded
  560. for (auto canvas : m_loadedCanvases)
  561. {
  562. canvas->MarkRenderGraphDirty();
  563. }
  564. }
  565. ////////////////////////////////////////////////////////////////////////////////////////////////////
  566. bool UiCanvasManager::HandleInputEventForLoadedCanvases(const AzFramework::InputChannel& inputChannel)
  567. {
  568. // Take a snapshot of the input channel instead of just passing through the channel itself.
  569. // This is necessary because UI input is currently simulated in the editor's UI Preview mode
  570. // by constructing 'fake' input events, which we can do with snapshots but not input channels.
  571. // Long term we should look to update the AzFramework input system while in UI Editor Preview
  572. // mode so that it works exactly the same as in-game input, but this is a larger task for later.
  573. const AzFramework::InputChannel::Snapshot inputSnapshot(inputChannel);
  574. // De-normalize the position (if any) of the input event, as the UI system expects it relative
  575. // to the viewport from here on.
  576. AZ::Vector2 viewportPos(0.0f, 0.0f);
  577. const AzFramework::InputChannel::PositionData2D* positionData2D = inputChannel.GetCustomData<AzFramework::InputChannel::PositionData2D>();
  578. if (positionData2D)
  579. {
  580. viewportPos.SetX(positionData2D->m_normalizedPosition.GetX() * m_latestViewportSize.GetX());
  581. viewportPos.SetY(positionData2D->m_normalizedPosition.GetY() * m_latestViewportSize.GetY());
  582. }
  583. // Get the active modifier keys (if any) of the input event. Will only exist for keyboard keys.
  584. const AzFramework::ModifierKeyStates* modifierKeyStates = inputChannel.GetCustomData<AzFramework::ModifierKeyStates>();
  585. const AzFramework::ModifierKeyMask activeModifierKeys = modifierKeyStates ?
  586. modifierKeyStates->GetActiveModifierKeys() :
  587. AzFramework::ModifierKeyMask::None;
  588. bool handled = HandleInputEventForLoadedCanvases(inputSnapshot, viewportPos, activeModifierKeys, positionData2D ? true : false);
  589. return handled;
  590. }
  591. bool UiCanvasManager::HandleInputEventForLoadedCanvases(const AzFramework::InputChannel::Snapshot& inputSnapshot,
  592. const AZ::Vector2& viewportPos,
  593. AzFramework::ModifierKeyMask activeModifierKeys,
  594. bool isPositional)
  595. {
  596. bool handled = false;
  597. if (isPositional)
  598. {
  599. m_generateMousePositionInputEvent = false;
  600. }
  601. // make a temporary copy of the list in case the input handling ends up releasing or loading canvases during iterating over the list
  602. auto loadedCanvases = m_loadedCanvases;
  603. // reverse iterate over the loaded canvases so that the front most canvas gets first chance to
  604. // handle the event
  605. bool areAnyInWorldInputCanvasesLoaded = false;
  606. // HandleInputEvent is likely to call user code and scripts that could potentially cause a canvas to be released.
  607. // Setting this flag will cause any canvas deletions to be deferred. Due to the weird behavior when switching levels this function
  608. // (HandleInputEventForLoadedCanvases) can actually be called recursively because it can flush the input events.
  609. m_recursionGuardCount++;
  610. for (auto iter = loadedCanvases.rbegin(); iter != loadedCanvases.rend(); ++iter)
  611. {
  612. UiCanvasComponent* canvas = *iter;
  613. if (canvas->GetIsRenderToTexture() && canvas->GetIsPositionalInputSupported())
  614. {
  615. // keep track of whether any canvases are rendering to texture. Positional events for these
  616. // are ignored in HandleInputEvent and handled later in this function by HandleInputEventForInWorldCanvases
  617. areAnyInWorldInputCanvasesLoaded = true;
  618. }
  619. if (canvas->HandleInputEvent(inputSnapshot, &viewportPos, activeModifierKeys))
  620. {
  621. handled = true;
  622. break;
  623. }
  624. }
  625. m_recursionGuardCount--;
  626. // If not being called recursively from other canvas processing then immediately do any deferred canvas deletes
  627. DeleteCanvasesQueuedForDeletion();
  628. // if there are any canvases loaded that are rendering to texture we handle them seperately after the screen canvases
  629. // only do this for input events that are actually associated with a position
  630. if (!handled && areAnyInWorldInputCanvasesLoaded && isPositional)
  631. {
  632. if (HandleInputEventForInWorldCanvases(inputSnapshot, viewportPos))
  633. {
  634. handled = true;
  635. }
  636. }
  637. return handled;
  638. }
  639. ////////////////////////////////////////////////////////////////////////////////////////////////////
  640. bool UiCanvasManager::HandleTextEventForLoadedCanvases(const AZStd::string& textUTF8)
  641. {
  642. // reverse iterate over the loaded canvases so that the front most canvas gets first chance to
  643. // handle the event
  644. for (auto iter = m_loadedCanvases.rbegin(); iter != m_loadedCanvases.rend(); ++iter)
  645. {
  646. if ((*iter)->HandleTextEvent(textUTF8))
  647. {
  648. return true;
  649. }
  650. }
  651. return false;
  652. }
  653. ////////////////////////////////////////////////////////////////////////////////////////////////////
  654. // PRIVATE MEMBER FUNCTIONS
  655. ////////////////////////////////////////////////////////////////////////////////////////////////////
  656. ////////////////////////////////////////////////////////////////////////////////////////////////////
  657. void UiCanvasManager::SortCanvasesByDrawOrder()
  658. {
  659. std::stable_sort(m_loadedCanvases.begin(), m_loadedCanvases.end(), CompareCanvasDrawOrder);
  660. }
  661. ////////////////////////////////////////////////////////////////////////////////////////////////////
  662. UiCanvasComponent* UiCanvasManager::FindCanvasComponentByPathname(const AZStd::string& name)
  663. {
  664. AZStd::string adjustedSearchName = GetAssePathFromUserDefinedPath(name);
  665. for (auto canvas : (m_loadedCanvases))
  666. {
  667. if (adjustedSearchName == canvas->GetPathname())
  668. {
  669. return canvas;
  670. }
  671. }
  672. return nullptr;
  673. }
  674. ////////////////////////////////////////////////////////////////////////////////////////////////////
  675. UiCanvasComponent* UiCanvasManager::FindEditorCanvasComponentByPathname(const AZStd::string& name)
  676. {
  677. for (auto canvas : (m_loadedCanvasesInEditor))
  678. {
  679. if (name == canvas->GetPathname())
  680. {
  681. return canvas;
  682. }
  683. }
  684. return nullptr;
  685. }
  686. ////////////////////////////////////////////////////////////////////////////////////////////////////
  687. bool UiCanvasManager::HandleInputEventForInWorldCanvases(const AzFramework::InputChannel::Snapshot& inputSnapshot, const AZ::Vector2& viewportPos)
  688. {
  689. if (!AZ::Interface<ILyShine>::Get())
  690. {
  691. return false;
  692. }
  693. // First we need to construct a ray from either the center of the screen or the mouse position
  694. CLyShine* lyShine = static_cast<CLyShine*>(AZ::Interface<ILyShine>::Get());
  695. auto viewportContext = lyShine->GetUiRenderer()->GetViewportContext();
  696. AZ::Transform cameraTransform = viewportContext->GetCameraTransform();
  697. // Use a standard far clipping plane value for the ray length. This value could be made
  698. // configurable if need be
  699. const float rayLength = 1000.0f;
  700. AZ::Vector3 rayOrigin(0.0f);
  701. AZ::Vector3 endpoint(0.0f, rayLength, 0.0f);
  702. rayOrigin = cameraTransform.TransformPoint(rayOrigin);
  703. // If the mouse cursor is visible we will assume that the ray should be in the direction of the
  704. // mouse pointer. This is a temporary solution. A better solution is to be able to configure the
  705. // LyShine system to say how ray input should be handled.
  706. bool isCursorVisible = false;
  707. UiCursorBus::BroadcastResult(isCursorVisible, &UiCursorInterface::IsUiCursorVisible);
  708. if (!isCursorVisible)
  709. {
  710. endpoint = cameraTransform.TransformPoint(endpoint);
  711. }
  712. else
  713. {
  714. AzFramework::WindowSize viewportSize = viewportContext->GetViewportSize();
  715. AzFramework::ScreenSize screenSize(viewportSize.m_width, viewportSize.m_height);
  716. AzFramework::ScreenPoint screenPosition(static_cast<int>(viewportPos.GetX()), static_cast<int>(viewportPos.GetY()));
  717. AzFramework::CameraState cameraState = AzFramework::CreateDefaultCamera(cameraTransform, screenSize);
  718. const AZ::Matrix4x4& viewToClipMatrix = viewportContext->GetCameraProjectionMatrix();
  719. AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cameraState, viewToClipMatrix);
  720. endpoint = AzFramework::ScreenToWorld(
  721. screenPosition,
  722. cameraState
  723. );
  724. AZ::Vector3 rayDirection = (endpoint - rayOrigin).GetNormalized();
  725. rayDirection.SetLength(rayLength);
  726. endpoint = rayOrigin + rayDirection;
  727. }
  728. // Check if the ray intersects any entities
  729. AzFramework::EntityContextId gameContextId;
  730. AzFramework::GameEntityContextRequestBus::BroadcastResult(gameContextId,
  731. &AzFramework::GameEntityContextRequests::GetGameEntityContextId);
  732. AzFramework::RenderGeometry::RayRequest request;
  733. request.m_startWorldPosition = rayOrigin;
  734. request.m_endWorldPosition = endpoint;
  735. AzFramework::RenderGeometry::RayResult rayResult;
  736. AzFramework::RenderGeometry::IntersectorBus::EventResult(rayResult, gameContextId,
  737. &AzFramework::RenderGeometry::IntersectorInterface::RayIntersect, request);
  738. if (rayResult)
  739. {
  740. AZ::EntityId hitEntity = rayResult.m_entityAndComponent.GetEntityId();
  741. if (hitEntity.IsValid())
  742. {
  743. AZ::EntityId canvasEntityId;
  744. UiCanvasRefBus::EventResult(canvasEntityId, hitEntity, &UiCanvasRefInterface::GetCanvas);
  745. if (canvasEntityId.IsValid())
  746. {
  747. // Checkif the UI canvas referenced by the hit entity supports automatic input
  748. bool doesCanvasSupportInput = false;
  749. UiCanvasBus::EventResult(doesCanvasSupportInput, canvasEntityId, &UiCanvasInterface::GetIsPositionalInputSupported);
  750. if (doesCanvasSupportInput)
  751. {
  752. // Send the hit details to the hit entity. It will convert into canvas coords and send to canvas.
  753. // TODO: RayResult has a m_uv field but that has not been implemented in Atom yet and is always zero.
  754. // Once this is implemented in Atom, we can pass the result directly, and remove our own UV calculations
  755. // in ProcessHitInputEvent
  756. bool handled = false;
  757. UiCanvasOnMeshBus::EventResult(handled, hitEntity,
  758. &UiCanvasOnMeshInterface::ProcessHitInputEvent, inputSnapshot, request);
  759. if (handled)
  760. {
  761. return true;
  762. }
  763. }
  764. }
  765. }
  766. }
  767. return false;
  768. }
  769. ////////////////////////////////////////////////////////////////////////////////////////////////////
  770. AZ::EntityId UiCanvasManager::LoadCanvasInternal(const AZStd::string& assetIdPathname, bool forEditor, const AZStd::string& fullSourceAssetPathname, UiEntityContext* entityContext,
  771. const AZ::SliceComponent::EntityIdToEntityIdMap* previousRemapTable, AZ::EntityId previousCanvasId)
  772. {
  773. // Fix up user defined asset path for runtime. For editor, the asset path should already be valid
  774. AZStd::string assetIdPath = forEditor ? assetIdPathname : GetAssePathFromUserDefinedPath(assetIdPathname);
  775. // If loading from the editor we load the source asset path.
  776. // If loading in game this could be a path that a developer typed into a script.
  777. // However, it has to be a valid asset ID path. E.g. it can be resolved from the asset root
  778. // since at runtime we cannot convert from an arbitrary dev asset path to an asset ID
  779. const AZStd::string& pathToOpen = forEditor ? fullSourceAssetPathname : assetIdPath;
  780. // if the canvas is already loaded in the editor and we are running in game then we clone the
  781. // editor version so that the user can test their canvas without saving it
  782. UiCanvasComponent* canvasComponent = FindEditorCanvasComponentByPathname(assetIdPath);
  783. if (canvasComponent)
  784. {
  785. // this canvas is already loaded in the editor
  786. if (forEditor)
  787. {
  788. // should never load a canvas in Editor if it is already loaded. The Editor should avoid loading the
  789. // same canvas twice in Editor. If the game is running it is not possible to load a canvas
  790. // from the editor.
  791. gEnv->pSystem->Warning(VALIDATOR_MODULE_SHINE, VALIDATOR_WARNING, VALIDATOR_FLAG_FILE,
  792. pathToOpen.c_str(),
  793. "UI canvas file: %s is already loaded",
  794. pathToOpen.c_str());
  795. return AZ::EntityId();
  796. }
  797. else
  798. {
  799. // we are loading from the game, the canvas is already open in the editor, so
  800. // we clone the canvas that is open in the editor.
  801. canvasComponent = canvasComponent->CloneAndInitializeCanvas(entityContext, assetIdPath);
  802. }
  803. }
  804. else
  805. {
  806. // not already loaded in editor, attempt to load...
  807. canvasComponent = UiCanvasComponent::LoadCanvasInternal(pathToOpen.c_str(), forEditor, assetIdPath.c_str(), entityContext, previousRemapTable, previousCanvasId);
  808. }
  809. if (canvasComponent)
  810. {
  811. // canvas loaded OK (or cloned from Editor canvas OK)
  812. // add to the list of loaded canvases
  813. if (forEditor)
  814. {
  815. m_loadedCanvasesInEditor.push_back(canvasComponent);
  816. }
  817. else
  818. {
  819. if (canvasComponent->GetEnabled() && canvasComponent->GetIsConsumingAllInputEvents())
  820. {
  821. AzFramework::InputChannelRequestBus::Broadcast(&AzFramework::InputChannelRequests::ResetState);
  822. UiCanvasBus::Broadcast(&UiCanvasBus::Events::ClearAllInteractables);
  823. }
  824. m_loadedCanvases.push_back(canvasComponent);
  825. SortCanvasesByDrawOrder();
  826. // Update hover state for loaded canvases
  827. m_generateMousePositionInputEvent = true;
  828. }
  829. canvasComponent->SetLocalUserIdInputFilter(m_localUserIdInputFilter);
  830. }
  831. return (canvasComponent) ? canvasComponent->GetEntityId() : AZ::EntityId();
  832. }
  833. ////////////////////////////////////////////////////////////////////////////////////////////////////
  834. void UiCanvasManager::QueueCanvasForDeletion(AZ::EntityId canvasEntityId)
  835. {
  836. m_canvasesQueuedForDeletion.push_back(canvasEntityId);
  837. }
  838. ////////////////////////////////////////////////////////////////////////////////////////////////////
  839. void UiCanvasManager::DeleteCanvasesQueuedForDeletion()
  840. {
  841. // In weird cases like level unload HandleInputEventForLoadedCanvases can get called recursively
  842. // so do not delete any canvases until there is no recursion
  843. if (m_recursionGuardCount == 0)
  844. {
  845. for (auto canvasEntityId : m_canvasesQueuedForDeletion)
  846. {
  847. AZ::Entity* canvasEntity = nullptr;
  848. AZ::ComponentApplicationBus::BroadcastResult(canvasEntity, &AZ::ComponentApplicationBus::Events::FindEntity, canvasEntityId);
  849. delete canvasEntity;
  850. }
  851. m_canvasesQueuedForDeletion.clear();
  852. }
  853. }
  854. #ifndef _RELEASE
  855. ////////////////////////////////////////////////////////////////////////////////////////////////////
  856. void UiCanvasManager::DebugDisplayCanvasData(int setting) const
  857. {
  858. bool onlyShowEnabledCanvases = (setting == 2) ? true : false;
  859. IDraw2d* draw2d = Draw2dHelper::GetDefaultDraw2d();
  860. float dpiScale = draw2d->GetViewportDpiScalingFactor();
  861. float xOffset = 20.0f * dpiScale;
  862. float yOffset = 20.0f * dpiScale;
  863. const int elementNameFieldLength = 20;
  864. auto blackTexture = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::Black);
  865. float textOpacity = 1.0f;
  866. float backgroundRectOpacity = 0.0f; // 0.75f; // [GHI #6515] Reenable background rect
  867. const AZ::Vector3 white(1.0f, 1.0f, 1.0f);
  868. const AZ::Vector3 grey(0.5f, 0.5f, 0.5f);
  869. const AZ::Vector3 red(1.0f, 0.3f, 0.3f);
  870. const AZ::Vector3 blue(0.3f, 0.3f, 1.0f);
  871. const float fontSize = 8.0f;
  872. const float lineSpacing = 20.0f * dpiScale;
  873. // local function to write a line of text (with a background rect) and increment Y offset
  874. AZStd::function<void(const char*, const AZ::Vector3&)> WriteLine = [&](const char* buffer, const AZ::Vector3& color)
  875. {
  876. IDraw2d::TextOptions textOptions = draw2d->GetDefaultTextOptions();
  877. textOptions.color = color;
  878. AZ::Vector2 textSize = draw2d->GetTextSize(buffer, fontSize, &textOptions);
  879. AZ::Vector2 rectTopLeft = AZ::Vector2(xOffset - 2, yOffset);
  880. AZ::Vector2 rectSize = AZ::Vector2(textSize.GetX() + 4, lineSpacing);
  881. draw2d->DrawImage(blackTexture, rectTopLeft, rectSize, backgroundRectOpacity);
  882. draw2d->DrawText(buffer, AZ::Vector2(xOffset, yOffset), fontSize, textOpacity, &textOptions);
  883. yOffset += lineSpacing;
  884. };
  885. char buffer[200];
  886. sprintf_s(buffer, "There are %d loaded UI canvases", static_cast<int>(m_loadedCanvases.size()));
  887. WriteLine(buffer, white);
  888. sprintf_s(buffer, "NN: %20s %2s %2s %2s %11s %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s %20s %20s",
  889. "Name", "En", "Po", "Na", "DrawOrder",
  890. "nElem", "nEnab", "nRend", "nRCtl", "nImg", "nText", "nMask", "nFadr", "nIntr", "nUpdt", "ActiveInt", "HoverInt");
  891. WriteLine(buffer, white);
  892. int totalEnabled = 0;
  893. int totalPositionalInputs = 0;
  894. int totalNavigable = 0;
  895. int totalElements = 0;
  896. int totalEnabledElements = 0;
  897. int totalEnabledRenderables = 0;
  898. int totalEnabledRCtls = 0;
  899. int totalEnabledImages = 0;
  900. int totalEnabledTexts = 0;
  901. int totalEnabledMasks = 0;
  902. int totalEnabledFaders = 0;
  903. int totalEnabledIntrs = 0;
  904. int totalEnabledUpdates = 0;
  905. int i = 0;
  906. for (auto canvas : m_loadedCanvases)
  907. {
  908. // Name
  909. const AZStd::string pathname = canvas->GetPathname().c_str();
  910. size_t lastDot = pathname.find_last_of(".");
  911. size_t lastSlash = pathname.find_last_of("/");
  912. AZStd::string leafName = pathname;
  913. if (lastDot > lastSlash)
  914. {
  915. leafName = pathname.substr(lastSlash+1, lastDot-lastSlash-1);
  916. }
  917. leafName = leafName.substr(0, 20);
  918. // Enabled
  919. bool isCanvasEnabled = canvas->GetEnabled();
  920. if (onlyShowEnabledCanvases && !isCanvasEnabled)
  921. {
  922. continue;
  923. }
  924. const char* enabledString = isCanvasEnabled ? "Y" : "N";
  925. totalEnabled += isCanvasEnabled ? 1 : 0;
  926. bool posEnabled = canvas->GetIsPositionalInputSupported();
  927. const char* posEnabledString = posEnabled ? "Y" : "N";
  928. totalPositionalInputs += posEnabled ? 1 : 0;
  929. bool navEnabled = canvas->GetIsNavigationSupported();
  930. const char* navEnabledString = navEnabled ? "Y" : "N";
  931. totalNavigable += navEnabled ? 1 : 0;
  932. // Draw order
  933. int drawOrder = canvas->GetDrawOrder();
  934. // Active and hover
  935. AZ::EntityId activeInteractableId;
  936. AZ::EntityId hoverInteractableId;
  937. canvas->GetDebugInfoInteractables(activeInteractableId, hoverInteractableId);
  938. AZStd::string activeInteractableName = "None";
  939. AZStd::string hoverInteractableName = "None";
  940. if (activeInteractableId.IsValid())
  941. {
  942. activeInteractableName = DebugGetElementName(activeInteractableId, elementNameFieldLength);
  943. }
  944. if (hoverInteractableId.IsValid())
  945. {
  946. hoverInteractableName = DebugGetElementName(hoverInteractableId, elementNameFieldLength);
  947. }
  948. // Num elements
  949. UiCanvasComponent::DebugInfoNumElements info;
  950. canvas->GetDebugInfoNumElements(info);
  951. sprintf_s(buffer, "%2d: %20s %2s %2s %2s %11d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %20s %20s",
  952. i, leafName.c_str(),
  953. enabledString, posEnabledString, navEnabledString,
  954. drawOrder,
  955. info.m_numElements, info.m_numEnabledElements,
  956. info.m_numRenderElements, info.m_numRenderControlElements,
  957. info.m_numImageElements, info.m_numTextElements,
  958. info.m_numMaskElements, info.m_numFaderElements,
  959. info.m_numInteractableElements,info.m_numUpdateElements,
  960. activeInteractableName.c_str(), hoverInteractableName.c_str());
  961. const AZ::Vector3& color = isCanvasEnabled ? white : grey;
  962. WriteLine(buffer, color);
  963. ++i;
  964. totalElements += info.m_numElements;
  965. totalEnabledElements += info.m_numEnabledElements;
  966. totalEnabledRenderables += info.m_numRenderElements;
  967. totalEnabledRCtls += info.m_numRenderControlElements;
  968. totalEnabledImages += info.m_numImageElements;
  969. totalEnabledTexts += info.m_numTextElements;
  970. totalEnabledMasks += info.m_numMaskElements;
  971. totalEnabledFaders += info.m_numFaderElements;
  972. totalEnabledIntrs += info.m_numInteractableElements;
  973. totalEnabledUpdates += info.m_numUpdateElements;
  974. }
  975. sprintf_s(buffer, "Totals: %16s %2d %2d %2d %11s %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d",
  976. "",
  977. totalEnabled, totalPositionalInputs, totalNavigable,
  978. "",
  979. totalElements, totalEnabledElements,
  980. totalEnabledRenderables, totalEnabledRCtls,
  981. totalEnabledImages, totalEnabledTexts,
  982. totalEnabledMasks, totalEnabledFaders,
  983. totalEnabledIntrs, totalEnabledUpdates);
  984. WriteLine(buffer, red);
  985. }
  986. ////////////////////////////////////////////////////////////////////////////////////////////////////
  987. void UiCanvasManager::DebugDisplayDrawCallData() const
  988. {
  989. IDraw2d* draw2d = Draw2dHelper::GetDefaultDraw2d();
  990. float dpiScale = draw2d->GetViewportDpiScalingFactor();
  991. float xOffset = 20.0f * dpiScale;
  992. float yOffset = 20.0f * dpiScale;
  993. auto blackTexture = AZ::RPI::ImageSystemInterface::Get()->GetSystemImage(AZ::RPI::SystemImage::Black);
  994. float textOpacity = 1.0f;
  995. float backgroundRectOpacity = 0.0f; // 0.75f; // [GHI #6515] Reenable background rect
  996. const AZ::Vector3 white(1,1,1);
  997. const AZ::Vector3 red(1,0.3f,0.3f);
  998. const AZ::Vector3 blue(0.3f,0.3f,1);
  999. const AZ::Vector3 green(0.3f,1,0.3f);
  1000. const AZ::Vector3 yellow(0.7f,0.7f,0.2f);
  1001. const float fontSize = 8.0f;
  1002. const float lineSpacing = 20.0f * dpiScale;
  1003. // local function to write a line of text (with a background rect) and increment Y offset
  1004. AZStd::function<void(const char*, const AZ::Vector3&)> WriteLine = [&](const char* buffer, const AZ::Vector3& color)
  1005. {
  1006. IDraw2d::TextOptions textOptions = draw2d->GetDefaultTextOptions();
  1007. textOptions.color = color;
  1008. AZ::Vector2 textSize = draw2d->GetTextSize(buffer, fontSize, &textOptions);
  1009. AZ::Vector2 rectTopLeft = AZ::Vector2(xOffset - 2, yOffset);
  1010. AZ::Vector2 rectSize = AZ::Vector2(textSize.GetX() + 4, lineSpacing);
  1011. draw2d->DrawImage(blackTexture, rectTopLeft, rectSize, backgroundRectOpacity);
  1012. draw2d->DrawText(buffer, AZ::Vector2(xOffset, yOffset), fontSize, textOpacity, &textOptions);
  1013. yOffset += lineSpacing;
  1014. };
  1015. char buffer[200];
  1016. sprintf_s(buffer, "NN: %20s %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s %5s",
  1017. "Canvas name", "nDraw", "nPrim", "nTris", "nMask", "nRTs", "nUTex", "XMask", "XRT", "XBlnd", "XSrgb", "XMaxV", "XTex");
  1018. WriteLine(buffer, blue);
  1019. int totalRenderNodes = 0;
  1020. int totalPrimitives = 0;
  1021. int totalTriangles = 0;
  1022. int totalMasks = 0;
  1023. int totalRTs = 0;
  1024. int totalDueToMask = 0;
  1025. int totalDueToRT = 0;
  1026. int totalDueToBlendMode = 0;
  1027. int totalDueToSrgb = 0;
  1028. int totalDueToMaxVerts = 0;
  1029. int totalDueToTextures = 0;
  1030. int i = 0;
  1031. for (auto canvas : m_loadedCanvases)
  1032. {
  1033. // Name
  1034. const AZStd::string pathname = canvas->GetPathname().c_str();
  1035. size_t lastDot = pathname.find_last_of(".");
  1036. size_t lastSlash = pathname.find_last_of("/");
  1037. AZStd::string leafName = pathname;
  1038. if (lastDot > lastSlash)
  1039. {
  1040. leafName = pathname.substr(lastSlash+1, lastDot-lastSlash-1);
  1041. }
  1042. // Enabled
  1043. bool isCanvasEnabled = canvas->GetEnabled();
  1044. if (!isCanvasEnabled)
  1045. {
  1046. continue;
  1047. }
  1048. // Num elements
  1049. LyShineDebug::DebugInfoRenderGraph info;
  1050. canvas->GetDebugInfoRenderGraph(info);
  1051. sprintf_s(buffer, "%2d: %20s %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d",
  1052. i, leafName.c_str(),
  1053. info.m_numRenderNodes,
  1054. info.m_numPrimitives, info.m_numTriangles,
  1055. info.m_numMasks, info.m_numRTs, info.m_numUniqueTextures,
  1056. info.m_numNodesDueToMask, info.m_numNodesDueToRT,
  1057. info.m_numNodesDueToBlendMode, info.m_numNodesDueToSrgb,
  1058. info.m_numNodesDueToMaxVerts, info.m_numNodesDueToTextures);
  1059. AZ::u64 timeSinceBuiltMs = AZStd::GetTimeUTCMilliSecond() - info.m_timeGraphLastBuiltMs;
  1060. if (timeSinceBuiltMs > 1000)
  1061. {
  1062. timeSinceBuiltMs = 1000;
  1063. }
  1064. float percentageOfSecSinceLastBuilt = static_cast<float>(timeSinceBuiltMs) / 1000.0f;
  1065. AZ::Vector3 color;
  1066. if (info.m_wasBuiltThisFrame)
  1067. {
  1068. color = white; // white used if the render graph was rebuilt this frame
  1069. }
  1070. else
  1071. {
  1072. if (info.m_isReusingRenderTargets)
  1073. {
  1074. color = yellow; // yellow used if the render graph was not rebuilt and render targets were reused
  1075. }
  1076. else
  1077. {
  1078. color = green; // green used if render graph not regenerated this frame and no render targets reused
  1079. }
  1080. // When the render graph switches to not being built each frame we take 1 second to interpolate from white to
  1081. // the desired color, otherwise it is not possible to see when the rendergraph gets rebuilt at high frame rates
  1082. color = white + (color - white) * percentageOfSecSinceLastBuilt;
  1083. }
  1084. WriteLine(buffer, color);
  1085. ++i;
  1086. totalRenderNodes += info.m_numRenderNodes;
  1087. totalPrimitives += info.m_numPrimitives;
  1088. totalTriangles += info.m_numTriangles;
  1089. totalMasks += info.m_numMasks;
  1090. totalRTs += info.m_numRTs;
  1091. totalDueToMask += info.m_numNodesDueToMask;
  1092. totalDueToRT += info.m_numNodesDueToRT;
  1093. totalDueToBlendMode += info.m_numNodesDueToBlendMode;
  1094. totalDueToSrgb += info.m_numNodesDueToSrgb;
  1095. totalDueToMaxVerts += info.m_numNodesDueToMaxVerts;
  1096. totalDueToTextures += info.m_numNodesDueToTextures;
  1097. }
  1098. sprintf_s(buffer, "Totals: %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d",
  1099. totalRenderNodes,
  1100. totalPrimitives, totalTriangles, totalMasks, totalRTs,
  1101. totalDueToMask, totalDueToRT,
  1102. totalDueToBlendMode, totalDueToSrgb,
  1103. totalDueToMaxVerts, totalDueToTextures);
  1104. WriteLine(buffer, red);
  1105. }
  1106. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1107. AZStd::string UiCanvasManager::DebugGetElementName(AZ::EntityId entityId, int maxLength) const
  1108. {
  1109. AZStd::string name = "None";
  1110. AZ::Entity* entity = nullptr;
  1111. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationBus::Events::FindEntity, entityId);
  1112. if (entity)
  1113. {
  1114. name = entity->GetName();
  1115. if (name.length() < maxLength)
  1116. {
  1117. AZ::Entity* parent = nullptr;
  1118. UiElementBus::EventResult(parent, entityId, &UiElementBus::Events::GetParent);
  1119. if (parent)
  1120. {
  1121. name = parent->GetName() + "/" + name;
  1122. if (name.length() > maxLength)
  1123. {
  1124. AZStd::string maxString = name.substr(name.length() - maxLength);
  1125. name = maxString;
  1126. }
  1127. }
  1128. }
  1129. }
  1130. return name;
  1131. }
  1132. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1133. void UiCanvasManager::DebugReportDrawCalls(const AZStd::string& name) const
  1134. {
  1135. AZStd::string logFolder = AZStd::string::format("@log@/LyShine");
  1136. AZ::IO::LocalFileIO::GetInstance()->CreatePath(logFolder.c_str());
  1137. AZStd::string logFileLeafName = "DrawCallReport";
  1138. if (!name.empty())
  1139. {
  1140. logFileLeafName += "_";
  1141. logFileLeafName += name;
  1142. }
  1143. AZStd::string logFile = AZStd::string::format("%s/%s.txt", logFolder.c_str(), logFileLeafName.c_str());
  1144. AZ::IO::HandleType logHandle;
  1145. AZ::IO::Result result = AZ::IO::LocalFileIO::GetInstance()->Open(logFile.c_str(), AZ::IO::OpenMode::ModeWrite, logHandle);
  1146. if (!result)
  1147. {
  1148. AZ_TracePrintf("UI", "Failed to open file for Draw Call Report at %s\n", logFile.c_str());
  1149. return;
  1150. }
  1151. AZStd::string logLine = AZStd::string::format("Draw call report for \'%s\'\r\n", name.c_str());
  1152. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1153. logLine = AZStd::string::format("Output by the ui_ReportDrawCalls console command\r\n\r\n");
  1154. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1155. int numEnabledCanvases = 0;
  1156. for (auto canvas : m_loadedCanvases)
  1157. {
  1158. if (canvas->GetEnabled())
  1159. {
  1160. numEnabledCanvases++;
  1161. }
  1162. }
  1163. logLine = AZStd::string::format("There are %zu loaded UI canvases, %d of which are enabled.\r\nThe below report only includes the enabled canvases\r\n",
  1164. m_loadedCanvases.size(), numEnabledCanvases);
  1165. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1166. LyShineDebug::DebugInfoDrawCallReport reportInfo;
  1167. for (auto canvas : m_loadedCanvases)
  1168. {
  1169. // Check enabled
  1170. bool isCanvasEnabled = canvas->GetEnabled();
  1171. if (!isCanvasEnabled)
  1172. {
  1173. continue;
  1174. }
  1175. // Name of canvas
  1176. const AZStd::string pathname = canvas->GetPathname().c_str();
  1177. logLine = "\r\n=====================================================================================\r\n";
  1178. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1179. logLine = AZStd::string::format("Canvas: %s\r\n", pathname.c_str());
  1180. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1181. logLine = "=====================================================================================\r\n\r\n";
  1182. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1183. // Get canvas summary data
  1184. LyShineDebug::DebugInfoRenderGraph renderGraphInfo;
  1185. canvas->GetDebugInfoRenderGraph(renderGraphInfo);
  1186. // Output a summary report
  1187. if (renderGraphInfo.m_numRenderNodes > 0)
  1188. {
  1189. logLine = AZStd::string::format("Canvas has %d draw calls and %d primitives with a total of %d triangles\r\n",
  1190. renderGraphInfo.m_numRenderNodes, renderGraphInfo.m_numPrimitives, renderGraphInfo.m_numTriangles);
  1191. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1192. logLine = AZStd::string::format("There are %d unique textures used, %d mask render nodes and %d render target render nodes\r\n",
  1193. renderGraphInfo.m_numUniqueTextures, renderGraphInfo.m_numMasks, renderGraphInfo.m_numRTs);
  1194. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1195. logLine = AZStd::string::format(
  1196. "Extra draw calls caused by... Masks: %d, RenderTargets: %d, BlendModes: %d, Srgb: %d, MaxVerts: %d, MaxTextures: %d\r\n\r\n",
  1197. renderGraphInfo.m_numNodesDueToMask, renderGraphInfo.m_numNodesDueToRT,
  1198. renderGraphInfo.m_numNodesDueToBlendMode,
  1199. renderGraphInfo.m_numNodesDueToSrgb, renderGraphInfo.m_numNodesDueToMaxVerts, renderGraphInfo.m_numNodesDueToTextures);
  1200. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1201. }
  1202. // output the details on each draw call and gather info for all canvases
  1203. canvas->DebugReportDrawCalls(logHandle, reportInfo, canvas);
  1204. }
  1205. AZStd::string fontTexturePrefix = "$AutoFont";
  1206. logLine = "\r\n\r\n--------------------------------------------------------------------------------------------\r\n";
  1207. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1208. logLine = AZStd::string::format("Textures used on multiple canvases that are causing extra draw calls\r\n");
  1209. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1210. logLine = "--------------------------------------------------------------------------------------------\r\n\r\n";
  1211. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1212. for (LyShineDebug::DebugInfoTextureUsage& reportTextureUsage : reportInfo.m_textures)
  1213. {
  1214. if (reportTextureUsage.m_numCanvasesUsed > 1 &&
  1215. reportTextureUsage.m_numDrawCallsWhereExceedingMaxTextures)
  1216. {
  1217. AZStd::string textureName;
  1218. AZ::Data::AssetCatalogRequestBus::BroadcastResult(textureName, &AZ::Data::AssetCatalogRequests::GetAssetPathById, reportTextureUsage.m_texture->GetAssetId());
  1219. if (textureName.compare(0, fontTexturePrefix.length(), fontTexturePrefix) != 0)
  1220. {
  1221. logLine = AZStd::string::format("%s\r\n", textureName.c_str());
  1222. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1223. }
  1224. }
  1225. }
  1226. logLine = "\r\n\r\n--------------------------------------------------------------------------------------------\r\n";
  1227. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1228. logLine = AZStd::string::format("Per canvas report of textures used on only that canvas that are causing extra draw calls\r\n");
  1229. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1230. logLine = "--------------------------------------------------------------------------------------------\r\n\r\n";
  1231. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1232. for (auto canvas : m_loadedCanvases)
  1233. {
  1234. // Check enabled
  1235. bool isCanvasEnabled = canvas->GetEnabled();
  1236. if (!isCanvasEnabled)
  1237. {
  1238. continue;
  1239. }
  1240. bool loggedCanvasHeader = false;
  1241. for (LyShineDebug::DebugInfoTextureUsage& reportTextureUsage : reportInfo.m_textures)
  1242. {
  1243. if (reportTextureUsage.m_numCanvasesUsed == 1 &&
  1244. reportTextureUsage.m_lastContextUsed == canvas &&
  1245. reportTextureUsage.m_numDrawCallsWhereExceedingMaxTextures)
  1246. {
  1247. AZStd::string textureName;
  1248. AZ::Data::AssetCatalogRequestBus::BroadcastResult(textureName, &AZ::Data::AssetCatalogRequests::GetAssetPathById, reportTextureUsage.m_texture->GetAssetId());
  1249. // exclude font textures
  1250. if (textureName.compare(0, fontTexturePrefix.length(), fontTexturePrefix) != 0)
  1251. {
  1252. if (!loggedCanvasHeader)
  1253. {
  1254. const AZStd::string pathname = canvas->GetPathname().c_str();
  1255. logLine = AZStd::string::format("\r\nCanvas: %s\r\n\r\n", pathname.c_str());
  1256. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1257. loggedCanvasHeader = true;
  1258. }
  1259. logLine = AZStd::string::format("%s\r\n", textureName.c_str());
  1260. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1261. }
  1262. }
  1263. }
  1264. }
  1265. logLine = "\r\n--------------------------------------------------------------------------------------------\r\n";
  1266. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1267. logLine = "End of report\r\n";
  1268. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1269. logLine = "--------------------------------------------------------------------------------------------\r\n";
  1270. AZ::IO::LocalFileIO::GetInstance()->Write(logHandle, logLine.c_str(), logLine.size());
  1271. AZ::IO::LocalFileIO::GetInstance()->Close(logHandle);
  1272. AZ_TracePrintf("UI", "Wrote Draw Call Report to %s\n", logFile.c_str());
  1273. }
  1274. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1275. void UiCanvasManager::DebugDisplayElemBounds(int canvasIndexFilter) const
  1276. {
  1277. IDraw2d* draw2d = Draw2dHelper::GetDefaultDraw2d();
  1278. int canvasIndex = 0;
  1279. for (auto canvas : m_loadedCanvases)
  1280. {
  1281. // Enabled
  1282. bool isCanvasEnabled = canvas->GetEnabled();
  1283. if (!isCanvasEnabled)
  1284. {
  1285. continue;
  1286. }
  1287. // filter canvas index
  1288. if (canvasIndexFilter == -1 || canvasIndexFilter == canvasIndex)
  1289. {
  1290. // Display the elem bounds
  1291. canvas->DebugDisplayElemBounds(draw2d);
  1292. }
  1293. ++canvasIndex; // only increments for enabled canvases so index matches "ui_DisplayCanvasData 2"
  1294. }
  1295. }
  1296. #endif