main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #ifdef _MSC_VER
  2. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  3. #include <Windows.h>
  4. #endif
  5. #define STB_IMAGE_IMPLEMENTATION
  6. #include "../shared/stb_image.h" // for .png loading
  7. #include "../../imgui.h"
  8. // glew & glfw
  9. #define GLEW_STATIC
  10. #include <GL/glew.h>
  11. #include <GLFW/glfw3.h>
  12. #ifdef _MSC_VER
  13. #define GLFW_EXPOSE_NATIVE_WIN32
  14. #define GLFW_EXPOSE_NATIVE_WGL
  15. #include <GLFW/glfw3native.h>
  16. #endif
  17. static GLFWwindow* window;
  18. static GLuint fontTex;
  19. static bool mousePressed[2] = { false, false };
  20. static ImVec2 mousePosScale(1.0f, 1.0f);
  21. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  22. // If text or lines are blurry when integrating ImGui in your engine:
  23. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  24. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
  25. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  26. {
  27. if (cmd_lists_count == 0)
  28. return;
  29. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  30. // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
  31. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
  32. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  33. glEnable(GL_BLEND);
  34. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  35. glDisable(GL_CULL_FACE);
  36. glDisable(GL_DEPTH_TEST);
  37. glEnable(GL_SCISSOR_TEST);
  38. glEnableClientState(GL_VERTEX_ARRAY);
  39. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  40. glEnableClientState(GL_COLOR_ARRAY);
  41. // Setup texture
  42. glBindTexture(GL_TEXTURE_2D, fontTex);
  43. glEnable(GL_TEXTURE_2D);
  44. // Setup orthographic projection matrix
  45. const float width = ImGui::GetIO().DisplaySize.x;
  46. const float height = ImGui::GetIO().DisplaySize.y;
  47. glMatrixMode(GL_PROJECTION);
  48. glPushMatrix();
  49. glLoadIdentity();
  50. glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
  51. glMatrixMode(GL_MODELVIEW);
  52. glPushMatrix();
  53. glLoadIdentity();
  54. // Render command lists
  55. for (int n = 0; n < cmd_lists_count; n++)
  56. {
  57. const ImDrawList* cmd_list = cmd_lists[n];
  58. const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->vtx_buffer.front();
  59. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, pos)));
  60. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, uv)));
  61. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, col)));
  62. int vtx_offset = 0;
  63. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  64. {
  65. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  66. glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
  67. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  68. vtx_offset += pcmd->vtx_count;
  69. }
  70. }
  71. // Restore modified state
  72. glDisableClientState(GL_COLOR_ARRAY);
  73. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  74. glDisableClientState(GL_VERTEX_ARRAY);
  75. glMatrixMode(GL_MODELVIEW);
  76. glPopMatrix();
  77. glMatrixMode(GL_PROJECTION);
  78. glPopMatrix();
  79. glPopAttrib();
  80. }
  81. // NB: ImGui already provide OS clipboard support for Windows so this isn't needed if you are using Windows only.
  82. static const char* ImImpl_GetClipboardTextFn()
  83. {
  84. return glfwGetClipboardString(window);
  85. }
  86. static void ImImpl_SetClipboardTextFn(const char* text)
  87. {
  88. glfwSetClipboardString(window, text);
  89. }
  90. // GLFW callbacks to get events
  91. static void glfw_error_callback(int error, const char* description)
  92. {
  93. fputs(description, stderr);
  94. }
  95. static void glfw_mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
  96. {
  97. if (action == GLFW_PRESS && button >= 0 && button < 2)
  98. mousePressed[button] = true;
  99. }
  100. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  101. {
  102. ImGuiIO& io = ImGui::GetIO();
  103. io.MouseWheel = (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  104. }
  105. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  106. {
  107. ImGuiIO& io = ImGui::GetIO();
  108. if (action == GLFW_PRESS)
  109. io.KeysDown[key] = true;
  110. if (action == GLFW_RELEASE)
  111. io.KeysDown[key] = false;
  112. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  113. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  114. }
  115. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  116. {
  117. if (c > 0 && c < 0x10000)
  118. ImGui::GetIO().AddInputCharacter((unsigned short)c);
  119. }
  120. // OpenGL code based on http://open.gl tutorials
  121. void InitGL()
  122. {
  123. glfwSetErrorCallback(glfw_error_callback);
  124. if (!glfwInit())
  125. exit(1);
  126. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  127. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
  128. glfwMakeContextCurrent(window);
  129. glfwSetKeyCallback(window, glfw_key_callback);
  130. glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
  131. glfwSetScrollCallback(window, glfw_scroll_callback);
  132. glfwSetCharCallback(window, glfw_char_callback);
  133. glewInit();
  134. }
  135. void InitImGui()
  136. {
  137. int w, h;
  138. int fb_w, fb_h;
  139. glfwGetWindowSize(window, &w, &h);
  140. glfwGetFramebufferSize(window, &fb_w, &fb_h);
  141. mousePosScale.x = (float)fb_w / w; // Some screens e.g. Retina display have framebuffer size != from window size, and mouse inputs are given in window/screen coordinates.
  142. mousePosScale.y = (float)fb_h / h;
  143. ImGuiIO& io = ImGui::GetIO();
  144. io.DisplaySize = ImVec2((float)fb_w, (float)fb_h); // Display size, in pixels. For clamping windows positions.
  145. io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our timestep is variable)
  146. io.PixelCenterOffset = 0.0f; // Align OpenGL texels
  147. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  148. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  149. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  150. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  151. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  152. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  153. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  154. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  155. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  156. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  157. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  158. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  159. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  160. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  161. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  162. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  163. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  164. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  165. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  166. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  167. // Load font texture
  168. glGenTextures(1, &fontTex);
  169. glBindTexture(GL_TEXTURE_2D, fontTex);
  170. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  171. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  172. #if 1
  173. // Default font (embedded in code)
  174. const void* png_data;
  175. unsigned int png_size;
  176. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  177. int tex_x, tex_y, tex_comp;
  178. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  179. IM_ASSERT(tex_data != NULL);
  180. #else
  181. // Custom font from filesystem
  182. io.Font = new ImFont();
  183. io.Font->LoadFromFile("../../extra_fonts/mplus-2m-medium_18.fnt");
  184. IM_ASSERT(io.Font->IsLoaded());
  185. int tex_x, tex_y, tex_comp;
  186. void* tex_data = stbi_load("../../extra_fonts/mplus-2m-medium_18.png", &tex_x, &tex_y, &tex_comp, 0);
  187. IM_ASSERT(tex_data != NULL);
  188. // Automatically find white pixel from the texture we just loaded
  189. // (io.Font->TexUvForWhite needs to contains UV coordinates pointing to a white pixel in order to render solid objects)
  190. for (int tex_data_off = 0; tex_data_off < tex_x*tex_y; tex_data_off++)
  191. if (((unsigned int*)tex_data)[tex_data_off] == 0xffffffff)
  192. {
  193. io.Font->TexUvForWhite = ImVec2((float)(tex_data_off % tex_x)/(tex_x), (float)(tex_data_off / tex_x)/(tex_y));
  194. break;
  195. }
  196. #endif
  197. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  198. stbi_image_free(tex_data);
  199. }
  200. void UpdateImGui()
  201. {
  202. ImGuiIO& io = ImGui::GetIO();
  203. // Setup timestep
  204. static double time = 0.0f;
  205. const double current_time = glfwGetTime();
  206. io.DeltaTime = (float)(current_time - time);
  207. time = current_time;
  208. // Setup inputs
  209. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  210. double mouse_x, mouse_y;
  211. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  212. io.MousePos = ImVec2((float)mouse_x * mousePosScale.x, (float)mouse_y * mousePosScale.y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  213. io.MouseDown[0] = mousePressed[0] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
  214. io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  215. // Start the frame
  216. ImGui::NewFrame();
  217. }
  218. // Application code
  219. int main(int argc, char** argv)
  220. {
  221. InitGL();
  222. InitImGui();
  223. while (!glfwWindowShouldClose(window))
  224. {
  225. ImGuiIO& io = ImGui::GetIO();
  226. mousePressed[0] = mousePressed[1] = false;
  227. io.MouseWheel = 0;
  228. glfwPollEvents();
  229. UpdateImGui();
  230. static bool show_test_window = true;
  231. static bool show_another_window = false;
  232. // 1. Show a simple window
  233. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  234. {
  235. static float f;
  236. ImGui::Text("Hello, world!");
  237. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  238. show_test_window ^= ImGui::Button("Test Window");
  239. show_another_window ^= ImGui::Button("Another Window");
  240. // Calculate and show frame rate
  241. static float ms_per_frame[120] = { 0 };
  242. static int ms_per_frame_idx = 0;
  243. static float ms_per_frame_accum = 0.0f;
  244. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  245. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  246. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  247. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  248. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  249. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  250. }
  251. // 2. Show another simple window, this time using an explicit Begin/End pair
  252. if (show_another_window)
  253. {
  254. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  255. ImGui::Text("Hello");
  256. ImGui::End();
  257. }
  258. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  259. if (show_test_window)
  260. {
  261. ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call this, because positions are saved in .ini file. Here we just want to make the demo initial state a bit more friendly!
  262. ImGui::ShowTestWindow(&show_test_window);
  263. }
  264. // Rendering
  265. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  266. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  267. glClear(GL_COLOR_BUFFER_BIT);
  268. ImGui::Render();
  269. glfwSwapBuffers(window);
  270. }
  271. ImGui::Shutdown();
  272. glfwTerminate();
  273. return 0;
  274. }