2
0

Application.cpp 9.7 KB

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