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_IMPLEMENTATION
  7. #include "../shared/stb_image.h" // stb_image.h for PNG loading
  8. // Glfw/Glew
  9. #define GLEW_STATIC
  10. #include <GL/glew.h>
  11. #include <GLFW/glfw3.h>
  12. static GLFWwindow* window;
  13. static GLuint fontTex;
  14. static bool mousePressed[2] = { false, false };
  15. static ImVec2 mousePosScale(1.0f, 1.0f);
  16. // Shader variables
  17. static int shader_handle, vert_handle, frag_handle;
  18. static int texture_location, ortho_location;
  19. static int position_location, uv_location, colour_location;
  20. //streaming vbo
  21. //we are going to use the same vertex buffer for all rendering of imgui
  22. //so we need to use a large enough buffer as default.
  23. //the buffer will be resized if needed in the rendering code, but it is not a "free" operation.
  24. static size_t vbo_max_size = 1000000;
  25. static unsigned int vbo_handle, vao_handle;
  26. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  27. // If text or lines are blurry when integrating ImGui in your engine:
  28. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.0f or 0.5f
  29. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  30. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  31. {
  32. if (cmd_lists_count == 0)
  33. return;
  34. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  35. glEnable(GL_BLEND);
  36. glBlendEquation(GL_FUNC_ADD);
  37. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  38. glDisable(GL_CULL_FACE);
  39. glDisable(GL_DEPTH_TEST);
  40. glEnable(GL_SCISSOR_TEST);
  41. // Setup texture
  42. glActiveTexture(GL_TEXTURE0);
  43. glBindTexture(GL_TEXTURE_2D, fontTex);
  44. // Setup orthographic projection matrix
  45. const float width = ImGui::GetIO().DisplaySize.x;
  46. const float height = ImGui::GetIO().DisplaySize.y;
  47. const float ortho_projection[4][4] =
  48. {
  49. { 2.0f/width, 0.0f, 0.0f, 0.0f },
  50. { 0.0f, 2.0f/-height, 0.0f, 0.0f },
  51. { 0.0f, 0.0f, -1.0f, 0.0f },
  52. { -1.0f, 1.0f, 0.0f, 1.0f },
  53. };
  54. glUseProgram(shader_handle);
  55. glUniform1i(texture_location, 0);
  56. glUniformMatrix4fv(ortho_location, 1, GL_FALSE, &ortho_projection[0][0]);
  57. // we will update the buffer in full, so we need to compute the total size of the buffer.
  58. size_t total_vtx_count = 0;
  59. for (int n = 0; n < cmd_lists_count; n++)
  60. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  61. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  62. size_t neededBufferSize = total_vtx_count * sizeof(ImDrawVert);
  63. if (neededBufferSize > vbo_max_size)
  64. {
  65. vbo_max_size = neededBufferSize;
  66. glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW);
  67. }
  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. 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));
  89. glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
  90. vtx_offset += pcmd->vtx_count;
  91. }
  92. cmd_offset = vtx_offset;
  93. }
  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_RESIZABLE, GL_FALSE);
  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 OpenGL example", NULL, NULL);
  148. glfwMakeContextCurrent(window);
  149. glfwSetKeyCallback(window, glfw_key_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. {
  156. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  157. }
  158. const GLchar *vertex_shader = \
  159. "#version 330\n"
  160. "uniform mat4 ortho;\n"
  161. "in vec2 Position;\n"
  162. "in vec2 UV;\n"
  163. "in vec4 Colour;\n"
  164. "out vec2 Frag_UV;\n"
  165. "out vec4 Frag_Colour;\n"
  166. "void main()\n"
  167. "{\n"
  168. " Frag_UV = UV;\n"
  169. " Frag_Colour = Colour;\n"
  170. " gl_Position = ortho*vec4(Position.xy,0,1);\n"
  171. "}\n";
  172. const GLchar* fragment_shader = \
  173. "#version 330\n"
  174. "uniform sampler2D Texture;\n"
  175. "in vec2 Frag_UV;\n"
  176. "in vec4 Frag_Colour;\n"
  177. "out vec4 FragColor;\n"
  178. "void main()\n"
  179. "{\n"
  180. " FragColor = Frag_Colour * texture( Texture, Frag_UV.st);\n"
  181. "}\n";
  182. shader_handle = glCreateProgram();
  183. vert_handle = glCreateShader(GL_VERTEX_SHADER);
  184. frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
  185. glShaderSource(vert_handle, 1, &vertex_shader, 0);
  186. glShaderSource(frag_handle, 1, &fragment_shader, 0);
  187. glCompileShader(vert_handle);
  188. glCompileShader(frag_handle);
  189. glAttachShader(shader_handle, vert_handle);
  190. glAttachShader(shader_handle, frag_handle);
  191. glLinkProgram(shader_handle);
  192. texture_location = glGetUniformLocation(shader_handle, "Texture");
  193. ortho_location = glGetUniformLocation(shader_handle, "ortho");
  194. position_location = glGetAttribLocation(shader_handle, "Position");
  195. uv_location = glGetAttribLocation(shader_handle, "UV");
  196. colour_location = glGetAttribLocation(shader_handle, "Colour");
  197. glGenBuffers(1, &vbo_handle);
  198. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  199. glBufferData(GL_ARRAY_BUFFER, vbo_max_size, NULL, GL_DYNAMIC_DRAW);
  200. glGenVertexArrays(1, &vao_handle);
  201. glBindVertexArray(vao_handle);
  202. glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
  203. glEnableVertexAttribArray(position_location);
  204. glEnableVertexAttribArray(uv_location);
  205. glEnableVertexAttribArray(colour_location);
  206. glVertexAttribPointer(position_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, pos));
  207. glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, uv));
  208. glVertexAttribPointer(colour_location, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) offsetof(ImDrawVert, col));
  209. glBindVertexArray(0);
  210. glBindBuffer(GL_ARRAY_BUFFER, 0);
  211. }
  212. void InitImGui()
  213. {
  214. int w, h;
  215. glfwGetWindowSize(window, &w, &h);
  216. ImGuiIO& io = ImGui::GetIO();
  217. io.DisplaySize = ImVec2((float)w, (float)h); // Display size, in pixels. For clamping windows positions.
  218. 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)
  219. io.PixelCenterOffset = 0.5f; // Align OpenGL texels
  220. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  221. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  222. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  223. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  224. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  225. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  226. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  227. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  228. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  229. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  230. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  231. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  232. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  233. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  234. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  235. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  236. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  237. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  238. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  239. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  240. // Load font texture
  241. glGenTextures(1, &fontTex);
  242. glBindTexture(GL_TEXTURE_2D, fontTex);
  243. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  244. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  245. const void* png_data;
  246. unsigned int png_size;
  247. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  248. int tex_x, tex_y, tex_comp;
  249. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  250. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  251. stbi_image_free(tex_data);
  252. }
  253. void UpdateImGui()
  254. {
  255. ImGuiIO& io = ImGui::GetIO();
  256. // Setup timestep
  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. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  266. io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
  267. io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  268. // Start the frame
  269. ImGui::NewFrame();
  270. }
  271. // Application code
  272. int main(int argc, char** argv)
  273. {
  274. InitGL();
  275. InitImGui();
  276. while (!glfwWindowShouldClose(window))
  277. {
  278. ImGuiIO& io = ImGui::GetIO();
  279. io.MouseWheel = 0;
  280. glfwPollEvents();
  281. UpdateImGui();
  282. // Create a simple window
  283. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  284. static bool show_test_window = true;
  285. static bool show_another_window = false;
  286. static float f;
  287. ImGui::Text("Hello, world!");
  288. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  289. show_test_window ^= ImGui::Button("Test Window");
  290. show_another_window ^= ImGui::Button("Another Window");
  291. // Calculate and show framerate
  292. static float ms_per_frame[120] = { 0 };
  293. static int ms_per_frame_idx = 0;
  294. static float ms_per_frame_accum = 0.0f;
  295. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  296. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  297. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  298. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  299. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  300. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  301. // Show the ImGui test window
  302. // Most of user example code is in ImGui::ShowTestWindow()
  303. if (show_test_window)
  304. {
  305. ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  306. ImGui::ShowTestWindow(&show_test_window);
  307. }
  308. // Show another simple window
  309. if (show_another_window)
  310. {
  311. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  312. ImGui::Text("Hello");
  313. ImGui::End();
  314. }
  315. // Rendering
  316. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  317. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  318. glClear(GL_COLOR_BUFFER_BIT);
  319. ImGui::Render();
  320. glfwSwapBuffers(window);
  321. }
  322. if (vao_handle) glDeleteVertexArrays(1, &vao_handle);
  323. if (vbo_handle) glDeleteBuffers(1, &vbo_handle);
  324. glDetachShader(shader_handle, vert_handle);
  325. glDetachShader(shader_handle, frag_handle);
  326. glDeleteShader(vert_handle);
  327. glDeleteShader(frag_handle);
  328. glDeleteProgram(shader_handle);
  329. ImGui::Shutdown();
  330. glfwTerminate();
  331. return 0;
  332. }