Application.cpp 11 KB

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