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 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 guiScale = 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. guiScale = 2;
  58. } else if (strcmp(argv[i], "--gles") == 0) {
  59. SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengles2");
  60. } else {
  61. warn << "Unknown argument: " << argv[i];
  62. }
  63. }
  64. sdlassert(SDL_Init(SDL_INIT_VIDEO) >= 0, "Could not initialize SDL");
  65. Deferred<SDL_Quit> sdl;
  66. int imgFlags = IMG_INIT_PNG;
  67. imgassert(IMG_Init(imgFlags) == imgFlags, "Could not initialize SDL_Image");
  68. Deferred<IMG_Quit> sdlImage;
  69. // Create the window
  70. CPtr<SDL_Window, SDL_DestroyWindow> window(
  71. SDL_CreateWindow(
  72. "Project: SWAN",
  73. SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
  74. (int)(640 * guiScale), (int)(480 * guiScale), winFlags));
  75. // Load and display application icon
  76. CPtr<SDL_Surface, SDL_FreeSurface> icon(
  77. IMG_Load("assets/icon.png"));
  78. sdlassert(icon, "Could not load icon");
  79. SDL_SetWindowIcon(window.get(), icon.get());
  80. CPtr<SDL_Renderer, SDL_DestroyRenderer> renderer(
  81. SDL_CreateRenderer(window.get(), -1, renderFlags));
  82. sdlassert(renderer, "Could not create renderer");
  83. SDL_SetRenderDrawBlendMode(renderer.get(), SDL_BLENDMODE_BLEND);
  84. SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255);
  85. Win win(window.get(), renderer.get(), guiScale);
  86. // Init ImGUI and ImGUI_SDL
  87. IMGUI_CHECKVERSION();
  88. CPtr<ImGuiContext, ImGui::DestroyContext> context(
  89. ImGui::CreateContext());
  90. ImGuiSDL::Initialize(renderer.get(), (int)win.getPixSize().x, (int)win.getPixSize().y);
  91. Deferred<ImGuiSDL::Deinitialize> imguiSDL;
  92. info << "Initialized with window size " << win.getPixSize();
  93. // ImGuiIO is to glue SDL and ImGUI together
  94. ImGuiIO& imguiIO = ImGui::GetIO();
  95. imguiIO.BackendPlatformName = "imgui_sdl + Project: SWAN";
  96. // Create a world
  97. Game game(win);
  98. std::vector<std::string> mods{ "core.mod" };
  99. game.createWorld("core::default", mods);
  100. auto prevTime = std::chrono::steady_clock::now();
  101. float fpsAcc = 0;
  102. float tickAcc = 0;
  103. int fCount = 0;
  104. int slowFrames = 0;
  105. while (1) {
  106. ZoneScopedN("game loop");
  107. RTClock totalTimeClock;
  108. SDL_Event evt;
  109. while (SDL_PollEvent(&evt)) {
  110. switch (evt.type) {
  111. case SDL_QUIT:
  112. goto exit;
  113. break;
  114. case SDL_WINDOWEVENT:
  115. if (evt.window.event == SDL_WINDOWEVENT_RESIZED) {
  116. imguiIO.DisplaySize.x = (float)evt.window.data1;
  117. imguiIO.DisplaySize.y = (float)evt.window.data2;
  118. win.onResize(evt.window.data1, evt.window.data2);
  119. }
  120. break;
  121. case SDL_KEYDOWN:
  122. game.onKeyDown(evt.key.keysym);
  123. break;
  124. case SDL_KEYUP:
  125. game.onKeyUp(evt.key.keysym);
  126. break;
  127. case SDL_MOUSEMOTION:
  128. imguiIO.MousePos.x = (float)evt.motion.x;
  129. imguiIO.MousePos.y = (float)evt.motion.y;
  130. if (!imguiIO.WantCaptureMouse)
  131. game.onMouseMove(evt.motion.x, evt.motion.y);
  132. break;
  133. case SDL_MOUSEBUTTONDOWN:
  134. imguiIO.MouseDown[sdlButtonToImGuiButton(evt.button.button)] = true;
  135. if (!imguiIO.WantCaptureMouse)
  136. game.onMouseDown(evt.button.x, evt.button.y, evt.button.button);
  137. break;
  138. case SDL_MOUSEBUTTONUP:
  139. imguiIO.MouseDown[sdlButtonToImGuiButton(evt.button.button)] = false;
  140. if (!imguiIO.WantCaptureMouse)
  141. game.onMouseUp(evt.button.x, evt.button.y, evt.button.button);
  142. break;
  143. case SDL_MOUSEWHEEL:
  144. imguiIO.MouseWheel += (float)evt.wheel.y;
  145. if (!imguiIO.WantCaptureMouse)
  146. game.onScrollWheel(evt.wheel.y);
  147. break;
  148. }
  149. }
  150. auto now = std::chrono::steady_clock::now();
  151. std::chrono::duration<float> dur(now - prevTime);
  152. prevTime = now;
  153. float dt = dur.count();
  154. // Display FPS
  155. fpsAcc += dt;
  156. fCount += 1;
  157. if (fpsAcc >= 4) {
  158. info << "FPS: " << fCount / 4.0;
  159. fpsAcc -= 4;
  160. fCount = 0;
  161. }
  162. // We want to warn if one frame takes over 0.1 seconds...
  163. if (dt > 0.1) {
  164. if (slowFrames == 0)
  165. warn << "Delta time too high! (" << dt << "s)";
  166. slowFrames += 1;
  167. // And we never want to do physics as if our one frame is greater than
  168. // 0.5 seconds.
  169. if (dt > 0.5)
  170. dt = 0.5;
  171. } else if (slowFrames > 0) {
  172. if (slowFrames > 1)
  173. warn << slowFrames << " consecutive slow frames.";
  174. slowFrames = 0;
  175. }
  176. // Simple case: we can keep up, only need one physics update
  177. RTClock updateClock;
  178. if (dt <= 1 / 25.0) {
  179. ZoneScopedN("game update");
  180. game.update(dt);
  181. // Complex case: run multiple steps this iteration
  182. } else {
  183. int count = (int)ceil(dt / (1/30.0));
  184. float delta = dt / (float)count;
  185. info << "Delta time " << dt << "s. Running " << count
  186. << " updates in one frame, with a delta as if we had "
  187. << 1.0 / delta << " FPS.";
  188. for (int i = 0; i < count; ++i) {
  189. ZoneScopedN("game update");
  190. game.update(delta);
  191. }
  192. }
  193. // Tick at a consistent TICK_RATE
  194. tickAcc += dt;
  195. while (tickAcc >= 1.0 / TICK_RATE) {
  196. ZoneScopedN("game tick");
  197. tickAcc -= 1.0 / TICK_RATE;
  198. RTClock tick_clock;
  199. game.tick(1.0 / TICK_RATE);
  200. }
  201. {
  202. auto [r, g, b, a] = game.backgroundColor();
  203. RenderDrawColor c(renderer.get(), r, g, b, a);
  204. SDL_RenderClear(renderer.get());
  205. }
  206. // ImGUI
  207. imguiIO.DeltaTime = dt;
  208. ImGui::NewFrame();
  209. {
  210. ZoneScopedN("game draw");
  211. RTClock drawClock;
  212. game.draw();
  213. }
  214. // Render ImGUI
  215. {
  216. ZoneScopedN("imgui render");
  217. ImGui::Render();
  218. ImGuiSDL::Render(ImGui::GetDrawData());
  219. }
  220. RTClock presentClock;
  221. {
  222. ZoneScopedN("render present");
  223. SDL_RenderPresent(renderer.get());
  224. }
  225. FrameMark
  226. }
  227. exit:
  228. return EXIT_SUCCESS;
  229. }