Merge branch 'development' into linux_ar

This commit is contained in:
sweeneys
2021-11-15 08:48:14 -08:00
160 changed files with 1507 additions and 2259 deletions
@@ -140,13 +140,13 @@ def Docking_BasicDockedTools():
# 2.5,6) Send a console command.
console_line_edit = console.findChild(QtWidgets.QLineEdit, "lineEdit")
console_line_edit.setText("t_Scale 2")
console_line_edit.setText("t_simulationTickScale 2")
QtTest.QTest.keyClick(console_line_edit, QtCore.Qt.Key_Enter)
general.get_cvar("t_Scale")
Report.result(Tests.docked_console_works, general.get_cvar("t_Scale") == "2")
general.get_cvar("t_simulationTickScale")
Report.result(Tests.docked_console_works, general.get_cvar("t_simulationTickScale") == "2")
# Reset the altered cvar
console_line_edit.setText("t_Scale 1")
console_line_edit.setText("t_simulationTickScale 1")
QtTest.QTest.keyClick(console_line_edit, QtCore.Qt.Key_Enter)
run_test()
+14 -9
View File
@@ -21,6 +21,8 @@
#include "Include/IObjectManager.h"
#include "Objects/EntityObject.h"
#include <AzCore/Time/ITime.h>
//////////////////////////////////////////////////////////////////////////
// Movie Callback.
//////////////////////////////////////////////////////////////////////////
@@ -499,25 +501,24 @@ void CAnimationContext::Update()
return;
}
ITimer* pTimer = GetIEditor()->GetSystem()->GetITimer();
const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs();
const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs);
if (!m_bAutoRecording)
{
AnimateActiveSequence();
float dt = pTimer->GetFrameTime();
m_currTime += dt * m_fTimeScale;
m_currTime += frameDeltaTime * m_fTimeScale;
if (!m_recording)
{
GetIEditor()->GetMovieSystem()->PreUpdate(dt);
GetIEditor()->GetMovieSystem()->PostUpdate(dt);
GetIEditor()->GetMovieSystem()->PreUpdate(frameDeltaTime);
GetIEditor()->GetMovieSystem()->PostUpdate(frameDeltaTime);
}
}
else
{
float dt = pTimer->GetFrameTime();
m_fRecordingCurrTime += dt * m_fTimeScale;
m_fRecordingCurrTime += frameDeltaTime * m_fTimeScale;
if (fabs(m_fRecordingCurrTime - m_currTime) > m_fRecordingTimeStep)
{
m_currTime += m_fRecordingTimeStep;
@@ -644,7 +645,9 @@ void CAnimationContext::OnPostRender()
{
SAnimContext ac;
ac.dt = 0;
ac.fps = GetIEditor()->GetSystem()->GetITimer()->GetFrameRate();
const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs();
const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs);
ac.fps = 1.0f / frameDeltaTime;
ac.time = m_currTime;
ac.singleFrame = true;
ac.forcePlay = true;
@@ -797,7 +800,9 @@ void CAnimationContext::AnimateActiveSequence()
SAnimContext ac;
ac.dt = 0;
ac.fps = GetIEditor()->GetSystem()->GetITimer()->GetFrameRate();
const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs();
const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs);
ac.fps = 1.0f / frameDeltaTime;
ac.time = m_currTime;
ac.singleFrame = true;
ac.forcePlay = true;
-1
View File
@@ -80,7 +80,6 @@ AZ_POP_DISABLE_WARNING
#include <AzQtComponents/Utilities/QtPluginPaths.h>
// CryCommon
#include <CryCommon/ITimer.h>
#include <CryCommon/ILevelSystem.h>
// Editor
+8 -3
View File
@@ -19,6 +19,7 @@
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Asset/AssetManager.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Time/ITime.h>
#include <AzCore/Utils/Utils.h>
#include <MathConversion.h>
@@ -749,7 +750,9 @@ bool CCryEditDoc::OnOpenDocument(const QString& lpszPathName)
bool CCryEditDoc::BeforeOpenDocument(const QString& lpszPathName, TOpenDocContext& context)
{
CTimeValue loading_start_time = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
const CTimeValue loading_start_time(timeSec);
bool usePrefabSystemForLevels = false;
AzFramework::ApplicationRequests::Bus::BroadcastResult(
@@ -790,7 +793,7 @@ bool CCryEditDoc::BeforeOpenDocument(const QString& lpszPathName, TOpenDocContex
bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context)
{
CTimeValue& loading_start_time = context.loading_start_time;
const CTimeValue& loading_start_time = context.loading_start_time;
bool isPrefabEnabled = false;
AzFramework::ApplicationRequests::Bus::BroadcastResult(isPrefabEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled);
@@ -860,7 +863,9 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context)
StartStreamingLoad();
CTimeValue loading_end_time = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
const CTimeValue loading_end_time(timeSec);
CLogFile::FormatLine("-----------------------------------------------------------");
CLogFile::FormatLine("Successfully opened document %s", context.absoluteLevelPath.toUtf8().data());
-1
View File
@@ -105,7 +105,6 @@
#include <CryFile.h>
#include <ISystem.h>
#include <IIndexedMesh.h>
#include <ITimer.h>
#include <IXml.h>
#include <IMovieSystem.h>
+2 -2
View File
@@ -822,7 +822,7 @@ void CGameEngine::Update()
if (gEnv->pSystem)
{
gEnv->pSystem->UpdatePreTickBus();
componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME));
componentApplication->Tick();
gEnv->pSystem->UpdatePostTickBus();
}
@@ -838,7 +838,7 @@ void CGameEngine::Update()
unsigned int updateFlags = ESYSUPDATE_EDITOR;
GetIEditor()->GetAnimation()->Update();
GetIEditor()->GetSystem()->UpdatePreTickBus(updateFlags);
componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME));
componentApplication->Tick();
GetIEditor()->GetSystem()->UpdatePostTickBus(updateFlags);
}
}
@@ -25,7 +25,6 @@
#include <Mocks/ISystemMock.h>
#include <Mocks/IConsoleMock.h>
#include <Mocks/ILogMock.h>
#include <Mocks/ITimerMock.h>
#include <Mocks/IConsoleMock.h>
#include "IEditorMock.h"
-1
View File
@@ -7,7 +7,6 @@
*/
#include <AzCore/Debug/Timer.h>
#include <AzCore/Debug/TraceMessageBus.h>
#include <AzCore/std/typetraits/typetraits.h>
#include <AzCore/UnitTest/TestTypes.h>
@@ -19,7 +19,6 @@
#include <AzCore/Slice/SliceSystemComponent.h>
#include <AzCore/Slice/SliceMetadataInfoComponent.h>
#include <AzCore/UserSettings/UserSettingsComponent.h>
#include <AzCore/Time/TimeSystemComponent.h>
#include <AzCore/Console/LoggerSystemComponent.h>
#include <AzCore/EBus/EventSchedulerSystemComponent.h>
#include <AzCore/Task/TaskGraphSystemComponent.h>
@@ -40,7 +39,6 @@ namespace AZ
SliceComponent::CreateDescriptor(),
SliceSystemComponent::CreateDescriptor(),
SliceMetadataInfoComponent::CreateDescriptor(),
TimeSystemComponent::CreateDescriptor(),
LoggerSystemComponent::CreateDescriptor(),
EventSchedulerSystemComponent::CreateDescriptor(),
TaskGraphSystemComponent::CreateDescriptor(),
@@ -59,7 +57,6 @@ namespace AZ
{
return AZ::ComponentTypeList
{
azrtti_typeid<TimeSystemComponent>(),
azrtti_typeid<LoggerSystemComponent>(),
azrtti_typeid<EventSchedulerSystemComponent>(),
azrtti_typeid<TaskGraphSystemComponent>(),
@@ -72,6 +72,7 @@
#include <AzCore/Module/Environment.h>
#include <AzCore/std/string/conversions.h>
#include <AzCore/Time/TimeSystem.h>
static void PrintEntityName(const AZ::ConsoleCommandContainer& arguments)
{
@@ -416,6 +417,7 @@ namespace AZ
ComponentApplication::ComponentApplication(int argC, char** argV)
: m_eventLogger{}
, m_timeSystem(AZStd::make_unique<TimeSystem>())
{
if (Interface<ComponentApplicationRequests>::Get() == nullptr)
{
@@ -574,7 +576,6 @@ namespace AZ
DestroyAllocator();
}
void ReportBadEngineRoot()
{
AZStd::string errorMessage = {"Unable to determine a valid path to the engine.\n"
@@ -677,7 +678,6 @@ namespace AZ
ComponentApplicationBus::Handler::BusConnect();
m_currentTime = AZStd::chrono::system_clock::now();
TickRequestBus::Handler::BusConnect();
#if defined(AZ_ENABLE_DEBUG_TOOLS)
@@ -1413,31 +1413,23 @@ namespace AZ
#endif
}
void ComponentApplication::Tick(float deltaOverride /*= -1.f*/)
void ComponentApplication::Tick()
{
AZ_PROFILE_SCOPE(System, "Component application simulation tick");
{
AZ_PROFILE_SCOPE(System, "Component application simulation tick");
AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now();
m_deltaTime = 0.0f;
if (now >= m_currentTime)
{
AZStd::chrono::duration<float> delta = now - m_currentTime;
m_deltaTime = deltaOverride >= 0.f ? deltaOverride : delta.count();
}
{
AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:ExecuteQueuedEvents");
TickBus::ExecuteQueuedEvents();
}
m_currentTime = now;
{
AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick");
EBUS_EVENT(TickBus, OnTick, m_deltaTime, ScriptTimePoint(now));
}
AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:ExecuteQueuedEvents");
TickBus::ExecuteQueuedEvents();
}
{
AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick");
const AZ::TimeUs deltaTimeUs = m_timeSystem->AdvanceTickDeltaTimes();
const float deltaTimeSeconds = AZ::TimeUsToSeconds(deltaTimeUs);
AZ::TickBus::Broadcast(&TickEvents::OnTick, deltaTimeSeconds, GetTimeAtCurrentTick());
}
m_timeSystem->ApplyTickRateLimiterIfNeeded();
}
void ComponentApplication::TickSystem()
@@ -1519,13 +1511,10 @@ namespace AZ
appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Invalid;
}
//=========================================================================
// GetFrameTime
// [1/22/2016]
//=========================================================================
float ComponentApplication::GetTickDeltaTime()
{
return m_deltaTime;
const AZ::TimeUs gameTickTime = m_timeSystem->GetSimulationTickDeltaTimeUs();
return AZ::TimeUsToSeconds(gameTickTime);
}
//=========================================================================
@@ -1534,7 +1523,8 @@ namespace AZ
//=========================================================================
ScriptTimePoint ComponentApplication::GetTimeAtCurrentTick()
{
return ScriptTimePoint(m_currentTime);
const AZ::TimeUs lastGameTickTime = m_timeSystem->GetLastSimulationTickTime();
return ScriptTimePoint(AZ::TimeUsToChrono(lastGameTickTime));
}
//=========================================================================
@@ -30,12 +30,14 @@
#include <AzCore/std/string/conversions.h>
#include <AzCore/std/string/osstring.h>
namespace AZ
{
class BehaviorContext;
class IConsole;
class Module;
class ModuleManager;
class TimeSystem;
}
namespace AZ::Debug
{
@@ -237,7 +239,7 @@ namespace AZ
/**
* Ticks all components using the \ref AZ::TickBus during simulation time. May not tick if the application is not active (i.e. not in focus)
*/
virtual void Tick(float deltaOverride = -1.f);
virtual void Tick();
/**
* Ticks all using the \ref AZ::SystemTickBus at all times. Should always tick even if the application is not active.
@@ -359,8 +361,6 @@ namespace AZ
}
}
AZStd::chrono::system_clock::time_point m_currentTime{ AZStd::chrono::system_clock::time_point::max() };
float m_deltaTime{ 0.0f };
AZStd::unique_ptr<ModuleManager> m_moduleManager;
AZStd::unique_ptr<SettingsRegistryInterface> m_settingsRegistry;
EntityAddedEvent m_entityAddedEvent;
@@ -381,6 +381,8 @@ namespace AZ
AZ::SettingsRegistryInterface::NotifyEventHandler m_projectNameChangedHandler;
AZ::SettingsRegistryInterface::NotifyEventHandler m_commandLineUpdatedHandler;
AZStd::unique_ptr<AZ::TimeSystem> m_timeSystem;
// ConsoleFunctorHandle is responsible for unregistering the Settings Registry Console
// from the m_console member when it goes out of scope
AZ::SettingsRegistryConsoleUtils::ConsoleFunctorHandle m_settingsRegistryConsoleFunctors;
@@ -60,7 +60,7 @@ namespace AZ
void EventSchedulerSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
{
TimeMs startTime = GetElapsedTimeMs();
TimeMs startTime = AZ::GetElapsedTimeMs();
bool usingTimeslice = bg_maxScheduledEventProcessTimeMs != TimeMs{ 0 };
while (!m_queue.empty())
@@ -76,7 +76,7 @@ namespace AZ
while (!m_pendingQueue.empty())
{
if (usingTimeslice && (GetElapsedTimeMs() - startTime > bg_maxScheduledEventProcessTimeMs))
if (usingTimeslice && (AZ::GetElapsedTimeMs() - startTime > bg_maxScheduledEventProcessTimeMs))
{
AZLOG_WARN("Failed to trigger all pending scheduled events, %u events remain on the pending queue", aznumeric_cast<uint32_t>(m_pendingQueue.size()));
break;
@@ -103,7 +103,7 @@ namespace AZ
durationMs = TimeMs{ 0 };
}
TimeMs currentMilliseconds = GetElapsedTimeMs();
TimeMs currentMilliseconds = AZ::GetElapsedTimeMs();
if (timedEvent->m_handle == nullptr)
{
timedEvent->m_handle = AllocateHandle();
@@ -122,7 +122,7 @@ namespace AZ
durationMs = TimeMs{ 0 };
}
TimeMs currentMilliseconds = GetElapsedTimeMs();
TimeMs currentMilliseconds = AZ::GetElapsedTimeMs();
ScheduledEvent* timedEvent = AllocateManagedEvent(callback, eventName);
const bool ownsScheduledEvent = true;
*(timedEvent->m_handle) = ScheduledEventHandle(TimeMs(currentMilliseconds + durationMs), durationMs, timedEvent, ownsScheduledEvent);
@@ -76,7 +76,7 @@ namespace AZ
TimeMs ScheduledEvent::TimeInQueueMs() const
{
return GetElapsedTimeMs() - m_timeInserted;
return AZ::GetElapsedTimeMs() - m_timeInserted;
}
TimeMs ScheduledEvent::RemainingTimeInQueueMs() const
+121 -9
View File
@@ -12,8 +12,8 @@
#include <AzCore/EBus/EBus.h>
#include <AzCore/RTTI/RTTI.h>
#include <AzCore/RTTI/TypeSafeIntegral.h>
#include <AzCore/std/time.h>
#include <AzCore/std/chrono/chrono.h>
#include <AzCore/std/time.h>
namespace AZ
{
@@ -24,15 +24,21 @@ namespace AZ
//! Using int64_t as the underlying type, this is good to represent approximately 292,471 years
AZ_TYPE_SAFE_INTEGRAL(TimeUs, int64_t);
namespace Time
{
static const AZ::TimeMs ZeroTimeMs = AZ::TimeMs{ 0 };
static const AZ::TimeUs ZeroTimeUs = AZ::TimeUs{ 0 };
}
//! @class ITime
//! @brief This is an AZ::Interface<> for managing time related operations.
//! AZ::ITime and associated types may not operate in realtime. These abstractions are to allow our application
//! simulation to operate both slower and faster than realtime in a well defined and user controllable manner
//! The rate at which time passes for AZ::ITime is controlled by the cvar t_scale
//! t_scale == 0 means simulation time should halt
//! 0 < t_scale < 1 will cause time to pass slower than realtime, with t_scale 0.1 being roughly 1/10th realtime
//! t_scale == 1 will cause time to pass at roughly realtime
//! t_scale > 1 will cause time to pass faster than normal, with t_scale 10 being roughly 10x realtime
//! The rate at which time passes for AZ::ITime is controlled by the cvar t_simulationTickScale
//! t_simulationTickScale == 0 means simulation time should halt
//! 0 < t_simulationTickScale < 1 will cause time to pass slower than realtime, with t_simulationTickScale 0.1 being roughly 1/10th realtime
//! t_simulationTickScale == 1 will cause time to pass at roughly realtime
//! t_simulationTickScale > 1 will cause time to pass faster than normal, with t_simulationTickScale 10 being roughly 10x realtime
class ITime
{
public:
@@ -41,15 +47,72 @@ namespace AZ
ITime() = default;
virtual ~ITime() = default;
//! Returns the number of milliseconds since application start.
//! @return the number of milliseconds that have elapsed since application start
//! Returns the number of milliseconds since application start scaled by t_simulationTickScale.
//! @return The number of milliseconds that have elapsed since application start.
virtual TimeMs GetElapsedTimeMs() const = 0;
//! Returns the number of microseconds since application start.
//! Returns the number of microseconds since application start scaled by t_simulationTickScale.
//! @return the number of microseconds that have elapsed since application start
virtual TimeUs GetElapsedTimeUs() const = 0;
//! Returns the number of milliseconds since application start.
//! This value is not affected by the t_simulationTickScale cvar.
//! @return The number of milliseconds that have elapsed since application start.
virtual TimeMs GetRealElapsedTimeMs() const = 0;
//! Returns the number of microseconds since application start.
//! This value is not affected by the t_simulationTickScale cvar.
//! @return The number of microseconds that have elapsed since application start.
virtual TimeUs GetRealElapsedTimeUs() const = 0;
//! Returns the current simulation tick delta time.
//! This is affected by the cvars t_simulationTickScale, t_simulationTickDeltaOverride, and t_maxGameTickDelta.
//! @return The number of microseconds elapsed since the last game tick.
virtual TimeUs GetSimulationTickDeltaTimeUs() const = 0;
//! Returns the non-manipulated tick time.
//! @return The number of microseconds elapsed since the last game tick.
virtual TimeUs GetRealTickDeltaTimeUs() const = 0;
//! Returns the time since application start of when the last simulation tick was updated.
virtual TimeUs GetLastSimulationTickTime() const = 0;
//! If > 0 this will override the simulation tick delta time with the provided value.
//! When enabled this will ignore any set simulation tick scale.
//! Setting to 0 disables the override.
//! @param timeMs The time in milliseconds to use for the tick delta.
virtual void SetSimulationTickDeltaOverride(TimeMs timeMs) = 0;
//! Returns the current simulation tick override.
//! 0 means disabled.
//! @returns The current simulation tick override in milliseconds.
virtual TimeMs GetSimulationTickDeltaOverride() const = 0;
//! A scalar amount to adjust the passage of time by, 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime.
//! @param scale The scalar value to apply to the simulation time.
virtual void SetSimulationTickScale(float scale) = 0;
//! Returns the current simulation tick scale.
//! 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime.
//! @returns The simulation tick scale value.
virtual float GetSimulationTickScale() const = 0;
//! The minimum rate to force the simulation tick to run.
//! 0 for as fast as possible. 30 = ~33ms, 60 = ~16ms.
//! Setting to 0 will disable rate limiting.
//! @note It is not guaranteed to hit the requested tick rate exactly.
//! @param rate The rate in frames per second.
virtual void SetSimulationTickRate(int rate) = 0;
//! Return the current simulation tick rate.
//! 0 means disabled.
//! @return The rate in frames per second.
virtual int32_t GetSimulationTickRate() const = 0;
AZ_DISABLE_COPY_MOVE(ITime);
static const AZ::TimeMs ZeroTimeMs = AZ::TimeMs{ 0 };
static const AZ::TimeUs ZeroTimeUs = AZ::TimeUs{ 0 };
};
// EBus wrapper for ScriptCanvas
@@ -74,6 +137,29 @@ namespace AZ
return AZ::Interface<ITime>::Get()->GetElapsedTimeUs();
}
inline TimeMs GetRealElapsedTimeMs()
{
return AZ::Interface<ITime>::Get()->GetRealElapsedTimeMs();
}
//! This is a simple convenience wrapper
inline TimeUs GetSimulationTickDeltaTimeUs()
{
return AZ::Interface<ITime>::Get()->GetSimulationTickDeltaTimeUs();
}
//! This is a simple convenience wrapper
inline TimeUs GetRealTickDeltaTimeUs()
{
return AZ::Interface<ITime>::Get()->GetRealTickDeltaTimeUs();
}
//! This is a simple convenience wrapper
inline TimeUs GetLastSimulationTickTime()
{
return AZ::Interface<ITime>::Get()->GetLastSimulationTickTime();
}
//! Converts from milliseconds to microseconds
inline TimeUs TimeMsToUs(TimeMs value)
{
@@ -92,12 +178,24 @@ namespace AZ
return static_cast<float>(value) / 1000.0f;
}
//! Converts from milliseconds to seconds
inline double TimeMsToSecondsDouble(TimeMs value)
{
return static_cast<double>(value) / 1000.0;
}
//! Converts from microseconds to seconds
inline float TimeUsToSeconds(TimeUs value)
{
return static_cast<float>(value) / 1000000.0f;
}
//! Converts from microseconds to seconds
inline double TimeUsToSecondsDouble(TimeUs value)
{
return static_cast<double>(value) / 1000000.0;
}
//! Converts from milliseconds to AZStd::chrono::time_point
inline auto TimeMsToChrono(TimeMs value)
{
@@ -113,6 +211,20 @@ namespace AZ
auto chronoValue = AZStd::chrono::microseconds(aznumeric_cast<int64_t>(value));
return epoch + chronoValue;
}
//! A utility function to convert from seconds to TimeMs
inline TimeMs SecondsToTimeMs(const double value)
{
const double valueMs = value * 1000.0;
return static_cast<TimeMs>(static_cast<int64_t>(valueMs));
}
//! A utility function to convert from seconds to TimeUs
inline TimeUs SecondsToTimeUs(const double value)
{
const double valueMs = value * 1000000.0;
return static_cast<TimeUs>(static_cast<int64_t>(valueMs));
}
} // namespace AZ
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(AZ::TimeMs);
@@ -0,0 +1,214 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Time/TimeSystem.h>
#include <AzCore/Console/IConsole.h>
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Serialization/SerializeContext.h>
namespace AZ
{
namespace
{
void cvar_t_simulationTickScale_Changed(const float& value)
{
if (auto* timeSystem = AZ::Interface<ITime>::Get())
{
timeSystem->SetSimulationTickScale(value);
}
}
void cvar_t_simulationTickDeltaOverride_Changed(const float& value)
{
if (auto* timeSystem = AZ::Interface<ITime>::Get())
{
timeSystem->SetSimulationTickDeltaOverride(AZ::SecondsToTimeMs(value));
}
}
void cvar_t_simulationTickRate_Changed(const int& rate)
{
AZ_Warning("tick", false, "Simulation tick rate limiting is currently disabled. Setting will not be applied.");
if (auto* timeSystem = AZ::Interface<ITime>::Get())
{
timeSystem->SetSimulationTickRate(rate);
}
}
} // namespace
AZ_CVAR(float, t_simulationTickScale, 1.0f, cvar_t_simulationTickScale_Changed, AZ::ConsoleFunctorFlags::Null,
"A scalar amount to adjust time passage by, 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime");
AZ_CVAR(float, t_simulationTickDeltaOverride, 0.0f, cvar_t_simulationTickDeltaOverride_Changed, AZ::ConsoleFunctorFlags::Null,
"If > 0, overrides the simulation tick delta time with the provided value (Seconds) and ignores any t_simulationTickScale value.");
AZ_CVAR(int, t_simulationTickRate, 0, cvar_t_simulationTickRate_Changed, AZ::ConsoleFunctorFlags::Null,
"The minimum rate to force the game simulation tick to run. 0 for as fast as possible. 30 = ~33ms, 60 = ~16ms");
void TimeSystem::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<TimeSystem, ITime>()
->Version(1);
}
}
TimeSystem::TimeSystem()
{
m_lastInvokedTimeUs = static_cast<TimeUs>(AZStd::GetTimeNowMicroSecond());
AZ::Interface<ITime>::Register(this);
ITimeRequestBus::Handler::BusConnect();
}
TimeSystem::~TimeSystem()
{
AZ::Interface<ITime>::Unregister(this);
ITimeRequestBus::Handler::BusDisconnect();
}
TimeMs TimeSystem::GetElapsedTimeMs() const
{
return AZ::TimeUsToMs(GetElapsedTimeUs());
}
TimeUs TimeSystem::GetElapsedTimeUs() const
{
TimeUs currentTime = static_cast<TimeUs>(AZStd::GetTimeNowMicroSecond());
TimeUs deltaTime = currentTime - m_lastInvokedTimeUs;
if (t_simulationTickScale != 1.0f)
{
const float floatDelta = AZStd::GetMax(static_cast<float>(deltaTime) * t_simulationTickScale, 1.0f);
deltaTime = static_cast<TimeUs>(static_cast<int64_t>(floatDelta));
}
m_accumulatedTimeUs += deltaTime;
m_lastInvokedTimeUs = currentTime;
return m_accumulatedTimeUs;
}
TimeMs TimeSystem::GetRealElapsedTimeMs() const
{
return AZ::TimeUsToMs(GetRealElapsedTimeUs());
}
TimeUs TimeSystem::GetRealElapsedTimeUs() const
{
return static_cast<TimeUs>(AZStd::GetTimeNowMicroSecond());
}
TimeUs TimeSystem::GetSimulationTickDeltaTimeUs() const
{
return m_simulationTickDeltaTimeUs;
}
TimeUs TimeSystem::GetRealTickDeltaTimeUs() const
{
return m_realTickDeltaTimeUs;
}
TimeUs TimeSystem::GetLastSimulationTickTime() const
{
return m_lastSimulationTickTimeUs;
}
TimeUs TimeSystem::AdvanceTickDeltaTimes()
{
const TimeUs currentTimeUs = static_cast<TimeUs>(AZStd::GetTimeNowMicroSecond());
//real time
m_realTickDeltaTimeUs = currentTimeUs - m_lastRealTickTimeUs;
m_lastRealTickTimeUs = currentTimeUs;
//game time
if (m_simulationTickDeltaOverride > AZ::Time::ZeroTimeUs)
{
m_simulationTickDeltaTimeUs = m_simulationTickDeltaOverride;
m_lastSimulationTickTimeUs = m_simulationTickDeltaTimeUs;
return m_simulationTickDeltaTimeUs;
}
m_simulationTickDeltaTimeUs = currentTimeUs - m_lastSimulationTickTimeUs;
if (!AZ::IsClose(t_simulationTickScale, 1.0f))
{
const double floatDelta = AZStd::GetMax(static_cast<double>(m_simulationTickDeltaTimeUs) * static_cast<double>(t_simulationTickScale), 1.0);
m_simulationTickDeltaTimeUs = static_cast<TimeUs>(static_cast<int64_t>(floatDelta));
}
m_lastSimulationTickTimeUs = currentTimeUs;
return m_simulationTickDeltaTimeUs;
}
void TimeSystem::ApplyTickRateLimiterIfNeeded()
{
// Currently disabling the Tick rate limiter as there are some reported issues when using it.
#ifdef ENABLE_TICK_RATE_LIMITER
// If tick rate limiting is on, ensure (1 / t_simulationTickRate) ms has elapsed since the last frame,
// sleeping if there's still time remaining.
if (t_simulationTickRate > 0)
{
const TimeUs currentTimeUs = AZ::GetRealElapsedTimeUs();
const TimeUs timeUntilNextTick = (m_lastSimulationTickTimeUs + m_simulationTickLimitTimeUs) - currentTimeUs;
if (timeUntilNextTick > AZ::Time::ZeroTimeUs)
{
AZ_TracePrintf("tick", "Sleeping for %.2f", AZ::TimeUsToSecondsDouble(timeUntilNextTick));
AZStd::this_thread::sleep_for(AZStd::chrono::microseconds(static_cast<int64_t>(timeUntilNextTick)));
}
}
#endif // #ifdef ENABLE_TICK_RATE_LIMITER
}
void TimeSystem::SetSimulationTickDeltaOverride(TimeMs timeMs)
{
const TimeUs timeUs = AZ::TimeMsToUs(timeMs);
if (timeUs != m_simulationTickDeltaOverride)
{
m_simulationTickDeltaOverride = timeUs;
t_simulationTickDeltaOverride = AZ::TimeUsToSeconds(timeUs); //update the cvar
}
}
TimeMs TimeSystem::GetSimulationTickDeltaOverride() const
{
return AZ::TimeUsToMs(m_simulationTickDeltaOverride);
}
void TimeSystem::SetSimulationTickScale(float scale)
{
if (!AZ::IsClose(scale, t_simulationTickScale))
{
t_simulationTickScale = scale;
}
}
float TimeSystem::GetSimulationTickScale() const
{
return t_simulationTickScale;
}
void TimeSystem::SetSimulationTickRate(int rate)
{
m_simulationTickLimitRate = AZStd::abs(rate);
if (m_simulationTickLimitRate != 0)
{
m_simulationTickLimitTimeUs = AZ::SecondsToTimeUs(1.0f / m_simulationTickLimitRate);
}
else
{
m_simulationTickLimitTimeUs = AZ::Time::ZeroTimeUs;
}
}
int32_t TimeSystem::GetSimulationTickRate() const
{
return m_simulationTickLimitRate;
}
} // namespace AZ
@@ -0,0 +1,84 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/RTTI/RTTI.h>
#include <AzCore/Time/ITime.h>
namespace AZ
{
class ReflectContext;
//! Implementation of the ITime system interface.
class TimeSystem
: public ITimeRequestBus::Handler
{
public:
AZ_RTTI(AZ::TimeSystem, "{CE1C5E4F-7DC1-4248-B10C-AC55E8924A48}", AZ::ITime);
static void Reflect(AZ::ReflectContext* context);
TimeSystem();
virtual ~TimeSystem();
//! ITime overrides.
//! @{
TimeMs GetElapsedTimeMs() const override;
TimeUs GetElapsedTimeUs() const override;
TimeMs GetRealElapsedTimeMs() const override;
TimeUs GetRealElapsedTimeUs() const override;
TimeUs GetSimulationTickDeltaTimeUs() const override;
TimeUs GetRealTickDeltaTimeUs() const override;
TimeUs GetLastSimulationTickTime() const override;
void SetSimulationTickDeltaOverride(TimeMs timeMs) override;
TimeMs GetSimulationTickDeltaOverride() const override;
void SetSimulationTickScale(float scale) override;
float GetSimulationTickScale() const override;
void SetSimulationTickRate(int rate) override;
int32_t GetSimulationTickRate() const override;
//! @}
//! Advances the Simulation and Real tick delta time counters.
//! This is called from the owner of the TimeSystem, ComponentApplication in Tick().
//! @return The delta in microseconds from the last call to AdvanceTickDeltaTimes(). Value will be the same as GetSimulationTickDeltaTimeUs().
TimeUs AdvanceTickDeltaTimes();
//! If t_simulationTickRate is >0 this will try to have the game delta time run at a maximum of the rate set.
//! This is called from the owner of the TimeSystem, ComponentApplication in Tick().
//! example. If t_simulationTickRate is set to 60Fps, and the game tick delta is <17ms(60fps), this will add a sleep for the remaining time.
//! example. If t_simulationTickRate is set to 60Fps, and the game tick delta is >=17ms(60fps), this will not sleep at all.
//! @note It is not guaranteed to hit the requested tick rate exactly.
void ApplyTickRateLimiterIfNeeded();
private:
//! Used to calculate the delta time between calls to GetElapsedTimeMs/TimeUs().
//! Mutable to allow GetElapsedTimeMs/TimeUs() to be a const functions.
mutable TimeUs m_lastInvokedTimeUs = AZ::Time::ZeroTimeUs;
//! Accumulates the delta time of GetElapsedTimeMs/TimeUs() calls.
//! Mutable to allow GetElapsedTimeMs/TimeUs() to be a const functions.
mutable TimeUs m_accumulatedTimeUs = AZ::Time::ZeroTimeUs;
//! The current game tick delta time.
//! Can be affected by time system cvars.
//! Updated in AdvanceTickDeltaTimes().
TimeUs m_simulationTickDeltaTimeUs = AZ::Time::ZeroTimeUs;
//! The current real tick delta time.
//! Will not be affected by time system cvars.
//! Updated in AdvanceTickDeltaTimes().
TimeUs m_realTickDeltaTimeUs = AZ::Time::ZeroTimeUs;
TimeUs m_lastSimulationTickTimeUs = AZ::Time::ZeroTimeUs; //!< Used to determine the game tick delta time (affected by cvars).
TimeUs m_lastRealTickTimeUs = AZ::Time::ZeroTimeUs; //!< Used to determine the real game tick delta time (not affected by cvars).
TimeUs m_simulationTickDeltaOverride = AZ::Time::ZeroTimeUs; //<! Stores the TimeUs value of the t_simulationTickDeltaOverride cvar.
TimeUs m_simulationTickLimitTimeUs = AZ::Time::ZeroTimeUs; //<! Stores the TimeUs value of the t_simulationTickRate cvar.
int32_t m_simulationTickLimitRate = 0; //<! Stores the simulation rate limit in frames per second.
};
}
@@ -1,80 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Time/TimeSystemComponent.h>
#include <AzCore/Console/IConsole.h>
#include <AzCore/Serialization/SerializeContext.h>
namespace AZ
{
AZ_CVAR(float, t_scale, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "A scalar amount to adjust time passage by, 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime");
void TimeSystemComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<TimeSystemComponent, AZ::Component>()
->Version(1);
}
}
void TimeSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC_CE("TimeService"));
}
void TimeSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC_CE("TimeService"));
}
TimeSystemComponent::TimeSystemComponent()
{
m_lastInvokedTimeUs = static_cast<TimeUs>(AZStd::GetTimeNowMicroSecond());
AZ::Interface<ITime>::Register(this);
ITimeRequestBus::Handler::BusConnect();
}
TimeSystemComponent::~TimeSystemComponent()
{
ITimeRequestBus::Handler::BusDisconnect();
AZ::Interface<ITime>::Unregister(this);
}
void TimeSystemComponent::Activate()
{
;
}
void TimeSystemComponent::Deactivate()
{
;
}
TimeMs TimeSystemComponent::GetElapsedTimeMs() const
{
return TimeUsToMs(GetElapsedTimeUs());
}
TimeUs TimeSystemComponent::GetElapsedTimeUs() const
{
TimeUs currentTime = static_cast<TimeUs>(AZStd::GetTimeNowMicroSecond());
TimeUs deltaTime = currentTime - m_lastInvokedTimeUs;
if (t_scale != 1.0f)
{
float floatDelta = static_cast<float>(deltaTime) * t_scale;
deltaTime = static_cast<TimeUs>(static_cast<int64_t>(floatDelta));
}
m_accumulatedTimeUs += deltaTime;
m_lastInvokedTimeUs = currentTime;
return m_accumulatedTimeUs;
}
}
@@ -1,50 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/Time/ITime.h>
#include <AzCore/Component/Component.h>
#include <AzCore/Console/IConsole.h>
namespace AZ
{
//! Implementation of the ITime system interface.
class TimeSystemComponent
: public AZ::Component
, public ITimeRequestBus::Handler
{
public:
AZ_COMPONENT(TimeSystemComponent, "{CE1C5E4F-7DC1-4248-B10C-AC55E8924A48}");
static void Reflect(AZ::ReflectContext* context);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
TimeSystemComponent();
virtual ~TimeSystemComponent();
//! AZ::Component overrides.
//! @{
void Activate() override;
void Deactivate() override;
//! @}
//! ITime overrides.
//! @{
TimeMs GetElapsedTimeMs() const override;
TimeUs GetElapsedTimeUs() const override;
//! @}
private:
mutable TimeUs m_lastInvokedTimeUs = TimeUs{0};
mutable TimeUs m_accumulatedTimeUs = TimeUs{0};
};
}
@@ -0,0 +1,119 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/Time/TimeSystem.h>
#include <gmock/gmock.h>
namespace AZ
{
class MockTimeSystem;
using NiceTimeSystemMock =::testing::NiceMock<MockTimeSystem>;
//used if you wish to mock any of the Get time functions.
class MockTimeSystem
: public ITimeRequestBus::Handler
{
public:
MockTimeSystem()
{
AZ::Interface<ITime>::Register(this);
ITimeRequestBus::Handler::BusConnect();
}
virtual ~MockTimeSystem()
{
AZ::Interface<ITime>::Unregister(this);
ITimeRequestBus::Handler::BusDisconnect();
}
MOCK_CONST_METHOD0(GetElapsedTimeMs, TimeMs());
MOCK_CONST_METHOD0(GetElapsedTimeUs, TimeUs());
MOCK_CONST_METHOD0(GetRealElapsedTimeMs, TimeMs());
MOCK_CONST_METHOD0(GetRealElapsedTimeUs, TimeUs());
MOCK_CONST_METHOD0(GetSimulationTickDeltaTimeUs, TimeUs());
MOCK_CONST_METHOD0(GetRealTickDeltaTimeUs, TimeUs());
MOCK_CONST_METHOD0(GetLastSimulationTickTime, TimeUs());
MOCK_METHOD1(SetSimulationTickDeltaOverride, void(TimeMs));
MOCK_CONST_METHOD0(GetSimulationTickDeltaOverride, TimeMs());
MOCK_METHOD1(SetSimulationTickScale, void(float));
MOCK_CONST_METHOD0(GetSimulationTickScale, float());
MOCK_METHOD1(SetSimulationTickRate, void(int));
MOCK_CONST_METHOD0(GetSimulationTickRate, int32_t());
};
//used if you wish to override any of the Get time functions with specific functionality.
class StubTimeSystem
: public AZ::TimeSystem
{
public:
AZ_RTTI(AZ::StubTimeSystem, "{DD5D5A6A-345F-49FD-A61E-A40E63C49CFA}", AZ::TimeSystem);
virtual AZ::TimeMs GetElapsedTimeMs() const override
{
return AZ::Time::ZeroTimeMs;
}
virtual AZ::TimeUs GetElapsedTimeUs() const override
{
return AZ::Time::ZeroTimeUs;
}
virtual AZ::TimeMs GetRealElapsedTimeMs() const override
{
return AZ::Time::ZeroTimeMs;
}
virtual AZ::TimeUs GetRealElapsedTimeUs() const override
{
return AZ::Time::ZeroTimeUs;
}
virtual AZ::TimeUs GetSimulationTickDeltaTimeUs() const override
{
return AZ::Time::ZeroTimeUs;
}
virtual AZ::TimeUs GetRealTickDeltaTimeUs() const override
{
return AZ::Time::ZeroTimeUs;
}
virtual AZ::TimeUs GetLastSimulationTickTime() const override
{
return AZ::Time::ZeroTimeUs;
}
virtual void SetSimulationTickDeltaOverride([[maybe_unused]]TimeMs timeMs) override
{
}
virtual TimeMs GetSimulationTickDeltaOverride() const override
{
return AZ::Time::ZeroTimeMs;
}
virtual void SetSimulationTickScale([[maybe_unused]] float scale) override
{
}
virtual float GetSimulationTickScale() const override
{
return 1.0f;
}
virtual void SetSimulationTickRate([[maybe_unused]] int rate) override
{
}
virtual int32_t GetSimulationTickRate() const override
{
return 0;
}
};
} // namespace AZ
@@ -654,8 +654,8 @@ set(FILES
Threading/ThreadUtils.h
Threading/ThreadUtils.cpp
Time/ITime.h
Time/TimeSystemComponent.cpp
Time/TimeSystemComponent.h
Time/TimeSystem.cpp
Time/TimeSystem.h
)
# Prevent the following files from being grouped in UNITY builds
@@ -12,5 +12,6 @@ set(FILES
UnitTest/UnitTest.h
UnitTest/TestTypes.h
UnitTest/Mocks/MockFileIOBase.h
UnitTest/Mocks/MockITime.h
UnitTest/Mocks/MockSettingsRegistry.h
)
-1
View File
@@ -6,7 +6,6 @@
*
*/
#include <AzCore/Debug/Timer.h>
#include <AzCore/Debug/StackTracer.h>
#include <AzCore/Debug/TraceMessagesDrillerBus.h>
#include <AzCore/Debug/Profiler.h>
@@ -11,7 +11,7 @@
#include <AzCore/EBus/ScheduledEvent.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Console/LoggerSystemComponent.h>
#include <AzCore/Time/TimeSystemComponent.h>
#include <AzCore/Time/TimeSystem.h>
#include <AzCore/Name/NameDictionary.h>
#include <AzCore/UnitTest/TestTypes.h>
@@ -26,22 +26,22 @@ namespace UnitTest
SetupAllocator();
AZ::NameDictionary::Create();
m_loggerComponent = new AZ::LoggerSystemComponent;
m_timeComponent = new AZ::TimeSystemComponent;
m_eventSchedulerComponent = new AZ::EventSchedulerSystemComponent;
m_loggerComponent = AZStd::make_unique<AZ::LoggerSystemComponent>();
m_timeSystem = AZStd::make_unique<AZ::TimeSystem>();
m_eventSchedulerComponent = AZStd::make_unique<AZ::EventSchedulerSystemComponent>();
m_testEvent = new AZ::ScheduledEvent([this] { TestBasicEvent(); }, AZ::Name("UnitTestEvent fire once event"));
m_testRequeue = new AZ::ScheduledEvent([this] { TestAutoRequeuedEvent(); }, AZ::Name("UnitTestEvent auto Requeue"));
m_testEvent = AZStd::make_unique<AZ::ScheduledEvent>([this] { TestBasicEvent(); }, AZ::Name("UnitTestEvent fire once event"));
m_testRequeue = AZStd::make_unique<AZ::ScheduledEvent>([this] { TestAutoRequeuedEvent(); }, AZ::Name("UnitTestEvent auto Requeue"));
}
void TearDown() override
{
delete m_testEvent;
delete m_testRequeue;
m_testEvent.reset();
m_testRequeue.reset();
delete m_eventSchedulerComponent;
delete m_timeComponent;
delete m_loggerComponent;
m_eventSchedulerComponent.reset();
m_timeSystem.reset();
m_loggerComponent.reset();
AZ::NameDictionary::Destroy();
TeardownAllocator();
@@ -60,12 +60,12 @@ namespace UnitTest
uint32_t m_basicEventTriggerCount = 0;
uint32_t m_requeuedEventTriggerCount = 0;
AZ::ScheduledEvent* m_testEvent = nullptr;
AZ::ScheduledEvent* m_testRequeue = nullptr;
AZStd::unique_ptr<AZ::ScheduledEvent> m_testEvent;
AZStd::unique_ptr<AZ::ScheduledEvent> m_testRequeue;
AZ::LoggerSystemComponent* m_loggerComponent = nullptr;
AZ::TimeSystemComponent* m_timeComponent = nullptr;
AZ::EventSchedulerSystemComponent* m_eventSchedulerComponent = nullptr;
AZStd::unique_ptr<AZ::LoggerSystemComponent> m_loggerComponent;
AZStd::unique_ptr<AZ::TimeSystem> m_timeSystem;
AZStd::unique_ptr<AZ::EventSchedulerSystemComponent> m_eventSchedulerComponent;
};
TEST_F(ScheduledEventTests, TestFireOnce)
+28 -4
View File
@@ -6,7 +6,7 @@
*
*/
#include <AzCore/Time/TimeSystemComponent.h>
#include <AzCore/Time/TimeSystem.h>
#include <AzCore/UnitTest/TestTypes.h>
namespace UnitTest
@@ -18,16 +18,16 @@ namespace UnitTest
void SetUp() override
{
SetupAllocator();
m_timeComponent = new AZ::TimeSystemComponent;
m_timeSystem = AZStd::make_unique<AZ::TimeSystem>();
}
void TearDown() override
{
delete m_timeComponent;
m_timeSystem.reset();
TeardownAllocator();
}
AZ::TimeSystemComponent* m_timeComponent = nullptr;
AZStd::unique_ptr<AZ::TimeSystem> m_timeSystem;
};
TEST_F(TimeTests, TestConversionUsToMs)
@@ -44,6 +44,30 @@ namespace UnitTest
EXPECT_EQ(timeUs, AZ::TimeUs{ 1000000 });
}
TEST_F(TimeTests, TestConversionTimeMsToSeconds)
{
AZ::TimeMs timeMs = AZ::TimeMs{ 1000 };
float timeSecondsFloat = AZ::TimeMsToSeconds(timeMs);
EXPECT_TRUE(AZ::IsClose(timeSecondsFloat, 1.0f));
double timeSecondsDouble = AZ::TimeMsToSecondsDouble(timeMs);
EXPECT_TRUE(AZ::IsClose(timeSecondsDouble, 1.0));
}
TEST_F(TimeTests, TestConversionSecondsToTimeUs)
{
double seconds = 1.0;
AZ::TimeUs timeUs = AZ::SecondsToTimeUs(seconds);
EXPECT_EQ(timeUs, AZ::TimeUs{ 1000000 });
}
TEST_F(TimeTests, TestConversionSecondsToTimeMs)
{
double seconds = 1.0;
AZ::TimeMs timeMs = AZ::SecondsToTimeMs(seconds);
EXPECT_EQ(timeMs, AZ::TimeMs{ 1000 });
}
TEST_F(TimeTests, TestClocks)
{
AZ::TimeUs timeUs = AZ::GetElapsedTimeUs();
@@ -553,11 +553,9 @@ namespace AzFramework
////////////////////////////////////////////////////////////////////////////
AZ_CVAR(float, t_frameTimeOverride, 0.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "If > 0, overrides the application delta frame-time with the provided value");
void Application::Tick(float deltaOverride /*= -1.f*/)
void Application::Tick()
{
ComponentApplication::Tick((t_frameTimeOverride > 0.0f) ? t_frameTimeOverride : deltaOverride);
ComponentApplication::Tick();
}
////////////////////////////////////////////////////////////////////////////
@@ -87,7 +87,7 @@ namespace AzFramework
*/
virtual void Stop();
void Tick(float deltaOverride = -1.f) override;
void Tick() override;
AZ::ComponentTypeList GetRequiredSystemComponents() const override;
@@ -534,7 +534,7 @@ namespace AzFramework
void TransformComponent::SetParentImpl(AZ::EntityId parentId, bool isKeepWorldTM)
{
if (parentId == GetEntityId())
if (GetEntity() && parentId == GetEntityId())
{
AZ_Warning("TransformComponent", false, "An entity can not be set as its own parent.");
return;
@@ -42,7 +42,7 @@ namespace AzNetworking
{
const uint32_t sampleAtom = 1 - m_activeAtom;
if (m_atoms[sampleAtom].m_timeAccumulatorMs == AZ::TimeMs{0})
if (m_atoms[sampleAtom].m_timeAccumulatorMs == AZ::Time::ZeroTimeMs)
{
return 0.0f;
}
@@ -19,7 +19,7 @@ namespace AzNetworking
{
DatarateAtom() = default;
AZ::TimeMs m_timeAccumulatorMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_timeAccumulatorMs = AZ::Time::ZeroTimeMs;
uint32_t m_bytesTransmitted = 0;
uint32_t m_packetsSent = 0;
uint32_t m_packetsLost = 0;
@@ -78,7 +78,7 @@ namespace AzNetworking
ConnectionPacketEntry(PacketId packetId, AZ::TimeMs sendTimeMs);
PacketId m_packetId = InvalidPacketId;
AZ::TimeMs m_sendTimeMs = AZ::TimeMs{0};
AZ::TimeMs m_sendTimeMs = AZ::Time::ZeroTimeMs;
};
//! @class ConnectionComputeRtt
@@ -28,8 +28,8 @@ namespace AzNetworking
ConnectionQuality(int32_t lossPercentage, AZ::TimeMs latencyMs, AZ::TimeMs varianceMs);
int32_t m_lossPercentage = 0;
AZ::TimeMs m_latencyMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_varianceMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_latencyMs = AZ::Time::ZeroTimeMs;
AZ::TimeMs m_varianceMs = AZ::Time::ZeroTimeMs;
};
enum class TrustZone
@@ -37,8 +37,8 @@ namespace AzNetworking
void UpdateTimeoutTime(AZ::TimeMs currentTimeMs);
uint64_t m_userData = 0;
AZ::TimeMs m_timeoutMs = AZ::TimeMs{0};
AZ::TimeMs m_nextTimeoutTimeMs = AZ::TimeMs{0};
AZ::TimeMs m_timeoutMs = AZ::Time::ZeroTimeMs;
AZ::TimeMs m_nextTimeoutTimeMs = AZ::Time::ZeroTimeMs;
};
TimeoutQueue() = default;
@@ -15,11 +15,11 @@ namespace AzNetworking
struct NetworkInterfaceMetrics
{
//! Returns the total number of milliseconds spent updating this network interface.
AZ::TimeMs m_updateTimeMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_updateTimeMs = AZ::Time::ZeroTimeMs;
//! Returns the total number of connections bound to this network interface.
uint64_t m_connectionCount = 0;
//! Returns the total number of milliseconds spent sending data on this network interface.
AZ::TimeMs m_sendTimeMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_sendTimeMs = AZ::Time::ZeroTimeMs;
//! Returns the total number of packets sent on this socket.
uint64_t m_sendPackets = 0;
//! Returns the total number of encrypted packets sent on this socket.
@@ -37,7 +37,7 @@ namespace AzNetworking
//! Returns the total number of packets that had to be resent on this network interface due to packet loss.
uint64_t m_resentPackets = 0;
//! Returns the total number of milliseconds spent processing received data on this network interface.
AZ::TimeMs m_recvTimeMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_recvTimeMs = AZ::Time::ZeroTimeMs;
//! Returns the total number of packets received on this socket.
uint64_t m_recvPackets = 0;
//! Returns the total number of bytes received on this socket after compression.
@@ -67,6 +67,6 @@ namespace AzNetworking
uint32_t m_listenPortCount = 0;
TcpSocketManager m_tcpSocketManager;
AZ::ThreadSafeDeque<ListenPort> m_listenPorts;
AZ::TimeMs m_updateTimeMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_updateTimeMs = AZ::Time::ZeroTimeMs;
};
}
@@ -107,7 +107,7 @@ namespace AzNetworking
auto readCallback = [this, startTimeMs](SocketFd socketFd) { HandleConnectionRecv(socketFd, startTimeMs); };
auto writeCallback = [this](SocketFd socketFd) { HandleConnectionSend(socketFd); };
m_tcpSocketManager.ProcessEvents(AZ::TimeMs{ 0 }, readCallback, writeCallback);
m_tcpSocketManager.ProcessEvents(AZ::Time::ZeroTimeMs, readCallback, writeCallback);
FlushQueuedRemoves();
@@ -146,7 +146,7 @@ namespace AzNetworking
AZ::Name m_name;
TrustZone m_trustZone;
uint16_t m_port = 0;
AZ::TimeMs m_timeoutMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_timeoutMs = AZ::Time::ZeroTimeMs;
IConnectionListener& m_connectionListener;
TcpConnectionSet m_connectionSet;
TcpSocketManager m_tcpSocketManager;
@@ -736,7 +736,7 @@ namespace AzNetworking
udpConnection->SendUnreliablePacket(CorePackets::HeartbeatPacket(true));
++udpConnection->m_timeoutCounter;
}
else if (net_UdpTimeoutConnections && (GetTimeoutMs() > AZ::TimeMs{ 0 }))
else if (net_UdpTimeoutConnections && (GetTimeoutMs() > AZ::Time::ZeroTimeMs))
{
udpConnection->Disconnect(DisconnectReason::Timeout, TerminationEndpoint::Local);
return TimeoutResult::Delete;
@@ -171,7 +171,7 @@ namespace AzNetworking
TrustZone m_trustZone;
uint16_t m_port = 0;
bool m_allowIncomingConnections = false;
AZ::TimeMs m_timeoutMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_timeoutMs = AZ::Time::ZeroTimeMs;
IConnectionListener& m_connectionListener;
UdpConnectionSet m_connectionSet;
TimeoutQueue m_connectionTimeoutQueue;
@@ -94,6 +94,6 @@ namespace AzNetworking
int32_t m_backIndex = 0;
AZStd::array<ReaderBuffer, 2> m_readerBuffers;
AZStd::vector<UdpSocket*> m_pendingAdds;
AZ::TimeMs m_updateTimeMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_updateTimeMs = AZ::Time::ZeroTimeMs;
};
}
@@ -135,7 +135,7 @@ namespace AzNetworking
int32_t sentBytes = size;
#ifdef ENABLE_LATENCY_DEBUG
if (connectionQuality.m_latencyMs <= AZ::TimeMs{ 0 })
if (connectionQuality.m_latencyMs <= AZ::Time::ZeroTimeMs)
#endif
{
sentBytes = SendInternal(address, data, size, encrypt, dtlsEndpoint);
@@ -153,9 +153,9 @@ namespace AzNetworking
}
}
#ifdef ENABLE_LATENCY_DEBUG
else if ((connectionQuality.m_latencyMs > AZ::TimeMs{ 0 }) || (connectionQuality.m_varianceMs > AZ::TimeMs{ 0 }))
else if ((connectionQuality.m_latencyMs > AZ::Time::ZeroTimeMs) || (connectionQuality.m_varianceMs > AZ::Time::ZeroTimeMs))
{
const AZ::TimeMs jitterMs = aznumeric_cast<AZ::TimeMs>(m_random.GetRandom()) % (connectionQuality.m_varianceMs > AZ::TimeMs{ 0 }
const AZ::TimeMs jitterMs = aznumeric_cast<AZ::TimeMs>(m_random.GetRandom()) % (connectionQuality.m_varianceMs > AZ::Time::ZeroTimeMs
? connectionQuality.m_varianceMs
: AZ::TimeMs{ 1 });
const AZ::TimeMs deferTimeMs = (connectionQuality.m_latencyMs) + jitterMs;
@@ -94,7 +94,7 @@ namespace AzNetworking
static const uint32_t MaxCookieHistory = 8;
static bool g_encryptionInitialized = false;
static int32_t g_azNetworkingTrustDataIndex = 0;
static AZ::TimeMs g_lastCookieTimestamp = AZ::TimeMs{0};
static AZ::TimeMs g_lastCookieTimestamp = AZ::Time::ZeroTimeMs;
static uint64_t g_validCookieArray[MaxCookieHistory];
static uint32_t g_cookieReplaceIndex = 0;
@@ -15,7 +15,7 @@ namespace UnitTest
{
AzNetworking::PacketId m_packetId = AzNetworking::InvalidPacketId;
uint32_t m_id = 0;
AZ::TimeMs m_timeMs = AZ::TimeMs{ 0 };
AZ::TimeMs m_timeMs = AZ::Time::ZeroTimeMs;
float m_blendFactor = 0.f;
AZStd::vector<int> m_growVector, m_shrinkVector;
@@ -11,7 +11,7 @@
#include <AzNetworking/AutoGen/CorePackets.AutoPackets.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Console/LoggerSystemComponent.h>
#include <AzCore/Time/TimeSystemComponent.h>
#include <AzCore/Time/TimeSystem.h>
#include <AzCore/Name/NameDictionary.h>
#include <AzCore/UnitTest/TestTypes.h>
@@ -102,24 +102,24 @@ namespace UnitTest
SetupAllocator();
AZ::NameDictionary::Create();
m_loggerComponent = new AZ::LoggerSystemComponent;
m_timeComponent = new AZ::TimeSystemComponent;
m_networkingSystemComponent = new AzNetworking::NetworkingSystemComponent;
m_loggerComponent = AZStd::make_unique<AZ::LoggerSystemComponent>();
m_timeSystem = AZStd::make_unique<AZ::TimeSystem>();
m_networkingSystemComponent = AZStd::make_unique<AzNetworking::NetworkingSystemComponent>();
}
void TearDown() override
{
delete m_networkingSystemComponent;
delete m_timeComponent;
delete m_loggerComponent;
m_networkingSystemComponent.reset();
m_timeSystem.reset();
m_loggerComponent.reset();
AZ::NameDictionary::Destroy();
TeardownAllocator();
}
AZ::LoggerSystemComponent* m_loggerComponent;
AZ::TimeSystemComponent* m_timeComponent;
AzNetworking::NetworkingSystemComponent* m_networkingSystemComponent;
AZStd::unique_ptr<AZ::LoggerSystemComponent> m_loggerComponent;
AZStd::unique_ptr<AZ::TimeSystem> m_timeSystem;
AZStd::unique_ptr<AzNetworking::NetworkingSystemComponent> m_networkingSystemComponent;
};
#if AZ_TRAIT_DISABLE_FAILED_NETWORKING_TESTS
@@ -14,7 +14,7 @@
#include <AzNetworking/AutoGen/CorePackets.AutoPackets.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Console/LoggerSystemComponent.h>
#include <AzCore/Time/TimeSystemComponent.h>
#include <AzCore/Time/TimeSystem.h>
#include <AzCore/Name/NameDictionary.h>
#include <AzCore/UnitTest/TestTypes.h>
@@ -105,24 +105,24 @@ namespace UnitTest
SetupAllocator();
AZ::NameDictionary::Create();
m_loggerComponent = new AZ::LoggerSystemComponent;
m_timeComponent = new AZ::TimeSystemComponent;
m_networkingSystemComponent = new AzNetworking::NetworkingSystemComponent;
m_loggerComponent = AZStd::make_unique<AZ::LoggerSystemComponent>();
m_timeSystem = AZStd::make_unique<AZ::TimeSystem>();
m_networkingSystemComponent = AZStd::make_unique<AzNetworking::NetworkingSystemComponent>();
}
void TearDown() override
{
delete m_networkingSystemComponent;
delete m_timeComponent;
delete m_loggerComponent;
m_networkingSystemComponent.reset();
m_timeSystem.reset();
m_loggerComponent.reset();
AZ::NameDictionary::Destroy();
TeardownAllocator();
}
AZ::LoggerSystemComponent* m_loggerComponent;
AZ::TimeSystemComponent* m_timeComponent;
AzNetworking::NetworkingSystemComponent* m_networkingSystemComponent;
AZStd::unique_ptr<AZ::LoggerSystemComponent> m_loggerComponent;
AZStd::unique_ptr<AZ::TimeSystem> m_timeSystem;
AZStd::unique_ptr<AzNetworking::NetworkingSystemComponent> m_networkingSystemComponent;
};
TEST_F(UdpTransportTests, PacketIdWrap)
@@ -362,23 +362,11 @@ namespace AzToolsFramework
// Tick the component app.
AZ::ComponentApplication* pApp = nullptr;
EBUS_EVENT_RESULT(pApp, AZ::ComponentApplicationBus, GetApplication);
if (pApp)
if (pApp && m_ptrTicker)
{
AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now();
static AZStd::chrono::system_clock::time_point lastUpdate = now;
AZStd::chrono::duration<float> delta = now - lastUpdate;
float deltaTime = delta.count();
lastUpdate = now;
if (m_ptrTicker)
{
AZ::SystemTickBus::ExecuteQueuedEvents();
AZ::SystemTickBus::Broadcast(&AZ::SystemTickEvents::OnSystemTick);
pApp->Tick(deltaTime);
}
AZ::SystemTickBus::ExecuteQueuedEvents();
AZ::SystemTickBus::Broadcast(&AZ::SystemTickEvents::OnSystemTick);
pApp->Tick();
}
m_bTicking = false;
+1 -2
View File
@@ -26,7 +26,6 @@
#include <AzGameFramework/Application/GameApplication.h>
#include <ISystem.h>
#include <ITimer.h>
#include <LegacyAllocator.h>
#include <Launcher_Traits_Platform.h>
@@ -113,7 +112,7 @@ namespace
}
// Update the AzFramework application tick bus
gameApplication.Tick(gEnv->pTimer->GetFrameTime());
gameApplication.Tick();
// Post-update CrySystem
if (system)
-4
View File
@@ -47,7 +47,6 @@ struct IConsole;
struct IRemoteConsole;
struct IRenderer;
struct IProcess;
struct ITimer;
struct ICryFont;
struct IMovieSystem;
namespace Audio
@@ -610,7 +609,6 @@ struct SSystemGlobalEnvironment
{
AZ::IO::IArchive* pCryPak;
AZ::IO::FileIOBase* pFileIO;
ITimer* pTimer;
ICryFont* pCryFont;
::IConsole* pConsole;
ISystem* pSystem = nullptr;
@@ -831,8 +829,6 @@ struct ISystem
virtual IRemoteConsole* GetIRemoteConsole() = 0;
virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0;
virtual ITimer* GetITimer() = 0;
// Arguments:
// bValue - Set to true when running on a cheat protected server or a client that is connected to it (not used in singleplayer).
virtual void SetForceNonDevMode(bool bValue) = 0;
-211
View File
@@ -1,211 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_ITIMER_H
#define CRYINCLUDE_CRYCOMMON_ITIMER_H
#pragma once
#include "TimeValue.h" // CTimeValue
#include "SerializeFwd.h"
struct tm;
// Summary:
// Interface to the Timer System.
struct ITimer
{
enum ETimer
{
ETIMER_GAME = 0, // Pausable, serialized, frametime is smoothed/scaled/clamped.
ETIMER_UI, // Non-pausable, non-serialized, frametime unprocessed.
ETIMER_LAST
};
enum ETimeScaleChannels
{
eTSC_Trackview = 0,
eTSC_GameStart
};
// <interfuscator:shuffle>
virtual ~ITimer() {};
// Summary:
// Resets the timer
// Notes:
// Only needed because float precision wasn't last that long - can be removed if 64bit is used everywhere.
virtual void ResetTimer() = 0;
// Summary:
// Updates the timer every frame, needs to be called by the system.
virtual void UpdateOnFrameStart() = 0;
// Summary:
// Returns the absolute time at the last UpdateOnFrameStart() call.
// Todo:
// Remove, use GetFrameStartTime() instead.
// See also:
// UpdateOnFrameStart(),GetFrameStartTime()
virtual float GetCurrTime(ETimer which = ETIMER_GAME) const = 0;
// Summary:
// Returns the absolute time at the last UpdateOnFrameStart() call.
// See also:
// UpdateOnFrameStart()
//virtual const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const = 0;
virtual const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const = 0;
// Summary:
// Returns the absolute current time.
// Notes:
// The value continuously changes, slower than GetFrameStartTime().
// See also:
// GetFrameStartTime()
virtual CTimeValue GetAsyncTime() const = 0;
// Summary:
// Returns the absolute current time at the moment of the call.
virtual float GetAsyncCurTime() = 0;
// Summary:
// Returns the relative time passed from the last UpdateOnFrameStart() in seconds.
// See also:
// UpdateOnFrameStart()
virtual float GetFrameTime(ETimer which = ETIMER_GAME) const = 0;
// Description:
// Returns the relative time passed from the last UpdateOnFrameStart() in seconds without any dilation, smoothing, clamping, etc...
// See also:
// UpdateOnFrameStart()
virtual float GetRealFrameTime() const = 0;
// Summary:
// Returns the time scale applied to time values.
virtual float GetTimeScale() const = 0;
// Summary:
// Returns the time scale factor for the given channel
virtual float GetTimeScale(uint32 channel) const = 0;
// Summary:
// Clears all current time scale requests
virtual void ClearTimeScales() = 0;
// Summary:
// Sets the time scale applied to time values.
virtual void SetTimeScale(float s, uint32 channel = 0) = 0;
// Summary:
// Enables/disables timer.
virtual void EnableTimer(bool bEnable) = 0;
// Return Value:
// True if timer is enabled
virtual bool IsTimerEnabled() const = 0;
// Summary:
// Returns the current framerate in frames/second.
virtual float GetFrameRate() = 0;
// Summary:
// Returns the fraction to blend current frame in profiling stats.
virtual float GetProfileFrameBlending(float* pfBlendTime = 0, int* piBlendMode = 0) = 0;
// Summary:
// Serialization.
virtual void Serialize(TSerialize ser) = 0;
// Summary:
// Tries to pause/unpause a timer.
// Return Value:
// True if successfully paused/unpaused, false otherwise.
virtual bool PauseTimer(ETimer which, bool bPause) = 0;
// Summary:
// Determines if a timer is paused.
// Returns:
// True if paused, false otherwise.
virtual bool IsTimerPaused(ETimer which) = 0;
// Summary:
// Tries to set a timer.
// Returns:
// True if successful, false otherwise.
virtual bool SetTimer(ETimer which, float timeInSeconds) = 0;
// Summary:
// Makes a tm struct from a time_t in UTC
// Example:
// Like gmtime.
virtual void SecondsToDateUTC(time_t time, struct tm& outDateUTC) = 0;
// Summary:
// Makes a UTC time from a tm.
// Example:
// Like timegm, but not available on all platforms.
virtual time_t DateToSecondsUTC(struct tm& timePtr) = 0;
// Summary
// Convert from ticks (CryGetTicks()) to seconds
//
virtual float TicksToSeconds(int64 ticks) = 0;
// Summary
// Get number of ticks per second
//
virtual int64 GetTicksPerSecond() = 0;
// Summary
// Create a new timer of the same type
//
virtual ITimer* CreateNewTimer() = 0;
/*!
This is similar to the cvar t_FixedStep. However it is stronger, and will cause even GetRealFrameTime to follow the fixed time stamp.
GetRealFrameTime will always return the same value as GetFrameTime. This mode is mostly intended for Feature tests that have strict requirements
for determinism. It will cause even fps counters to return a fixed value that does not match the actual fps. I could see this also being useful
if rendering a video.
*/
virtual void EnableFixedTimeMode(bool enable, float timeStep) = 0;
// </interfuscator:shuffle>
};
// Description:
// This class is used for automatic profiling of a section of the code.
// Creates an instance of this class, and upon exiting from the code section.
template <typename time>
class CITimerAutoProfiler
{
public:
CITimerAutoProfiler (ITimer* pTimer, time& rTime)
: m_pTimer (pTimer)
, m_rTime (rTime)
{
rTime -= pTimer->GetAsyncCurTime();
}
~CITimerAutoProfiler ()
{
m_rTime += m_pTimer->GetAsyncCurTime();
}
protected:
ITimer* m_pTimer;
time& m_rTime;
};
// Description:
// Include this string AUTO_PROFILE_SECTION(pITimer, g_fTimer) for the section of code where the profiler timer must be turned on and off.
// The profiler timer is just some global or static float or double value that accumulates the time (in seconds) spent in the given block of code.
// pITimer is a pointer to the ITimer interface, g_fTimer is the global accumulator.
#define AUTO_PROFILE_SECTION(pITimer, g_fTimer) CITimerAutoProfiler<double> __section_auto_profiler(pITimer, g_fTimer)
#endif // CRYINCLUDE_CRYCOMMON_ITIMER_H
@@ -9,7 +9,6 @@
#include <Range.h>
#include <AnimKey.h>
#include <ITimer.h>
#include <LyShine/ILyShine.h>
#include <AzCore/Math/Vector2.h>
#include <AzCore/Math/Vector3.h>
+1 -1
View File
@@ -13,7 +13,7 @@
#include <AzCore/IO/Path/Path.h>
#include <AzFramework/Archive/INestedArchive.h>
#include <AzFramework/Archive/IArchive.h>
#include <CryCommon/platform.h>
struct CryPakMock
: AZ::IO::IArchive
@@ -75,8 +75,6 @@ public:
IRemoteConsole * ());
MOCK_METHOD0(GetISystemEventDispatcher,
ISystemEventDispatcher * ());
MOCK_METHOD0(GetITimer,
ITimer * ());
MOCK_METHOD1(SetForceNonDevMode,
void(bool bValue));
MOCK_CONST_METHOD0(GetForceNonDevMode,
-51
View File
@@ -1,51 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H
#define CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H
#pragma once
#include <ISerialize.h>
#include <ITimer.h>
#include <AzTest/AzTest.h>
// Implements all common timing routines
class TimerMock
: public ITimer
{
public:
MOCK_METHOD0(ResetTimer, void());
MOCK_METHOD0(UpdateOnFrameStart, void());
MOCK_CONST_METHOD1(GetCurrTime, float(ETimer which));
MOCK_CONST_METHOD0(GetAsyncTime, CTimeValue());
MOCK_METHOD0(GetAsyncCurTime, float());
MOCK_CONST_METHOD1(GetFrameTime, float(ETimer which));
MOCK_CONST_METHOD0(GetRealFrameTime, float());
MOCK_CONST_METHOD0(GetTimeScale, float());
MOCK_CONST_METHOD1(GetTimeScale, float(uint32 channel));
MOCK_METHOD2(SetTimeScale, void(float scale, uint32 channel));
MOCK_METHOD0(ClearTimeScales, void());
MOCK_METHOD1(EnableTimer, void(bool bEnable));
MOCK_METHOD0(GetFrameRate, float());
MOCK_METHOD2(GetProfileFrameBlending, float(float* pfBlendTime, int* piBlendMode));
MOCK_METHOD1(Serialize, void(TSerialize ser));
MOCK_CONST_METHOD0(IsTimerEnabled, bool());
MOCK_METHOD2(PauseTimer, bool(ETimer which, bool bPause));
MOCK_METHOD1(IsTimerPaused, bool(ETimer which));
MOCK_METHOD2(SetTimer, bool(ETimer which, float timeInSeconds));
MOCK_METHOD2(SecondsToDateUTC, void(time_t time, struct tm& outDateUTC));
MOCK_METHOD1(DateToSecondsUTC, time_t(struct tm& timePtr));
MOCK_METHOD1(TicksToSeconds, float(int64 ticks));
MOCK_METHOD0(GetTicksPerSecond, int64());
MOCK_CONST_METHOD1(GetFrameStartTime, const CTimeValue&(ETimer which));
MOCK_METHOD0(CreateNewTimer, ITimer * ());
MOCK_METHOD2(EnableFixedTimeMode, void(bool enable, float timeStep));
};
#endif // CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H
-112
View File
@@ -1,112 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <CryCommon/ITimer.h>
#include <CryCommon/ISerialize.h>
//! Simple stub timer that exposes a single simple interface for setting the current time.
class StubTimer
: public ITimer
{
public:
// Stub methods
void SetTime(float seconds)
{
m_frameStartTime.SetSeconds(seconds);
}
//~Stub methods
StubTimer(float frameTime)
: m_frameTime(frameTime)
, m_frameRate(1.0f / frameTime)
, m_frameStartTime(0.0f)
{
}
virtual ~StubTimer() {};
// ITimer
void ResetTimer() override {}
void UpdateOnFrameStart() override {}
float GetCurrTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override
{
// return the same as the frame start time
return m_frameStartTime.GetSeconds();
}
const CTimeValue& GetFrameStartTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override
{
return m_frameStartTime;
}
CTimeValue GetAsyncTime() const override
{
return m_frameStartTime;
}
float GetAsyncCurTime() override
{
return m_frameStartTime.GetSeconds();
}
float GetFrameTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override
{
return m_frameTime;
}
float GetRealFrameTime() const override
{
return m_frameTime;
}
float GetTimeScale() const override
{
return 1.0f;
}
float GetTimeScale([[maybe_unused]] uint32 channel) const override
{
return 1.0f;
}
void ClearTimeScales() override {}
void SetTimeScale([[maybe_unused]] float s, [[maybe_unused]] uint32 channel = 0) override {}
void EnableTimer([[maybe_unused]] bool bEnable) override {}
bool IsTimerEnabled() const override
{
return true;
}
float GetFrameRate() override
{
return m_frameRate;
}
float GetProfileFrameBlending([[maybe_unused]] float* pfBlendTime = 0, [[maybe_unused]] int* piBlendMode = 0) override
{
return 0.0f;
}
void Serialize([[maybe_unused]] TSerialize ser) override {}
bool PauseTimer([[maybe_unused]] ETimer which, [[maybe_unused]] bool bPause) override { return false; }
bool IsTimerPaused([[maybe_unused]] ETimer which) override { return false; }
bool SetTimer([[maybe_unused]] ETimer which, [[maybe_unused]] float timeInSeconds) override { return false; }
void SecondsToDateUTC([[maybe_unused]] time_t time, [[maybe_unused]] struct tm& outDateUTC) override {}
time_t DateToSecondsUTC([[maybe_unused]] struct tm& timePtr) override
{
return 0;
}
float TicksToSeconds([[maybe_unused]] int64 ticks) override
{
return 0.0f;
}
int64 GetTicksPerSecond() override
{
return 0;
}
ITimer* CreateNewTimer() override
{
return nullptr;
}
void EnableFixedTimeMode([[maybe_unused]] bool enable, [[maybe_unused]] float timeStep) override {}
// ~ITimer
private:
CTimeValue m_frameStartTime;
float m_frameTime;
float m_frameRate;
};
-38
View File
@@ -1,38 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#ifndef CRYINCLUDE_CRYCOMMON_TIMER_H
#define CRYINCLUDE_CRYCOMMON_TIMER_H
struct Timer
{
Timer()
: endTime(-1.0f)
{
}
void Reset(float duration, float variation = 0.0f)
{
endTime = gEnv->pSystem->GetITimer()->GetFrameStartTime() + CTimeValue(duration) + CTimeValue(cry_random(0.0f, variation));
}
bool Elapsed() const
{
return endTime >= 0.0f && gEnv->pSystem->GetITimer()->GetFrameStartTime() >= endTime;
}
float GetSecondsLeft() const
{
return (endTime - gEnv->pSystem->GetITimer()->GetFrameStartTime()).GetSeconds();
}
CTimeValue endTime;
};
#endif // CRYINCLUDE_CRYCOMMON_TIMER_H
@@ -34,7 +34,6 @@ set(FILES
StatObjBus.h
ISystem.h
ITexture.h
ITimer.h
IValidator.h
IWindowMessageHandler.h
IXml.h
@@ -68,7 +67,6 @@ set(FILES
SimpleSerialize.h
smartptr.h
StlUtils.h
Timer.h
TimeValue.h
VectorMap.h
VertexFormats.h
@@ -12,6 +12,5 @@ set(FILES
Mocks/ICryPakMock.h
Mocks/ILogMock.h
Mocks/ISystemMock.h
Mocks/ITimerMock.h
Mocks/ICVarMock.h
)
@@ -89,7 +89,6 @@ inline int RoundToClosestMB(size_t memSize)
#include <IRenderer.h>
#include <CryFile.h>
#include <ISystem.h>
#include <ITimer.h>
#include <IXml.h>
#include <ICmdLine.h>
#include <IConsole.h>
@@ -19,6 +19,7 @@
#include <CryCommon/StaticInstance.h>
#include <AzCore/Debug/AssetTracking.h>
#include <AzCore/Time/ITime.h>
#include <AzFramework/API/ApplicationAPI.h>
#include <AzFramework/IO/FileOperations.h>
#include <AzFramework/Entity/GameEntityContextBus.h>
@@ -553,8 +554,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName)
// Not remove a scope!!!
{
//m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime();
CLevelInfo* pLevelInfo = GetLevelInfoInternal(levelName);
if (!pLevelInfo)
@@ -693,7 +692,9 @@ void CLevelSystem::PrepareNextLevel(const char* levelName)
// This work not required in-editor.
if (!gEnv || !gEnv->IsEditor())
{
m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
m_levelLoadStartTime = CTimeValue(timeSec);
// Open pak file for a new level.
pLevelInfo->OpenLevelPak();
@@ -726,7 +727,8 @@ void CLevelSystem::OnLoadingStart(const char* levelName)
gEnv->pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_Level);
}
m_fLastTime = gEnv->pTimer->GetAsyncCurTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
m_fLastTime = AZ::TimeMsToSeconds(timeMs);
GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START, 0, 0);
@@ -757,7 +759,9 @@ void CLevelSystem::OnLoadingError(const char* levelName, const char* error)
//------------------------------------------------------------------------
void CLevelSystem::OnLoadingComplete(const char* levelName)
{
CTimeValue t = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
const CTimeValue t(timeSec);
m_fLastLevelLoadTime = (t - m_levelLoadStartTime).GetSeconds();
LogLoadingTime();
@@ -851,7 +855,7 @@ void CLevelSystem::UnloadLevel()
gEnv->pCryPak->DisableRuntimeFileAccess(false);
}
CTimeValue tBegin = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs beginTimeMs = AZ::GetRealElapsedTimeMs();
// Clear level entities and prefab instances.
EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext);
@@ -889,8 +893,8 @@ void CLevelSystem::UnloadLevel()
m_bLevelLoaded = false;
CTimeValue tUnloadTime = gEnv->pTimer->GetAsyncTime() - tBegin;
CryLog("UnloadLevel End: %.1f sec", tUnloadTime.GetSeconds());
const AZ::TimeMs unloadTimeMs = AZ::GetRealElapsedTimeMs() - beginTimeMs;
CryLog("UnloadLevel End: %.1f sec", AZ::TimeMsToSeconds(unloadTimeMs));
// Must be sent last.
// Cleanup all containers
@@ -11,6 +11,7 @@
#include "ILevelSystem.h"
#include <AzFramework/Archive/IArchive.h>
#include <CryCommon/TimeValue.h>
// [LYN-2376] Remove the entire file once legacy slice support is removed
@@ -24,8 +24,8 @@
#include <AzCore/IO/Path/Path.h>
#include <AzCore/Settings/SettingsRegistryVisitorUtils.h>
#include <AzCore/StringFunc/StringFunc.h>
#include <AzCore/Script/ScriptSystemBus.h>
#include <AzCore/Time/ITime.h>
namespace LegacyLevelSystem
{
@@ -368,7 +368,9 @@ namespace LegacyLevelSystem
// This work not required in-editor.
if (!gEnv || !gEnv->IsEditor())
{
m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
m_levelLoadStartTime = CTimeValue(timeSec);
// switched to level heap, so now imm start the loading screen (renderer will be reinitialized in the levelheap)
gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN, 0, 0);
@@ -409,7 +411,8 @@ namespace LegacyLevelSystem
gEnv->pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_Level);
}
m_fLastTime = gEnv->pTimer->GetAsyncCurTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
m_fLastTime = AZ::TimeMsToSeconds(timeMs);
GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START, 0, 0);
@@ -433,7 +436,9 @@ namespace LegacyLevelSystem
//------------------------------------------------------------------------
void SpawnableLevelSystem::OnLoadingComplete(const char* levelName)
{
CTimeValue t = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
const CTimeValue t(timeSec);
m_fLastLevelLoadTime = (t - m_levelLoadStartTime).GetSeconds();
LogLoadingTime();
@@ -532,7 +537,7 @@ namespace LegacyLevelSystem
gEnv->pCryPak->DisableRuntimeFileAccess(false);
}
CTimeValue tBegin = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs beginTimeMs = AZ::GetRealElapsedTimeMs();
// Clear level entities and prefab instances.
EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext);
@@ -561,8 +566,8 @@ namespace LegacyLevelSystem
m_bLevelLoaded = false;
CTimeValue tUnloadTime = gEnv->pTimer->GetAsyncTime() - tBegin;
AZ_TracePrintf("LevelSystem", "UnloadLevel End: %.1f sec\n", tUnloadTime.GetSeconds());
const AZ::TimeMs unloadTimeMs = AZ::GetRealElapsedTimeMs() - beginTimeMs;
AZ_TracePrintf("LevelSystem", "UnloadLevel End: %.1f sec\n", AZ::TimeMsToSeconds(unloadTimeMs));
// Must be sent last.
// Cleanup all containers
@@ -12,6 +12,7 @@
#include <AzCore/Console/IConsole.h>
#include <AzFramework/Archive/IArchive.h>
#include <AzFramework/Spawnable/RootSpawnableInterface.h>
#include <CryCommon/TimeValue.h>
namespace LegacyLevelSystem
{
@@ -136,6 +136,44 @@ static const char* PLATFORM_INDEPENDENT_LANGUAGE_NAMES[ ILocalizationManager::eP
"da-DK" // Danish (Denmark)
};
#if defined(WIN32) || defined(WIN64)
namespace
{
#if defined(WIN32)
time_t gmt_to_local_win32(void)
{
TIME_ZONE_INFORMATION tzinfo;
DWORD dwStandardDaylight;
long bias;
dwStandardDaylight = GetTimeZoneInformation(&tzinfo);
bias = tzinfo.Bias;
if (dwStandardDaylight == TIME_ZONE_ID_STANDARD)
{
bias += tzinfo.StandardBias;
}
if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT)
{
bias += tzinfo.DaylightBias;
}
return (-bias * 60);
}
#endif // #if defined(WIN32)
time_t DateToSecondsUTC(struct tm& inDate)
{
#if defined(WIN32)
return mktime(&inDate) + gmt_to_local_win32();
#else
return mktime(&inDate);
#endif // #if defined(WIN32)
}
}
#endif // #if defined(WIN32) || defined(WIN64)
//////////////////////////////////////////////////////////////////////////
#if !defined(_RELEASE)
static void ReloadDialogData([[maybe_unused]] IConsoleCmdArgs* pArgs)
@@ -2656,7 +2694,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool
{
struct tm thetime;
localtime_s(&thetime, &t);
t = gEnv->pTimer->DateToSecondsUTC(thetime);
t = DateToSecondsUTC(thetime);
}
outTimeString.clear();
LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT;
@@ -2680,7 +2718,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool
{
struct tm thetime;
localtime_s(&thetime, &t);
t = gEnv->pTimer->DateToSecondsUTC(thetime);
t = DateToSecondsUTC(thetime);
}
outDateString.resize(0);
LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT;
+28 -28
View File
@@ -22,6 +22,7 @@
#include <AzFramework/IO/FileOperations.h>
#include <AzCore/IO/FileIO.h>
#include <AzCore/IO/Path/Path.h>
#include <AzCore/Time/ITime.h>
#ifdef WIN32
#include <time.h>
@@ -503,7 +504,8 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo
{
const int sz = sizeof(m_history) / sizeof(m_history[0]);
int i, j;
float time = m_pSystem->GetITimer()->GetCurrTime();
const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs();
const float time = AZ::TimeMsToSeconds(realTimeMs);
for (i = m_iLastHistoryItem, j = 0; m_history[i].time > time - dt && j < sz; j++, i = i - 1 & sz - 1)
{
if (m_history[i].type != type)
@@ -908,7 +910,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
}
#endif
if (m_pLogIncludeTime && gEnv && gEnv->pTimer)
if (m_pLogIncludeTime)
{
uint32 dwCVarState = m_pLogIncludeTime->GetIVal();
// char szTemp[MAX_TEMP_LENGTH_SIZE];
@@ -933,12 +935,12 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
}
else if (dwCVarState == 2) // Log_IncludeTime
{
static CTimeValue lasttime;
CTimeValue currenttime = gEnv->pTimer->GetAsyncTime();
if (lasttime != CTimeValue())
static AZ::TimeMs lasttime = AZ::Time::ZeroTimeMs;
const AZ::TimeMs currenttime = AZ::GetRealElapsedTimeMs();
if (lasttime != AZ::Time::ZeroTimeMs)
{
timeStr.clear();
uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
uint32 dwMs = aznumeric_cast<uint32>(currenttime - lasttime);
timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
tempString = timeStr + tempString;
}
@@ -960,12 +962,12 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
#endif
tempString = LogStringType(sTime) + tempString;
static CTimeValue lasttime;
CTimeValue currenttime = gEnv->pTimer->GetAsyncTime();
if (lasttime != CTimeValue())
static AZ::TimeMs lasttime = AZ::Time::ZeroTimeMs;
const AZ::TimeMs currenttime = AZ::GetRealElapsedTimeMs();
if (lasttime != AZ::Time::ZeroTimeMs)
{
timeStr.clear();
uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
uint32 dwMs = (uint32)(currenttime - lasttime);
timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
tempString = timeStr + tempString;
}
@@ -975,22 +977,19 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[
{
static bool bFirst = true;
if (gEnv->pTimer)
static AZ::TimeMs lasttime = AZ::Time::ZeroTimeMs;
const AZ::TimeMs currenttime = AZ::GetRealElapsedTimeMs();
if (lasttime != AZ::Time::ZeroTimeMs)
{
static CTimeValue lasttime;
CTimeValue currenttime = gEnv->pTimer->GetAsyncTime();
if (lasttime != CTimeValue())
{
timeStr.clear();
uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds());
timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
tempString = timeStr + tempString;
}
if (bFirst)
{
lasttime = currenttime;
bFirst = false;
}
timeStr.clear();
uint32 dwMs = (uint32)(currenttime - lasttime);
timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000);
tempString = timeStr + tempString;
}
if (bFirst)
{
lasttime = currenttime;
bFirst = false;
}
}
else if (dwCVarState == 5) // Log_IncludeTime
@@ -1465,9 +1464,10 @@ void CLog::Update()
if (LogCVars::s_log_tick != 0)
{
static CTimeValue t0 = GetISystem()->GetITimer()->GetAsyncTime();
CTimeValue t1 = GetISystem()->GetITimer()->GetAsyncTime();
if (fabs((t1 - t0).GetSeconds()) > LogCVars::s_log_tick)
static AZ::TimeUs t0 = AZ::GetElapsedTimeUs();
const AZ::TimeUs t1 = AZ::GetElapsedTimeUs();
const float tSec = AZ::TimeUsToSeconds(t1 - t0);
if (tSec > LogCVars::s_log_tick)
{
t0 = t1;
+47 -36
View File
@@ -29,6 +29,7 @@
#include <AzCore/Debug/IEventLogger.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/std/algorithm.h>
#include <AzCore/Time/ITime.h>
#include <AzFramework/Logging/MissingAssetLogger.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <AzCore/Interface/Interface.h>
@@ -156,6 +157,16 @@ SSystemCVars g_cvars;
#include <AzCore/Component/ComponentApplication.h>
#include "AZCoreLogSink.h"
namespace
{
float GetMovieFrameDeltaTime()
{
// Use GetRealTickDeltaTimeUs for CryMovie, because it should not be affected by pausing game time
const AZ::TimeUs delta = AZ::GetRealTickDeltaTimeUs();
return AZ::TimeUsToSeconds(delta);
}
}
/////////////////////////////////////////////////////////////////////////////////
// System Implementation.
//////////////////////////////////////////////////////////////////////////
@@ -192,7 +203,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment)
//////////////////////////////////////////////////////////////////////////
// Initialize global environment interface pointers.
m_env.pSystem = this;
m_env.pTimer = &m_Time;
m_env.bIgnoreAllAsserts = false;
m_env.bNoAssertDialog = false;
@@ -563,14 +573,15 @@ ISystem* CSystem::GetCrySystem()
//////////////////////////////////////////////////////////////////////////
void CSystem::SleepIfNeeded()
{
ITimer* const pTimer = gEnv->pTimer;
static bool firstCall = true;
typedef MiniQueue<CTimeValue, 32> PrevNow;
static PrevNow prevNow;
if (firstCall)
{
m_lastTickTime = pTimer->GetAsyncTime();
const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs();
const double timeSec = AZ::TimeMsToSecondsDouble(timeMs);
m_lastTickTime = CTimeValue(timeSec);
prevNow.Push(m_lastTickTime);
firstCall = false;
return;
@@ -578,8 +589,10 @@ void CSystem::SleepIfNeeded()
const float maxRate = m_svDedicatedMaxRate->GetFVal();
const float minTime = 1.0f / maxRate;
CTimeValue now = pTimer->GetAsyncTime();
float elapsed = (now - m_lastTickTime).GetSeconds();
const AZ::TimeMs nowTimeMs = AZ::GetRealElapsedTimeMs();
const double nowTimeSec = AZ::TimeMsToSecondsDouble(nowTimeMs);
const CTimeValue now = CTimeValue(nowTimeSec);
const float elapsed = (now - m_lastTickTime).GetSeconds();
if (prevNow.Full())
{
@@ -591,7 +604,9 @@ void CSystem::SleepIfNeeded()
if (elapsed > minTime && allowStallCatchup)
{
allowStallCatchup = false;
m_lastTickTime = pTimer->GetAsyncTime();
const AZ::TimeMs lastTimeMs = AZ::GetRealElapsedTimeMs();
const double lastTimeSec = AZ::TimeMsToSecondsDouble(lastTimeMs);
m_lastTickTime = CTimeValue(lastTimeSec);
return;
}
allowStallCatchup = true;
@@ -607,7 +622,9 @@ void CSystem::SleepIfNeeded()
Sleep(sleepMS);
}
m_lastTickTime = pTimer->GetAsyncTime();
const AZ::TimeMs lastTimeMs = AZ::GetRealElapsedTimeMs();
const double lastTimeSec = AZ::TimeMsToSecondsDouble(lastTimeMs);
m_lastTickTime = CTimeValue(lastTimeSec);
}
extern DWORD g_idDebugThreads[];
@@ -734,24 +751,21 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode)
if (maxFPS > 0 && vSync == 0)
{
CTimeValue timeFrameMax;
const float safeMarginFPS = 0.5f;//save margin to not drop below 30 fps
static CTimeValue sTimeLast = gEnv->pTimer->GetAsyncTime();
timeFrameMax.SetMilliSeconds((int64)(1000.f / ((float)maxFPS + safeMarginFPS)));
const CTimeValue timeLast = timeFrameMax + sTimeLast;
while (timeLast.GetValue() > gEnv->pTimer->GetAsyncTime().GetValue())
static AZ::TimeMs sTimeLast = AZ::GetRealElapsedTimeMs();
const AZ::TimeMs timeFrameMax(static_cast<AZ::TimeMs>(
(int64)(1000.f / ((float)maxFPS + safeMarginFPS))
));
const AZ::TimeMs timeLast = timeFrameMax + sTimeLast;
while (timeLast > AZ::GetRealElapsedTimeMs())
{
CrySleep(0);
}
sTimeLast = gEnv->pTimer->GetAsyncTime();
sTimeLast = AZ::GetRealElapsedTimeMs();
}
}
}
//////////////////////////////////////////////////////////////////////
//update time subsystem
m_Time.UpdateOnFrameStart();
//////////////////////////////////////////////////////////////////////
//update console system
if (m_env.pConsole)
@@ -765,13 +779,10 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode)
return false;
}
// Use UI timer for CryMovie, because it should not be affected by pausing game time
const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI);
// Run movie system pre-update
if (!bNoUpdate)
{
UpdateMovieSystem(updateFlags, fMovieFrameTime, true);
UpdateMovieSystem(updateFlags, GetMovieFrameDeltaTime(), true);
}
return !IsQuitting();
@@ -780,13 +791,14 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode)
//////////////////////////////////////////////////////////////////////
bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/)
{
CTimeValue updateStart = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs updateStartTimeMs = AZ::GetRealElapsedTimeMs();
const double updateStartTimeSec = AZ::TimeMsToSecondsDouble(updateStartTimeMs);
const CTimeValue updateStart(updateStartTimeSec);
// Run movie system post-update
if (!m_bNoUpdate)
{
const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI);
UpdateMovieSystem(updateFlags, fMovieFrameTime, false);
UpdateMovieSystem(updateFlags, GetMovieFrameDeltaTime(), false);
}
//////////////////////////////////////////////////////////////////////
@@ -797,7 +809,9 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/)
}
//Now update frame statistics
CTimeValue cur_time = gEnv->pTimer->GetAsyncTime();
const AZ::TimeMs curTimeMs = AZ::GetRealElapsedTimeMs();
const double curTimeSec = AZ::TimeMsToSecondsDouble(curTimeMs);
const CTimeValue cur_time(curTimeSec);
CTimeValue a_second(g_cvars.sys_update_profile_time);
std::vector< std::pair<CTimeValue, float> >::iterator it = m_updateTimes.begin();
@@ -1366,19 +1380,16 @@ const char* CSystem::GetSystemGlobalStateName(const ESystemGlobalState systemGlo
void CSystem::SetSystemGlobalState(const ESystemGlobalState systemGlobalState)
{
static CTimeValue s_startTime = CTimeValue();
static AZ::TimeMs s_startTime = AZ::Time::ZeroTimeMs;
if (systemGlobalState != m_systemGlobalState)
{
if (gEnv && gEnv->pTimer)
{
const CTimeValue endTime = gEnv->pTimer->GetAsyncTime();
[[maybe_unused]] const float numSeconds = endTime.GetDifferenceInSeconds(s_startTime);
CryLog("SetGlobalState %d->%d '%s'->'%s' %3.1f seconds",
m_systemGlobalState, systemGlobalState,
CSystem::GetSystemGlobalStateName(m_systemGlobalState), CSystem::GetSystemGlobalStateName(systemGlobalState),
numSeconds);
s_startTime = gEnv->pTimer->GetAsyncTime();
}
const AZ::TimeMs endTime = AZ::GetRealElapsedTimeMs();
[[maybe_unused]] const double numSeconds = AZ::TimeMsToSecondsDouble(endTime - s_startTime);
CryLog("SetGlobalState %d->%d '%s'->'%s' %3.1f seconds",
m_systemGlobalState, systemGlobalState,
CSystem::GetSystemGlobalStateName(m_systemGlobalState), CSystem::GetSystemGlobalStateName(systemGlobalState),
numSeconds);
s_startTime = AZ::GetRealElapsedTimeMs();
}
m_systemGlobalState = systemGlobalState;
+2 -3
View File
@@ -13,7 +13,6 @@
#include <IRenderer.h>
#include <IWindowMessageHandler.h>
#include "Timer.h"
#include <CryVersion.h>
#include "CmdLine.h"
@@ -23,6 +22,8 @@
#include <AzCore/Module/DynamicModuleHandle.h>
#include <AzCore/Math/Crc.h>
#include <CryCommon/TimeValue.h>
#include <list>
#include <map>
@@ -226,7 +227,6 @@ public:
int GetApplicationInstance() override;
int GetApplicationLogInstance(const char* logFilePath) override;
ITimer* GetITimer() override{ return m_env.pTimer; }
AZ::IO::IArchive* GetIPak() override { return m_env.pCryPak; };
IConsole* GetIConsole() override { return m_env.pConsole; };
IRemoteConsole* GetIRemoteConsole() override;
@@ -382,7 +382,6 @@ private: // ------------------------------------------------------
// System environment.
SSystemGlobalEnvironment m_env;
CTimer m_Time; //!<
bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps
bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch)
int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading)
-11
View File
@@ -1099,17 +1099,6 @@ AZ_POP_DISABLE_WARNING
AzFramework::SystemCursorState::ConstrainedAndHidden);
}
//////////////////////////////////////////////////////////////////////////
// TIME
//////////////////////////////////////////////////////////////////////////
AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Time initialization");
if (!m_Time.Init())
{
AZ_Assert(false, "Failed to initialize CTimer instance.");
return false;
}
m_Time.ResetTimer();
// CONSOLE
//////////////////////////////////////////////////////////////////////////
if (!InitConsole())
-725
View File
@@ -1,725 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "CrySystem_precompiled.h"
#include "Timer.h"
#include <time.h>
#include <ISystem.h>
#include <IConsole.h>
#include <ILog.h>
#include <ISerialize.h>
/////////////////////////////////////////////////////
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#include "Mmsystem.h"
#endif
//#define PROFILING 1
#ifdef PROFILING
static int64 g_lCurrentTime = 0;
#endif
//! Profile smoothing time in seconds (original default was .8 / log(10) ~= .35 s)
static const float fDEFAULT_PROFILE_SMOOTHING = 1.0f;
#define DEFAULT_FRAME_SMOOTHING 1
/////////////////////////////////////////////////////
CTimer::CTimer()
{
// Default CVar values
m_fixed_time_step = 0;
m_max_time_step = 0.25f;
m_cvar_time_scale = 1.0f;
m_TimeSmoothing = DEFAULT_FRAME_SMOOTHING; // note: frame numbers (old version - commented out) are not used but is based on time
m_TimeDebug = 0;
m_profile_smooth_time = fDEFAULT_PROFILE_SMOOTHING;
m_profile_weighting = 1;
// Persistant state
m_bEnabled = true;
//m_fixedTimeModeEnabled = false;
m_nFrameCounter = 0;
m_lTicksPerSec = CryGetTicksPerSec();
m_fSecsPerTick = 1.0 / m_lTicksPerSec;
m_fAverageFrameTime = 1.0f / 30.0f;
for (int i = 0; i < MAX_FRAME_AVERAGE; i++)
{
m_arrFrameTimes[i] = m_fAverageFrameTime;
}
m_fAvgFrameTime = 0.0f;
m_fProfileBlend = 1.0f;
m_fSmoothTime = 0;
m_totalTimeScale = 1.0f;
ClearTimeScales();
ResetTimer();
}
/////////////////////////////////////////////////////
bool CTimer::Init()
{
// if game code was accessing them by name there was something wrong anyway
REGISTER_CVAR2("t_Smoothing", &m_TimeSmoothing, DEFAULT_FRAME_SMOOTHING, 0,
"time smoothing\n"
"0=off, 1=on");
REGISTER_CVAR2("t_FixedStep", &m_fixed_time_step, 0, VF_NET_SYNCED | VF_DEV_ONLY,
"Game updated with this fixed frame time\n"
"0=off, number specifies the frame time in seconds\n"
"e.g. 0.033333(30 fps), 0.1(10 fps), 0.01(100 fps)");
REGISTER_CVAR2("t_MaxStep", &m_max_time_step, 0.25f, 0,
"Game systems clamped to this frame time");
// todo: reconsider exposing that as cvar (negative time, same value is used by Trackview, better would be another value multipled with the internal one)
REGISTER_CVAR2("t_Scale", &m_cvar_time_scale, 1.0f, VF_NET_SYNCED | VF_DEV_ONLY,
"Game time scaled by this - for variable slow motion");
REGISTER_CVAR2("t_Debug", &m_TimeDebug, 0, 0, "Timer debug: 0 = off, 1 = events, 2 = verbose");
// -----------------
REGISTER_CVAR2("profile_smooth", &m_profile_smooth_time, fDEFAULT_PROFILE_SMOOTHING, 0,
"Profiler exponential smoothing interval (seconds)");
REGISTER_CVAR2("profile_weighting", &m_profile_weighting, 1, 0,
"Profiler smoothing mode: 0 = legacy, 1 = average, 2 = peak weighted, 3 = peak hold");
return true;
}
/////////////////////////////////////////////////////
float CTimer::GetFrameTime(ETimer which) const
{
float result = 0.0f;
if (m_bEnabled)
{
if (which != ETIMER_GAME || !m_bGameTimerPaused)
{
if (which == ETIMER_UI)
{
result = m_fRealFrameTime;
}
else
{
result = m_fFrameTime;
}
}
}
return result;
}
/////////////////////////////////////////////////////
float CTimer::GetCurrTime(ETimer which) const
{
assert(which >= 0 && which < ETIMER_LAST && "Bad timer index");
return m_CurrTime[which].GetSeconds();
}
/////////////////////////////////////////////////////
float CTimer::GetRealFrameTime() const
{
return m_bEnabled ? m_fRealFrameTime : 0.0f;
}
/////////////////////////////////////////////////////
float CTimer::GetTimeScale() const
{
return m_cvar_time_scale * m_totalTimeScale;
}
/////////////////////////////////////////////////////
float CTimer::GetTimeScale(uint32 channel) const
{
assert(channel < NUM_TIME_SCALE_CHANNELS);
if (channel >= NUM_TIME_SCALE_CHANNELS)
{
return GetTimeScale();
}
return m_cvar_time_scale * m_timeScaleChannels[channel];
}
/////////////////////////////////////////////////////
void CTimer::SetTimeScale(float scale, uint32 channel /* = 0 */)
{
assert(channel < NUM_TIME_SCALE_CHANNELS);
if (channel >= NUM_TIME_SCALE_CHANNELS)
{
return;
}
const float currentScale = m_timeScaleChannels[channel];
if (scale != currentScale)
{
// Need to adjust previous frame times for time scale to have immediate effect
const float adjustFactor = scale / currentScale;
for (uint32 i = 0; i < MAX_FRAME_AVERAGE; ++i)
{
m_arrFrameTimes[i] *= adjustFactor;
}
// Update total time scale immediately
m_totalTimeScale *= adjustFactor;
}
m_timeScaleChannels[channel] = scale;
}
/////////////////////////////////////////////////////
void CTimer::ClearTimeScales()
{
if (m_totalTimeScale != 1.0f)
{
// Need to adjust previous frame times for time scale to have immediate effect
const float adjustFactor = 1.0f / m_totalTimeScale;
for (uint32 i = 0; i < MAX_FRAME_AVERAGE; ++i)
{
m_arrFrameTimes[i] *= adjustFactor;
}
}
for (int i = 0; i < NUM_TIME_SCALE_CHANNELS; ++i)
{
m_timeScaleChannels[i] = 1.0f;
}
m_totalTimeScale = 1.0f;
}
/////////////////////////////////////////////////////
float CTimer::GetAsyncCurTime()
{
//int64 llNow = CryGetTicks() - m_lBaseTime_Async;
int64 llNow = CryGetTicks() - m_lBaseTime;
return TicksToSeconds(llNow);
}
/////////////////////////////////////////////////////
float CTimer::GetFrameRate()
{
// Use real frame time.
if (m_fRealFrameTime != 0.f)
{
return 1.f / m_fRealFrameTime;
}
return 0.f;
}
void CTimer::UpdateBlending()
{
// Accumulate smoothing time up to specified max.
float fFrameTime = m_fRealFrameTime;
m_fSmoothTime = min(m_fSmoothTime + fFrameTime, m_profile_smooth_time);
if (m_fSmoothTime <= fFrameTime)
{
m_fAvgFrameTime = fFrameTime;
m_fProfileBlend = 1.f;
return;
}
if (m_profile_weighting <= 2)
{
// Update average frame time.
if (m_fSmoothTime < m_fAvgFrameTime)
{
m_fAvgFrameTime = m_fSmoothTime;
}
m_fAvgFrameTime *= m_fSmoothTime / (m_fSmoothTime - fFrameTime + m_fAvgFrameTime);
if (m_profile_weighting == 1)
{
// Weight all frames equally.
m_fProfileBlend = m_fAvgFrameTime / m_fSmoothTime;
}
else
{
// Weight frames by time.
m_fProfileBlend = fFrameTime / m_fSmoothTime;
}
}
else
{
// Decay avg frame time, set as new peak.
m_fAvgFrameTime *= 1.f - fFrameTime / m_fSmoothTime;
if (fFrameTime > m_fAvgFrameTime)
{
m_fAvgFrameTime = fFrameTime;
m_fProfileBlend = 1.f;
}
else
{
m_fProfileBlend = 0.f;
}
}
}
float CTimer::GetProfileFrameBlending(float* pfBlendTime, int* piBlendMode)
{
if (piBlendMode)
{
*piBlendMode = m_profile_weighting;
}
if (pfBlendTime)
{
*pfBlendTime = m_fSmoothTime;
}
return m_fProfileBlend;
}
/////////////////////////////////////////////////////
void CTimer::RefreshGameTime(int64 curTime)
{
assert(curTime + m_lOffsetTime >= 0);
m_CurrTime[ETIMER_GAME].SetSeconds(TicksToSeconds(curTime + m_lOffsetTime));
}
/////////////////////////////////////////////////////
void CTimer::RefreshUITime(int64 curTime)
{
assert(curTime >= 0);
m_CurrTime[ETIMER_UI].SetSeconds(TicksToSeconds(curTime));
}
/////////////////////////////////////////////////////
void CTimer::UpdateOnFrameStart()
{
if (!m_bEnabled)
{
return;
}
//int64 now;
//if (m_fixedTimeModeEnabled)
//{
// m_nFrameCounter++;
// m_fRealFrameTime = m_fFrameTime = m_fixedTimeModeStep;
// m_lCurrentTime += m_fixedTimeModeStep*m_lTicksPerSec;
// now = m_lCurrentTime;
//}
//else
//{
// On Windows before Vista, frequency can change (even though it should be impossible),
// See also: https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
// Win2000, WinXP: Uses RDTSC, which may not be monotonic across all cores (a bug), costs in the order of 10~100 cycles (cheap).
// WinVista: Uses HPET or ACPI timer (a kernel call, and much more expensive than RDTSC, but it's not bugged).
// Win7+: RDTSC if the CPU feature bit for monotonic is set, HPET or ACPI otherwise (not bugged).
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600
if ((m_nFrameCounter & 127) == 0)
{
// every bunch of frames, check frequency to adapt to
// CPU power management clock rate changes
LARGE_INTEGER TTicksPerSec;
if (QueryPerformanceFrequency(&TTicksPerSec))
{
// if returns false, no performance counter is available
m_lTicksPerSec = TTicksPerSec.QuadPart;
m_fSecsPerTick = 1.0 / m_lTicksPerSec;
}
}
m_nFrameCounter++;
#endif
//}
#ifdef PROFILING
m_fRealFrameTime = m_fFrameTime = 0.020f; // 20ms = 50fps
g_lCurrentTime += (int)(m_fFrameTime * (float)(CTimeValue::TIMEVALUE_PRECISION));
m_lLastTime = g_lCurrentTime;
RefreshGameTime(m_lLastTime);
RefreshUITime(m_lLastTime);
return;
#endif
if (m_fixed_time_step < 0.0f)
{
// Enforce real framerate by sleeping.
const int64 elapsedTicks = CryGetTicks() - m_lBaseTime - m_lLastTime;
const int64 minTicks = SecondsToTicks(-m_fixed_time_step);
if (elapsedTicks < minTicks)
{
const int64 ms = (minTicks - elapsedTicks) * 1000 / m_lTicksPerSec;
CrySleep((unsigned int)ms);
}
}
const int64 now = CryGetTicks();
assert(now + 1 >= m_lBaseTime && "Invalid base time"); //+1 margin because QPC may be one off across cores
m_fRealFrameTime = TicksToSeconds(now - m_lBaseTime - m_lLastTime);
if (0.0f != m_fixed_time_step)
{
// Apply fixed_time_step
m_fFrameTime = abs(m_fixed_time_step);
}
else
{
// Clamp to max_time_step
m_fFrameTime = min(m_fRealFrameTime, m_max_time_step);
}
// Dilate time.
m_fFrameTime *= GetTimeScale();
if (m_TimeSmoothing > 0)
{
m_fFrameTime = GetAverageFrameTime();
}
// Time can only go forward.
if (m_fFrameTime < 0.0f)
{
m_fFrameTime = 0.0f;
}
if (m_fRealFrameTime < 0.0f)
{
m_fRealFrameTime = 0.0;
}
// Adjust the base time so that time actually seems to have moved forward m_fFrameTime
const int64 frameTicks = SecondsToTicks(m_fFrameTime);
const int64 realTicks = SecondsToTicks(m_fRealFrameTime);
m_lBaseTime += realTicks - frameTicks;
if (m_lBaseTime > now)
{
// Guard against rounding errors due to float <-> int64 precision
assert(m_lBaseTime - now <= 10 && "Bad base time or adjustment, too much difference for a rounding error");
m_lBaseTime = now;
}
const int64 currentTime = now - m_lBaseTime;
assert(fabsf(TicksToSeconds(currentTime - m_lLastTime) - m_fFrameTime) < 0.01f && "Bad calculation");
assert(currentTime >= m_lLastTime && "Bad adjustment in previous frame");
assert(currentTime + m_lOffsetTime >= 0 && "Sum of game time is negative");
// Update timers
RefreshUITime(currentTime);
if (!m_bGameTimerPaused)
{
RefreshGameTime(currentTime);
}
m_lLastTime = currentTime;
UpdateBlending();
if (m_TimeDebug > 1)
{
CryLogAlways("[CTimer]: Cur=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)currentTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI));
}
}
//------------------------------------------------------------------------
//-- average frame-times to avoid stalls and peaks in framerate
//-- note that is is time-base averaging and not frame-based
//------------------------------------------------------------------------
float CTimer::GetAverageFrameTime()
{
f32 LastAverageFrameTime = m_fAverageFrameTime;
f32 FrameTime = m_fFrameTime;
uint32 numFT = MAX_FRAME_AVERAGE;
for (int32 i = (numFT - 2); i > -1; i--)
{
m_arrFrameTimes[i + 1] = m_arrFrameTimes[i];
}
if (FrameTime > 0.4f)
{
FrameTime = 0.4f;
}
if (FrameTime < 0.0f)
{
FrameTime = 0.0f;
}
m_arrFrameTimes[0] = FrameTime;
//get smoothed frame
uint32 avrg_ftime = 1;
if (LastAverageFrameTime)
{
avrg_ftime = uint32(0.25f / LastAverageFrameTime + 0.5f); //average the frame-times for a certain time-period (sec)
if (avrg_ftime > numFT)
{
avrg_ftime = numFT;
}
if (avrg_ftime < 1)
{
avrg_ftime = 1;
}
}
f32 AverageFrameTime = 0;
for (uint32 i = 0; i < avrg_ftime; i++)
{
AverageFrameTime += m_arrFrameTimes[i];
}
AverageFrameTime /= avrg_ftime;
//don't smooth if we pause the game
if (FrameTime < 0.0001f)
{
AverageFrameTime = FrameTime;
}
m_fAverageFrameTime = AverageFrameTime;
return AverageFrameTime;
}
/////////////////////////////////////////////////////
void CTimer::ResetTimer()
{
m_lBaseTime = CryGetTicks();
//m_lBaseTime_Async = CryGetTicks();
m_lLastTime = 0;
m_lOffsetTime = 0;
m_fFrameTime = 0.0f;
m_fRealFrameTime = 0.0f;
RefreshGameTime(0);
RefreshUITime(0);
m_bGameTimerPaused = false;
m_lGameTimerPausedTime = 0;
}
/////////////////////////////////////////////////////
void CTimer::EnableTimer(bool bEnable)
{
m_bEnabled = bEnable;
}
bool CTimer::IsTimerEnabled() const
{
return m_bEnabled;
}
/////////////////////////////////////////////////////
CTimeValue CTimer::GetAsyncTime() const
{
int64 llNow = CryGetTicks();
double fConvert = CTimeValue::TIMEVALUE_PRECISION * m_fSecsPerTick;
return CTimeValue(int64(llNow * fConvert));
}
/////////////////////////////////////////////////////
void CTimer::Serialize(TSerialize ser)
{
// cannot change m_lBaseTime, as this is used for async time (which shouldn't be affected by save games)
if (ser.IsWriting())
{
int64 currentGameTime = m_lLastTime + m_lOffsetTime;
ser.Value("curTime", currentGameTime);
ser.Value("ticksPerSecond", m_lTicksPerSec);
}
else
{
int64 ticksPerSecond = 1, curTime = 1;
ser.Value("curTime", curTime);
ser.Value("ticksPerSecond", ticksPerSecond);
// Adjust curTime for ticksPerSecond on this machine.
// Some precision will be lost if the frequencies are not identical.
const double multiplier = (double)m_lTicksPerSec / (double)ticksPerSecond;
curTime = (int64)((double)curTime * multiplier);
SetOffsetToMatchGameTime(curTime);
if (m_TimeDebug)
{
[[maybe_unused]] const int64 now = CryGetTicks();
CryLogAlways("[CTimer]: Serialize: Last=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI));
}
}
}
//! try to pause/unpause a timer
// returns true if successfully paused/unpaused, false otherwise
bool CTimer::PauseTimer(ETimer which, bool bPause)
{
if (which != ETIMER_GAME)
{
return false;
}
if (m_bGameTimerPaused == bPause)
{
return false;
}
m_bGameTimerPaused = bPause;
if (bPause)
{
m_lGameTimerPausedTime = m_lLastTime + m_lOffsetTime;
if (m_TimeDebug)
{
CryLogAlways("[CTimer]: Pausing ON: Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI));
}
}
else
{
SetOffsetToMatchGameTime(m_lGameTimerPausedTime);
m_lGameTimerPausedTime = 0;
if (m_TimeDebug)
{
CryLogAlways("[CTimer]: Pausing OFF: Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI));
}
}
return true;
}
//! determine if a timer is paused
// returns true if paused, false otherwise
bool CTimer::IsTimerPaused(ETimer which)
{
if (which != ETIMER_GAME)
{
return false;
}
return m_bGameTimerPaused;
}
//! try to set a timer
// return true if successful, false otherwise
bool CTimer::SetTimer(ETimer which, float timeInSeconds)
{
if (which != ETIMER_GAME)
{
return false;
}
SetOffsetToMatchGameTime(SecondsToTicks(timeInSeconds));
return true;
}
ITimer* CTimer::CreateNewTimer()
{
return new CTimer();
}
void CTimer::SecondsToDateUTC(time_t inTime, struct tm& outDateUTC)
{
#ifdef AZ_COMPILER_MSVC
gmtime_s(&outDateUTC, &inTime);
#else
outDateUTC = *gmtime(&inTime);
#endif
}
#if defined (WIN32) || defined(WIN64)
time_t gmt_to_local_win32(void)
{
TIME_ZONE_INFORMATION tzinfo;
DWORD dwStandardDaylight;
long bias;
dwStandardDaylight = GetTimeZoneInformation(&tzinfo);
bias = tzinfo.Bias;
if (dwStandardDaylight == TIME_ZONE_ID_STANDARD)
{
bias += tzinfo.StandardBias;
}
if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT)
{
bias += tzinfo.DaylightBias;
}
return (-bias * 60);
}
#endif
time_t CTimer::DateToSecondsUTC(struct tm& inDate)
{
#if defined (WIN32)
return mktime(&inDate) + gmt_to_local_win32();
#elif defined (LINUX)
#if defined (HAVE_TIMEGM)
// return timegm(&inDate);
#else
// craig: temp disabled the +tm.tm_gmtoff because i can't see the intention here
// and it doesn't compile anymore
// alexl: tm_gmtoff is the offset to greenwhich mean time, whereas mktime uses localtime
// but not all linux distributions have it...
return mktime(&inDate) /*+ tm.tm_gmtoff*/;
#endif
#else
return mktime(&inDate);
#endif
}
void CTimer::EnableFixedTimeMode([[maybe_unused]] bool enable, [[maybe_unused]] float timeStep)
{
//if (enable)
//{
// m_fixedTimeModeEnabled = true;
// m_fixedTimeModeStep = timeStep;
// m_lBaseTime =0;
// m_lBaseTime_Async = 0;
// m_lLastTime = m_lCurrentTime = 0;
// m_fRealFrameTime = m_fFrameTime = timeStep;
// RefreshGameTime(m_lCurrentTime);
// RefreshUITime(m_lCurrentTime);
// m_lForcedGameTime = -1;
// m_bGameTimerPaused = false;
// m_lGameTimerPausedTime = 0;
//}
//else
//{
// m_fixedTimeModeEnabled = false;
// ResetTimer();
//}
}
void CTimer::SetOffsetToMatchGameTime(int64 ticks)
{
[[maybe_unused]] const int64 previousOffset = m_lOffsetTime;
[[maybe_unused]] const float previousGameTime = GetCurrTime(ETIMER_GAME);
m_lOffsetTime = ticks - m_lLastTime;
RefreshGameTime(m_lLastTime);
if (m_bGameTimerPaused)
{
// On un-pause, we will restore the specified time.
// If we don't do this, the un-pause will over-write the offset again.
m_lGameTimerPausedTime = ticks;
}
if (m_TimeDebug)
{
CryLogAlways("[CTimer] SetOffset: Offset %lld -> %lld, GameTime %f -> %f", (long long)previousOffset, (long long)m_lOffsetTime, GetCurrTime(ETIMER_GAME), previousGameTime);
}
}
int64 CTimer::SecondsToTicks(double seconds) const
{
return (int64)(seconds * (double)m_lTicksPerSec);
}
-166
View File
@@ -1,166 +0,0 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYSYSTEM_TIMER_H
#define CRYINCLUDE_CRYSYSTEM_TIMER_H
# pragma once
#include <ITimer.h>
// Implements all common timing routines
class CTimer
: public ITimer
{
public:
// constructor
CTimer();
// destructor
~CTimer() = default;
bool Init();
// interface ITimer ----------------------------------------------------------
// TODO: Review m_time usage in System.cpp
// if it wants Game Time / UI Time or a new Render Time?
void ResetTimer() override;
void UpdateOnFrameStart() override;
float GetCurrTime(ETimer which = ETIMER_GAME) const override;
CTimeValue GetAsyncTime() const override;
float GetAsyncCurTime() override; // retrieve the actual wall clock time passed since the game started, in seconds
float GetFrameTime(ETimer which = ETIMER_GAME) const override;
float GetRealFrameTime() const override;
float GetTimeScale() const override;
float GetTimeScale(uint32 channel) const override;
void SetTimeScale(float scale, uint32 channel = 0) override;
void ClearTimeScales() override;
void EnableTimer(bool bEnable) override;
float GetFrameRate() override;
float GetProfileFrameBlending(float* pfBlendTime = nullptr, int* piBlendMode = nullptr) override;
void Serialize(TSerialize ser) override;
bool IsTimerEnabled() const override;
//! try to pause/unpause a timer
// returns true if successfully paused/unpaused, false otherwise
bool PauseTimer(ETimer which, bool bPause) override;
//! determine if a timer is paused
// returns true if paused, false otherwise
bool IsTimerPaused(ETimer which) override;
//! try to set a timer
// return true if successful, false otherwise
bool SetTimer(ETimer which, float timeInSeconds) override;
//! make a tm struct from a time_t in UTC (like gmtime)
void SecondsToDateUTC(time_t time, struct tm& outDateUTC) override;
//! make a UTC time from a tm (like timegm, but not available on all platforms)
time_t DateToSecondsUTC(struct tm& timePtr) override;
//! Convert from Tics to Seconds
float TicksToSeconds(int64 ticks) override
{
return float((double)ticks * m_fSecsPerTick);
}
//! Get number of ticks per second
int64 GetTicksPerSecond() override
{
return m_lTicksPerSec;
}
const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const override { return m_CurrTime[(int)which]; }
ITimer* CreateNewTimer() override;
void EnableFixedTimeMode(bool enable, float timeStep) override;
private: // ---------------------------------------------------------------------
// ---------------------------------------------------------------------------
// updates m_CurrTime (either pass m_lCurrentTime or custom curTime)
void RefreshGameTime(int64 curTime);
void RefreshUITime(int64 curTime);
void UpdateBlending();
float GetAverageFrameTime();
// Updates the game-time offset to match the the specified time.
// The argument is the new number of ticks since the last Reset().
void SetOffsetToMatchGameTime(int64 ticks);
// Convert seconds to ticks using the timer frequency.
// Note: Loss of precision may occur, especially if magnitude of argument or timer frequency is large.
int64 SecondsToTicks(double seconds) const;
enum
{
MAX_FRAME_AVERAGE = 100,
NUM_TIME_SCALE_CHANNELS = 8,
};
//////////////////////////////////////////////////////////////////////////
// Dynamic state, reset by ResetTimer()
//////////////////////////////////////////////////////////////////////////
CTimeValue m_CurrTime[ETIMER_LAST]; // Time since last Reset(), cached during Update()
int64 m_lBaseTime; // Ticks elapsed since system boot, all other tick-unit variables are relative to this.
int64 m_lLastTime; // Ticks since last Reset(). This is the base for UI time. UI time is monotonic, it always moves forward at a constant rate until the timer is Reset()).
int64 m_lOffsetTime; // Additional ticks for Game time (relative to UI time). Game time can be affected by loading, pausing, time smoothing and time clamping, as well as SetTimer().
//// the GetcurAsyncTime function appears to want to return the actual wall clock time delta
//// but its using the base time (above) which is adjusted when there is a frame skip.
//int64 m_lBaseTime_Async;
float m_fFrameTime; // In seconds since the last Update(), clamped/smoothed etc.
float m_fRealFrameTime; // In real seconds since the last Update(), non-clamped/un-smoothed etc.
bool m_bGameTimerPaused; // Set if the game is paused. GetFrameTime() will return 0, GetCurrTime(ETIMER_GAME) will not progress.
int64 m_lGameTimerPausedTime; // The UI time when the game timer was paused. On un-pause, offset will be adjusted to match.
//////////////////////////////////////////////////////////////////////////
// Persistant state, kept by ResetTimer()
//////////////////////////////////////////////////////////////////////////
bool m_bEnabled;
unsigned int m_nFrameCounter;
int64 m_lTicksPerSec; // Ticks per second
double m_fSecsPerTick; // Seconds per tick
// smoothing
float m_arrFrameTimes[MAX_FRAME_AVERAGE];
float m_fAverageFrameTime; // used for smoothing (AverageFrameTime())
float m_fAvgFrameTime; // used for blend weighting (UpdateBlending())
float m_fProfileBlend; // current blending amount for profile.
float m_fSmoothTime; // smoothing interval (up to m_profile_smooth_time).
// time scale
float m_timeScaleChannels[NUM_TIME_SCALE_CHANNELS];
float m_totalTimeScale;
//////////////////////////////////////////////////////////////////////////
// Console vars, always have default value on secondary CTimer instances
//////////////////////////////////////////////////////////////////////////
float m_fixed_time_step; // in seconds
float m_max_time_step; // in seconds
float m_cvar_time_scale; // slow down time cvar
int m_TimeSmoothing; // Console Variable, 0=off, otherwise on
int m_TimeDebug; // Console Variable, 0=off, otherwise on
// Profile averaging help.
float m_profile_smooth_time; // seconds to exponentially smooth profile results.
int m_profile_weighting; // weighting mode (see RegisterVar desc).
//bool m_fixedTimeModeEnabled;
//float m_fixedTimeModeStep;
};
#endif // CRYINCLUDE_CRYSYSTEM_TIMER_H
+8 -6
View File
@@ -16,7 +16,6 @@
#include "System.h"
#include "ConsoleBatchFile.h"
#include <ITimer.h>
#include <IRenderer.h>
#include <ISystem.h>
#include <ILog.h>
@@ -28,6 +27,7 @@
#include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
#include <AzCore/std/string/conversions.h>
#include <AzCore/std/algorithm.h>
#include <AzCore/Time/ITime.h>
#include <LyShine/Bus/UiCursorBus.h>
//#define DEFENCE_CVAR_HASH_LOGGING
@@ -105,7 +105,8 @@ void Command_SetWaitSeconds(IConsoleCmdArgs* pCmd)
if (pCmd->GetArgCount() > 1)
{
pConsole->m_waitSeconds.SetSeconds(atof(pCmd->GetArg(1)));
pConsole->m_waitSeconds += gEnv->pTimer->GetFrameStartTime();
const AZ::TimeMs elaspedTimeMs = AZ::GetRealElapsedTimeMs();
pConsole->m_waitSeconds += CTimeValue(AZ::TimeMsToSecondsDouble(elaspedTimeMs));
}
}
@@ -305,7 +306,6 @@ void CXConsole::Init(ISystem* pSystem)
{
m_pFont = pSystem->GetICryFont()->GetFont("default");
}
m_pTimer = pSystem->GetITimer();
AzFramework::InputChannelEventListener::Connect();
AzFramework::InputTextEventListener::Connect();
@@ -934,8 +934,8 @@ void CXConsole::Update()
const float fRepeatDelay = 1.0f / 40.0f; // in sec (similar to Windows default but might differ from actual setting)
const float fHitchDelay = 1.0f / 10.0f; // in sec. Very low, but still reasonable frame-rate (debug builds)
m_fRepeatTimer -= gEnv->pTimer->GetRealFrameTime(); // works even when time is manipulated
// m_fRepeatTimer -= gEnv->pTimer->GetFrameTime(ITimer::ETIMER_UI); // can be used once ETIMER_UI works even with t_FixedTime
const AZ::TimeUs delta = AZ::GetRealTickDeltaTimeUs(); // works even when time is manipulated
m_fRepeatTimer -= AZ::TimeUsToSeconds(delta);
if (m_fRepeatTimer <= 0.0f)
{
@@ -1961,7 +1961,9 @@ void CXConsole::ExecuteDeferredCommands()
if (m_waitSeconds.GetValue())
{
if (m_waitSeconds > gEnv->pTimer->GetFrameStartTime())
const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs();
const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs);
if (m_waitSeconds > CTimeValue(elaspedTimeSec))
{
return;
}
+1 -2
View File
@@ -13,8 +13,8 @@
#pragma once
#include <IConsole.h>
#include "Timer.h"
#include <CryCommon/StlUtils.h>
#include <CryCommon/TimeValue.h>
#include <AzFramework/Components/ConsoleBus.h>
#include <AzFramework/CommandLine/CommandRegistrationBus.h>
@@ -377,7 +377,6 @@ private: // ----------------------------------------------------------
CSystem* m_pSystem;
IFFont* m_pFont;
ITimer* m_pTimer;
ICVar* m_pSysDeactivateConsole;
@@ -10,6 +10,7 @@
#include "CrySystem_precompiled.h"
#include "SerializeXMLReader.h"
#include <ISystem.h>
#include <AzCore/Time/ITime.h>
#define TAG_SCRIPT_VALUE "v"
#define TAG_SCRIPT_TYPE "t"
@@ -21,7 +22,6 @@
CSerializeXMLReaderImpl::CSerializeXMLReaderImpl(const XmlNodeRef& nodeRef)
: m_nErrors(0)
{
//m_curTime = gEnv->pTimer->GetFrameStartTime();
assert(!!nodeRef);
m_nodeStack.push_back(CParseState());
m_nodeStack.back().Init(nodeRef);
@@ -87,18 +87,21 @@ bool CSerializeXMLReaderImpl::Value(const char* name, CTimeValue& value)
}
else
{
const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs();
const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs);
const CTimeValue elaspedTime(elaspedTimeSec);
float delta;
if (!GetAttr(nodeRef, name, delta))
{
//CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,"Failed to read time value %s", name);
//Failed();
value = gEnv->pTimer->GetFrameStartTime(); // in case we don't find the node, it was assumed to be the default value (0.0)
value = elaspedTime; // in case we don't find the node, it was assumed to be the default value (0.0)
// 0.0 means current time, whereas "zero" really means CTimeValue(0.0), see above
return false;
}
else
{
value = CTimeValue(gEnv->pTimer->GetFrameStartTime() + delta);
value = CTimeValue(elaspedTime + delta);
}
}
return true;
@@ -11,7 +11,6 @@
#include "SimpleSerialize.h"
#include <stack>
#include <IXml.h>
#include <ITimer.h>
#include "xml.h"
class CSerializeXMLReaderImpl
@@ -10,6 +10,8 @@
#include "CrySystem_precompiled.h"
#include "SerializeXMLWriter.h"
#include <AzCore/Time/ITime.h>
static const size_t MAX_NODE_STACK_DEPTH = 40;
#define TAG_SCRIPT_VALUE "v"
@@ -18,7 +20,9 @@ static const size_t MAX_NODE_STACK_DEPTH = 40;
CSerializeXMLWriterImpl::CSerializeXMLWriterImpl(const XmlNodeRef& nodeRef)
{
m_curTime = gEnv->pTimer->GetFrameStartTime();
const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs();
const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs);
m_curTime = CTimeValue(elaspedTimeSec);
assert(!!nodeRef);
m_nodeStack.push_back(nodeRef);
@@ -13,7 +13,6 @@
#include <ISystem.h>
#include <ITimer.h>
#include <IXml.h>
#include "SimpleSerialize.h"
@@ -20,7 +20,6 @@ set(FILES
SystemEventDispatcher.cpp
SystemInit.cpp
SystemWin32.cpp
Timer.cpp
XConsole.cpp
XConsoleVariable.cpp
AZCrySystemInitLogSink.h
@@ -36,7 +35,6 @@ set(FILES
CrySystem_precompiled.h
System.h
SystemEventDispatcher.h
Timer.h
XConsole.h
XConsoleVariable.h
XML/SerializeXMLReader.cpp
@@ -20,7 +20,6 @@
#include <AzCore/std/parallel/lock.h>
#include <AzCore/Casting/numeric_cast.h>
#include <AzCore/Debug/EventTrace.h>
#include <AzCore/Debug/Timer.h>
#include <AzCore/Jobs/JobFunction.h>
#include <AzCore/Jobs/Job.h>
#include <AzCore/Task/TaskGraph.h>
@@ -58,7 +58,7 @@ namespace AtomToolsFramework
void CreateStaticModules(AZStd::vector<AZ::Module*>& outModules) override;
const char* GetCurrentConfigurationName() const override;
void StartCommon(AZ::Entity* systemEntity) override;
void Tick(float deltaOverride = -1.f) override;
void Tick() override;
void Stop() override;
protected:
@@ -454,10 +454,10 @@ namespace AtomToolsFramework
return false;
}
void AtomToolsApplication::Tick(float deltaOverride)
void AtomToolsApplication::Tick()
{
TickSystem();
Base::Tick(deltaOverride);
Base::Tick();
if (WasExitMainLoopRequested())
{
@@ -8,7 +8,6 @@
#include "FlyCameraInputComponent.h"
#include <ISystem.h>
#include <ITimer.h>
#include <IConsole.h>
#include <AzCore/Component/Component.h>
@@ -514,7 +514,6 @@ namespace EMotionFX
AzToolsFramework::EditorEvents::Bus::Handler::BusConnect();
AzToolsFramework::EditorAnimationSystemRequestsBus::Handler::BusConnect();
AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect();
m_updateTimer.Stamp();
// Register custom property handlers for the reflected property editor.
m_propertyHandlers = RegisterPropertyTypes();
@@ -604,15 +603,8 @@ namespace EMotionFX
}
//////////////////////////////////////////////////////////////////////////
void SystemComponent::OnTick(float delta, AZ::ScriptTimePoint timePoint)
void SystemComponent::OnTick(float delta, [[maybe_unused]]AZ::ScriptTimePoint timePoint)
{
AZ_UNUSED(timePoint);
#if defined (EMOTIONFXANIMATION_EDITOR)
AZ_UNUSED(delta);
delta = m_updateTimer.StampAndGetDeltaTimeInSeconds();
#endif
// Flush events prior to updating EMotion FX.
ActorNotificationBus::ExecuteQueuedEvents();
@@ -20,7 +20,6 @@
#include <CrySystemBus.h>
#if defined (EMOTIONFXANIMATION_EDITOR)
# include <AzCore/Debug/Timer.h>
# include <AzToolsFramework/API/ToolsApplicationAPI.h>
# include <AzToolsFramework/API/EditorAnimationSystemRequestBus.h>
# include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
@@ -117,7 +116,6 @@ namespace EMotionFX
AzToolsFramework::AssetBrowser::SourceFileDetails GetSourceFileDetails(const char* fullSourceFileName) override;
//////////////////////////////////////////////////////////////////////////////////////
AZ::Debug::Timer m_updateTimer;
AZStd::vector<AzToolsFramework::PropertyHandlerBase*> m_propertyHandlers;
#endif // EMOTIONFXANIMATION_EDITOR
@@ -7,7 +7,6 @@
*/
#include <AzTest/AzTest.h>
#include <Mocks/ITimerMock.h>
#include <Mocks/ICryPakMock.h>
#include <Mocks/IConsoleMock.h>
#include <Mocks/ISystemMock.h>
@@ -106,7 +105,6 @@ struct MockGlobalEnvironment
{
MockGlobalEnvironment()
{
m_stubEnv.pTimer = &m_stubTimer;
m_stubEnv.pCryPak = &m_stubPak;
m_stubEnv.pConsole = &m_stubConsole;
m_stubEnv.pSystem = &m_stubSystem;
@@ -120,7 +118,6 @@ struct MockGlobalEnvironment
private:
SSystemGlobalEnvironment m_stubEnv;
testing::NiceMock<TimerMock> m_stubTimer;
testing::NiceMock<CryPakMock> m_stubPak;
testing::NiceMock<ConsoleMock> m_stubConsole;
testing::NiceMock<SystemMock> m_stubSystem;
@@ -10,6 +10,7 @@
#include "IGestureRecognizer.h"
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Time/ITime.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace Gestures
@@ -83,7 +84,7 @@ namespace Gestures
Config m_config;
int64 m_timeOfLastEvent;
AZ::TimeMs m_timeOfLastEvent;
ScreenPosition m_positionOfFirstEvent;
ScreenPosition m_positionOfLastEvent;
@@ -8,9 +8,8 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Time/ITime.h>
#include <CryCommon/ISystem.h>
#include <CryCommon/TimeValue.h>
#include <CryCommon/ITimer.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext* context)
@@ -57,7 +56,7 @@ inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext*
////////////////////////////////////////////////////////////////////////////////////////////////////
inline Gestures::RecognizerClickOrTap::RecognizerClickOrTap(const Config& config)
: m_config(config)
, m_timeOfLastEvent(0)
, m_timeOfLastEvent(AZ::Time::ZeroTimeMs)
, m_positionOfFirstEvent()
, m_positionOfLastEvent()
, m_currentCount(0)
@@ -77,13 +76,12 @@ inline bool Gestures::RecognizerClickOrTap::OnPressedEvent(const AZ::Vector2& sc
{
return false;
}
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs();
switch (m_currentState)
{
case State::Idle:
{
m_timeOfLastEvent = currentTime.GetValue();
m_timeOfLastEvent = currentTime;
m_positionOfFirstEvent = screenPosition;
m_positionOfLastEvent = screenPosition;
m_currentCount = 0;
@@ -92,7 +90,7 @@ inline bool Gestures::RecognizerClickOrTap::OnPressedEvent(const AZ::Vector2& sc
break;
case State::Released:
{
if ((currentTime.GetDifferenceInSeconds(m_timeOfLastEvent) > m_config.maxSecondsBetweenClicksOrTaps) ||
if ((AZ::TimeMsToSeconds(currentTime - m_timeOfLastEvent) > m_config.maxSecondsBetweenClicksOrTaps) ||
(screenPosition.GetDistance(m_positionOfFirstEvent) > m_config.maxPixelsBetweenClicksOrTaps))
{
// Treat this as the start of a new tap sequence.
@@ -100,7 +98,7 @@ inline bool Gestures::RecognizerClickOrTap::OnPressedEvent(const AZ::Vector2& sc
m_positionOfFirstEvent = screenPosition;
}
m_timeOfLastEvent = currentTime.GetValue();
m_timeOfLastEvent = currentTime;
m_positionOfLastEvent = screenPosition;
m_currentState = State::Pressed;
}
@@ -129,8 +127,8 @@ inline bool Gestures::RecognizerClickOrTap::OnDownEvent(const AZ::Vector2& scree
{
case State::Pressed:
{
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
if ((currentTime.GetDifferenceInSeconds(m_timeOfLastEvent) > m_config.maxSecondsHeld) ||
const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs();
if ((AZ::TimeMsToSeconds(currentTime - m_timeOfLastEvent) > m_config.maxSecondsHeld) ||
(screenPosition.GetDistance(m_positionOfLastEvent) > m_config.maxPixelsMoved))
{
// Tap recognition failed.
@@ -168,8 +166,8 @@ inline bool Gestures::RecognizerClickOrTap::OnReleasedEvent(const AZ::Vector2& s
{
case State::Pressed:
{
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
if ((currentTime.GetDifferenceInSeconds(m_timeOfLastEvent) > m_config.maxSecondsHeld) ||
const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs();
if ((AZ::TimeMsToSeconds(currentTime - m_timeOfLastEvent) > m_config.maxSecondsHeld) ||
(screenPosition.GetDistance(m_positionOfLastEvent) > m_config.maxPixelsMoved))
{
// Tap recognition failed.
@@ -179,7 +177,7 @@ inline bool Gestures::RecognizerClickOrTap::OnReleasedEvent(const AZ::Vector2& s
else if (++m_currentCount >= m_config.minClicksOrTaps)
{
// Tap recognition succeeded.
m_timeOfLastEvent = currentTime.GetValue();
m_timeOfLastEvent = currentTime;
m_positionOfLastEvent = screenPosition;
OnDiscreteGestureRecognized();
@@ -190,7 +188,7 @@ inline bool Gestures::RecognizerClickOrTap::OnReleasedEvent(const AZ::Vector2& s
else
{
// More taps are needed.
m_timeOfLastEvent = currentTime.GetValue();
m_timeOfLastEvent = currentTime;
m_positionOfLastEvent = screenPosition;
m_currentState = State::Released;
}
@@ -10,6 +10,7 @@
#include "IGestureRecognizer.h"
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Time/ITime.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace Gestures
@@ -75,7 +76,7 @@ namespace Gestures
Config m_config;
int64 m_startTime;
AZ::TimeMs m_startTime;
ScreenPosition m_startPosition;
ScreenPosition m_currentPosition;
@@ -8,7 +8,6 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ITimer.h>
#include <CryCommon/ISystem.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -44,7 +43,7 @@ inline void Gestures::RecognizerDrag::Config::Reflect(AZ::ReflectContext* contex
////////////////////////////////////////////////////////////////////////////////////////////////////
inline Gestures::RecognizerDrag::RecognizerDrag(const Config& config)
: m_config(config)
, m_startTime(0)
, m_startTime(AZ::Time::ZeroTimeMs)
, m_startPosition()
, m_currentPosition()
, m_currentState(State::Idle)
@@ -68,7 +67,7 @@ inline bool Gestures::RecognizerDrag::OnPressedEvent(const AZ::Vector2& screenPo
{
case State::Idle:
{
m_startTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0;
m_startTime = AZ::GetRealElapsedTimeMs();
m_startPosition = screenPosition;
m_currentPosition = screenPosition;
m_currentState = State::Pressed;
@@ -101,11 +100,11 @@ inline bool Gestures::RecognizerDrag::OnDownEvent(const AZ::Vector2& screenPosit
{
case State::Pressed:
{
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
if ((currentTime.GetDifferenceInSeconds(m_startTime) >= m_config.minSecondsHeld) &&
const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs();
if ((AZ::TimeMsToSeconds(currentTime - m_startTime) >= m_config.minSecondsHeld) &&
(GetDistance() >= m_config.minPixelsMoved))
{
m_startTime = currentTime.GetValue();
m_startTime = currentTime;
m_startPosition = m_currentPosition;
OnContinuousGestureInitiated();
m_currentState = State::Dragging;
@@ -10,8 +10,8 @@
#include "IGestureRecognizer.h"
#include <CryCommon/ISystem.h>
#include <CryCommon/ITimer.h>
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Time/ITime.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace Gestures
@@ -64,7 +64,7 @@ namespace Gestures
AZ::Vector2 GetStartPosition() const { return m_startPosition; }
AZ::Vector2 GetCurrentPosition() const { return m_currentPosition; }
float GetDuration() const { return (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetDifferenceInSeconds(m_startTime) : 0.0f; }
float GetDuration() const { return AZ::TimeUsToSeconds(AZ::GetLastSimulationTickTime() - m_startTime); }
private:
enum class State
@@ -76,7 +76,7 @@ namespace Gestures
Config m_config;
int64 m_startTime;
AZ::TimeUs m_startTime;
ScreenPosition m_startPosition;
ScreenPosition m_currentPosition;
@@ -8,7 +8,6 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ITimer.h>
#include <CryCommon/ISystem.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -44,7 +43,7 @@ inline void Gestures::RecognizerHold::Config::Reflect(AZ::ReflectContext* contex
////////////////////////////////////////////////////////////////////////////////////////////////////
inline Gestures::RecognizerHold::RecognizerHold(const Config& config)
: m_config(config)
, m_startTime(0)
, m_startTime(AZ::Time::ZeroTimeUs)
, m_startPosition()
, m_currentPosition()
, m_currentState(State::Idle)
@@ -68,7 +67,7 @@ inline bool Gestures::RecognizerHold::OnPressedEvent(const AZ::Vector2& screenPo
{
case State::Idle:
{
m_startTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0;
m_startTime = AZ::GetLastSimulationTickTime();
m_startPosition = screenPosition;
m_currentPosition = screenPosition;
m_currentState = State::Pressed;
@@ -101,13 +100,13 @@ inline bool Gestures::RecognizerHold::OnDownEvent(const AZ::Vector2& screenPosit
{
case State::Pressed:
{
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
if (screenPosition.GetDistance(m_startPosition) > m_config.maxPixelsMoved)
{
// Hold recognition failed.
m_currentState = State::Idle;
}
else if (currentTime.GetDifferenceInSeconds(m_startTime) >= m_config.minSecondsHeld)
else if (const AZ::TimeUs currentTime = AZ::GetLastSimulationTickTime();
AZ::TimeUsToSeconds(currentTime - m_startTime) >= m_config.minSecondsHeld)
{
// Hold recognition succeeded.
OnContinuousGestureInitiated();
@@ -10,6 +10,7 @@
#include "IGestureRecognizer.h"
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Time/ITime.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace Gestures
@@ -90,7 +91,7 @@ namespace Gestures
ScreenPosition m_startPositions[2];
ScreenPosition m_currentPositions[2];
int64_t m_lastUpdateTimes[2];
AZ::TimeMs m_lastUpdateTimes[2];
State m_currentState;
};
@@ -8,7 +8,6 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ITimer.h>
#include <CryCommon/ISystem.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -42,8 +41,8 @@ inline Gestures::RecognizerPinch::RecognizerPinch(const Config& config)
: m_config(config)
, m_currentState(State::Idle)
{
m_lastUpdateTimes[0] = 0;
m_lastUpdateTimes[1] = 0;
m_lastUpdateTimes[0] = AZ::Time::ZeroTimeMs;
m_lastUpdateTimes[1] = AZ::Time::ZeroTimeMs;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -112,7 +111,7 @@ inline bool Gestures::RecognizerPinch::OnDownEvent(const AZ::Vector2& screenPosi
}
m_currentPositions[pointerIndex] = screenPosition;
m_lastUpdateTimes[pointerIndex] = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0;
m_lastUpdateTimes[pointerIndex] = AZ::GetRealElapsedTimeMs();
if (m_lastUpdateTimes[0] != m_lastUpdateTimes[1])
{
// We need to wait until both touches have been updated this frame.
@@ -10,6 +10,7 @@
#include "IGestureRecognizer.h"
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Time/ITime.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace Gestures
@@ -86,7 +87,7 @@ namespace Gestures
ScreenPosition m_startPositions[2];
ScreenPosition m_currentPositions[2];
int64_t m_lastUpdateTimes[2];
AZ::TimeMs m_lastUpdateTimes[2];
State m_currentState;
};
@@ -9,7 +9,6 @@
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <CryCommon/ISystem.h>
#include <CryCommon/ITimer.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void Gestures::RecognizerRotate::Config::Reflect(AZ::ReflectContext* context)
@@ -42,8 +41,8 @@ inline Gestures::RecognizerRotate::RecognizerRotate(const Config& config)
: m_config(config)
, m_currentState(State::Idle)
{
m_lastUpdateTimes[0] = 0;
m_lastUpdateTimes[1] = 0;
m_lastUpdateTimes[0] = AZ::Time::ZeroTimeMs;
m_lastUpdateTimes[1] = AZ::Time::ZeroTimeMs;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -101,7 +100,7 @@ inline bool Gestures::RecognizerRotate::OnDownEvent(const AZ::Vector2& screenPos
}
m_currentPositions[pointerIndex] = screenPosition;
m_lastUpdateTimes[pointerIndex] = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0;
m_lastUpdateTimes[pointerIndex] = AZ::GetRealElapsedTimeMs();
if (m_lastUpdateTimes[0] != m_lastUpdateTimes[1])
{
// We need to wait until both touches have been updated this frame.
@@ -8,8 +8,8 @@
#pragma once
#include "IGestureRecognizer.h"
#include <CryCommon/ITimer.h>
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Time/ITime.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace Gestures
@@ -66,7 +66,7 @@ namespace Gestures
AZ::Vector2 GetDirection() const { return GetDelta().GetNormalized(); }
float GetDistance() const { return GetEndPosition().GetDistance(GetStartPosition()); }
float GetDuration() const { return CTimeValue(m_endTime).GetDifferenceInSeconds(m_startTime); }
float GetDuration() const { return AZ::TimeMsToSeconds(m_endTime - m_startTime); }
float GetVelocity() const { return GetDistance() / GetDuration(); }
private:
@@ -81,8 +81,8 @@ namespace Gestures
ScreenPosition m_startPosition;
ScreenPosition m_endPosition;
int64 m_startTime;
int64 m_endTime;
AZ::TimeMs m_startTime;
AZ::TimeMs m_endTime;
State m_currentState;
};
@@ -45,8 +45,8 @@ inline Gestures::RecognizerSwipe::RecognizerSwipe(const Config& config)
: m_config(config)
, m_startPosition()
, m_endPosition()
, m_startTime(0)
, m_endTime(0)
, m_startTime(AZ::Time::ZeroTimeMs)
, m_endTime(AZ::Time::ZeroTimeMs)
, m_currentState(State::Idle)
{
}
@@ -68,7 +68,7 @@ inline bool Gestures::RecognizerSwipe::OnPressedEvent(const AZ::Vector2& screenP
{
case State::Idle:
{
m_startTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0;
m_startTime = AZ::GetRealElapsedTimeMs();
m_startPosition = screenPosition;
m_endPosition = screenPosition;
m_currentState = State::Pressed;
@@ -98,8 +98,8 @@ inline bool Gestures::RecognizerSwipe::OnDownEvent([[maybe_unused]] const AZ::Ve
{
case State::Pressed:
{
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
if (currentTime.GetDifferenceInSeconds(m_startTime) > m_config.maxSecondsHeld)
const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs();
if (AZ::TimeMsToSeconds(currentTime - m_startTime) > m_config.maxSecondsHeld)
{
// Swipe recognition failed because we took too long.
m_currentState = State::Idle;
@@ -134,12 +134,12 @@ inline bool Gestures::RecognizerSwipe::OnReleasedEvent(const AZ::Vector2& screen
{
case State::Pressed:
{
const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue();
if ((currentTime.GetDifferenceInSeconds(m_startTime) <= m_config.maxSecondsHeld) &&
const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs();
if ((AZ::TimeMsToSeconds(currentTime - m_startTime) <= m_config.maxSecondsHeld) &&
(screenPosition.GetDistance(m_startPosition) >= m_config.minPixelsMoved))
{
// Swipe recognition succeeded.
m_endTime = currentTime.GetValue();
m_endTime = currentTime;
m_endPosition = screenPosition;
OnDiscreteGestureRecognized();
m_currentState = State::Idle;
+22 -21
View File
@@ -6,13 +6,25 @@
*
*/
#pragma once
#include <AzTest/AzTest.h>
#include <Mocks/StubTimer.h>
#include <Gestures/IGestureRecognizer.h>
#include <AzCore/Memory/OSAllocator.h>
#include <AzCore/UnitTest/Mocks/MockITime.h>
#include <AzTest/AzTest.h>
#include <Gestures/IGestureRecognizer.h>
class BaseGestureTest
: public ::testing::Test
namespace GesturesTests
{
struct StubTimer : public AZ::StubTimeSystem
{
AZ::TimeMs GetRealElapsedTimeMs() const override
{
return m_realElapsedTime;
}
AZ::TimeMs m_realElapsedTime = AZ::Time::ZeroTimeMs;
};
} // namespace GesturesTests
class BaseGestureTest : public ::testing::Test
{
public:
BaseGestureTest()
@@ -24,39 +36,30 @@ public:
{
// global environment stubs
m_env = new(AZ_OS_MALLOC(sizeof(SSystemGlobalEnvironment), alignof(SSystemGlobalEnvironment))) SSystemGlobalEnvironment();
m_stubTimer = new StubTimer(1.0f / 30.0f);
gEnv = m_env;
gEnv->pTimer = m_stubTimer;
m_stubTimer = new GesturesTests::StubTimer();
// simulated position
m_pos = AZ::Vector2(0.0f, 0.0f);
}
void TearDown() override
{
gEnv->pTimer = nullptr;
gEnv = nullptr;
if (m_stubTimer)
{
delete m_stubTimer;
m_stubTimer = nullptr;
}
if (m_env)
{
m_env->~SSystemGlobalEnvironment();
AZ_OS_FREE(m_env);
m_env = nullptr;
}
delete m_stubTimer;
}
protected:
// time manipulation
void SetTime(float sec)
{
m_stubTimer->SetTime(sec);
m_stubTimer->m_realElapsedTime = AZ::SecondsToTimeMs(sec);
}
// simple position caching interface
@@ -97,9 +100,7 @@ protected:
}
private:
SSystemGlobalEnvironment* m_env;
StubTimer* m_stubTimer;
SSystemGlobalEnvironment* m_env = nullptr;
GesturesTests::StubTimer* m_stubTimer = nullptr;
AZ::Vector2 m_pos;
};
@@ -7,7 +7,6 @@
*/
#include <AzTest/AzTest.h>
#include <Mocks/StubTimer.h>
#include <Gestures/GestureRecognizerClickOrTap.h>
#include "BaseGestureTest.h"
@@ -7,7 +7,6 @@
*/
#include <AzTest/AzTest.h>
#include <Mocks/StubTimer.h>
#include <Gestures/GestureRecognizerPinch.h>
#include "BaseGestureTest.h"
@@ -12,21 +12,35 @@
namespace HttpRequestor
{
/*
**
** The Parameters needed to make a HTTP call and then receive the
** returned JSON in a meaningful place. Examples of use are in the
** HttpRequestCaller class.
**
*/
//! Models the parameters needed to make a HTTP call and then receive the
//! returned JSON in a meaningful place. Examples of use are in the HttpRequestCaller class.
class Parameters
{
public:
// Initializing ctor
// Ctors
//! @param URI A universal resource indicator representing an endpoint.
//! @param method The HTTP method to use, for example HTTP_GET.
//! @param callback The callback method to receive a HTTP call's response.
Parameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Callback& callback);
//! @param URI A universal resource indicator representing an endpoint.
//! @param method The HTTP method to use, for example HTTP_GET.
//! @param headers A map of header names and values to use.
//! @param callback The callback method to receive a HTTP call's response.
Parameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const Callback& callback);
Parameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const AZStd::string& body, const Callback& callback);
//! @param URI A universal resource indicator representing an endpoint.
//! @param method The HTTP method to use, for example HTTP_POST.
//! @param headers A map of header names and values to use.
//! @param body An data to associate with an HTTP call.
//! @param callback The callback method to receive a HTTP call's response.
Parameters(
const AZStd::string& URI,
Aws::Http::HttpMethod method,
const Headers& headers,
const AZStd::string& body,
const Callback& callback);
// Defaults
virtual ~Parameters() = default;
@@ -36,30 +50,49 @@ namespace HttpRequestor
Parameters(Parameters&&) = default;
Parameters& operator=(Parameters&&) = default;
//returns the URI in string form as an recipient of the HTTP connection
const Aws::String& GetURI() const { return m_URI; }
//! Get the URI in string form as an recipient of the HTTP connection.
const Aws::String& GetURI() const
{
return m_URI;
}
//returns the method of which the HTTP request will take. GET, POST, DELETE, PUT, or HEAD
Aws::Http::HttpMethod GetMethod() const { return m_method; }
//! Get the HTTP method configured to use for a request.
Aws::Http::HttpMethod GetMethod() const
{
return m_method;
}
//returns the list of extra headers to include in the request
const Headers & GetHeaders() const { return m_headers; }
//! Get the list of extra headers to send as part of a request.
//! @return A map of header-value pairs.
const Headers& GetHeaders() const
{
return m_headers;
}
//returns the stream for the body of the request
const std::shared_ptr<std::stringstream> & GetBodyStream() const { return m_bodyStream; }
//! Get an input stream that can be used to send the body of a request.
//! @return A string stream representing a request body.
const std::shared_ptr<std::stringstream>& GetBodyStream() const
{
return m_bodyStream;
}
//returns the function of which to feed back the JSON that the HTTP call resulted in. The function also requires the HTTPResponseCode indicating if the call was successful or failed
const Callback & GetCallback() const { return m_callback; }
//! Get the callback function for processing JSON returned in an HTTP response.
//! Callback functions are responsible for correctly interpreting the HTTP response code, and should communicate any
//! failures.
//! @return The callback function to process endpoint responses with.
const Callback& GetCallback() const
{
return m_callback;
}
private:
Aws::String m_URI;
Aws::Http::HttpMethod m_method;
Headers m_headers;
std::shared_ptr<std::stringstream> m_bodyStream; // required by Aws::Http::HttpRequest
Callback m_callback;
Aws::String m_URI;
Aws::Http::HttpMethod m_method;
Headers m_headers;
std::shared_ptr<std::stringstream> m_bodyStream; // required by Aws::Http::HttpRequest
Callback m_callback;
};
inline Parameters::Parameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Callback& callback)
: m_URI(URI.c_str())
, m_method(method)
@@ -75,7 +108,8 @@ namespace HttpRequestor
{
}
inline Parameters::Parameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const AZStd::string& body, const Callback& callback)
inline Parameters::Parameters(
const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const AZStd::string& body, const Callback& callback)
: m_URI(URI.c_str())
, m_method(method)
, m_headers(headers)
@@ -83,6 +117,5 @@ namespace HttpRequestor
, m_callback(callback)
{
}
}
@@ -5,7 +5,6 @@
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/EBus/EBus.h>
@@ -13,24 +12,70 @@
namespace HttpRequestor
{
class HttpRequestorRequests
: public AZ::EBusTraits
//! Defines request APIs for Gem. Supports making HTTP requests.
//! See [HTTP RFC](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html) for expectations around methods, headers, and body.
class HttpRequestorRequests : public AZ::EBusTraits
{
public:
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single;
// Public functions
//! Make a RESTful call to a HTTP(s) endpoint. Receive the response, via the supplied callback as JSON.
//! @param URI The universal resource indicator representing the endpoint to make the request to.
//! @param method The HTTP method to use, for example HTTP_GET.
//! @param callback The callback method to receive the JSON response object.
virtual void AddRequest(const AZStd::string& URI, Aws::Http::HttpMethod method, const Callback& callback) = 0;
virtual void AddRequestWithHeaders(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers & headers, const Callback& callback) = 0;
virtual void AddRequestWithHeadersAndBody(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers & headers, const AZStd::string& body, const Callback& callback) = 0;
//! Make a RESTful call to a HTTP(s) endpoint with customized headers. Receive the response, via the supplied callback as JSON.
//! @param URI The universal resource indicator representing the endpoint to make the request to.
//! @param method The HTTP method to use, for example HTTP_GET.
//! @param headers A map of header names and values to set on the request.
//! @param callback The callback method to receive the JSON response object.
virtual void AddRequestWithHeaders(
const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const Callback& callback) = 0;
//! Make a RESTful call to a HTTP(s) endpoint with customized headers and a body. Receive the response, via the supplied callback as JSON.
//! @param URI The universal resource indicator representing the endpoint to make the request to.
//! @param method The HTTP method to use, for example HTTP_POST.
//! @param headers A map of header names and values to set on the request.
//! @param body Any HTTP request data to include in the request. Use Content-Type and Content-Length headers to specify the nature
//! of the body payload.
//! @param callback The callback method to receive the JSON response object.
virtual void AddRequestWithHeadersAndBody(
const AZStd::string& URI,
Aws::Http::HttpMethod method,
const Headers& headers,
const AZStd::string& body,
const Callback& callback) = 0;
//! Make a RESTful call to a HTTP(s) endpoint. Receive the response, via the supplied callback as text.
//! @param URI The universal resource indicator representing the endpoint to make the request to.
//! @param method The http method to use, for example HTTP_GET.
//! @param callback The callback method to receive the JSON response object.
virtual void AddTextRequest(const AZStd::string& URI, Aws::Http::HttpMethod method, const TextCallback& callback) = 0;
virtual void AddTextRequestWithHeaders(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers & headers, const TextCallback& callback) = 0;
virtual void AddTextRequestWithHeadersAndBody(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers & headers, const AZStd::string& body, const TextCallback& callback) = 0;
//! Make a RESTful call to a HTTP(s) endpoint with customized headers. Receive the response, via the supplied callback as text.
//! @param URI The universal resource indicator representing the endpoint to make the request to.
//! @param method The HTTP method to use, for example HTTP_GET.
//! @param headers A map of header names and values to set on the request.
//! @param callback The callback method to receive the JSON response object.
virtual void AddTextRequestWithHeaders(
const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const TextCallback& callback) = 0;
//! Make a RESTful call to a HTTP(s) endpoint with customized headers and a body. Receive the response, via the supplied callback as text.
//! @param URI The universal resource indicator representing the endpoint to make the request to.
//! @param method The HTTP method to use, for example HTTP_POST.
//! @param headers A map of header names and values to set on the request.
//! @param body Any HTTP request data to include in the request. Use Content-Type and Content-Length headers to specify the nature of the body payload.
//! @param callback The callback method to receive the JSON response object.
virtual void AddTextRequestWithHeadersAndBody(
const AZStd::string& URI,
Aws::Http::HttpMethod method,
const Headers& headers,
const AZStd::string& body,
const TextCallback& callback) = 0;
};
using HttpRequestorRequestBus = AZ::EBus<HttpRequestorRequests>;
} // namespace HttpRequestor
} // namespace HttpRequestor
@@ -11,20 +11,35 @@
namespace HttpRequestor
{
/*
**
** The Parameters needed to make a HTTP call and then receive the
** returned TEXT from the web request without parsing it.
**
*/
//! Models the parameters needed to make a HTTP call and then receive the
//! returned TEXT from the web request without parsing it.
class TextParameters
{
public:
// Initializing ctor
//! @param URI A universal resource indicator representing an endpoint.
//! @param method The HTTP method to configure.
//! @param callback The callback method to receive a HTTP call's response.
TextParameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const TextCallback& callback);
//! @param URI A universal resource indicator representing an endpoint.
//! @param method The HTTP method to configure.
//! @param headers A map of header names and values to use.
//! @param callback The callback method to receive a HTTP call's response.
TextParameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const TextCallback& callback);
TextParameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const AZStd::string& body, const TextCallback& callback);
//! @param URI A universal resource indicator representing an endpoint.
//! @param method The HTTP method to configure.
//! @param headers A map of header names and values to use.
//! @param body An data to associate with an HTTP call.
//! @param callback The callback method to receive a HTTP call's response.
TextParameters(
const AZStd::string& URI,
Aws::Http::HttpMethod method,
const Headers& headers,
const AZStd::string& body,
const TextCallback& callback);
// Defaults
~TextParameters() = default;
@@ -34,29 +49,49 @@ namespace HttpRequestor
TextParameters(TextParameters&&) = default;
TextParameters& operator=(TextParameters&&) = default;
//returns the URI in string form as an recipient of the HTTP connection
const Aws::String& GetURI() const { return m_URI; }
//! Get the URI in string form as an recipient of the HTTP connection.
const Aws::String& GetURI() const
{
return m_URI;
}
//returns the method of which the HTTP request will take. GET, POST, DELETE, PUT, or HEAD
Aws::Http::HttpMethod GetMethod() const { return m_method; }
//! Get the HTTP method configured to use for a request.
Aws::Http::HttpMethod GetMethod() const
{
return m_method;
}
//returns the list of extra headers to include in the request
const Headers & GetHeaders() const { return m_headers; }
//! Get the list of extra headers to send as part of a request.
//! @return A map of header-value pairs.
const Headers& GetHeaders() const
{
return m_headers;
}
//returns the stream for the body of the request
const std::shared_ptr<std::stringstream> & GetBodyStream() const { return m_bodyStream; }
//! Get an input stream that can be used to send the body of a request.
//! @return A string stream representing a request body.
const std::shared_ptr<std::stringstream>& GetBodyStream() const
{
return m_bodyStream;
}
//returns the function of which to feed back the TEXT that the HTTP call resulted in. The function also requires the HTTPResponseCode indicating if the call was successful or failed
const TextCallback & GetCallback() const { return m_callback; }
//! Get the callback function for processing text returned in an HTTP response.
//! Callback functions are responsible for correctly interpreting the HTTP response code, and should communicate any
//! failures.
//! @return The callback function to process endpoint responses with.
const TextCallback& GetCallback() const
{
return m_callback;
}
private:
Aws::String m_URI;
Aws::Http::HttpMethod m_method;
Headers m_headers;
std::shared_ptr<std::stringstream> m_bodyStream;
TextCallback m_callback;
Aws::String m_URI;
Aws::Http::HttpMethod m_method;
Headers m_headers;
std::shared_ptr<std::stringstream> m_bodyStream;
TextCallback m_callback;
};
inline TextParameters::TextParameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const TextCallback& callback)
: m_URI(URI.c_str())
, m_method(method)
@@ -64,7 +99,8 @@ namespace HttpRequestor
{
}
inline TextParameters::TextParameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const TextCallback& callback)
inline TextParameters::TextParameters(
const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const TextCallback& callback)
: m_URI(URI.c_str())
, m_method(method)
, m_headers(headers)
@@ -72,12 +108,17 @@ namespace HttpRequestor
{
}
inline TextParameters::TextParameters(const AZStd::string& URI, Aws::Http::HttpMethod method, const Headers& headers, const AZStd::string& body, const TextCallback& callback)
inline TextParameters::TextParameters(
const AZStd::string& URI,
Aws::Http::HttpMethod method,
const Headers& headers,
const AZStd::string& body,
const TextCallback& callback)
: m_URI(URI.c_str())
, m_method(method)
, m_headers(headers)
, m_bodyStream( std::make_shared<std::stringstream>(body.c_str()) )
, m_bodyStream(std::make_shared<std::stringstream>(body.c_str()))
, m_callback(callback)
{
}
}
} // namespace HttpRequestor
@@ -23,20 +23,16 @@ AZ_POP_DISABLE_WARNING
namespace HttpRequestor
{
//
// the call back function for http requests.
//
// A callback function for processing JSON return values from an HTTP request. This callback is responsible for correctly interpreting
// the HTTP response code and setting any internal information from the returned JSON object.
using Callback = AZStd::function<void(const Aws::Utils::Json::JsonView&, Aws::Http::HttpResponseCode)>;
//
// the call back function for any http text requests.
//
// A callback function for processing HTTP response as raw text. This callback is responsible for correctly interpreting the HTTP
// response code and setting any internal information from the returned data. If the data includes a JSON fragment, the callback is
// responsible for parsing it.
using TextCallback = AZStd::function<void(const AZStd::string&, Aws::Http::HttpResponseCode)>;
//
// a map of REST headers.
//
// A map of REST headers.
using Headers = AZStd::map<AZStd::string, AZStd::string>;
}
} // namespace HttpRequestor

Some files were not shown because too many files have changed in this diff Show More