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