Application.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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/Factory.h>
  11. #include <Jolt/RegisterTypes.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. #ifdef JPH_PLATFORM_WINDOWS
  14. #include <crtdbg.h>
  15. #include <Input/Win/KeyboardWin.h>
  16. #include <Input/Win/MouseWin.h>
  17. #include <Window/ApplicationWindowWin.h>
  18. #elif defined(JPH_PLATFORM_LINUX)
  19. #include <Input/Linux/KeyboardLinux.h>
  20. #include <Input/Linux/MouseLinux.h>
  21. #include <Window/ApplicationWindowLinux.h>
  22. #elif defined(JPH_PLATFORM_MACOS)
  23. #include <Input/MacOS/KeyboardMacOS.h>
  24. #include <Input/MacOS/MouseMacOS.h>
  25. #include <Window/ApplicationWindowMacOS.h>
  26. #endif
  27. #ifdef JPH_USE_VK
  28. extern Renderer *CreateRendererVK();
  29. #endif
  30. JPH_GCC_SUPPRESS_WARNING("-Wswitch")
  31. // Constructor
  32. Application::Application(const char *inApplicationName, [[maybe_unused]] const String &inCommandLine) :
  33. mDebugRenderer(nullptr),
  34. mRenderer(nullptr),
  35. mKeyboard(nullptr),
  36. mMouse(nullptr),
  37. mUI(nullptr),
  38. mDebugUI(nullptr)
  39. {
  40. #if defined(JPH_PLATFORM_WINDOWS) && defined(_DEBUG)
  41. // Enable leak detection
  42. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  43. #endif
  44. // Register trace implementation
  45. Trace = TraceImpl;
  46. #ifdef JPH_ENABLE_ASSERTS
  47. // Register assert failed handler
  48. AssertFailed = [](const char *inExpression, const char *inMessage, const char *inFile, uint inLine)
  49. {
  50. Trace("%s (%d): Assert Failed: %s", inFile, inLine, inMessage != nullptr? inMessage : inExpression);
  51. return true;
  52. };
  53. #endif // JPH_ENABLE_ASSERTS
  54. // Create factory
  55. Factory::sInstance = new Factory;
  56. // Register physics types with the factory
  57. RegisterTypes();
  58. // Explode command line into separate arguments
  59. Array<String> args;
  60. StringToVector(ToLower(inCommandLine), args, " ");
  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(inApplicationName);
  75. // Create renderer
  76. #ifdef JPH_USE_VK
  77. if (std::find(args.begin(), args.end(), "-vulkan") != args.end())
  78. mRenderer = CreateRendererVK();
  79. else
  80. #endif
  81. mRenderer = Renderer::sCreate();
  82. mRenderer->Initialize(mWindow);
  83. // Create font
  84. Font *font = new Font(mRenderer);
  85. font->Create("Roboto-Regular", 24);
  86. mFont = font;
  87. // Init debug renderer
  88. mDebugRenderer = new DebugRendererImp(mRenderer, mFont);
  89. // Init keyboard
  90. #ifdef JPH_PLATFORM_WINDOWS
  91. mKeyboard = new KeyboardWin;
  92. #elif defined(JPH_PLATFORM_LINUX)
  93. mKeyboard = new KeyboardLinux;
  94. #elif defined(JPH_PLATFORM_MACOS)
  95. mKeyboard = new KeyboardMacOS;
  96. #else
  97. #error No keyboard defined
  98. #endif
  99. mKeyboard->Initialize(mWindow);
  100. // Init mouse
  101. #ifdef JPH_PLATFORM_WINDOWS
  102. mMouse = new MouseWin;
  103. #elif defined(JPH_PLATFORM_LINUX)
  104. mMouse = new MouseLinux;
  105. #elif defined(JPH_PLATFORM_MACOS)
  106. mMouse = new MouseMacOS;
  107. #else
  108. #error No mouse defined
  109. #endif
  110. mMouse->Initialize(mWindow);
  111. // Init UI
  112. mUI = new UIManager(mRenderer);
  113. mUI->SetVisible(false);
  114. // Init debug UI
  115. mDebugUI = new DebugUI(mUI, mFont);
  116. }
  117. // Get initial time
  118. mLastUpdateTime = chrono::high_resolution_clock::now();
  119. }
  120. // Destructor
  121. Application::~Application()
  122. {
  123. {
  124. // Disable allocation checking
  125. DisableCustomMemoryHook dcmh;
  126. delete mDebugUI;
  127. delete mUI;
  128. delete mMouse;
  129. delete mKeyboard;
  130. delete mDebugRenderer;
  131. mFont = nullptr;
  132. delete mRenderer;
  133. delete mWindow;
  134. }
  135. // Unregisters all types with the factory and cleans up the default material
  136. UnregisterTypes();
  137. delete Factory::sInstance;
  138. Factory::sInstance = nullptr;
  139. }
  140. String Application::sCreateCommandLine(int inArgC, char **inArgV)
  141. {
  142. String command_line;
  143. for (int i = 0; i < inArgC; ++i)
  144. {
  145. if (i > 0)
  146. command_line += " ";
  147. command_line += inArgV[i];
  148. }
  149. return command_line;
  150. }
  151. // Clear debug lines / triangles / texts that have been accumulated
  152. void Application::ClearDebugRenderer()
  153. {
  154. JPH_PROFILE_FUNCTION();
  155. static_cast<DebugRendererImp *>(mDebugRenderer)->Clear();
  156. mDebugRendererCleared = true;
  157. }
  158. // Main loop
  159. void Application::Run()
  160. {
  161. // Set initial camera position
  162. ResetCamera();
  163. // Enter the main loop
  164. mWindow->MainLoop([this]() { return RenderFrame(); });
  165. }
  166. bool Application::RenderFrame()
  167. {
  168. // Get new input
  169. mKeyboard->Poll();
  170. mMouse->Poll();
  171. // Handle keyboard input
  172. for (EKey key = mKeyboard->GetFirstKey(); key != EKey::Invalid; key = mKeyboard->GetNextKey())
  173. switch (key)
  174. {
  175. case EKey::P:
  176. mIsPaused = !mIsPaused;
  177. break;
  178. case EKey::O:
  179. mSingleStep = true;
  180. break;
  181. case EKey::T:
  182. // Dump timing info to file
  183. JPH_PROFILE_DUMP();
  184. break;
  185. case EKey::Escape:
  186. mDebugUI->ToggleVisibility();
  187. break;
  188. }
  189. // Calculate delta time
  190. chrono::high_resolution_clock::time_point time = chrono::high_resolution_clock::now();
  191. chrono::microseconds delta = chrono::duration_cast<chrono::microseconds>(time - mLastUpdateTime);
  192. mLastUpdateTime = time;
  193. float clock_delta_time = 1.0e-6f * delta.count();
  194. float world_delta_time = 0.0f;
  195. if (mRequestedDeltaTime <= 0.0f)
  196. {
  197. // If no fixed frequency update is requested, update with variable time step
  198. world_delta_time = !mIsPaused || mSingleStep? clock_delta_time : 0.0f;
  199. mResidualDeltaTime = 0.0f;
  200. }
  201. else
  202. {
  203. // Else use fixed time steps
  204. if (mSingleStep)
  205. {
  206. // Single step
  207. world_delta_time = mRequestedDeltaTime;
  208. }
  209. else if (!mIsPaused)
  210. {
  211. // Calculate how much time has passed since the last render
  212. world_delta_time = clock_delta_time + mResidualDeltaTime;
  213. if (world_delta_time < mRequestedDeltaTime)
  214. {
  215. // Too soon, set the residual time and don't update
  216. mResidualDeltaTime = world_delta_time;
  217. world_delta_time = 0.0f;
  218. }
  219. else
  220. {
  221. // Update and clamp the residual time to a full update to avoid spiral of death
  222. mResidualDeltaTime = min(mRequestedDeltaTime, world_delta_time - mRequestedDeltaTime);
  223. world_delta_time = mRequestedDeltaTime;
  224. }
  225. }
  226. }
  227. mSingleStep = false;
  228. // Clear debug lines if we're going to step
  229. if (world_delta_time > 0.0f)
  230. ClearDebugRenderer();
  231. {
  232. JPH_PROFILE("UpdateFrame");
  233. if (!UpdateFrame(world_delta_time))
  234. return false;
  235. }
  236. // Draw coordinate axis
  237. if (mDebugRendererCleared)
  238. mDebugRenderer->DrawCoordinateSystem(RMat44::sIdentity());
  239. // For next frame: mark that we haven't cleared debug stuff
  240. mDebugRendererCleared = false;
  241. // Update the camera position
  242. if (!mUI->IsVisible())
  243. UpdateCamera(clock_delta_time);
  244. // Start rendering
  245. if (!mRenderer->BeginFrame(mWorldCamera, GetWorldScale()))
  246. return true;
  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. }