2
0

Application.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 = !mIsPaused || mSingleStep? clock_delta_time : 0.0f;
  140. mSingleStep = false;
  141. // Clear debug lines if we're going to step
  142. if (world_delta_time > 0.0f)
  143. ClearDebugRenderer();
  144. // Update the camera position
  145. if (!mUI->IsVisible())
  146. UpdateCamera(clock_delta_time);
  147. // Start rendering
  148. mRenderer->BeginFrame(mWorldCamera, GetWorldScale());
  149. {
  150. JPH_PROFILE("RenderFrame");
  151. if (!RenderFrame(world_delta_time))
  152. break;
  153. }
  154. // Draw coordinate axis
  155. if (mDebugRendererCleared)
  156. mDebugRenderer->DrawCoordinateSystem(RMat44::sIdentity());
  157. // For next frame: mark that we haven't cleared debug stuff
  158. mDebugRendererCleared = false;
  159. // Draw debug information
  160. static_cast<DebugRendererImp *>(mDebugRenderer)->Draw();
  161. // Draw the frame rate counter
  162. DrawFPS(clock_delta_time);
  163. if (mUI->IsVisible())
  164. {
  165. // Send mouse input to UI
  166. bool left_pressed = mMouse->IsLeftPressed();
  167. if (left_pressed && !mLeftMousePressed)
  168. mUI->MouseDown(mMouse->GetX(), mMouse->GetY());
  169. else if (!left_pressed && mLeftMousePressed)
  170. mUI->MouseUp(mMouse->GetX(), mMouse->GetY());
  171. mLeftMousePressed = left_pressed;
  172. mUI->MouseMove(mMouse->GetX(), mMouse->GetY());
  173. {
  174. // Disable allocation checking
  175. DisableCustomMemoryHook dcmh;
  176. // Update and draw the menu
  177. mUI->Update(clock_delta_time);
  178. mUI->Draw();
  179. }
  180. }
  181. else
  182. {
  183. // Menu not visible, cancel any mouse operations
  184. mUI->MouseCancel();
  185. }
  186. // Show the frame
  187. mRenderer->EndFrame();
  188. // Notify of next frame
  189. JPH_PROFILE_NEXTFRAME();
  190. }
  191. }
  192. }
  193. void Application::GetCameraLocalHeadingAndPitch(float &outHeading, float &outPitch)
  194. {
  195. outHeading = ATan2(mLocalCamera.mForward.GetZ(), mLocalCamera.mForward.GetX());
  196. outPitch = ATan2(mLocalCamera.mForward.GetY(), Vec3(mLocalCamera.mForward.GetX(), 0, mLocalCamera.mForward.GetZ()).Length());
  197. }
  198. void Application::ConvertCameraLocalToWorld(float inCameraHeading, float inCameraPitch)
  199. {
  200. // Convert local to world space using the camera pivot
  201. RMat44 pivot = GetCameraPivot(inCameraHeading, inCameraPitch);
  202. mWorldCamera = mLocalCamera;
  203. mWorldCamera.mPos = pivot * mLocalCamera.mPos;
  204. mWorldCamera.mForward = pivot.Multiply3x3(mLocalCamera.mForward);
  205. mWorldCamera.mUp = pivot.Multiply3x3(mLocalCamera.mUp);
  206. }
  207. void Application::ResetCamera()
  208. {
  209. // Get local space camera state
  210. mLocalCamera = CameraState();
  211. GetInitialCamera(mLocalCamera);
  212. // Convert to world space
  213. float heading, pitch;
  214. GetCameraLocalHeadingAndPitch(heading, pitch);
  215. ConvertCameraLocalToWorld(heading, pitch);
  216. }
  217. // Update camera position
  218. void Application::UpdateCamera(float inDeltaTime)
  219. {
  220. JPH_PROFILE_FUNCTION();
  221. // Determine speed
  222. float speed = GetWorldScale() * mWorldCamera.mFarPlane / 50.0f * inDeltaTime;
  223. bool shift = mKeyboard->IsKeyPressed(DIK_LSHIFT) || mKeyboard->IsKeyPressed(DIK_RSHIFT);
  224. bool control = mKeyboard->IsKeyPressed(DIK_LCONTROL) || mKeyboard->IsKeyPressed(DIK_RCONTROL);
  225. bool alt = mKeyboard->IsKeyPressed(DIK_LALT) || mKeyboard->IsKeyPressed(DIK_RALT);
  226. if (shift) speed *= 10.0f;
  227. else if (control) speed /= 25.0f;
  228. else if (alt) speed = 0.0f;
  229. // Position
  230. Vec3 right = mLocalCamera.mForward.Cross(mLocalCamera.mUp);
  231. if (mKeyboard->IsKeyPressed(DIK_A)) mLocalCamera.mPos -= speed * right;
  232. if (mKeyboard->IsKeyPressed(DIK_D)) mLocalCamera.mPos += speed * right;
  233. if (mKeyboard->IsKeyPressed(DIK_W)) mLocalCamera.mPos += speed * mLocalCamera.mForward;
  234. if (mKeyboard->IsKeyPressed(DIK_S)) mLocalCamera.mPos -= speed * mLocalCamera.mForward;
  235. // Forward
  236. float heading, pitch;
  237. GetCameraLocalHeadingAndPitch(heading, pitch);
  238. heading += DegreesToRadians(mMouse->GetDX() * 0.5f);
  239. pitch = Clamp(pitch - DegreesToRadians(mMouse->GetDY() * 0.5f), -0.49f * JPH_PI, 0.49f * JPH_PI);
  240. mLocalCamera.mForward = Vec3(Cos(pitch) * Cos(heading), Sin(pitch), Cos(pitch) * Sin(heading));
  241. // Convert to world space
  242. ConvertCameraLocalToWorld(heading, pitch);
  243. }
  244. void Application::DrawFPS(float inDeltaTime)
  245. {
  246. JPH_PROFILE_FUNCTION();
  247. // Don't divide by zero
  248. if (inDeltaTime <= 0.0f)
  249. return;
  250. // Switch tho ortho mode
  251. mRenderer->SetOrthoMode();
  252. // Update stats
  253. mTotalDeltaTime += inDeltaTime;
  254. mNumFrames++;
  255. if (mNumFrames > 10)
  256. {
  257. mFPS = mNumFrames / mTotalDeltaTime;
  258. mNumFrames = 0;
  259. mTotalDeltaTime = 0.0f;
  260. }
  261. // Create string
  262. String fps = StringFormat("%.1f", (double)mFPS);
  263. // Get size of text on screen
  264. Float2 text_size = mFont->MeasureText(fps);
  265. int text_w = int(text_size.x * mFont->GetCharHeight());
  266. int text_h = int(text_size.y * mFont->GetCharHeight());
  267. // Draw FPS counter
  268. int x = (mRenderer->GetWindowWidth() - text_w) / 2 - 20;
  269. int y = 10;
  270. mUI->DrawQuad(x - 5, y - 3, text_w + 10, text_h + 6, UITexturedQuad(), Color(0, 0, 0, 128));
  271. mUI->DrawText(x, y, fps, mFont);
  272. // Draw status string
  273. if (!mStatusString.empty())
  274. mUI->DrawText(5, 5, mStatusString, mFont);
  275. // Draw paused string if the app is paused
  276. if (mIsPaused)
  277. {
  278. string_view paused_str = "P: Unpause, ESC: Menu";
  279. Float2 pause_size = mFont->MeasureText(paused_str);
  280. mUI->DrawText(mRenderer->GetWindowWidth() - 5 - int(pause_size.x * mFont->GetCharHeight()), 5, paused_str, mFont);
  281. }
  282. // Restore state
  283. mRenderer->SetProjectionMode();
  284. }