Application.cpp 11 KB

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