summaryrefslogtreecommitdiffstats
path: root/NativeApp/src/UWP
diff options
context:
space:
mode:
authorEgor Yusov <egor.yusov@gmail.com>2019-11-11 15:42:14 +0000
committerEgor Yusov <egor.yusov@gmail.com>2019-11-11 15:42:14 +0000
commitee177d37df85b982d6c528a7b79e3cd9ca9749d6 (patch)
treedda6c9b0c2a3f2756c08b71ebaca32644dbc9d32 /NativeApp/src/UWP
parentUpdated HLSL2GLSL converter app (diff)
downloadDiligentTools-ee177d37df85b982d6c528a7b79e3cd9ca9749d6.tar.gz
DiligentTools-ee177d37df85b982d6c528a7b79e3cd9ca9749d6.zip
Moved Native App from master repository
Diffstat (limited to 'NativeApp/src/UWP')
-rw-r--r--NativeApp/src/UWP/App.cpp351
-rw-r--r--NativeApp/src/UWP/App.h71
-rw-r--r--NativeApp/src/UWP/Common/DeviceResources.cpp328
-rw-r--r--NativeApp/src/UWP/Common/DeviceResources.h72
-rw-r--r--NativeApp/src/UWP/Common/DirectXHelper.h58
-rw-r--r--NativeApp/src/UWP/Common/StepTimer.h183
-rw-r--r--NativeApp/src/UWP/UWPAppBase.cpp50
-rw-r--r--NativeApp/src/UWP/dummy.cpp7
8 files changed, 1120 insertions, 0 deletions
diff --git a/NativeApp/src/UWP/App.cpp b/NativeApp/src/UWP/App.cpp
new file mode 100644
index 0000000..0c928eb
--- /dev/null
+++ b/NativeApp/src/UWP/App.cpp
@@ -0,0 +1,351 @@
+/* Copyright 2015-2016 Egor Yusov
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
+ *
+ * In no event and under no legal theory, whether in tort (including negligence),
+ * contract, or otherwise, unless required by applicable law (such as deliberate
+ * and grossly negligent acts) or agreed to in writing, shall any Contributor be
+ * liable for any damages, including any direct, indirect, special, incidental,
+ * or consequential damages of any character arising as a result of this License or
+ * out of the use or inability to use the software (including but not limited to damages
+ * for loss of goodwill, work stoppage, computer failure or malfunction, or any and
+ * all other commercial damages or losses), even if such Contributor has been advised
+ * of the possibility of such damages.
+ */
+
+#define NOMINIMAX
+#include <wrl.h>
+#include <wrl/client.h>
+#include <DirectXMath.h>
+#include <agile.h>
+
+#if defined(_DEBUG)
+# include <dxgidebug.h>
+#endif
+
+#include "App.h"
+#include "StringTools.h"
+
+#include <ppltasks.h>
+
+using namespace SampleApp;
+using namespace Diligent;
+
+using namespace concurrency;
+using namespace Windows::ApplicationModel;
+using namespace Windows::ApplicationModel::Core;
+using namespace Windows::ApplicationModel::Activation;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Input;
+using namespace Windows::System;
+using namespace Windows::Foundation;
+using namespace Windows::Graphics::Display;
+
+using Microsoft::WRL::ComPtr;
+
+
+ref class ApplicationSource sealed : IFrameworkViewSource
+{
+public:
+ virtual IFrameworkView^ CreateView()
+ {
+ return ref new App();
+ }
+};
+
+
+// The main function is only used to initialize our IFrameworkView class.
+[Platform::MTAThread]
+int main(Platform::Array<Platform::String^>^)
+{
+ auto direct3DApplicationSource = ref new ApplicationSource();
+ CoreApplication::Run(direct3DApplicationSource);
+ return 0;
+}
+
+App::App() :
+ m_windowClosed(false),
+ m_windowVisible(true)
+{
+}
+
+
+// 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);
+
+ CoreApplication::Suspending +=
+ ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);
+
+ 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->VisibilityChanged +=
+ ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
+
+ window->Closed +=
+ ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
+
+ window->KeyDown +=
+ ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyDown);
+
+ window->KeyUp +=
+ ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyUp);
+
+ DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
+
+ currentDisplayInformation->DpiChanged +=
+ ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged);
+
+ currentDisplayInformation->OrientationChanged +=
+ ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);
+
+ DisplayInformation::DisplayContentsInvalidated +=
+ ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated);
+
+ if (m_Main)
+ {
+ m_Main->OnSetWindow(window);
+ }
+}
+
+// Initializes scene resources, or loads a previously saved app state.
+void App::Load(Platform::String^ entryPoint)
+{
+ 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);
+
+ // Initialize device resources
+ GetDeviceResources();
+
+ //PIXBeginEvent(commandQueue, 0, L"Update");
+ {
+ m_Main->Update();
+ }
+ //PIXEndEvent(commandQueue);
+
+ //PIXBeginEvent(commandQueue, 0, L"Render");
+ {
+ m_Main->Render();
+ if (m_Main->IsFrameReady())
+ {
+ m_Main->Present();
+ }
+ }
+ //PIXEndEvent(commandQueue);
+ }
+ else
+ {
+ CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
+ }
+ }
+}
+
+// Required for IFrameworkView.
+// Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
+// class is torn down while the app is in the foreground.
+void App::Uninitialize()
+{
+}
+
+// Application lifecycle event handlers.
+
+void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
+{
+ if (args->Kind == ActivationKind::Launch)
+ {
+ LaunchActivatedEventArgs^ launchArgs = (LaunchActivatedEventArgs^)args;
+ auto CmdLine = Diligent::NarrowString(launchArgs->Arguments->Data());
+ m_Main->ProcessCommandLine(CmdLine.c_str());
+ }
+
+ auto Title = Diligent::WidenString(m_Main->GetAppTitle());
+ Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Title = ref new Platform::String(Title.c_str());
+
+ // Run() won't start until the CoreWindow is activated.
+ CoreWindow::GetForCurrentThread()->Activate();
+}
+
+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();
+ });
+}
+
+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.
+
+ m_Main->OnResuming();
+}
+
+// Window event handlers.
+
+void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
+{
+ if (auto DeviceResources = GetDeviceResources())
+ {
+ DeviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height));
+ m_Main->OnWindowSizeChanged();
+ }
+}
+
+void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
+{
+ m_windowVisible = args->Visible;
+}
+
+void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
+{
+ 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.
+ if (auto DeviceResources = GetDeviceResources())
+ {
+ DeviceResources->SetDpi(sender->LogicalDpi);
+ m_Main->OnWindowSizeChanged();
+ }
+}
+
+void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
+{
+ if (auto DeviceResources = GetDeviceResources())
+ {
+ DeviceResources->SetCurrentOrientation(sender->CurrentOrientation);
+ m_Main->OnWindowSizeChanged();
+ }
+}
+
+void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args)
+{
+ if (auto DeviceResources = GetDeviceResources())
+ {
+ DeviceResources->ValidateDevice();
+ }
+}
+
+void App::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
+{
+ auto Key = args->VirtualKey;
+ switch(Key)
+ {
+ case VirtualKey::Escape:
+ CoreApplication::Exit();
+ break;
+
+ case VirtualKey::Enter:
+ if(m_bShiftPressed)
+ {
+ auto applicationView = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView();
+ if (applicationView->IsFullScreenMode)
+ {
+ applicationView->ExitFullScreenMode();
+ }
+ else
+ {
+ applicationView->TryEnterFullScreenMode();
+ }
+ }
+ break;
+
+ case VirtualKey::Shift:
+ m_bShiftPressed = true;
+ break;
+ }
+}
+
+void App::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
+{
+ auto Key = args->VirtualKey;
+ switch (Key)
+ {
+ case VirtualKey::Shift:
+ m_bShiftPressed = false;
+ break;
+ }
+}
+
+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.
+
+ 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));
+ }
+#endif
+ }
+
+ if (m_deviceResources == nullptr)
+ {
+ m_deviceResources = m_Main->InitDeviceResources();
+ if (m_deviceResources)
+ {
+ 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();
+ }
+ }
+ return m_deviceResources;
+}
diff --git a/NativeApp/src/UWP/App.h b/NativeApp/src/UWP/App.h
new file mode 100644
index 0000000..4f31f07
--- /dev/null
+++ b/NativeApp/src/UWP/App.h
@@ -0,0 +1,71 @@
+/* Copyright 2015-2016 Egor Yusov
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
+ *
+ * In no event and under no legal theory, whether in tort (including negligence),
+ * contract, or otherwise, unless required by applicable law (such as deliberate
+ * and grossly negligent acts) or agreed to in writing, shall any Contributor be
+ * liable for any damages, including any direct, indirect, special, incidental,
+ * or consequential damages of any character arising as a result of this License or
+ * out of the use or inability to use the software (including but not limited to damages
+ * for loss of goodwill, work stoppage, computer failure or malfunction, or any and
+ * all other commercial damages or losses), even if such Contributor has been advised
+ * of the possibility of such damages.
+ */
+
+#pragma once
+
+#include "Common\DeviceResources.h"
+#include "NativeAppBase.h"
+
+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();
+
+ // 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);
+
+ // 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);
+
+ 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:
+ 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;
+ bool m_bShiftPressed = false;
+ };
+}
diff --git a/NativeApp/src/UWP/Common/DeviceResources.cpp b/NativeApp/src/UWP/Common/DeviceResources.cpp
new file mode 100644
index 0000000..c111a54
--- /dev/null
+++ b/NativeApp/src/UWP/Common/DeviceResources.cpp
@@ -0,0 +1,328 @@
+
+#define NOMINIMAX
+#include <wrl.h>
+#include <wrl/client.h>
+#include <DirectXMath.h>
+#include <agile.h>
+
+#include <dxgi1_4.h>
+#include <d3d12.h>
+#include <d3d11.h>
+#include <pix.h>
+
+#if defined(_DEBUG)
+# include <dxgidebug.h>
+#endif
+
+#include "DeviceResources.h"
+#include "DirectXHelper.h"
+
+
+using namespace DirectX;
+using namespace Microsoft::WRL;
+using namespace Windows::Foundation;
+using namespace Windows::Graphics::Display;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Xaml::Controls;
+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.
+};
+
+// 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
+ );
+};
+
+// 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_d3d11Device(d3d11Device),
+ m_d3d12Device(d3d12Device)
+{
+}
+
+
+void DX::DeviceResources::SetSwapChainRotation(IDXGISwapChain3 *swapChain)
+{
+ // Set the proper orientation for the swap chain, and generate
+ // 3D matrix transformations for rendering to the rotated swap chain.
+ // The 3D matrix is specified explicitly to avoid rounding errors.
+ DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
+ switch (displayRotation)
+ {
+ case DXGI_MODE_ROTATION_IDENTITY:
+ m_orientationTransform3D = ScreenRotation::Rotation0;
+ break;
+
+ case DXGI_MODE_ROTATION_ROTATE90:
+ m_orientationTransform3D = ScreenRotation::Rotation270;
+ break;
+
+ case DXGI_MODE_ROTATION_ROTATE180:
+ m_orientationTransform3D = ScreenRotation::Rotation180;
+ break;
+
+ case DXGI_MODE_ROTATION_ROTATE270:
+ m_orientationTransform3D = ScreenRotation::Rotation90;
+ break;
+
+ default:
+ throw ref new FailureException();
+ }
+
+ DX::ThrowIfFailed(
+ swapChain->SetRotation(displayRotation)
+ );
+}
+
+// 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);
+
+
+ // The width and height of the swap chain must be based on the window's
+ // natively-oriented width and height. If the window is not in the native
+ // orientation, the dimensions must be reversed.
+ DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
+
+ bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
+ auto fWidth = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
+ auto fHeight = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
+
+ m_backBufferWidth = lround(fWidth);
+ m_backBufferHeight = lround(fHeight);
+}
+
+// This method is called when the CoreWindow is created (or re-created).
+void DX::DeviceResources::SetWindow(CoreWindow^ window)
+{
+ 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;
+
+ //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();
+ }
+}
+
+// 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;
+
+ // 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();
+ }
+}
+
+// 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();
+ }
+}
+
+// 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.
+
+ ComPtr<IDXGIDevice3> dxgiDevice;
+ if(m_d3d11Device)
+ 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<IDXGIFactory2> deviceFactory;
+ DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
+
+ // 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));
+
+ DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
+ }
+
+ // Next, get the information for the current default adapter.
+
+ DXGI_ADAPTER_DESC currentDesc;
+ {
+ ComPtr<IDXGIFactory4> currentDxgiFactory;
+ DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentDxgiFactory)));
+
+ ComPtr<IDXGIAdapter1> currentDefaultAdapter;
+ DX::ThrowIfFailed(currentDxgiFactory->EnumAdapters1(0, &currentDefaultAdapter));
+
+ DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
+ }
+
+ // 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()) ||
+ m_d3d12Device && FAILED(m_d3d12Device->GetDeviceRemovedReason()))
+ {
+ 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;
+}
diff --git a/NativeApp/src/UWP/Common/DeviceResources.h b/NativeApp/src/UWP/Common/DeviceResources.h
new file mode 100644
index 0000000..69fa00c
--- /dev/null
+++ b/NativeApp/src/UWP/Common/DeviceResources.h
@@ -0,0 +1,72 @@
+#pragma once
+
+#include <dxgi1_4.h>
+#include <d3d12.h>
+#include <d3d11.h>
+#include <DirectXMath.h>
+#include <agile.h>
+
+namespace DX
+{
+ // 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 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 dips.
+ Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; }
+
+ float GetDpi() const { return m_effectiveDpi; }
+ bool IsDeviceRemoved() const { return m_deviceRemoved; }
+
+ // D3D Accessors.
+ DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; }
+
+ void UpdateRenderTargetSize();
+ UINT GetBackBufferWidth() {return m_backBufferWidth;}
+ UINT GetBackBufferHeight() {return m_backBufferHeight;}
+
+ Windows::UI::Core::CoreWindow^ GetWindow(){return m_window.Get();}
+
+ private:
+
+
+ DXGI_MODE_ROTATION ComputeDisplayRotation();
+
+ bool m_deviceRemoved;
+
+ // 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 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;
+
+ // Transforms used for display orientation.
+ DirectX::XMFLOAT4X4 m_orientationTransform3D;
+ };
+}
diff --git a/NativeApp/src/UWP/Common/DirectXHelper.h b/NativeApp/src/UWP/Common/DirectXHelper.h
new file mode 100644
index 0000000..7bfe36f
--- /dev/null
+++ b/NativeApp/src/UWP/Common/DirectXHelper.h
@@ -0,0 +1,58 @@
+#pragma once
+
+#include <ppltasks.h> // For create_task
+
+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.
+#if defined(_DEBUG)
+ inline void SetName(ID3D12Object* pObject, LPCWSTR name)
+ {
+ pObject->SetName(name);
+ }
+#else
+ inline void SetName(ID3D12Object*, LPCWSTR)
+ {
+ }
+#endif
+}
+
+// Naming helper function for ComPtr<T>.
+// Assigns the name of the variable as the name of the object.
+#define NAME_D3D12_OBJECT(x) DX::SetName(x.Get(), L#x)
diff --git a/NativeApp/src/UWP/Common/StepTimer.h b/NativeApp/src/UWP/Common/StepTimer.h
new file mode 100644
index 0000000..c8addbc
--- /dev/null
+++ b/NativeApp/src/UWP/Common/StepTimer.h
@@ -0,0 +1,183 @@
+#pragma once
+
+#include <wrl.h>
+
+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(&currentTime))
+ {
+ 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;
+ };
+}
diff --git a/NativeApp/src/UWP/UWPAppBase.cpp b/NativeApp/src/UWP/UWPAppBase.cpp
new file mode 100644
index 0000000..346b2bd
--- /dev/null
+++ b/NativeApp/src/UWP/UWPAppBase.cpp
@@ -0,0 +1,50 @@
+/* Copyright 2015-2018 Egor Yusov
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
+ *
+ * In no event and under no legal theory, whether in tort (including negligence),
+ * contract, or otherwise, unless required by applicable law (such as deliberate
+ * and grossly negligent acts) or agreed to in writing, shall any Contributor be
+ * liable for any damages, including any direct, indirect, special, incidental,
+ * or consequential damages of any character arising as a result of this License or
+ * out of the use or inability to use the software (including but not limited to damages
+ * for loss of goodwill, work stoppage, computer failure or malfunction, or any and
+ * all other commercial damages or losses), even if such Contributor has been advised
+ * of the possibility of such damages.
+ */
+
+#include "UWPAppBase.h"
+
+namespace Diligent
+{
+
+UWPAppBase::UWPAppBase()
+{
+ // TODO: Change the timer settings if you want something other than the default variable timestep mode.
+ // e.g. for 60 FPS fixed timestep update logic, call:
+ /*
+ m_timer.SetFixedTimeStep(true);
+ m_timer.SetTargetElapsedSeconds(1.0 / 60);
+ */
+}
+
+void UWPAppBase::Update()
+{
+ // Update scene objects.
+ m_timer.Tick([&]()
+ {
+ auto CurrTime = m_timer.GetTotalSeconds();
+ auto ElapsedTime = m_timer.GetElapsedSeconds();
+ Update(CurrTime, ElapsedTime);
+ });
+}
+
+}
diff --git a/NativeApp/src/UWP/dummy.cpp b/NativeApp/src/UWP/dummy.cpp
new file mode 100644
index 0000000..5caae53
--- /dev/null
+++ b/NativeApp/src/UWP/dummy.cpp
@@ -0,0 +1,7 @@
+#include "AppBase.h"
+
+// This dummy file is only required for the NativeAppBase.lib to be created,
+// which is required to avoid linker error
+
+// We cannot add real source to this library because Windows Runtime types cannot
+// be included into static libraries \ No newline at end of file