main.cpp 15 KB

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