diff options
| author | Egor Yusov <egor.yusov@gmail.com> | 2019-10-27 20:43:14 +0000 |
|---|---|---|
| committer | Egor Yusov <egor.yusov@gmail.com> | 2019-10-27 20:43:14 +0000 |
| commit | 7af12d4c1e5429a21e560dc15d516e2a6319a5af (patch) | |
| tree | 79e9732c27a2380b303545ed2986e5b4fb4910e4 /Common/NativeApp/src | |
| parent | Updated core (diff) | |
| download | DiligentEngine-7af12d4c1e5429a21e560dc15d516e2a6319a5af.tar.gz DiligentEngine-7af12d4c1e5429a21e560dc15d516e2a6319a5af.zip | |
Fixed tabs in UWP app source
Diffstat (limited to 'Common/NativeApp/src')
| -rw-r--r-- | Common/NativeApp/src/UWP/App.cpp | 198 | ||||
| -rw-r--r-- | Common/NativeApp/src/UWP/App.h | 58 | ||||
| -rw-r--r-- | Common/NativeApp/src/UWP/Common/DeviceResources.cpp | 364 | ||||
| -rw-r--r-- | Common/NativeApp/src/UWP/Common/DeviceResources.h | 78 | ||||
| -rw-r--r-- | Common/NativeApp/src/UWP/Common/DirectXHelper.h | 88 | ||||
| -rw-r--r-- | Common/NativeApp/src/UWP/Common/StepTimer.h | 352 |
6 files changed, 569 insertions, 569 deletions
diff --git a/Common/NativeApp/src/UWP/App.cpp b/Common/NativeApp/src/UWP/App.cpp index a36fe49..0c928eb 100644 --- a/Common/NativeApp/src/UWP/App.cpp +++ b/Common/NativeApp/src/UWP/App.cpp @@ -66,14 +66,14 @@ public: [Platform::MTAThread] int main(Platform::Array<Platform::String^>^) { - auto direct3DApplicationSource = ref new ApplicationSource(); - CoreApplication::Run(direct3DApplicationSource); - return 0; + auto direct3DApplicationSource = ref new ApplicationSource(); + CoreApplication::Run(direct3DApplicationSource); + return 0; } App::App() : - m_windowClosed(false), - m_windowVisible(true) + m_windowClosed(false), + m_windowVisible(true) { } @@ -81,29 +81,29 @@ App::App() : // The first method called when the IFrameworkView is being created. void App::Initialize(CoreApplicationView^ applicationView) { - // Register event handlers for app lifecycle. This example includes Activated, so that we - // can make the CoreWindow active and start rendering on the window. - applicationView->Activated += - ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated); + // Register event handlers for app lifecycle. This example includes Activated, so that we + // can make the CoreWindow active and start rendering on the window. + applicationView->Activated += + ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated); - CoreApplication::Suspending += - ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending); + CoreApplication::Suspending += + ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending); - CoreApplication::Resuming += - ref new EventHandler<Platform::Object^>(this, &App::OnResuming); + CoreApplication::Resuming += + ref new EventHandler<Platform::Object^>(this, &App::OnResuming); } // Called when the CoreWindow object is created (or re-created). void App::SetWindow(CoreWindow^ window) { - window->SizeChanged += - ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged); + window->SizeChanged += + ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged); - window->VisibilityChanged += - ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged); + window->VisibilityChanged += + ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged); - window->Closed += - ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed); + window->Closed += + ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed); window->KeyDown += ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyDown); @@ -111,16 +111,16 @@ void App::SetWindow(CoreWindow^ window) window->KeyUp += ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyUp); - DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); - currentDisplayInformation->DpiChanged += - ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged); + currentDisplayInformation->DpiChanged += + ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged); - currentDisplayInformation->OrientationChanged += - ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged); + currentDisplayInformation->OrientationChanged += + ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged); - DisplayInformation::DisplayContentsInvalidated += - ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated); + DisplayInformation::DisplayContentsInvalidated += + ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated); if (m_Main) { @@ -131,46 +131,46 @@ void App::SetWindow(CoreWindow^ window) // Initializes scene resources, or loads a previously saved app state. void App::Load(Platform::String^ entryPoint) { - if (m_Main == nullptr) - { + if (m_Main == nullptr) + { m_Main.reset(CreateApplication()); m_Main->OnSetWindow(CoreWindow::GetForCurrentThread()); - } + } } // This method is called after the window becomes active. void App::Run() { - while (!m_windowClosed) - { - if (m_windowVisible) - { - CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); + while (!m_windowClosed) + { + if (m_windowVisible) + { + CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); // Initialize device resources GetDeviceResources(); - //PIXBeginEvent(commandQueue, 0, L"Update"); - { - m_Main->Update(); - } - //PIXEndEvent(commandQueue); + //PIXBeginEvent(commandQueue, 0, L"Update"); + { + m_Main->Update(); + } + //PIXEndEvent(commandQueue); - //PIXBeginEvent(commandQueue, 0, L"Render"); - { + //PIXBeginEvent(commandQueue, 0, L"Render"); + { m_Main->Render(); - if (m_Main->IsFrameReady()) - { + if (m_Main->IsFrameReady()) + { m_Main->Present(); - } - } - //PIXEndEvent(commandQueue); - } - else - { - CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending); - } - } + } + } + //PIXEndEvent(commandQueue); + } + else + { + CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending); + } + } } // Required for IFrameworkView. @@ -200,26 +200,26 @@ void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args) { - // Save app state asynchronously after requesting a deferral. Holding a deferral - // indicates that the application is busy performing suspending operations. Be - // aware that a deferral may not be held indefinitely. After about five seconds, - // the app will be forced to exit. - SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); - - create_task([this, deferral]() - { - m_Main->OnSuspending(); - deferral->Complete(); - }); + // Save app state asynchronously after requesting a deferral. Holding a deferral + // indicates that the application is busy performing suspending operations. Be + // aware that a deferral may not be held indefinitely. After about five seconds, + // the app will be forced to exit. + SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); + + create_task([this, deferral]() + { + m_Main->OnSuspending(); + deferral->Complete(); + }); } void App::OnResuming(Platform::Object^ sender, Platform::Object^ args) { - // Restore any data or state that was unloaded on suspend. By default, data - // and state are persisted when resuming from suspend. Note that this event - // does not occur if the app was previously terminated. + // Restore any data or state that was unloaded on suspend. By default, data + // and state are persisted when resuming from suspend. Note that this event + // does not occur if the app was previously terminated. - m_Main->OnResuming(); + m_Main->OnResuming(); } // Window event handlers. @@ -228,33 +228,33 @@ void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ ar { if (auto DeviceResources = GetDeviceResources()) { - DeviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height)); - m_Main->OnWindowSizeChanged(); + DeviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height)); + m_Main->OnWindowSizeChanged(); } } void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args) { - m_windowVisible = args->Visible; + m_windowVisible = args->Visible; } void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args) { - m_windowClosed = true; + m_windowClosed = true; } // DisplayInformation event handlers. void App::OnDpiChanged(DisplayInformation^ sender, Object^ args) { - // Note: The value for LogicalDpi retrieved here may not match the effective DPI of the app - // if it is being scaled for high resolution devices. Once the DPI is set on DeviceResources, - // you should always retrieve it using the GetDpi method. - // See DeviceResources.cpp for more details. + // Note: The value for LogicalDpi retrieved here may not match the effective DPI of the app + // if it is being scaled for high resolution devices. Once the DPI is set on DeviceResources, + // you should always retrieve it using the GetDpi method. + // See DeviceResources.cpp for more details. if (auto DeviceResources = GetDeviceResources()) { - DeviceResources->SetDpi(sender->LogicalDpi); - m_Main->OnWindowSizeChanged(); + DeviceResources->SetDpi(sender->LogicalDpi); + m_Main->OnWindowSizeChanged(); } } @@ -262,8 +262,8 @@ void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args) { if (auto DeviceResources = GetDeviceResources()) { - DeviceResources->SetCurrentOrientation(sender->CurrentOrientation); - m_Main->OnWindowSizeChanged(); + DeviceResources->SetCurrentOrientation(sender->CurrentOrientation); + m_Main->OnWindowSizeChanged(); } } @@ -271,7 +271,7 @@ void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args) { if (auto DeviceResources = GetDeviceResources()) { - DeviceResources->ValidateDevice(); + DeviceResources->ValidateDevice(); } } @@ -318,34 +318,34 @@ void App::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyE std::shared_ptr<DX::DeviceResources> App::GetDeviceResources() { - if (m_deviceResources != nullptr && m_deviceResources->IsDeviceRemoved()) - { - // All references to the existing D3D device must be released before a new device - // can be created. + if (m_deviceResources != nullptr && m_deviceResources->IsDeviceRemoved()) + { + // All references to the existing D3D device must be released before a new device + // can be created. - m_deviceResources = nullptr; - m_Main->OnDeviceRemoved(); + m_deviceResources = nullptr; + m_Main->OnDeviceRemoved(); #if defined(_DEBUG) - ComPtr<IDXGIDebug1> dxgiDebug; - if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&dxgiDebug)))) - { - dxgiDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_FLAGS(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_IGNORE_INTERNAL)); - } + ComPtr<IDXGIDebug1> dxgiDebug; + if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&dxgiDebug)))) + { + dxgiDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_FLAGS(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_IGNORE_INTERNAL)); + } #endif - } + } - if (m_deviceResources == nullptr) - { - m_deviceResources = m_Main->InitDeviceResources(); + if (m_deviceResources == nullptr) + { + m_deviceResources = m_Main->InitDeviceResources(); if (m_deviceResources) { - m_deviceResources->SetWindow(CoreWindow::GetForCurrentThread()); + m_deviceResources->SetWindow(CoreWindow::GetForCurrentThread()); auto Title = Diligent::WidenString(m_Main->GetAppTitle()); Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Title = ref new Platform::String(Title.c_str()); m_Main->OnWindowSizeChanged(); - m_Main->CreateRenderers(); + m_Main->CreateRenderers(); } - } - return m_deviceResources; + } + return m_deviceResources; } diff --git a/Common/NativeApp/src/UWP/App.h b/Common/NativeApp/src/UWP/App.h index 6b3fea2..4f31f07 100644 --- a/Common/NativeApp/src/UWP/App.h +++ b/Common/NativeApp/src/UWP/App.h @@ -28,44 +28,44 @@ namespace SampleApp { - // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events. - ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView - { - public: - App(); + // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events. + ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView + { + public: + App(); - // IFrameworkView methods. - virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView); - virtual void SetWindow(Windows::UI::Core::CoreWindow^ window); - virtual void Load(Platform::String^ entryPoint); - virtual void Run(); - virtual void Uninitialize(); + // IFrameworkView methods. + virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView); + virtual void SetWindow(Windows::UI::Core::CoreWindow^ window); + virtual void Load(Platform::String^ entryPoint); + virtual void Run(); + virtual void Uninitialize(); - protected: - // Application lifecycle event handlers. - void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args); - void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args); - void OnResuming(Platform::Object^ sender, Platform::Object^ args); + protected: + // Application lifecycle event handlers. + void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args); + void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args); + void OnResuming(Platform::Object^ sender, Platform::Object^ args); - // Window event handlers. - void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args); - void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args); - void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args); + // Window event handlers. + void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args); + void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args); + void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args); - // DisplayInformation event handlers. - void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); - void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); - void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + // DisplayInformation event handlers. + void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); void OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args); void OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args); - private: + private: std::shared_ptr<DX::DeviceResources> GetDeviceResources(); std::unique_ptr<Diligent::NativeAppBase> m_Main; - std::shared_ptr<DX::DeviceResources> m_deviceResources; - bool m_windowClosed = false; - bool m_windowVisible = false; + std::shared_ptr<DX::DeviceResources> m_deviceResources; + bool m_windowClosed = false; + bool m_windowVisible = false; bool m_bShiftPressed = false; - }; + }; } diff --git a/Common/NativeApp/src/UWP/Common/DeviceResources.cpp b/Common/NativeApp/src/UWP/Common/DeviceResources.cpp index b6ea12d..c111a54 100644 --- a/Common/NativeApp/src/UWP/Common/DeviceResources.cpp +++ b/Common/NativeApp/src/UWP/Common/DeviceResources.cpp @@ -28,66 +28,66 @@ using namespace Platform; namespace DisplayMetrics { - // High resolution displays can require a lot of GPU and battery power to render. - // High resolution phones, for example, may suffer from poor battery life if - // games attempt to render at 60 frames per second at full fidelity. - // The decision to render at full fidelity across all platforms and form factors - // should be deliberate. - static const bool SupportHighResolutions = false; - - // The default thresholds that define a "high resolution" display. If the thresholds - // are exceeded and SupportHighResolutions is false, the dimensions will be scaled - // by 50%. - static const float DpiThreshold = 192.0f; // 200% of standard desktop display. - static const float WidthThreshold = 1920.0f; // 1080p width. - static const float HeightThreshold = 1080.0f; // 1080p height. + // High resolution displays can require a lot of GPU and battery power to render. + // High resolution phones, for example, may suffer from poor battery life if + // games attempt to render at 60 frames per second at full fidelity. + // The decision to render at full fidelity across all platforms and form factors + // should be deliberate. + static const bool SupportHighResolutions = false; + + // The default thresholds that define a "high resolution" display. If the thresholds + // are exceeded and SupportHighResolutions is false, the dimensions will be scaled + // by 50%. + static const float DpiThreshold = 192.0f; // 200% of standard desktop display. + static const float WidthThreshold = 1920.0f; // 1080p width. + static const float HeightThreshold = 1080.0f; // 1080p height. }; // Constants used to calculate screen rotations. namespace ScreenRotation { - // 0-degree Z-rotation - static const XMFLOAT4X4 Rotation0( - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - - // 90-degree Z-rotation - static const XMFLOAT4X4 Rotation90( - 0.0f, 1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - - // 180-degree Z-rotation - static const XMFLOAT4X4 Rotation180( - -1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, -1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); - - // 270-degree Z-rotation - static const XMFLOAT4X4 Rotation270( - 0.0f, -1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); + // 0-degree Z-rotation + static const XMFLOAT4X4 Rotation0( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 90-degree Z-rotation + static const XMFLOAT4X4 Rotation90( + 0.0f, 1.0f, 0.0f, 0.0f, + -1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 180-degree Z-rotation + static const XMFLOAT4X4 Rotation180( + -1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 270-degree Z-rotation + static const XMFLOAT4X4 Rotation270( + 0.0f, -1.0f, 0.0f, 0.0f, + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); }; // Constructor for DeviceResources. DX::DeviceResources::DeviceResources(ID3D11Device *d3d11Device, ID3D12Device *d3d12Device) : - m_d3dRenderTargetSize(), - m_outputSize(), - m_logicalSize(), - m_nativeOrientation(DisplayOrientations::None), - m_currentOrientation(DisplayOrientations::None), - m_dpi(-1.0f), - m_deviceRemoved(false), + m_d3dRenderTargetSize(), + m_outputSize(), + m_logicalSize(), + m_nativeOrientation(DisplayOrientations::None), + m_currentOrientation(DisplayOrientations::None), + m_dpi(-1.0f), + m_deviceRemoved(false), m_d3d11Device(d3d11Device), m_d3d12Device(d3d12Device) { @@ -130,32 +130,32 @@ void DX::DeviceResources::SetSwapChainRotation(IDXGISwapChain3 *swapChain) // Determine the dimensions of the render target and whether it will be scaled down. void DX::DeviceResources::UpdateRenderTargetSize() { - m_effectiveDpi = m_dpi; - - // To improve battery life on high resolution devices, render to a smaller render target - // and allow the GPU to scale the output when it is presented. - if (!DisplayMetrics::SupportHighResolutions && m_dpi > DisplayMetrics::DpiThreshold) - { - float width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi); - float height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi); - - // When the device is in portrait orientation, height > width. Compare the - // larger dimension against the width threshold and the smaller dimension - // against the height threshold. - if (max(width, height) > DisplayMetrics::WidthThreshold && min(width, height) > DisplayMetrics::HeightThreshold) - { - // To scale the app we change the effective DPI. Logical size does not change. - m_effectiveDpi /= 2.0f; - } - } - - // Calculate the necessary render target size in pixels. - m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_effectiveDpi); - m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_effectiveDpi); - - // Prevent zero size DirectX content from being created. - m_outputSize.Width = max(m_outputSize.Width, 1); - m_outputSize.Height = max(m_outputSize.Height, 1); + m_effectiveDpi = m_dpi; + + // To improve battery life on high resolution devices, render to a smaller render target + // and allow the GPU to scale the output when it is presented. + if (!DisplayMetrics::SupportHighResolutions && m_dpi > DisplayMetrics::DpiThreshold) + { + float width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi); + float height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi); + + // When the device is in portrait orientation, height > width. Compare the + // larger dimension against the width threshold and the smaller dimension + // against the height threshold. + if (max(width, height) > DisplayMetrics::WidthThreshold && min(width, height) > DisplayMetrics::HeightThreshold) + { + // To scale the app we change the effective DPI. Logical size does not change. + m_effectiveDpi /= 2.0f; + } + } + + // Calculate the necessary render target size in pixels. + m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_effectiveDpi); + m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_effectiveDpi); + + // Prevent zero size DirectX content from being created. + m_outputSize.Width = max(m_outputSize.Width, 1); + m_outputSize.Height = max(m_outputSize.Height, 1); // The width and height of the swap chain must be based on the window's @@ -174,155 +174,155 @@ void DX::DeviceResources::UpdateRenderTargetSize() // This method is called when the CoreWindow is created (or re-created). void DX::DeviceResources::SetWindow(CoreWindow^ window) { - DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); - m_window = window; - m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height); - m_nativeOrientation = currentDisplayInformation->NativeOrientation; - m_currentOrientation = currentDisplayInformation->CurrentOrientation; - m_dpi = currentDisplayInformation->LogicalDpi; + m_window = window; + m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height); + m_nativeOrientation = currentDisplayInformation->NativeOrientation; + m_currentOrientation = currentDisplayInformation->CurrentOrientation; + m_dpi = currentDisplayInformation->LogicalDpi; - //CreateWindowSizeDependentResources(); + //CreateWindowSizeDependentResources(); } // This method is called in the event handler for the SizeChanged event. void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize) { - if (m_logicalSize != logicalSize) - { - m_logicalSize = logicalSize; - //CreateWindowSizeDependentResources(); - } + if (m_logicalSize != logicalSize) + { + m_logicalSize = logicalSize; + //CreateWindowSizeDependentResources(); + } } // This method is called in the event handler for the DpiChanged event. void DX::DeviceResources::SetDpi(float dpi) { - if (dpi != m_dpi) - { - m_dpi = dpi; + if (dpi != m_dpi) + { + m_dpi = dpi; - // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated. - m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height); + // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated. + m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height); - //CreateWindowSizeDependentResources(); - } + //CreateWindowSizeDependentResources(); + } } // This method is called in the event handler for the OrientationChanged event. void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation) { - if (m_currentOrientation != currentOrientation) - { - m_currentOrientation = currentOrientation; - //CreateWindowSizeDependentResources(); - } + if (m_currentOrientation != currentOrientation) + { + m_currentOrientation = currentOrientation; + //CreateWindowSizeDependentResources(); + } } // This method is called in the event handler for the DisplayContentsInvalidated event. void DX::DeviceResources::ValidateDevice() { - // The D3D Device is no longer valid if the default adapter changed since the device - // was created or if the device has been removed. + // The D3D Device is no longer valid if the default adapter changed since the device + // was created or if the device has been removed. - ComPtr<IDXGIDevice3> dxgiDevice; + ComPtr<IDXGIDevice3> dxgiDevice; if(m_d3d11Device) - DX::ThrowIfFailed(m_d3d11Device.As(&dxgiDevice)); + DX::ThrowIfFailed(m_d3d11Device.As(&dxgiDevice)); else if(m_d3d12Device) DX::ThrowIfFailed(m_d3d12Device.As(&dxgiDevice)); - ComPtr<IDXGIAdapter> deviceAdapter; - DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter)); + ComPtr<IDXGIAdapter> deviceAdapter; + DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter)); - ComPtr<IDXGIFactory2> deviceFactory; - DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory))); + ComPtr<IDXGIFactory2> deviceFactory; + DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory))); - // First, get the LUID for the default adapter from when the device was created. + // First, get the LUID for the default adapter from when the device was created. - DXGI_ADAPTER_DESC previousDesc; - { - ComPtr<IDXGIAdapter1> previousDefaultAdapter; - DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter)); + DXGI_ADAPTER_DESC previousDesc; + { + ComPtr<IDXGIAdapter1> previousDefaultAdapter; + DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter)); - DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc)); - } + DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc)); + } - // Next, get the information for the current default adapter. + // Next, get the information for the current default adapter. - DXGI_ADAPTER_DESC currentDesc; - { - ComPtr<IDXGIFactory4> currentDxgiFactory; - DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(¤tDxgiFactory))); + DXGI_ADAPTER_DESC currentDesc; + { + ComPtr<IDXGIFactory4> currentDxgiFactory; + DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(¤tDxgiFactory))); - ComPtr<IDXGIAdapter1> currentDefaultAdapter; - DX::ThrowIfFailed(currentDxgiFactory->EnumAdapters1(0, ¤tDefaultAdapter)); + ComPtr<IDXGIAdapter1> currentDefaultAdapter; + DX::ThrowIfFailed(currentDxgiFactory->EnumAdapters1(0, ¤tDefaultAdapter)); - DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(¤tDesc)); - } + DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(¤tDesc)); + } - // If the adapter LUIDs don't match, or if the device reports that it has been removed, - // a new D3D device must be created. + // If the adapter LUIDs don't match, or if the device reports that it has been removed, + // a new D3D device must be created. - if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart || - previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart || - m_d3d11Device && FAILED(m_d3d11Device->GetDeviceRemovedReason()) || + if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart || + previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart || + m_d3d11Device && FAILED(m_d3d11Device->GetDeviceRemovedReason()) || m_d3d12Device && FAILED(m_d3d12Device->GetDeviceRemovedReason())) - { - m_deviceRemoved = true; - } + { + m_deviceRemoved = true; + } } // This method determines the rotation between the display device's native Orientation and the // current display orientation. DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation() { - DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; - - // Note: NativeOrientation can only be Landscape or Portrait even though - // the DisplayOrientations enum has other values. - switch (m_nativeOrientation) - { - case DisplayOrientations::Landscape: - switch (m_currentOrientation) - { - case DisplayOrientations::Landscape: - rotation = DXGI_MODE_ROTATION_IDENTITY; - break; - - case DisplayOrientations::Portrait: - rotation = DXGI_MODE_ROTATION_ROTATE270; - break; - - case DisplayOrientations::LandscapeFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE180; - break; - - case DisplayOrientations::PortraitFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE90; - break; - } - break; - - case DisplayOrientations::Portrait: - switch (m_currentOrientation) - { - case DisplayOrientations::Landscape: - rotation = DXGI_MODE_ROTATION_ROTATE90; - break; - - case DisplayOrientations::Portrait: - rotation = DXGI_MODE_ROTATION_IDENTITY; - break; - - case DisplayOrientations::LandscapeFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE270; - break; - - case DisplayOrientations::PortraitFlipped: - rotation = DXGI_MODE_ROTATION_ROTATE180; - break; - } - break; - } - return rotation; + DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; + + // Note: NativeOrientation can only be Landscape or Portrait even though + // the DisplayOrientations enum has other values. + switch (m_nativeOrientation) + { + case DisplayOrientations::Landscape: + switch (m_currentOrientation) + { + case DisplayOrientations::Landscape: + rotation = DXGI_MODE_ROTATION_IDENTITY; + break; + + case DisplayOrientations::Portrait: + rotation = DXGI_MODE_ROTATION_ROTATE270; + break; + + case DisplayOrientations::LandscapeFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE180; + break; + + case DisplayOrientations::PortraitFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE90; + break; + } + break; + + case DisplayOrientations::Portrait: + switch (m_currentOrientation) + { + case DisplayOrientations::Landscape: + rotation = DXGI_MODE_ROTATION_ROTATE90; + break; + + case DisplayOrientations::Portrait: + rotation = DXGI_MODE_ROTATION_IDENTITY; + break; + + case DisplayOrientations::LandscapeFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE270; + break; + + case DisplayOrientations::PortraitFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE180; + break; + } + break; + } + return rotation; } diff --git a/Common/NativeApp/src/UWP/Common/DeviceResources.h b/Common/NativeApp/src/UWP/Common/DeviceResources.h index 403d118..69fa00c 100644 --- a/Common/NativeApp/src/UWP/Common/DeviceResources.h +++ b/Common/NativeApp/src/UWP/Common/DeviceResources.h @@ -8,30 +8,30 @@ namespace DX { - // Controls all the DirectX device resources. - class DeviceResources - { - public: - DeviceResources(ID3D11Device *d3d11Device, ID3D12Device *d3d12Device); + // Controls all the DirectX device resources. + class DeviceResources + { + public: + DeviceResources(ID3D11Device *d3d11Device, ID3D12Device *d3d12Device); - void SetWindow(Windows::UI::Core::CoreWindow^ window); - void SetLogicalSize(Windows::Foundation::Size logicalSize); - void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation); - void SetDpi(float dpi); - void ValidateDevice(); + void SetWindow(Windows::UI::Core::CoreWindow^ window); + void SetLogicalSize(Windows::Foundation::Size logicalSize); + void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation); + void SetDpi(float dpi); + void ValidateDevice(); void SetSwapChainRotation(IDXGISwapChain3 *swapChain); - // The size of the render target, in pixels. - Windows::Foundation::Size GetOutputSize() const { return m_outputSize; } + // The size of the render target, in pixels. + Windows::Foundation::Size GetOutputSize() const { return m_outputSize; } - // The size of the render target, in dips. - Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; } + // The size of the render target, in dips. + Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; } - float GetDpi() const { return m_effectiveDpi; } - bool IsDeviceRemoved() const { return m_deviceRemoved; } + float GetDpi() const { return m_effectiveDpi; } + bool IsDeviceRemoved() const { return m_deviceRemoved; } - // D3D Accessors. - DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; } + // D3D Accessors. + DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; } void UpdateRenderTargetSize(); UINT GetBackBufferWidth() {return m_backBufferWidth;} @@ -39,34 +39,34 @@ namespace DX Windows::UI::Core::CoreWindow^ GetWindow(){return m_window.Get();} - private: - - - DXGI_MODE_ROTATION ComputeDisplayRotation(); + private: + + + DXGI_MODE_ROTATION ComputeDisplayRotation(); bool m_deviceRemoved; - // Direct3D objects. - Microsoft::WRL::ComPtr<ID3D12Device> m_d3d12Device; + // Direct3D objects. + Microsoft::WRL::ComPtr<ID3D12Device> m_d3d12Device; Microsoft::WRL::ComPtr<ID3D11Device> m_d3d11Device; - - // Cached reference to the Window. - Platform::Agile<Windows::UI::Core::CoreWindow> m_window; + + // Cached reference to the Window. + Platform::Agile<Windows::UI::Core::CoreWindow> m_window; - // Cached device properties. - Windows::Foundation::Size m_d3dRenderTargetSize; - Windows::Foundation::Size m_outputSize; - Windows::Foundation::Size m_logicalSize; - Windows::Graphics::Display::DisplayOrientations m_nativeOrientation; - Windows::Graphics::Display::DisplayOrientations m_currentOrientation; - float m_dpi; + // Cached device properties. + Windows::Foundation::Size m_d3dRenderTargetSize; + Windows::Foundation::Size m_outputSize; + Windows::Foundation::Size m_logicalSize; + Windows::Graphics::Display::DisplayOrientations m_nativeOrientation; + Windows::Graphics::Display::DisplayOrientations m_currentOrientation; + float m_dpi; UINT m_backBufferWidth = 0; UINT m_backBufferHeight = 0; - // This is the DPI that will be reported back to the app. It takes into account whether the app supports high resolution screens or not. - float m_effectiveDpi; + // This is the DPI that will be reported back to the app. It takes into account whether the app supports high resolution screens or not. + float m_effectiveDpi; - // Transforms used for display orientation. - DirectX::XMFLOAT4X4 m_orientationTransform3D; - }; + // Transforms used for display orientation. + DirectX::XMFLOAT4X4 m_orientationTransform3D; + }; } diff --git a/Common/NativeApp/src/UWP/Common/DirectXHelper.h b/Common/NativeApp/src/UWP/Common/DirectXHelper.h index 958b355..7bfe36f 100644 --- a/Common/NativeApp/src/UWP/Common/DirectXHelper.h +++ b/Common/NativeApp/src/UWP/Common/DirectXHelper.h @@ -4,52 +4,52 @@ namespace DX { - inline void ThrowIfFailed(HRESULT hr) - { - if (FAILED(hr)) - { - // Set a breakpoint on this line to catch Win32 API errors. - throw Platform::Exception::CreateException(hr); - } - } - - // Function that reads from a binary file asynchronously. - inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename) - { - using namespace Windows::Storage; - using namespace Concurrency; - - auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation; - - return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([](StorageFile^ file) - { - return FileIO::ReadBufferAsync(file); - }).then([](Streams::IBuffer^ fileBuffer) -> std::vector<byte> - { - std::vector<byte> returnBuffer; - returnBuffer.resize(fileBuffer->Length); - Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length)); - return returnBuffer; - }); - } - - // Converts a length in device-independent pixels (DIPs) to a length in physical pixels. - inline float ConvertDipsToPixels(float dips, float dpi) - { - static const float dipsPerInch = 96.0f; - return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer. - } - - // Assign a name to the object to aid with debugging. + inline void ThrowIfFailed(HRESULT hr) + { + if (FAILED(hr)) + { + // Set a breakpoint on this line to catch Win32 API errors. + throw Platform::Exception::CreateException(hr); + } + } + + // Function that reads from a binary file asynchronously. + inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename) + { + using namespace Windows::Storage; + using namespace Concurrency; + + auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation; + + return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([](StorageFile^ file) + { + return FileIO::ReadBufferAsync(file); + }).then([](Streams::IBuffer^ fileBuffer) -> std::vector<byte> + { + std::vector<byte> returnBuffer; + returnBuffer.resize(fileBuffer->Length); + Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length)); + return returnBuffer; + }); + } + + // Converts a length in device-independent pixels (DIPs) to a length in physical pixels. + inline float ConvertDipsToPixels(float dips, float dpi) + { + static const float dipsPerInch = 96.0f; + return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer. + } + + // Assign a name to the object to aid with debugging. #if defined(_DEBUG) - inline void SetName(ID3D12Object* pObject, LPCWSTR name) - { - pObject->SetName(name); - } + inline void SetName(ID3D12Object* pObject, LPCWSTR name) + { + pObject->SetName(name); + } #else - inline void SetName(ID3D12Object*, LPCWSTR) - { - } + inline void SetName(ID3D12Object*, LPCWSTR) + { + } #endif } diff --git a/Common/NativeApp/src/UWP/Common/StepTimer.h b/Common/NativeApp/src/UWP/Common/StepTimer.h index 286710c..c8addbc 100644 --- a/Common/NativeApp/src/UWP/Common/StepTimer.h +++ b/Common/NativeApp/src/UWP/Common/StepTimer.h @@ -4,180 +4,180 @@ namespace DX { - // Helper class for animation and simulation timing. - class StepTimer - { - public: - StepTimer() : - m_elapsedTicks(0), - m_totalTicks(0), - m_leftOverTicks(0), - m_frameCount(0), - m_framesPerSecond(0), - m_framesThisSecond(0), - m_qpcSecondCounter(0), - m_isFixedTimeStep(false), - m_targetElapsedTicks(TicksPerSecond / 60) - { - if (!QueryPerformanceFrequency(&m_qpcFrequency)) - { - throw ref new Platform::FailureException(); - } - - if (!QueryPerformanceCounter(&m_qpcLastTime)) - { - throw ref new Platform::FailureException(); - } - - // Initialize max delta to 1/10 of a second. - m_qpcMaxDelta = m_qpcFrequency.QuadPart / 10; - } - - // Get elapsed time since the previous Update call. - uint64 GetElapsedTicks() const { return m_elapsedTicks; } - double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); } - - // Get total time since the start of the program. - uint64 GetTotalTicks() const { return m_totalTicks; } - double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); } - - // Get total number of updates since start of the program. - uint32 GetFrameCount() const { return m_frameCount; } - - // Get the current framerate. - uint32 GetFramesPerSecond() const { return m_framesPerSecond; } - - // Set whether to use fixed or variable timestep mode. - void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; } - - // Set how often to call Update when in fixed timestep mode. - void SetTargetElapsedTicks(uint64 targetElapsed) { m_targetElapsedTicks = targetElapsed; } - void SetTargetElapsedSeconds(double targetElapsed) { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } - - // Integer format represents time using 10,000,000 ticks per second. - static const uint64 TicksPerSecond = 10000000; - - static double TicksToSeconds(uint64 ticks) { return static_cast<double>(ticks) / TicksPerSecond; } - static uint64 SecondsToTicks(double seconds) { return static_cast<uint64>(seconds * TicksPerSecond); } - - // After an intentional timing discontinuity (for instance a blocking IO operation) - // call this to avoid having the fixed timestep logic attempt a set of catch-up - // Update calls. - - void ResetElapsedTime() - { - if (!QueryPerformanceCounter(&m_qpcLastTime)) - { - throw ref new Platform::FailureException(); - } - - m_leftOverTicks = 0; - m_framesPerSecond = 0; - m_framesThisSecond = 0; - m_qpcSecondCounter = 0; - } - - // Update timer state, calling the specified Update function the appropriate number of times. - template<typename TUpdate> - void Tick(const TUpdate& update) - { - // Query the current time. - LARGE_INTEGER currentTime; - - if (!QueryPerformanceCounter(¤tTime)) - { - throw ref new Platform::FailureException(); - } - - uint64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart; - - m_qpcLastTime = currentTime; - m_qpcSecondCounter += timeDelta; - - // Clamp excessively large time deltas (e.g. after paused in the debugger). - if (timeDelta > m_qpcMaxDelta) - { - timeDelta = m_qpcMaxDelta; - } - - // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. - timeDelta *= TicksPerSecond; - timeDelta /= m_qpcFrequency.QuadPart; - - uint32 lastFrameCount = m_frameCount; - - if (m_isFixedTimeStep) - { - // Fixed timestep update logic - - // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp - // the clock to exactly match the target value. This prevents tiny and irrelevant errors - // from accumulating over time. Without this clamping, a game that requested a 60 fps - // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually - // accumulate enough tiny errors that it would drop a frame. It is better to just round - // small deviations down to zero to leave things running smoothly. - - if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000) - { - timeDelta = m_targetElapsedTicks; - } - - m_leftOverTicks += timeDelta; - - while (m_leftOverTicks >= m_targetElapsedTicks) - { - m_elapsedTicks = m_targetElapsedTicks; - m_totalTicks += m_targetElapsedTicks; - m_leftOverTicks -= m_targetElapsedTicks; - m_frameCount++; - - update(); - } - } - else - { - // Variable timestep update logic. - m_elapsedTicks = timeDelta; - m_totalTicks += timeDelta; - m_leftOverTicks = 0; - m_frameCount++; - - update(); - } - - // Track the current framerate. - if (m_frameCount != lastFrameCount) - { - m_framesThisSecond++; - } - - if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency.QuadPart)) - { - m_framesPerSecond = m_framesThisSecond; - m_framesThisSecond = 0; - m_qpcSecondCounter %= m_qpcFrequency.QuadPart; - } - } - - private: - // Source timing data uses QPC units. - LARGE_INTEGER m_qpcFrequency; - LARGE_INTEGER m_qpcLastTime; - uint64 m_qpcMaxDelta; - - // Derived timing data uses a canonical tick format. - uint64 m_elapsedTicks; - uint64 m_totalTicks; - uint64 m_leftOverTicks; - - // Members for tracking the framerate. - uint32 m_frameCount; - uint32 m_framesPerSecond; - uint32 m_framesThisSecond; - uint64 m_qpcSecondCounter; - - // Members for configuring fixed timestep mode. - bool m_isFixedTimeStep; - uint64 m_targetElapsedTicks; - }; + // Helper class for animation and simulation timing. + class StepTimer + { + public: + StepTimer() : + m_elapsedTicks(0), + m_totalTicks(0), + m_leftOverTicks(0), + m_frameCount(0), + m_framesPerSecond(0), + m_framesThisSecond(0), + m_qpcSecondCounter(0), + m_isFixedTimeStep(false), + m_targetElapsedTicks(TicksPerSecond / 60) + { + if (!QueryPerformanceFrequency(&m_qpcFrequency)) + { + throw ref new Platform::FailureException(); + } + + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw ref new Platform::FailureException(); + } + + // Initialize max delta to 1/10 of a second. + m_qpcMaxDelta = m_qpcFrequency.QuadPart / 10; + } + + // Get elapsed time since the previous Update call. + uint64 GetElapsedTicks() const { return m_elapsedTicks; } + double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); } + + // Get total time since the start of the program. + uint64 GetTotalTicks() const { return m_totalTicks; } + double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); } + + // Get total number of updates since start of the program. + uint32 GetFrameCount() const { return m_frameCount; } + + // Get the current framerate. + uint32 GetFramesPerSecond() const { return m_framesPerSecond; } + + // Set whether to use fixed or variable timestep mode. + void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; } + + // Set how often to call Update when in fixed timestep mode. + void SetTargetElapsedTicks(uint64 targetElapsed) { m_targetElapsedTicks = targetElapsed; } + void SetTargetElapsedSeconds(double targetElapsed) { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } + + // Integer format represents time using 10,000,000 ticks per second. + static const uint64 TicksPerSecond = 10000000; + + static double TicksToSeconds(uint64 ticks) { return static_cast<double>(ticks) / TicksPerSecond; } + static uint64 SecondsToTicks(double seconds) { return static_cast<uint64>(seconds * TicksPerSecond); } + + // After an intentional timing discontinuity (for instance a blocking IO operation) + // call this to avoid having the fixed timestep logic attempt a set of catch-up + // Update calls. + + void ResetElapsedTime() + { + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw ref new Platform::FailureException(); + } + + m_leftOverTicks = 0; + m_framesPerSecond = 0; + m_framesThisSecond = 0; + m_qpcSecondCounter = 0; + } + + // Update timer state, calling the specified Update function the appropriate number of times. + template<typename TUpdate> + void Tick(const TUpdate& update) + { + // Query the current time. + LARGE_INTEGER currentTime; + + if (!QueryPerformanceCounter(¤tTime)) + { + throw ref new Platform::FailureException(); + } + + uint64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart; + + m_qpcLastTime = currentTime; + m_qpcSecondCounter += timeDelta; + + // Clamp excessively large time deltas (e.g. after paused in the debugger). + if (timeDelta > m_qpcMaxDelta) + { + timeDelta = m_qpcMaxDelta; + } + + // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. + timeDelta *= TicksPerSecond; + timeDelta /= m_qpcFrequency.QuadPart; + + uint32 lastFrameCount = m_frameCount; + + if (m_isFixedTimeStep) + { + // Fixed timestep update logic + + // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp + // the clock to exactly match the target value. This prevents tiny and irrelevant errors + // from accumulating over time. Without this clamping, a game that requested a 60 fps + // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually + // accumulate enough tiny errors that it would drop a frame. It is better to just round + // small deviations down to zero to leave things running smoothly. + + if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000) + { + timeDelta = m_targetElapsedTicks; + } + + m_leftOverTicks += timeDelta; + + while (m_leftOverTicks >= m_targetElapsedTicks) + { + m_elapsedTicks = m_targetElapsedTicks; + m_totalTicks += m_targetElapsedTicks; + m_leftOverTicks -= m_targetElapsedTicks; + m_frameCount++; + + update(); + } + } + else + { + // Variable timestep update logic. + m_elapsedTicks = timeDelta; + m_totalTicks += timeDelta; + m_leftOverTicks = 0; + m_frameCount++; + + update(); + } + + // Track the current framerate. + if (m_frameCount != lastFrameCount) + { + m_framesThisSecond++; + } + + if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency.QuadPart)) + { + m_framesPerSecond = m_framesThisSecond; + m_framesThisSecond = 0; + m_qpcSecondCounter %= m_qpcFrequency.QuadPart; + } + } + + private: + // Source timing data uses QPC units. + LARGE_INTEGER m_qpcFrequency; + LARGE_INTEGER m_qpcLastTime; + uint64 m_qpcMaxDelta; + + // Derived timing data uses a canonical tick format. + uint64 m_elapsedTicks; + uint64 m_totalTicks; + uint64 m_leftOverTicks; + + // Members for tracking the framerate. + uint32 m_frameCount; + uint32 m_framesPerSecond; + uint32 m_framesThisSecond; + uint64 m_qpcSecondCounter; + + // Members for configuring fixed timestep mode. + bool m_isFixedTimeStep; + uint64 m_targetElapsedTicks; + }; } |
