main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // ImGui - standalone example application for OpenGL 3, using programmable pipeline
  2. #ifdef _MSC_VER
  3. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  4. #endif
  5. #include "../../imgui.h"
  6. #define STB_IMAGE_STATIC
  7. #define STB_IMAGE_IMPLEMENTATION
  8. #include "../shared/stb_image.h" // stb_image.h for PNG loading
  9. // Glfw/Glew
  10. #define GLEW_STATIC
  11. #include <GL/glew.h>
  12. #include <GLFW/glfw3.h>
  13. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  14. static GLFWwindow* window;
  15. static GLuint fontTex;
  16. static bool mousePressed[2] = { false, false };
  17. // Shader variables
  18. static int shader_handle, vert_handle, frag_handle;
  19. static int texture_location, ortho_location;
  20. static int position_location, uv_location, colour_location;
  21. static size_t vbo_max_size = 20000;
  22. static unsigned int vbo_handle, vao_handle;
  23. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  24. // If text or lines are blurry when integrating ImGui in your engine:
  25. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f
  26. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  27. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  28. {
  29. if (cmd_lists_count == 0)
  30. return;
  31. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  32. glEnable(GL_BLEND);
  33. glBlendEquation(GL_FUNC_ADD);
  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. // Setup texture
  39. glActiveTexture(GL_TEXTURE0);
  40. glBindTexture(GL_TEXTURE_2D, fontTex);
  41. // Setup orthographic projection matrix
  42. const float width = ImGui::GetIO().DisplaySize.x;
  43. const float height = ImGui::GetIO().DisplaySize.y;
  44. const float ortho_projection[4][4] =
  45. {
  46. { 2.0f/width, 0.0f, 0.0f, 0.0f },
  47. { 0.0f, 2.0f/-height, 0.0f, 0.0f },
  48. { 0.0f, 0.0f, -1.0f, 0.0f },
  49. { -1.0f, 1.0f, 0.0f, 1.0f },
  50. };
  51. glUseProgram(shader_handle);
  52. glUniform1i(texture_location, 0);
  53. glUniformMatrix4fv(ortho_location, 1, GL_FALSE, &ortho_projection[0][0]);
  54. // Grow our buffer according to what we need
  55. size_t total_vtx_count = 0;
  56. for (int n = 0; n < cmd_lists_count; n++)
  57. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  58. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  59. size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert);
  60. if (neededBufferSize > vbo_max_size)
  61. {
  62. vbo_max_size = neededBufferSize + 5000; // Grow buffer
  63. glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_STREAM_DRAW);
  64. }
  65. // Copy and convert all vertices into a single contiguous buffer
  66. unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  67. if (!buffer_data)
  68. return;
  69. for (int n = 0; n < cmd_lists_count; n++)
  70. {
  71. const ImDrawList* cmd_list = cmd_lists[n];
  72. memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  73. buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  74. }
  75. glUnmapBuffer(GL_ARRAY_BUFFER);
  76. glBindBuffer(GL_ARRAY_BUFFER, 0);
  77. glBindVertexArray(vao_handle);
  78. int cmd_offset = 0;
  79. for (int n = 0; n < cmd_lists_count; n++)
  80. {
  81. const ImDrawList* cmd_list = cmd_lists[n];
  82. int vtx_offset = cmd_offset;
  83. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  84. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  85. {
  86. 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));
  87. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  88. vtx_offset += pcmd->vtx_count;
  89. }
  90. cmd_offset = vtx_offset;
  91. }
  92. // Restore modified state
  93. glBindVertexArray(0);
  94. glUseProgram(0);
  95. glDisable(GL_SCISSOR_TEST);
  96. glBindTexture(GL_TEXTURE_2D, 0);
  97. }
  98. static const char* ImImpl_GetClipboardTextFn()
  99. {
  100. return glfwGetClipboardString(window);
  101. }
  102. static void ImImpl_SetClipboardTextFn(const char* text)
  103. {
  104. glfwSetClipboardString(window, text);
  105. }
  106. // GLFW callbacks to get events
  107. static void glfw_error_callback(int error, const char* description)
  108. {
  109. fputs(description, stderr);
  110. }
  111. static void glfw_mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
  112. {
  113. if (action == GLFW_PRESS && button >= 0 && button < 2)
  114. mousePressed[button] = true;
  115. }
  116. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  117. {
  118. ImGuiIO& io = ImGui::GetIO();
  119. io.MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  120. }
  121. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  122. {
  123. ImGuiIO& io = ImGui::GetIO();
  124. if (action == GLFW_PRESS)
  125. io.KeysDown[key] = true;
  126. if (action == GLFW_RELEASE)
  127. io.KeysDown[key] = false;
  128. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  129. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  130. }
  131. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  132. {
  133. if (c > 0 && c < 0x10000)
  134. ImGui::GetIO().AddInputCharacter((unsigned short)c);
  135. }
  136. // OpenGL code based on http://open.gl tutorials
  137. void InitGL()
  138. {
  139. glfwSetErrorCallback(glfw_error_callback);
  140. if (!glfwInit())
  141. exit(1);
  142. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  143. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  144. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  145. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", NULL, NULL);
  146. glfwMakeContextCurrent(window);
  147. glfwSetKeyCallback(window, glfw_key_callback);
  148. glfwSetMouseButtonCallback(window, glfw_mouse_button_callback);
  149. glfwSetScrollCallback(window, glfw_scroll_callback);
  150. glfwSetCharCallback(window, glfw_char_callback);
  151. glewExperimental = GL_TRUE;
  152. GLenum err = glewInit();
  153. if (GLEW_OK != err)
  154. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  155. const GLchar *vertex_shader =
  156. "#version 330\n"
  157. "uniform mat4 ortho;\n"
  158. "in vec2 Position;\n"
  159. "in vec2 UV;\n"
  160. "in vec4 Colour;\n"
  161. "out vec2 Frag_UV;\n"
  162. "out vec4 Frag_Colour;\n"
  163. "void main()\n"
  164. "{\n"
  165. " Frag_UV = UV;\n"
  166. " Frag_Colour = Colour;\n"
  167. " gl_Position = ortho*vec4(Position.xy,0,1);\n"
  168. "}\n";
  169. const GLchar* fragment_shader =
  170. "#version 330\n"
  171. "uniform sampler2D Texture;\n"
  172. "in vec2 Frag_UV;\n"
  173. "in vec4 Frag_Colour;\n"
  174. "out vec4 FragColor;\n"
  175. "void main()\n"
  176. "{\n"
  177. " FragColor = Frag_Colour * texture( Texture, Frag_UV.st);\n"
  178. "}\n";
  179. shader_handle = glCreateProgram();
  180. vert_handle = glCreateShader(GL_VERTEX_SHADER);
  181. frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
  182. glShaderSource(vert_handle, 1, &vertex_shader, 0);
  183. glShaderSource(frag_handle, 1, &fragment_shader, 0);
  184. glCompileShader(vert_handle);
  185. glCompileShader(frag_handle);
  186. glAttachShader(shader_handle, vert_handle);
  187. glAttachShader(shader_handle, frag_handle);
  188. glLinkProgram(shader_handle);
  189. texture_location = glGetUniformLocation(shader_handle, "Texture");
  190. ortho_location = glGetUniformLocation(shader_handle, "ortho");
  191. position_location = glGetAttribLocation(shader_handle, "Position");
  192. uv_location = glGetAttribLocation(shader_handle, "UV");
  193. colour_location = glGetAttribLocation(shader_handle, "Colour");
  194. glGenBuffers(1, &vbo_handle);
  195. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  196. glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW);
  197. glGenVertexArrays(1, &vao_handle);
  198. glBindVertexArray(vao_handle);
  199. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  200. glEnableVertexAttribArray(position_location);
  201. glEnableVertexAttribArray(uv_location);
  202. glEnableVertexAttribArray(colour_location);
  203. glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  204. glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  205. glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  206. glBindVertexArray(0);
  207. glBindBuffer(GL_ARRAY_BUFFER, 0);
  208. }
  209. void InitImGui()
  210. {
  211. ImGuiIO& io = ImGui::GetIO();
  212. 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)
  213. io.PixelCenterOffset = 0.5f; // Align OpenGL texels
  214. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  215. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  216. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  217. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  218. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  219. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  220. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  221. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  222. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  223. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  224. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  225. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  226. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  227. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  228. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  229. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  230. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  231. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  232. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  233. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  234. // Load font texture
  235. glGenTextures(1, &fontTex);
  236. glBindTexture(GL_TEXTURE_2D, fontTex);
  237. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  238. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  239. const void* png_data;
  240. unsigned int png_size;
  241. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  242. int tex_x, tex_y, tex_comp;
  243. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  244. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  245. stbi_image_free(tex_data);
  246. }
  247. void UpdateImGui()
  248. {
  249. ImGuiIO& io = ImGui::GetIO();
  250. // Setup resolution (every frame to accommodate for window resizing)
  251. int w, h;
  252. int display_w, display_h;
  253. glfwGetWindowSize(window, &w, &h);
  254. glfwGetFramebufferSize(window, &display_w, &display_h);
  255. io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
  256. // Setup time step
  257. static double time = 0.0f;
  258. const double current_time = glfwGetTime();
  259. io.DeltaTime = (float)(current_time - time);
  260. time = current_time;
  261. // Setup inputs
  262. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  263. double mouse_x, mouse_y;
  264. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  265. mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
  266. mouse_y *= (float)display_h / h;
  267. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  268. 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.
  269. io.MouseDown[1] = mousePressed[1] || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  270. // Start the frame
  271. ImGui::NewFrame();
  272. }
  273. // Application code
  274. int main(int argc, char** argv)
  275. {
  276. InitGL();
  277. InitImGui();
  278. while (!glfwWindowShouldClose(window))
  279. {
  280. ImGuiIO& io = ImGui::GetIO();
  281. io.MouseWheel = 0;
  282. mousePressed[0] = mousePressed[1] = false;
  283. glfwPollEvents();
  284. UpdateImGui();
  285. static bool show_test_window = true;
  286. static bool show_another_window = false;
  287. // 1. Show a simple window
  288. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  289. {
  290. static float f;
  291. ImGui::Text("Hello, world!");
  292. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  293. show_test_window ^= ImGui::Button("Test Window");
  294. show_another_window ^= ImGui::Button("Another Window");
  295. // Calculate and show frame rate
  296. static float ms_per_frame[120] = { 0 };
  297. static int ms_per_frame_idx = 0;
  298. static float ms_per_frame_accum = 0.0f;
  299. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  300. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  301. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  302. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  303. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  304. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  305. }
  306. // 2. Show another simple window, this time using an explicit Begin/End pair
  307. if (show_another_window)
  308. {
  309. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  310. ImGui::Text("Hello");
  311. ImGui::End();
  312. }
  313. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  314. if (show_test_window)
  315. {
  316. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver);
  317. ImGui::ShowTestWindow(&show_test_window);
  318. }
  319. // Rendering
  320. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  321. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  322. glClear(GL_COLOR_BUFFER_BIT);
  323. ImGui::Render();
  324. glfwSwapBuffers(window);
  325. }
  326. // Cleanup
  327. if (vao_handle) glDeleteVertexArrays(1, &vao_handle);
  328. if (vbo_handle) glDeleteBuffers(1, &vbo_handle);
  329. glDetachShader(shader_handle, vert_handle);
  330. glDetachShader(shader_handle, frag_handle);
  331. glDeleteShader(vert_handle);
  332. glDeleteShader(frag_handle);
  333. glDeleteProgram(shader_handle);
  334. ImGui::Shutdown();
  335. glfwTerminate();
  336. return 0;
  337. }