A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.cc 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #include <time.h>
  2. #include <unistd.h>
  3. #include <vector>
  4. #include <memory>
  5. #include <chrono>
  6. #include <ratio>
  7. #include <SDL2/SDL.h>
  8. #include <SDL2/SDL_image.h>
  9. #include <string.h>
  10. #include <imgui.h>
  11. #include <imgui_sdl/imgui_sdl.h>
  12. #include <swan/swan.h>
  13. using namespace Swan;
  14. #define errassert(expr, str, errfn) do { \
  15. if (!(expr)) { \
  16. panic << (str) << ": " << errfn(); \
  17. return EXIT_FAILURE; \
  18. } \
  19. } while (0)
  20. #define sdlassert(expr, str) errassert(expr, str, SDL_GetError);
  21. #define imgassert(expr, str) errassert(expr, str, IMG_GetError);
  22. // ImGUI and SDL have different numbers for mouse buttons
  23. int sdlButtonToImGuiButton(uint8_t button) {
  24. switch (button) {
  25. case SDL_BUTTON_LEFT:
  26. return 0;
  27. case SDL_BUTTON_RIGHT:
  28. return 1;
  29. case SDL_BUTTON_MIDDLE:
  30. return 2;
  31. case SDL_BUTTON_X1:
  32. return 3;
  33. case SDL_BUTTON_X2:
  34. return 4;
  35. default:
  36. warn << "Unknown mouse button: " << button;
  37. return 4; // Let's call that X2?
  38. }
  39. }
  40. int main(int argc, char **argv) {
  41. uint32_t winflags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
  42. uint32_t renderflags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
  43. float gui_scale = 1;
  44. for (int i = 1; i < argc; ++i) {
  45. if (strcmp(argv[i], "--lodpi") == 0) {
  46. winflags &= ~SDL_WINDOW_ALLOW_HIGHDPI;
  47. } else if (strcmp(argv[i], "--fullscreen") == 0) {
  48. winflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
  49. } else if (strcmp(argv[i], "--no-vsync") == 0) {
  50. renderflags &= ~SDL_RENDERER_PRESENTVSYNC;
  51. } else if (strcmp(argv[i], "--vulkan") == 0) {
  52. winflags |= SDL_WINDOW_VULKAN;
  53. } else if (strcmp(argv[i], "--sw-render") == 0) {
  54. renderflags &= ~SDL_RENDERER_ACCELERATED;
  55. renderflags |= SDL_RENDERER_SOFTWARE;
  56. } else if (strcmp(argv[i], "--2x") == 0) {
  57. gui_scale = 2;
  58. } else {
  59. warn << "Unknown argument: " << argv[i];
  60. }
  61. }
  62. sdlassert(SDL_Init(SDL_INIT_VIDEO) >= 0, "Could not initialize SDL");
  63. Deferred<SDL_Quit> sdl;
  64. int imgflags = IMG_INIT_PNG;
  65. imgassert(IMG_Init(imgflags) == imgflags, "Could not initialize SDL_Image");
  66. Deferred<IMG_Quit> sdl_image;
  67. // Create the window
  68. CPtr<SDL_Window, SDL_DestroyWindow> window(
  69. SDL_CreateWindow(
  70. "Project: SWAN",
  71. SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
  72. (int)(640 * gui_scale), (int)(480 * gui_scale), winflags));
  73. // Load and display application icon
  74. CPtr<SDL_Surface, SDL_FreeSurface> icon(
  75. IMG_Load("assets/icon.png"));
  76. sdlassert(icon, "Could not load icon");
  77. SDL_SetWindowIcon(window.get(), icon.get());
  78. CPtr<SDL_Renderer, SDL_DestroyRenderer> renderer(
  79. SDL_CreateRenderer(window.get(), -1, renderflags));
  80. sdlassert(renderer, "Could not create renderer");
  81. SDL_SetRenderDrawBlendMode(renderer.get(), SDL_BLENDMODE_BLEND);
  82. SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255);
  83. Win win(window.get(), renderer.get(), gui_scale);
  84. // Init ImGUI and ImGUI_SDL
  85. IMGUI_CHECKVERSION();
  86. CPtr<ImGuiContext, ImGui::DestroyContext> context(
  87. ImGui::CreateContext());
  88. ImGuiSDL::Initialize(renderer.get(), (int)win.getPixSize().x, (int)win.getPixSize().y);
  89. Deferred<ImGuiSDL::Deinitialize> imgui_sdl;
  90. info << "Initialized with window size " << win.getPixSize();
  91. // ImGuiIO is to glue SDL and ImGUI together
  92. ImGuiIO& imgui_io = ImGui::GetIO();
  93. imgui_io.BackendPlatformName = "imgui_sdl + Project: SWAN";
  94. // Create a world
  95. Game game(win);
  96. std::vector<std::string> mods{ "core.mod" };
  97. game.createWorld("core::default", mods);
  98. PerfCounter pcounter;
  99. auto prev_time = std::chrono::steady_clock::now();
  100. float fps_acc = 0;
  101. float tick_acc = 0;
  102. int fcount = 0;
  103. int slow_frames = 0;
  104. while (1) {
  105. ZoneScopedN("game loop");
  106. RTClock total_time_clock;
  107. SDL_Event evt;
  108. while (SDL_PollEvent(&evt)) {
  109. switch (evt.type) {
  110. case SDL_QUIT:
  111. goto exit;
  112. break;
  113. case SDL_WINDOWEVENT:
  114. if (evt.window.event == SDL_WINDOWEVENT_RESIZED) {
  115. imgui_io.DisplaySize.x = (float)evt.window.data1;
  116. imgui_io.DisplaySize.y = (float)evt.window.data2;
  117. win.onResize(evt.window.data1, evt.window.data2);
  118. }
  119. break;
  120. case SDL_KEYDOWN:
  121. game.onKeyDown(evt.key.keysym);
  122. break;
  123. case SDL_KEYUP:
  124. game.onKeyUp(evt.key.keysym);
  125. break;
  126. case SDL_MOUSEMOTION:
  127. imgui_io.MousePos.x = (float)evt.motion.x;
  128. imgui_io.MousePos.y = (float)evt.motion.y;
  129. if (!imgui_io.WantCaptureMouse)
  130. game.onMouseMove(evt.motion.x, evt.motion.y);
  131. break;
  132. case SDL_MOUSEBUTTONDOWN:
  133. imgui_io.MouseDown[sdlButtonToImGuiButton(evt.button.button)] = true;
  134. if (!imgui_io.WantCaptureMouse)
  135. game.onMouseDown(evt.button.x, evt.button.y, evt.button.button);
  136. break;
  137. case SDL_MOUSEBUTTONUP:
  138. imgui_io.MouseDown[sdlButtonToImGuiButton(evt.button.button)] = false;
  139. if (!imgui_io.WantCaptureMouse)
  140. game.onMouseUp(evt.button.x, evt.button.y, evt.button.button);
  141. break;
  142. case SDL_MOUSEWHEEL:
  143. imgui_io.MouseWheel += (float)evt.wheel.y;
  144. if (!imgui_io.WantCaptureMouse)
  145. game.onScrollWheel(evt.wheel.y);
  146. break;
  147. }
  148. }
  149. auto now = std::chrono::steady_clock::now();
  150. std::chrono::duration<float> dur(now - prev_time);
  151. prev_time = now;
  152. float dt = dur.count();
  153. // Display FPS
  154. fps_acc += dt;
  155. fcount += 1;
  156. if (fps_acc >= 4) {
  157. info << "FPS: " << fcount / 4.0;
  158. fps_acc -= 4;
  159. fcount = 0;
  160. }
  161. // We want to warn if one frame takes over 0.1 seconds...
  162. if (dt > 0.1) {
  163. if (slow_frames == 0)
  164. warn << "Delta time too high! (" << dt << "s)";
  165. slow_frames += 1;
  166. // And we never want to do physics as if our one frame is greater than
  167. // 0.5 seconds.
  168. if (dt > 0.5)
  169. dt = 0.5;
  170. } else if (slow_frames > 0) {
  171. if (slow_frames > 1)
  172. warn << slow_frames << " consecutive slow frames.";
  173. slow_frames = 0;
  174. }
  175. // Simple case: we can keep up, only need one physics update
  176. RTClock update_clock;
  177. if (dt <= 1 / 25.0) {
  178. ZoneScopedN("game update");
  179. pcounter.countGameUpdatesPerFrame(1);
  180. game.update(dt);
  181. // Complex case: run multiple steps this iteration
  182. } else {
  183. int count = (int)ceil(dt / (1/30.0));
  184. pcounter.countGameUpdatesPerFrame(count);
  185. float delta = dt / (float)count;
  186. info << "Delta time " << dt << "s. Running " << count
  187. << " updates in one frame, with a delta as if we had "
  188. << 1.0 / delta << " FPS.";
  189. for (int i = 0; i < count; ++i) {
  190. ZoneScopedN("game update");
  191. game.update(delta);
  192. }
  193. }
  194. pcounter.countGameUpdate(update_clock.duration());
  195. // Tick at a consistent TICK_RATE
  196. tick_acc += dt;
  197. while (tick_acc >= 1.0 / TICK_RATE) {
  198. ZoneScopedN("game tick");
  199. tick_acc -= 1.0 / TICK_RATE;
  200. RTClock tick_clock;
  201. game.tick(1.0 / TICK_RATE);
  202. pcounter.countGameTick(tick_clock.duration());
  203. }
  204. {
  205. auto [r, g, b, a] = game.backgroundColor();
  206. RenderDrawColor c(renderer.get(), r, g, b, a);
  207. SDL_RenderClear(renderer.get());
  208. }
  209. // ImGUI
  210. imgui_io.DeltaTime = dt;
  211. ImGui::NewFrame();
  212. {
  213. ZoneScopedN("game draw");
  214. RTClock draw_clock;
  215. game.draw();
  216. pcounter.countGameDraw(draw_clock.duration());
  217. }
  218. pcounter.countFrameTime(total_time_clock.duration());
  219. pcounter.render();
  220. // Render ImGUI
  221. {
  222. ZoneScopedN("imgui render");
  223. ImGui::Render();
  224. ImGuiSDL::Render(ImGui::GetDrawData());
  225. }
  226. RTClock present_clock;
  227. {
  228. ZoneScopedN("render present");
  229. SDL_RenderPresent(renderer.get());
  230. }
  231. FrameMark
  232. pcounter.countRenderPresent(present_clock.duration());
  233. pcounter.countTotalTime(total_time_clock.duration());
  234. }
  235. exit:
  236. return EXIT_SUCCESS;
  237. }