ScriptManager.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  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 <Automation/ScriptManager.h>
  9. #include <Automation/ScriptableImGui.h>
  10. #include <SampleComponentManagerBus.h>
  11. #include <imgui/imgui_internal.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  13. #include <Atom/RPI.Public/RPISystemInterface.h>
  14. #include <Atom/Component/DebugCamera/CameraComponent.h>
  15. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  16. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  17. #include <Atom/Feature/ImGui/SystemBus.h>
  18. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  19. #include <Atom/RHI/Factory.h>
  20. #include <AzCore/Component/Entity.h>
  21. #include <AzCore/Settings/SettingsRegistryScriptUtils.h>
  22. #include <AzCore/Script/ScriptContext.h>
  23. #include <AzCore/Script/ScriptSystemBus.h>
  24. #include <AzCore/Script/ScriptAsset.h>
  25. #include <AzCore/Math/MathReflection.h>
  26. #include <AzCore/Console/IConsole.h>
  27. #include <AzCore/Time/ITime.h>
  28. #include <AzFramework/API/ApplicationAPI.h>
  29. #include <AzFramework/Components/ConsoleBus.h>
  30. #include <AzFramework/IO/LocalFileIO.h>
  31. #include <AzFramework/Windowing/WindowBus.h>
  32. #include <AtomSampleViewerRequestBus.h>
  33. #include <Utils/Utils.h>
  34. namespace AtomSampleViewer
  35. {
  36. ScriptManager::ScriptManager()
  37. : m_scriptBrowser("@user@/lua_script_browser.xml")
  38. {
  39. }
  40. ScriptManager* ScriptManager::GetInstance()
  41. {
  42. static ScriptManager* s_instance = nullptr;
  43. if (!s_instance)
  44. {
  45. AtomSampleViewer::SampleComponentSingletonRequestBus::BroadcastResult(s_instance, &AtomSampleViewer::SampleComponentSingletonRequestBus::Events::GetScriptManagerInstance);
  46. }
  47. return s_instance;
  48. }
  49. void ScriptManager::Activate()
  50. {
  51. m_scriptContext = AZStd::make_unique<AZ::ScriptContext>();
  52. m_sriptBehaviorContext = AZStd::make_unique<AZ::BehaviorContext>();
  53. ReflectScriptContext(m_sriptBehaviorContext.get());
  54. m_scriptContext->BindTo(m_sriptBehaviorContext.get());
  55. m_scriptBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  56. {
  57. return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath, ".bv.luac");
  58. });
  59. m_scriptBrowser.Activate();
  60. ScriptRepeaterRequestBus::Handler::BusConnect();
  61. ScriptRunnerRequestBus::Handler::BusConnect();
  62. m_imageComparisonOptions.Activate();
  63. }
  64. void ScriptManager::Deactivate()
  65. {
  66. m_scriptContext = nullptr;
  67. m_sriptBehaviorContext = nullptr;
  68. m_scriptBrowser.Deactivate();
  69. m_imageComparisonOptions.Deactivate();
  70. ScriptRunnerRequestBus::Handler::BusDisconnect();
  71. ScriptRepeaterRequestBus::Handler::BusDisconnect();
  72. AZ::Debug::CameraControllerNotificationBus::Handler::BusDisconnect();
  73. }
  74. void ScriptManager::SetCameraEntity(AZ::Entity* cameraEntity)
  75. {
  76. AZ::Debug::CameraControllerNotificationBus::Handler::BusDisconnect();
  77. m_cameraEntity = cameraEntity;
  78. AZ::Debug::CameraControllerNotificationBus::Handler::BusConnect(m_cameraEntity->GetId());
  79. }
  80. void ScriptManager::PauseScript()
  81. {
  82. PauseScriptWithTimeout(DefaultPauseTimeout);
  83. }
  84. void ScriptManager::PauseScriptWithTimeout(float timeout)
  85. {
  86. m_scriptPaused = true;
  87. m_scriptPauseTimeout = AZ::GetMax(timeout, m_scriptPauseTimeout);
  88. }
  89. void ScriptManager::ResumeScript()
  90. {
  91. AZ_Warning("Automation", m_scriptPaused, "Script is not paused");
  92. m_scriptPaused = false;
  93. }
  94. void ScriptManager::ReportScriptError([[maybe_unused]] const AZStd::string& message)
  95. {
  96. AZ_Error("Automation", false, "Script: %s", message.c_str());
  97. }
  98. void ScriptManager::ReportScriptWarning([[maybe_unused]] const AZStd::string& message)
  99. {
  100. AZ_Warning("Automation", false, "Script: %s", message.c_str());
  101. }
  102. void ScriptManager::ReportScriptableAction([[maybe_unused]] AZStd::string_view scriptCommand)
  103. {
  104. AZ_TracePrintf("Automation", "Scriptable Action: %.*s\n", AZ_STRING_ARG(scriptCommand));
  105. }
  106. void ScriptManager::ImageComparisonOptions::Activate()
  107. {
  108. m_configAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::AnyAsset>("config/ImageComparisonConfig.azasset", AZ::RPI::AssetUtils::TraceLevel::Assert);
  109. if (m_configAsset)
  110. {
  111. AZ::Data::AssetBus::Handler::BusConnect(m_configAsset.GetId());
  112. OnAssetReloaded(m_configAsset);
  113. }
  114. }
  115. void ScriptManager::ImageComparisonOptions::Deactivate()
  116. {
  117. m_configAsset.Release();
  118. ResetImGuiSettings();
  119. AZ::Data::AssetBus::Handler::BusDisconnect();
  120. }
  121. ImageComparisonToleranceLevel* ScriptManager::ImageComparisonOptions::FindToleranceLevel(const AZStd::string& name, bool allowLevelAdjustment)
  122. {
  123. size_t foundIndex = m_config.m_toleranceLevels.size();
  124. for (size_t i = 0; i < m_config.m_toleranceLevels.size(); ++i)
  125. {
  126. if (m_config.m_toleranceLevels[i].m_name == name)
  127. {
  128. foundIndex = i;
  129. break;
  130. }
  131. }
  132. if (foundIndex == m_config.m_toleranceLevels.size())
  133. {
  134. return nullptr;
  135. }
  136. if (allowLevelAdjustment)
  137. {
  138. int adjustedIndex = aznumeric_cast<int>(foundIndex);
  139. adjustedIndex += m_toleranceAdjustment;
  140. adjustedIndex = AZ::GetClamp(adjustedIndex, 0, aznumeric_cast<int>(m_config.m_toleranceLevels.size()) - 1);
  141. foundIndex = aznumeric_cast<size_t>(adjustedIndex);
  142. }
  143. return &m_config.m_toleranceLevels[foundIndex];
  144. }
  145. const AZStd::vector<ImageComparisonToleranceLevel>& ScriptManager::ImageComparisonOptions::GetAvailableToleranceLevels() const
  146. {
  147. return m_config.m_toleranceLevels;
  148. }
  149. void ScriptManager::ImageComparisonOptions::SelectToleranceLevel(const AZStd::string& name, bool allowLevelAdjustment)
  150. {
  151. if (m_selectedOverrideSetting == OverrideSetting_ScriptControlled)
  152. {
  153. ImageComparisonToleranceLevel* level = FindToleranceLevel(name, allowLevelAdjustment);
  154. if (level)
  155. {
  156. m_currentToleranceLevel = level;
  157. }
  158. else
  159. {
  160. ReportScriptError(AZStd::string::format("ImageComparisonToleranceLevel '%s' not found.", name.c_str()));
  161. }
  162. }
  163. }
  164. void ScriptManager::ImageComparisonOptions::SelectToleranceLevel(ImageComparisonToleranceLevel* level)
  165. {
  166. if (nullptr == level)
  167. {
  168. m_currentToleranceLevel = level;
  169. return;
  170. }
  171. else
  172. {
  173. SelectToleranceLevel(level->m_name);
  174. AZ_Assert(GetCurrentToleranceLevel() == level, "Wrong ImageComparisonToleranceLevel pointer used");
  175. }
  176. }
  177. ImageComparisonToleranceLevel* ScriptManager::ImageComparisonOptions::GetCurrentToleranceLevel()
  178. {
  179. return m_currentToleranceLevel;
  180. }
  181. bool ScriptManager::ImageComparisonOptions::IsScriptControlled() const
  182. {
  183. return m_selectedOverrideSetting == OverrideSetting_ScriptControlled;
  184. }
  185. bool ScriptManager::ImageComparisonOptions::IsLevelAdjusted() const
  186. {
  187. return m_toleranceAdjustment != 0;
  188. }
  189. void ScriptManager::ImageComparisonOptions::DrawImGuiSettings()
  190. {
  191. ImGui::Text("Tolerance");
  192. ImGui::Indent();
  193. if (ImGui::Combo("Level",
  194. &m_selectedOverrideSetting,
  195. m_overrideSettings.data(),
  196. aznumeric_cast<int>(m_overrideSettings.size())))
  197. {
  198. if (m_selectedOverrideSetting == OverrideSetting_ScriptControlled)
  199. {
  200. m_currentToleranceLevel = nullptr;
  201. }
  202. else
  203. {
  204. m_currentToleranceLevel = &m_config.m_toleranceLevels[m_selectedOverrideSetting - 1];
  205. }
  206. }
  207. if (IsScriptControlled())
  208. {
  209. ImGui::InputInt("Level Adjustment", &m_toleranceAdjustment);
  210. }
  211. ImGui::Unindent();
  212. }
  213. void ScriptManager::ImageComparisonOptions::ResetImGuiSettings()
  214. {
  215. m_currentToleranceLevel = nullptr;
  216. m_selectedOverrideSetting = OverrideSetting_ScriptControlled;
  217. m_toleranceAdjustment = 0;
  218. }
  219. void ScriptManager::ImageComparisonOptions::OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset)
  220. {
  221. m_configAsset = asset;
  222. m_config = *m_configAsset->GetDataAs<ImageComparisonConfig>();
  223. m_overrideSettings.clear();
  224. m_overrideSettings.push_back("[Script-controlled]");
  225. for (size_t i = 0; i < m_config.m_toleranceLevels.size(); ++i)
  226. {
  227. AZ_Assert(i == 0 || m_config.m_toleranceLevels[i].m_threshold > m_config.m_toleranceLevels[i - 1].m_threshold, "Threshold values are not sequential");
  228. m_overrideSettings.push_back(m_config.m_toleranceLevels[i].m_name.c_str());
  229. }
  230. }
  231. void ScriptManager::TickImGui()
  232. {
  233. if (m_showScriptRunnerDialog)
  234. {
  235. ShowScriptRunnerDialog();
  236. }
  237. m_scriptReporter.TickImGui();
  238. if (m_showPrecommitWizard)
  239. {
  240. ShowPrecommitWizard();
  241. }
  242. if (m_testSuiteRunConfig.m_automatedRunEnabled)
  243. {
  244. if (m_testSuiteRunConfig.m_isStarted == false)
  245. {
  246. m_testSuiteRunConfig.m_isStarted = true;
  247. PrepareAndExecuteScript(m_testSuiteRunConfig.m_testSuitePath);
  248. }
  249. }
  250. }
  251. void ScriptManager::TickScript(float deltaTime)
  252. {
  253. // All actions must be consumed each frame. Otherwise, this indicates that a script is
  254. // scheduling ScriptableImGui actions for fields that don't exist.
  255. ScriptableImGui::CheckAllActionsConsumed();
  256. ScriptableImGui::ClearActions();
  257. // We delayed PopScript() until after the above CheckAllActionsConsumed(), so that any errors
  258. // reported by that function will be associated with the proper script.
  259. if (m_shouldPopScript)
  260. {
  261. m_scriptReporter.PopScript();
  262. m_shouldPopScript = false;
  263. }
  264. while (!m_scriptOperations.empty())
  265. {
  266. if (m_shouldPopScript)
  267. {
  268. // If we just finished executing a script, the remaining m_scriptOperations are for some other script.
  269. // We need to proceed to the next frame and allow that PopScript() to happen, otherwise any errors related
  270. // to subsequent operations would be reported against the prior script.
  271. break;
  272. }
  273. if (m_scriptPaused)
  274. {
  275. m_scriptPauseTimeout -= deltaTime;
  276. if (m_scriptPauseTimeout < 0)
  277. {
  278. AZ_Error("Automation", false, "Script pause timed out. Continuing...");
  279. m_scriptPaused = false;
  280. }
  281. else
  282. {
  283. break;
  284. }
  285. }
  286. if (m_waitForAssetTracker)
  287. {
  288. m_assetTrackingTimeout -= deltaTime;
  289. if (m_assetTrackingTimeout < 0)
  290. {
  291. auto incomplateAssetList = m_assetStatusTracker.GetIncompleteAssetList();
  292. AZStd::string incompleteAssetListString;
  293. AzFramework::StringFunc::Join(incompleteAssetListString, incomplateAssetList.begin(), incomplateAssetList.end(), "\n ");
  294. AZ_Error("Automation", false, "Script asset tracking timed out waiting for:\n %s \n Continuing...", incompleteAssetListString.c_str());
  295. m_waitForAssetTracker = false;
  296. }
  297. else if (m_assetStatusTracker.DidExpectedAssetsFinish())
  298. {
  299. AZ_Printf("Automation", "Asset Tracker finished with %f seconds remaining.", m_assetTrackingTimeout);
  300. m_waitForAssetTracker = false;
  301. }
  302. else
  303. {
  304. break;
  305. }
  306. }
  307. if (m_scriptIdleFrames > 0)
  308. {
  309. m_scriptIdleFrames--;
  310. break;
  311. }
  312. if (m_scriptIdleSeconds > 0)
  313. {
  314. m_scriptIdleSeconds -= deltaTime;
  315. break;
  316. }
  317. // Execute the next operation
  318. m_scriptOperations.front()();
  319. m_scriptOperations.pop();
  320. if (m_scriptOperations.empty())
  321. {
  322. m_doFinalScriptCleanup = true;
  323. }
  324. }
  325. if (m_shouldPopScript)
  326. {
  327. // We need to proceed for one more frame to do the last PopScript() before final cleanup
  328. return;
  329. }
  330. if (m_doFinalScriptCleanup)
  331. {
  332. bool frameCapturePending = false;
  333. SampleComponentManagerRequestBus::BroadcastResult(frameCapturePending, &SampleComponentManagerRequests::IsFrameCapturePending);
  334. if (!frameCapturePending && !m_isCapturePending)
  335. {
  336. AZ_Assert(m_scriptPaused == false, "Script manager is in an unexpected state.");
  337. AZ_Assert(m_scriptIdleFrames == 0, "Script manager is in an unexpected state.");
  338. AZ_Assert(m_scriptIdleSeconds <= 0.0f, "Script manager is in an unexpected state.");
  339. AZ_Assert(m_waitForAssetTracker == false, "Script manager is in an unexpected state.");
  340. AZ_Assert(!m_scriptReporter.HasActiveScript(), "Script manager is in an unexpected state.");
  341. AZ_Assert(m_executingScripts.size() == 0, "Script manager is in an unexpected state");
  342. m_assetStatusTracker.StopTracking();
  343. if (m_frameTimeIsLocked)
  344. {
  345. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("t_simulationTickDeltaOverride 0");
  346. m_frameTimeIsLocked = false;
  347. }
  348. if (m_shouldRestoreViewportSize)
  349. {
  350. Utils::ResizeClientArea(m_savedViewportWidth, m_savedViewportHeight, AzFramework::WindowPosOptions());
  351. m_shouldRestoreViewportSize = false;
  352. }
  353. // In case scripts were aborted while ImGui was temporarily hidden, show it again.
  354. SetShowImGui(true);
  355. m_scriptReporter.SortScriptReports();
  356. m_scriptReporter.OpenReportDialog();
  357. m_shouldPopScript = false;
  358. m_doFinalScriptCleanup = false;
  359. if (m_testSuiteRunConfig.m_automatedRunEnabled && m_testSuiteRunConfig.m_closeOnTestScriptFinish)
  360. {
  361. m_testSuiteRunConfig.m_automatedRunEnabled = false;
  362. if (m_scriptReporter.HasErrorsAssertsInReport())
  363. {
  364. AtomSampleViewerRequestsBus::Broadcast(&AtomSampleViewerRequestsBus::Events::SetExitCode, 1);
  365. // Useful console logging for Hydra tests
  366. int failedTests = 0;
  367. for (const ScriptReporter::ScriptReport& testReport : m_scriptReporter.GetScriptReport())
  368. {
  369. if (testReport.m_assertCount > 0 || testReport.m_generalErrorCount > 0 || testReport.m_screenshotErrorCount > 0)
  370. {
  371. ++failedTests;
  372. AZ_Printf("AtomSampleViewer", "Test failure %s: asserts %u, general errors %u, screenshot failures %u\n", testReport.m_scriptAssetPath.c_str(),
  373. testReport.m_assertCount, testReport.m_generalErrorCount, testReport.m_screenshotErrorCount);
  374. }
  375. }
  376. AZ_Printf("AtomSampleViewer", "%d tests failed\n", failedTests);
  377. }
  378. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  379. }
  380. }
  381. }
  382. }
  383. void ScriptManager::OpenScriptRunnerDialog()
  384. {
  385. m_showScriptRunnerDialog = true;
  386. }
  387. void ScriptManager::OpenPrecommitWizard()
  388. {
  389. m_showPrecommitWizard = true;
  390. }
  391. void ScriptManager::RunMainTestSuite(const AZStd::string& suiteFilePath, bool exitOnTestEnd, int randomSeed)
  392. {
  393. m_testSuiteRunConfig.m_automatedRunEnabled = true;
  394. m_testSuiteRunConfig.m_testSuitePath = suiteFilePath;
  395. m_testSuiteRunConfig.m_closeOnTestScriptFinish = exitOnTestEnd;
  396. m_testSuiteRunConfig.m_randomSeed = randomSeed;
  397. }
  398. void ScriptManager::AbortScripts(const AZStd::string& reason)
  399. {
  400. m_scriptReporter.SetInvalidationMessage(reason);
  401. m_scriptOperations = {};
  402. m_executingScripts.clear();
  403. m_scriptPaused = false;
  404. m_scriptIdleFrames = 0;
  405. m_scriptIdleSeconds = 0.0f;
  406. m_waitForAssetTracker = false;
  407. while (m_scriptReporter.HasActiveScript())
  408. {
  409. m_scriptReporter.PopScript();
  410. }
  411. m_doFinalScriptCleanup = true;
  412. }
  413. void ScriptManager::ShowScriptRunnerDialog()
  414. {
  415. if (ImGui::Begin("Script Runner", &m_showScriptRunnerDialog))
  416. {
  417. auto drawAbortButton = [this](const char* uniqueId)
  418. {
  419. ImGui::PushID(uniqueId);
  420. if (ImGui::Button("Abort"))
  421. {
  422. AbortScripts("Script(s) manually aborted.");
  423. }
  424. ImGui::PopID();
  425. };
  426. // The main buttons are at the bottom, but show the Abort button at the top too, in case the window size is small.
  427. if (!m_scriptOperations.empty())
  428. {
  429. drawAbortButton("Button1");
  430. }
  431. ImGuiAssetBrowser::WidgetSettings assetBrowserSettings;
  432. assetBrowserSettings.m_labels.m_root = "Lua Scripts";
  433. m_scriptBrowser.Tick(assetBrowserSettings);
  434. AZStd::string selectedFileName = "<none>";
  435. AzFramework::StringFunc::Path::GetFullFileName(m_scriptBrowser.GetSelectedAssetPath().c_str(), selectedFileName);
  436. ImGui::LabelText("##SelectedScript", "Selected: %s", selectedFileName.c_str());
  437. ImGui::Separator();
  438. ImGui::Text("Settings");
  439. ImGui::Indent();
  440. ImGui::InputInt("Random Seed for Test Order Execution", &m_testSuiteRunConfig.m_randomSeed);
  441. m_imageComparisonOptions.DrawImGuiSettings();
  442. if (ImGui::Button("Reset"))
  443. {
  444. m_imageComparisonOptions.ResetImGuiSettings();
  445. }
  446. ImGui::Unindent();
  447. ImGui::Separator();
  448. if (ImGui::Button("Run"))
  449. {
  450. auto scriptAsset = m_scriptBrowser.GetSelectedAsset<AZ::ScriptAsset>();
  451. if (scriptAsset.GetId().IsValid())
  452. {
  453. PrepareAndExecuteScript(m_scriptBrowser.GetSelectedAssetPath());
  454. }
  455. }
  456. if (ImGui::Button("View Latest Results"))
  457. {
  458. m_scriptReporter.OpenReportDialog();
  459. }
  460. if (m_scriptOperations.size() > 0)
  461. {
  462. ImGui::LabelText("##RunningScript", "Running %zu operations...", m_scriptOperations.size());
  463. drawAbortButton("Button2");
  464. }
  465. }
  466. m_messageBox.TickPopup();
  467. ImGui::End();
  468. }
  469. void ScriptManager::ShowPrecommitWizard()
  470. {
  471. if (ImGui::Begin("Pre-commit Wizard", &m_showPrecommitWizard))
  472. {
  473. ShowBackToIntroWarning();
  474. if (ImGui::Button("Start from the Beginning"))
  475. {
  476. ImGui::OpenPopup("Return to Intro Window");
  477. }
  478. switch (m_wizardSettings.m_stage)
  479. {
  480. case PrecommitWizardSettings::Stage::Intro:
  481. ShowPrecommitWizardIntro();
  482. break;
  483. case PrecommitWizardSettings::Stage::RunFullsuiteTest:
  484. ShowPrecommitWizardRunFullsuiteTest();
  485. break;
  486. case PrecommitWizardSettings::Stage::ReportFullsuiteSummary:
  487. ShowPrecommitWizardReportFullsuiteTest();
  488. break;
  489. case PrecommitWizardSettings::Stage::ManualInspection:
  490. // Go through each pass in the full suite test and require users to manually pick from a list
  491. // to describe the difference if it exists.
  492. ShowPrecomitWizardManualInspection();
  493. break;
  494. case PrecommitWizardSettings::Stage::ReportFinalSummary:
  495. // Generate a summary that can be easily copied into the clipboard
  496. ShowPrecommitWizardReportFinalSummary();
  497. break;
  498. }
  499. }
  500. ImGui::End();
  501. }
  502. void ScriptManager::ShowBackToIntroWarning()
  503. {
  504. if (ImGui::BeginPopupModal("Return to Intro Window", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
  505. {
  506. ImGui::Text("Warning: You are returning to the intro window. Current full test suite results will be lost.\n\nAre you sure?");
  507. if (ImGui::Button("Yes"))
  508. {
  509. m_wizardSettings = PrecommitWizardSettings();
  510. ImGui::CloseCurrentPopup();
  511. }
  512. ImGui::SameLine();
  513. if (ImGui::Button("No"))
  514. {
  515. ImGui::CloseCurrentPopup();
  516. }
  517. ImGui::EndPopup();
  518. }
  519. }
  520. void ScriptManager::ShowPrecommitWizardIntro()
  521. {
  522. ImGui::Separator();
  523. ImGui::TextWrapped("Here's what will take place...\n"
  524. "1) The standard '_fulltestsuite_' script will be run.\n"
  525. "2) You'll see a summary of the test results. If any tests failed the automatic checks, "
  526. "you are strongly encouraged to address those issues first.\n"
  527. "3) You will be guided through a series of visual screenshot validations. For each one, "
  528. "you'll need to inspect an image comparison and indicate whether you see visual differences.\n"
  529. "4) The final report will be generated. Copy and paste this into your PR description.");
  530. ImGui::Separator();
  531. if (ImGui::Button("Run Full Test Suite"))
  532. {
  533. PrepareAndExecuteScript(FullSuiteScriptFilepath);
  534. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::RunFullsuiteTest;
  535. }
  536. }
  537. void ScriptManager::ShowPrecommitWizardRunFullsuiteTest()
  538. {
  539. ImGui::Text("Running Full Test Suite. Please Wait...");
  540. if (m_scriptOperations.empty() && !m_doFinalScriptCleanup)
  541. {
  542. m_scriptReporter.HideReportDialog();
  543. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFullsuiteSummary;
  544. }
  545. }
  546. void ScriptManager::ShowPrecommitWizardReportFullsuiteTest()
  547. {
  548. m_scriptReporter.DisplayScriptResultsSummary();
  549. if (ImGui::Button("See Details..."))
  550. {
  551. m_scriptReporter.OpenReportDialog();
  552. }
  553. ImGui::Separator();
  554. if (ImGui::Button("Back"))
  555. {
  556. ImGui::OpenPopup("Return to Intro Window");
  557. }
  558. ImGui::SameLine();
  559. if (ImGui::Button("Continue"))
  560. {
  561. m_wizardSettings.ProcessScriptReports(m_scriptReporter.GetScriptReport());
  562. if (!m_wizardSettings.m_reportsOrderedByThresholdToInspect.empty())
  563. {
  564. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ManualInspection;
  565. }
  566. else
  567. {
  568. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFinalSummary;
  569. }
  570. }
  571. }
  572. void ScriptManager::ShowPrecomitWizardManualInspection()
  573. {
  574. const AZStd::vector<ScriptReporter::ScriptReport>& scriptReports = m_scriptReporter.GetScriptReport();
  575. // Get the script report and screenshot test corresponding to the current index
  576. const ScriptReporter::ReportIndex currentIndex = m_wizardSettings.m_reportIterator->second;
  577. const ScriptReporter::ScriptReport& scriptReport = scriptReports[currentIndex.first];
  578. const ScriptReporter::ScreenshotTestInfo& screenshotTest = scriptReport.m_screenshotTests[currentIndex.second];
  579. ImGui::Text("Script Name: %s", scriptReport.m_scriptAssetPath.c_str());
  580. ImGui::Text("Screenshot Name: %s", screenshotTest.m_officialBaselineScreenshotFilePath.c_str());
  581. ImGui::Separator();
  582. ImGui::Text("Diff Score: %f", screenshotTest.m_officialComparisonResult.m_diffScore);
  583. // TODO: Render screenshots in ImGui.
  584. ImGui::Separator();
  585. // Check if the current index's screenshot has been manually validated and let the user know
  586. auto it = m_wizardSettings.m_reportIndexDifferenceLevelMap.find(currentIndex);
  587. if (it != m_wizardSettings.m_reportIndexDifferenceLevelMap.end())
  588. {
  589. m_wizardSettings.m_inspectionSelection = it->second;
  590. ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(0, 255, 0, 255));
  591. ImGui::Text("This inspection has been added to the report summary");
  592. ImGui::PopStyleColor();
  593. }
  594. else
  595. {
  596. ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 0, 0, 255));
  597. ImGui::Text("This inspection has not been added to the report summary");
  598. ImGui::PopStyleColor();
  599. }
  600. ImGui::TextWrapped(
  601. "Use the 'Export Png' button to inspect the screenshot. Choose from the options below that describe the difference level "
  602. "then click 'Next' to add it in the report summary. Once there are no more noticeable differences as the threshold decreases, "
  603. "click 'Finish' to generate the report summary. Note that the remaining screenshots that were not manually inspected will not "
  604. "appear in the report summary.");
  605. for (int i = 0; i < 4; ++i)
  606. {
  607. ImGui::RadioButton(PrecommitWizardSettings::ManualInspectionOptions[i], &m_wizardSettings.m_inspectionSelection, i);
  608. }
  609. if (ImGui::Button("View Diff"))
  610. {
  611. if (!Utils::RunDiffTool(screenshotTest.m_officialBaselineScreenshotFilePath, screenshotTest.m_screenshotFilePath))
  612. {
  613. ImGui::OpenPopup("Cannot open diff tool");
  614. }
  615. }
  616. if (ImGui::BeginPopupModal("Cannot open diff tool", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
  617. {
  618. ImGui::Text("Image diff is not supported on this platform, or the required diff tool is not installed.");
  619. if (ImGui::Button("Ok"))
  620. {
  621. ImGui::CloseCurrentPopup();
  622. }
  623. ImGui::EndPopup();
  624. }
  625. ImGui::SameLine();
  626. if (ImGui::Button("Export Png"))
  627. {
  628. m_wizardSettings.m_exportedPngPath = m_scriptReporter.ExportImageDiff(scriptReport, screenshotTest);
  629. }
  630. if (!m_wizardSettings.m_exportedPngPath.empty())
  631. {
  632. ImGui::SameLine();
  633. bool copyPath = ImGui::Button("Copy Path");
  634. ImGui::Text("Diff Png was exported to:");
  635. ImGui::SameLine();
  636. if (copyPath)
  637. {
  638. ImGui::LogToClipboard();
  639. }
  640. ImGui::Text("%s", m_wizardSettings.m_exportedPngPath.c_str());
  641. if (copyPath)
  642. {
  643. ImGui::LogFinish();
  644. }
  645. }
  646. ImGui::Separator();
  647. if (ImGui::Button("Back"))
  648. {
  649. if (m_wizardSettings.m_reportIterator == m_wizardSettings.m_reportsOrderedByThresholdToInspect.begin())
  650. {
  651. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFullsuiteSummary;
  652. }
  653. else
  654. {
  655. --m_wizardSettings.m_reportIterator;
  656. }
  657. }
  658. ImGui::SameLine();
  659. const bool isNextButtonDisabled =
  660. m_wizardSettings.m_inspectionSelection == PrecommitWizardSettings::DefaultInspectionSelection ? true : false;
  661. if (isNextButtonDisabled)
  662. {
  663. ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
  664. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f);
  665. }
  666. if (ImGui::Button("Next"))
  667. {
  668. m_wizardSettings.m_reportIndexDifferenceLevelMap[currentIndex] =
  669. PrecommitWizardSettings::ImageDifferenceLevel::Levels(m_wizardSettings.m_inspectionSelection);
  670. m_wizardSettings.m_inspectionSelection = PrecommitWizardSettings::DefaultInspectionSelection;
  671. m_wizardSettings.m_exportedPngPath.clear();
  672. ++m_wizardSettings.m_reportIterator;
  673. if (m_wizardSettings.m_reportIterator == m_wizardSettings.m_reportsOrderedByThresholdToInspect.end())
  674. {
  675. // Decrement the iterator to make sure it's pointing to the last element in case the user goes
  676. // back to the manual inspection page.
  677. --m_wizardSettings.m_reportIterator;
  678. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFinalSummary;
  679. }
  680. }
  681. if (isNextButtonDisabled)
  682. {
  683. ImGui::PopItemFlag();
  684. ImGui::PopStyleVar();
  685. }
  686. ImGui::SameLine();
  687. if (ImGui::Button("Finish Manual Inspection"))
  688. {
  689. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFinalSummary;
  690. }
  691. ImGui::SameLine();
  692. ImGui::Text(
  693. "%zu/%zu", aznumeric_cast<size_t>(AZStd::distance(m_wizardSettings.m_reportsOrderedByThresholdToInspect.begin(), m_wizardSettings.m_reportIterator) + 1),
  694. m_wizardSettings.m_reportsOrderedByThresholdToInspect.size());
  695. }
  696. void ScriptManager::ShowPrecommitWizardReportFinalSummary()
  697. {
  698. ImGui::Text("Tests are complete! here is the final report.");
  699. bool copyToClipboard = ImGui::Button("Copy To Clipboard");
  700. const ScriptReporter::ScriptResultsSummary resultsSummary = m_scriptReporter.GetScriptResultSummary();
  701. const AZStd::vector<ScriptReporter::ScriptReport>& scriptReports = m_scriptReporter.GetScriptReport();
  702. AZStd::vector<AZStd::vector<ScriptReporter::ReportIndex>> imageDifferenceSummary(
  703. PrecommitWizardSettings::ImageDifferenceLevel::NumDifferenceLevels);
  704. int totalValidatedScreenshots = 0;
  705. for (const auto& [reportIndex, differenceLevel] : m_wizardSettings.m_reportIndexDifferenceLevelMap)
  706. {
  707. imageDifferenceSummary[differenceLevel].push_back(reportIndex);
  708. }
  709. for (const auto& differenceLevelReports : imageDifferenceSummary)
  710. {
  711. totalValidatedScreenshots += aznumeric_cast<int>(differenceLevelReports.size());
  712. }
  713. ImGui::Separator();
  714. if (copyToClipboard)
  715. {
  716. ImGui::LogToClipboard();
  717. }
  718. ImGui::Text("RHI API: %s", AZ::RHI::Factory::Get().GetName().GetCStr());
  719. ImGui::Text("Test Script Count: %zu", scriptReports.size());
  720. ImGui::Text("Screenshot Count: %d", resultsSummary.m_totalScreenshotsCount);
  721. ImGui::Text(
  722. "Manually Validated Screenshots: %d/%zu", totalValidatedScreenshots,
  723. m_wizardSettings.m_reportsOrderedByThresholdToInspect.size());
  724. ImGui::Text("Screenshot automatic checks failed: %zu", m_wizardSettings.m_failedReports.size());
  725. for (const auto& failedReport : m_wizardSettings.m_failedReports)
  726. {
  727. const ScriptReporter::ReportIndex& reportIndex = failedReport.second;
  728. const ScriptReporter::ScriptReport& scriptReport = scriptReports[reportIndex.first];
  729. const ScriptReporter::ScreenshotTestInfo& screenshotTest = scriptReport.m_screenshotTests[reportIndex.second];
  730. ImGui::Text(
  731. "\t%s %s '%s' %f", scriptReport.m_scriptAssetPath.c_str(), screenshotTest.m_screenshotFilePath.c_str(),
  732. screenshotTest.m_toleranceLevel.m_name.c_str(), screenshotTest.m_officialComparisonResult.m_diffScore);
  733. }
  734. // Present the information by printing highest differences first. See enum class ImageDifferenceLevel
  735. for (int i = aznumeric_cast<int>(imageDifferenceSummary.size() - 1); i >= 0; --i)
  736. {
  737. if (!imageDifferenceSummary[i].empty())
  738. {
  739. ImGui::Text("Screenshot interactive check '%s'", PrecommitWizardSettings::ManualInspectionDifferenceLevels[i]);
  740. for (const auto& reportIndex : imageDifferenceSummary[i])
  741. {
  742. const ScriptReporter::ScriptReport& scriptReport = scriptReports[reportIndex.first];
  743. const ScriptReporter::ScreenshotTestInfo& screenshotTest = scriptReport.m_screenshotTests[reportIndex.second];
  744. ImGui::Text(
  745. "\t%s %s '%s' %f", scriptReport.m_scriptAssetPath.c_str(), screenshotTest.m_screenshotFilePath.c_str(),
  746. screenshotTest.m_toleranceLevel.m_name.c_str(), screenshotTest.m_officialComparisonResult.m_diffScore);
  747. }
  748. }
  749. }
  750. if (copyToClipboard)
  751. {
  752. ImGui::LogFinish();
  753. }
  754. ImGui::Separator();
  755. if (ImGui::Button("Back"))
  756. {
  757. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ManualInspection;
  758. auto reportIndexToDifference = m_wizardSettings.m_reportIndexDifferenceLevelMap.find(m_wizardSettings.m_reportIterator->second);
  759. m_wizardSettings.m_inspectionSelection = reportIndexToDifference != m_wizardSettings.m_reportIndexDifferenceLevelMap.end()
  760. ? reportIndexToDifference->second
  761. : PrecommitWizardSettings::DefaultInspectionSelection;
  762. }
  763. }
  764. void ScriptManager::PrepareAndExecuteScript(const AZStd::string& scriptFilePath)
  765. {
  766. ReportScriptableAction(AZStd::string::format("RunScript('%s')", scriptFilePath.c_str()));
  767. // Save the window size so we can restore it after running the script, in case the script calls ResizeViewport
  768. AzFramework::NativeWindowHandle defaultWindowHandle;
  769. AzFramework::WindowSize windowSize;
  770. AzFramework::WindowSystemRequestBus::BroadcastResult(defaultWindowHandle, &AzFramework::WindowSystemRequestBus::Events::GetDefaultWindowHandle);
  771. AzFramework::WindowRequestBus::EventResult(windowSize, defaultWindowHandle, &AzFramework::WindowRequests::GetClientAreaSize);
  772. m_savedViewportWidth = windowSize.m_width;
  773. m_savedViewportHeight = windowSize.m_height;
  774. if (m_savedViewportWidth == 0 || m_savedViewportHeight == 0)
  775. {
  776. AZ_Assert(false, "Could not get current window size");
  777. }
  778. else
  779. {
  780. m_shouldRestoreViewportSize = true;
  781. }
  782. // Setup the ScriptReporter to track and report the results
  783. m_scriptReporter.Reset();
  784. m_scriptReporter.SetAvailableToleranceLevels(m_imageComparisonOptions.GetAvailableToleranceLevels());
  785. if (m_imageComparisonOptions.IsLevelAdjusted())
  786. {
  787. m_scriptReporter.SetInvalidationMessage("Results are invalid because the tolerance level has been adjusted.");
  788. }
  789. else if (!m_imageComparisonOptions.IsScriptControlled())
  790. {
  791. m_scriptReporter.SetInvalidationMessage("Results are invalid because the tolerance level has been overridden.");
  792. }
  793. else
  794. {
  795. m_scriptReporter.SetInvalidationMessage("");
  796. }
  797. AZ_Assert(m_executingScripts.empty(), "There should be no active scripts at this point");
  798. ExecuteScript(scriptFilePath);
  799. }
  800. void ScriptManager::ExecuteScript(const AZStd::string& scriptFilePath)
  801. {
  802. ScriptManager* s_instance = GetInstance();
  803. AZ::Data::Asset<AZ::ScriptAsset> scriptAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::ScriptAsset>(scriptFilePath.c_str());
  804. if (!scriptAsset)
  805. {
  806. // Push an error operation on the back of the queue instead of reporting it immediately so it doesn't get lost
  807. // in front of a bunch of queued m_scriptOperations.
  808. Script_Error(AZStd::string::format("Could not find or load script asset '%s'.", scriptFilePath.c_str()));
  809. return;
  810. }
  811. if (s_instance->m_executingScripts.find(scriptAsset.GetId()) != s_instance->m_executingScripts.end())
  812. {
  813. Script_Error(AZStd::string::format("Calling script '%s' would likely cause an infinite loop and crash. Skipping.", scriptFilePath.c_str()));
  814. return;
  815. }
  816. if (s_instance->m_imageComparisonOptions.IsScriptControlled())
  817. {
  818. s_instance->m_imageComparisonOptions.SelectToleranceLevel(nullptr); // Clear the preset before each script to make sure the script is selecting it.
  819. }
  820. // Execute(script) will add commands to the m_scriptOperations. These should be considered part of their own test script, for reporting purposes.
  821. s_instance->m_scriptOperations.push([scriptFilePath]()
  822. {
  823. GetInstance()->m_scriptReporter.PushScript(scriptFilePath);
  824. }
  825. );
  826. s_instance->m_scriptOperations.push([scriptFilePath]()
  827. {
  828. AZ_Printf("Automation", "Running script '%s'...\n", scriptFilePath.c_str());
  829. }
  830. );
  831. s_instance->m_executingScripts.insert(scriptAsset.GetId());
  832. auto& scriptData = scriptAsset->m_data;
  833. if (!s_instance->m_scriptContext->Execute(scriptData.GetScriptBuffer().data(), scriptFilePath.c_str(), scriptData.GetScriptBuffer().size()))
  834. {
  835. // Push an error operation on the back of the queue instead of reporting it immediately so it doesn't get lost
  836. // in front of a bunch of queued m_scriptOperations.
  837. Script_Error(AZStd::string::format("Error running script '%s'.", scriptAsset.ToString<AZStd::string>().c_str()));
  838. }
  839. s_instance->m_executingScripts.erase(scriptAsset.GetId());
  840. // Execute(script) will have added commands to the m_scriptOperations. When they finish, consider this test as completed, for reporting purposes.
  841. s_instance->m_scriptOperations.push([]()
  842. {
  843. // We don't call m_scriptReporter.PopScript() yet because some cleanup needs to happen in TickScript() on the next frame.
  844. AZ_Assert(!GetInstance()->m_shouldPopScript, "m_shouldPopScript is already true");
  845. GetInstance()->m_shouldPopScript = true;
  846. }
  847. );
  848. }
  849. void ScriptManager::OnCameraMoveEnded(AZ::TypeId controllerTypeId, uint32_t channels)
  850. {
  851. if (controllerTypeId == azrtti_typeid<AZ::Debug::ArcBallControllerComponent>())
  852. {
  853. if (channels & AZ::Debug::ArcBallControllerChannel_Center)
  854. {
  855. AZ::Vector3 center = AZ::Vector3::CreateZero();
  856. AZ::Debug::ArcBallControllerRequestBus::EventResult(center, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetCenter);
  857. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetCenter(Vector3(%f, %f, %f))", (float)center.GetX(), (float)center.GetY(), (float)center.GetZ()));
  858. }
  859. if (channels & AZ::Debug::ArcBallControllerChannel_Pan)
  860. {
  861. AZ::Vector3 pan = AZ::Vector3::CreateZero();
  862. AZ::Debug::ArcBallControllerRequestBus::EventResult(pan, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetPan);
  863. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetPan(Vector3(%f, %f, %f))", (float)pan.GetX(), (float)pan.GetY(), (float)pan.GetZ()));
  864. }
  865. if (channels & AZ::Debug::ArcBallControllerChannel_Heading)
  866. {
  867. float heading = 0.0;
  868. AZ::Debug::ArcBallControllerRequestBus::EventResult(heading, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetHeading);
  869. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetHeading(DegToRad(%f))", AZ::RadToDeg(heading)));
  870. }
  871. if (channels & AZ::Debug::ArcBallControllerChannel_Pitch)
  872. {
  873. float pitch = 0.0;
  874. AZ::Debug::ArcBallControllerRequestBus::EventResult(pitch, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetPitch);
  875. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetPitch(DegToRad(%f))", AZ::RadToDeg(pitch)));
  876. }
  877. if (channels & AZ::Debug::ArcBallControllerChannel_Distance)
  878. {
  879. float distance = 0.0;
  880. AZ::Debug::ArcBallControllerRequestBus::EventResult(distance, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetDistance);
  881. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetDistance(%f)", distance));
  882. }
  883. }
  884. if (controllerTypeId == azrtti_typeid<AZ::Debug::NoClipControllerComponent>())
  885. {
  886. if (channels & AZ::Debug::NoClipControllerChannel_Position)
  887. {
  888. AZ::Vector3 position = AZ::Vector3::CreateZero();
  889. AZ::Debug::NoClipControllerRequestBus::EventResult(position, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetPosition);
  890. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetPosition(Vector3(%f, %f, %f))", (float)position.GetX(), (float)position.GetY(), (float)position.GetZ()));
  891. }
  892. if (channels & AZ::Debug::NoClipControllerChannel_Orientation)
  893. {
  894. float heading = 0.0;
  895. AZ::Debug::NoClipControllerRequestBus::EventResult(heading, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetHeading);
  896. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetHeading(DegToRad(%f))", AZ::RadToDeg(heading)));
  897. float pitch = 0.0;
  898. AZ::Debug::NoClipControllerRequestBus::EventResult(pitch, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetPitch);
  899. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetPitch(DegToRad(%f))", AZ::RadToDeg(pitch)));
  900. }
  901. if (channels & AZ::Debug::NoClipControllerChannel_Fov)
  902. {
  903. float fov = 0.0;
  904. AZ::Debug::NoClipControllerRequestBus::EventResult(fov, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetFov);
  905. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetFov(DegToRad(%f))", AZ::RadToDeg(fov)));
  906. }
  907. }
  908. }
  909. void ScriptManager::ReflectScriptContext(AZ::BehaviorContext* behaviorContext)
  910. {
  911. AZ::MathReflect(behaviorContext);
  912. AZ::SettingsRegistryScriptUtils::ReflectSettingsRegistryToBehaviorContext(*behaviorContext);
  913. // Utilities...
  914. behaviorContext->Method("RunScript", &Script_RunScript);
  915. behaviorContext->Method("Error", &Script_Error);
  916. behaviorContext->Method("Warning", &Script_Warning);
  917. behaviorContext->Method("Print", &Script_Print);
  918. behaviorContext->Method("IdleFrames", &Script_IdleFrames);
  919. behaviorContext->Method("IdleSeconds", &Script_IdleSeconds);
  920. behaviorContext->Method("LockFrameTime", &Script_LockFrameTime);
  921. behaviorContext->Method("UnlockFrameTime", &Script_UnlockFrameTime);
  922. behaviorContext->Method("ResizeViewport", &Script_ResizeViewport);
  923. behaviorContext->Method("SetShowImGui", &Script_SetShowImGui);
  924. behaviorContext->Method("ExecuteConsoleCommand", &Script_ExecuteConsoleCommand);
  925. // Utilities returning data (these special functions do return data because they don't read dynamic state)...
  926. behaviorContext->Method("ResolvePath", &Script_ResolvePath);
  927. behaviorContext->Method("NormalizePath", &Script_NormalizePath);
  928. behaviorContext->Method("DegToRad", &Script_DegToRad);
  929. behaviorContext->Method("GetRenderApiName", &Script_GetRenderApiName);
  930. behaviorContext->Method("GetRandomTestSeed", &Script_GetRandomTestSeed);
  931. // Samples...
  932. behaviorContext->Method("OpenSample", &Script_OpenSample);
  933. behaviorContext->Method("SetImguiValue", &Script_SetImguiValue);
  934. // Debug profilers...
  935. behaviorContext->Method("ShowTool", &Script_ShowTool);
  936. // Screenshots...
  937. behaviorContext->Method("SetScreenshotFolder", &Script_SetScreenshotFolder);
  938. behaviorContext->Method("SetTestEnvPath", &Script_SetTestEnvPath);
  939. behaviorContext->Method("SetOfficialBaselineImageFolder", &Script_SetOfficialBaselineImageFolder);
  940. behaviorContext->Method("SetLocalBaselineImageFolder", &Script_SetLocalBaselineImageFolder);
  941. behaviorContext->Method("SelectImageComparisonToleranceLevel", &Script_SelectImageComparisonToleranceLevel);
  942. behaviorContext->Method("CaptureScreenshot", &Script_CaptureScreenshot);
  943. behaviorContext->Method("CaptureScreenshotWithImGui", &Script_CaptureScreenshotWithImGui);
  944. behaviorContext->Method("CaptureScreenshotWithPreview", &Script_CaptureScreenshotWithPreview);
  945. behaviorContext->Method("CapturePassAttachment", &Script_CapturePassAttachment);
  946. // Profiling data...
  947. behaviorContext->Method("CapturePassTimestamp", &Script_CapturePassTimestamp);
  948. behaviorContext->Method("CaptureCpuFrameTime", &Script_CaptureCpuFrameTime);
  949. behaviorContext->Method("CapturePassPipelineStatistics", &Script_CapturePassPipelineStatistics);
  950. behaviorContext->Method("CaptureCpuProfilingStatistics", &Script_CaptureCpuProfilingStatistics);
  951. behaviorContext->Method("CaptureBenchmarkMetadata", &Script_CaptureBenchmarkMetadata);
  952. // Camera...
  953. behaviorContext->Method("ArcBallCameraController_SetCenter", &Script_ArcBallCameraController_SetCenter);
  954. behaviorContext->Method("ArcBallCameraController_SetPan", &Script_ArcBallCameraController_SetPan);
  955. behaviorContext->Method("ArcBallCameraController_SetDistance", &Script_ArcBallCameraController_SetDistance);
  956. behaviorContext->Method("ArcBallCameraController_SetHeading", &Script_ArcBallCameraController_SetHeading);
  957. behaviorContext->Method("ArcBallCameraController_SetPitch", &Script_ArcBallCameraController_SetPitch);
  958. behaviorContext->Method("NoClipCameraController_SetPosition", &Script_NoClipCameraController_SetPosition);
  959. behaviorContext->Method("NoClipCameraController_SetHeading", &Script_NoClipCameraController_SetHeading);
  960. behaviorContext->Method("NoClipCameraController_SetPitch", &Script_NoClipCameraController_SetPitch);
  961. behaviorContext->Method("NoClipCameraController_SetFov", &Script_NoClipCameraController_SetFov);
  962. // Asset System...
  963. AZ::BehaviorParameterOverrides expectedCountDetails = {"expectedCount", "Expected number of asset jobs; default=1", aznew AZ::BehaviorDefaultValue(1u)};
  964. const AZStd::array<AZ::BehaviorParameterOverrides, 2> assetTrackingExpectAssetArgs = {{ AZ::BehaviorParameterOverrides{}, expectedCountDetails }};
  965. behaviorContext->Method("AssetTracking_Start", &Script_AssetTracking_Start);
  966. behaviorContext->Method("AssetTracking_ExpectAsset", &Script_AssetTracking_ExpectAsset, assetTrackingExpectAssetArgs);
  967. behaviorContext->Method("AssetTracking_IdleUntilExpectedAssetsFinish", &Script_AssetTracking_IdleUntilExpectedAssetsFinish);
  968. behaviorContext->Method("AssetTracking_Stop", &Script_AssetTracking_Stop);
  969. }
  970. void ScriptManager::Script_Error(const AZStd::string& message)
  971. {
  972. auto func = [message]()
  973. {
  974. ReportScriptError(message.c_str());
  975. };
  976. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  977. }
  978. void ScriptManager::Script_Warning(const AZStd::string& message)
  979. {
  980. auto func = [message]()
  981. {
  982. ReportScriptWarning(message.c_str());
  983. };
  984. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  985. }
  986. void ScriptManager::Script_Print(const AZStd::string& message [[maybe_unused]])
  987. {
  988. #ifndef RELEASE // AZ_TracePrintf is a no-op in release builds
  989. auto func = [message]()
  990. {
  991. AZ_TracePrintf("Automation", "Script: %s\n", message.c_str());
  992. };
  993. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  994. #endif
  995. }
  996. AZStd::string ScriptManager::Script_ResolvePath(const AZStd::string& path)
  997. {
  998. return Utils::ResolvePath(path);
  999. }
  1000. AZStd::string ScriptManager::Script_NormalizePath(const AZStd::string& path)
  1001. {
  1002. AZStd::string normalizedPath = path;
  1003. AzFramework::StringFunc::Path::Normalize(normalizedPath);
  1004. return normalizedPath;
  1005. }
  1006. void ScriptManager::Script_OpenSample(const AZStd::string& sampleName)
  1007. {
  1008. auto operation = [sampleName]()
  1009. {
  1010. if (sampleName.empty())
  1011. {
  1012. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  1013. }
  1014. else
  1015. {
  1016. bool foundSample = false;
  1017. SampleComponentManagerRequestBus::BroadcastResult(foundSample, &SampleComponentManagerRequests::OpenSample, sampleName);
  1018. if (foundSample)
  1019. {
  1020. // Samples need a few frames to initialize before consuming actions from ScriptableImGui,
  1021. // so we need to wait before letting the script schedule ScriptableImGui actions.
  1022. // They need 1 frame to activate, 1 frame to start ticking, and 1 frame to guarantee
  1023. // that a sample OnTick occurs before a ScriptManager::OnTick. We schedule
  1024. // a few extra just in case.
  1025. AZ_Assert(GetInstance()->m_scriptIdleFrames == 0, "m_scriptIdleFrames is being stomped");
  1026. GetInstance()->m_scriptIdleFrames = 6;
  1027. }
  1028. }
  1029. };
  1030. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1031. }
  1032. void ScriptManager::Script_ShowTool(const AZStd::string& toolName, bool enable)
  1033. {
  1034. auto operation = [toolName, enable]()
  1035. {
  1036. bool foundTool = false;
  1037. SampleComponentManagerRequestBus::BroadcastResult(foundTool, &SampleComponentManagerRequests::ShowTool, toolName, enable);
  1038. AZ_Warning("ScriptManager", foundTool, "Can't find [%s] tool", toolName.c_str());
  1039. };
  1040. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1041. }
  1042. void ScriptManager::Script_RunScript(const AZStd::string& scriptFilePath)
  1043. {
  1044. // Unlike other Script_ callback functions, we process immediately instead of pushing onto the m_scriptOperations queue.
  1045. // This function is special because running the script is what adds more commands onto the m_scriptOperations queue.
  1046. GetInstance()->ExecuteScript(scriptFilePath);
  1047. }
  1048. void ScriptManager::Script_IdleFrames(int numFrames)
  1049. {
  1050. auto operation = [numFrames]()
  1051. {
  1052. AZ_Assert(GetInstance()->m_scriptIdleFrames == 0, "m_scriptIdleFrames is being stomped");
  1053. GetInstance()->m_scriptIdleFrames = numFrames;
  1054. };
  1055. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1056. }
  1057. void ScriptManager::Script_IdleSeconds(float numSeconds)
  1058. {
  1059. auto operation = [numSeconds]()
  1060. {
  1061. GetInstance()->m_scriptIdleSeconds = numSeconds;
  1062. };
  1063. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1064. }
  1065. void ScriptManager::Script_LockFrameTime(float seconds)
  1066. {
  1067. auto operation = [seconds]()
  1068. {
  1069. AZ::TimeUs us = AZ::SecondsToTimeUs(seconds);
  1070. AZ::CVarFixedString commandString = AZ::CVarFixedString::format("t_simulationTickDeltaOverride %" PRId64, static_cast<int64_t>(us));
  1071. AZ::Interface<AZ::IConsole>::Get()->PerformCommand(commandString.c_str());
  1072. GetInstance()->m_frameTimeIsLocked = true;
  1073. };
  1074. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1075. }
  1076. void ScriptManager::Script_UnlockFrameTime()
  1077. {
  1078. auto operation = []()
  1079. {
  1080. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("t_simulationTickDeltaOverride 0");
  1081. GetInstance()->m_frameTimeIsLocked = false;
  1082. };
  1083. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1084. }
  1085. void ScriptManager::Script_SetImguiValue(AZ::ScriptDataContext& dc)
  1086. {
  1087. if (dc.GetNumArguments() != 2)
  1088. {
  1089. ReportScriptError("Wrong number of arguments for SetImguiValue");
  1090. return;
  1091. }
  1092. if (!dc.IsString(0))
  1093. {
  1094. ReportScriptError("SetImguiValue first argument must be a string");
  1095. return;
  1096. }
  1097. const char* fieldName = nullptr;
  1098. dc.ReadArg(0, fieldName);
  1099. AZStd::string fieldNameString = fieldName; // Because the lambda will need to capture a copy of something, not a pointer
  1100. if (dc.IsBoolean(1))
  1101. {
  1102. bool value = false;
  1103. dc.ReadArg(1, value);
  1104. auto func = [fieldNameString, value]()
  1105. {
  1106. ScriptableImGui::SetBool(fieldNameString, value);
  1107. };
  1108. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  1109. }
  1110. else if (dc.IsNumber(1))
  1111. {
  1112. float value = 0.0f;
  1113. dc.ReadArg(1, value);
  1114. auto func = [fieldNameString, value]()
  1115. {
  1116. ScriptableImGui::SetNumber(fieldNameString, value);
  1117. };
  1118. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  1119. }
  1120. else if (dc.IsString(1))
  1121. {
  1122. const char* value = nullptr;
  1123. dc.ReadArg(1, value);
  1124. AZStd::string valueString = value; // Because the lambda will need to capture a copy of something, not a pointer
  1125. auto func = [fieldNameString, valueString]()
  1126. {
  1127. ScriptableImGui::SetString(fieldNameString, valueString);
  1128. };
  1129. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  1130. }
  1131. else if (dc.IsClass<AZ::Vector3>(1))
  1132. {
  1133. AZ::Vector3 value = AZ::Vector3::CreateZero();
  1134. dc.ReadArg(1, value);
  1135. auto func = [fieldNameString, value]()
  1136. {
  1137. ScriptableImGui::SetVector(fieldNameString, value);
  1138. };
  1139. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  1140. }
  1141. else if (dc.IsClass<AZ::Vector2>(1))
  1142. {
  1143. AZ::Vector2 value = AZ::Vector2::CreateZero();
  1144. dc.ReadArg(1, value);
  1145. auto func = [fieldNameString, value]()
  1146. {
  1147. ScriptableImGui::SetVector(fieldNameString, value);
  1148. };
  1149. GetInstance()->m_scriptOperations.push(AZStd::move(func));
  1150. }
  1151. }
  1152. void ScriptManager::Script_ResizeViewport(int width, int height)
  1153. {
  1154. auto operation = [width,height]()
  1155. {
  1156. if (Utils::SupportsResizeClientArea())
  1157. {
  1158. AzFramework::WindowPosOptions options;
  1159. options.m_ignoreScreenSizeLimit = true;
  1160. Utils::ResizeClientArea(width, height, options);
  1161. }
  1162. else
  1163. {
  1164. GetInstance()->ReportScriptError("ResizeViewport() is not supported on this platform");
  1165. }
  1166. };
  1167. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1168. }
  1169. void ScriptManager::Script_ExecuteConsoleCommand(const AZStd::string& command)
  1170. {
  1171. auto operation = [command]()
  1172. {
  1173. AZ::Interface<AZ::IConsole>::Get()->PerformCommand(command.c_str());
  1174. };
  1175. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1176. }
  1177. void ScriptManager::SetShowImGui(bool show)
  1178. {
  1179. m_prevShowImGui = m_showImGui;
  1180. if (show)
  1181. {
  1182. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::ShowAllImGuiPasses);
  1183. }
  1184. else
  1185. {
  1186. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::HideAllImGuiPasses);
  1187. }
  1188. m_showImGui = show;
  1189. }
  1190. void ScriptManager::Script_SetShowImGui(bool show)
  1191. {
  1192. auto operation = [show]()
  1193. {
  1194. GetInstance()->SetShowImGui(show);
  1195. };
  1196. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1197. }
  1198. bool ScriptManager::PrepareForScreenCapture(const AZStd::string& imageName)
  1199. {
  1200. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1201. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1202. pathOutcome,
  1203. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1204. imageName, true);
  1205. if (!pathOutcome.IsSuccess())
  1206. {
  1207. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1208. return false;
  1209. }
  1210. AZStd::string fullFilePath = pathOutcome.IsSuccess() ? pathOutcome.GetValue() : "";
  1211. // Delete the file if it already exists because if the screen capture fails, we don't want to do a screenshot comparison test using an old screenshot.
  1212. if (AZ::IO::LocalFileIO::GetInstance()->Exists(fullFilePath.c_str()) && !AZ::IO::LocalFileIO::GetInstance()->Remove(fullFilePath.c_str()))
  1213. {
  1214. ReportScriptError(AZStd::string::format("Failed to delete existing screenshot file '%s'.", fullFilePath.c_str()));
  1215. return false;
  1216. }
  1217. ScriptManager* s_instance = GetInstance();
  1218. s_instance->m_scriptReporter.AddScreenshotTest(imageName);
  1219. s_instance->m_isCapturePending = true;
  1220. s_instance->PauseScript();
  1221. return true;
  1222. }
  1223. void ScriptManager::Script_SetScreenshotFolder(const AZStd::string& screenshotFolder)
  1224. {
  1225. auto operation = [screenshotFolder]()
  1226. {
  1227. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1228. &AZ::Render::FrameCaptureTestRequestBus::Events::SetScreenshotFolder, screenshotFolder);
  1229. };
  1230. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1231. }
  1232. void ScriptManager::Script_SetTestEnvPath(const AZStd::string& envPath)
  1233. {
  1234. auto operation = [envPath]()
  1235. {
  1236. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1237. &AZ::Render::FrameCaptureTestRequestBus::Events::SetTestEnvPath, envPath);
  1238. };
  1239. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1240. }
  1241. void ScriptManager::Script_SetOfficialBaselineImageFolder(const AZStd::string& baselineFolder)
  1242. {
  1243. auto operation = [baselineFolder]()
  1244. {
  1245. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1246. &AZ::Render::FrameCaptureTestRequestBus::Events::SetOfficialBaselineImageFolder, baselineFolder);
  1247. };
  1248. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1249. }
  1250. void ScriptManager::Script_SetLocalBaselineImageFolder(const AZStd::string& baselineFolder)
  1251. {
  1252. auto operation = [baselineFolder]()
  1253. {
  1254. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1255. &AZ::Render::FrameCaptureTestRequestBus::Events::SetLocalBaselineImageFolder, baselineFolder);
  1256. };
  1257. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1258. }
  1259. void ScriptManager::Script_SelectImageComparisonToleranceLevel(const AZStd::string& presetName)
  1260. {
  1261. auto operation = [presetName]()
  1262. {
  1263. GetInstance()->m_imageComparisonOptions.SelectToleranceLevel(presetName);
  1264. };
  1265. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1266. }
  1267. void ScriptManager::Script_CaptureScreenshot(const AZStd::string& imageName)
  1268. {
  1269. Script_SetShowImGui(false);
  1270. auto operation = [imageName]()
  1271. {
  1272. ScriptManager* s_instance = GetInstance();
  1273. // Note this will pause the script until the capture is complete
  1274. if (PrepareForScreenCapture(imageName))
  1275. {
  1276. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1277. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1278. pathOutcome,
  1279. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1280. imageName, true);
  1281. if (!pathOutcome.IsSuccess())
  1282. {
  1283. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1284. s_instance->m_isCapturePending = false;
  1285. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1286. s_instance->ResumeScript();
  1287. return;
  1288. }
  1289. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1290. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1291. AZ::Render::FrameCaptureOutcome capOutcome;
  1292. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, screenshotFilePath);
  1293. if (!capOutcome.IsSuccess())
  1294. {
  1295. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1296. s_instance->m_isCapturePending = false;
  1297. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1298. s_instance->ResumeScript();
  1299. return;
  1300. }
  1301. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1302. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1303. }
  1304. };
  1305. ScriptManager* s_instance = GetInstance();
  1306. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1307. s_instance->m_scriptOperations.push([]()
  1308. {
  1309. GetInstance()->m_scriptReporter.CheckLatestScreenshot(GetInstance()->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1310. });
  1311. // restore imgui show/hide
  1312. s_instance->m_scriptOperations.push([]()
  1313. {
  1314. GetInstance()->SetShowImGui(GetInstance()->m_prevShowImGui);
  1315. });
  1316. }
  1317. void ScriptManager::Script_CaptureScreenshotWithImGui(const AZStd::string& imageName)
  1318. {
  1319. Script_SetShowImGui(true);
  1320. auto operation = [imageName]()
  1321. {
  1322. ScriptManager* s_instance = GetInstance();
  1323. // Note this will pause the script until the capture is complete
  1324. if (PrepareForScreenCapture(imageName))
  1325. {
  1326. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1327. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1328. pathOutcome,
  1329. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1330. imageName, true);
  1331. if (!pathOutcome.IsSuccess())
  1332. {
  1333. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1334. s_instance->m_isCapturePending = false;
  1335. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1336. s_instance->ResumeScript();
  1337. return;
  1338. }
  1339. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1340. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1341. AZ::Render::FrameCaptureOutcome capOutcome;
  1342. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, screenshotFilePath);
  1343. if (!capOutcome.IsSuccess())
  1344. {
  1345. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1346. s_instance->m_isCapturePending = false;
  1347. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1348. s_instance->ResumeScript();
  1349. return;
  1350. }
  1351. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1352. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1353. }
  1354. };
  1355. ScriptManager* s_instance = GetInstance();
  1356. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1357. s_instance->m_scriptOperations.push([]()
  1358. {
  1359. GetInstance()->m_scriptReporter.CheckLatestScreenshot(GetInstance()->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1360. });
  1361. // restore imgui show/hide
  1362. s_instance->m_scriptOperations.push([]()
  1363. {
  1364. GetInstance()->SetShowImGui(GetInstance()->m_prevShowImGui);
  1365. });
  1366. }
  1367. void ScriptManager::Script_CaptureScreenshotWithPreview(const AZStd::string& imageName)
  1368. {
  1369. auto operation = [imageName]()
  1370. {
  1371. ScriptManager* s_instance = GetInstance();
  1372. // Note this will pause the script until the capture is complete
  1373. if (PrepareForScreenCapture(imageName))
  1374. {
  1375. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1376. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1377. pathOutcome,
  1378. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1379. imageName, true);
  1380. if (!pathOutcome.IsSuccess())
  1381. {
  1382. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1383. s_instance->m_isCapturePending = false;
  1384. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1385. s_instance->ResumeScript();
  1386. return;
  1387. }
  1388. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1389. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1390. AZ::Render::FrameCaptureOutcome capOutcome;
  1391. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshotWithPreview, screenshotFilePath);
  1392. if (!capOutcome.IsSuccess())
  1393. {
  1394. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1395. s_instance->m_isCapturePending = false;
  1396. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1397. s_instance->ResumeScript();
  1398. return;
  1399. }
  1400. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1401. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1402. }
  1403. };
  1404. ScriptManager* s_instance = GetInstance();
  1405. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1406. s_instance->m_scriptOperations.push([]()
  1407. {
  1408. GetInstance()->m_scriptReporter.CheckLatestScreenshot(GetInstance()->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1409. });
  1410. }
  1411. void ScriptManager::Script_CapturePassAttachment(AZ::ScriptDataContext& dc)
  1412. {
  1413. if (dc.GetNumArguments() != 3 && dc.GetNumArguments() != 4)
  1414. {
  1415. ReportScriptError("CapturePassAttachment needs three or four arguments");
  1416. return;
  1417. }
  1418. if (!dc.IsTable(0))
  1419. {
  1420. ReportScriptError("CapturePassAttachment's first argument must be a table of strings");
  1421. return;
  1422. }
  1423. if (!dc.IsString(1) || !dc.IsString(2))
  1424. {
  1425. ReportScriptError("CapturePassAttachment's second and third argument must be strings");
  1426. return;
  1427. }
  1428. if (dc.GetNumArguments() == 4 && !dc.IsString(3))
  1429. {
  1430. ReportScriptError("CapturePassAttachment's forth argument must be a string 'Input' or 'Output'");
  1431. return;
  1432. }
  1433. const char* stringValue = nullptr;
  1434. AZStd::vector<AZStd::string> passHierarchy;
  1435. AZStd::string slot;
  1436. AZStd::string imageName;
  1437. // read slot name and output file path
  1438. dc.ReadArg(1, stringValue);
  1439. slot = AZStd::string(stringValue);
  1440. dc.ReadArg(2, stringValue);
  1441. imageName = AZStd::string(stringValue);
  1442. AZ::RPI::PassAttachmentReadbackOption readbackOption = AZ::RPI::PassAttachmentReadbackOption::Output;
  1443. if (dc.GetNumArguments() == 4)
  1444. {
  1445. AZStd::string option;
  1446. dc.ReadArg(3, option);
  1447. if (option == "Input")
  1448. {
  1449. readbackOption = AZ::RPI::PassAttachmentReadbackOption::Input;
  1450. }
  1451. }
  1452. // read pass hierarchy
  1453. AZ::ScriptDataContext stringtable;
  1454. dc.InspectTable(0, stringtable);
  1455. const char* fieldName;
  1456. int fieldIndex;
  1457. int elementIndex;
  1458. while (stringtable.InspectNextElement(elementIndex, fieldName, fieldIndex))
  1459. {
  1460. if (fieldIndex != -1)
  1461. {
  1462. if (!stringtable.IsString(elementIndex))
  1463. {
  1464. ReportScriptError("CapturePassAttachment's first argument must contain only strings");
  1465. return;
  1466. }
  1467. const char* stringTableValue = nullptr;
  1468. if (stringtable.ReadValue(elementIndex, stringTableValue))
  1469. {
  1470. passHierarchy.push_back(stringTableValue);
  1471. }
  1472. }
  1473. }
  1474. auto operation = [passHierarchy, slot, imageName, readbackOption]()
  1475. {
  1476. ScriptManager* s_instance = GetInstance();
  1477. // Note this will pause the script until the capture is complete
  1478. if (PrepareForScreenCapture(imageName))
  1479. {
  1480. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1481. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1482. pathOutcome,
  1483. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1484. imageName, true);
  1485. if (!pathOutcome.IsSuccess())
  1486. {
  1487. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1488. s_instance->m_isCapturePending = false;
  1489. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1490. s_instance->ResumeScript();
  1491. return;
  1492. }
  1493. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1494. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1495. AZ::Render::FrameCaptureOutcome capOutcome;
  1496. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CapturePassAttachment, screenshotFilePath, passHierarchy, slot, readbackOption);
  1497. if (!capOutcome.IsSuccess())
  1498. {
  1499. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1500. s_instance->m_isCapturePending = false;
  1501. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1502. s_instance->ResumeScript();
  1503. return;
  1504. }
  1505. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1506. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1507. }
  1508. };
  1509. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1510. GetInstance()->m_scriptOperations.push([]()
  1511. {
  1512. GetInstance()->m_scriptReporter.CheckLatestScreenshot(GetInstance()->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1513. });
  1514. }
  1515. void ScriptManager::OnFrameCaptureFinished(AZ::Render::FrameCaptureResult result, const AZStd::string &info)
  1516. {
  1517. m_isCapturePending = false;
  1518. m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1519. AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect();
  1520. ResumeScript();
  1521. // This is checking for the exact scenario that results from an HDR setup. The goal is to add a very specific and prominent message that will
  1522. // alert users to a common issue and what action to take. Any other Format issues will be reported by FrameCaptureSystemComponent with a
  1523. // "Can't save image with format %s to a ppm file" message.
  1524. if (result == AZ::Render::FrameCaptureResult::UnsupportedFormat && info.find(AZ::RHI::ToString(AZ::RHI::Format::R10G10B10A2_UNORM)) != AZStd::string::npos)
  1525. {
  1526. m_messageBox.OpenPopupMessage("HDR Not Supported", "Screen capture testing is not supported in HDR. Please change the system configuration to disable the HDR display feature.");
  1527. AbortScripts("Script(s) aborted due to HDR configuration.");
  1528. }
  1529. }
  1530. void ScriptManager::OnCaptureQueryTimestampFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1531. {
  1532. m_isCapturePending = false;
  1533. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1534. ResumeScript();
  1535. }
  1536. void ScriptManager::OnCaptureCpuFrameTimeFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1537. {
  1538. m_isCapturePending = false;
  1539. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1540. ResumeScript();
  1541. }
  1542. void ScriptManager::OnCaptureQueryPipelineStatisticsFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1543. {
  1544. m_isCapturePending = false;
  1545. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1546. ResumeScript();
  1547. }
  1548. void ScriptManager::OnCaptureFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1549. {
  1550. m_isCapturePending = false;
  1551. AZ::Debug::ProfilerNotificationBus::Handler::BusDisconnect();
  1552. ResumeScript();
  1553. }
  1554. void ScriptManager::OnCaptureBenchmarkMetadataFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1555. {
  1556. m_isCapturePending = false;
  1557. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1558. ResumeScript();
  1559. }
  1560. void ScriptManager::Script_CapturePassTimestamp(AZ::ScriptDataContext& dc)
  1561. {
  1562. AZStd::string outputFilePath;
  1563. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1564. if (!readScriptDataContext)
  1565. {
  1566. return;
  1567. }
  1568. auto operation = [outputFilePath]()
  1569. {
  1570. GetInstance()->m_isCapturePending = true;
  1571. GetInstance()->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1572. GetInstance()->PauseScript();
  1573. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CapturePassTimestamp, outputFilePath);
  1574. };
  1575. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1576. }
  1577. void ScriptManager::Script_CaptureCpuFrameTime(AZ::ScriptDataContext& dc)
  1578. {
  1579. AZStd::string outputFilePath;
  1580. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1581. if (!readScriptDataContext)
  1582. {
  1583. return;
  1584. }
  1585. auto operation = [outputFilePath]()
  1586. {
  1587. GetInstance()->m_isCapturePending = true;
  1588. GetInstance()->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1589. GetInstance()->PauseScript();
  1590. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CaptureCpuFrameTime, outputFilePath);
  1591. };
  1592. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1593. }
  1594. void ScriptManager::Script_CapturePassPipelineStatistics(AZ::ScriptDataContext& dc)
  1595. {
  1596. AZStd::string outputFilePath;
  1597. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1598. if (!readScriptDataContext)
  1599. {
  1600. return;
  1601. }
  1602. auto operation = [outputFilePath]()
  1603. {
  1604. GetInstance()->m_isCapturePending = true;
  1605. GetInstance()->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1606. GetInstance()->PauseScript();
  1607. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CapturePassPipelineStatistics, outputFilePath);
  1608. };
  1609. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1610. }
  1611. void ScriptManager::Script_CaptureCpuProfilingStatistics(AZ::ScriptDataContext& dc)
  1612. {
  1613. AZStd::string outputFilePath;
  1614. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1615. if (!readScriptDataContext)
  1616. {
  1617. return;
  1618. }
  1619. auto operation = [outputFilePath]()
  1620. {
  1621. GetInstance()->m_isCapturePending = true;
  1622. GetInstance()->AZ::Debug::ProfilerNotificationBus::Handler::BusConnect();
  1623. GetInstance()->PauseScript();
  1624. if (auto profilerSystem = AZ::Debug::ProfilerSystemInterface::Get(); profilerSystem)
  1625. {
  1626. profilerSystem->CaptureFrame(outputFilePath);
  1627. }
  1628. };
  1629. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1630. }
  1631. void ScriptManager::Script_CaptureBenchmarkMetadata(AZ::ScriptDataContext& dc)
  1632. {
  1633. if (dc.GetNumArguments() != 2)
  1634. {
  1635. ReportScriptError("CaptureBenchmarkMetadata needs two arguments, benchmarkName and outputFilePath.");
  1636. return;
  1637. }
  1638. if (!dc.IsString(0) || !dc.IsString(1))
  1639. {
  1640. ReportScriptError("CaptureBenchmarkMetadata's arguments benchmarkName and outputFilePath must both be of type string.");
  1641. return;
  1642. }
  1643. const char* stringValue = nullptr;
  1644. AZStd::string benchmarkName;
  1645. AZStd::string outputFilePath;
  1646. dc.ReadArg(0, stringValue);
  1647. benchmarkName = AZStd::string(stringValue);
  1648. dc.ReadArg(1, stringValue);
  1649. outputFilePath = AZStd::string(stringValue);
  1650. auto operation = [benchmarkName, outputFilePath]()
  1651. {
  1652. GetInstance()->m_isCapturePending = true;
  1653. GetInstance()->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1654. GetInstance()->PauseScript();
  1655. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CaptureBenchmarkMetadata, benchmarkName, outputFilePath);
  1656. };
  1657. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1658. }
  1659. bool ScriptManager::ValidateProfilingCaptureScripContexts(AZ::ScriptDataContext& dc, AZStd::string& outputFilePath)
  1660. {
  1661. if (dc.GetNumArguments() != 1)
  1662. {
  1663. ReportScriptError("ProfilingCaptureScriptDataContext needs one argument");
  1664. return false;
  1665. }
  1666. if (!dc.IsString(0))
  1667. {
  1668. ReportScriptError("ProfilingCaptureScriptDataContext's first (and only) argument must be of type string");
  1669. return false;
  1670. }
  1671. // Read slot name and output file path
  1672. const char* stringValue = nullptr;
  1673. dc.ReadArg(0, stringValue);
  1674. if (stringValue == nullptr)
  1675. {
  1676. ReportScriptError("ProfilingCaptureScriptDataContext failed to read the string value");
  1677. return false;
  1678. }
  1679. outputFilePath = AZStd::string(stringValue);
  1680. return true;
  1681. }
  1682. float ScriptManager::Script_DegToRad(float degrees)
  1683. {
  1684. return AZ::DegToRad(degrees);
  1685. }
  1686. AZStd::string ScriptManager::Script_GetRenderApiName()
  1687. {
  1688. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  1689. return rpiSystem->GetRenderApiName().GetCStr();
  1690. }
  1691. int ScriptManager::Script_GetRandomTestSeed()
  1692. {
  1693. return GetInstance()->m_testSuiteRunConfig.m_randomSeed;
  1694. }
  1695. void ScriptManager::CheckArcBallControllerHandler()
  1696. {
  1697. if (0 == AZ::Debug::ArcBallControllerRequestBus::GetNumOfEventHandlers(GetInstance()->m_cameraEntity->GetId()))
  1698. {
  1699. ReportScriptError("There is no handler for ArcBallControllerRequestBus for the camera entity.");
  1700. }
  1701. }
  1702. void ScriptManager::CheckNoClipControllerHandler()
  1703. {
  1704. if (0 == AZ::Debug::NoClipControllerRequestBus::GetNumOfEventHandlers(GetInstance()->m_cameraEntity->GetId()))
  1705. {
  1706. ReportScriptError("There is no handler for NoClipControllerRequestBus for the camera entity.");
  1707. }
  1708. }
  1709. void ScriptManager::Script_ArcBallCameraController_SetCenter(AZ::Vector3 center)
  1710. {
  1711. auto operation = [center]()
  1712. {
  1713. CheckArcBallControllerHandler();
  1714. AZ::Debug::ArcBallControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  1715. };
  1716. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1717. }
  1718. void ScriptManager::Script_ArcBallCameraController_SetPan(AZ::Vector3 pan)
  1719. {
  1720. auto operation = [pan]()
  1721. {
  1722. CheckArcBallControllerHandler();
  1723. AZ::Debug::ArcBallControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetPan, pan);
  1724. };
  1725. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1726. }
  1727. void ScriptManager::Script_ArcBallCameraController_SetDistance(float distance)
  1728. {
  1729. auto operation = [distance]()
  1730. {
  1731. CheckArcBallControllerHandler();
  1732. AZ::Debug::ArcBallControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, distance);
  1733. };
  1734. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1735. }
  1736. void ScriptManager::Script_ArcBallCameraController_SetHeading(float heading)
  1737. {
  1738. auto operation = [heading]()
  1739. {
  1740. CheckArcBallControllerHandler();
  1741. AZ::Debug::ArcBallControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetHeading, heading);
  1742. };
  1743. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1744. }
  1745. void ScriptManager::Script_ArcBallCameraController_SetPitch(float pitch)
  1746. {
  1747. auto operation = [pitch]()
  1748. {
  1749. CheckArcBallControllerHandler();
  1750. AZ::Debug::ArcBallControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetPitch, pitch);
  1751. };
  1752. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1753. }
  1754. void ScriptManager::Script_NoClipCameraController_SetPosition(AZ::Vector3 position)
  1755. {
  1756. auto operation = [position]()
  1757. {
  1758. CheckNoClipControllerHandler();
  1759. AZ::Debug::NoClipControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPosition, position);
  1760. };
  1761. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1762. }
  1763. void ScriptManager::Script_NoClipCameraController_SetHeading(float heading)
  1764. {
  1765. auto operation = [heading]()
  1766. {
  1767. CheckNoClipControllerHandler();
  1768. AZ::Debug::NoClipControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetHeading, heading);
  1769. };
  1770. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1771. }
  1772. void ScriptManager::Script_NoClipCameraController_SetPitch(float pitch)
  1773. {
  1774. auto operation = [pitch]()
  1775. {
  1776. CheckNoClipControllerHandler();
  1777. AZ::Debug::NoClipControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPitch, pitch);
  1778. };
  1779. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1780. }
  1781. void ScriptManager::Script_NoClipCameraController_SetFov(float fov)
  1782. {
  1783. auto operation = [fov]()
  1784. {
  1785. CheckNoClipControllerHandler();
  1786. AZ::Debug::NoClipControllerRequestBus::Event(GetInstance()->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetFov, fov);
  1787. };
  1788. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1789. }
  1790. void ScriptManager::Script_AssetTracking_Start()
  1791. {
  1792. auto operation = []()
  1793. {
  1794. GetInstance()->m_assetStatusTracker.StartTracking();
  1795. };
  1796. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1797. }
  1798. void ScriptManager::Script_AssetTracking_ExpectAsset(const AZStd::string& sourceAssetPath, uint32_t expectedCount)
  1799. {
  1800. auto operation = [sourceAssetPath, expectedCount]()
  1801. {
  1802. GetInstance()->m_assetStatusTracker.ExpectAsset(sourceAssetPath, expectedCount);
  1803. };
  1804. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1805. }
  1806. void ScriptManager::Script_AssetTracking_IdleUntilExpectedAssetsFinish(float timeout)
  1807. {
  1808. auto operation = [timeout]()
  1809. {
  1810. AZ_Assert(!GetInstance()->m_waitForAssetTracker, "It shouldn't be possible to run the next command until m_waitForAssetTracker is false");
  1811. GetInstance()->m_waitForAssetTracker = true;
  1812. GetInstance()->m_assetTrackingTimeout = timeout;
  1813. };
  1814. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1815. }
  1816. void ScriptManager::Script_AssetTracking_Stop()
  1817. {
  1818. auto operation = []()
  1819. {
  1820. GetInstance()->m_assetStatusTracker.StopTracking();
  1821. };
  1822. GetInstance()->m_scriptOperations.push(AZStd::move(operation));
  1823. }
  1824. } // namespace AtomSampleViewer