Application.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Application/Application.h>
  6. #include <UI/UIManager.h>
  7. #include <Application/DebugUI.h>
  8. #include <Utils/Log.h>
  9. #include <Utils/CustomMemoryHook.h>
  10. #include <Jolt/Core/FPException.h>
  11. #include <Jolt/Core/Factory.h>
  12. #include <Jolt/RegisterTypes.h>
  13. #include <Renderer/DebugRendererImp.h>
  14. #include <crtdbg.h>
  15. #ifdef JPH_ENABLE_VULKAN
  16. #include <Renderer/VK/RendererVK.h>
  17. #else
  18. #include <Renderer/DX12/RendererDX12.h>
  19. #endif
  20. // Constructor
  21. Application::Application() :
  22. mDebugRenderer(nullptr),
  23. mRenderer(nullptr),
  24. mKeyboard(nullptr),
  25. mMouse(nullptr),
  26. mUI(nullptr),
  27. mDebugUI(nullptr)
  28. {
  29. #if defined(_DEBUG)
  30. // Enable leak detection
  31. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  32. #endif
  33. // Register trace implementation
  34. Trace = TraceImpl;
  35. #ifdef JPH_ENABLE_ASSERTS
  36. // Register assert failed handler
  37. AssertFailed = [](const char *inExpression, const char *inMessage, const char *inFile, uint inLine)
  38. {
  39. Trace("%s (%d): Assert Failed: %s", inFile, inLine, inMessage != nullptr? inMessage : inExpression);
  40. return true;
  41. };
  42. #endif // JPH_ENABLE_ASSERTS
  43. // Create factory
  44. Factory::sInstance = new Factory;
  45. // Register physics types with the factory
  46. RegisterTypes();
  47. {
  48. // Disable allocation checking
  49. DisableCustomMemoryHook dcmh;
  50. // Create renderer
  51. #ifdef JPH_ENABLE_VULKAN
  52. mRenderer = new RendererVK;
  53. #else
  54. mRenderer = new RendererDX12;
  55. #endif
  56. mRenderer->Initialize();
  57. // Create font
  58. Font *font = new Font(mRenderer);
  59. font->Create("Arial", 24);
  60. mFont = font;
  61. // Init debug renderer
  62. mDebugRenderer = new DebugRendererImp(mRenderer, mFont);
  63. // Init keyboard
  64. mKeyboard = new Keyboard;
  65. mKeyboard->Initialize(mRenderer);
  66. // Init mouse
  67. mMouse = new Mouse;
  68. mMouse->Initialize(mRenderer);
  69. // Init UI
  70. mUI = new UIManager(mRenderer);
  71. mUI->SetVisible(false);
  72. // Init debug UI
  73. mDebugUI = new DebugUI(mUI, mFont);
  74. }
  75. // Get initial time
  76. mLastUpdateTime = chrono::high_resolution_clock::now();
  77. }
  78. // Destructor
  79. Application::~Application()
  80. {
  81. {
  82. // Disable allocation checking
  83. DisableCustomMemoryHook dcmh;
  84. delete mDebugUI;
  85. delete mUI;
  86. delete mMouse;
  87. delete mKeyboard;
  88. delete mDebugRenderer;
  89. mFont = nullptr;
  90. delete mRenderer;
  91. }
  92. // Unregisters all types with the factory and cleans up the default material
  93. UnregisterTypes();
  94. delete Factory::sInstance;
  95. Factory::sInstance = nullptr;
  96. }
  97. // Clear debug lines / triangles / texts that have been accumulated
  98. void Application::ClearDebugRenderer()
  99. {
  100. JPH_PROFILE_FUNCTION();
  101. static_cast<DebugRendererImp *>(mDebugRenderer)->Clear();
  102. mDebugRendererCleared = true;
  103. }
  104. // Main loop
  105. void Application::Run()
  106. {
  107. // Set initial camera position
  108. ResetCamera();
  109. // Main message loop
  110. MSG msg;
  111. memset(&msg, 0, sizeof(msg));
  112. while (WM_QUIT != msg.message)
  113. {
  114. if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
  115. {
  116. JPH_PROFILE("DispatchMessage");
  117. TranslateMessage(&msg);
  118. DispatchMessage(&msg);
  119. }
  120. else
  121. {
  122. // Get new input
  123. mKeyboard->Poll();
  124. mMouse->Poll();
  125. // Handle keyboard input
  126. for (int key = mKeyboard->GetFirstKey(); key != 0; key = mKeyboard->GetNextKey())
  127. switch (key)
  128. {
  129. case DIK_P:
  130. mIsPaused = !mIsPaused;
  131. break;
  132. case DIK_O:
  133. mSingleStep = true;
  134. break;
  135. case DIK_T:
  136. // Dump timing info to file
  137. JPH_PROFILE_DUMP();
  138. break;
  139. case DIK_ESCAPE:
  140. mDebugUI->ToggleVisibility();
  141. break;
  142. }
  143. // Calculate delta time
  144. chrono::high_resolution_clock::time_point time = chrono::high_resolution_clock::now();
  145. chrono::microseconds delta = chrono::duration_cast<chrono::microseconds>(time - mLastUpdateTime);
  146. mLastUpdateTime = time;
  147. float clock_delta_time = 1.0e-6f * delta.count();
  148. float world_delta_time = 0.0f;
  149. if (mRequestedDeltaTime <= 0.0f)
  150. {
  151. // If no fixed frequency update is requested, update with variable time step
  152. world_delta_time = !mIsPaused || mSingleStep? clock_delta_time : 0.0f;
  153. mResidualDeltaTime = 0.0f;
  154. }
  155. else
  156. {
  157. // Else use fixed time steps
  158. if (mSingleStep)
  159. {
  160. // Single step
  161. world_delta_time = mRequestedDeltaTime;
  162. }
  163. else if (!mIsPaused)
  164. {
  165. // Calculate how much time has passed since the last render
  166. world_delta_time = clock_delta_time + mResidualDeltaTime;
  167. if (world_delta_time < mRequestedDeltaTime)
  168. {
  169. // Too soon, set the residual time and don't update
  170. mResidualDeltaTime = world_delta_time;
  171. world_delta_time = 0.0f;
  172. }
  173. else
  174. {
  175. // Update and clamp the residual time to a full update to avoid spiral of death
  176. mResidualDeltaTime = min(mRequestedDeltaTime, world_delta_time - mRequestedDeltaTime);
  177. world_delta_time = mRequestedDeltaTime;
  178. }
  179. }
  180. }
  181. mSingleStep = false;
  182. // Clear debug lines if we're going to step
  183. if (world_delta_time > 0.0f)
  184. ClearDebugRenderer();
  185. {
  186. JPH_PROFILE("UpdateFrame");
  187. if (!UpdateFrame(world_delta_time))
  188. break;
  189. }
  190. // Draw coordinate axis
  191. if (mDebugRendererCleared)
  192. mDebugRenderer->DrawCoordinateSystem(RMat44::sIdentity());
  193. // For next frame: mark that we haven't cleared debug stuff
  194. mDebugRendererCleared = false;
  195. // Update the camera position
  196. if (!mUI->IsVisible())
  197. UpdateCamera(clock_delta_time);
  198. // Start rendering
  199. mRenderer->BeginFrame(mWorldCamera, GetWorldScale());
  200. // Draw from light
  201. static_cast<DebugRendererImp *>(mDebugRenderer)->DrawShadowPass();
  202. // Start drawing normally
  203. mRenderer->EndShadowPass();
  204. // Draw debug information
  205. static_cast<DebugRendererImp *>(mDebugRenderer)->Draw();
  206. // Draw the frame rate counter
  207. DrawFPS(clock_delta_time);
  208. if (mUI->IsVisible())
  209. {
  210. // Send mouse input to UI
  211. bool left_pressed = mMouse->IsLeftPressed();
  212. if (left_pressed && !mLeftMousePressed)
  213. mUI->MouseDown(mMouse->GetX(), mMouse->GetY());
  214. else if (!left_pressed && mLeftMousePressed)
  215. mUI->MouseUp(mMouse->GetX(), mMouse->GetY());
  216. mLeftMousePressed = left_pressed;
  217. mUI->MouseMove(mMouse->GetX(), mMouse->GetY());
  218. {
  219. // Disable allocation checking
  220. DisableCustomMemoryHook dcmh;
  221. // Update and draw the menu
  222. mUI->Update(clock_delta_time);
  223. mUI->Draw();
  224. }
  225. }
  226. else
  227. {
  228. // Menu not visible, cancel any mouse operations
  229. mUI->MouseCancel();
  230. }
  231. // Show the frame
  232. mRenderer->EndFrame();
  233. // Notify of next frame
  234. JPH_PROFILE_NEXTFRAME();
  235. }
  236. }
  237. }
  238. void Application::GetCameraLocalHeadingAndPitch(float &outHeading, float &outPitch)
  239. {
  240. outHeading = ATan2(mLocalCamera.mForward.GetZ(), mLocalCamera.mForward.GetX());
  241. outPitch = ATan2(mLocalCamera.mForward.GetY(), Vec3(mLocalCamera.mForward.GetX(), 0, mLocalCamera.mForward.GetZ()).Length());
  242. }
  243. void Application::ConvertCameraLocalToWorld(float inCameraHeading, float inCameraPitch)
  244. {
  245. // Convert local to world space using the camera pivot
  246. RMat44 pivot = GetCameraPivot(inCameraHeading, inCameraPitch);
  247. mWorldCamera = mLocalCamera;
  248. mWorldCamera.mPos = pivot * mLocalCamera.mPos;
  249. mWorldCamera.mForward = pivot.Multiply3x3(mLocalCamera.mForward);
  250. mWorldCamera.mUp = pivot.Multiply3x3(mLocalCamera.mUp);
  251. }
  252. void Application::ResetCamera()
  253. {
  254. // Get local space camera state
  255. mLocalCamera = CameraState();
  256. GetInitialCamera(mLocalCamera);
  257. // Convert to world space
  258. float heading, pitch;
  259. GetCameraLocalHeadingAndPitch(heading, pitch);
  260. ConvertCameraLocalToWorld(heading, pitch);
  261. }
  262. // Update camera position
  263. void Application::UpdateCamera(float inDeltaTime)
  264. {
  265. JPH_PROFILE_FUNCTION();
  266. // Determine speed
  267. float speed = 20.0f * GetWorldScale() * inDeltaTime;
  268. bool shift = mKeyboard->IsKeyPressed(DIK_LSHIFT) || mKeyboard->IsKeyPressed(DIK_RSHIFT);
  269. bool control = mKeyboard->IsKeyPressed(DIK_LCONTROL) || mKeyboard->IsKeyPressed(DIK_RCONTROL);
  270. bool alt = mKeyboard->IsKeyPressed(DIK_LALT) || mKeyboard->IsKeyPressed(DIK_RALT);
  271. if (shift) speed *= 10.0f;
  272. else if (control) speed /= 25.0f;
  273. else if (alt) speed = 0.0f;
  274. // Position
  275. Vec3 right = mLocalCamera.mForward.Cross(mLocalCamera.mUp);
  276. if (mKeyboard->IsKeyPressed(DIK_A)) mLocalCamera.mPos -= speed * right;
  277. if (mKeyboard->IsKeyPressed(DIK_D)) mLocalCamera.mPos += speed * right;
  278. if (mKeyboard->IsKeyPressed(DIK_W)) mLocalCamera.mPos += speed * mLocalCamera.mForward;
  279. if (mKeyboard->IsKeyPressed(DIK_S)) mLocalCamera.mPos -= speed * mLocalCamera.mForward;
  280. // Forward
  281. float heading, pitch;
  282. GetCameraLocalHeadingAndPitch(heading, pitch);
  283. heading += DegreesToRadians(mMouse->GetDX() * 0.5f);
  284. pitch = Clamp(pitch - DegreesToRadians(mMouse->GetDY() * 0.5f), -0.49f * JPH_PI, 0.49f * JPH_PI);
  285. mLocalCamera.mForward = Vec3(Cos(pitch) * Cos(heading), Sin(pitch), Cos(pitch) * Sin(heading));
  286. // Convert to world space
  287. ConvertCameraLocalToWorld(heading, pitch);
  288. }
  289. void Application::DrawFPS(float inDeltaTime)
  290. {
  291. JPH_PROFILE_FUNCTION();
  292. // Don't divide by zero
  293. if (inDeltaTime <= 0.0f)
  294. return;
  295. // Switch tho ortho mode
  296. mRenderer->SetOrthoMode();
  297. // Update stats
  298. mTotalDeltaTime += inDeltaTime;
  299. mNumFrames++;
  300. if (mNumFrames > 10)
  301. {
  302. mFPS = mNumFrames / mTotalDeltaTime;
  303. mNumFrames = 0;
  304. mTotalDeltaTime = 0.0f;
  305. }
  306. // Create string
  307. String fps = StringFormat("%.1f", (double)mFPS);
  308. // Get size of text on screen
  309. Float2 text_size = mFont->MeasureText(fps);
  310. int text_w = int(text_size.x * mFont->GetCharHeight());
  311. int text_h = int(text_size.y * mFont->GetCharHeight());
  312. // Draw FPS counter
  313. int x = (mRenderer->GetWindowWidth() - text_w) / 2 - 20;
  314. int y = 10;
  315. mUI->DrawQuad(x - 5, y - 3, text_w + 10, text_h + 6, UITexturedQuad(), Color(0, 0, 0, 128));
  316. mUI->DrawText(x, y, fps, mFont);
  317. // Draw status string
  318. if (!mStatusString.empty())
  319. mUI->DrawText(5, 5, mStatusString, mFont);
  320. // Draw paused string if the app is paused
  321. if (mIsPaused)
  322. {
  323. string_view paused_str = "P: Unpause, ESC: Menu";
  324. Float2 pause_size = mFont->MeasureText(paused_str);
  325. mUI->DrawText(mRenderer->GetWindowWidth() - 5 - int(pause_size.x * mFont->GetCharHeight()), 5, paused_str, mFont);
  326. }
  327. // Restore state
  328. mRenderer->SetProjectionMode();
  329. }