AnimationContext.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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 "EditorDefs.h"
  9. #include "AnimationContext.h"
  10. // CryCommon
  11. #include <CryCommon/Maestro/Bus/EditorSequenceBus.h>
  12. // Editor
  13. #include "TrackView/TrackViewDialog.h"
  14. #include "ViewManager.h"
  15. #include <AzCore/Serialization/Locale.h>
  16. #include <AzCore/Time/ITime.h>
  17. #include <AzToolsFramework/API/EditorCameraBus.h>
  18. #include <Maestro/Bus/EditorSequenceComponentBus.h>
  19. #include <Maestro/Types/AnimNodeType.h>
  20. //////////////////////////////////////////////////////////////////////////
  21. // Movie Callback.
  22. //////////////////////////////////////////////////////////////////////////
  23. class CMovieCallback
  24. : public IMovieCallback
  25. {
  26. protected:
  27. void OnMovieCallback(ECallbackReason reason, [[maybe_unused]] IAnimNode* pNode) override
  28. {
  29. switch (reason)
  30. {
  31. case CBR_CHANGENODE:
  32. // Invalidate nodes
  33. break;
  34. case CBR_CHANGETRACK:
  35. {
  36. // Invalidate tracks
  37. CTrackViewDialog* pTrackViewDialog = CTrackViewDialog::GetCurrentInstance();
  38. if (pTrackViewDialog)
  39. {
  40. pTrackViewDialog->InvalidateDopeSheet();
  41. }
  42. }
  43. break;
  44. }
  45. }
  46. bool IsSequenceCamUsed() const override
  47. {
  48. if (gEnv->IsEditorGameMode() == true)
  49. {
  50. return true;
  51. }
  52. if (GetIEditor()->GetViewManager() == nullptr)
  53. {
  54. return false;
  55. }
  56. CViewport* pRendView = GetIEditor()->GetViewManager()->GetViewport(ET_ViewportCamera);
  57. if (pRendView)
  58. {
  59. return pRendView->IsSequenceCamera();
  60. }
  61. return false;
  62. }
  63. };
  64. static CMovieCallback s_movieCallback;
  65. //////////////////////////////////////////////////////////////////////////
  66. //-----------------------------------------------------------------------------
  67. //!
  68. class CAnimationContextPostRender
  69. : public IPostRenderer
  70. {
  71. public:
  72. CAnimationContextPostRender(CAnimationContext* pAC)
  73. : m_pAC(pAC){}
  74. void OnPostRender() const override { assert(m_pAC); m_pAC->OnPostRender(); }
  75. protected:
  76. CAnimationContext* m_pAC;
  77. };
  78. //////////////////////////////////////////////////////////////////////////
  79. CAnimationContext::CAnimationContext()
  80. : m_movieSystem(AZ::Interface<IMovieSystem>::Get())
  81. {
  82. m_paused = 0;
  83. m_playing = false;
  84. m_recording = false;
  85. m_bSavedRecordingState = false;
  86. m_timeRange.Set(0, 0);
  87. m_timeMarker.Set(0, 0);
  88. m_currTime = 0.0f;
  89. m_lastTimeChangedNotificationTime = .0f;
  90. m_bForceUpdateInNextFrame = false;
  91. m_fTimeScale = 1.0f;
  92. m_pSequence = nullptr;
  93. m_mostRecentSequenceId.SetInvalid();
  94. m_mostRecentSequenceTime = 0.0f;
  95. m_bLooping = false;
  96. m_bAutoRecording = false;
  97. m_fRecordingTimeStep = 0;
  98. m_bSingleFrame = false;
  99. m_bPostRenderRegistered = false;
  100. m_bForcingAnimation = false;
  101. GetIEditor()->GetUndoManager()->AddListener(this);
  102. GetIEditor()->GetSequenceManager()->AddListener(this);
  103. GetIEditor()->RegisterNotifyListener(this);
  104. AzToolsFramework::Prefab::PrefabPublicNotificationBus::Handler::BusConnect();
  105. }
  106. //////////////////////////////////////////////////////////////////////////
  107. CAnimationContext::~CAnimationContext()
  108. {
  109. if (Maestro::SequenceComponentNotificationBus::Handler::BusIsConnected())
  110. {
  111. Maestro::SequenceComponentNotificationBus::Handler::BusDisconnect();
  112. }
  113. AzToolsFramework::Prefab::PrefabPublicNotificationBus::Handler::BusDisconnect();
  114. GetIEditor()->GetSequenceManager()->RemoveListener(this);
  115. GetIEditor()->GetUndoManager()->RemoveListener(this);
  116. GetIEditor()->UnregisterNotifyListener(this);
  117. }
  118. //////////////////////////////////////////////////////////////////////////
  119. void CAnimationContext::Init()
  120. {
  121. if (m_movieSystem)
  122. {
  123. m_movieSystem->SetCallback(&s_movieCallback);
  124. }
  125. REGISTER_COMMAND("mov_goToFrameEditor", (ConsoleCommandFunc)GoToFrameCmd, 0, "Make a specified sequence go to a given frame time in the editor.");
  126. }
  127. //////////////////////////////////////////////////////////////////////////
  128. void CAnimationContext::AddListener(IAnimationContextListener* pListener)
  129. {
  130. stl::push_back_unique(m_contextListeners, pListener);
  131. }
  132. //////////////////////////////////////////////////////////////////////////
  133. void CAnimationContext::RemoveListener(IAnimationContextListener* pListener)
  134. {
  135. stl::find_and_erase(m_contextListeners, pListener);
  136. }
  137. void CAnimationContext::NotifyTimeChangedListenersUsingCurrTime() const
  138. {
  139. for (size_t i = 0; i < m_contextListeners.size(); ++i)
  140. {
  141. m_contextListeners[i]->OnTimeChanged(m_currTime);
  142. }
  143. m_lastTimeChangedNotificationTime = m_currTime;
  144. }
  145. //////////////////////////////////////////////////////////////////////////
  146. void CAnimationContext::SetSequence(CTrackViewSequence* sequence, bool force, bool noNotify, bool user)
  147. {
  148. if (!force && sequence == m_pSequence)
  149. {
  150. return;
  151. }
  152. if (!m_bIsInGameMode) // In Editor Play Game mode switching Editor Viewport cameras is currently not supported.
  153. {
  154. // Restore camera in the active Editor Viewport Widget to the value saved while a sequence was activated.
  155. SwitchEditorViewportCamera(m_defaulViewCameraEntityId);
  156. }
  157. // Prevent keys being created from time change
  158. const bool bRecording = m_recording;
  159. m_recording = false;
  160. SetRecordingInternal(false);
  161. const float newSeqStartTime = sequence ? sequence->GetTimeRange().start : 0.f;
  162. m_currTime = newSeqStartTime;
  163. m_fRecordingCurrTime = newSeqStartTime;
  164. if (!m_bPostRenderRegistered)
  165. {
  166. if (GetIEditor() && GetIEditor()->GetViewManager())
  167. {
  168. CViewport* pViewport = GetIEditor()->GetViewManager()->GetViewport(ET_ViewportCamera);
  169. if (pViewport)
  170. {
  171. pViewport->AddPostRenderer(new CAnimationContextPostRender(this));
  172. m_bPostRenderRegistered = true;
  173. }
  174. }
  175. }
  176. if (m_pSequence)
  177. {
  178. const auto oldSequenceEntityId = m_pSequence->GetSequenceComponentEntityId();
  179. if (Maestro::SequenceComponentNotificationBus::Handler::BusIsConnectedId(oldSequenceEntityId))
  180. {
  181. Maestro::SequenceComponentNotificationBus::Handler::BusDisconnect(oldSequenceEntityId);
  182. }
  183. m_pSequence->Deactivate();
  184. if (m_playing)
  185. {
  186. m_pSequence->EndCutScene();
  187. }
  188. m_pSequence->UnBindFromEditorObjects();
  189. }
  190. m_pSequence = sequence;
  191. // Notify a new sequence was just selected.
  192. Maestro::EditorSequenceNotificationBus::Broadcast(&Maestro::EditorSequenceNotificationBus::Events::OnSequenceSelected, m_pSequence ? m_pSequence->GetSequenceComponentEntityId() : AZ::EntityId());
  193. if (m_pSequence)
  194. {
  195. // Set the last valid sequence that was selected.
  196. m_mostRecentSequenceId = m_pSequence->GetSequenceComponentEntityId();
  197. if (!m_mostRecentSequenceId.IsValid())
  198. {
  199. m_pSequence = nullptr;
  200. return;
  201. }
  202. // Get ready to handle camera switching in this sequence, if ever, in order to switch camera in Editor Viewport Widget
  203. Maestro::SequenceComponentNotificationBus::Handler::BusConnect(m_mostRecentSequenceId);
  204. if (m_playing)
  205. {
  206. m_pSequence->BeginCutScene(true);
  207. }
  208. m_timeRange = m_pSequence->GetTimeRange();
  209. m_timeMarker = m_timeRange;
  210. m_pSequence->Activate();
  211. m_pSequence->PrecacheData(newSeqStartTime);
  212. m_pSequence->BindToEditorObjects();
  213. }
  214. else if (user)
  215. {
  216. // If this was a sequence that was selected by the user in Track View
  217. // and it was "No Sequence" clear the m_mostRecentSequenceId so the sequence
  218. // will not be reselected at unwanted events like an undo operation.
  219. m_mostRecentSequenceId.SetInvalid();
  220. }
  221. ForceAnimation();
  222. if (!noNotify)
  223. {
  224. NotifyTimeChangedListenersUsingCurrTime();
  225. for (size_t i = 0; i < m_contextListeners.size(); ++i)
  226. {
  227. m_contextListeners[i]->OnSequenceChanged(m_pSequence);
  228. }
  229. }
  230. TimeChanged(newSeqStartTime);
  231. m_recording = bRecording;
  232. SetRecordingInternal(bRecording);
  233. }
  234. //////////////////////////////////////////////////////////////////////////
  235. bool CAnimationContext::IsInGameMode() const
  236. {
  237. const auto editor = GetIEditor();
  238. const bool isInGame = editor && editor->IsInGameMode();
  239. return m_bIsInGameMode || isInGame;
  240. }
  241. //////////////////////////////////////////////////////////////////////////
  242. bool CAnimationContext::IsInEditingMode() const
  243. {
  244. const auto editor = GetIEditor();
  245. const bool isNotEditing = !editor || editor->IsInConsolewMode() || editor->IsInTestMode() || editor->IsInLevelLoadTestMode() ||
  246. editor->IsInPreviewMode() || editor->IsInSimulationMode();
  247. return !m_bIsInGameMode && !isNotEditing;
  248. }
  249. //////////////////////////////////////////////////////////////////////////
  250. bool CAnimationContext::IsSequenceAutostartFlagOn() const
  251. {
  252. const auto sequence = GetSequence();
  253. return sequence && ((sequence->GetFlags() & IAnimSequence::eSeqFlags_PlayOnReset) != 0);
  254. }
  255. //////////////////////////////////////////////////////////////////////////
  256. void CAnimationContext::SwitchEditorViewportCamera(const AZ::EntityId& newCameraEntityId)
  257. {
  258. if (!IsInEditingMode())
  259. {
  260. return; // Camera switching is currently supported in editing mode only.
  261. }
  262. AZ::EntityId currentEditorViewportCamId;
  263. Camera::EditorCameraRequestBus::BroadcastResult(currentEditorViewportCamId, &Camera::EditorCameraRequestBus::Events::GetCurrentViewEntityId);
  264. if (currentEditorViewportCamId == newCameraEntityId)
  265. {
  266. return; // Camera in Editor Viewport Widget is already set to the requested value, avoid unneeded actions.
  267. }
  268. Camera::EditorCameraRequestBus::Broadcast(&Camera::EditorCameraRequestBus::Events::SetViewFromEntityPerspective, newCameraEntityId);
  269. }
  270. //////////////////////////////////////////////////////////////////////////
  271. void CAnimationContext::OnCameraChanged([[maybe_unused]] const AZ::EntityId&, const AZ::EntityId& newCameraEntityId)
  272. {
  273. if (!newCameraEntityId.IsValid())
  274. {
  275. return; // Only valid camera Ids are sent to the active editor viewport
  276. }
  277. if (!IsInEditingMode())
  278. {
  279. return; // Camera switching is currently supported in editing mode only.
  280. }
  281. if (!IsSequenceAutostartFlagOn())
  282. {
  283. return; // The "Autostart" flag is not set for the active sequence.
  284. }
  285. AZ::EntityId currentEditorViewportCamId;
  286. Camera::EditorCameraRequestBus::BroadcastResult( currentEditorViewportCamId, &Camera::EditorCameraRequestBus::Events::GetCurrentViewEntityId);
  287. if (currentEditorViewportCamId == newCameraEntityId)
  288. {
  289. return; // Camera in Editor Viewport Widget is already set to the requested value, avoid unneeded actions.
  290. }
  291. Camera::EditorCameraRequestBus::Broadcast(&Camera::EditorCameraRequestBus::Events::SetViewFromEntityPerspective, newCameraEntityId);
  292. }
  293. //////////////////////////////////////////////////////////////////////////
  294. void CAnimationContext::UpdateTimeRange()
  295. {
  296. if (m_pSequence)
  297. {
  298. m_timeRange = m_pSequence->GetTimeRange();
  299. // reset the current time to make sure it is clamped
  300. // to the new range.
  301. SetTime(m_currTime);
  302. }
  303. }
  304. //////////////////////////////////////////////////////////////////////////
  305. void CAnimationContext::SetTime(float t)
  306. {
  307. if (t < m_timeRange.start)
  308. {
  309. t = m_timeRange.start;
  310. }
  311. if (t > m_timeRange.end)
  312. {
  313. t = m_timeRange.end;
  314. }
  315. if (fabs(m_currTime - t) < 0.001f)
  316. {
  317. return;
  318. }
  319. m_currTime = t;
  320. m_fRecordingCurrTime = t;
  321. ForceAnimation();
  322. NotifyTimeChangedListenersUsingCurrTime();
  323. }
  324. void CAnimationContext::TimeChanged(float newTime)
  325. {
  326. if (m_pSequence)
  327. {
  328. m_mostRecentSequenceTime = newTime;
  329. m_pSequence->TimeChanged(newTime);
  330. }
  331. }
  332. //////////////////////////////////////////////////////////////////////////
  333. void CAnimationContext::OnSequenceActivated(AZ::EntityId entityId)
  334. {
  335. if (!entityId.IsValid())
  336. {
  337. AZ_Assert(false, "Expected valid sequence EntityId.");
  338. return;
  339. }
  340. const auto editor = GetIEditor();
  341. if (!editor)
  342. {
  343. AZ_Assert(false, "No Editor.");
  344. return;
  345. }
  346. const auto manager = editor->GetSequenceManager();
  347. if (!manager)
  348. {
  349. AZ_Assert(false, "No SequenceManager.");
  350. return;
  351. }
  352. const auto sequence = manager->GetSequenceByEntityId(entityId);
  353. if (!sequence)
  354. {
  355. AZ_Assert(false, "No sequence with EntityId=%s.", entityId.ToString().c_str());
  356. return;
  357. }
  358. // Store initial Editor Viewport camera EntityId
  359. Camera::EditorCameraRequestBus::BroadcastResult(m_defaulViewCameraEntityId, &Camera::EditorCameraRequestBus::Events::GetCurrentViewEntityId);
  360. // If nothing is selected and there is a valid most recent selected
  361. // try to find that sequence by id and select it. This is useful
  362. // for restoring the selected sequence during undo and redo.
  363. if (m_pSequence == nullptr && m_mostRecentSequenceId.IsValid() && entityId == m_mostRecentSequenceId)
  364. {
  365. // Hang onto this because SetSequence() will reset it.
  366. float lastTime = m_mostRecentSequenceTime;
  367. SetSequence(sequence, false, false);
  368. // Restore the current time.
  369. SetTime(lastTime);
  370. // Notify time may have changed, use m_currTime in case it was clamped by SetTime()
  371. TimeChanged(m_currTime);
  372. return;
  373. }
  374. // This method could be invoked after Undoing a sequence deletion, so try to find this sequence and reconnect it
  375. const auto entityNodes = sequence->GetAnimNodesByType(AnimNodeType::AzEntity);
  376. const auto numNodes = entityNodes.GetCount();
  377. for (unsigned int i = 0; i < numNodes; ++i)
  378. {
  379. const auto animatedEntityId = entityNodes.GetNode(i)->GetAzEntityId();
  380. if (!animatedEntityId.IsValid())
  381. {
  382. AZ_Error("AnimationContext", false, "OnSequenceActivated('%s' %s): AzEntityNode has invalid EntityId %s.",
  383. sequence->GetName().c_str(), entityId.ToString().c_str(), animatedEntityId.ToString().c_str());
  384. continue;
  385. }
  386. bool wasInvoked = false;
  387. Maestro::EditorSequenceComponentRequestBus::EventResult(
  388. wasInvoked, entityId, &Maestro::EditorSequenceComponentRequestBus::Events::AddEntityToAnimate, animatedEntityId);
  389. if (!wasInvoked)
  390. {
  391. AZ_Error("AnimationContext", false, "OnSequenceActivated('%s' %s): Failed to connect to animated EntityId %s.",
  392. sequence->GetName().c_str(), entityId.ToString().c_str(), animatedEntityId.ToString().c_str());
  393. }
  394. }
  395. }
  396. void CAnimationContext::OnSequenceDeactivated(AZ::EntityId entityId)
  397. {
  398. auto editor = GetIEditor();
  399. if (editor != nullptr)
  400. {
  401. auto manager = editor->GetSequenceManager();
  402. if (manager != nullptr)
  403. {
  404. auto sequence = manager->GetSequenceByEntityId(entityId);
  405. if (sequence != nullptr && sequence == m_pSequence)
  406. {
  407. SetSequence(nullptr, true, false);
  408. }
  409. }
  410. }
  411. }
  412. //////////////////////////////////////////////////////////////////////////
  413. void CAnimationContext::Pause()
  414. {
  415. assert(m_paused >= 0);
  416. m_paused++;
  417. if (m_recording)
  418. {
  419. SetRecordingInternal(false);
  420. }
  421. if (m_movieSystem)
  422. {
  423. m_movieSystem->Pause();
  424. }
  425. if (m_pSequence)
  426. {
  427. m_pSequence->Pause();
  428. }
  429. }
  430. //////////////////////////////////////////////////////////////////////////
  431. void CAnimationContext::Resume()
  432. {
  433. assert(m_paused > 0);
  434. m_paused--;
  435. if (m_recording && m_paused == 0)
  436. {
  437. SetRecordingInternal(true);
  438. }
  439. if (m_movieSystem)
  440. {
  441. m_movieSystem->Resume();
  442. }
  443. if (m_pSequence)
  444. {
  445. m_pSequence->Resume();
  446. }
  447. }
  448. //////////////////////////////////////////////////////////////////////////
  449. void CAnimationContext::SetRecording(bool recording)
  450. {
  451. if (recording == m_recording)
  452. {
  453. return;
  454. }
  455. m_paused = 0;
  456. m_recording = recording;
  457. m_playing = false;
  458. if (!recording && m_fRecordingTimeStep != 0)
  459. {
  460. SetAutoRecording(false, 0);
  461. }
  462. // If started recording, assume we have modified the document.
  463. GetIEditor()->SetModifiedFlag();
  464. SetRecordingInternal(recording);
  465. }
  466. //////////////////////////////////////////////////////////////////////////
  467. //////////////////////////////////////////////////////////////////////////
  468. void CAnimationContext::SetPlaying(bool playing)
  469. {
  470. if (playing == m_playing)
  471. {
  472. return;
  473. }
  474. m_paused = 0;
  475. m_playing = playing;
  476. m_recording = false;
  477. SetRecordingInternal(false);
  478. if (m_movieSystem)
  479. {
  480. if (playing)
  481. {
  482. m_movieSystem->Resume();
  483. if (m_pSequence)
  484. {
  485. m_pSequence->Resume();
  486. IMovieUser* pMovieUser = m_movieSystem->GetUser();
  487. if (pMovieUser)
  488. {
  489. m_pSequence->BeginCutScene(true);
  490. }
  491. }
  492. m_movieSystem->ResumeCutScenes();
  493. }
  494. else
  495. {
  496. m_movieSystem->Pause();
  497. if (m_pSequence)
  498. {
  499. m_pSequence->Pause();
  500. }
  501. m_movieSystem->PauseCutScenes();
  502. if (m_pSequence)
  503. {
  504. IMovieUser* pMovieUser = m_movieSystem->GetUser();
  505. if (pMovieUser)
  506. {
  507. m_pSequence->EndCutScene();
  508. }
  509. }
  510. }
  511. }
  512. }
  513. //////////////////////////////////////////////////////////////////////////
  514. void CAnimationContext::Update()
  515. {
  516. if (m_countWaitingForExitingGameMode > 0) // Waiting while Editor is exiting Play Game mode ?
  517. {
  518. if (--m_countWaitingForExitingGameMode == 0) // The 2nd frame after StopPlayInEditor event sent ?
  519. {
  520. m_bIsInGameMode = false; // Now Editor Viewport Widget is in the "Editor" state,
  521. RestoreSequenceOnEnteringEditMode(); // So restore previously active sequence and camera in Editor Viewport.
  522. }
  523. else
  524. {
  525. return; // while the Editor Viewport state goes from "Started" to "Stopping" and finally back to "Editor".
  526. }
  527. }
  528. if (m_bForceUpdateInNextFrame)
  529. {
  530. ForceAnimation();
  531. m_bForceUpdateInNextFrame = false;
  532. }
  533. if (m_paused > 0 || !(m_playing || m_bAutoRecording))
  534. {
  535. if (m_pSequence)
  536. {
  537. m_pSequence->StillUpdate();
  538. }
  539. if (!m_recording)
  540. {
  541. if (m_movieSystem)
  542. {
  543. m_movieSystem->StillUpdate();
  544. }
  545. }
  546. return;
  547. }
  548. const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs();
  549. const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs);
  550. if (!m_bAutoRecording)
  551. {
  552. AnimateActiveSequence();
  553. m_currTime += frameDeltaTime * m_fTimeScale;
  554. if (!m_recording)
  555. {
  556. if (m_movieSystem)
  557. {
  558. m_movieSystem->PreUpdate(frameDeltaTime);
  559. m_movieSystem->PostUpdate(frameDeltaTime);
  560. }
  561. }
  562. }
  563. else
  564. {
  565. m_fRecordingCurrTime += frameDeltaTime * m_fTimeScale;
  566. if (fabs(m_fRecordingCurrTime - m_currTime) > m_fRecordingTimeStep)
  567. {
  568. m_currTime += m_fRecordingTimeStep;
  569. }
  570. }
  571. if (m_currTime > m_timeMarker.end)
  572. {
  573. if (m_bAutoRecording)
  574. {
  575. SetAutoRecording(false, 0);
  576. }
  577. else
  578. {
  579. if (m_bLooping)
  580. {
  581. m_currTime = m_timeMarker.start;
  582. if (m_pSequence)
  583. {
  584. m_pSequence->OnLoop();
  585. }
  586. }
  587. else
  588. {
  589. SetPlaying(false);
  590. m_currTime = m_timeMarker.end;
  591. }
  592. }
  593. }
  594. if (fabs(m_lastTimeChangedNotificationTime - m_currTime) > 0.001f)
  595. {
  596. NotifyTimeChangedListenersUsingCurrTime();
  597. }
  598. }
  599. //////////////////////////////////////////////////////////////////////////
  600. void CAnimationContext::ForceAnimation()
  601. {
  602. if (m_bForcingAnimation)
  603. {
  604. // reentrant calls are possible when using subsequences
  605. return;
  606. }
  607. m_bForcingAnimation = true;
  608. // Before animating node, pause recording.
  609. if (m_bAutoRecording)
  610. {
  611. Pause();
  612. }
  613. AnimateActiveSequence();
  614. // Animate a second time to properly update camera DoF
  615. AnimateActiveSequence();
  616. if (m_bAutoRecording)
  617. {
  618. Resume();
  619. }
  620. m_bForcingAnimation = false;
  621. }
  622. //////////////////////////////////////////////////////////////////////////
  623. void CAnimationContext::SetAutoRecording(bool bEnable, float fTimeStep)
  624. {
  625. if (bEnable)
  626. {
  627. m_bAutoRecording = true;
  628. m_fRecordingTimeStep = fTimeStep;
  629. SetRecording(bEnable);
  630. }
  631. else
  632. {
  633. m_bAutoRecording = false;
  634. m_fRecordingTimeStep = 0;
  635. }
  636. }
  637. //////////////////////////////////////////////////////////////////////////
  638. void CAnimationContext::GoToFrameCmd(IConsoleCmdArgs* pArgs)
  639. {
  640. if (pArgs->GetArgCount() < 2)
  641. {
  642. gEnv->pLog->LogError("GoToFrame: You must provide a 'frame time' to go to");
  643. return;
  644. }
  645. assert(GetIEditor()->GetAnimation());
  646. CTrackViewSequence* pSeq = GetIEditor()->GetAnimation()->GetSequence();
  647. if (!pSeq)
  648. {
  649. gEnv->pLog->LogError("GoToFrame: No active animation sequence");
  650. return;
  651. }
  652. // console commands are in the invariant locale, for atof()
  653. AZ::Locale::ScopedSerializationLocale scopedLocale;
  654. float targetFrame = (float)atof(pArgs->GetArg(1));
  655. scopedLocale.Deactivate();
  656. if (pSeq->GetTimeRange().start > targetFrame || targetFrame > pSeq->GetTimeRange().end)
  657. {
  658. gEnv->pLog->LogError("GoToFrame: requested time %f is outside the range of sequence %s (%f, %f)", targetFrame, pSeq->GetName().c_str(), pSeq->GetTimeRange().start, pSeq->GetTimeRange().end);
  659. return;
  660. }
  661. GetIEditor()->GetAnimation()->m_currTime = targetFrame;
  662. GetIEditor()->GetAnimation()->m_bSingleFrame = true;
  663. GetIEditor()->GetAnimation()->ForceAnimation();
  664. }
  665. //////////////////////////////////////////////////////////////////////////
  666. void CAnimationContext::OnPostRender()
  667. {
  668. if (m_pSequence)
  669. {
  670. SAnimContext ac;
  671. ac.dt = 0;
  672. const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs();
  673. const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs);
  674. ac.fps = 1.0f / frameDeltaTime;
  675. ac.time = m_currTime;
  676. ac.singleFrame = true;
  677. ac.forcePlay = true;
  678. m_pSequence->Render(ac);
  679. }
  680. }
  681. void CAnimationContext::BeginUndoTransaction()
  682. {
  683. m_bSavedRecordingState = m_recording;
  684. SetRecordingInternal(false);
  685. }
  686. //////////////////////////////////////////////////////////////////////////
  687. void CAnimationContext::EndUndoTransaction()
  688. {
  689. if (m_pSequence)
  690. {
  691. m_pSequence->BindToEditorObjects();
  692. }
  693. SetRecordingInternal(m_bSavedRecordingState);
  694. }
  695. void CAnimationContext::OnPrefabInstancePropagationEnd()
  696. {
  697. if (m_pSequence)
  698. {
  699. m_pSequence->BindToEditorObjects();
  700. }
  701. }
  702. //////////////////////////////////////////////////////////////////////////
  703. void CAnimationContext::TogglePlay()
  704. {
  705. if (!IsPlaying())
  706. {
  707. SetPlaying(true);
  708. }
  709. else
  710. {
  711. SetPlaying(false);
  712. }
  713. }
  714. //////////////////////////////////////////////////////////////////////////
  715. void CAnimationContext::OnSequenceRemoved(CTrackViewSequence* pSequence)
  716. {
  717. if (m_pSequence == pSequence)
  718. {
  719. SetSequence(nullptr, true, false);
  720. }
  721. }
  722. //////////////////////////////////////////////////////////////////////////
  723. void CAnimationContext::StoreSequenceOnExitingEditMode(bool isSwitchingToGameMode)
  724. {
  725. // Store currently active Editor Viewport camera EntityId
  726. Camera::EditorCameraRequestBus::BroadcastResult(
  727. m_viewCameraEntityIdToRestore, &Camera::EditorCameraRequestBus::Events::GetCurrentViewEntityId);
  728. if (isSwitchingToGameMode)
  729. {
  730. SwitchEditorViewportCamera(AZ::EntityId()); // Switch Editor Viewport back to the default Editor camera
  731. m_bIsInGameMode = true; // and set the flag of Editor being switched into Play Game mode.
  732. }
  733. if (m_pSequence)
  734. {
  735. m_sequenceToRestore = m_pSequence->GetSequenceComponentEntityId();
  736. }
  737. else
  738. {
  739. m_sequenceToRestore.SetInvalid();
  740. }
  741. m_sequenceRestoreTime = GetTime();
  742. m_bSavedRecordingState = m_recording;
  743. SetRecordingInternal(false);
  744. SetSequence(nullptr, true, true);
  745. }
  746. //////////////////////////////////////////////////////////////////////////
  747. void CAnimationContext::RestoreSequenceOnEnteringEditMode()
  748. {
  749. m_currTime = m_sequenceRestoreTime;
  750. SetSequence(GetIEditor()->GetSequenceManager()->GetSequenceByEntityId(m_sequenceToRestore), true, true);
  751. SetTime(m_sequenceRestoreTime);
  752. SetRecordingInternal(m_bSavedRecordingState);
  753. SwitchEditorViewportCamera(m_viewCameraEntityIdToRestore); // Switch Editor Viewport back to the stored camera, which was active prior to switching to Play Game mode.
  754. }
  755. //////////////////////////////////////////////////////////////////////////
  756. void CAnimationContext::OnEditorNotifyEvent(EEditorNotifyEvent event)
  757. {
  758. switch (event)
  759. {
  760. case eNotify_OnBeginGameMode:
  761. if (m_pSequence)
  762. {
  763. // Reset the sequence, so that changed camera positions are restored
  764. m_pSequence->Reset(false);
  765. // Force recent changes made in TrackView, updating in-memory prefab using Undo/Redo framework
  766. AzToolsFramework::ScopedUndoBatch undoBatch("Update TrackView Sequence Before Playing Game");
  767. undoBatch.MarkEntityDirty(m_pSequence->GetSequenceComponentEntityId());
  768. }
  769. {
  770. // This notification arrives before even the OnStartPlayInEditorBegin and later OnStartPlayInEditor events
  771. // arrive to Editor Views, and thus switching cameras is still available.
  772. // So, after storing an active camera Id, rollback the Editor Viewport to default "Editor camera" in order
  773. // to help Editor correctly restore viewport state after switching back to Editing mode,
  774. // then set the 'm_bIsInGameMode' flag, store an active sequence and drop it.
  775. constexpr const bool isSwitchingToGameMode = true;
  776. StoreSequenceOnExitingEditMode(isSwitchingToGameMode);
  777. }
  778. break;
  779. case eNotify_OnBeginSceneSave:
  780. case eNotify_OnBeginLayerExport:
  781. if (m_pSequence)
  782. {
  783. // Reset the sequence, so that changed camera positions are restored
  784. m_pSequence->Reset(false);
  785. // Force recent changes made in TrackView, updating in-memory prefab using Undo/Redo framework
  786. AzToolsFramework::ScopedUndoBatch undoBatch("Update TrackView Sequence Before Saving");
  787. undoBatch.MarkEntityDirty(m_pSequence->GetSequenceComponentEntityId());
  788. }
  789. {
  790. // Store active sequence and camera Ids and drop this sequence.
  791. constexpr const bool isSwitchingToGameMode = false;
  792. StoreSequenceOnExitingEditMode(isSwitchingToGameMode);
  793. }
  794. break;
  795. case eNotify_OnEndGameMode:
  796. // Delay restoring previously active sequence and Editor Viewport camera, and clearing 'm_bIsInGameMode' flag,
  797. // for 2 frames, while Editor Viewport state goes from "Started" to "Stopping" and finally back to "Editor",
  798. // and switching cameras is not supported.
  799. m_countWaitingForExitingGameMode = 2;
  800. break;
  801. case eNotify_OnEndSceneSave:
  802. case eNotify_OnEndLayerExport:
  803. // Restore previously active sequence and camera in Editor Viewport.
  804. RestoreSequenceOnEnteringEditMode();
  805. break;
  806. case eNotify_OnQuit:
  807. case eNotify_OnCloseScene:
  808. SetSequence(nullptr, true, false);
  809. break;
  810. case eNotify_OnBeginNewScene:
  811. SetSequence(nullptr, false, false);
  812. break;
  813. case eNotify_OnBeginLoad:
  814. m_mostRecentSequenceId.SetInvalid();
  815. m_mostRecentSequenceTime = 0.0f;
  816. m_bSavedRecordingState = m_recording;
  817. SetRecordingInternal(false);
  818. SetSequence(nullptr, false, false);
  819. break;
  820. case eNotify_OnEndLoad:
  821. SetRecordingInternal(m_bSavedRecordingState);
  822. break;
  823. }
  824. }
  825. void CAnimationContext::SetRecordingInternal(bool enableRecording)
  826. {
  827. if (m_movieSystem)
  828. {
  829. m_movieSystem->SetRecording(enableRecording);
  830. }
  831. if (m_pSequence)
  832. {
  833. m_pSequence->SetRecording(enableRecording);
  834. }
  835. }
  836. void CAnimationContext::AnimateActiveSequence()
  837. {
  838. if (!m_pSequence)
  839. {
  840. return;
  841. }
  842. SAnimContext ac;
  843. ac.dt = 0;
  844. const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs();
  845. const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs);
  846. ac.fps = 1.0f / frameDeltaTime;
  847. ac.time = m_currTime;
  848. ac.singleFrame = true;
  849. ac.forcePlay = true;
  850. m_pSequence->Animate(ac);
  851. m_pSequence->SyncToConsole(ac);
  852. }