diff options
| author | Egor Yusov <egor.yusov@gmail.com> | 2019-11-11 15:42:14 +0000 |
|---|---|---|
| committer | Egor Yusov <egor.yusov@gmail.com> | 2019-11-11 15:42:14 +0000 |
| commit | ee177d37df85b982d6c528a7b79e3cd9ca9749d6 (patch) | |
| tree | dda6c9b0c2a3f2756c08b71ebaca32644dbc9d32 /NativeApp/src | |
| parent | Updated HLSL2GLSL converter app (diff) | |
| download | DiligentTools-ee177d37df85b982d6c528a7b79e3cd9ca9749d6.tar.gz DiligentTools-ee177d37df85b982d6c528a7b79e3cd9ca9749d6.zip | |
Moved Native App from master repository
Diffstat (limited to 'NativeApp/src')
| -rw-r--r-- | NativeApp/src/Android/AndroidAppBase.cpp | 266 | ||||
| -rw-r--r-- | NativeApp/src/Android/AndroidMain.cpp | 93 | ||||
| -rw-r--r-- | NativeApp/src/IOS/IOSAppBase.cpp | 38 | ||||
| -rw-r--r-- | NativeApp/src/Linux/LinuxMain.cpp | 526 | ||||
| -rw-r--r-- | NativeApp/src/MacOS/MacOSAppBase.cpp | 38 | ||||
| -rw-r--r-- | NativeApp/src/UWP/App.cpp | 351 | ||||
| -rw-r--r-- | NativeApp/src/UWP/App.h | 71 | ||||
| -rw-r--r-- | NativeApp/src/UWP/Common/DeviceResources.cpp | 328 | ||||
| -rw-r--r-- | NativeApp/src/UWP/Common/DeviceResources.h | 72 | ||||
| -rw-r--r-- | NativeApp/src/UWP/Common/DirectXHelper.h | 58 | ||||
| -rw-r--r-- | NativeApp/src/UWP/Common/StepTimer.h | 183 | ||||
| -rw-r--r-- | NativeApp/src/UWP/UWPAppBase.cpp | 50 | ||||
| -rw-r--r-- | NativeApp/src/UWP/dummy.cpp | 7 | ||||
| -rw-r--r-- | NativeApp/src/Win32/WinMain.cpp | 168 |
14 files changed, 2249 insertions, 0 deletions
diff --git a/NativeApp/src/Android/AndroidAppBase.cpp b/NativeApp/src/Android/AndroidAppBase.cpp new file mode 100644 index 0000000..f3e341c --- /dev/null +++ b/NativeApp/src/Android/AndroidAppBase.cpp @@ -0,0 +1,266 @@ +/* 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 "AndroidAppBase.h" +#include "Timer.h" + +#include <android/sensor.h> +//#include <android/log.h> +//#include <android_native_app_glue.h> +#include <android/native_window_jni.h> +//#include <cpu-features.h> + +namespace Diligent +{ + +int AndroidAppBase::InitDisplay() +{ + if( !initialized_resources_ ) + { + Initialize(); + + LoadResources(); + initialized_resources_ = true; + } + else + { + // initialize OpenGL ES and EGL + if( EGL_SUCCESS != Resume( app_->window ) ) + { + UnloadResources(); + LoadResources(); + } + } + + ShowUI(); + + //tap_camera_.SetFlip( 1.f, -1.f, -1.f ); + //tap_camera_.SetPinchTransformFactor( 2.f, 2.f, 8.f ); + + return 0; +} + +void AndroidAppBase::InitSensors() +{ + sensor_manager_ = ASensorManager_getInstance(); + accelerometer_sensor_ = ASensorManager_getDefaultSensor( sensor_manager_, ASENSOR_TYPE_ACCELEROMETER ); + sensor_event_queue_ = ASensorManager_createEventQueue( sensor_manager_, app_->looper, LOOPER_ID_USER, NULL, NULL ); +} + +// +// Just the current frame in the display. +// +void AndroidAppBase::DrawFrame() +{ + // APP_CMD_CONFIG_CHANGED event is generated seveal frames + // before the screen is actually resized. The only robust way + // to detect window resize is to check it very frame + if(CheckWindowSizeChanged()) + WindowResize(0,0); + + float fFPS; + if( monitor_.Update( fFPS ) ) + { + UpdateFPS( fFPS ); + } + + static Diligent::Timer Timer; + static double PrevTime = Timer.GetElapsedTime(); + auto CurrTime = Timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + + Update(CurrTime, ElapsedTime); + + Render(); + + Present(); + //if( EGL_SUCCESS != pRenderDevice_->Present() ) + //{ + // UnloadResources(); + // LoadResources(); + //} +} + + +// +// Process the next input event. +// +int32_t AndroidAppBase::HandleInput( android_app* app, AInputEvent* event ) +{ + AndroidAppBase* eng = (AndroidAppBase*)app->userData; + return eng->HandleInput( event ); +} + +// +// Process the next main command. +// +void AndroidAppBase::HandleCmd( struct android_app* app, int32_t cmd ) +{ + AndroidAppBase* eng = (AndroidAppBase*)app->userData; + switch( cmd ) + { + case APP_CMD_SAVE_STATE: + break; + + case APP_CMD_INIT_WINDOW: + // The window is being shown, get it ready. + if( app->window != NULL ) + { + eng->InitDisplay(); + eng->DrawFrame(); + } + break; + + case APP_CMD_CONFIG_CHANGED: + case APP_CMD_WINDOW_RESIZED: + // This does not work as the screen resizes few frames + // after the event has been received + // eng->WindowResize(0,0); + break; + + case APP_CMD_TERM_WINDOW: + // The window is being hidden or closed, clean it up. + eng->TermDisplay(); + eng->has_focus_ = false; + break; + + case APP_CMD_STOP: + break; + + case APP_CMD_GAINED_FOCUS: + eng->ResumeSensors(); + //Start animation + eng->has_focus_ = true; + break; + + case APP_CMD_LOST_FOCUS: + eng->SuspendSensors(); + // Also stop animating. + eng->has_focus_ = false; + eng->DrawFrame(); + break; + + case APP_CMD_LOW_MEMORY: + //Free up GL resources + eng->TrimMemory(); + break; + } +} + +//------------------------------------------------------------------------- +//Sensor handlers +//------------------------------------------------------------------------- +void AndroidAppBase::ProcessSensors( int32_t id ) +{ + // If a sensor has data, process it now. + if( id == LOOPER_ID_USER ) + { + if( accelerometer_sensor_ != NULL ) + { + ASensorEvent event; + while( ASensorEventQueue_getEvents( sensor_event_queue_, &event, 1 ) > 0 ) + { + } + } + } +} + +void AndroidAppBase::ResumeSensors() +{ + // When our app gains focus, we start monitoring the accelerometer. + if( accelerometer_sensor_ != NULL ) + { + ASensorEventQueue_enableSensor( sensor_event_queue_, accelerometer_sensor_ ); + // We'd like to get 60 events per second (in us). + ASensorEventQueue_setEventRate( sensor_event_queue_, accelerometer_sensor_, + (1000L / 60) * 1000 ); + } +} + +void AndroidAppBase::SuspendSensors() +{ + // When our app loses focus, we stop monitoring the accelerometer. + // This is to avoid consuming battery while not being used. + if( accelerometer_sensor_ != NULL ) + { + ASensorEventQueue_disableSensor( sensor_event_queue_, accelerometer_sensor_ ); + } +} + +//------------------------------------------------------------------------- +//Misc +//------------------------------------------------------------------------- +void AndroidAppBase::SetState( android_app* state, const char* native_activity_class_name ) +{ + app_ = state; + native_activity_class_name_ = native_activity_class_name; + doubletap_detector_.SetConfiguration( app_->config ); + drag_detector_.SetConfiguration( app_->config ); + pinch_detector_.SetConfiguration( app_->config ); +} + +bool AndroidAppBase::IsReady() +{ + if( has_focus_ ) + return true; + + return false; +} + +//void Engine::TransformPosition( ndk_helper::Vec2& vec ) +//{ +// vec = ndk_helper::Vec2( 2.0f, 2.0f ) * vec +// / ndk_helper::Vec2( pDeviceContext_->GetMainBackBufferDesc().Width, pDeviceContext_->GetMainBackBufferDesc().Height ) +// - ndk_helper::Vec2( 1.f, 1.f ); +//} + +void AndroidAppBase::ShowUI() +{ + JNIEnv *jni; + app_->activity->vm->AttachCurrentThread( &jni, NULL ); + + //Default class retrieval + jclass clazz = jni->GetObjectClass( app_->activity->clazz ); + jmethodID methodID = jni->GetMethodID( clazz, "showUI", "()V" ); + jni->CallVoidMethod( app_->activity->clazz, methodID ); + + app_->activity->vm->DetachCurrentThread(); + return; +} + +void AndroidAppBase::UpdateFPS( float fFPS ) +{ + JNIEnv *jni; + app_->activity->vm->AttachCurrentThread( &jni, NULL ); + + //Default class retrieval + jclass clazz = jni->GetObjectClass( app_->activity->clazz ); + jmethodID methodID = jni->GetMethodID( clazz, "updateFPS", "(F)V" ); + jni->CallVoidMethod( app_->activity->clazz, methodID, fFPS ); + + app_->activity->vm->DetachCurrentThread(); + return; +} + +} diff --git a/NativeApp/src/Android/AndroidMain.cpp b/NativeApp/src/Android/AndroidMain.cpp new file mode 100644 index 0000000..6e65b8a --- /dev/null +++ b/NativeApp/src/Android/AndroidMain.cpp @@ -0,0 +1,93 @@ + /* 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 <memory> +#include <jni.h> +#include <errno.h> + +#include "PlatformDefinitions.h" +#include "NativeAppBase.h" + + +#define HELPER_CLASS_NAME "com/android/helper/NDKHelper" //Class name of helper function +#define NATIVEACTIVITY_CLASS_NAME "android/app/NativeActivity" + +using namespace Diligent; + +// This is the main entry point of a native application that is using +// android_native_app_glue. It runs in its own thread, with its own +// event loop for receiving input events and doing other things. +void android_main( android_app* state ) +{ + std::unique_ptr<AndroidAppBase> theApp(CreateApplication()); + theApp->SetState( state, NATIVEACTIVITY_CLASS_NAME ); + + //Init helper functions + ndk_helper::JNIHelper::Init( state->activity, HELPER_CLASS_NAME ); + + state->userData = theApp.get(); + state->onAppCmd = AndroidAppBase::HandleCmd; + state->onInputEvent = AndroidAppBase::HandleInput; + +#ifdef USE_NDK_PROFILER + monstartup( "libEngineSandbox.so" ); +#endif + + // Prepare to monitor accelerometer + theApp->InitSensors(); + + // loop waiting for stuff to do. + while( 1 ) + { + // Read all pending events. + int id; + int events; + android_poll_source* source; + + // If not animating, we will block forever waiting for events. + // If animating, we loop until all events are read, then continue + // to draw the next frame of animation. + while( (id = ALooper_pollAll( theApp->IsReady() ? 0 : -1, NULL, &events, (void**)&source )) >= 0 ) + { + // Process this event. + if( source != NULL ) + source->process( state, source ); + + theApp->ProcessSensors( id ); + + // Check if we are exiting. + if( state->destroyRequested != 0 ) + { + theApp->TermDisplay(); + return; + } + } + + if( theApp->IsReady() ) + { + // Drawing is throttled to the screen update rate, so there + // is no need to do timing here. + theApp->DrawFrame(); + } + } +} diff --git a/NativeApp/src/IOS/IOSAppBase.cpp b/NativeApp/src/IOS/IOSAppBase.cpp new file mode 100644 index 0000000..d4defb8 --- /dev/null +++ b/NativeApp/src/IOS/IOSAppBase.cpp @@ -0,0 +1,38 @@ +/* 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 "IOSAppBase.h" + +namespace Diligent +{ + +void IOSAppBase::Update() +{ + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + Update(CurrTime, ElapsedTime); +} + +} diff --git a/NativeApp/src/Linux/LinuxMain.cpp b/NativeApp/src/Linux/LinuxMain.cpp new file mode 100644 index 0000000..c8cf197 --- /dev/null +++ b/NativeApp/src/Linux/LinuxMain.cpp @@ -0,0 +1,526 @@ +/* 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 <memory> +#include <iomanip> + +#include "PlatformDefinitions.h" +#include "NativeAppBase.h" +#include "StringTools.h" +#include "Timer.h" +#include "Errors.h" + + +#ifndef GLX_CONTEXT_MAJOR_VERSION_ARB +# define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#endif + +#ifndef GLX_CONTEXT_MINOR_VERSION_ARB +# define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 +#endif + +#ifndef GLX_CONTEXT_FLAGS_ARB +# define GLX_CONTEXT_FLAGS_ARB 0x2094 +#endif + +#ifndef GLX_CONTEXT_DEBUG_BIT_ARB +# define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001 +#endif + +typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, int, const int*); + +static constexpr uint16_t WindowWidth = 1024; +static constexpr uint16_t WindowHeight = 768; +static constexpr uint16_t MinWindowWidth = 320; +static constexpr uint16_t MinWindowHeight = 240; + +using namespace Diligent; + +namespace +{ + +class WindowTitleHelper +{ +public: + WindowTitleHelper(std::string _Title) : + Title(std::move(_Title)) + {} + + std::string GetTitleWithFPS(double ElapsedTime) + { + double filterScale = 0.2; + FilteredFrameTime = FilteredFrameTime * (1.0 - filterScale) + filterScale * ElapsedTime; + std::stringstream TitleWithFpsSS; + TitleWithFpsSS << Title; + TitleWithFpsSS << " - " << std::fixed << std::setprecision(1) << FilteredFrameTime * 1000; + TitleWithFpsSS << " ms (" << 1.0 / FilteredFrameTime << " fps)"; + return TitleWithFpsSS.str(); + } + +private: + const std::string Title; + double FilteredFrameTime = 0.0; +}; + +} + +#if VULKAN_SUPPORTED + +// https://code.woboq.org/qt5/include/xcb/xcb_icccm.h.html +enum XCB_SIZE_HINT +{ + XCB_SIZE_HINT_US_POSITION = 1 << 0, + XCB_SIZE_HINT_US_SIZE = 1 << 1, + XCB_SIZE_HINT_P_POSITION = 1 << 2, + XCB_SIZE_HINT_P_SIZE = 1 << 3, + XCB_SIZE_HINT_P_MIN_SIZE = 1 << 4, + XCB_SIZE_HINT_P_MAX_SIZE = 1 << 5, + XCB_SIZE_HINT_P_RESIZE_INC = 1 << 6, + XCB_SIZE_HINT_P_ASPECT = 1 << 7, + XCB_SIZE_HINT_BASE_SIZE = 1 << 8, + XCB_SIZE_HINT_P_WIN_GRAVITY = 1 << 9 +}; + +struct xcb_size_hints_t +{ + uint32_t flags; /** User specified flags */ + int32_t x, y; /** User-specified position */ + int32_t width, height; /** User-specified size */ + int32_t min_width, min_height; /** Program-specified minimum size */ + int32_t max_width, max_height; /** Program-specified maximum size */ + int32_t width_inc, height_inc; /** Program-specified resize increments */ + int32_t min_aspect_num, min_aspect_den; /** Program-specified minimum aspect ratios */ + int32_t max_aspect_num, max_aspect_den; /** Program-specified maximum aspect ratios */ + int32_t base_width, base_height; /** Program-specified base size */ + uint32_t win_gravity; /** Program-specified window gravity */ +}; + +struct XCBInfo +{ + xcb_connection_t* connection = nullptr; + uint32_t window = 0; + uint16_t width = 0; + uint16_t height = 0; + xcb_intern_atom_reply_t* atom_wm_delete_window = nullptr; +}; + +XCBInfo InitXCBConnectionAndWindow(const std::string& Title) +{ + XCBInfo info; + + int scr = 0; + info.connection = xcb_connect(nullptr, &scr); + if (info.connection == nullptr || xcb_connection_has_error(info.connection)) + { + std::cerr << "Unable to make an XCB connection\n"; + exit(-1); + } + + const xcb_setup_t* setup = xcb_get_setup(info.connection); + xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup); + while (scr-- > 0) + xcb_screen_next(&iter); + + auto screen = iter.data; + + info.width = WindowWidth; + info.height = WindowHeight; + + uint32_t value_mask, value_list[32]; + + info.window = xcb_generate_id(info.connection); + + value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; + value_list[0] = screen->black_pixel; + value_list[1] = + XCB_EVENT_MASK_KEY_RELEASE | + XCB_EVENT_MASK_KEY_PRESS | + XCB_EVENT_MASK_EXPOSURE | + XCB_EVENT_MASK_STRUCTURE_NOTIFY | + XCB_EVENT_MASK_POINTER_MOTION | + XCB_EVENT_MASK_BUTTON_PRESS | + XCB_EVENT_MASK_BUTTON_RELEASE; + + xcb_create_window(info.connection, XCB_COPY_FROM_PARENT, info.window, screen->root, 0, 0, info.width, info.height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list); + + // Magic code that will send notification when window is destroyed + xcb_intern_atom_cookie_t cookie = xcb_intern_atom(info.connection, 1, 12, "WM_PROTOCOLS"); + xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(info.connection, cookie, 0); + + xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(info.connection, 0, 16, "WM_DELETE_WINDOW"); + info.atom_wm_delete_window = xcb_intern_atom_reply(info.connection, cookie2, 0); + + xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window, (*reply).atom, 4, 32, 1, + &(*info.atom_wm_delete_window).atom); + free(reply); + + xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, + 8, Title.length(), Title.c_str() ); + + // https://stackoverflow.com/a/27771295 + xcb_size_hints_t hints = {}; + hints.flags = XCB_SIZE_HINT_P_MIN_SIZE; + hints.min_width = MinWindowWidth; + hints.min_height = MinWindowHeight; + xcb_change_property(info.connection, XCB_PROP_MODE_REPLACE, info.window, XCB_ATOM_WM_NORMAL_HINTS, XCB_ATOM_WM_SIZE_HINTS, + 32, sizeof(xcb_size_hints_t), &hints); + + xcb_map_window(info.connection, info.window); + + // Force the x/y coordinates to 100,100 results are identical in consecutive + // runs + const uint32_t coords[] = {100, 100}; + xcb_configure_window(info.connection, info.window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); + xcb_flush(info.connection); + + xcb_generic_event_t *e; + while ((e = xcb_wait_for_event(info.connection))) + { + if ((e->response_type & ~0x80) == XCB_EXPOSE) break; + } + return info; +} + +void DestroyXCBConnectionAndWindow(XCBInfo &info) +{ + xcb_destroy_window(info.connection, info.window); + xcb_disconnect(info.connection); +} + +int xcb_main() +{ + std::unique_ptr<NativeAppBase> TheApp(CreateApplication()); + + std::string Title = TheApp->GetAppTitle(); + auto xcbInfo = InitXCBConnectionAndWindow(Title); + if(!TheApp->InitVulkan(xcbInfo.connection, xcbInfo.window)) + return -1; + + xcb_flush(xcbInfo.connection); + + Timer timer; + auto PrevTime = timer.GetElapsedTime(); + Title = TheApp->GetAppTitle(); + WindowTitleHelper TitleHelper(Title); + + while (true) + { + xcb_generic_event_t* event = nullptr; + bool Quit = false; + while ((event = xcb_poll_for_event(xcbInfo.connection)) != nullptr) + { + TheApp->HandleXCBEvent(event); + switch (event->response_type & 0x7f) + { + case XCB_CLIENT_MESSAGE: + if ((*(xcb_client_message_event_t*)event).data.data32[0] == + (*xcbInfo.atom_wm_delete_window).atom) + { + Quit = true; + } + break; + + case XCB_KEY_RELEASE: + { + const auto* keyEvent = reinterpret_cast<const xcb_key_release_event_t*>(event); + switch (keyEvent->detail) + { + #define KEY_ESCAPE 0x9 + case KEY_ESCAPE: + Quit = true; + break; + } + } + break; + + case XCB_DESTROY_NOTIFY: + Quit = true; + break; + + case XCB_CONFIGURE_NOTIFY: + { + const auto* cfgEvent = reinterpret_cast<const xcb_configure_notify_event_t*>(event); + if ((cfgEvent->width != xcbInfo.width) || (cfgEvent->height != xcbInfo.height)) + { + xcbInfo.width = cfgEvent->width; + xcbInfo.height = cfgEvent->height; + if ((xcbInfo.width > 0) && (xcbInfo.height > 0)) + { + TheApp->WindowResize(xcbInfo.width, xcbInfo.height); + } + } + } + break; + + default: + break; + } + free(event); + } + + if (Quit) + break; + + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + + TheApp->Update(CurrTime, ElapsedTime); + + TheApp->Render(); + + TheApp->Present(); + + auto TitleWithFPS = TitleHelper.GetTitleWithFPS(ElapsedTime); + xcb_change_property(xcbInfo.connection, XCB_PROP_MODE_REPLACE, xcbInfo.window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, + 8, TitleWithFPS.length(), TitleWithFPS.c_str() ); + xcb_flush(xcbInfo.connection); + } + + TheApp.reset(); + DestroyXCBConnectionAndWindow(xcbInfo); + + return 0; +} + +#endif + + +int x_main() +{ + std::unique_ptr<NativeAppBase> TheApp(CreateApplication()); + Display *display = XOpenDisplay(0); + + static int visual_attribs[] = + { + GLX_RENDER_TYPE, GLX_RGBA_BIT, + GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, + GLX_DOUBLEBUFFER, true, + + // The largest available total RGBA color buffer size (sum of GLX_RED_SIZE, + // GLX_GREEN_SIZE, GLX_BLUE_SIZE, and GLX_ALPHA_SIZE) of at least the minimum + // size specified for each color component is preferred. + GLX_RED_SIZE, 8, + GLX_GREEN_SIZE, 8, + GLX_BLUE_SIZE, 8, + GLX_ALPHA_SIZE, 8, + + // The largest available depth buffer of at least GLX_DEPTH_SIZE size is preferred + GLX_DEPTH_SIZE, 24, + + //GLX_SAMPLE_BUFFERS, 1, + GLX_SAMPLES, 1, + None + }; + + int fbcount = 0; + GLXFBConfig *fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount); + if (!fbc) + { + LOG_ERROR_MESSAGE("Failed to retrieve a framebuffer config"); + return -1; + } + + XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[0]); + + XSetWindowAttributes swa; + swa.colormap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone); + swa.border_pixel = 0; + swa.event_mask = + StructureNotifyMask | + ExposureMask | + KeyPressMask | + KeyReleaseMask | + ButtonPressMask | + ButtonReleaseMask | + PointerMotionMask; + + Window win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, WindowWidth, WindowHeight, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa); + if (!win) + { + LOG_ERROR_MESSAGE("Failed to create window."); + return -1; + } + + { + auto SizeHints = XAllocSizeHints(); + SizeHints->flags = PMinSize; + SizeHints->min_width = MinWindowWidth; + SizeHints->min_height = MinWindowHeight; + XSetWMNormalHints(display, win, SizeHints); + XFree(SizeHints); + } + + XMapWindow(display, win); + + glXCreateContextAttribsARBProc glXCreateContextAttribsARB = nullptr; + { + // Create an oldstyle context first, to get the correct function pointer for glXCreateContextAttribsARB + GLXContext ctx_old = glXCreateContext(display, vi, 0, GL_TRUE); + glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); + glXMakeCurrent(display, None, NULL); + glXDestroyContext(display, ctx_old); + } + + if (glXCreateContextAttribsARB == nullptr) + { + LOG_ERROR("glXCreateContextAttribsARB entry point not found. Aborting."); + return -1; + } + + int Flags = GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; +#ifdef _DEBUG + Flags |= GLX_CONTEXT_DEBUG_BIT_ARB; +#endif + + int major_version = 4; + int minor_version = 3; + static int context_attribs[] = + { + GLX_CONTEXT_MAJOR_VERSION_ARB, major_version, + GLX_CONTEXT_MINOR_VERSION_ARB, minor_version, + GLX_CONTEXT_FLAGS_ARB, Flags, + None + }; + + constexpr int True = 1; + GLXContext ctx = glXCreateContextAttribsARB(display, fbc[0], NULL, True, context_attribs); + if (!ctx) + { + LOG_ERROR("Failed to create GL context."); + return -1; + } + XFree(fbc); + + + glXMakeCurrent(display, win, ctx); + TheApp->OnGLContextCreated(display, win); + std::string Title = TheApp->GetAppTitle(); + + Timer timer; + auto PrevTime = timer.GetElapsedTime(); + WindowTitleHelper TitleHelper(Title); + + while (true) + { + bool EscPressed = false; + XEvent xev; + // Handle all events in the queue + while(XCheckMaskEvent(display, 0xFFFFFFFF, &xev)) + { + TheApp->HandleXEvent(&xev); + switch(xev.type) + { + case KeyPress: + { + KeySym keysym; + char buffer[80]; + int num_char = XLookupString((XKeyEvent *)&xev, buffer, _countof(buffer), &keysym, 0); + EscPressed = (keysym==XK_Escape); + } + + case ConfigureNotify: + { + XConfigureEvent &xce = reinterpret_cast<XConfigureEvent &>(xev); + if(xce.width != 0 && xce.height != 0) + TheApp->WindowResize(xce.width, xce.height); + break; + } + } + } + + if(EscPressed) + break; + + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + + TheApp->Update(CurrTime, ElapsedTime); + + TheApp->Render(); + + TheApp->Present(); + + auto TitleWithFPS = TitleHelper.GetTitleWithFPS(ElapsedTime); + XStoreName(display, win, TitleWithFPS.c_str()); + } + + TheApp.reset(); + + ctx = glXGetCurrentContext(); + glXMakeCurrent(display, None, NULL); + glXDestroyContext(display, ctx); + XDestroyWindow(display, win); + XCloseDisplay(display); +} + +int main (int argc, char ** argv) +{ + bool UseVulkan = false; + +#if VULKAN_SUPPORTED + UseVulkan = true; + if (argc > 1) + { + const auto* Key = "-mode "; + const auto* pos = strstr(argv[1], Key); + if (pos != nullptr) + { + pos += strlen(Key); + while(*pos != 0 && *pos == ' ')++pos; + if (strcasecmp(pos, "GL") == 0) + { + UseVulkan = false; + } + else if (strcasecmp(pos, "VK") == 0) + { + UseVulkan = true; + } + else + { + std::cerr << "Unknown device type. Only the following types are supported: GL, VK"; + return -1; + } + } + } + + if (UseVulkan) + { + auto ret = xcb_main(); + if (ret >= 0) + { + return ret; + } + else + { + LOG_ERROR_MESSAGE("Failed to initialize the engine in Vulkan mode. Attempting to use OpenGL"); + } + } +#endif + + return x_main(); +} diff --git a/NativeApp/src/MacOS/MacOSAppBase.cpp b/NativeApp/src/MacOS/MacOSAppBase.cpp new file mode 100644 index 0000000..f3d0313 --- /dev/null +++ b/NativeApp/src/MacOS/MacOSAppBase.cpp @@ -0,0 +1,38 @@ +/* Copyright 2015-2019 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 "MacOSAppBase.h" + +namespace Diligent +{ + +void MacOSAppBase::Update() +{ + // Render the scene + auto CurrTime = timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + Update(CurrTime, ElapsedTime); +} + +} 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(¤tDxgiFactory))); + + ComPtr<IDXGIAdapter1> currentDefaultAdapter; + DX::ThrowIfFailed(currentDxgiFactory->EnumAdapters1(0, ¤tDefaultAdapter)); + + 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 (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(¤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; + }; +} 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 diff --git a/NativeApp/src/Win32/WinMain.cpp b/NativeApp/src/Win32/WinMain.cpp new file mode 100644 index 0000000..8f63460 --- /dev/null +++ b/NativeApp/src/Win32/WinMain.cpp @@ -0,0 +1,168 @@ +/* Copyright 2019 Diligent Graphics LLC + * + * 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 <memory> +#include <iomanip> +#include <Windows.h> +#include <crtdbg.h> +#include "NativeAppBase.h" +#include "StringTools.h" +#include "Timer.h" + +using namespace Diligent; + +std::unique_ptr<NativeAppBase> g_pTheApp; + +LRESULT CALLBACK MessageProc(HWND, UINT, WPARAM, LPARAM); +// Main +int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int cmdShow) +{ +#if defined(_DEBUG) || defined(DEBUG) + _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); +#endif + + g_pTheApp.reset( CreateApplication() ); + + const auto* cmdLine = GetCommandLineA(); + g_pTheApp->ProcessCommandLine(cmdLine); + + const auto* AppTitle = g_pTheApp->GetAppTitle(); + +#ifdef UNICODE + const auto* const WindowClassName = L"SampleApp"; +#else + const auto* const WindowClassName = "SampleApp"; +#endif + + // Register our window class + WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_HREDRAW|CS_VREDRAW, MessageProc, + 0L, 0L, instance, NULL, NULL, NULL, NULL, WindowClassName, NULL }; + RegisterClassEx(&wcex); + + int DesiredWidth = 0; + int DesiredHeight = 0; + g_pTheApp->GetDesiredInitialWindowSize(DesiredWidth, DesiredHeight); + // Create a window + LONG WindowWidth = DesiredWidth > 0 ? DesiredWidth : 1280; + LONG WindowHeight = DesiredHeight > 0 ? DesiredHeight : 1024; + RECT rc = { 0, 0, WindowWidth, WindowHeight }; + AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); + HWND wnd = CreateWindowA("SampleApp", AppTitle, + WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, + rc.right-rc.left, rc.bottom-rc.top, NULL, NULL, instance, NULL); + if (!wnd) + { + MessageBoxA(NULL, "Cannot create window", "Error", MB_OK|MB_ICONERROR); + return 0; + } + ShowWindow(wnd, cmdShow); + UpdateWindow(wnd); + + g_pTheApp->OnWindowCreated(wnd, WindowWidth, WindowHeight); + AppTitle = g_pTheApp->GetAppTitle(); + + Diligent::Timer Timer; + auto PrevTime = Timer.GetElapsedTime(); + double filteredFrameTime = 0.0; + + // Main message loop + MSG msg = {0}; + while (WM_QUIT != msg.message) + { + if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + else + { + auto CurrTime = Timer.GetElapsedTime(); + auto ElapsedTime = CurrTime - PrevTime; + PrevTime = CurrTime; + g_pTheApp->Update(CurrTime, ElapsedTime); + + g_pTheApp->Render(); + + g_pTheApp->Present(); + + double filterScale = 0.2; + filteredFrameTime = filteredFrameTime * (1.0 - filterScale) + filterScale * ElapsedTime; + std::stringstream fpsCounterSS; + fpsCounterSS << AppTitle << " - " << std::fixed << std::setprecision(1) << filteredFrameTime * 1000; + fpsCounterSS << " ms (" << 1.0 / filteredFrameTime << " fps)"; + SetWindowTextA(wnd, fpsCounterSS.str().c_str()); + } + } + + g_pTheApp.reset(); + + return (int)msg.wParam; +} + +// Called every time the NativeNativeAppBase receives a message +LRESULT CALLBACK MessageProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + if(g_pTheApp) + { + auto res = g_pTheApp->HandleWin32Message(wnd, message, wParam, lParam); + if (res != 0) + return res; + } + + switch (message) + { + case WM_PAINT: + { + PAINTSTRUCT ps; + BeginPaint(wnd, &ps); + EndPaint(wnd, &ps); + return 0; + } + case WM_SIZE: // Window size has been changed + if( g_pTheApp ) + { + g_pTheApp->WindowResize(LOWORD(lParam), HIWORD(lParam)); + } + return 0; + + case WM_CHAR: + if (wParam == VK_ESCAPE) + PostQuitMessage(0); + return 0; + + case WM_DESTROY: + PostQuitMessage(0); + return 0; + + case WM_GETMINMAXINFO: + { + LPMINMAXINFO lpMMI = (LPMINMAXINFO)lParam; + lpMMI->ptMinTrackSize.x = 320; + lpMMI->ptMinTrackSize.y = 240; + return 0; + } + + default: + return DefWindowProc(wnd, message, wParam, lParam); + } +} |
