Application.cpp 11 KB

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